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();
241 const wrap = el('span', {
242 class: media.className + ' editor-media-wrap',
245 wrap.addEventListener('click', e => {
246 _editor.update(() => $selectSingleNode(this));
252 updateDOM(prevNode: MediaNode, dom: HTMLElement): boolean {
253 if (prevNode.__tag !== this.__tag) {
257 if (JSON.stringify(prevNode.__sources) !== JSON.stringify(this.__sources)) {
261 if (JSON.stringify(prevNode.__attributes) !== JSON.stringify(this.__attributes)) {
265 const mediaEl = dom.firstElementChild as HTMLElement;
267 if (prevNode.__id !== this.__id) {
268 setOrRemoveAttribute(mediaEl, 'id', this.__id);
271 if (prevNode.__alignment !== this.__alignment) {
272 if (prevNode.__alignment) {
273 dom.classList.remove(`align-${prevNode.__alignment}`);
274 mediaEl.classList.remove(`align-${prevNode.__alignment}`);
276 if (this.__alignment) {
277 dom.classList.add(`align-${this.__alignment}`);
278 mediaEl.classList.add(`align-${this.__alignment}`);
282 if (prevNode.__inset !== this.__inset) {
283 dom.style.paddingLeft = `${this.__inset}px`;
289 static importDOM(): DOMConversionMap|null {
291 const buildConverter = (tag: MediaNodeTag) => {
292 return (node: HTMLElement): DOMConversion|null => {
294 conversion: (element: HTMLElement): DOMConversionOutput|null => {
296 node: domElementToNode(tag, element),
305 iframe: buildConverter('iframe'),
306 embed: buildConverter('embed'),
307 object: buildConverter('object'),
308 video: buildConverter('video'),
309 audio: buildConverter('audio'),
313 exportDOM(editor: LexicalEditor): DOMExportOutput {
314 const element = this.createInnerDOM();
318 exportJSON(): SerializedMediaNode {
320 ...super.exportJSON(),
324 alignment: this.__alignment,
327 attributes: this.__attributes,
328 sources: this.__sources,
332 static importJSON(serializedNode: SerializedMediaNode): MediaNode {
333 const node = $createMediaNode(serializedNode.tag);
334 deserializeCommonBlockNode(serializedNode, node);
340 export function $createMediaNode(tag: MediaNodeTag) {
341 return new MediaNode(tag);
344 export function $createMediaNodeFromHtml(html: string): MediaNode | null {
345 const parser = new DOMParser();
346 const doc = parser.parseFromString(`<body>${html}</body>`, 'text/html');
348 const el = doc.body.children[0];
349 if (!(el instanceof HTMLElement)) {
353 const tag = el.tagName.toLowerCase();
354 const validTypes = ['embed', 'iframe', 'video', 'audio', 'object'];
355 if (!validTypes.includes(tag)) {
359 return domElementToNode(tag as MediaNodeTag, el);
362 interface UrlPattern {
363 readonly regex: RegExp;
366 readonly url: string;
370 * These patterns originate from the tinymce/tinymce project.
371 * https://github.com/tinymce/tinymce/blob/release/6.6/modules/tinymce/src/plugins/media/main/ts/core/UrlPatterns.ts
372 * License: MIT Copyright (c) 2022 Ephox Corporation DBA Tiny Technologies, Inc.
373 * License Link: https://github.com/tinymce/tinymce/blob/584a150679669859a528828e5d2910a083b1d911/LICENSE.TXT
375 const urlPatterns: UrlPattern[] = [
377 regex: /.*?youtu\.be\/([\w\-_\?&=.]+)/i,
379 url: 'https://www.youtube.com/embed/$1',
382 regex: /.*youtube\.com(.+)v=([^&]+)(&([a-z0-9&=\-_]+))?.*/i,
384 url: 'https://www.youtube.com/embed/$2?$4',
387 regex: /.*youtube.com\/embed\/([a-z0-9\?&=\-_]+).*/i,
389 url: 'https://www.youtube.com/embed/$1',
393 const videoExtensions = ['mp4', 'mpeg', 'm4v', 'm4p', 'mov'];
394 const audioExtensions = ['3gp', 'aac', 'flac', 'mp3', 'm4a', 'ogg', 'wav', 'webm'];
395 const iframeExtensions = ['html', 'htm', 'php', 'asp', 'aspx', ''];
397 export function $createMediaNodeFromSrc(src: string): MediaNode {
399 for (const pattern of urlPatterns) {
400 const match = src.match(pattern.regex);
402 const newSrc = src.replace(pattern.regex, pattern.url);
403 const node = new MediaNode('iframe');
405 node.setHeight(pattern.h);
406 node.setWidth(pattern.w);
411 let nodeTag: MediaNodeTag = 'iframe';
412 const srcEnd = src.split('?')[0].split('/').pop() || '';
413 const srcEndSplit = srcEnd.split('.');
414 const extension = (srcEndSplit.length > 1 ? srcEndSplit[srcEndSplit.length - 1] : '').toLowerCase();
415 if (videoExtensions.includes(extension)) {
417 } else if (audioExtensions.includes(extension)) {
419 } else if (extension && !iframeExtensions.includes(extension)) {
423 const node = new MediaNode(nodeTag);
428 export function $isMediaNode(node: LexicalNode | null | undefined): node is MediaNode {
429 return node instanceof MediaNode;
432 export function $isMediaNodeOfTag(node: LexicalNode | null | undefined, tag: MediaNodeTag): boolean {
433 return node instanceof MediaNode && (node as MediaNode).getTag() === tag;