3 DOMConversionMap, DOMConversionOutput, DOMExportOutput,
9 import type {EditorConfig} from "lexical/LexicalEditor";
11 import {el, setOrRemoveAttribute, sizeToPixels, styleMapToStyleString, styleStringToStyleMap} 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";
20 export type MediaNodeTag = 'iframe' | 'embed' | 'object' | 'video' | 'audio';
21 export type MediaNodeSource = {
26 export type SerializedMediaNode = Spread<{
28 attributes: Record<string, string>;
29 sources: MediaNodeSource[];
30 }, SerializedCommonBlockNode>
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'
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];
49 function removeStyleFromAttributes(attributes: Record<string, string>, styleName: string): Record<string, string> {
50 const attrCopy = Object.assign({}, attributes);
51 if (!attributes.style) {
55 const map = styleStringToStyleMap(attributes.style);
56 map.delete(styleName);
58 attrCopy.style = styleMapToStyleString(map);
62 function domElementToNode(tag: MediaNodeTag, element: HTMLElement): MediaNode {
63 const node = $createMediaNode(tag);
65 const attributes: Record<string, string> = {};
66 for (const attribute of element.attributes) {
67 attributes[attribute.name] = attribute.value;
69 node.setAttributes(attributes);
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');
78 sources.push({ src, type });
82 node.setSources(sources);
85 setCommonBlockPropsFromElement(element, node);
90 export class MediaNode extends ElementNode {
92 __alignment: CommonBlockAlignment = '';
94 __attributes: Record<string, string> = {};
95 __sources: MediaNodeSource[] = [];
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;
112 constructor(tag: MediaNodeTag, key?: string) {
117 setTag(tag: MediaNodeTag) {
118 const self = this.getWritable();
122 getTag(): MediaNodeTag {
123 const self = this.getLatest();
127 setAttributes(attributes: Record<string, string>) {
128 const self = this.getWritable();
129 self.__attributes = filterAttributes(attributes);
132 getAttributes(): Record<string, string> {
133 const self = this.getLatest();
134 return Object.assign({}, self.__attributes);
137 setSources(sources: MediaNodeSource[]) {
138 const self = this.getWritable();
139 self.__sources = sources;
142 getSources(): MediaNodeSource[] {
143 const self = this.getLatest();
144 return self.__sources;
147 setSrc(src: string): void {
148 const attrs = this.getAttributes();
149 if (this.__tag ==='object') {
154 this.setAttributes(attrs);
157 setWidthAndHeight(width: string, height: string): void {
158 let attrs: Record<string, string> = Object.assign(
159 this.getAttributes(),
163 attrs = removeStyleFromAttributes(attrs, 'width');
164 attrs = removeStyleFromAttributes(attrs, 'height');
165 this.setAttributes(attrs);
169 const self = this.getWritable();
174 const self = this.getLatest();
178 setAlignment(alignment: CommonBlockAlignment) {
179 const self = this.getWritable();
180 self.__alignment = alignment;
183 getAlignment(): CommonBlockAlignment {
184 const self = this.getLatest();
185 return self.__alignment;
188 setInset(size: number) {
189 const self = this.getWritable();
194 const self = this.getLatest();
198 setHeight(height: number): void {
203 const attrs = Object.assign(this.getAttributes(), {height});
204 this.setAttributes(removeStyleFromAttributes(attrs, 'height'));
207 getHeight(): number {
208 const self = this.getLatest();
209 return sizeToPixels(self.__attributes.height || '0');
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'));
219 const self = this.getLatest();
220 return sizeToPixels(self.__attributes.width || '0');
223 isInline(): boolean {
227 isParentRequired(): boolean {
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);
239 createDOM(_config: EditorConfig, _editor: LexicalEditor) {
240 const media = this.createInnerDOM();
242 class: media.className + ' editor-media-wrap',
246 updateDOM(prevNode: MediaNode, dom: HTMLElement): boolean {
247 if (prevNode.__tag !== this.__tag) {
251 if (JSON.stringify(prevNode.__sources) !== JSON.stringify(this.__sources)) {
255 if (JSON.stringify(prevNode.__attributes) !== JSON.stringify(this.__attributes)) {
259 const mediaEl = dom.firstElementChild as HTMLElement;
261 if (prevNode.__id !== this.__id) {
262 setOrRemoveAttribute(mediaEl, 'id', this.__id);
265 if (prevNode.__alignment !== this.__alignment) {
266 if (prevNode.__alignment) {
267 dom.classList.remove(`align-${prevNode.__alignment}`);
268 mediaEl.classList.remove(`align-${prevNode.__alignment}`);
270 if (this.__alignment) {
271 dom.classList.add(`align-${this.__alignment}`);
272 mediaEl.classList.add(`align-${this.__alignment}`);
276 if (prevNode.__inset !== this.__inset) {
277 dom.style.paddingLeft = `${this.__inset}px`;
283 static importDOM(): DOMConversionMap|null {
285 const buildConverter = (tag: MediaNodeTag) => {
286 return (node: HTMLElement): DOMConversion|null => {
288 conversion: (element: HTMLElement): DOMConversionOutput|null => {
290 node: domElementToNode(tag, element),
299 iframe: buildConverter('iframe'),
300 embed: buildConverter('embed'),
301 object: buildConverter('object'),
302 video: buildConverter('video'),
303 audio: buildConverter('audio'),
307 exportDOM(editor: LexicalEditor): DOMExportOutput {
308 const element = this.createInnerDOM();
312 exportJSON(): SerializedMediaNode {
314 ...super.exportJSON(),
318 alignment: this.__alignment,
321 attributes: this.__attributes,
322 sources: this.__sources,
326 static importJSON(serializedNode: SerializedMediaNode): MediaNode {
327 const node = $createMediaNode(serializedNode.tag);
328 deserializeCommonBlockNode(serializedNode, node);
334 export function $createMediaNode(tag: MediaNodeTag) {
335 return new MediaNode(tag);
338 export function $createMediaNodeFromHtml(html: string): MediaNode | null {
339 const parser = new DOMParser();
340 const doc = parser.parseFromString(`<body>${html}</body>`, 'text/html');
342 const el = doc.body.children[0];
343 if (!(el instanceof HTMLElement)) {
347 const tag = el.tagName.toLowerCase();
348 const validTypes = ['embed', 'iframe', 'video', 'audio', 'object'];
349 if (!validTypes.includes(tag)) {
353 return domElementToNode(tag as MediaNodeTag, el);
356 interface UrlPattern {
357 readonly regex: RegExp;
360 readonly url: string;
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
369 const urlPatterns: UrlPattern[] = [
371 regex: /.*?youtu\.be\/([\w\-_\?&=.]+)/i,
373 url: 'https://www.youtube.com/embed/$1',
376 regex: /.*youtube\.com(.+)v=([^&]+)(&([a-z0-9&=\-_]+))?.*/i,
378 url: 'https://www.youtube.com/embed/$2?$4',
381 regex: /.*youtube.com\/embed\/([a-z0-9\?&=\-_]+).*/i,
383 url: 'https://www.youtube.com/embed/$1',
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', ''];
391 export function $createMediaNodeFromSrc(src: string): MediaNode {
393 for (const pattern of urlPatterns) {
394 const match = src.match(pattern.regex);
396 const newSrc = src.replace(pattern.regex, pattern.url);
397 const node = new MediaNode('iframe');
399 node.setHeight(pattern.h);
400 node.setWidth(pattern.w);
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)) {
411 } else if (audioExtensions.includes(extension)) {
413 } else if (extension && !iframeExtensions.includes(extension)) {
417 const node = new MediaNode(nodeTag);
422 export function $isMediaNode(node: LexicalNode | null | undefined): node is MediaNode {
423 return node instanceof MediaNode;
426 export function $isMediaNodeOfTag(node: LexicalNode | null | undefined, tag: MediaNodeTag): boolean {
427 return node instanceof MediaNode && (node as MediaNode).getTag() === tag;