]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/utils/dom.ts
a307bdd7531986289187cd3e53483cb8d515a178
[bookstack] / resources / js / wysiwyg / utils / dom.ts
1 export function el(tag: string, attrs: Record<string, string | null> = {}, children: (string | HTMLElement)[] = []): HTMLElement {
2     const el = document.createElement(tag);
3     const attrKeys = Object.keys(attrs);
4     for (const attr of attrKeys) {
5         if (attrs[attr] !== null) {
6             el.setAttribute(attr, attrs[attr] as string);
7         }
8     }
9
10     for (const child of children) {
11         if (typeof child === 'string') {
12             el.append(document.createTextNode(child));
13         } else {
14             el.append(child);
15         }
16     }
17
18     return el;
19 }
20
21 export function htmlToDom(html: string): Document {
22     const parser = new DOMParser();
23     return parser.parseFromString(html, 'text/html');
24 }
25
26 export function formatSizeValue(size: number | string, defaultSuffix: string = 'px'): string {
27     if (typeof size === 'number' || /^-?\d+$/.test(size)) {
28         return `${size}${defaultSuffix}`;
29     }
30
31     return size;
32 }
33
34 export type StyleMap = Map<string, string>;
35
36 /**
37  * Creates a map from an element's styles.
38  * Uses direct attribute value string handling since attempting to iterate
39  * over .style will expand out any shorthand properties (like 'padding') making
40  * rather than being representative of the actual properties set.
41  */
42 export function extractStyleMapFromElement(element: HTMLElement): StyleMap {
43     const map: StyleMap = new Map();
44     const styleText= element.getAttribute('style') || '';
45
46     const rules = styleText.split(';');
47     for (const rule of rules) {
48         const [name, value] = rule.split(':');
49         if (!name || !value) {
50             continue;
51         }
52
53         map.set(name.trim().toLowerCase(), value.trim());
54     }
55
56     return map;
57 }