-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
profile-browser.ts
422 lines (363 loc) · 10.7 KB
/
profile-browser.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
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import { property, state, query, customElement } from "lit/decorators.js";
import { msg, localized, str } from "@lit/localize";
import type { AuthState } from "@/utils/AuthService";
import LiteElement, { html } from "@/utils/LiteElement";
import { type PropertyValues } from "lit";
const POLL_INTERVAL_SECONDS = 2;
const hiddenClassList = ["translate-x-2/3", "opacity-0", "pointer-events-none"];
/**
* View embedded profile browser
*
* Usage example:
* ```ts
* <btrix-profile-browser
* authState=${authState}
* orgId=${orgId}
* browserId=${browserId}
* initialNavigateUrl=${initialNavigateUrl}
* origins=${origins}
* ></btrix-profile-browser>
* ```
*
* @event load Event on iframe load, with src URL
*/
@localized()
@customElement("btrix-profile-browser")
export class ProfileBrowser extends LiteElement {
@property({ type: Object })
authState!: AuthState;
@property({ type: String })
orgId!: string;
@property({ type: String })
browserId?: string;
@property({ type: String })
initialNavigateUrl?: string;
@property({ type: Array })
origins?: string[];
@state()
private iframeSrc?: string;
@state()
private isIframeLoaded = false;
@state()
private hasFetchError = false;
@state()
private isFullscreen = false;
@state()
private showOriginSidebar = false;
@state()
private newOrigins?: string[] = [];
@query("#profileBrowserSidebar")
private readonly sidebar?: HTMLElement;
@query("#iframeWrapper")
private readonly iframeWrapper?: HTMLElement;
@query("iframe")
private readonly iframe?: HTMLIFrameElement;
private pollTimerId?: number;
connectedCallback() {
super.connectedCallback();
document.addEventListener("fullscreenchange", this.onFullscreenChange);
}
disconnectedCallback() {
window.clearTimeout(this.pollTimerId);
document.removeEventListener("fullscreenchange", this.onFullscreenChange);
}
willUpdate(changedProperties: PropertyValues<this> & Map<string, unknown>) {
if (changedProperties.has("browserId")) {
if (this.browserId) {
window.clearTimeout(this.pollTimerId);
void this.fetchBrowser();
} else if (changedProperties.get("browserId")) {
this.iframeSrc = undefined;
this.isIframeLoaded = false;
window.clearTimeout(this.pollTimerId);
}
}
if (
changedProperties.has("showOriginSidebar") &&
changedProperties.get("showOriginSidebar") !== undefined
) {
this.animateSidebar();
}
}
private animateSidebar() {
if (!this.sidebar) return;
if (this.showOriginSidebar) {
this.sidebar.classList.remove(...hiddenClassList);
} else {
this.sidebar.classList.add(...hiddenClassList);
}
}
render() {
return html`
<div id="interactive-browser" class="flex h-full w-full flex-col">
${this.renderControlBar()}
<div
id="iframeWrapper"
class="${this.isFullscreen
? "w-screen h-screen"
: "border-t"} relative flex-1 overflow-hidden bg-neutral-50"
aria-live="polite"
>
${this.renderBrowser()}
<div
id="profileBrowserSidebar"
class="${hiddenClassList.join(
" ",
)} bottom-0 right-0 top-0 flex transition-all duration-300 ease-out lg:absolute lg:w-80 lg:p-3"
>
<div
class="flex-1 overflow-auto rounded-lg border bg-white shadow-lg"
>
${this.renderOrigins()} ${this.renderNewOrigins()}
</div>
</div>
</div>
</div>
`;
}
private renderControlBar() {
if (this.isFullscreen) {
return html`
<div
class="fixed left-1/2 top-2 z-50 flex -translate-x-1/2 items-center rounded-lg bg-white text-base shadow"
>
${this.renderSidebarButton()}
<sl-icon-button
name="fullscreen-exit"
label=${msg("Exit fullscreen")}
@click=${() => void document.exitFullscreen()}
></sl-icon-button>
</div>
`;
}
return html`
<div class="p-1 text-right text-base">
${this.renderSidebarButton()}
<sl-icon-button
name="arrows-fullscreen"
label=${msg("Enter fullscreen")}
@click=${() => void this.enterFullscreen("interactive-browser")}
></sl-icon-button>
</div>
`;
}
private renderBrowser() {
if (this.hasFetchError) {
return html`
<btrix-alert variant="danger">
${msg(`The interactive browser is not available.`)}
</btrix-alert>
`;
}
if (this.iframeSrc) {
return html`<iframe
class="h-full w-full"
title=${msg("Interactive browser for creating browser profile")}
src=${this.iframeSrc}
@load=${this.onIframeLoad}
></iframe>`;
}
if (this.browserId && !this.isIframeLoaded) {
return html`
<div class="flex h-full w-full items-center justify-center text-3xl">
<sl-spinner></sl-spinner>
</div>
`;
}
return "";
}
private renderSidebarButton() {
return html`
<sl-icon-button
name="layout-sidebar-reverse"
label=${!this.showOriginSidebar
? msg("Show sidebar")
: msg("Hide sidebar")}
class="${this.showOriginSidebar ? "text-blue-600" : ""}"
@click=${() => (this.showOriginSidebar = !this.showOriginSidebar)}
></sl-icon-button>
`;
}
private renderOrigins() {
return html`
<h4 class="border-b p-2 text-xs leading-tight text-neutral-500">
<span class="inline-block align-middle">${msg("Visited Sites")}</span>
<sl-tooltip content=${msg("Websites in the browser profile")}
><sl-icon
class="inline-block align-middle"
name="info-circle"
></sl-icon
></sl-tooltip>
</h4>
<ul>
${this.origins?.map((url) => this.renderOriginItem(url))}
</ul>
`;
}
private renderNewOrigins() {
if (!this.newOrigins?.length) return;
return html`
<h4 class="border-b p-2 text-xs leading-tight text-neutral-500">
<span class="inline-block align-middle">${msg("New Sites")}</span>
<sl-tooltip
content=${msg(
"Websites that are not in the browser profile yet. Finish editing and save to add these websites to the profile.",
)}
><sl-icon
class="inline-block align-middle"
name="info-circle"
></sl-icon
></sl-tooltip>
</h4>
<ul>
${this.newOrigins.map((url) => this.renderOriginItem(url))}
</ul>
`;
}
private renderOriginItem(url: string) {
return html`<li
class="border-t-neutral-100${this.iframeSrc
? " hover:bg-slate-50 hover:text-primary"
: ""} flex items-center justify-between border-t p-2 first:border-t-0"
role=${this.iframeSrc ? "button" : "listitem"}
title=${msg(str`Go to ${url}`)}
@click=${() => (this.iframeSrc ? this.navigateBrowser({ url }) : {})}
>
<div class="w-full truncate text-sm">${url}</div>
${this.iframeSrc
? html`<sl-icon name="play-btn" class="text-xl"></sl-icon>`
: ""}
</li>`;
}
/**
* Fetch browser profile and update internal state
*/
private async fetchBrowser(): Promise<void> {
await this.updateComplete;
this.iframeSrc = undefined;
this.isIframeLoaded = false;
try {
await this.checkBrowserStatus();
} catch (e) {
this.hasFetchError = true;
this.notify({
message: msg("Sorry, couldn't create browser profile at this time."),
variant: "danger",
icon: "exclamation-octagon",
});
}
}
/**
* Check whether temporary browser is up
**/
private async checkBrowserStatus() {
const result = await this.getBrowser();
if (result.detail === "waiting_for_browser") {
this.pollTimerId = window.setTimeout(
() => void this.checkBrowserStatus(),
POLL_INTERVAL_SECONDS * 1000,
);
return;
} else if (result.url) {
// check that the browser is actually available
// if not, continue waiting
// (will not work with local frontend due to CORS)
try {
const resp = await fetch(result.url, { method: "HEAD" });
if (!resp.ok) {
return;
}
} catch (e) {
// ignore
}
if (this.initialNavigateUrl) {
await this.navigateBrowser({ url: this.initialNavigateUrl });
}
this.iframeSrc = result.url;
await this.updateComplete;
this.dispatchEvent(new CustomEvent("load", { detail: result.url }));
void this.pingBrowser();
} else {
console.debug("Unknown checkBrowserStatus state");
}
}
private async getBrowser() {
const data = await this.apiFetch<{
detail?: string;
url?: string;
}>(
`/orgs/${this.orgId}/profiles/browser/${this.browserId}`,
this.authState!,
);
return data;
}
/**
* Navigate to URL in temporary browser
**/
private async navigateBrowser({ url }: { url: string }) {
if (!this.iframeSrc) return;
const data = this.apiFetch(
`/orgs/${this.orgId}/profiles/browser/${this.browserId}/navigate`,
this.authState!,
{
method: "POST",
body: JSON.stringify({ url }),
},
);
return data;
}
/**
* Ping temporary browser every minute to keep it alive
**/
private async pingBrowser() {
if (!this.iframeSrc) return;
const data = await this.apiFetch<{ origins?: string[] }>(
`/orgs/${this.orgId}/profiles/browser/${this.browserId}/ping`,
this.authState!,
{
method: "POST",
},
);
if (!this.origins) {
this.origins = data.origins;
} else {
this.newOrigins = data.origins?.filter(
(url: string) => !this.origins?.includes(url),
);
}
this.pollTimerId = window.setTimeout(
() => void this.pingBrowser(),
POLL_INTERVAL_SECONDS * 1000,
);
}
/**
* Enter fullscreen mode
* @param id ID of element to fullscreen
*/
private async enterFullscreen(id: string) {
try {
await document.getElementById(id)!.requestFullscreen({
// Hide browser navigation controls
navigationUI: "hide",
});
} catch (err) {
console.error(err);
}
}
private onIframeLoad() {
this.isIframeLoaded = true;
try {
this.iframe?.contentWindow?.localStorage.setItem("uiTheme", '"default"');
} catch (e) {
/* empty */
}
this.dispatchEvent(new CustomEvent("load", { detail: this.iframeSrc }));
}
private readonly onFullscreenChange = async () => {
if (document.fullscreenElement) {
this.isFullscreen = true;
} else {
this.isFullscreen = false;
}
};
}