3 DOMConversionMap, DOMConversionOutput, DOMExportOutput,
9 import type {EditorConfig} from "lexical/LexicalEditor";
11 import {el, setOrRemoveAttribute, sizeToPixels} from "../utils/dom";
13 CommonBlockAlignment, deserializeCommonBlockNode,
14 SerializedCommonBlockNode,
15 setCommonBlockPropsFromElement,
16 updateElementWithCommonBlockProps
18 import {$selectSingleNode} from "../utils/selection";
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 domElementToNode(tag: MediaNodeTag, element: HTMLElement): MediaNode {
50 const node = $createMediaNode(tag);
52 const attributes: Record<string, string> = {};
53 for (const attribute of element.attributes) {
54 attributes[attribute.name] = attribute.value;
56 node.setAttributes(attributes);
58 const sources: MediaNodeSource[] = [];
59 if (tag === 'video' || tag === 'audio') {
60 for (const child of element.children) {
61 if (child.tagName === 'SOURCE') {
62 const src = child.getAttribute('src');
63 const type = child.getAttribute('type');
65 sources.push({ src, type });
69 node.setSources(sources);
72 setCommonBlockPropsFromElement(element, node);
77 export class MediaNode extends ElementNode {
79 __alignment: CommonBlockAlignment = '';
81 __attributes: Record<string, string> = {};
82 __sources: MediaNodeSource[] = [];
89 static clone(node: MediaNode) {
90 const newNode = new MediaNode(node.__tag, node.__key);
91 newNode.__attributes = Object.assign({}, node.__attributes);
92 newNode.__sources = node.__sources.map(s => Object.assign({}, s));
93 newNode.__id = node.__id;
94 newNode.__alignment = node.__alignment;
95 newNode.__inset = node.__inset;
99 constructor(tag: MediaNodeTag, key?: string) {
104 setTag(tag: MediaNodeTag) {
105 const self = this.getWritable();
109 getTag(): MediaNodeTag {
110 const self = this.getLatest();
114 setAttributes(attributes: Record<string, string>) {
115 const self = this.getWritable();
116 self.__attributes = filterAttributes(attributes);
119 getAttributes(): Record<string, string> {
120 const self = this.getLatest();
121 return self.__attributes;
124 setSources(sources: MediaNodeSource[]) {
125 const self = this.getWritable();
126 self.__sources = sources;
129 getSources(): MediaNodeSource[] {
130 const self = this.getLatest();
131 return self.__sources;
134 setSrc(src: string): void {
135 const attrs = Object.assign({}, this.getAttributes());
136 if (this.__tag ==='object') {
141 this.setAttributes(attrs);
144 setWidthAndHeight(width: string, height: string): void {
145 const attrs = Object.assign(
147 this.getAttributes(),
150 this.setAttributes(attrs);
154 const self = this.getWritable();
159 const self = this.getLatest();
163 setAlignment(alignment: CommonBlockAlignment) {
164 const self = this.getWritable();
165 self.__alignment = alignment;
168 getAlignment(): CommonBlockAlignment {
169 const self = this.getLatest();
170 return self.__alignment;
173 setInset(size: number) {
174 const self = this.getWritable();
179 const self = this.getLatest();
183 setHeight(height: number): void {
188 const attrs = Object.assign({}, this.getAttributes(), {height});
189 this.setAttributes(attrs);
192 getHeight(): number {
193 const self = this.getLatest();
194 return sizeToPixels(self.__attributes.height || '0');
197 setWidth(width: number): void {
198 const attrs = Object.assign({}, this.getAttributes(), {width});
199 this.setAttributes(attrs);
203 const self = this.getLatest();
204 return sizeToPixels(self.__attributes.width || '0');
207 isInline(): boolean {
211 isParentRequired(): boolean {
216 const sources = (this.__tag === 'video' || this.__tag === 'audio') ? this.__sources : [];
217 const sourceEls = sources.map(source => el('source', source));
218 const element = el(this.__tag, this.__attributes, sourceEls);
219 updateElementWithCommonBlockProps(element, this);
223 createDOM(_config: EditorConfig, _editor: LexicalEditor) {
224 const media = this.createInnerDOM();
225 const wrap = el('span', {
226 class: media.className + ' editor-media-wrap',
229 wrap.addEventListener('click', e => {
230 _editor.update(() => $selectSingleNode(this));
236 updateDOM(prevNode: MediaNode, dom: HTMLElement): boolean {
237 if (prevNode.__tag !== this.__tag) {
241 if (JSON.stringify(prevNode.__sources) !== JSON.stringify(this.__sources)) {
245 if (JSON.stringify(prevNode.__attributes) !== JSON.stringify(this.__attributes)) {
249 const mediaEl = dom.firstElementChild as HTMLElement;
251 if (prevNode.__id !== this.__id) {
252 setOrRemoveAttribute(mediaEl, 'id', this.__id);
255 if (prevNode.__alignment !== this.__alignment) {
256 if (prevNode.__alignment) {
257 dom.classList.remove(`align-${prevNode.__alignment}`);
258 mediaEl.classList.remove(`align-${prevNode.__alignment}`);
260 if (this.__alignment) {
261 dom.classList.add(`align-${this.__alignment}`);
262 mediaEl.classList.add(`align-${this.__alignment}`);
266 if (prevNode.__inset !== this.__inset) {
267 dom.style.paddingLeft = `${this.__inset}px`;
273 static importDOM(): DOMConversionMap|null {
275 const buildConverter = (tag: MediaNodeTag) => {
276 return (node: HTMLElement): DOMConversion|null => {
278 conversion: (element: HTMLElement): DOMConversionOutput|null => {
280 node: domElementToNode(tag, element),
289 iframe: buildConverter('iframe'),
290 embed: buildConverter('embed'),
291 object: buildConverter('object'),
292 video: buildConverter('video'),
293 audio: buildConverter('audio'),
297 exportDOM(editor: LexicalEditor): DOMExportOutput {
298 const element = this.createInnerDOM();
302 exportJSON(): SerializedMediaNode {
304 ...super.exportJSON(),
308 alignment: this.__alignment,
311 attributes: this.__attributes,
312 sources: this.__sources,
316 static importJSON(serializedNode: SerializedMediaNode): MediaNode {
317 const node = $createMediaNode(serializedNode.tag);
318 deserializeCommonBlockNode(serializedNode, node);
324 export function $createMediaNode(tag: MediaNodeTag) {
325 return new MediaNode(tag);
328 export function $createMediaNodeFromHtml(html: string): MediaNode | null {
329 const parser = new DOMParser();
330 const doc = parser.parseFromString(`<body>${html}</body>`, 'text/html');
332 const el = doc.body.children[0];
333 if (!(el instanceof HTMLElement)) {
337 const tag = el.tagName.toLowerCase();
338 const validTypes = ['embed', 'iframe', 'video', 'audio', 'object'];
339 if (!validTypes.includes(tag)) {
343 return domElementToNode(tag as MediaNodeTag, el);
346 const videoExtensions = ['mp4', 'mpeg', 'm4v', 'm4p', 'mov'];
347 const audioExtensions = ['3gp', 'aac', 'flac', 'mp3', 'm4a', 'ogg', 'wav', 'webm'];
348 const iframeExtensions = ['html', 'htm', 'php', 'asp', 'aspx', ''];
350 export function $createMediaNodeFromSrc(src: string): MediaNode {
351 let nodeTag: MediaNodeTag = 'iframe';
352 const srcEnd = src.split('?')[0].split('/').pop() || '';
353 const srcEndSplit = srcEnd.split('.');
354 const extension = (srcEndSplit.length > 1 ? srcEndSplit[srcEndSplit.length - 1] : '').toLowerCase();
355 if (videoExtensions.includes(extension)) {
357 } else if (audioExtensions.includes(extension)) {
359 } else if (extension && !iframeExtensions.includes(extension)) {
363 return new MediaNode(nodeTag);
366 export function $isMediaNode(node: LexicalNode | null | undefined): node is MediaNode {
367 return node instanceof MediaNode;
370 export function $isMediaNodeOfTag(node: LexicalNode | null | undefined, tag: MediaNodeTag): boolean {
371 return node instanceof MediaNode && (node as MediaNode).getTag() === tag;