forked from callstack/linaria
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument.js
More file actions
83 lines (69 loc) · 1.71 KB
/
Copy pathdocument.js
File metadata and controls
83 lines (69 loc) · 1.71 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
/**
* It's annoying we have to write this, but document.styleSheets returns an empty array in JSDOM, so we cannot use it
*
* @flow
*/
import CSSOM from 'cssom'; // eslint-disable-line import/no-extraneous-dependencies
class Text {
constructor(text: string) {
this.textContent = text;
this.nodeName = '#text';
}
textContent: string;
parentNode: any;
nodeName: string;
appendData(t: string) {
if (this.parentNode instanceof HTMLStyleElement) {
const ast = CSSOM.parse(t);
this.parentNode.__ast.cssRules.push(...ast.cssRules);
}
this.textContent += t;
}
}
class HTMLElement {
constructor(tag: string) {
this.tagName = tag.toUpperCase();
this.nodeName = tag.toUpperCase();
this.children = [];
this.attributes = {};
}
tagName: string;
nodeName: string;
children: any;
attributes: Object;
get textContent(): string {
return this.children.map(c => c.textContent).join('');
}
appendChild(el: *) {
el.parentNode = this; // eslint-disable-line no-param-reassign
this.children.push(el);
}
setAttribute(name: string, value: string) {
this.attributes[name] = value;
}
}
class HTMLStyleElement extends HTMLElement {
constructor(tag: string) {
super(tag);
this.__ast = CSSOM.parse('');
}
__ast: Object;
}
const document = {
createElement(tag: string) {
if (tag === 'style') {
return new HTMLStyleElement(tag);
}
return new HTMLElement(tag);
},
createTextNode(text: string) {
return new Text(text);
},
get styleSheets() {
return this.head.children
.filter(el => el instanceof HTMLStyleElement)
.map(el => el.__ast);
},
head: new HTMLElement('head'),
};
export default document;