forked from webpack/webpack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFakeDocument.js
102 lines (88 loc) · 2.09 KB
/
FakeDocument.js
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
module.exports = class FakeDocument {
constructor() {
this.head = this.createElement("head");
this._elementsByTagName = new Map([["head", [this.head]]]);
}
createElement(type) {
return new FakeElement(this, type);
}
_onElementAttached(element) {
const type = element._type;
let list = this._elementsByTagName.get(type);
if (list === undefined) {
list = [];
this._elementsByTagName.set(type, list);
}
list.push(element);
}
_onElementRemoved(element) {
const type = element._type;
let list = this._elementsByTagName.get(type);
const idx = list.indexOf(element);
list.splice(idx, 1);
}
getElementsByTagName(name) {
return this._elementsByTagName.get(name) || [];
}
};
class FakeElement {
constructor(document, type) {
this._document = document;
this._type = type;
this._children = [];
this._attributes = Object.create(null);
this._src = undefined;
this._href = undefined;
this.parentNode = undefined;
}
appendChild(node) {
this._document._onElementAttached(node);
this._children.push(node);
node.parentNode = this;
}
removeChild(node) {
const idx = this._children.indexOf(node);
if (idx >= 0) {
this._children.splice(idx, 1);
this._document._onElementRemoved(node);
node.parentNode = undefined;
}
}
setAttribute(name, value) {
this._attributes[name] = value;
}
getAttribute(name) {
return this._attributes[name];
}
_toRealUrl(value) {
if (/^\//.test(value)) {
return `https://test.cases${value}`;
} else if (/^\.\.\//.test(value)) {
return `https://test.cases${value.substr(2)}`;
} else if (/^\.\//.test(value)) {
return `https://test.cases/path${value.substr(1)}`;
} else if (/^\w+:\/\//.test(value)) {
return value;
} else if (/^\/\//.test(value)) {
return `https:${value}`;
} else {
return `https://test.cases/path/${value}`;
}
}
set src(value) {
if (this._type === "script") {
this._src = this._toRealUrl(value);
}
}
get src() {
return this._src;
}
set href(value) {
if (this._type === "link") {
this._href = this._toRealUrl(value);
}
}
get href() {
return this._href;
}
}