@peers-app/peers-ui 0.34.7 → 0.34.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/command-palette/command-palette-ui.js +14 -14
  2. package/dist/command-palette/command-palette.d.ts +10 -3
  3. package/dist/command-palette/command-palette.js +60 -6
  4. package/dist/command-palette/frame-commands.d.ts +37 -0
  5. package/dist/command-palette/frame-commands.js +43 -0
  6. package/dist/globals.d.ts +13 -2
  7. package/dist/globals.js +24 -2
  8. package/dist/index.d.ts +2 -1
  9. package/dist/index.js +9 -1
  10. package/dist/isolated-screens/config.js +1 -5
  11. package/dist/isolated-screens/frame-permissions.d.ts +11 -0
  12. package/dist/isolated-screens/frame-permissions.js +33 -0
  13. package/dist/isolated-screens/frame-protocol.d.ts +64 -0
  14. package/dist/isolated-screens/frame-protocol.js +28 -0
  15. package/dist/isolated-screens/frame-runtime.js +68 -2
  16. package/dist/isolated-screens/frame-viewport.d.ts +9 -0
  17. package/dist/isolated-screens/frame-viewport.js +36 -0
  18. package/dist/isolated-screens/global-widgets.d.ts +74 -0
  19. package/dist/isolated-screens/global-widgets.js +270 -0
  20. package/dist/isolated-screens/isolated-screen.d.ts +51 -1
  21. package/dist/isolated-screens/isolated-screen.js +228 -14
  22. package/dist/isolated-screens/piece-reach.d.ts +24 -0
  23. package/dist/isolated-screens/piece-reach.js +24 -8
  24. package/dist/isolated-screens/widget-box.d.ts +48 -0
  25. package/dist/isolated-screens/widget-box.js +193 -0
  26. package/dist/operator-console/operator-console-state.js +5 -1
  27. package/dist/root-layout/root-layout-host.js +3 -1
  28. package/dist/screens/devices/devices-list.d.ts +5 -1
  29. package/dist/screens/devices/devices-list.js +12 -4
  30. package/dist/screens/packages/package-info.js +2 -1
  31. package/dist/screens/packages/package-widgets-panel.d.ts +15 -0
  32. package/dist/screens/packages/package-widgets-panel.js +64 -0
  33. package/dist/tabs-layout/tabs-state.d.ts +5 -2
  34. package/dist/tabs-layout/tabs-state.js +41 -17
  35. package/package.json +3 -3
@@ -5,6 +5,7 @@ const jsx_runtime_1 = require("react/jsx-runtime");
5
5
  const peers_sdk_1 = require("@peers-app/peers-sdk");
6
6
  const react_1 = require("react");
7
7
  const client_1 = require("react-dom/client");
8
+ const frame_commands_1 = require("../command-palette/frame-commands");
8
9
  const globals_1 = require("../globals");
9
10
  const hooks_1 = require("../hooks");
10
11
  const global_overlays_1 = require("../root-layout/global-overlays");
@@ -16,7 +17,9 @@ const ui_inspection_1 = require("../ui-inspection");
16
17
  const focus_relay_1 = require("./focus-relay");
17
18
  const frame_bridge_1 = require("./frame-bridge");
18
19
  const frame_protocol_1 = require("./frame-protocol");
20
+ const frame_viewport_1 = require("./frame-viewport");
19
21
  const wheel_relay_1 = require("./wheel-relay");
22
+ const widget_box_1 = require("./widget-box");
20
23
  let root;
21
24
  let setScreen;
22
25
  let pending = { props: {} };
@@ -27,6 +30,10 @@ let loadedVersionId;
27
30
  let drawsPiece = false;
28
31
  /** Whether this frame's piece is drawn over a framed screen's slot, so Tab out goes through the host. */
29
32
  let relaysTab = false;
33
+ /** Whether this frame draws a global widget, over the window. */
34
+ let drawsWidget = false;
35
+ /** For a global widget's frame: where the host put it. */
36
+ let placement;
30
37
  /**
31
38
  * Apply the host's theme. The starting document uses the theme attribute for its color scheme
32
39
  * and keeps a piece's background transparent across page color updates.
@@ -34,7 +41,7 @@ let relaysTab = false;
34
41
  function applyTheme(mode) {
35
42
  const html = document.documentElement;
36
43
  html.setAttribute("data-bs-theme", mode);
37
- if (drawsPiece)
44
+ if (drawsPiece || drawsWidget)
38
45
  return;
39
46
  const background = mode === "dark" ? "rgb(33, 37, 41)" : "";
40
47
  html.style.backgroundColor = background;
@@ -92,6 +99,10 @@ function FrameScreen(props) {
92
99
  if (!state.ui)
93
100
  return null;
94
101
  const Screen = state.ui.content;
102
+ if (state.widget) {
103
+ // A global widget draws over the window: no tab's box around it, and no package overlays.
104
+ return ((0, jsx_runtime_1.jsx)(ScreenErrorBoundary, { packageName: props.packageName, onError: (message) => props.host.notify(frame_protocol_1.FrameNotice.failed, { message }), children: (0, jsx_runtime_1.jsx)(Screen, { ...state.props }) }));
105
+ }
95
106
  // The same box a tab draws around a screen in the host, so a screen's CSS that cancels the
96
107
  // tab's padding (`.p-3 > .x-app`) still lines up.
97
108
  return ((0, jsx_runtime_1.jsx)("div", { className: `h-100 overflow-auto ${desktop ? "p-3" : "p-2"}`, children: (0, jsx_runtime_1.jsxs)(ScreenErrorBoundary, { packageName: props.packageName, onError: (message) => props.host.notify(frame_protocol_1.FrameNotice.failed, { message }), children: [(0, jsx_runtime_1.jsx)(Screen, { ...state.props }), (0, jsx_runtime_1.jsx)(FrameOverlays, {})] }) }));
@@ -139,11 +150,13 @@ function PieceInFrame(props) {
139
150
  * The box a framed piece draws in: measured for `usePieceSize`, and, for a piece that takes its
140
151
  * own height (and in a popover its width), reported to the host. The size lives here, apart from
141
152
  * the piece, so a resize re-renders only what reads it, as `<Piece>`'s box does in the window.
153
+ * The frame of a piece that takes its own height never scrolls (`holdFrameViewport`).
142
154
  */
143
155
  function PieceRoot(props) {
144
156
  const { host, height: mode, width: maxWidth } = props;
145
157
  const rootRef = (0, react_1.useRef)(null);
146
158
  const [size, setSize] = (0, react_1.useState)({ width: 0, height: 0 });
159
+ (0, react_1.useEffect)(() => (mode === "content" ? (0, frame_viewport_1.holdFrameViewport)() : undefined), [mode]);
147
160
  (0, react_1.useEffect)(() => {
148
161
  const root = rootRef.current;
149
162
  if (!root)
@@ -215,10 +228,35 @@ async function runBundle(init) {
215
228
  }
216
229
  /** Numbers each init, so an older one that finishes later doesn't replace a newer one's screen. */
217
230
  let latestInit = 0;
231
+ /**
232
+ * Put a global widget's frame where the host says: the body lays out as the whole window and is
233
+ * shifted back by where the frame is, and, being transformed, holds the frame's `position: fixed`
234
+ * elements, portals included. So a widget's `position: fixed` means the window.
235
+ */
236
+ function placeWidget(next) {
237
+ placement = next;
238
+ (0, globals_1.followHostViewport)(next.viewportWidth, next.viewportHeight);
239
+ const html = document.documentElement;
240
+ html.style.overflow = "hidden";
241
+ const body = document.body.style;
242
+ body.position = "fixed";
243
+ body.margin = "0";
244
+ body.left = `${-next.x}px`;
245
+ body.top = `${-next.y}px`;
246
+ body.width = `${next.viewportWidth}px`;
247
+ body.height = `${next.viewportHeight}px`;
248
+ body.transform = "translate(0, 0)";
249
+ }
218
250
  async function handleInit(host, init) {
219
251
  const thisInit = ++latestInit;
220
252
  drawsPiece = init.piece !== undefined;
221
253
  relaysTab = init.piece?.overSlot === true;
254
+ const firstWidgetInit = init.widget !== undefined && !drawsWidget;
255
+ drawsWidget = init.widget !== undefined;
256
+ if (init.widget)
257
+ placeWidget(init.widget.placement);
258
+ if (firstWidgetInit)
259
+ (0, widget_box_1.startWidgetBoxReports)(host, () => placement);
222
260
  const firstInit = !root;
223
261
  if (firstInit) {
224
262
  const bridge = (0, frame_bridge_1.frameBridge)();
@@ -286,7 +324,7 @@ async function handleInit(host, init) {
286
324
  host.notify(frame_protocol_1.FrameNotice.failed, { message });
287
325
  return;
288
326
  }
289
- show({ ui, props: init.props });
327
+ show({ ui, props: init.props, ...(init.widget ? { widget: true } : {}) });
290
328
  }
291
329
  /** Links to the web open outside Peers, and `#` links navigate the tab, through the host. */
292
330
  function installLinkHandling(host) {
@@ -473,6 +511,16 @@ function installWheelRelay(host) {
473
511
  scheduled = requestAnimationFrame(flush);
474
512
  }, { capture: true, passive: true });
475
513
  }
514
+ /** A placement as the host sends it: six finite numbers, sizes not negative. */
515
+ function isPlacement(value) {
516
+ const p = value;
517
+ if (!p)
518
+ return false;
519
+ const nums = [p.x, p.y, p.width, p.height, p.viewportWidth, p.viewportHeight];
520
+ return (nums.every((n) => typeof n === "number" && Number.isFinite(n)) &&
521
+ p.width >= 0 &&
522
+ p.height >= 0);
523
+ }
476
524
  /** The screen's warnings and errors also go to the host, whose console the Console app reads. */
477
525
  function installConsoleForwarding(host) {
478
526
  for (const level of ["warn", "error"]) {
@@ -512,6 +560,24 @@ function startFrameRuntime() {
512
560
  host.onNotify(frame_protocol_1.HostNotice.theme, ({ colorMode }) => applyTheme(colorMode));
513
561
  // The host resolves the screen's pieces; when what they depend on changes, they resolve again.
514
562
  host.onNotify(frame_protocol_1.HostNotice.pieceRevision, () => (0, piece_resolution_1.pieceRevision)((0, piece_resolution_1.pieceRevision)() + 1));
563
+ host.onNotify(frame_protocol_1.HostNotice.widgetPlacement, (next) => {
564
+ if (drawsWidget && isPlacement(next))
565
+ placeWidget(next);
566
+ });
567
+ // The package's commands go to the host's palette, which runs them by telling this frame.
568
+ (0, frame_commands_1.bridgeCommandsToHost)({
569
+ register: (command) => void host
570
+ .request(frame_protocol_1.FrameRequest.commandRegister, command)
571
+ .catch((error) => console.warn(`Couldn't add the command ${command.id}`, error)),
572
+ unregister: (commandId) => void host.request(frame_protocol_1.FrameRequest.commandUnregister, { id: commandId }).catch(() => undefined),
573
+ run: (commandId) => void host
574
+ .request(frame_protocol_1.FrameRequest.commandRun, { id: commandId })
575
+ .catch((error) => console.warn(`Couldn't run the command ${commandId}`, error)),
576
+ });
577
+ host.onNotify(frame_protocol_1.HostNotice.commandRun, ({ id }) => {
578
+ if (typeof id === "string")
579
+ (0, frame_commands_1.runFrameCommand)(id);
580
+ });
515
581
  installLinkHandling(host);
516
582
  installKeyForwarding(host);
517
583
  installPointerRelay(host);
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Keep this frame's viewport from scrolling: no scrollbar, and a scroll made by script (such as
3
+ * `scrollIntoView` on an option drawn past the frame's edge) is put back at once, since the user
4
+ * couldn't scroll back from it.
5
+ *
6
+ * @param doc - The frame's document.
7
+ * @returns A function that lets the viewport scroll again.
8
+ */
9
+ export declare function holdFrameViewport(doc?: Document): () => void;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ // A frame sized to its content (a piece that takes its own height, or a piece in a popover) is
3
+ // exactly as big as what it draws, so its own viewport never has anything to scroll to. Only
4
+ // something drawn over the content can reach past the frame's edge, such as the mention picker
5
+ // hanging below the caret, and the host cuts that off at the frame's edge whatever the frame does.
6
+ //
7
+ // Left to scroll, such a frame loops. The overlay makes it scrollable, so a scrollbar takes width
8
+ // from the content; the content wraps taller, and the frame grows to fit it; now the overlay fits,
9
+ // the scrollbar goes, the content unwraps, the frame shrinks, and the overlay reaches past it
10
+ // again, on every frame, for as long as the overlay is open (W147: the picker in Tasks' details
11
+ // in Desk's side panel flickered without end, on a Mac set to show scrollbars).
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.holdFrameViewport = holdFrameViewport;
14
+ /**
15
+ * Keep this frame's viewport from scrolling: no scrollbar, and a scroll made by script (such as
16
+ * `scrollIntoView` on an option drawn past the frame's edge) is put back at once, since the user
17
+ * couldn't scroll back from it.
18
+ *
19
+ * @param doc - The frame's document.
20
+ * @returns A function that lets the viewport scroll again.
21
+ */
22
+ function holdFrameViewport(doc = document) {
23
+ const html = doc.documentElement;
24
+ const view = doc.defaultView;
25
+ const previous = html.style.overflow;
26
+ html.style.overflow = "hidden";
27
+ const putBack = () => {
28
+ if (view && (view.scrollX !== 0 || view.scrollY !== 0))
29
+ view.scrollTo(0, 0);
30
+ };
31
+ view?.addEventListener("scroll", putBack);
32
+ return () => {
33
+ view?.removeEventListener("scroll", putBack);
34
+ html.style.overflow = previous;
35
+ };
36
+ }
@@ -0,0 +1,74 @@
1
+ import { type IIsolatedGlobalWidget } from "@peers-app/peers-sdk";
2
+ import { type IPieceBundle } from "../ui-contracts/piece-host";
3
+ import type { IWidgetPlacement } from "./frame-protocol";
4
+ import { type IStoredManifest } from "./piece-reach";
5
+ import type { IWidgetBox } from "./widget-box";
6
+ /**
7
+ * Global widgets: what packages draw over every app (Tasks' timer, Operator's assistant),
8
+ * declared in their definitions (`pkg.globalWidgets`), never registered by their code.
9
+ *
10
+ * The shell draws each widget of each package that runs in the person's Personal group, in a
11
+ * frame of its own acting as the package, once the first screen has drawn. Only Personal's: a
12
+ * package another member installs in a shared group can't draw over the person's apps. The
13
+ * frame is transparent and placed over just the box the widget's content covers, so the rest of
14
+ * the window stays the apps'; while the widget drags something, it covers the window. The person
15
+ * turns a widget off on a device in the package's details.
16
+ *
17
+ * A package still on the shared-window list (`SHARED_WINDOW_PACKAGES`) draws its widgets in the
18
+ * window instead, as its screens do: Operator, whose assistant needs the microphone, which a
19
+ * frame's opaque origin can't open.
20
+ */
21
+ /** A widget to draw: its package's running version in Personal, and the widget's declaration. */
22
+ export interface IGlobalWidgetEntry {
23
+ /** `<packageId>:<widgetId>`: how `globalWidgetsOff` names it. */
24
+ key: string;
25
+ packageId: string;
26
+ /** The version running in Personal, whose manifest declares it. */
27
+ packageVersionId: string;
28
+ widget: IIsolatedGlobalWidget;
29
+ /** For a widget drawn in a frame: its package's UI bundle, read and checked. */
30
+ bundle?: IPieceBundle;
31
+ }
32
+ /** The widgets the layer draws now, turned off ones included: for the packages' details. */
33
+ export declare const listedGlobalWidgets: import("@peers-app/peers-sdk").Observable<IGlobalWidgetEntry[]>;
34
+ /**
35
+ * The global widgets a stored manifest declares: only well-formed ones (the host validated the
36
+ * manifest when it stored it; this keeps a bad row from drawing anything).
37
+ *
38
+ * @param manifest - From `readStoredManifest`.
39
+ */
40
+ export declare function widgetsDeclaredIn(manifest: IStoredManifest): IIsolatedGlobalWidget[];
41
+ /**
42
+ * The global widgets a version's stored manifest declares ({@link widgetsDeclaredIn}).
43
+ *
44
+ * @param dataContextId - The context the version's row is in.
45
+ * @param packageVersionId - The version.
46
+ */
47
+ export declare function declaredGlobalWidgets(dataContextId: string, packageVersionId: string): Promise<IIsolatedGlobalWidget[]>;
48
+ /** The global widgets of every package running in the person's Personal group on this device. */
49
+ export declare function listGlobalWidgets(): Promise<IGlobalWidgetEntry[]>;
50
+ /**
51
+ * Every global widget, each in a frame of its own over the window. The shell mounts it once,
52
+ * beside the root layout; it starts listing widgets at the first idle moment after the first
53
+ * screen has drawn, and again whenever which packages run in Personal changes.
54
+ */
55
+ export declare function GlobalWidgetsLayer(): import("react/jsx-runtime").JSX.Element;
56
+ /**
57
+ * Where a widget's frame goes: over the whole window until it has measured itself and while it
58
+ * drags something; over its box once it has; a pixel in the corner while it draws nothing (a
59
+ * frame with no size may stop being rendered, and then never says it has something to draw).
60
+ *
61
+ * @param box - What it last said it covers: `undefined` before it said, `null` for nothing.
62
+ * @param dragging - Whether it holds the pointer.
63
+ * @param viewportWidth - The window's width.
64
+ * @param viewportHeight - The window's height.
65
+ */
66
+ export declare function widgetPlacement(box: IWidgetBox | null | undefined, dragging: boolean, viewportWidth: number, viewportHeight: number): IWidgetPlacement;
67
+ /**
68
+ * Whether a UI id is the package's own: the window's loader finds a UI's package by its routes,
69
+ * so a widget drawn in the window must name a UI its own package's routes register.
70
+ *
71
+ * @param packageId - The package that declares the widget.
72
+ * @param peersUIId - The UI the widget names.
73
+ */
74
+ export declare function ownsUI(packageId: string, peersUIId: string): boolean;
@@ -0,0 +1,270 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listedGlobalWidgets = void 0;
4
+ exports.widgetsDeclaredIn = widgetsDeclaredIn;
5
+ exports.declaredGlobalWidgets = declaredGlobalWidgets;
6
+ exports.listGlobalWidgets = listGlobalWidgets;
7
+ exports.GlobalWidgetsLayer = GlobalWidgetsLayer;
8
+ exports.widgetPlacement = widgetPlacement;
9
+ exports.ownsUI = ownsUI;
10
+ const jsx_runtime_1 = require("react/jsx-runtime");
11
+ const peers_sdk_1 = require("@peers-app/peers-sdk");
12
+ const react_1 = require("react");
13
+ const globals_1 = require("../globals");
14
+ const hooks_1 = require("../hooks");
15
+ const packages_ipc_1 = require("../screens/packages/packages-ipc");
16
+ const piece_host_1 = require("../ui-contracts/piece-host");
17
+ const config_1 = require("./config");
18
+ const frame_permissions_1 = require("./frame-permissions");
19
+ const isolated_screen_1 = require("./isolated-screen");
20
+ const piece_reach_1 = require("./piece-reach");
21
+ /** The widgets the layer draws now, turned off ones included: for the packages' details. */
22
+ exports.listedGlobalWidgets = (0, peers_sdk_1.observable)([]);
23
+ /**
24
+ * Each version's declared widgets, by `<dataContextId>:<packageVersionId>`: a stored manifest
25
+ * doesn't change. Only a read that found the manifest is kept, so a version whose manifest is
26
+ * stored later (a folder-loaded build promoted to a release) is read again.
27
+ */
28
+ const declaredByVersion = new Map();
29
+ /**
30
+ * The global widgets a stored manifest declares: only well-formed ones (the host validated the
31
+ * manifest when it stored it; this keeps a bad row from drawing anything).
32
+ *
33
+ * @param manifest - From `readStoredManifest`.
34
+ */
35
+ function widgetsDeclaredIn(manifest) {
36
+ return Array.isArray(manifest.globalWidgets)
37
+ ? manifest.globalWidgets.filter((widget) => !!widget &&
38
+ typeof widget.id === "string" &&
39
+ typeof widget.peersUIId === "string" &&
40
+ typeof widget.title === "string")
41
+ : [];
42
+ }
43
+ /**
44
+ * The global widgets a version's stored manifest declares ({@link widgetsDeclaredIn}).
45
+ *
46
+ * @param dataContextId - The context the version's row is in.
47
+ * @param packageVersionId - The version.
48
+ */
49
+ async function declaredGlobalWidgets(dataContextId, packageVersionId) {
50
+ const key = `${dataContextId}:${packageVersionId}`;
51
+ const known = declaredByVersion.get(key);
52
+ if (known)
53
+ return known;
54
+ const manifest = await (0, piece_reach_1.readStoredManifest)(dataContextId, packageVersionId);
55
+ if (!manifest)
56
+ return [];
57
+ const widgets = widgetsDeclaredIn(manifest);
58
+ declaredByVersion.set(key, widgets);
59
+ return widgets;
60
+ }
61
+ /** The global widgets of every package running in the person's Personal group on this device. */
62
+ async function listGlobalWidgets() {
63
+ const user = await (0, peers_sdk_1.getUserContext)();
64
+ const consumer = await (0, packages_ipc_1.packagesContractFor)(user.userId).get();
65
+ const { packages } = await consumer.tools.listPackages();
66
+ const entries = [];
67
+ for (const pkg of packages) {
68
+ const packageVersionId = pkg.runtime.running?.packageVersionId;
69
+ if (!packageVersionId || pkg.disabled)
70
+ continue;
71
+ try {
72
+ const widgets = await declaredGlobalWidgets(user.userId, packageVersionId);
73
+ if (!widgets.length)
74
+ continue;
75
+ // A shared-window package's widgets draw in the window, which loads its bundle itself.
76
+ const bundle = (0, config_1.runsIsolated)(pkg.packageId)
77
+ ? await (0, piece_host_1.readVersionBundle)(user.userId, pkg.packageId, packageVersionId)
78
+ : undefined;
79
+ for (const widget of widgets) {
80
+ entries.push({
81
+ key: `${pkg.packageId}:${widget.id}`,
82
+ packageId: pkg.packageId,
83
+ packageVersionId,
84
+ widget,
85
+ ...(bundle ? { bundle } : {}),
86
+ });
87
+ }
88
+ }
89
+ catch (error) {
90
+ console.warn(`Couldn't read ${pkg.packageId}'s global widgets`, error);
91
+ }
92
+ }
93
+ return entries;
94
+ }
95
+ /** Which widgets to draw, in which versions: when it's the same, nothing is drawn anew. */
96
+ function entriesKey(entries) {
97
+ return entries
98
+ .map(({ key, widget, packageVersionId, bundle }) => `${key}:${widget.peersUIId}:${packageVersionId}:${bundle ? bundle.uiBundleFileId : "window"}`)
99
+ .join("\n");
100
+ }
101
+ /** How long to wait for an idle moment before drawing the widgets anyway, in ms. */
102
+ const START_TIMEOUT_MS = 3_000;
103
+ /**
104
+ * Every global widget, each in a frame of its own over the window. The shell mounts it once,
105
+ * beside the root layout; it starts listing widgets at the first idle moment after the first
106
+ * screen has drawn, and again whenever which packages run in Personal changes.
107
+ */
108
+ function GlobalWidgetsLayer() {
109
+ const [entries, setEntries] = (0, react_1.useState)([]);
110
+ const [off] = (0, hooks_1.useObservable)(frame_permissions_1.globalWidgetsOff);
111
+ (0, react_1.useEffect)(() => {
112
+ let live = true;
113
+ let running = false;
114
+ let again = false;
115
+ let shownKey;
116
+ const refresh = async () => {
117
+ if (running) {
118
+ again = true;
119
+ return;
120
+ }
121
+ running = true;
122
+ do {
123
+ again = false;
124
+ try {
125
+ let next;
126
+ if (shownKey === undefined) {
127
+ // Start the first listing alongside the initial preference read. Later the SDK uses
128
+ // loadingPromise for saves, which mustn't hold up removing a stopped package.
129
+ [next] = await Promise.all([
130
+ listGlobalWidgets(),
131
+ frame_permissions_1.globalWidgetsOff.loadingPromise,
132
+ ]);
133
+ shownKey = "";
134
+ }
135
+ else {
136
+ next = await listGlobalWidgets();
137
+ }
138
+ if (!live || again)
139
+ continue;
140
+ const key = entriesKey(next);
141
+ if (key !== shownKey) {
142
+ shownKey = key;
143
+ setEntries(next);
144
+ (0, exports.listedGlobalWidgets)(next);
145
+ }
146
+ }
147
+ catch (error) {
148
+ console.warn("Couldn't list the global widgets", error);
149
+ }
150
+ } while (again && live);
151
+ running = false;
152
+ };
153
+ const start = () => {
154
+ if (!live)
155
+ return;
156
+ void (0, peers_sdk_1.getUserContext)().then((user) => {
157
+ // It also looks once right away.
158
+ if (live)
159
+ (0, piece_host_1.watchProviders)(user.userId, () => (live ? void refresh() : undefined));
160
+ });
161
+ };
162
+ // Safari has no requestIdleCallback.
163
+ const idle = typeof globalThis.requestIdleCallback === "function";
164
+ const handle = idle
165
+ ? globalThis.requestIdleCallback(start, { timeout: START_TIMEOUT_MS })
166
+ : setTimeout(start, START_TIMEOUT_MS / 3);
167
+ return () => {
168
+ live = false;
169
+ (0, exports.listedGlobalWidgets)([]);
170
+ if (idle)
171
+ globalThis.cancelIdleCallback(handle);
172
+ else
173
+ clearTimeout(handle);
174
+ };
175
+ }, []);
176
+ const hidden = new Set(Array.isArray(off) ? off : []);
177
+ return ((0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: entries
178
+ .filter((entry) => !hidden.has(entry.key))
179
+ .map((entry) => entry.bundle ? ((0, jsx_runtime_1.jsx)(GlobalWidgetFrame, { entry: entry, bundle: entry.bundle }, `${entry.key}:${entry.packageVersionId}:${entry.bundle.uiBundleFileId}`)) : ((0, jsx_runtime_1.jsx)(WindowWidget, { entry: entry }, `${entry.key}:${entry.packageVersionId}`))) }));
180
+ }
181
+ /**
182
+ * Where a widget's frame goes: over the whole window until it has measured itself and while it
183
+ * drags something; over its box once it has; a pixel in the corner while it draws nothing (a
184
+ * frame with no size may stop being rendered, and then never says it has something to draw).
185
+ *
186
+ * @param box - What it last said it covers: `undefined` before it said, `null` for nothing.
187
+ * @param dragging - Whether it holds the pointer.
188
+ * @param viewportWidth - The window's width.
189
+ * @param viewportHeight - The window's height.
190
+ */
191
+ function widgetPlacement(box, dragging, viewportWidth, viewportHeight) {
192
+ const viewport = { viewportWidth, viewportHeight };
193
+ if (dragging || box === undefined) {
194
+ return { x: 0, y: 0, width: viewportWidth, height: viewportHeight, ...viewport };
195
+ }
196
+ if (box === null)
197
+ return { x: 0, y: 0, width: 1, height: 1, ...viewport };
198
+ return { ...box, ...viewport };
199
+ }
200
+ /** The layer widgets draw on: above the apps and their dropdowns, below Peers' dialogs. */
201
+ const WIDGET_Z_INDEX = 1040;
202
+ /**
203
+ * Whether a UI id is the package's own: the window's loader finds a UI's package by its routes,
204
+ * so a widget drawn in the window must name a UI its own package's routes register.
205
+ *
206
+ * @param packageId - The package that declares the widget.
207
+ * @param peersUIId - The UI the widget names.
208
+ */
209
+ function ownsUI(packageId, peersUIId) {
210
+ const routes = window.getPeersUIRoutes?.() ?? [];
211
+ const owners = new Set(routes.filter((route) => route.peersUIId === peersUIId).map((route) => route.packageId));
212
+ return owners.size === 1 && owners.has(packageId);
213
+ }
214
+ /**
215
+ * A shared-window package's widget, drawn in the window as its screens are, by the window's UI
216
+ * loader. Its `position: fixed` already means the window.
217
+ */
218
+ function WindowWidget({ entry }) {
219
+ if (!ownsUI(entry.packageId, entry.widget.peersUIId)) {
220
+ console.warn(`${entry.packageId}'s widget ${entry.widget.id} names a UI its routes don't register`);
221
+ return null;
222
+ }
223
+ return ((0, jsx_runtime_1.jsx)("div", { className: "peers-global-widget", "data-peers-widget": entry.key, children: (0, jsx_runtime_1.jsx)(peers_sdk_1.PeersUI, { peersUIId: entry.widget.peersUIId }) }));
224
+ }
225
+ /** One widget's frame, placed over the box it covers. A widget that fails draws nothing. */
226
+ function GlobalWidgetFrame({ entry, bundle }) {
227
+ const [box, setBox] = (0, react_1.useState)(undefined);
228
+ const [dragging, setDragging] = (0, react_1.useState)(false);
229
+ const [failed, setFailed] = (0, react_1.useState)(false);
230
+ const [width] = (0, hooks_1.useObservable)(globals_1.windowWidth);
231
+ const [height] = (0, hooks_1.useObservable)(globals_1.windowHeight);
232
+ const placement = (0, react_1.useMemo)(() => widgetPlacement(box, dragging, width, height), [
233
+ box?.x,
234
+ box?.y,
235
+ box?.width,
236
+ box?.height,
237
+ box === null,
238
+ box === undefined,
239
+ dragging,
240
+ width,
241
+ height,
242
+ ]);
243
+ const events = (0, react_1.useMemo)(() => ({
244
+ onBox: setBox,
245
+ onCapture: setDragging,
246
+ onFailed: (message) => {
247
+ console.warn(`${bundle.pkg.name}'s widget ${entry.widget.id} failed: ${message}`);
248
+ setFailed(true);
249
+ },
250
+ }), [entry, bundle]);
251
+ const content = (0, react_1.useMemo)(() => ({
252
+ kind: "widget",
253
+ widgetId: entry.widget.id,
254
+ peersUIId: entry.widget.peersUIId,
255
+ props: {},
256
+ }), [entry.widget.id, entry.widget.peersUIId]);
257
+ const interactive = dragging || (box !== undefined && box !== null);
258
+ return ((0, jsx_runtime_1.jsx)("div", {
259
+ // Over the tab strip, a click reaches the widget instead of moving the desktop window; not
260
+ // while it takes no clicks, so the strip still moves the window there.
261
+ className: `peers-global-widget${interactive ? " peers-window-no-drag" : ""}`, "data-peers-widget": entry.key, hidden: failed, style: {
262
+ position: "fixed",
263
+ left: placement.x,
264
+ top: placement.y,
265
+ width: placement.width,
266
+ height: placement.height,
267
+ zIndex: WIDGET_Z_INDEX,
268
+ pointerEvents: interactive ? "auto" : "none",
269
+ }, children: (0, jsx_runtime_1.jsx)(isolated_screen_1.PackageFrame, { pkg: bundle.pkg, bundle: bundle, content: content, widget: { placement, events, interactive }, label: `${entry.widget.title} (${bundle.pkg.name})` }) }));
270
+ }
@@ -1,5 +1,6 @@
1
1
  import { type IContractPiece, type IPackage, type Observable } from "@peers-app/peers-sdk";
2
2
  import { type IPieceBundle } from "../ui-contracts/piece-host";
3
+ import { type IWidgetPlacement } from "./frame-protocol";
3
4
  /**
4
5
  * The host side of an isolated package screen: the frame, and everything the host does for it.
5
6
  *
@@ -26,12 +27,22 @@ interface IIsolatedScreenProps {
26
27
  /** The tab's path. */
27
28
  path: string;
28
29
  }
29
- /** What a package's frame shows: one of its screens, or one of its pieces for an embedder. */
30
+ /**
31
+ * What a package's frame shows: one of its screens, one of its pieces for an embedder, or one of
32
+ * its global widgets over the window.
33
+ */
30
34
  export type FrameContent = {
31
35
  kind: "screen";
32
36
  peersUIId: string;
33
37
  props: Record<string, unknown>;
34
38
  path: string;
39
+ } | {
40
+ kind: "widget";
41
+ /** The widget's id in its package. */
42
+ widgetId: string;
43
+ /** The UI that draws it. */
44
+ peersUIId: string;
45
+ props: Record<string, unknown>;
35
46
  } | {
36
47
  kind: "piece";
37
48
  /** The piece's key (`pieceKey`) under the version the provider implements. */
@@ -63,6 +74,23 @@ export interface IFramePieceEvents {
63
74
  /** A wheel over it that it didn't scroll with, in pixels: for the screen it's drawn over. */
64
75
  onWheel?(deltaX: number, deltaY: number): void;
65
76
  }
77
+ /** What a global widget's frame tells the layer that draws it. */
78
+ export interface IFrameWidgetEvents {
79
+ /**
80
+ * The box its content covers, in the window's coordinates, or null when it draws nothing;
81
+ * `undefined` when its frame went, so the next one hasn't measured itself yet.
82
+ */
83
+ onBox(box: {
84
+ x: number;
85
+ y: number;
86
+ width: number;
87
+ height: number;
88
+ } | null | undefined): void;
89
+ /** An element in it captured the pointer (a drag started), or let it go. */
90
+ onCapture(active: boolean): void;
91
+ /** It failed to load or threw. */
92
+ onFailed(message: string): void;
93
+ }
66
94
  /** A slot in a framed screen where one of the pieces it embeds is drawn, over the frame. */
67
95
  interface IPieceSlot {
68
96
  slotId: string;
@@ -105,6 +133,8 @@ declare class FrameSession {
105
133
  private readonly tabPath;
106
134
  private readonly disposers;
107
135
  private init?;
136
+ /** The commands this frame added to the host's palette, by their id there. */
137
+ private readonly commands;
108
138
  constructor(opts: {
109
139
  port: MessagePort;
110
140
  frameId: string;
@@ -114,6 +144,10 @@ declare class FrameSession {
114
144
  tabId: () => string | undefined;
115
145
  /** For a piece's frame: where its emits, close and size go. */
116
146
  pieceEvents: () => IFramePieceEvents | undefined;
147
+ /** For a global widget's frame: where its box and pointer capture go. */
148
+ widgetEvents: () => IFrameWidgetEvents | undefined;
149
+ /** For a global widget's frame: where the host has put it. */
150
+ widgetPlacement: () => IWidgetPlacement | undefined;
117
151
  /** The pieces this frame embeds, drawn over it by its component. */
118
152
  slots: Observable<IPieceSlot[]>;
119
153
  /** For a piece drawn over a framed screen's slot: that screen, and the slot. */
@@ -148,6 +182,15 @@ declare class FrameSession {
148
182
  */
149
183
  private mountPiece;
150
184
  private updateSlot;
185
+ /**
186
+ * Add one of the frame's commands to the host's palette, under its package's id and name. A
187
+ * shortcut another command has is refused, so a package can't take over ⌘K or another's keys.
188
+ */
189
+ private registerCommand;
190
+ /** Take one of this frame's commands out of the host's palette. */
191
+ private unregisterCommand;
192
+ /** A global widget's frame moved: it lays its content out again where it is now. */
193
+ placeWidget(placement: IWidgetPlacement): void;
151
194
  /** Tell a piece slot's frame what happened in its piece. */
152
195
  slotNotify(type: string, payload: Record<string, unknown>): void;
153
196
  /** Focus came to this piece's frame from its screen's slot: at its first or last control. */
@@ -188,6 +231,13 @@ export interface IPackageFrameProps {
188
231
  pieceEvents?: IFramePieceEvents;
189
232
  /** For a piece drawn over a framed screen's slot: that screen, and the slot. */
190
233
  slotOf?: SlotLink;
234
+ /** For a global widget: where the layer put its frame, and where its box and drags go. */
235
+ widget?: {
236
+ placement: IWidgetPlacement;
237
+ events: IFrameWidgetEvents;
238
+ /** Whether it takes clicks and focus now: not while it draws nothing or hasn't measured. */
239
+ interactive?: boolean;
240
+ };
191
241
  /** The frame's name, for screen readers. */
192
242
  label: string;
193
243
  }