import { IAttributeItem, IAttributes } from './../interfaces/IAttributes'; import { IHTMLElement } from '../interfaces/IHTMLElement'; export class HtmlConverter { static toJSON(element: HTMLElement, order: string = '1'): IHTMLElement { const tag = element.tagName.toLocaleLowerCase(); const attributes = HtmlConverter._attributes(element); const result: IHTMLElement = { tag, attributes, order }; if ( ![ 'p', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'b', 'i', 'u', ].includes(tag) ) { const elementList = Array.from(element.children); const elements = elementList.map((e: HTMLElement, index: number) => HtmlConverter.toJSON(e, `${order}.${index + 1}`) ); elements.length && (result.elements = elements); } return result; } private static _attributes(element: HTMLElement): IAttributes { let attributes: IAttributes = {}; const styles = HtmlConverter.getStyle(element); const classes = HtmlConverter._getClasses(element); const dataset = HtmlConverter._getDataSet(element); const properties = HtmlConverter._getProperties(element); styles && (attributes.styles = styles); classes && (attributes.classes = classes); dataset && (attributes.dataset = dataset); properties && (attributes.properties = properties); return attributes; } static getStyle(element: HTMLElement): IAttributeItem[] | undefined { if (!element.style.cssText) return; return element.style.cssText .split(';') .filter((a) => a) .map((r) => { let [key, value] = r.split(':'); key = key.trim(); value = value.trim(); return { key, value }; }); } private static _getDataSet(element: HTMLElement): IAttributeItem[] { const dataset = ['selectable', '_id', 'type', 'parent'] .map((key) => { const value = element.dataset[key]; if (!value) return; return { key, value }; }) .filter((r) => r); if (!dataset.length) return []; return dataset; } private static _getClasses( element: HTMLElement ): IAttributeItem[] | undefined { const classList = Array.from(element.classList); if (!classList.length) return; return Array.from(element.classList).map((value) => { return { key: 'class', value: value.trim(), }; }); } private static _getProperties(element: HTMLElement): IAttributeItem[] { const tagName = element.tagName.toLocaleLowerCase(); let result: IAttributeItem[] = []; if (['p', 'span', 'h1', 'h2', 'h3', 'h4', 'h5'].includes(tagName)) { result = [ ...['innerHTML'] .map((key) => { const value = (element)[key]; if (!value) return; return { key, value }; }) .filter((r) => r), ]; } if (['img', 'video', 'source'].includes(tagName)) { result = [ ...['src', 'alt', 'controls', 'autoplay', 'type'] .map((key) => { const value = (element)[key]; if (!value) return; return { key, value }; }) .filter((r) => r), ]; } if (['video', 'source'].includes(tagName)) { result = [ ...['controls', 'autoplay', 'type', 'src'] .map((key) => { const value = (element)[key]; if (!value) return; return { key, value }; }) .filter((r) => r), ]; } return result; } }