-
Notifications
You must be signed in to change notification settings - Fork 22
/
sidebarController.tsx
599 lines (523 loc) · 17.7 KB
/
sidebarController.tsx
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
/*
* Copyright (C) 2024 PixieBrix, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import reportEvent from "@/telemetry/reportEvent";
import { Events } from "@/telemetry/events";
import { expectContext } from "@/utils/expectContext";
import sidebarInThisTab from "@/sidebar/messenger/api";
import { isEmpty, throttle } from "lodash";
import { signalFromEvent } from "abort-utils";
import { SimpleEventTarget } from "@/utils/SimpleEventTarget";
import * as sidebarMv2 from "@/contentScript/sidebarDomControllerLite";
import { type Except } from "type-fest";
import { type RunArgs, RunReason } from "@/types/runtimeTypes";
import { type UUID } from "@/types/stringTypes";
import { type RegistryId } from "@/types/registryTypes";
import { type ModComponentRef } from "@/types/modComponentTypes";
import type {
ActivatePanelOptions,
ModActivationPanelEntry,
FormPanelEntry,
PanelEntry,
PanelPayload,
TemporaryPanelEntry,
} from "@/types/sidebarTypes";
import { getTemporaryPanelSidebarEntries } from "@/platform/panels/panelController";
import { getFormPanelSidebarEntries } from "@/platform/forms/formController";
import { getSidebarTargetForCurrentTab } from "@/utils/sidePanelUtils";
import { memoizeUntilSettled } from "@/utils/promiseUtils";
import { getTimedSequence } from "@/types/helpers";
import { messenger } from "webext-messenger";
import { isMV3 } from "@/mv3/api";
import { getErrorMessage } from "@/errors/errorHelpers";
import { focusCaptureDialog } from "@/contentScript/focusCaptureDialog";
import { isLoadedInIframe } from "@/utils/iframeUtils";
import { showMySidePanel } from "@/background/messenger/strict/api";
import { getSidebarElement } from "@/contentScript/sidebarDomControllerLite";
import focusController from "@/utils/focusController";
import selectionController from "@/utils/selectionController";
const HIDE_SIDEBAR_EVENT_NAME = "pixiebrix:hideSidebar";
/* Approximate sidebar width in pixels. Used to determine whether it's open */
const MINIMUM_SIDEBAR_WIDTH = 300;
export const isSidePanelOpen = isMV3()
? isSidePanelOpenMv3
: sidebarMv2.isSidebarFrameVisible;
/**
* Determines whether the sidebar is open.
* @returns false when it's definitely closed or 'unknown' when it cannot be determined,
* because the extra padding might be caused by the dev tools being open on the side
* or due to another sidebar
*/
// The type cannot be `undefined` due to strictNullChecks
function isSidePanelOpenSync(): false | "unknown" {
if (!isMV3()) {
throw new Error("isSidePanelOpenSync is only available in MV3");
}
if (!globalThis.window) {
return "unknown";
}
return window.outerWidth - window.innerWidth > MINIMUM_SIDEBAR_WIDTH
? "unknown"
: false;
}
// This method is exclusive to the content script, don't export it
async function isSidePanelOpenMv3(): Promise<boolean> {
if (isSidePanelOpenSync() === false) {
return false;
}
try {
await messenger(
"SIDEBAR_PING",
{ retry: false },
await getSidebarTargetForCurrentTab(),
);
return true;
} catch {
return false;
}
}
// - Only start one ping at a time
// - Limit to one request every second (if the user closes the sidebar that quickly, we likely see those errors anyway)
// - Throw custom error if the sidebar doesn't respond in time
const pingSidebar = memoizeUntilSettled(
throttle(async () => {
try {
await sidebarInThisTab.pingSidebar();
} catch (error) {
// TODO: Use TimeoutError after https://github.com/sindresorhus/p-timeout/issues/41
throw new Error("The sidebar did not respond in time", { cause: error });
}
}, 1000) as () => Promise<void>,
);
/**
* Event listeners triggered when the sidebar shows and is ready to receive messages.
*/
export const sidebarShowEvents = new SimpleEventTarget<RunArgs>();
export function sidebarWasLoaded(): void {
sidebarShowEvents.emit({ reason: RunReason.MANUAL });
}
// eslint-disable-next-line local-rules/persistBackgroundData -- Unused there
const panels: PanelEntry[] = [];
let modActivationPanelEntry: ModActivationPanelEntry | null = null;
/**
* Attach the sidebar to the page if it's not already attached. Then re-renders all panels.
*/
export async function showSidebar(): Promise<void> {
reportEvent(Events.SIDEBAR_SHOW);
if (isMV3() || isLoadedInIframe()) {
try {
await showMySidePanel();
} catch (error) {
if (!getErrorMessage(error).includes("user gesture")) {
throw error;
}
await focusCaptureDialog(
'Please click "OK" to allow PixieBrix to open the sidebar.',
{
signal: signalFromEvent(
sidebarShowEvents,
sidebarShowEvents.coreEvent,
),
},
);
await showMySidePanel();
}
} else if (!sidebarMv2.isSidebarFrameVisible()) {
sidebarMv2.insertSidebarFrame();
}
try {
await pingSidebar();
} catch (error) {
throw new Error("The sidebar did not respond in time", { cause: error });
}
}
/**
* Force-show the panel for the given extension id
* @param extensionId the extension UUID
*/
export async function activateExtensionPanel(extensionId: UUID): Promise<void> {
expectContext("contentScript");
if (!(await isSidePanelOpen())) {
console.warn("sidebar is not attached to the page");
}
void sidebarInThisTab.activatePanel(getTimedSequence(), {
extensionId,
force: true,
});
}
/**
* Hide the sidebar. Dispatches HIDE_SIDEBAR_EVENT_NAME event even if the sidebar is not currently visible.
* @see HIDE_SIDEBAR_EVENT_NAME
*/
export function hideSidebar(): void {
reportEvent(Events.SIDEBAR_HIDE);
sidebarMv2.removeSidebarFrame();
window.dispatchEvent(new CustomEvent(HIDE_SIDEBAR_EVENT_NAME));
}
/**
* @param activateOptions options controlling the visible panel in the sidebar
*/
export async function updateSidebar(
activateOptions: ActivatePanelOptions = {},
): Promise<void> {
await pingSidebar();
if (!isEmpty(activateOptions)) {
// The sidebarSlice handles the race condition with the panels loading by keeping track of the latest pending
// activatePanel request.
await sidebarInThisTab.activatePanel(getTimedSequence(), {
...activateOptions,
force: activateOptions.force,
});
}
}
export async function renderPanelsIfVisible(): Promise<void> {
expectContext("contentScript");
if (isLoadedInIframe()) {
console.warn("renderPanelsIfVisible should not be called from a frame");
return;
}
if (await isSidePanelOpen()) {
void sidebarInThisTab.renderPanels(getTimedSequence(), panels);
} else {
console.debug(
"sidebarController:renderPanelsIfVisible: skipping renderPanels because the sidebar is not visible",
);
}
}
export async function showSidebarForm(
entry: Except<FormPanelEntry, "type">,
): Promise<void> {
expectContext("contentScript");
if (!(await isSidePanelOpen())) {
throw new Error("Cannot add sidebar form if the sidebar is not visible");
}
void sidebarInThisTab.showForm(getTimedSequence(), {
type: "form",
...entry,
});
}
export async function hideSidebarForm(nonce: UUID): Promise<void> {
expectContext("contentScript");
if (!(await isSidePanelOpen())) {
// Already hidden
return;
}
void sidebarInThisTab.hideForm(getTimedSequence(), nonce);
}
export async function showTemporarySidebarPanel(
entry: Except<TemporaryPanelEntry, "type">,
): Promise<void> {
expectContext("contentScript");
if (!(await isSidePanelOpen())) {
throw new Error(
"Cannot add temporary sidebar panel if the sidebar is not visible",
);
}
void sidebarInThisTab.showTemporaryPanel(getTimedSequence(), {
type: "temporaryPanel",
...entry,
});
}
export async function updateTemporarySidebarPanel(
entry: Except<TemporaryPanelEntry, "type">,
): Promise<void> {
expectContext("contentScript");
if (!(await isSidePanelOpen())) {
throw new Error(
"Cannot add temporary sidebar panel if the sidebar is not visible",
);
}
sidebarInThisTab.updateTemporaryPanel(getTimedSequence(), {
type: "temporaryPanel",
...entry,
});
}
export async function hideTemporarySidebarPanel(nonce: UUID): Promise<void> {
expectContext("contentScript");
if (!(await isSidePanelOpen())) {
return;
}
void sidebarInThisTab.hideTemporaryPanel(getTimedSequence(), nonce);
}
/**
* Remove all panels associated with given extensionIds.
* @param extensionIds the extension UUIDs to remove
*/
export function removeExtensions(extensionIds: UUID[]): void {
expectContext("contentScript");
console.debug("sidebarController:removeExtensions", { extensionIds });
// Avoid unnecessary messaging. Also, prevent issues if this method is called as cleanup from a frame
if (extensionIds.length === 0) {
return;
}
// `panels` is const, so replace the contents
const current = panels.splice(0);
panels.push(...current.filter((x) => !extensionIds.includes(x.extensionId)));
void renderPanelsIfVisible();
}
/**
* Remove all panels associated with the given extensionPointId.
* @param extensionPointId the extension point id (internal or external)
* @param preserveExtensionIds array of extension ids to keep in the panel. Used to avoid flickering if updating
* the extensionPoint for a sidebar extension from the Page Editor
*/
export function removeExtensionPoint(
extensionPointId: RegistryId,
{ preserveExtensionIds = [] }: { preserveExtensionIds?: UUID[] } = {},
): void {
expectContext("contentScript");
console.debug("sidebarController:removeExtensionPoint %s", extensionPointId, {
preserveExtensionIds,
panels: panels.filter((x) => x.extensionPointId === extensionPointId),
});
// `panels` is const, so replace the contents
const current = panels.splice(0);
panels.push(
...current.filter(
(x) =>
x.extensionPointId !== extensionPointId ||
preserveExtensionIds.includes(x.extensionId),
),
);
void renderPanelsIfVisible();
}
/**
* Create placeholder panels showing loading indicators
*/
export function reservePanels(refs: ModComponentRef[]): void {
if (refs.length === 0) {
return;
}
const current = new Set(panels.map((x) => x.extensionId));
for (const { extensionId, extensionPointId, blueprintId } of refs) {
if (!current.has(extensionId)) {
const entry: PanelEntry = {
type: "panel",
extensionId,
extensionPointId,
blueprintId,
heading: "",
payload: null,
};
console.debug(
"sidebarController:reservePanels: reserve panel %s for %s",
extensionId,
extensionPointId,
blueprintId,
{ ...entry },
);
panels.push(entry);
}
}
void renderPanelsIfVisible();
}
export function updateHeading(extensionId: UUID, heading: string): void {
const entry = panels.find((x) => x.extensionId === extensionId);
if (entry) {
entry.heading = heading;
console.debug(
"updateHeading: update heading for panel %s for %s",
extensionId,
entry.extensionPointId,
{ ...entry },
);
void renderPanelsIfVisible();
} else {
console.warn(
"updateHeading: No panel exists for extension %s",
extensionId,
);
}
}
export function upsertPanel(
{ extensionId, extensionPointId, blueprintId }: ModComponentRef,
heading: string,
payload: PanelPayload,
): void {
const entry = panels.find((panel) => panel.extensionId === extensionId);
if (entry) {
entry.payload = payload;
entry.heading = heading;
console.debug(
"sidebarController:upsertPanel: update existing panel %s for %s",
extensionId,
extensionPointId,
blueprintId,
{ ...entry },
);
} else {
console.debug(
"sidebarController:upsertPanel: add new panel %s for %s",
extensionId,
extensionPointId,
blueprintId,
{
entry,
extensionPointId,
heading,
payload,
},
);
panels.push({
type: "panel",
extensionId,
extensionPointId,
blueprintId,
heading,
payload,
});
}
void renderPanelsIfVisible();
}
/**
* Show a mod activation panel in the sidebar. If there's already a panel showing, it will be replaced.
*
* @param entry the mod activation panel entry
* @throws Error if the sidebar frame is not visible
*/
export async function showModActivationInSidebar(
entry: Except<ModActivationPanelEntry, "type">,
): Promise<void> {
expectContext("contentScript");
if (!(await isSidePanelOpen())) {
throw new Error(
"Cannot activate mods in the sidebar if the sidebar is not visible",
);
}
modActivationPanelEntry = {
type: "activateMods",
...entry,
};
void sidebarInThisTab.showModActivationPanel(
getTimedSequence(),
modActivationPanelEntry,
);
}
/**
* Hide the mod activation panel in the sidebar.
* @see showModActivationInSidebar
*/
export async function hideModActivationInSidebar(): Promise<void> {
expectContext("contentScript");
// Clear out in in-memory tracking
modActivationPanelEntry = null;
if (!(await isSidePanelOpen())) {
return;
}
void sidebarInThisTab.hideModActivationPanel(getTimedSequence());
}
/**
* Return the panels that are "reserved", that will be shown when the sidebar is shown. The content may not be computed
* yet. This includes:
* - Permanent panels added by sidebarExtension
* - Temporary panels added by DisplayTemporaryInfo
* - Temporary form definitions added by ephemeralForm
* - Activate Recipe panel added by sidebarActivation.ts activate button click-handlers
*/
export function getReservedPanelEntries(): {
panels: PanelEntry[];
temporaryPanels: TemporaryPanelEntry[];
forms: FormPanelEntry[];
modActivationPanel: ModActivationPanelEntry | null;
} {
return {
panels,
temporaryPanels: getTemporaryPanelSidebarEntries(),
forms: getFormPanelSidebarEntries(),
modActivationPanel: modActivationPanelEntry,
};
}
function sidePanelOnCloseSignal(): AbortSignal {
const controller = new AbortController();
expectContext("contentScript");
if (isMV3()) {
window.addEventListener(
"resize",
() => {
// TODO: It doesn't work when the dev tools are open on the side.
// This is a rare event because we condition users to move the dev tools to
// the bottom via https://github.com/pixiebrix/pixiebrix-extension/pull/6952
// … but it's still possible for people with very large screens and those
// who temporarily moved the dev tools to the side anyway.
// Official event requested in https://github.com/w3c/webextensions/issues/517
if (isSidePanelOpenSync() === false) {
controller.abort();
}
},
{ signal: controller.signal },
);
} else {
window.addEventListener(
HIDE_SIDEBAR_EVENT_NAME,
() => {
controller.abort();
},
{
signal: controller.signal,
},
);
}
return controller.signal;
}
export function sidePanelOnClose(callback: () => void): void {
const signal = sidePanelOnCloseSignal();
signal.addEventListener("abort", callback, { once: true });
}
export function initSidebarFocusEvents(): void {
if (!isMV3()) {
// Add listeners to track keep track of focus with the MV2 sidebar. When the user interacts
// with the MV2 sidebar, the sidebar gets set as the document.activeElement. Required for brick
// functionality such as InsertAtCursorEffect
sidebarShowEvents.add(() => {
const sidebar = getSidebarElement();
if (!sidebar) {
// Should always exist because sidebarShowEvents is called on Sidebar App initialization
return;
}
// Save focus on initial load, because the user may have `mouseenter`ed the sidebar before the React App
// fired the sidebarShowEvent event. For example, if the user clicked the browserAction toolbar button and
// immediately `mouseenter`ed the sidebar (because the top of the sidebar is very close to the top browserAction)
if (document.activeElement !== sidebar) {
focusController.save();
}
const closeSignal = sidePanelOnCloseSignal();
// Can't detect clicks in the sidebar itself. So need to just watch for enter/leave the sidebar element
sidebar.addEventListener(
"mouseenter",
() => {
// If the user clicks into the sidebar and then leaves the sidebar, don't set the focus to the sidebar
// when they re-enter the sidebar
if (document.activeElement !== sidebar) {
// FIXME: If the user closes the sidebar when these two items are stored,
// both controllers will be stuck that way until some other .restore()/.clear() call resets it. It will need a "sidebar hide" listener to ensure it doesn't happen
// https://github.com/pixiebrix/pixiebrix-extension/pull/7842#discussion_r1516015396
focusController.save();
selectionController.save();
}
},
{ passive: true, capture: true, signal: closeSignal },
);
sidebar.addEventListener(
"mouseleave",
() => {
focusController.clear();
selectionController.clear();
},
{ passive: true, capture: true, signal: closeSignal },
);
});
}
}