generated from daviddarnes/component-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
link-peek.js
76 lines (61 loc) · 1.67 KB
/
link-peek.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
class LinkPeek extends HTMLElement {
static register(tagName) {
if ("customElements" in window) {
customElements.define(tagName || "link-peek", LinkPeek);
}
}
async connectedCallback() {
this.append(this.template);
const data = { ...(await this.data), link: this.link };
this.slots.forEach((slot) => {
slot.dataset.key.split(",").forEach((keyItem) => {
const value = this.getValue(keyItem, data);
this.populateSlot(slot, value);
});
});
}
populateSlot(slot, value) {
if (typeof value == "string" && value.startsWith("http")) {
if (slot.localName === "img") slot.src = value;
if (slot.localName === "a") slot.href = value;
} else {
slot.textContent = value;
}
}
handleKey(object, key) {
const parsedKeyInt = parseFloat(key);
if (Number.isNaN(parsedKeyInt)) {
return object[key];
}
return object[parsedKeyInt];
}
getValue(string, data) {
let keys = string.trim().split(/\.|\[|\]/g);
keys = keys.filter((string) => string.length);
const value = keys.reduce(
(object, key) => this.handleKey(object, key),
data
);
return value;
}
get template() {
return document
.getElementById(
this.getAttribute("template") || `${this.localName}-template`
)
.content.cloneNode(true);
}
get slots() {
return this.querySelectorAll("[data-key]");
}
get link() {
return this.querySelector("a").href;
}
get endpoint() {
return this.getAttribute("api").replace("${link}", this.link);
}
get data() {
return fetch(this.endpoint).then((response) => response.json());
}
}
LinkPeek.register();