-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
97 lines (96 loc) · 2.44 KB
/
index.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
// node_modules/@vanillaes/interpolate/index.js
function interpolate(template, tags = {}) {
const keys = Object.keys(tags);
const values = Object.values(tags);
try {
return new Function(...keys, `return \`${template}\`;`)(...values);
} catch (e) {
throw new TemplateException(template, tags, e);
}
}
var TemplateException = class extends Error {
constructor(template, tags, message) {
super();
this.name = "TemplateError";
let msg = "\n------------------\n";
msg += `Template: \`${template}\``;
msg += "\n------------------\n";
msg += `Tags: ${JSON.stringify(tags, null, 2)}`;
msg += "\n------------------\n";
msg += message;
this.message = msg;
}
};
// src/wc-template.js
var WCTemplate = class extends HTMLElement {
static get observedAttributes() {
return ["src", "context"];
}
attributeChangedCallback(name, oldValue, newValue) {
if (!this.__initialized) {
return;
}
if (oldValue !== newValue) {
this[name] = newValue;
}
}
get src() {
return this.getAttribute("src");
}
set src(value) {
this.setAttribute("src", value);
this.setSrc();
this.render();
}
get context() {
return this.getAttribute("context");
}
set context(value) {
this.setAttribute("context", value);
this.setContext();
this.render();
}
constructor() {
super();
this.__initialized = false;
this.__template = "";
this.__context = {};
}
async connectedCallback() {
if (this.hasAttribute("src")) {
await this.setSrc();
}
if (this.hasAttribute("context")) {
await this.setContext();
}
this.render();
this.__initialized = true;
}
async setSrc() {
const path = this.getAttribute("src");
this.__template = await this.fetchSrc(path);
}
async fetchSrc(src) {
const response = await fetch(src);
if (response.status !== 200)
throw Error(`ERR ${response.status}: ${response.statusText}`);
return response.text();
}
async setContext() {
const path = this.getAttribute("context");
this.__context = await this.fetchContext(path);
}
async fetchContext(src) {
const response = await fetch(src);
if (response.status !== 200)
throw Error(`ERR ${response.status}: ${response.statusText}`);
return response.json();
}
render() {
this.innerHTML = interpolate(this.__template, this.__context);
}
};
customElements.define("wc-template", WCTemplate);
export {
WCTemplate
};