-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathstudio-widget.ts
More file actions
333 lines (287 loc) · 9.67 KB
/
studio-widget.ts
File metadata and controls
333 lines (287 loc) · 9.67 KB
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
import { env } from '$env/dynamic/public';
import { app } from '$lib/stores/app';
import { get } from 'svelte/store';
import { goto } from '$app/navigation';
import { resolve } from '$app/paths';
import { ensureMonacoStyles } from './monaco-style-manager';
import DEV_CSS_URL from '@imagine.dev/web-components/imagine-web-components.css?url';
const COMPONENT_SELECTOR = 'imagine-web-components-wrapper[data-appwrite-studio]';
const STYLE_ATTRIBUTE = 'data-appwrite-studio-style';
const BLOCK_START_BASE_OFFSET = 48;
const INLINE_START_BASE_OFFSET = 8;
export const CDN_URL = env?.PUBLIC_IMAGINE_CDN_URL + '/web-components.js';
export const CDN_CSS_URL = env?.PUBLIC_IMAGINE_CDN_URL + '/web-components.css';
const DEV_OVERRIDE_WEB_COMPONENTS = env?.PUBLIC_AI_OVERRIDE_WEB_COMPONENTS === 'true';
let component: HTMLElement | null = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let webComponentsModule: Record<string, any> | null = null;
let configInitialized = false;
let routingInitialized = false;
let lastRouteKey: string | null = null;
let scrollLocked = false;
let previousBodyOverflow: string | null = null;
let previousDocumentOverflow: string | null = null;
function hasDocument(): boolean {
return typeof document !== 'undefined';
}
function disableBodyScroll() {
if (!hasDocument() || scrollLocked) {
return;
}
const { body, documentElement } = document;
previousBodyOverflow = body.style.overflow || '';
previousDocumentOverflow = documentElement.style.overflow || '';
body.style.overflow = 'hidden';
documentElement.style.overflow = 'hidden';
scrollLocked = true;
}
function restoreBodyScroll() {
if (!hasDocument() || !scrollLocked) {
return;
}
const { body, documentElement } = document;
body.style.overflow = previousBodyOverflow ?? '';
documentElement.style.overflow = previousDocumentOverflow ?? '';
previousBodyOverflow = null;
previousDocumentOverflow = null;
scrollLocked = false;
}
function ensureBaseStyles(node: HTMLElement) {
node.style.background = 'var(--bgcolor-neutral-primary)';
node.style.position = 'fixed';
node.style.height = `calc(100vh - ${BLOCK_START_BASE_OFFSET}px)`;
node.style.maxHeight = `calc(100vh - ${BLOCK_START_BASE_OFFSET}px)`;
if (!node.style.display) {
node.style.display = 'none';
}
if (!node.style.pointerEvents) {
node.style.pointerEvents = 'none';
}
}
function injectStyles(node: HTMLElement, attempt = 0) {
if (typeof customElements === 'undefined') {
return;
}
customElements
.whenDefined('imagine-web-components-wrapper')
.then(async () => {
const shadow = node.shadowRoot;
if (!shadow) {
if (attempt < 5 && typeof requestAnimationFrame !== 'undefined') {
requestAnimationFrame(() => injectStyles(node, attempt + 1));
}
return;
}
if (shadow.querySelector<HTMLLinkElement>(`link[${STYLE_ATTRIBUTE}]`)) {
ensureMonacoStyles(shadow);
return;
}
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = DEV_OVERRIDE_WEB_COMPONENTS ? DEV_CSS_URL : CDN_CSS_URL;
link.setAttribute(STYLE_ATTRIBUTE, 'true');
shadow.prepend(link);
ensureMonacoStyles(shadow);
})
.catch(() => {
/* no-op */
});
}
/**
* Get the web components module, loading it from CDN if necessary
*/
export async function getWebComponents() {
if (!webComponentsModule) {
if (DEV_OVERRIDE_WEB_COMPONENTS) {
webComponentsModule = await import('@imagine.dev/web-components/web-components');
} else {
webComponentsModule = await import(/* @vite-ignore */ CDN_URL);
}
}
return webComponentsModule;
}
/**
* Navigate to a route in the web components
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function navigateToRoute(...args: any[]) {
try {
const { navigateToRoute: navigate } = await getWebComponents();
return navigate(...args);
} catch (error) {
console.error('Failed to navigate:', error);
}
}
export function ensureStudioComponent(): HTMLElement | null {
if (!hasDocument()) {
return component;
}
if (component?.isConnected) {
ensureBaseStyles(component);
injectStyles(component);
return component;
}
const existing = document.querySelector<HTMLElement>(COMPONENT_SELECTOR);
if (existing) {
component = existing;
ensureBaseStyles(existing);
injectStyles(existing);
return existing;
}
if (component) {
component.dataset.appwriteStudio = 'true';
ensureBaseStyles(component);
document.body.appendChild(component);
injectStyles(component);
return component;
}
const created = document.createElement('imagine-web-components-wrapper');
created.addEventListener('click', (event) => {
event.stopPropagation();
});
created.dataset.appwriteStudio = 'true';
ensureBaseStyles(created);
document.body.appendChild(created);
component = created;
injectStyles(created);
return created;
}
export function getComponent(): HTMLElement | null {
return component;
}
export interface AttachOptions {
offsetX?: number;
offsetY?: number;
}
let anchorElement: HTMLElement | null = null;
let currentOptions: Required<AttachOptions> = {
offsetX: 0,
offsetY: 0
};
let scrollHandler: (() => void) | null = null;
const resizeObserver = new ResizeObserver(updatePosition);
function updatePosition() {
if (!component || !anchorElement) {
return;
}
const rect = anchorElement.getBoundingClientRect();
const { offsetX, offsetY } = currentOptions;
const left = rect.left + offsetX;
const top = BLOCK_START_BASE_OFFSET + offsetY;
component.style.width = `${rect.width}px`;
component.style.height = `calc(100vh - ${BLOCK_START_BASE_OFFSET}px)`;
component.style.paddingInlineStart = `${INLINE_START_BASE_OFFSET}px`;
component.style.left = `${left}px`;
component.style.top = `${top}px`;
}
function teardownAnchorWatchers() {
if (anchorElement) resizeObserver.unobserve(anchorElement);
resizeObserver.disconnect();
if (scrollHandler && hasDocument()) {
window.removeEventListener('scroll', scrollHandler, true);
window.removeEventListener('resize', scrollHandler);
}
scrollHandler = null;
}
function setupAnchorWatchers() {
teardownAnchorWatchers();
if (!anchorElement || !hasDocument()) {
return;
}
resizeObserver.observe(anchorElement);
scrollHandler = () => {
if (anchorElement && !anchorElement.isConnected) {
hideStudio();
return;
}
updatePosition();
};
window.addEventListener('scroll', scrollHandler, true);
window.addEventListener('resize', scrollHandler);
}
export function attachStudioTo(target: HTMLElement, options: AttachOptions = {}) {
const node = ensureStudioComponent();
if (!node) {
return;
}
anchorElement = target;
currentOptions = {
offsetX: options.offsetX ?? 0,
offsetY: options.offsetY ?? BLOCK_START_BASE_OFFSET
};
Object.assign(node.style, {
display: 'block',
pointerEvents: 'auto'
});
disableBodyScroll();
updatePosition();
setupAnchorWatchers();
}
export function hideStudio() {
if (!component) {
return;
}
teardownAnchorWatchers();
anchorElement = null;
component.style.display = 'none';
component.style.pointerEvents = 'none';
component.style.width = '';
restoreBodyScroll();
}
export async function initImagine(
region: string,
projectId: string,
callbacks?: {
onProjectNameChange: () => void;
onAddDomain: () => void | Promise<void>;
onManageDomains: (primaryDomain?: string) => void | Promise<void>;
}
) {
try {
const { initImagineConfig, initImagineRouting } = await getWebComponents();
if (!configInitialized) {
initImagineConfig(
{
AI_SERVICE_ENDPOINT: env.PUBLIC_AI_SERVICE_BASE_URL,
APPWRITE_ENDPOINT: env.PUBLIC_APPWRITE_ENDPOINT,
APPWRITE_SITES_BASE_URL: ''
},
{
initialTheme: get(app).themeInUse,
callbacks
}
);
configInitialized = true;
}
const routeKey = region && projectId ? `project:${region}:${projectId}` : 'home';
if (routingInitialized && routeKey === lastRouteKey) {
return;
}
initImagineRouting({
initialRoute:
region && projectId
? {
id: 'project',
props: { region, projectId }
}
: {
id: 'home',
props: {}
},
onNavigate(route) {
if (route.id === 'project') {
goto(
resolve('/(console)/project-[region]-[project]/(studio)/studio', {
region: route.props.region,
project: route.props.projectId
})
);
}
}
});
routingInitialized = true;
lastRouteKey = routeKey;
} catch (error) {
console.error('Failed to load web components library:', error);
}
}