-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpalladio-webcomponent-base.js
200 lines (174 loc) · 5.42 KB
/
palladio-webcomponent-base.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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
const throttle = (fn, wait) => {
let previouslyRun;
let queuedToRun;
return function invokeFn(...args) {
const now = Date.now();
queuedToRun = clearTimeout(queuedToRun);
if (!previouslyRun || now - previouslyRun >= wait) {
fn(...args);
previouslyRun = now;
} else {
queuedToRun = setTimeout(
invokeFn.bind(null, ...args),
wait - (now - previouslyRun),
);
}
};
};
const baseComponentStyles = `
:host { display: block; overflow: hidden; }
body { height: 100%; width: 100%; margin: 0; }
.error-msg { margin: 0; padding: 1em; color: #d8000c; background-color: #ffbaba; height: 100%; }
`;
class PalladioWebcomponentBase extends HTMLElement {
constructor() {
super();
if (new.target === PalladioWebcomponentBase) {
throw new TypeError(
`Cannot construct ${new.target.name} instances directly`,
);
}
this.attachShadow({ mode: "open" });
this.addEventListener("dataLoaded", this.onDataLoaded);
}
static get observedAttributes() {
return ["height", "width", "project-url"];
}
connectedCallback() {
if (this.visType === undefined) {
throw new TypeError(
"visType must be defined on classes derived from PalladioWebcomponentBase",
);
}
const { shadowRoot } = this;
shadowRoot.innerHTML = "";
this.body = document.createElement("body");
shadowRoot.appendChild(this.body);
const style = document.createElement("style");
shadowRoot.appendChild(style);
style.textContent = baseComponentStyles;
if (this.externalStylesheets) {
const stylesheetLink = document
.createRange()
.createContextualFragment(
`${this.externalStylesheets
.map(
(stylesheetUrl) =>
`<link rel="stylesheet" type="text/css" href="${stylesheetUrl}">`,
)
.join("\n")}`,
);
shadowRoot.appendChild(stylesheetLink);
}
if (this.inlineStylesheets) {
const styleTag = document.createElement("style");
styleTag.textContent = this.inlineStylesheets.join("\n\n");
this.shadowRoot.appendChild(styleTag);
}
// ResizeObserver was only rolled out in Safari and Safari/Chrome on iOS in
// March 2020, so probably needs to be polyfilled for the time being if
// the behaviour is considered important.
if (window.ResizeObserver && this.onResize) {
this.resizeObserver = new ResizeObserver(
throttle(this.onResize.bind(this), 250),
);
this.resizeObserver.observe(this);
}
if (!this.projectUrl) {
this.renderError('A "<code>project-url</code>" attribute is required!');
}
}
disconnectedCallback() {
if (this.resizeObserver) this.resizeObserver.disconnect();
this.removeEventListener("dataLoaded", this.onDataLoaded);
}
attributeChangedCallback(attrName, oldValue, newValue) {
if (attrName === "project-url" && newValue !== null) {
this.getDataFromUrl().then((data) => this.parseData(data));
}
if (["height", "width"].indexOf(attrName) !== -1) {
this.style[attrName] = newValue;
}
}
get projectUrl() {
return this.getAttribute("project-url");
}
set projectUrl(value) {
this.setAttribute("project-url", value);
}
getDataFromUrl() {
return fetch(this.projectUrl)
.then((response) => {
if (!response.ok) {
this.renderError(`
<pre>Error retrieving:\n\t${response.url}\n${response.status}: ${response.statusText}</pre>
`);
// eslint-disable-next-line no-console
console.error("response", response);
throw new Error();
}
return response.json();
})
.catch(() => {
throw new Error("Unable to retrieve project JSON.");
});
}
static getSettings(data, visType) {
try {
return data.vis.find((vis) => vis.type === visType).importJson;
} catch (e) {
return false;
}
}
static getFields(data) {
// TODO: this is going to need to be able to handle multiple files in a project.
try {
return data.files[0].fields;
} catch (e) {
return false;
}
}
static getRows(data) {
// TODO: this is going to need to be able to handle multiple files in a project.
try {
return data.files[0].data;
} catch (e) {
return false;
}
}
renderError(error) {
this.body.innerHTML = "";
const errorMessage = document.createElement("p");
errorMessage.classList.add("error-msg");
errorMessage.innerHTML = error;
this.body.appendChild(errorMessage);
}
parseData(data) {
if (!data || typeof data === "undefined") {
this.renderError("No Data!");
}
const rows = this.constructor.getRows(data);
if (!rows) {
this.renderError(`
<details>
<summary>Malformed project data!</summary>
<pre>${JSON.stringify(data, null, 2)}</pre>
</details>
`);
throw new Error("Malformed project data!");
}
const settings = this.constructor.getSettings(data, this.visType);
if (!settings) {
this.renderError(`
<details>
<summary>Visualization type "${this.visType}" not available!</summary>
<pre>${JSON.stringify(data, null, 2)}</pre>
</details>
`);
throw new Error("Visualization settings not available!");
}
Object.assign(this, { rows, settings });
this.dispatchEvent(new Event("dataLoaded"));
}
}
export default PalladioWebcomponentBase;