]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/nodes/custom-table.ts
Lexical: Split helpers to utils, refactored files
[bookstack] / resources / js / wysiwyg / nodes / custom-table.ts
1 import {SerializedTableNode, TableNode, TableRowNode} from "@lexical/table";
2 import {DOMConversion, DOMConversionMap, DOMConversionOutput, LexicalEditor, LexicalNode, Spread} from "lexical";
3 import {EditorConfig} from "lexical/LexicalEditor";
4
5 import {el} from "../utils/dom";
6
7 export type SerializedCustomTableNode = Spread<{
8     id: string;
9     colWidths: string[];
10 }, SerializedTableNode>
11
12 export class CustomTableNode extends TableNode {
13     __id: string = '';
14     __colWidths: string[] = [];
15
16     static getType() {
17         return 'custom-table';
18     }
19
20     setId(id: string) {
21         const self = this.getWritable();
22         self.__id = id;
23     }
24
25     getId(): string {
26         const self = this.getLatest();
27         return self.__id;
28     }
29
30     setColWidths(widths: string[]) {
31         const self = this.getWritable();
32         self.__colWidths = widths;
33     }
34
35     getColWidths(): string[] {
36         const self = this.getLatest();
37         return self.__colWidths;
38     }
39
40     static clone(node: CustomTableNode) {
41         const newNode = new CustomTableNode(node.__key);
42         newNode.__id = node.__id;
43         newNode.__colWidths = node.__colWidths;
44         return newNode;
45     }
46
47     createDOM(config: EditorConfig): HTMLElement {
48         const dom = super.createDOM(config);
49         const id = this.getId();
50         if (id) {
51             dom.setAttribute('id', id);
52         }
53
54         const colWidths = this.getColWidths();
55         if (colWidths.length > 0) {
56             const colgroup = el('colgroup');
57             for (const width of colWidths) {
58                 const col = el('col');
59                 if (width) {
60                     col.style.width = width;
61                 }
62                 colgroup.append(col);
63             }
64             dom.append(colgroup);
65         }
66
67         return dom;
68     }
69
70     updateDOM(): boolean {
71         return true;
72     }
73
74     exportJSON(): SerializedCustomTableNode {
75         return {
76             ...super.exportJSON(),
77             type: 'custom-table',
78             version: 1,
79             id: this.__id,
80             colWidths: this.__colWidths,
81         };
82     }
83
84     static importJSON(serializedNode: SerializedCustomTableNode): CustomTableNode {
85         const node = $createCustomTableNode();
86         node.setId(serializedNode.id);
87         node.setColWidths(serializedNode.colWidths);
88         return node;
89     }
90
91     static importDOM(): DOMConversionMap|null {
92         return {
93             table(node: HTMLElement): DOMConversion|null {
94                 return {
95                     conversion: (element: HTMLElement): DOMConversionOutput|null => {
96                         const node = $createCustomTableNode();
97
98                         if (element.id) {
99                             node.setId(element.id);
100                         }
101
102                         const colWidths = getTableColumnWidths(element as HTMLTableElement);
103                         node.setColWidths(colWidths);
104
105                         return {node};
106                     },
107                     priority: 1,
108                 };
109             },
110         };
111     }
112 }
113
114 function getTableColumnWidths(table: HTMLTableElement): string[] {
115     const maxColRow = getMaxColRowFromTable(table);
116
117     const colGroup = table.querySelector('colgroup');
118     let widths: string[] = [];
119     if (colGroup && (colGroup.childElementCount === maxColRow?.childElementCount || !maxColRow)) {
120         widths = extractWidthsFromRow(colGroup);
121     }
122     if (widths.filter(Boolean).length === 0 && maxColRow) {
123         widths = extractWidthsFromRow(maxColRow);
124     }
125
126     return widths;
127 }
128
129 function getMaxColRowFromTable(table: HTMLTableElement): HTMLTableRowElement|null {
130     const rows = table.querySelectorAll('tr');
131     let maxColCount: number = 0;
132     let maxColRow: HTMLTableRowElement|null = null;
133
134     for (const row of rows) {
135         if (row.childElementCount > maxColCount) {
136             maxColRow = row;
137             maxColCount = row.childElementCount;
138         }
139     }
140
141     return maxColRow;
142 }
143
144 function extractWidthsFromRow(row: HTMLTableRowElement|HTMLTableColElement) {
145     return [...row.children].map(child => extractWidthFromElement(child as HTMLElement))
146 }
147
148 function extractWidthFromElement(element: HTMLElement): string {
149     let width = element.style.width || element.getAttribute('width');
150     if (width && !Number.isNaN(Number(width))) {
151         width = width + 'px';
152     }
153
154     return width || '';
155 }
156
157 export function $createCustomTableNode(): CustomTableNode {
158     return new CustomTableNode();
159 }
160
161 export function $isCustomTableNode(node: LexicalNode | null | undefined): node is CustomTableNode {
162     return node instanceof CustomTableNode;
163 }
164
165 export function $setTableColumnWidth(node: CustomTableNode, columnIndex: number, width: number): void {
166     const rows = node.getChildren() as TableRowNode[];
167     let maxCols = 0;
168     for (const row of rows) {
169         const cellCount = row.getChildren().length;
170         if (cellCount > maxCols) {
171             maxCols = cellCount;
172         }
173     }
174
175     let colWidths = node.getColWidths();
176     if (colWidths.length === 0 || colWidths.length < maxCols) {
177         colWidths = Array(maxCols).fill('');
178     }
179
180     if (columnIndex + 1 > colWidths.length) {
181         console.error(`Attempted to set table column width for column [${columnIndex}] but only ${colWidths.length} columns found`);
182     }
183
184     colWidths[columnIndex] = width + 'px';
185     node.setColWidths(colWidths);
186 }
187
188 export function $getTableColumnWidth(editor: LexicalEditor, node: CustomTableNode, columnIndex: number): number {
189     const colWidths = node.getColWidths();
190     if (colWidths.length > columnIndex && colWidths[columnIndex].endsWith('px')) {
191         return Number(colWidths[columnIndex].replace('px', ''));
192     }
193
194     // Otherwise, get from table element
195     const table = editor.getElementByKey(node.__key) as HTMLTableElement|null;
196     if (table) {
197         const maxColRow = getMaxColRowFromTable(table);
198         if (maxColRow && maxColRow.children.length > columnIndex) {
199             const cell = maxColRow.children[columnIndex];
200             return cell.clientWidth;
201         }
202     }
203
204     return 0;
205 }