-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
toolbar.ts
583 lines (507 loc) · 15.3 KB
/
toolbar.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
/* eslint-disable no-console */
import type { DevToolbarApp as DevToolbarAppDefinition } from '../../../@types/astro.js';
import { settings } from './settings.js';
import { type Icon, getIconElement, isDefinedIcon } from './ui-library/icons.js';
export type DevToolbarApp = DevToolbarAppDefinition & {
builtIn: boolean;
active: boolean;
status: 'ready' | 'loading' | 'error';
notification: {
state: boolean;
level?: 'error' | 'warning' | 'info';
};
eventTarget: EventTarget;
};
const WS_EVENT_NAME = 'astro-dev-toolbar';
// TODO: Remove in Astro 5.0
const WS_EVENT_NAME_DEPRECATED = 'astro-dev-overlay';
const HOVER_DELAY = 2 * 1000;
const DEVBAR_HITBOX_ABOVE = 42;
export class AstroDevToolbar extends HTMLElement {
shadowRoot: ShadowRoot;
delayedHideTimeout: number | undefined;
devToolbarContainer: HTMLDivElement | undefined;
apps: DevToolbarApp[] = [];
hasBeenInitialized = false;
// TODO: This should be dynamic based on the screen size or at least configurable, erika - 2023-11-29
customAppsToShow = 3;
constructor() {
super();
this.shadowRoot = this.attachShadow({ mode: 'open' });
}
/**
* All one-time DOM setup runs through here. Only ever call this once,
* in connectedCallback(), and protect it from being called again.
*/
init() {
this.shadowRoot.innerHTML = `
<style>
:host {
/* Important! Reset all inherited styles to initial */
all: initial;
z-index: 999999;
view-transition-name: astro-dev-toolbar;
display: contents;
}
::view-transition-old(astro-dev-toolbar),
::view-transition-new(astro-dev-toolbar) {
animation: none;
}
#dev-toolbar-root {
position: fixed;
bottom: 0px;
left: 50%;
transform: translate(-50%, 0%);
z-index: 2000000010;
display: flex;
flex-direction: column;
align-items: center;
transition: bottom 0.35s cubic-bezier(0.485, -0.050, 0.285, 1.505);
pointer-events: none;
}
#dev-toolbar-root[data-hidden] {
bottom: -40px;
}
#dev-toolbar-root[data-hidden] #dev-bar .item {
opacity: 0.2;
}
#dev-bar-hitbox-above,
#dev-bar-hitbox-below {
width: 100%;
pointer-events: auto;
}
#dev-bar-hitbox-above {
height: ${DEVBAR_HITBOX_ABOVE}px;
}
#dev-bar-hitbox-below {
height: 16px;
}
#dev-bar {
height: 40px;
overflow: hidden;
pointer-events: auto;
background: linear-gradient(180deg, #13151A 0%, rgba(19, 21, 26, 0.88) 100%);
border: 1px solid #343841;
border-radius: 9999px;
box-shadow: 0px 0px 0px 0px rgba(19, 21, 26, 0.30), 0px 1px 2px 0px rgba(19, 21, 26, 0.29), 0px 4px 4px 0px rgba(19, 21, 26, 0.26), 0px 10px 6px 0px rgba(19, 21, 26, 0.15), 0px 17px 7px 0px rgba(19, 21, 26, 0.04), 0px 26px 7px 0px rgba(19, 21, 26, 0.01);
}
@media (forced-colors: active) {
#dev-bar {
background: white;
}
}
#dev-bar .item {
display: flex;
justify-content: center;
align-items: center;
width: 44px;
border: 0;
background: transparent;
color: white;
font-family: system-ui, sans-serif;
font-size: 1rem;
line-height: 1.2;
white-space: nowrap;
text-decoration: none;
padding: 0;
margin: 0;
overflow: hidden;
transition: opacity 0.2s ease-out 0s;
}
#dev-bar #bar-container .item:hover, #dev-bar #bar-container .item:focus-visible {
background: #FFFFFF20;
cursor: pointer;
outline-offset: -3px;
}
#dev-bar #bar-container .item[data-app-error]:hover, #dev-bar #bar-container .item[data-app-error]:focus-visible {
cursor: not-allowed;
background: #ff252520;
}
#dev-bar .item:first-of-type {
border-top-left-radius: 9999px;
border-bottom-left-radius: 9999px;
width: 42px;
padding-left: 4px;
}
#dev-bar .item:last-of-type {
border-top-right-radius: 9999px;
border-bottom-right-radius: 9999px;
width: 42px;
padding-right: 4px;
}
#dev-bar #bar-container .item.active {
background: rgba(71, 78, 94, 1);
}
#dev-bar .item-tooltip {
background: linear-gradient(0deg, #13151A, #13151A), linear-gradient(0deg, #343841, #343841);
border: 1px solid rgba(52, 56, 65, 1);
border-radius: 4px;
padding: 4px 8px;
position: absolute;
top: ${4 - DEVBAR_HITBOX_ABOVE}px;
font-size: 14px;
opacity: 0;
transition: opacity 0.2s ease-in-out 0s;
pointer-events: none;
}
#dev-bar .item-tooltip::after{
content: '';
position: absolute;
left: calc(50% - 5px);
bottom: -6px;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #343841;
}
#dev-bar .item[data-app-error] .icon {
opacity: 0.35;
}
#dev-bar .item:hover .item-tooltip, #dev-bar .item:not(.active):focus-visible .item-tooltip {
transition: opacity 0.2s ease-in-out 200ms;
opacity: 1;
}
@media (forced-colors: active) {
#dev-bar .item:hover .item-tooltip,
#dev-bar .item:not(.active):focus-visible .item-tooltip {
background: white;
}
}
#dev-bar #bar-container .item.active .notification rect, #dev-bar #bar-container .item.active .notification path {
stroke: rgba(71, 78, 94, 1);
}
#dev-bar .item .icon {
position: relative;
max-width: 20px;
max-height: 20px;
user-select: none;
}
#dev-bar .item .icon>svg {
width: 20px;
height: 20px;
display: block;
margin: auto;
}
@media (forced-colors: active) {
#dev-bar .item svg path[fill="#fff"] {
fill: black;
}
}
#dev-bar .item .notification {
display: none;
position: absolute;
top: -4px;
right: -6px;
width: 10px;
height: 10px;
}
#dev-bar .item .notification svg {
display: block;
}
#dev-toolbar-root:not([data-no-notification]) #dev-bar .item .notification[data-active] {
display: block;
}
#dev-bar #bar-container {
height: 100%;
display: flex;
}
#dev-bar .separator {
background: rgba(52, 56, 65, 1);
width: 1px;
}
</style>
<div id="dev-toolbar-root" data-hidden ${
settings.config.disableAppNotification ? 'data-no-notification' : ''
}>
<div id="dev-bar-hitbox-above"></div>
<div id="dev-bar">
<div id="bar-container">
${this.apps
.filter((app) => app.builtIn && !['astro:settings', 'astro:more'].includes(app.id))
.map((app) => this.getAppTemplate(app))
.join('')}
${
this.apps.filter((app) => !app.builtIn).length > 0
? `<div class="separator"></div>${this.apps
.filter((app) => !app.builtIn)
.slice(0, this.customAppsToShow)
.map((app) => this.getAppTemplate(app))
.join('')}`
: ''
}
${
this.apps.filter((app) => !app.builtIn).length > this.customAppsToShow
? this.getAppTemplate(
this.apps.find((app) => app.builtIn && app.id === 'astro:more')!
)
: ''
}
<div class="separator"></div>
${this.getAppTemplate(this.apps.find((app) => app.builtIn && app.id === 'astro:settings')!)}
</div>
</div>
<div id="dev-bar-hitbox-below"></div>
</div>`;
this.devToolbarContainer = this.shadowRoot.querySelector<HTMLDivElement>('#dev-toolbar-root')!;
this.attachEvents();
// Create app canvases
this.apps.forEach(async (app) => {
settings.logger.verboseLog(`Creating app canvas for ${app.id}`);
const appCanvas = document.createElement('astro-dev-toolbar-app-canvas');
appCanvas.dataset.appId = app.id;
this.shadowRoot?.append(appCanvas);
});
// Init app lazily, so that the page can load faster.
// Fallback to setTimeout for Safari (sad!)
if ('requestIdleCallback' in window) {
window.requestIdleCallback(
async () => {
this.apps.map((app) => this.initApp(app));
},
{ timeout: 300 }
);
} else {
setTimeout(async () => {
this.apps.map((app) => this.initApp(app));
}, 300);
}
}
// This is called whenever the component is connected to the DOM.
// This happens on first page load, and on each page change when
// view transitions are used.
connectedCallback() {
if (!this.hasBeenInitialized) {
this.init();
this.hasBeenInitialized = true;
}
// Run this every time to make sure the correct app is open.
this.apps.forEach(async (app) => {
await this.setAppStatus(app, app.active);
});
}
attachEvents() {
const items = this.shadowRoot.querySelectorAll<HTMLDivElement>('.item');
items.forEach((item) => {
item.addEventListener('click', async (event) => {
const target = event.currentTarget;
if (!target || !(target instanceof HTMLElement)) return;
const id = target.dataset.appId;
if (!id) return;
const app = this.getAppById(id);
if (!app) return;
event.stopPropagation();
await this.toggleAppStatus(app);
});
});
(['mouseenter', 'focusin'] as const).forEach((event) => {
this.devToolbarContainer!.addEventListener(event, () => {
this.clearDelayedHide();
if (this.isHidden()) {
this.setToolbarVisible(true);
}
});
});
(['mouseleave', 'focusout'] as const).forEach((event) => {
this.devToolbarContainer!.addEventListener(event, () => {
this.clearDelayedHide();
if (this.getActiveApp() || this.isHidden()) {
return;
}
this.triggerDelayedHide();
});
});
document.addEventListener('keyup', (event) => {
if (event.key !== 'Escape') return;
if (this.isHidden()) return;
const activeApp = this.getActiveApp();
if (activeApp) {
this.toggleAppStatus(activeApp);
} else {
this.setToolbarVisible(false);
}
});
}
async initApp(app: DevToolbarApp) {
const shadowRoot = this.getAppCanvasById(app.id)!.shadowRoot!;
app.status = 'loading';
try {
settings.logger.verboseLog(`Initializing app ${app.id}`);
await app.init?.(shadowRoot, app.eventTarget);
app.status = 'ready';
if (import.meta.hot) {
import.meta.hot.send(`${WS_EVENT_NAME}:${app.id}:initialized`);
// TODO: Remove in Astro 5.0
import.meta.hot.send(`${WS_EVENT_NAME_DEPRECATED}:${app.id}:initialized`);
}
} catch (e) {
console.error(`Failed to init app ${app.id}, error: ${e}`);
app.status = 'error';
if (import.meta.hot) {
import.meta.hot.send('astro:devtoolbar:error:init', {
app: app,
error: e instanceof Error ? e.stack : e,
});
}
const appButton = this.getAppButtonById(app.id);
const appTooltip = appButton?.querySelector<HTMLElement>('.item-tooltip');
if (appButton && appTooltip) {
appButton.toggleAttribute('data-app-error', true);
appTooltip.innerText = `Error initializing ${app.name}`;
}
}
}
getAppTemplate(app: DevToolbarApp) {
return `<button class="item" data-app-id="${app.id}">
<div class="icon">${app.icon ? getAppIcon(app.icon) : '?'}<div class="notification"></div></div>
<span class="item-tooltip">${app.name}</span>
</button>`;
}
getAppById(id: string) {
return this.apps.find((app) => app.id === id);
}
getAppCanvasById(id: string) {
return this.shadowRoot.querySelector<HTMLElement>(
`astro-dev-toolbar-app-canvas[data-app-id="${id}"]`
);
}
getAppButtonById(id: string) {
return this.shadowRoot.querySelector<HTMLElement>(`[data-app-id="${id}"]`);
}
async toggleAppStatus(app: DevToolbarApp) {
const activeApp = this.getActiveApp();
if (activeApp) {
const closeApp = await this.setAppStatus(activeApp, false);
// If the app returned false, don't open the new app, the old app didn't want to close
if (!closeApp) return;
}
// TODO(fks): Handle a app that hasn't loaded yet.
// Currently, this will just do nothing.
if (app.status !== 'ready') return;
// Open the selected app. If the selected app was
// already the active app then the desired outcome
// was to close that app, so no action needed.
if (app !== activeApp) {
await this.setAppStatus(app, true);
if (import.meta.hot && app.id !== 'astro:more') {
import.meta.hot.send('astro:devtoolbar:app:toggled', {
app: app,
});
}
}
}
async setAppStatus(app: DevToolbarApp, newStatus: boolean) {
const appCanvas = this.getAppCanvasById(app.id);
if (!appCanvas) return false;
if (app.active && !newStatus && app.beforeTogglingOff) {
const shouldToggleOff = await app.beforeTogglingOff(appCanvas.shadowRoot!);
// If the app returned false, don't toggle it off, maybe the app showed a confirmation dialog or similar
if (!shouldToggleOff) return false;
}
app.active = newStatus ?? !app.active;
const mainBarButton = this.getAppButtonById(app.id);
const moreBarButton = this.getAppCanvasById('astro:more')?.shadowRoot?.querySelector(
`[data-app-id="${app.id}"]`
);
if (mainBarButton) {
mainBarButton.classList.toggle('active', app.active);
}
if (moreBarButton) {
moreBarButton.classList.toggle('active', app.active);
}
if (app.active) {
appCanvas.style.display = 'block';
appCanvas.setAttribute('data-active', '');
} else {
appCanvas.style.display = 'none';
appCanvas.removeAttribute('data-active');
}
[
'app-toggled',
// Deprecated
// TODO: Remove in Astro 5.0
'plugin-toggled',
].forEach((eventName) => {
app.eventTarget.dispatchEvent(
new CustomEvent(eventName, {
detail: {
state: app.active,
app,
},
})
);
});
if (import.meta.hot) {
import.meta.hot.send(`${WS_EVENT_NAME}:${app.id}:toggled`, { state: app.active });
import.meta.hot.send(`${WS_EVENT_NAME_DEPRECATED}:${app.id}:toggled`, {
state: app.active,
});
}
return true;
}
isHidden(): boolean {
return this.devToolbarContainer?.hasAttribute('data-hidden') ?? true;
}
getActiveApp(): DevToolbarApp | undefined {
return this.apps.find((app) => app.active);
}
clearDelayedHide() {
window.clearTimeout(this.delayedHideTimeout);
this.delayedHideTimeout = undefined;
}
triggerDelayedHide() {
this.clearDelayedHide();
this.delayedHideTimeout = window.setTimeout(() => {
this.setToolbarVisible(false);
this.delayedHideTimeout = undefined;
}, HOVER_DELAY);
}
setToolbarVisible(newStatus: boolean) {
const barContainer = this.shadowRoot.querySelector<HTMLDivElement>('#bar-container');
const devBar = this.shadowRoot.querySelector<HTMLDivElement>('#dev-bar');
const devBarHitboxAbove =
this.shadowRoot.querySelector<HTMLDivElement>('#dev-bar-hitbox-above');
if (newStatus === true) {
this.devToolbarContainer?.removeAttribute('data-hidden');
barContainer?.removeAttribute('inert');
devBar?.removeAttribute('tabindex');
if (devBarHitboxAbove) devBarHitboxAbove.style.height = '0';
return;
}
if (newStatus === false) {
this.devToolbarContainer?.setAttribute('data-hidden', '');
barContainer?.setAttribute('inert', '');
devBar?.setAttribute('tabindex', '0');
if (devBarHitboxAbove) devBarHitboxAbove.style.height = `${DEVBAR_HITBOX_ABOVE}px`;
return;
}
}
setNotificationVisible(newStatus: boolean) {
this.devToolbarContainer?.toggleAttribute('data-no-notification', !newStatus);
const moreCanvas = this.getAppCanvasById('astro:more');
moreCanvas?.shadowRoot
?.querySelector('#dropdown')
?.toggleAttribute('data-no-notification', !newStatus);
}
}
export class DevToolbarCanvas extends HTMLElement {
shadowRoot: ShadowRoot;
constructor() {
super();
this.shadowRoot = this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<style>
:host {
position: absolute;
top: 0;
left: 0;
}
</style>`;
}
}
export function getAppIcon(icon: Icon) {
if (isDefinedIcon(icon)) {
return getIconElement(icon).outerHTML;
}
return icon;
}