]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/lexical/rich-text/LexicalMediaNode.ts
Lexical: Added a media toolbar, improved toolbars and media selection
[bookstack] / resources / js / wysiwyg / lexical / rich-text / LexicalMediaNode.ts
1 import {
2     DOMConversion,
3     DOMConversionMap, DOMConversionOutput, DOMExportOutput,
4     ElementNode,
5     LexicalEditor,
6     LexicalNode,
7     Spread
8 } from 'lexical';
9 import type {EditorConfig} from "lexical/LexicalEditor";
10
11 import {el, setOrRemoveAttribute, sizeToPixels, styleMapToStyleString, styleStringToStyleMap} from "../../utils/dom";
12 import {
13     CommonBlockAlignment, deserializeCommonBlockNode,
14     setCommonBlockPropsFromElement,
15     updateElementWithCommonBlockProps
16 } from "lexical/nodes/common";
17 import {$selectSingleNode} from "../../utils/selection";
18 import {SerializedCommonBlockNode} from "lexical/nodes/CommonBlockNode";
19
20 export type MediaNodeTag = 'iframe' | 'embed' | 'object' | 'video' | 'audio';
21 export type MediaNodeSource = {
22     src: string;
23     type: string;
24 };
25
26 export type SerializedMediaNode = Spread<{
27     tag: MediaNodeTag;
28     attributes: Record<string, string>;
29     sources: MediaNodeSource[];
30 }, SerializedCommonBlockNode>
31
32 const attributeAllowList = [
33     'width', 'height', 'style', 'title', 'name',
34     'src', 'allow', 'allowfullscreen', 'loading', 'sandbox',
35     'type', 'data', 'controls', 'autoplay', 'controlslist', 'loop',
36     'muted', 'playsinline', 'poster', 'preload'
37 ];
38
39 function filterAttributes(attributes: Record<string, string>): Record<string, string> {
40     const filtered: Record<string, string> = {};
41     for (const key of Object.keys(attributes)) {
42         if (attributeAllowList.includes(key)) {
43             filtered[key] = attributes[key];
44         }
45     }
46     return filtered;
47 }
48
49 function removeStyleFromAttributes(attributes: Record<string, string>, styleName: string): Record<string, string> {
50     const attrCopy = Object.assign({}, attributes);
51     if (!attributes.style) {
52         return attrCopy;
53     }
54
55     const map = styleStringToStyleMap(attributes.style);
56     map.delete(styleName);
57
58     attrCopy.style = styleMapToStyleString(map);
59     return attrCopy;
60 }
61
62 function domElementToNode(tag: MediaNodeTag, element: HTMLElement): MediaNode {
63     const node = $createMediaNode(tag);
64
65     const attributes: Record<string, string> = {};
66     for (const attribute of element.attributes) {
67         attributes[attribute.name] = attribute.value;
68     }
69     node.setAttributes(attributes);
70
71     const sources: MediaNodeSource[] = [];
72     if (tag === 'video' || tag === 'audio') {
73         for (const child of element.children) {
74             if (child.tagName === 'SOURCE') {
75                 const src = child.getAttribute('src');
76                 const type = child.getAttribute('type');
77                 if (src && type) {
78                     sources.push({ src, type });
79                 }
80             }
81         }
82         node.setSources(sources);
83     }
84
85     setCommonBlockPropsFromElement(element, node);
86
87     return node;
88 }
89
90 export class MediaNode extends ElementNode {
91     __id: string = '';
92     __alignment: CommonBlockAlignment = '';
93     __tag: MediaNodeTag;
94     __attributes: Record<string, string> = {};
95     __sources: MediaNodeSource[] = [];
96     __inset: number = 0;
97
98     static getType() {
99         return 'media';
100     }
101
102     static clone(node: MediaNode) {
103         const newNode = new MediaNode(node.__tag, node.__key);
104         newNode.__attributes = Object.assign({}, node.__attributes);
105         newNode.__sources = node.__sources.map(s => Object.assign({}, s));
106         newNode.__id = node.__id;
107         newNode.__alignment = node.__alignment;
108         newNode.__inset = node.__inset;
109         return newNode;
110     }
111
112     constructor(tag: MediaNodeTag, key?: string) {
113         super(key);
114         this.__tag = tag;
115     }
116
117     setTag(tag: MediaNodeTag) {
118         const self = this.getWritable();
119         self.__tag = tag;
120     }
121
122     getTag(): MediaNodeTag {
123         const self = this.getLatest();
124         return self.__tag;
125     }
126
127     setAttributes(attributes: Record<string, string>) {
128         const self = this.getWritable();
129         self.__attributes = filterAttributes(attributes);
130     }
131
132     getAttributes(): Record<string, string> {
133         const self = this.getLatest();
134         return Object.assign({}, self.__attributes);
135     }
136
137     setSources(sources: MediaNodeSource[]) {
138         const self = this.getWritable();
139         self.__sources = sources;
140     }
141
142     getSources(): MediaNodeSource[] {
143         const self = this.getLatest();
144         return self.__sources;
145     }
146
147     setSrc(src: string): void {
148         const attrs = this.getAttributes();
149         if (this.__tag ==='object') {
150             attrs.data = src;
151         } else {
152             attrs.src = src;
153         }
154         this.setAttributes(attrs);
155     }
156
157     setWidthAndHeight(width: string, height: string): void {
158         let attrs: Record<string, string> = Object.assign(
159             this.getAttributes(),
160             {width, height},
161         );
162
163         attrs = removeStyleFromAttributes(attrs, 'width');
164         attrs = removeStyleFromAttributes(attrs, 'height');
165         this.setAttributes(attrs);
166     }
167
168     setId(id: string) {
169         const self = this.getWritable();
170         self.__id = id;
171     }
172
173     getId(): string {
174         const self = this.getLatest();
175         return self.__id;
176     }
177
178     setAlignment(alignment: CommonBlockAlignment) {
179         const self = this.getWritable();
180         self.__alignment = alignment;
181     }
182
183     getAlignment(): CommonBlockAlignment {
184         const self = this.getLatest();
185         return self.__alignment;
186     }
187
188     setInset(size: number) {
189         const self = this.getWritable();
190         self.__inset = size;
191     }
192
193     getInset(): number {
194         const self = this.getLatest();
195         return self.__inset;
196     }
197
198     setHeight(height: number): void {
199         if (!height) {
200             return;
201         }
202
203         const attrs = Object.assign(this.getAttributes(), {height});
204         this.setAttributes(removeStyleFromAttributes(attrs, 'height'));
205     }
206
207     getHeight(): number {
208         const self = this.getLatest();
209         return sizeToPixels(self.__attributes.height || '0');
210     }
211
212     setWidth(width: number): void {
213         const existingAttrs = this.getAttributes();
214         const attrs: Record<string, string> = Object.assign(existingAttrs, {width});
215         this.setAttributes(removeStyleFromAttributes(attrs, 'width'));
216     }
217
218     getWidth(): number {
219         const self = this.getLatest();
220         return sizeToPixels(self.__attributes.width || '0');
221     }
222
223     isInline(): boolean {
224         return true;
225     }
226
227     isParentRequired(): boolean {
228         return true;
229     }
230
231     createInnerDOM() {
232         const sources = (this.__tag === 'video' || this.__tag === 'audio') ? this.__sources : [];
233         const sourceEls = sources.map(source => el('source', source));
234         const element = el(this.__tag, this.__attributes, sourceEls);
235         updateElementWithCommonBlockProps(element, this);
236         return element;
237     }
238
239     createDOM(_config: EditorConfig, _editor: LexicalEditor) {
240         const media = this.createInnerDOM();
241         return el('span', {
242             class: media.className + ' editor-media-wrap',
243         }, [media]);
244     }
245
246     updateDOM(prevNode: MediaNode, dom: HTMLElement): boolean {
247         if (prevNode.__tag !== this.__tag) {
248             return true;
249         }
250
251         if (JSON.stringify(prevNode.__sources) !== JSON.stringify(this.__sources)) {
252             return true;
253         }
254
255         if (JSON.stringify(prevNode.__attributes) !== JSON.stringify(this.__attributes)) {
256             return true;
257         }
258
259         const mediaEl = dom.firstElementChild as HTMLElement;
260
261         if (prevNode.__id !== this.__id) {
262             setOrRemoveAttribute(mediaEl, 'id', this.__id);
263         }
264
265         if (prevNode.__alignment !== this.__alignment) {
266             if (prevNode.__alignment) {
267                 dom.classList.remove(`align-${prevNode.__alignment}`);
268                 mediaEl.classList.remove(`align-${prevNode.__alignment}`);
269             }
270             if (this.__alignment) {
271                 dom.classList.add(`align-${this.__alignment}`);
272                 mediaEl.classList.add(`align-${this.__alignment}`);
273             }
274         }
275
276         if (prevNode.__inset !== this.__inset) {
277             dom.style.paddingLeft = `${this.__inset}px`;
278         }
279
280         return false;
281     }
282
283     static importDOM(): DOMConversionMap|null {
284
285         const buildConverter = (tag: MediaNodeTag) => {
286             return (node: HTMLElement): DOMConversion|null => {
287                 return {
288                     conversion: (element: HTMLElement): DOMConversionOutput|null => {
289                         return {
290                             node: domElementToNode(tag, element),
291                         };
292                     },
293                     priority: 3,
294                 };
295             };
296         };
297
298         return {
299             iframe: buildConverter('iframe'),
300             embed: buildConverter('embed'),
301             object: buildConverter('object'),
302             video: buildConverter('video'),
303             audio: buildConverter('audio'),
304         };
305     }
306
307     exportDOM(editor: LexicalEditor): DOMExportOutput {
308         const element = this.createInnerDOM();
309         return { element };
310     }
311
312     exportJSON(): SerializedMediaNode {
313         return {
314             ...super.exportJSON(),
315             type: 'media',
316             version: 1,
317             id: this.__id,
318             alignment: this.__alignment,
319             inset: this.__inset,
320             tag: this.__tag,
321             attributes: this.__attributes,
322             sources: this.__sources,
323         };
324     }
325
326     static importJSON(serializedNode: SerializedMediaNode): MediaNode {
327         const node = $createMediaNode(serializedNode.tag);
328         deserializeCommonBlockNode(serializedNode, node);
329         return node;
330     }
331
332 }
333
334 export function $createMediaNode(tag: MediaNodeTag) {
335     return new MediaNode(tag);
336 }
337
338 export function $createMediaNodeFromHtml(html: string): MediaNode | null {
339     const parser = new DOMParser();
340     const doc = parser.parseFromString(`<body>${html}</body>`, 'text/html');
341
342     const el = doc.body.children[0];
343     if (!(el instanceof HTMLElement)) {
344         return null;
345     }
346
347     const tag = el.tagName.toLowerCase();
348     const validTypes = ['embed', 'iframe', 'video', 'audio', 'object'];
349     if (!validTypes.includes(tag)) {
350         return null;
351     }
352
353     return domElementToNode(tag as MediaNodeTag, el);
354 }
355
356 interface UrlPattern {
357     readonly regex: RegExp;
358     readonly w: number;
359     readonly h: number;
360     readonly url: string;
361 }
362
363 /**
364  * These patterns originate from the tinymce/tinymce project.
365  * https://github.com/tinymce/tinymce/blob/release/6.6/modules/tinymce/src/plugins/media/main/ts/core/UrlPatterns.ts
366  * License: MIT Copyright (c) 2022 Ephox Corporation DBA Tiny Technologies, Inc.
367  * License Link: https://github.com/tinymce/tinymce/blob/584a150679669859a528828e5d2910a083b1d911/LICENSE.TXT
368  */
369 const urlPatterns: UrlPattern[] = [
370     {
371         regex: /.*?youtu\.be\/([\w\-_\?&=.]+)/i,
372         w: 560, h: 314,
373         url: 'https://www.youtube.com/embed/$1',
374     },
375     {
376         regex: /.*youtube\.com(.+)v=([^&]+)(&([a-z0-9&=\-_]+))?.*/i,
377         w: 560, h: 314,
378         url: 'https://www.youtube.com/embed/$2?$4',
379     },
380     {
381         regex: /.*youtube.com\/embed\/([a-z0-9\?&=\-_]+).*/i,
382         w: 560, h: 314,
383         url: 'https://www.youtube.com/embed/$1',
384     },
385 ];
386
387 const videoExtensions = ['mp4', 'mpeg', 'm4v', 'm4p', 'mov'];
388 const audioExtensions = ['3gp', 'aac', 'flac', 'mp3', 'm4a', 'ogg', 'wav', 'webm'];
389 const iframeExtensions = ['html', 'htm', 'php', 'asp', 'aspx', ''];
390
391 export function $createMediaNodeFromSrc(src: string): MediaNode {
392
393     for (const pattern of urlPatterns) {
394         const match = src.match(pattern.regex);
395         if (match) {
396             const newSrc = src.replace(pattern.regex, pattern.url);
397             const node = new MediaNode('iframe');
398             node.setSrc(newSrc);
399             node.setHeight(pattern.h);
400             node.setWidth(pattern.w);
401             return node;
402         }
403     }
404
405     let nodeTag: MediaNodeTag = 'iframe';
406     const srcEnd = src.split('?')[0].split('/').pop() || '';
407     const srcEndSplit = srcEnd.split('.');
408     const extension = (srcEndSplit.length > 1 ? srcEndSplit[srcEndSplit.length - 1] : '').toLowerCase();
409     if (videoExtensions.includes(extension)) {
410         nodeTag = 'video';
411     } else if (audioExtensions.includes(extension)) {
412         nodeTag = 'audio';
413     } else if (extension && !iframeExtensions.includes(extension)) {
414         nodeTag = 'embed';
415     }
416
417     const node = new MediaNode(nodeTag);
418     node.setSrc(src);
419     return node;
420 }
421
422 export function $isMediaNode(node: LexicalNode | null | undefined): node is MediaNode {
423     return node instanceof MediaNode;
424 }
425
426 export function $isMediaNodeOfTag(node: LexicalNode | null | undefined, tag: MediaNodeTag): boolean {
427     return node instanceof MediaNode && (node as MediaNode).getTag() === tag;
428 }