-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathparse.ts
More file actions
167 lines (153 loc) · 4.83 KB
/
parse.ts
File metadata and controls
167 lines (153 loc) · 4.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import {
HTMLElement,
Node as HTMLNode,
NodeType,
parse,
TextNode,
} from 'node-html-parser';
import { Tag } from './tags.js';
import { Block, Declaration, List, Rule, StyleSheet } from 'css-tree';
import { generate, parse as cssParse } from 'css-tree';
import supportedStyles from './supportedStyles.js';
import { HtmlStyle, HtmlStyles } from './styles.js';
import camelize from './camelize.js';
export type HtmlContent = (HtmlElement | string)[];
export type HtmlElement = HTMLElement & {
tag: Tag | 'string';
parentNode: HtmlElement;
style: HtmlStyle[];
content: HtmlContent;
indexOfType: number;
querySelectorAll: (selector: string) => HtmlElement[];
querySelector: (selector: string) => HtmlElement;
};
export const convertRule = (
rule: Block,
source: string = 'style'
): HtmlStyle => {
const declarations = rule.children
.filter((declaration) => declaration.type === 'Declaration')
.toArray() as Declaration[];
return declarations
.map((entry) => ({
...entry,
property: camelize(entry.property as string),
}))
.reduce((style, { property, value }: Declaration) => {
let valueString: string | string[] = generate(value);
if (property && value) {
if (property === 'fontFamily') {
valueString = valueString.replace(/["']+/g, '').split(',');
} else if (!supportedStyles.includes(property)) {
if (
(property === 'background' &&
/^#?[a-zA-Z0-9]+$/.test(valueString)) ||
/^rgba?\([0-9, ]+\)$/i.test(valueString) ||
/^hsla?\([0-9.%, ]+\)$/i.test(valueString)
) {
property = 'backgroundColor';
} else {
console.warn(`${source}: Found unsupported style "${property}"`, {
property,
value,
});
}
}
style[property as keyof HtmlStyle] = valueString;
}
return style;
}, {} as HtmlStyle);
};
export const convertStylesheet = (stylesheet: string): HtmlStyles => {
const response = {} as HtmlStyles;
try {
const parsed = cssParse(stylesheet) as StyleSheet;
const rules = parsed.children.filter(
(rule) => rule.type === 'Rule' && rule.prelude?.type === 'SelectorList'
) as List<Rule>;
rules.forEach((rule) => {
const style = convertRule(rule.block);
if (rule.prelude.type !== 'SelectorList') {
return;
}
rule.prelude.children.forEach((selector) => {
const selectorString = generate(selector);
if (selectorString.includes('::')) {
// skip pseudo-elements
return;
}
response[selectorString] = style;
});
});
} catch (e) {
console.error(`Error parsing stylesheet: "${stylesheet}"`, e);
}
return response;
};
export const convertElementStyle = (
styleAttr: string,
tag: string
): HtmlStyle | undefined => {
try {
const parsed = cssParse(`${tag} { ${styleAttr} }`) as StyleSheet;
const rules = parsed.children.filter(
(rule) => rule.type === 'Rule' && rule.prelude?.type === 'SelectorList'
) as List<Rule>;
const firstRule = rules?.first();
return firstRule ? convertRule(firstRule.block, tag) : undefined;
} catch (e) {
console.error(
`Error parsing style attribute "${styleAttr}" for tag: ${tag}`,
e
);
}
};
export const convertNode = (node: HTMLNode): HtmlElement | string => {
if (node.nodeType === NodeType.TEXT_NODE) {
return (node as TextNode).rawText;
}
if (node.nodeType === NodeType.COMMENT_NODE) {
return '';
}
if (node.nodeType !== NodeType.ELEMENT_NODE) {
throw new Error('Not sure what this is');
}
const html = node as HTMLElement;
const content = html.childNodes.map(convertNode);
const kindCounters: Record<string, number> = {};
content.forEach((child) => {
if (typeof child !== 'string') {
child.indexOfType =
child.tag in kindCounters
? (kindCounters[child.tag] = kindCounters[child.tag] + 1)
: (kindCounters[child.tag] = 0);
}
});
let style: HtmlStyle | undefined;
if (html.attributes.style && html.attributes.style.trim()) {
style = convertElementStyle(html.attributes.style, html.tagName);
}
return Object.assign(html, {
tag: (html.tagName || '').toLowerCase() as Tag | string,
style: style ? [style] : [],
content,
indexOfType: 0,
}) as HtmlElement;
};
const parseHtml = (
text: string
): { stylesheets: HtmlStyles[]; rootElement: HtmlElement } => {
const html = parse(text, { comment: false });
const stylesheets = html
.querySelectorAll('style')
.map((styleNode) =>
styleNode.childNodes.map((textNode) => textNode.rawText.trim()).join('\n')
)
.filter((styleText) => !!styleText)
.map(convertStylesheet);
return {
stylesheets,
rootElement: convertNode(html) as HtmlElement,
};
};
export default parseHtml;