3 DOMConversionMap, DOMConversionOutput, DOMExportOutput,
9 import type {EditorConfig} from "lexical/LexicalEditor";
11 import {el, setOrRemoveAttribute, sizeToPixels} from "../utils/dom";
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[] = [];
88 static clone(node: MediaNode) {
89 const newNode = new MediaNode(node.__tag, node.__key);
90 newNode.__attributes = Object.assign({}, node.__attributes);
91 newNode.__sources = node.__sources.map(s => Object.assign({}, s));
92 newNode.__id = node.__id;
93 newNode.__alignment = node.__alignment;
97 constructor(tag: MediaNodeTag, key?: string) {
102 setTag(tag: MediaNodeTag) {
103 const self = this.getWritable();
107 getTag(): MediaNodeTag {
108 const self = this.getLatest();
112 setAttributes(attributes: Record<string, string>) {
113 const self = this.getWritable();
114 self.__attributes = filterAttributes(attributes);
117 getAttributes(): Record<string, string> {
118 const self = this.getLatest();
119 return self.__attributes;
122 setSources(sources: MediaNodeSource[]) {
123 const self = this.getWritable();
124 self.__sources = sources;
127 getSources(): MediaNodeSource[] {
128 const self = this.getLatest();
129 return self.__sources;
132 setSrc(src: string): void {
133 const attrs = Object.assign({}, this.getAttributes());
134 if (this.__tag ==='object') {
139 this.setAttributes(attrs);
142 setWidthAndHeight(width: string, height: string): void {
143 const attrs = Object.assign(
145 this.getAttributes(),
148 this.setAttributes(attrs);
152 const self = this.getWritable();
157 const self = this.getLatest();
161 setAlignment(alignment: CommonBlockAlignment) {
162 const self = this.getWritable();
163 self.__alignment = alignment;
166 getAlignment(): CommonBlockAlignment {
167 const self = this.getLatest();
168 return self.__alignment;
171 setHeight(height: number): void {
176 const attrs = Object.assign({}, this.getAttributes(), {height});
177 this.setAttributes(attrs);
180 getHeight(): number {
181 const self = this.getLatest();
182 return sizeToPixels(self.__attributes.height || '0');
185 setWidth(width: number): void {
186 const attrs = Object.assign({}, this.getAttributes(), {width});
187 this.setAttributes(attrs);
191 const self = this.getLatest();
192 return sizeToPixels(self.__attributes.width || '0');
195 isInline(): boolean {
200 const sources = (this.__tag === 'video' || this.__tag === 'audio') ? this.__sources : [];
201 const sourceEls = sources.map(source => el('source', source));
202 const element = el(this.__tag, this.__attributes, sourceEls);
203 updateElementWithCommonBlockProps(element, this);
207 createDOM(_config: EditorConfig, _editor: LexicalEditor) {
208 const media = this.createInnerDOM();
209 const wrap = el('span', {
210 class: media.className + ' editor-media-wrap',
213 wrap.addEventListener('click', e => {
214 _editor.update(() => $selectSingleNode(this));
220 updateDOM(prevNode: MediaNode, dom: HTMLElement): boolean {
221 if (prevNode.__tag !== this.__tag) {
225 if (JSON.stringify(prevNode.__sources) !== JSON.stringify(this.__sources)) {
229 if (JSON.stringify(prevNode.__attributes) !== JSON.stringify(this.__attributes)) {
233 const mediaEl = dom.firstElementChild as HTMLElement;
235 if (prevNode.__id !== this.__id) {
236 setOrRemoveAttribute(mediaEl, 'id', this.__id);
239 if (prevNode.__alignment !== this.__alignment) {
240 if (prevNode.__alignment) {
241 dom.classList.remove(`align-${prevNode.__alignment}`);
242 mediaEl.classList.remove(`align-${prevNode.__alignment}`);
244 if (this.__alignment) {
245 dom.classList.add(`align-${this.__alignment}`);
246 mediaEl.classList.add(`align-${this.__alignment}`);
253 static importDOM(): DOMConversionMap|null {
255 const buildConverter = (tag: MediaNodeTag) => {
256 return (node: HTMLElement): DOMConversion|null => {
258 conversion: (element: HTMLElement): DOMConversionOutput|null => {
260 node: domElementToNode(tag, element),
269 iframe: buildConverter('iframe'),
270 embed: buildConverter('embed'),
271 object: buildConverter('object'),
272 video: buildConverter('video'),
273 audio: buildConverter('audio'),
277 exportDOM(editor: LexicalEditor): DOMExportOutput {
278 const element = this.createInnerDOM();
282 exportJSON(): SerializedMediaNode {
284 ...super.exportJSON(),
288 alignment: this.__alignment,
290 attributes: this.__attributes,
291 sources: this.__sources,
295 static importJSON(serializedNode: SerializedMediaNode): MediaNode {
296 const node = $createMediaNode(serializedNode.tag);
297 node.setId(serializedNode.id);
298 node.setAlignment(serializedNode.alignment);
304 export function $createMediaNode(tag: MediaNodeTag) {
305 return new MediaNode(tag);
308 export function $createMediaNodeFromHtml(html: string): MediaNode | null {
309 const parser = new DOMParser();
310 const doc = parser.parseFromString(`<body>${html}</body>`, 'text/html');
312 const el = doc.body.children[0];
313 if (!(el instanceof HTMLElement)) {
317 const tag = el.tagName.toLowerCase();
318 const validTypes = ['embed', 'iframe', 'video', 'audio', 'object'];
319 if (!validTypes.includes(tag)) {
323 return domElementToNode(tag as MediaNodeTag, el);
326 const videoExtensions = ['mp4', 'mpeg', 'm4v', 'm4p', 'mov'];
327 const audioExtensions = ['3gp', 'aac', 'flac', 'mp3', 'm4a', 'ogg', 'wav', 'webm'];
328 const iframeExtensions = ['html', 'htm', 'php', 'asp', 'aspx'];
330 export function $createMediaNodeFromSrc(src: string): MediaNode {
331 let nodeTag: MediaNodeTag = 'iframe';
332 const srcEnd = src.split('?')[0].split('/').pop() || '';
333 const extension = (srcEnd.split('.').pop() || '').toLowerCase();
334 if (videoExtensions.includes(extension)) {
336 } else if (audioExtensions.includes(extension)) {
338 } else if (extension && !iframeExtensions.includes(extension)) {
342 return new MediaNode(nodeTag);
345 export function $isMediaNode(node: LexicalNode | null | undefined): node is MediaNode {
346 return node instanceof MediaNode;
349 export function $isMediaNodeOfTag(node: LexicalNode | null | undefined, tag: MediaNodeTag): boolean {
350 return node instanceof MediaNode && (node as MediaNode).getTag() === tag;