-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
66 lines (55 loc) · 2.54 KB
/
index.ts
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
import { LitElement, PropertyValues, TemplateResult } from "lit";
import { html } from "lit/static-html.js";
import { unsafeHTML } from "lit/directives/unsafe-html.js";
import { property, state, customElement } from "lit/decorators.js";
export type Version = "published" | "preview";
export type PlasmicLoadedEvent = "loaded";
@customElement("plasmic-component")
export class PlasmicComponent extends LitElement {
@property({ type: String }) projectId!: string;
@property({ type: String }) publicApiToken!: string;
@property({ type: String }) name!: string;
@property({ type: String }) version: Version = "published";
@property({ type: Boolean }) hydrate = true;
@property({ type: Boolean }) embedHydrate = true;
@property({ type: Object }) componentProps: any | null = null;
@property({ type: Array }) globalVariants: ArrayLike<any> | null = null;
@state() fetchedHtml: string | null = null;
render(): TemplateResult {
return html`${this.fetchedHtml ? unsafeHTML(this.fetchedHtml) : ""}`;
}
public refetchComponent(): void {
if (!this.projectId) {
console.error(`Property projectId is not set in plasmic-component with name '${this.name}'`);
return;
}
if (!this.publicApiToken) {
console.error(`Property publicApiToken is not set in plasmic-component with name '${this.name}'`);
return;
}
if (!this.name) {
console.error(`Property name is not set in plasmic-component`);
return;
}
let url = "https://codegen.plasmic.app/api/v1/loader/html";
url += `/${this.version}/${this.projectId}/${this.name}`;
url += `?hydrate=${this.hydrate ? 1 : 0}&embedHydrate=${this.embedHydrate ? 1 : 0}`;
if (this.componentProps) url += `&componentProps=${JSON.stringify(this.componentProps)}`;
if (this.globalVariants) url += `&globalVariants=${JSON.stringify(this.globalVariants)}`;
fetch(url, {
headers: { "x-plasmic-api-project-tokens": this.publicApiToken },
}).then(res => res.json()).then(result => {
this.fetchedHtml = result.html;
}).catch(e => console.error(`Request to plasmic api fetching '${this.name}' component has failed`, e));
}
protected firstUpdated(_changedProperties: PropertyValues) {
super.firstUpdated(_changedProperties);
this.refetchComponent();
}
protected updated(_changedProperties: PropertyValues) {
super.updated(_changedProperties);
if (_changedProperties.has("fetchedHtml") && this.fetchedHtml)
this.dispatchEvent(new CustomEvent("loaded" as PlasmicLoadedEvent,
{ composed: true, bubbles: true }));
}
}