3 DOMConversionMap, DOMConversionOutput, DOMExportOutput,
7 SerializedElementNode, Spread
9 import type {EditorConfig} from "lexical/LexicalEditor";
11 import {el, sizeToPixels} from "../utils/dom";
14 SerializedCommonBlockNode,
15 setCommonBlockPropsFromElement,
16 updateElementWithCommonBlockProps
18 import {elem} from "../../services/dom";
19 import {$selectSingleNode} from "../utils/selection";
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[] = [];
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;
98 constructor(tag: MediaNodeTag, key?: string) {
103 setTag(tag: MediaNodeTag) {
104 const self = this.getWritable();
108 getTag(): MediaNodeTag {
109 const self = this.getLatest();
113 setAttributes(attributes: Record<string, string>) {
114 const self = this.getWritable();
115 self.__attributes = filterAttributes(attributes);
118 getAttributes(): Record<string, string> {
119 const self = this.getLatest();
120 return self.__attributes;
123 setSources(sources: MediaNodeSource[]) {
124 const self = this.getWritable();
125 self.__sources = sources;
128 getSources(): MediaNodeSource[] {
129 const self = this.getLatest();
130 return self.__sources;
133 setSrc(src: string): void {
134 const attrs = Object.assign({}, this.getAttributes());
135 if (this.__tag ==='object') {
140 this.setAttributes(attrs);
143 setWidthAndHeight(width: string, height: string): void {
144 const attrs = Object.assign(
146 this.getAttributes(),
149 this.setAttributes(attrs);
153 const self = this.getWritable();
158 const self = this.getLatest();
162 setAlignment(alignment: CommonBlockAlignment) {
163 const self = this.getWritable();
164 self.__alignment = alignment;
167 getAlignment(): CommonBlockAlignment {
168 const self = this.getLatest();
169 return self.__alignment;
172 setHeight(height: number): void {
177 const attrs = Object.assign({}, this.getAttributes(), {height});
178 this.setAttributes(attrs);
181 getHeight(): number {
182 const self = this.getLatest();
183 return sizeToPixels(self.__attributes.height || '0');
186 setWidth(width: number): void {
187 const attrs = Object.assign({}, this.getAttributes(), {width});
188 this.setAttributes(attrs);
192 const self = this.getLatest();
193 return sizeToPixels(self.__attributes.width || '0');
196 isInline(): boolean {
201 const sources = (this.__tag === 'video' || this.__tag === 'audio') ? this.__sources : [];
202 const sourceEls = sources.map(source => el('source', source));
203 const element = el(this.__tag, this.__attributes, sourceEls);
204 updateElementWithCommonBlockProps(element, this);
208 createDOM(_config: EditorConfig, _editor: LexicalEditor) {
209 const media = this.createInnerDOM();
210 const wrap = el('span', {
211 class: media.className + ' editor-media-wrap',
214 wrap.addEventListener('click', e => {
215 _editor.update(() => $selectSingleNode(this));
221 updateDOM(prevNode: unknown, dom: HTMLElement) {
225 static importDOM(): DOMConversionMap|null {
227 const buildConverter = (tag: MediaNodeTag) => {
228 return (node: HTMLElement): DOMConversion|null => {
230 conversion: (element: HTMLElement): DOMConversionOutput|null => {
232 node: domElementToNode(tag, element),
241 iframe: buildConverter('iframe'),
242 embed: buildConverter('embed'),
243 object: buildConverter('object'),
244 video: buildConverter('video'),
245 audio: buildConverter('audio'),
249 exportDOM(editor: LexicalEditor): DOMExportOutput {
250 const element = this.createInnerDOM();
254 exportJSON(): SerializedMediaNode {
256 ...super.exportJSON(),
260 alignment: this.__alignment,
262 attributes: this.__attributes,
263 sources: this.__sources,
267 static importJSON(serializedNode: SerializedMediaNode): MediaNode {
268 const node = $createMediaNode(serializedNode.tag);
269 node.setId(serializedNode.id);
270 node.setAlignment(serializedNode.alignment);
276 export function $createMediaNode(tag: MediaNodeTag) {
277 return new MediaNode(tag);
280 export function $createMediaNodeFromHtml(html: string): MediaNode | null {
281 const parser = new DOMParser();
282 const doc = parser.parseFromString(`<body>${html}</body>`, 'text/html');
284 const el = doc.body.children[0];
285 if (!(el instanceof HTMLElement)) {
289 const tag = el.tagName.toLowerCase();
290 const validTypes = ['embed', 'iframe', 'video', 'audio', 'object'];
291 if (!validTypes.includes(tag)) {
295 return domElementToNode(tag as MediaNodeTag, el);
298 const videoExtensions = ['mp4', 'mpeg', 'm4v', 'm4p', 'mov'];
299 const audioExtensions = ['3gp', 'aac', 'flac', 'mp3', 'm4a', 'ogg', 'wav', 'webm'];
300 const iframeExtensions = ['html', 'htm', 'php', 'asp', 'aspx'];
302 export function $createMediaNodeFromSrc(src: string): MediaNode {
303 let nodeTag: MediaNodeTag = 'iframe';
304 const srcEnd = src.split('?')[0].split('/').pop() || '';
305 const extension = (srcEnd.split('.').pop() || '').toLowerCase();
306 if (videoExtensions.includes(extension)) {
308 } else if (audioExtensions.includes(extension)) {
310 } else if (extension && !iframeExtensions.includes(extension)) {
314 return new MediaNode(nodeTag);
317 export function $isMediaNode(node: LexicalNode | null | undefined): node is MediaNode {
318 return node instanceof MediaNode;
321 export function $isMediaNodeOfTag(node: LexicalNode | null | undefined, tag: MediaNodeTag): boolean {
322 return node instanceof MediaNode && (node as MediaNode).getTag() === tag;