3 DOMConversionMap, DOMConversionOutput, DOMExportOutput,
9 import type {EditorConfig} from "lexical/LexicalEditor";
11 import {el, setOrRemoveAttribute, sizeToPixels} from "../../utils/dom";
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 import * as url from "node:url";
21 export type MediaNodeTag = 'iframe' | 'embed' | 'object' | 'video' | 'audio';
22 export type MediaNodeSource = {
27 export type SerializedMediaNode = Spread<{
29 attributes: Record<string, string>;
30 sources: MediaNodeSource[];
31 }, SerializedCommonBlockNode>
33 const attributeAllowList = [
34 'width', 'height', 'style', 'title', 'name',
35 'src', 'allow', 'allowfullscreen', 'loading', 'sandbox',
36 'type', 'data', 'controls', 'autoplay', 'controlslist', 'loop',
37 'muted', 'playsinline', 'poster', 'preload'
40 function filterAttributes(attributes: Record<string, string>): Record<string, string> {
41 const filtered: Record<string, string> = {};
42 for (const key of Object.keys(attributes)) {
43 if (attributeAllowList.includes(key)) {
44 filtered[key] = attributes[key];
50 function domElementToNode(tag: MediaNodeTag, element: HTMLElement): MediaNode {
51 const node = $createMediaNode(tag);
53 const attributes: Record<string, string> = {};
54 for (const attribute of element.attributes) {
55 attributes[attribute.name] = attribute.value;
57 node.setAttributes(attributes);
59 const sources: MediaNodeSource[] = [];
60 if (tag === 'video' || tag === 'audio') {
61 for (const child of element.children) {
62 if (child.tagName === 'SOURCE') {
63 const src = child.getAttribute('src');
64 const type = child.getAttribute('type');
66 sources.push({ src, type });
70 node.setSources(sources);
73 setCommonBlockPropsFromElement(element, node);
78 export class MediaNode extends ElementNode {
80 __alignment: CommonBlockAlignment = '';
82 __attributes: Record<string, string> = {};
83 __sources: MediaNodeSource[] = [];
90 static clone(node: MediaNode) {
91 const newNode = new MediaNode(node.__tag, node.__key);
92 newNode.__attributes = Object.assign({}, node.__attributes);
93 newNode.__sources = node.__sources.map(s => Object.assign({}, s));
94 newNode.__id = node.__id;
95 newNode.__alignment = node.__alignment;
96 newNode.__inset = node.__inset;
100 constructor(tag: MediaNodeTag, key?: string) {
105 setTag(tag: MediaNodeTag) {
106 const self = this.getWritable();
110 getTag(): MediaNodeTag {
111 const self = this.getLatest();
115 setAttributes(attributes: Record<string, string>) {
116 const self = this.getWritable();
117 self.__attributes = filterAttributes(attributes);
120 getAttributes(): Record<string, string> {
121 const self = this.getLatest();
122 return self.__attributes;
125 setSources(sources: MediaNodeSource[]) {
126 const self = this.getWritable();
127 self.__sources = sources;
130 getSources(): MediaNodeSource[] {
131 const self = this.getLatest();
132 return self.__sources;
135 setSrc(src: string): void {
136 const attrs = Object.assign({}, this.getAttributes());
137 if (this.__tag ==='object') {
142 this.setAttributes(attrs);
145 setWidthAndHeight(width: string, height: string): void {
146 const attrs = Object.assign(
148 this.getAttributes(),
151 this.setAttributes(attrs);
155 const self = this.getWritable();
160 const self = this.getLatest();
164 setAlignment(alignment: CommonBlockAlignment) {
165 const self = this.getWritable();
166 self.__alignment = alignment;
169 getAlignment(): CommonBlockAlignment {
170 const self = this.getLatest();
171 return self.__alignment;
174 setInset(size: number) {
175 const self = this.getWritable();
180 const self = this.getLatest();
184 setHeight(height: number): void {
189 const attrs = Object.assign({}, this.getAttributes(), {height});
190 this.setAttributes(attrs);
193 getHeight(): number {
194 const self = this.getLatest();
195 return sizeToPixels(self.__attributes.height || '0');
198 setWidth(width: number): void {
199 const attrs = Object.assign({}, this.getAttributes(), {width});
200 this.setAttributes(attrs);
204 const self = this.getLatest();
205 return sizeToPixels(self.__attributes.width || '0');
208 isInline(): boolean {
212 isParentRequired(): boolean {
217 const sources = (this.__tag === 'video' || this.__tag === 'audio') ? this.__sources : [];
218 const sourceEls = sources.map(source => el('source', source));
219 const element = el(this.__tag, this.__attributes, sourceEls);
220 updateElementWithCommonBlockProps(element, this);
224 createDOM(_config: EditorConfig, _editor: LexicalEditor) {
225 const media = this.createInnerDOM();
226 const wrap = el('span', {
227 class: media.className + ' editor-media-wrap',
230 wrap.addEventListener('click', e => {
231 _editor.update(() => $selectSingleNode(this));
237 updateDOM(prevNode: MediaNode, dom: HTMLElement): boolean {
238 if (prevNode.__tag !== this.__tag) {
242 if (JSON.stringify(prevNode.__sources) !== JSON.stringify(this.__sources)) {
246 if (JSON.stringify(prevNode.__attributes) !== JSON.stringify(this.__attributes)) {
250 const mediaEl = dom.firstElementChild as HTMLElement;
252 if (prevNode.__id !== this.__id) {
253 setOrRemoveAttribute(mediaEl, 'id', this.__id);
256 if (prevNode.__alignment !== this.__alignment) {
257 if (prevNode.__alignment) {
258 dom.classList.remove(`align-${prevNode.__alignment}`);
259 mediaEl.classList.remove(`align-${prevNode.__alignment}`);
261 if (this.__alignment) {
262 dom.classList.add(`align-${this.__alignment}`);
263 mediaEl.classList.add(`align-${this.__alignment}`);
267 if (prevNode.__inset !== this.__inset) {
268 dom.style.paddingLeft = `${this.__inset}px`;
274 static importDOM(): DOMConversionMap|null {
276 const buildConverter = (tag: MediaNodeTag) => {
277 return (node: HTMLElement): DOMConversion|null => {
279 conversion: (element: HTMLElement): DOMConversionOutput|null => {
281 node: domElementToNode(tag, element),
290 iframe: buildConverter('iframe'),
291 embed: buildConverter('embed'),
292 object: buildConverter('object'),
293 video: buildConverter('video'),
294 audio: buildConverter('audio'),
298 exportDOM(editor: LexicalEditor): DOMExportOutput {
299 const element = this.createInnerDOM();
303 exportJSON(): SerializedMediaNode {
305 ...super.exportJSON(),
309 alignment: this.__alignment,
312 attributes: this.__attributes,
313 sources: this.__sources,
317 static importJSON(serializedNode: SerializedMediaNode): MediaNode {
318 const node = $createMediaNode(serializedNode.tag);
319 deserializeCommonBlockNode(serializedNode, node);
325 export function $createMediaNode(tag: MediaNodeTag) {
326 return new MediaNode(tag);
329 export function $createMediaNodeFromHtml(html: string): MediaNode | null {
330 const parser = new DOMParser();
331 const doc = parser.parseFromString(`<body>${html}</body>`, 'text/html');
333 const el = doc.body.children[0];
334 if (!(el instanceof HTMLElement)) {
338 const tag = el.tagName.toLowerCase();
339 const validTypes = ['embed', 'iframe', 'video', 'audio', 'object'];
340 if (!validTypes.includes(tag)) {
344 return domElementToNode(tag as MediaNodeTag, el);
347 interface UrlPattern {
348 readonly regex: RegExp;
351 readonly url: string;
355 * These patterns originate from the tinymce/tinymce project.
356 * https://github.com/tinymce/tinymce/blob/release/6.6/modules/tinymce/src/plugins/media/main/ts/core/UrlPatterns.ts
357 * License: MIT Copyright (c) 2022 Ephox Corporation DBA Tiny Technologies, Inc.
358 * License Link: https://github.com/tinymce/tinymce/blob/584a150679669859a528828e5d2910a083b1d911/LICENSE.TXT
360 const urlPatterns: UrlPattern[] = [
362 regex: /.*?youtu\.be\/([\w\-_\?&=.]+)/i,
364 url: 'https://www.youtube.com/embed/$1',
367 regex: /.*youtube\.com(.+)v=([^&]+)(&([a-z0-9&=\-_]+))?.*/i,
369 url: 'https://www.youtube.com/embed/$2?$4',
372 regex: /.*youtube.com\/embed\/([a-z0-9\?&=\-_]+).*/i,
374 url: 'https://www.youtube.com/embed/$1',
378 const videoExtensions = ['mp4', 'mpeg', 'm4v', 'm4p', 'mov'];
379 const audioExtensions = ['3gp', 'aac', 'flac', 'mp3', 'm4a', 'ogg', 'wav', 'webm'];
380 const iframeExtensions = ['html', 'htm', 'php', 'asp', 'aspx', ''];
382 export function $createMediaNodeFromSrc(src: string): MediaNode {
384 for (const pattern of urlPatterns) {
385 const match = src.match(pattern.regex);
387 const newSrc = src.replace(pattern.regex, pattern.url);
388 const node = new MediaNode('iframe');
390 node.setHeight(pattern.h);
391 node.setWidth(pattern.w);
396 let nodeTag: MediaNodeTag = 'iframe';
397 const srcEnd = src.split('?')[0].split('/').pop() || '';
398 const srcEndSplit = srcEnd.split('.');
399 const extension = (srcEndSplit.length > 1 ? srcEndSplit[srcEndSplit.length - 1] : '').toLowerCase();
400 if (videoExtensions.includes(extension)) {
402 } else if (audioExtensions.includes(extension)) {
404 } else if (extension && !iframeExtensions.includes(extension)) {
408 const node = new MediaNode(nodeTag);
413 export function $isMediaNode(node: LexicalNode | null | undefined): node is MediaNode {
414 return node instanceof MediaNode;
417 export function $isMediaNodeOfTag(node: LexicalNode | null | undefined, tag: MediaNodeTag): boolean {
418 return node instanceof MediaNode && (node as MediaNode).getTag() === tag;