@reviewboostr/boostrjs
Version:
The ReviewBoostr widget for websites.
88 lines (80 loc) • 2.89 kB
JavaScript
import { ratingTemplate } from "./ratingTemplate";
import { reviewTemplate } from "./reviewTemplate";
import { thanksTemplate } from "./thanksTemplate";
class Boostr extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
async connectedCallback() {
const { data, error } = await this.post({ id: this.id, name: "Widget", method: "createEvent" });
if (error !== undefined) {
console.error(error);
return;
}
this.createRatingTemplate(data);
}
createRatingTemplate(data) {
this.shadowRoot.appendChild(ratingTemplate.content.cloneNode(true));
this.shadowRoot.getElementById("websiteName").innerHTML = data.websiteName;
this.shadowRoot.getElementById("close").onclick = () => this.toggle();
this.shadowRoot.getElementById("ratings").onchange = async event => {
this.createReviewTemplate(data, event);
if (event.isTrusted === true) {
const { error } = await this.post(
{ id: this.id, name: "Widget", method: "createEvent" },
{ rating: Number(event.target.value) }
);
if (error !== undefined) {
console.error(error);
// return;
}
}
};
}
createReviewTemplate(data, event) {
this.shadowRoot.innerHTML = "";
if (Number(event.target.value) === 5) {
this.shadowRoot.appendChild(reviewTemplate.content.cloneNode(true));
this.shadowRoot.getElementById("reviewWebsiteName").innerHTML = data.reviewWebsiteName;
this.shadowRoot.getElementById("reviewWebsite").href = data.reviewWebsite;
this.shadowRoot.getElementById("close").onclick = () => this.toggle();
this.shadowRoot.getElementById("reviewWebsite").onclick = async () => {
this.shadowRoot.innerHTML = "";
this.shadowRoot.appendChild(thanksTemplate.content.cloneNode(true));
this.shadowRoot.getElementById("close").onclick = () => this.toggle();
const { error } = await this.post({ id: this.id, name: "Widget", method: "createEvent" }, { outbound: true });
if (error !== undefined) {
console.error(error);
// return;
}
};
} else {
this.shadowRoot.appendChild(thanksTemplate.content.cloneNode(true));
this.shadowRoot.getElementById("close").onclick = () => this.toggle();
}
}
toggle() {
this.classList.toggle("closed");
}
async post({ id, name, method }, data) {
const response = await fetch("API_URL", {
method: "POST",
mode: "cors",
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify({
object: {
id,
name,
method
},
data
})
});
return await response.json();
}
}
customElements.define("review-boostr", Boostr);