]> BookStack Code Mirror - bookstack/blobdiff - resources/js/wysiwyg/nodes/media.ts
ExportFormatter: Add book description and check for empty book and chapter descriptio...
[bookstack] / resources / js / wysiwyg / nodes / media.ts
index 73208cb2e433dc00a45c663db2b7373e92791807..64fe8f77b4d2fed2dc664bf22366d8c594844074 100644 (file)
@@ -1,14 +1,21 @@
 import {
     DOMConversion,
-    DOMConversionMap, DOMConversionOutput,
+    DOMConversionMap, DOMConversionOutput, DOMExportOutput,
     ElementNode,
     LexicalEditor,
     LexicalNode,
-    SerializedElementNode, Spread
+    Spread
 } from 'lexical';
 import type {EditorConfig} from "lexical/LexicalEditor";
 
-import {el} from "../utils/dom";
+import {el, setOrRemoveAttribute, sizeToPixels} from "../utils/dom";
+import {
+    CommonBlockAlignment, deserializeCommonBlockNode,
+    SerializedCommonBlockNode,
+    setCommonBlockPropsFromElement,
+    updateElementWithCommonBlockProps
+} from "./_common";
+import {$selectSingleNode} from "../utils/selection";
 
 export type MediaNodeTag = 'iframe' | 'embed' | 'object' | 'video' | 'audio';
 export type MediaNodeSource = {
@@ -20,10 +27,10 @@ export type SerializedMediaNode = Spread<{
     tag: MediaNodeTag;
     attributes: Record<string, string>;
     sources: MediaNodeSource[];
-}, SerializedElementNode>
+}, SerializedCommonBlockNode>
 
 const attributeAllowList = [
-    'id', 'width', 'height', 'style', 'title', 'name',
+    'width', 'height', 'style', 'title', 'name',
     'src', 'allow', 'allowfullscreen', 'loading', 'sandbox',
     'type', 'data', 'controls', 'autoplay', 'controlslist', 'loop',
     'muted', 'playsinline', 'poster', 'preload'
@@ -39,7 +46,7 @@ function filterAttributes(attributes: Record<string, string>): Record<string, st
     return filtered;
 }
 
-function domElementToNode(tag: MediaNodeTag, element: Element): MediaNode {
+function domElementToNode(tag: MediaNodeTag, element: HTMLElement): MediaNode {
     const node = $createMediaNode(tag);
 
     const attributes: Record<string, string> = {};
@@ -62,13 +69,18 @@ function domElementToNode(tag: MediaNodeTag, element: Element): MediaNode {
         node.setSources(sources);
     }
 
+    setCommonBlockPropsFromElement(element, node);
+
     return node;
 }
 
 export class MediaNode extends ElementNode {
+    __id: string = '';
+    __alignment: CommonBlockAlignment = '';
     __tag: MediaNodeTag;
     __attributes: Record<string, string> = {};
     __sources: MediaNodeSource[] = [];
+    __inset: number = 0;
 
     static getType() {
         return 'media';
@@ -78,6 +90,9 @@ export class MediaNode extends ElementNode {
         const newNode = new MediaNode(node.__tag, node.__key);
         newNode.__attributes = Object.assign({}, node.__attributes);
         newNode.__sources = node.__sources.map(s => Object.assign({}, s));
+        newNode.__id = node.__id;
+        newNode.__alignment = node.__alignment;
+        newNode.__inset = node.__inset;
         return newNode;
     }
 
@@ -135,15 +150,124 @@ export class MediaNode extends ElementNode {
         this.setAttributes(attrs);
     }
 
-    createDOM(_config: EditorConfig, _editor: LexicalEditor) {
+    setId(id: string) {
+        const self = this.getWritable();
+        self.__id = id;
+    }
+
+    getId(): string {
+        const self = this.getLatest();
+        return self.__id;
+    }
+
+    setAlignment(alignment: CommonBlockAlignment) {
+        const self = this.getWritable();
+        self.__alignment = alignment;
+    }
+
+    getAlignment(): CommonBlockAlignment {
+        const self = this.getLatest();
+        return self.__alignment;
+    }
+
+    setInset(size: number) {
+        const self = this.getWritable();
+        self.__inset = size;
+    }
+
+    getInset(): number {
+        const self = this.getLatest();
+        return self.__inset;
+    }
+
+    setHeight(height: number): void {
+        if (!height) {
+            return;
+        }
+
+        const attrs = Object.assign({}, this.getAttributes(), {height});
+        this.setAttributes(attrs);
+    }
+
+    getHeight(): number {
+        const self = this.getLatest();
+        return sizeToPixels(self.__attributes.height || '0');
+    }
+
+    setWidth(width: number): void {
+        const attrs = Object.assign({}, this.getAttributes(), {width});
+        this.setAttributes(attrs);
+    }
+
+    getWidth(): number {
+        const self = this.getLatest();
+        return sizeToPixels(self.__attributes.width || '0');
+    }
+
+    isInline(): boolean {
+        return true;
+    }
+
+    isParentRequired(): boolean {
+        return true;
+    }
+
+    createInnerDOM() {
         const sources = (this.__tag === 'video' || this.__tag === 'audio') ? this.__sources : [];
         const sourceEls = sources.map(source => el('source', source));
+        const element = el(this.__tag, this.__attributes, sourceEls);
+        updateElementWithCommonBlockProps(element, this);
+        return element;
+    }
+
+    createDOM(_config: EditorConfig, _editor: LexicalEditor) {
+        const media = this.createInnerDOM();
+        const wrap = el('span', {
+            class: media.className + ' editor-media-wrap',
+        }, [media]);
 
-        return el(this.__tag, this.__attributes, sourceEls);
+        wrap.addEventListener('click', e => {
+            _editor.update(() => $selectSingleNode(this));
+        });
+
+        return wrap;
     }
 
-    updateDOM(prevNode: unknown, dom: HTMLElement) {
-        return true;
+    updateDOM(prevNode: MediaNode, dom: HTMLElement): boolean {
+        if (prevNode.__tag !== this.__tag) {
+            return true;
+        }
+
+        if (JSON.stringify(prevNode.__sources) !== JSON.stringify(this.__sources)) {
+            return true;
+        }
+
+        if (JSON.stringify(prevNode.__attributes) !== JSON.stringify(this.__attributes)) {
+            return true;
+        }
+
+        const mediaEl = dom.firstElementChild as HTMLElement;
+
+        if (prevNode.__id !== this.__id) {
+            setOrRemoveAttribute(mediaEl, 'id', this.__id);
+        }
+
+        if (prevNode.__alignment !== this.__alignment) {
+            if (prevNode.__alignment) {
+                dom.classList.remove(`align-${prevNode.__alignment}`);
+                mediaEl.classList.remove(`align-${prevNode.__alignment}`);
+            }
+            if (this.__alignment) {
+                dom.classList.add(`align-${this.__alignment}`);
+                mediaEl.classList.add(`align-${this.__alignment}`);
+            }
+        }
+
+        if (prevNode.__inset !== this.__inset) {
+            dom.style.paddingLeft = `${this.__inset}px`;
+        }
+
+        return false;
     }
 
     static importDOM(): DOMConversionMap|null {
@@ -170,11 +294,19 @@ export class MediaNode extends ElementNode {
         };
     }
 
+    exportDOM(editor: LexicalEditor): DOMExportOutput {
+        const element = this.createInnerDOM();
+        return { element };
+    }
+
     exportJSON(): SerializedMediaNode {
         return {
             ...super.exportJSON(),
             type: 'media',
             version: 1,
+            id: this.__id,
+            alignment: this.__alignment,
+            inset: this.__inset,
             tag: this.__tag,
             attributes: this.__attributes,
             sources: this.__sources,
@@ -182,7 +314,9 @@ export class MediaNode extends ElementNode {
     }
 
     static importJSON(serializedNode: SerializedMediaNode): MediaNode {
-        return $createMediaNode(serializedNode.tag);
+        const node = $createMediaNode(serializedNode.tag);
+        deserializeCommonBlockNode(serializedNode, node);
+        return node;
     }
 
 }
@@ -196,7 +330,7 @@ export function $createMediaNodeFromHtml(html: string): MediaNode | null {
     const doc = parser.parseFromString(`<body>${html}</body>`, 'text/html');
 
     const el = doc.body.children[0];
-    if (!el) {
+    if (!(el instanceof HTMLElement)) {
         return null;
     }
 
@@ -211,12 +345,13 @@ export function $createMediaNodeFromHtml(html: string): MediaNode | null {
 
 const videoExtensions = ['mp4', 'mpeg', 'm4v', 'm4p', 'mov'];
 const audioExtensions = ['3gp', 'aac', 'flac', 'mp3', 'm4a', 'ogg', 'wav', 'webm'];
-const iframeExtensions = ['html', 'htm', 'php', 'asp', 'aspx'];
+const iframeExtensions = ['html', 'htm', 'php', 'asp', 'aspx', ''];
 
 export function $createMediaNodeFromSrc(src: string): MediaNode {
     let nodeTag: MediaNodeTag = 'iframe';
     const srcEnd = src.split('?')[0].split('/').pop() || '';
-    const extension = (srcEnd.split('.').pop() || '').toLowerCase();
+    const srcEndSplit = srcEnd.split('.');
+    const extension = (srcEndSplit.length > 1 ? srcEndSplit[srcEndSplit.length - 1] : '').toLowerCase();
     if (videoExtensions.includes(extension)) {
         nodeTag = 'video';
     } else if (audioExtensions.includes(extension)) {