]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/nodes/_common.ts
Lexical: Added media resize support via drag handles
[bookstack] / resources / js / wysiwyg / nodes / _common.ts
1 import {LexicalNode, Spread} from "lexical";
2 import type {SerializedElementNode} from "lexical/nodes/LexicalElementNode";
3
4 export type CommonBlockAlignment = 'left' | 'right' | 'center' | 'justify' | '';
5 const validAlignments: CommonBlockAlignment[] = ['left', 'right', 'center', 'justify'];
6
7 export type SerializedCommonBlockNode = Spread<{
8     id: string;
9     alignment: CommonBlockAlignment;
10 }, SerializedElementNode>
11
12 export interface NodeHasAlignment {
13     readonly __alignment: CommonBlockAlignment;
14     setAlignment(alignment: CommonBlockAlignment): void;
15     getAlignment(): CommonBlockAlignment;
16 }
17
18 export interface NodeHasId {
19     readonly __id: string;
20     setId(id: string): void;
21     getId(): string;
22 }
23
24 interface CommonBlockInterface extends NodeHasId, NodeHasAlignment {}
25
26 export function extractAlignmentFromElement(element: HTMLElement): CommonBlockAlignment {
27     const textAlignStyle: string = element.style.textAlign || '';
28     if (validAlignments.includes(textAlignStyle as CommonBlockAlignment)) {
29         return textAlignStyle as CommonBlockAlignment;
30     }
31
32     if (element.classList.contains('align-left')) {
33         return 'left';
34     } else if (element.classList.contains('align-right')) {
35         return 'right'
36     } else if (element.classList.contains('align-center')) {
37         return 'center'
38     } else if (element.classList.contains('align-justify')) {
39         return 'justify'
40     }
41
42     return '';
43 }
44
45 export function setCommonBlockPropsFromElement(element: HTMLElement, node: CommonBlockInterface): void {
46     if (element.id) {
47         node.setId(element.id);
48     }
49
50     node.setAlignment(extractAlignmentFromElement(element));
51 }
52
53 export function commonPropertiesDifferent(nodeA: CommonBlockInterface, nodeB: CommonBlockInterface): boolean {
54     return nodeA.__id !== nodeB.__id ||
55         nodeA.__alignment !== nodeB.__alignment;
56 }
57
58 export function updateElementWithCommonBlockProps(element: HTMLElement, node: CommonBlockInterface): void {
59     if (node.__id) {
60         element.setAttribute('id', node.__id);
61     }
62
63     if (node.__alignment) {
64         element.classList.add('align-' + node.__alignment);
65     }
66 }
67
68 export interface NodeHasSize {
69     setHeight(height: number): void;
70     setWidth(width: number): void;
71     getHeight(): number;
72     getWidth(): number;
73 }