@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 @@ exports.PackageFrame = PackageFrame;
5
5
  const jsx_runtime_1 = require("react/jsx-runtime");
6
6
  const peers_sdk_1 = require("@peers-app/peers-sdk");
7
7
  const react_1 = require("react");
8
+ const command_palette_1 = require("../command-palette/command-palette");
8
9
  const hooks_1 = require("../hooks");
9
10
  const host_shell_consumer_1 = require("../host-shell/host-shell-consumer");
10
11
  const mentions_client_1 = require("../mentions/mentions-client");
@@ -26,6 +27,102 @@ const piece_reach_1 = require("./piece-reach");
26
27
  const port_channel_1 = require("./port-channel");
27
28
  const screen_tab_context_1 = require("./screen-tab-context");
28
29
  const wheel_relay_1 = require("./wheel-relay");
30
+ /**
31
+ * A widget's reported box, kept inside the window: the frame says where it draws, and the host
32
+ * never places it off the window or bigger than it.
33
+ */
34
+ function insideWindow(rect) {
35
+ const x = Math.max(0, rect.x);
36
+ const y = Math.max(0, rect.y);
37
+ const right = Math.min(rect.x + rect.width, window.innerWidth);
38
+ const bottom = Math.min(rect.y + rect.height, window.innerHeight);
39
+ return right > x && bottom > y ? { x, y, width: right - x, height: bottom - y } : null;
40
+ }
41
+ /** Commands package frames added to the host's palette, by their id there: the frame that owns each. */
42
+ const frameCommandOwners = new Map();
43
+ /** A package command's id in the host's palette: its package's id and its own. */
44
+ function hostCommandId(packageId, commandId) {
45
+ return `package:${packageId}:${commandId}`;
46
+ }
47
+ /** Only shortcuts with ⌘ or Ctrl reach the host from a frame. */
48
+ const FRAME_SHORTCUT = /(^|\+)(cmd|command|meta|ctrl)\+./i;
49
+ /**
50
+ * Keys a package's shortcut can't use, with any modifiers: editing (select all, copy, cut, paste,
51
+ * undo, redo, find) and the browser's and the window's own (new, open, print, save, close, quit,
52
+ * reload, new tab, the address bar). A package command's shortcut works from every app, and the
53
+ * palette cancels the key's own action when it runs one.
54
+ */
55
+ const RESERVED_SHORTCUT_KEYS = new Set([
56
+ "a",
57
+ "c",
58
+ "x",
59
+ "v",
60
+ "z",
61
+ "y",
62
+ "f",
63
+ "n",
64
+ "o",
65
+ "p",
66
+ "s",
67
+ "w",
68
+ "q",
69
+ "r",
70
+ "t",
71
+ "l",
72
+ ]);
73
+ /**
74
+ * Keys that are modifiers themselves: as a shortcut's key (`Cmd+Meta`), the command would run on
75
+ * every press of ⌘ or Ctrl, before each of the person's other shortcuts.
76
+ */
77
+ const MODIFIER_KEYS = new Set([
78
+ "meta",
79
+ "cmd",
80
+ "command",
81
+ "ctrl",
82
+ "control",
83
+ "alt",
84
+ "option",
85
+ "altgraph",
86
+ "shift",
87
+ "os",
88
+ ]);
89
+ /** A shortcut's key, without its modifiers: `Cmd+Shift+K` → `k`. */
90
+ function shortcutKey(shortcut) {
91
+ return (shortcut.split("+").pop() ?? "").trim().toLowerCase();
92
+ }
93
+ /** A command as a frame sends it, refused unless it's what {@link IFrameCommand} says. */
94
+ function toFrameCommand(value) {
95
+ const command = value;
96
+ const text = (key, max, required = false) => {
97
+ const field = command?.[key];
98
+ if (field === undefined && !required)
99
+ return undefined;
100
+ if (typeof field !== "string" || !field.trim() || field.length > max) {
101
+ throw new Error(`A command's ${key} must be text of 1 to ${max} characters`);
102
+ }
103
+ return field;
104
+ };
105
+ const id = text("id", 80, true);
106
+ const shortcut = text("shortcut", 40);
107
+ if (shortcut !== undefined && !FRAME_SHORTCUT.test(shortcut)) {
108
+ throw new Error(`A package's shortcut needs ⌘ or Ctrl: ${shortcut}`);
109
+ }
110
+ if (shortcut !== undefined && MODIFIER_KEYS.has(shortcutKey(shortcut))) {
111
+ throw new Error(`A package's shortcut needs a key besides ⌘, Ctrl, Alt and Shift: ${shortcut}`);
112
+ }
113
+ if (shortcut !== undefined && RESERVED_SHORTCUT_KEYS.has(shortcutKey(shortcut))) {
114
+ throw new Error(`${shortcut} is kept for editing and the browser`);
115
+ }
116
+ const description = text("description", 200);
117
+ const iconClassName = text("iconClassName", 80);
118
+ return {
119
+ id,
120
+ label: text("label", 100, true),
121
+ ...(description === undefined ? {} : { description }),
122
+ ...(shortcut === undefined ? {} : { shortcut }),
123
+ ...(iconClassName === undefined ? {} : { iconClassName }),
124
+ };
125
+ }
29
126
  /** A rectangle as a frame reports it, refused unless it's four finite numbers. */
30
127
  function toRect(value) {
31
128
  const r = value;
@@ -137,6 +234,8 @@ class FrameSession {
137
234
  tabPath = (0, peers_sdk_1.observable)("");
138
235
  disposers = [];
139
236
  init;
237
+ /** The commands this frame added to the host's palette, by their id there. */
238
+ commands = new Set();
140
239
  constructor(opts) {
141
240
  this.opts = opts;
142
241
  const { pkg } = opts;
@@ -292,6 +391,35 @@ class FrameSession {
292
391
  channel.onNotify(frame_protocol_1.FrameNotice.failed, ({ message }) => {
293
392
  console.error(`[${pkg.name}] failed: ${String(message)}`);
294
393
  opts.pieceEvents()?.onFailed(String(message));
394
+ opts.widgetEvents()?.onFailed(String(message));
395
+ });
396
+ // A global widget's frame: the box it covers and its drags go to the layer that draws it.
397
+ channel.onNotify(frame_protocol_1.FrameNotice.widgetBox, ({ box }) => {
398
+ const events = opts.widgetEvents();
399
+ if (!events)
400
+ return;
401
+ if (box === null)
402
+ events.onBox(null);
403
+ else {
404
+ const rect = toRect(box);
405
+ if (rect && rect.width >= 0 && rect.height >= 0)
406
+ events.onBox(insideWindow(rect));
407
+ }
408
+ });
409
+ channel.onNotify(frame_protocol_1.FrameNotice.widgetCapture, ({ active }) => {
410
+ opts.widgetEvents()?.onCapture(active === true);
411
+ });
412
+ // The package's commands, in the host's palette under its name.
413
+ channel.onRequest(frame_protocol_1.FrameRequest.commandRegister, (command) => this.registerCommand(command));
414
+ channel.onRequest(frame_protocol_1.FrameRequest.commandUnregister, ({ id }) => {
415
+ if (typeof id === "string")
416
+ this.unregisterCommand(hostCommandId(pkg.packageId, id));
417
+ });
418
+ channel.onRequest(frame_protocol_1.FrameRequest.commandRun, ({ id }) => {
419
+ const hostId = typeof id === "string" ? hostCommandId(pkg.packageId, id) : "";
420
+ if (!(0, command_palette_1.getCommand)(hostId))
421
+ throw new Error(`${pkg.name} has no command ${String(id)}`);
422
+ (0, command_palette_1.executeCommand)(hostId);
295
423
  });
296
424
  // A piece's frame: its emits, close and size go to its embedder.
297
425
  channel.onNotify(frame_protocol_1.FrameNotice.pieceEmit, ({ name, payload }) => {
@@ -464,6 +592,50 @@ class FrameSession {
464
592
  next[index] = change(slots[index]);
465
593
  this.opts.slots(next);
466
594
  }
595
+ /**
596
+ * Add one of the frame's commands to the host's palette, under its package's id and name. A
597
+ * shortcut another command has is refused, so a package can't take over ⌘K or another's keys.
598
+ */
599
+ registerCommand(value) {
600
+ const { pkg } = this.opts;
601
+ const command = toFrameCommand(value);
602
+ const hostId = hostCommandId(pkg.packageId, command.id);
603
+ if (command.shortcut) {
604
+ const taken = (0, command_palette_1.commandForShortcut)(command.shortcut);
605
+ if (taken && taken.id !== hostId) {
606
+ throw new Error(`${command.shortcut} is already the shortcut for ${taken.label}`);
607
+ }
608
+ }
609
+ const commandId = command.id;
610
+ (0, command_palette_1.registerCommand)({
611
+ id: hostId,
612
+ label: command.label,
613
+ ...(command.description === undefined ? {} : { description: command.description }),
614
+ ...(command.shortcut === undefined ? {} : { shortcut: command.shortcut }),
615
+ ...(command.iconClassName === undefined ? {} : { iconClassName: command.iconClassName }),
616
+ category: pkg.name,
617
+ action: () => frameCommandOwners.get(hostId)?.channel.notify(frame_protocol_1.HostNotice.commandRun, { id: commandId }),
618
+ });
619
+ // Another of the package's frames may have added it before: the latest one runs it now.
620
+ frameCommandOwners.get(hostId)?.commands.delete(hostId);
621
+ frameCommandOwners.set(hostId, this);
622
+ this.commands.add(hostId);
623
+ }
624
+ /** Take one of this frame's commands out of the host's palette. */
625
+ unregisterCommand(hostId) {
626
+ if (frameCommandOwners.get(hostId) !== this)
627
+ return;
628
+ frameCommandOwners.delete(hostId);
629
+ this.commands.delete(hostId);
630
+ (0, command_palette_1.unregisterCommand)(hostId);
631
+ }
632
+ /** A global widget's frame moved: it lays its content out again where it is now. */
633
+ placeWidget(placement) {
634
+ if (this.frameReady)
635
+ this.channel.notify(frame_protocol_1.HostNotice.widgetPlacement, placement);
636
+ else if (this.init?.widget)
637
+ this.init.widget.placement = placement;
638
+ }
467
639
  /** Tell a piece slot's frame what happened in its piece. */
468
640
  slotNotify(type, payload) {
469
641
  this.channel.notify(type, payload);
@@ -494,17 +666,33 @@ class FrameSession {
494
666
  bundleCode: this.opts.bundle.code,
495
667
  ...(content.kind === "screen"
496
668
  ? { peersUIId: content.peersUIId, path: content.path }
497
- : {
498
- path: "",
499
- piece: {
500
- key: content.key,
501
- groupId: content.groupId,
502
- height: content.height,
503
- ...(content.width !== undefined ? { width: content.width } : {}),
504
- ...(content.emits ? { emits: content.emits } : {}),
505
- ...(this.opts.slotOf?.() ? { overSlot: true } : {}),
506
- },
507
- }),
669
+ : content.kind === "widget"
670
+ ? {
671
+ peersUIId: content.peersUIId,
672
+ path: "",
673
+ widget: {
674
+ id: content.widgetId,
675
+ placement: this.opts.widgetPlacement() ?? {
676
+ x: 0,
677
+ y: 0,
678
+ width: window.innerWidth,
679
+ height: window.innerHeight,
680
+ viewportWidth: window.innerWidth,
681
+ viewportHeight: window.innerHeight,
682
+ },
683
+ },
684
+ }
685
+ : {
686
+ path: "",
687
+ piece: {
688
+ key: content.key,
689
+ groupId: content.groupId,
690
+ height: content.height,
691
+ ...(content.width !== undefined ? { width: content.width } : {}),
692
+ ...(content.emits ? { emits: content.emits } : {}),
693
+ ...(this.opts.slotOf?.() ? { overSlot: true } : {}),
694
+ },
695
+ }),
508
696
  props: content.props,
509
697
  colorMode: (0, color_mode_dropdown_1.colorMode)() === "light" ? "light" : "dark",
510
698
  storage,
@@ -536,6 +724,8 @@ class FrameSession {
536
724
  return this.init !== undefined;
537
725
  }
538
726
  dispose() {
727
+ for (const hostId of [...this.commands])
728
+ this.unregisterCommand(hostId);
539
729
  liveSessions.delete(this);
540
730
  if (!liveSessions.size)
541
731
  document.removeEventListener("mousedown", relayHostPointers, true);
@@ -578,10 +768,12 @@ function PackageFrameElement(props) {
578
768
  tabIdRef.current = props.tabId;
579
769
  const eventsRef = (0, react_1.useRef)(props.pieceEvents);
580
770
  eventsRef.current = props.pieceEvents;
771
+ const widgetRef = (0, react_1.useRef)(props.widget);
772
+ widgetRef.current = props.widget;
581
773
  const frameRef = (0, react_1.useRef)(null);
582
774
  const sessionRef = (0, react_1.useRef)();
583
775
  const [frameId] = (0, react_1.useState)(() => (0, peers_sdk_1.newid)());
584
- const [srcDoc] = (0, react_1.useState)(() => (0, frame_document_1.frameDocument)((0, color_mode_dropdown_1.colorMode)() === "light" ? "light" : "dark", content.kind === "piece"));
776
+ const [srcDoc] = (0, react_1.useState)(() => (0, frame_document_1.frameDocument)((0, color_mode_dropdown_1.colorMode)() === "light" ? "light" : "dark", content.kind !== "screen"));
585
777
  const [failure, setFailure] = (0, react_1.useState)();
586
778
  const [slots] = (0, react_1.useState)(() => (0, peers_sdk_1.observable)([]));
587
779
  const [shownSlots] = (0, hooks_1.useObservable)(slots);
@@ -622,6 +814,8 @@ function PackageFrameElement(props) {
622
814
  const message = error instanceof Error ? error.message : String(error);
623
815
  if (eventsRef.current)
624
816
  eventsRef.current.onFailed(message);
817
+ else if (widgetRef.current)
818
+ widgetRef.current.events.onFailed(message);
625
819
  else
626
820
  setFailure(message);
627
821
  return;
@@ -637,6 +831,8 @@ function PackageFrameElement(props) {
637
831
  bundle,
638
832
  tabId: () => tabIdRef.current,
639
833
  pieceEvents: () => eventsRef.current,
834
+ widgetEvents: () => widgetRef.current?.events,
835
+ widgetPlacement: () => widgetRef.current?.placement,
640
836
  slots,
641
837
  slotOf: () => latest.current.slotOf?.(),
642
838
  restart: () => onReplaced.current(),
@@ -655,6 +851,11 @@ function PackageFrameElement(props) {
655
851
  sessionRef.current?.dispose();
656
852
  sessionRef.current = undefined;
657
853
  slots([]);
854
+ // A widget's box and its hold on the pointer were this frame's: the frame that replaces it
855
+ // (its document was replaced, or a new version came) starts unmeasured, as a first
856
+ // one does, and can't inherit a drag it never saw end.
857
+ widgetRef.current?.events.onCapture(false);
858
+ widgetRef.current?.events.onBox(undefined);
658
859
  };
659
860
  }, [frameId, slots]);
660
861
  // Another UI of the package, new props or a new path: the same frame shows it.
@@ -666,6 +867,12 @@ function PackageFrameElement(props) {
666
867
  session.setPath(content.path);
667
868
  void session.show(() => latest.current.content);
668
869
  }, [content]);
870
+ // A global widget's frame moved: it lays its content out again where it is now.
871
+ const placement = props.widget?.placement;
872
+ (0, react_1.useEffect)(() => {
873
+ if (placement)
874
+ sessionRef.current?.placeWidget(placement);
875
+ }, [placement]);
669
876
  if (failure !== undefined) {
670
877
  return ((0, jsx_runtime_1.jsx)("div", { className: "p-3", children: (0, jsx_runtime_1.jsxs)("div", { className: "alert alert-danger", children: [(0, jsx_runtime_1.jsxs)("div", { className: "fw-semibold", children: [pkg.name, " couldn't start."] }), (0, jsx_runtime_1.jsx)("div", { className: "small text-break", children: failure }), (0, jsx_runtime_1.jsx)("button", { type: "button", className: "btn btn-sm btn-outline-danger mt-2", onClick: props.onReplaced, children: "Retry" })] }) }));
671
878
  }
@@ -675,7 +882,11 @@ function PackageFrameElement(props) {
675
882
  height: "100%",
676
883
  display: "block",
677
884
  };
678
- let frameClass = content.kind === "screen" ? "peers-screen-frame" : "peers-piece-frame";
885
+ let frameClass = content.kind === "screen"
886
+ ? "peers-screen-frame"
887
+ : content.kind === "widget"
888
+ ? "peers-widget-frame"
889
+ : "peers-piece-frame";
679
890
  if (content.kind === "piece" && content.width !== undefined) {
680
891
  // PopoverSurface positions the picker over other content and supplies no background. Over a
681
892
  // slot the frame stays clear until the piece paints its own on its first render, so the
@@ -689,7 +900,10 @@ function PackageFrameElement(props) {
689
900
  frameStyle.top = 0;
690
901
  frameStyle.left = 0;
691
902
  }
692
- return ((0, jsx_runtime_1.jsxs)("div", { className: "peers-package-frame", style: { position: "relative", width: "100%", height: "100%", overflow: FRAME_OVERFLOW }, children: [(0, jsx_runtime_1.jsx)("iframe", { ref: frameRef, title: props.label, tabIndex: props.slotOf ? -1 : undefined, srcDoc: srcDoc, sandbox: "allow-scripts allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-downloads", allow: "clipboard-read; clipboard-write; fullscreen; autoplay", "data-peers-frame": frameId, "data-peers-package": pkg.packageId, className: frameClass, style: frameStyle }), shownSlots.map((slot) => ((0, jsx_runtime_1.jsx)(PieceSlotFrame, { slot: slot, session: sessionRef }, slot.slotId)))] }));
903
+ return ((0, jsx_runtime_1.jsxs)("div", { className: "peers-package-frame", style: { position: "relative", width: "100%", height: "100%", overflow: FRAME_OVERFLOW }, children: [(0, jsx_runtime_1.jsx)("iframe", { ref: frameRef, title: props.label,
904
+ // Over a slot, the slot takes Tab in the piece's place and hands focus in; a widget that
905
+ // draws nothing is no Tab stop.
906
+ tabIndex: props.slotOf || (props.widget && !props.widget.interactive) ? -1 : undefined, srcDoc: srcDoc, sandbox: "allow-scripts allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-downloads", allow: "clipboard-read; clipboard-write; fullscreen; autoplay", "data-peers-frame": frameId, "data-peers-package": pkg.packageId, className: frameClass, style: frameStyle }), shownSlots.map((slot) => ((0, jsx_runtime_1.jsx)(PieceSlotFrame, { slot: slot, session: sessionRef }, slot.slotId)))] }));
693
907
  }
694
908
  /**
695
909
  * A piece a framed screen embeds, drawn over the slot the screen reports: a frame of its own,
@@ -1,3 +1,27 @@
1
+ /** What Peers reads from a version's stored manifest, without running any of its code. */
2
+ export interface IStoredManifest {
3
+ packageId: string;
4
+ version: string;
5
+ uiConsumes?: {
6
+ contractId: string;
7
+ version: number;
8
+ }[];
9
+ uiProvides?: {
10
+ contractId: string;
11
+ version: number;
12
+ alsoImplements?: never[];
13
+ }[];
14
+ globalWidgets?: unknown;
15
+ }
16
+ /**
17
+ * The manifest this device stored for a package version, when it has one that matches the
18
+ * version's row (its format, package, bundle hash and version); `undefined` otherwise, as for a
19
+ * folder-loaded build that was never stored.
20
+ *
21
+ * @param dataContextId - The context the version's row is in: a group, or the user's id.
22
+ * @param packageVersionId - The version.
23
+ */
24
+ export declare function readStoredManifest(dataContextId: string, packageVersionId: string): Promise<IStoredManifest | undefined>;
1
25
  /**
2
26
  * Whether the screen's package version declares a UI contract version.
3
27
  *
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readStoredManifest = readStoredManifest;
3
4
  exports.consumesUIContract = consumesUIContract;
4
5
  const peers_sdk_1 = require("@peers-app/peers-sdk");
5
6
  /**
@@ -10,17 +11,24 @@ const peers_sdk_1 = require("@peers-app/peers-sdk");
10
11
  * promoting it stores its manifest under the same version id.
11
12
  */
12
13
  const known = new Map();
13
- /** The UI contract versions a manifest declares, or undefined when there's no manifest to read. */
14
- async function readDeclared(bundle) {
14
+ /**
15
+ * The manifest this device stored for a package version, when it has one that matches the
16
+ * version's row (its format, package, bundle hash and version); `undefined` otherwise, as for a
17
+ * folder-loaded build that was never stored.
18
+ *
19
+ * @param dataContextId - The context the version's row is in: a group, or the user's id.
20
+ * @param packageVersionId - The version.
21
+ */
22
+ async function readStoredManifest(dataContextId, packageVersionId) {
15
23
  const user = await (0, peers_sdk_1.getUserContext)();
16
- const dataContext = bundle.dataContextId === user.userId
24
+ const dataContext = dataContextId === user.userId
17
25
  ? user.userDataContext
18
- : user.groupDataContexts.get(bundle.dataContextId);
26
+ : user.groupDataContexts.get(dataContextId);
19
27
  if (!dataContext)
20
- throw new Error("The screen's package group is no longer available");
28
+ throw new Error("The package's group is no longer available");
21
29
  const [pv, row] = await Promise.all([
22
- (0, peers_sdk_1.PackageVersions)(dataContext).get(bundle.packageVersionId),
23
- (0, peers_sdk_1.PackageVersionManifests)(dataContext).get(bundle.packageVersionId),
30
+ (0, peers_sdk_1.PackageVersions)(dataContext).get(packageVersionId),
31
+ (0, peers_sdk_1.PackageVersionManifests)(dataContext).get(packageVersionId),
24
32
  ]);
25
33
  if (!pv ||
26
34
  !row ||
@@ -30,7 +38,15 @@ async function readDeclared(bundle) {
30
38
  return undefined;
31
39
  }
32
40
  const manifest = JSON.parse(row.manifest);
33
- if (!manifest || manifest.packageId !== pv.packageId || manifest.version !== pv.version)
41
+ if (!manifest || manifest.packageId !== pv.packageId || manifest.version !== pv.version) {
42
+ return undefined;
43
+ }
44
+ return manifest;
45
+ }
46
+ /** The UI contract versions a manifest declares, or undefined when there's no manifest to read. */
47
+ async function readDeclared(bundle) {
48
+ const manifest = await readStoredManifest(bundle.dataContextId, bundle.packageVersionId);
49
+ if (!manifest)
34
50
  return undefined;
35
51
  const declared = new Set();
36
52
  for (const entry of manifest.uiConsumes ?? [])
@@ -0,0 +1,48 @@
1
+ import { type IWidgetPlacement } from "./frame-protocol";
2
+ import type { IPortChannel } from "./port-channel";
3
+ /**
4
+ * A global widget's frame, measuring what it draws: the host places the frame over just that
5
+ * box, so the rest of the window stays the apps'.
6
+ *
7
+ * The box is the union of what's painted: elements with a background, a border, a shadow, text
8
+ * of their own, or that are controls, images or media; a box that clips its content (a scroll
9
+ * box) counts whole and isn't looked into. A `position: fixed` element that takes clicks counts
10
+ * too, painted or not: a menu's transparent click-catcher over the window is there to take the
11
+ * click that closes the menu. Layout-only containers aren't counted, so a full-width wrapper
12
+ * around a corner button doesn't make the box the window's width. The box grows by
13
+ * {@link BOX_MARGIN} for shadows, and is reported in the window's coordinates.
14
+ */
15
+ /** A rectangle in the window's coordinates. */
16
+ export interface IWidgetBox {
17
+ x: number;
18
+ y: number;
19
+ width: number;
20
+ height: number;
21
+ }
22
+ /** Room around what's painted, in px, for shadows and focus rings. */
23
+ export declare const BOX_MARGIN = 8;
24
+ /**
25
+ * The box a frame's content covers, in the frame's viewport coordinates, or `undefined` when it
26
+ * draws nothing.
27
+ *
28
+ * @param root - Where to look: the frame's body.
29
+ */
30
+ export declare function paintedBox(root: Element): IWidgetBox | undefined;
31
+ /**
32
+ * The box to report: what's painted, moved into the window's coordinates by where the frame is,
33
+ * grown by the margin, rounded out to whole pixels and kept inside the window.
34
+ *
35
+ * @param painted - From {@link paintedBox}.
36
+ * @param placement - Where the host put the frame.
37
+ */
38
+ export declare function windowBox(painted: IWidgetBox | undefined, placement: IWidgetPlacement): IWidgetBox | null;
39
+ /**
40
+ * In a global widget's frame: report the box its content covers whenever it may have changed (the
41
+ * DOM or a style changed, the frame moved or resized, a transition ended), and when an element in
42
+ * it captures the pointer or lets it go. Mutations, not animation frames, drive it: a browser may
43
+ * stop rendering a frame that shows next to nothing.
44
+ *
45
+ * @param host - The channel to the host.
46
+ * @param where - Where the host has put the frame now.
47
+ */
48
+ export declare function startWidgetBoxReports(host: IPortChannel, where: () => IWidgetPlacement | undefined): () => void;
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BOX_MARGIN = void 0;
4
+ exports.paintedBox = paintedBox;
5
+ exports.windowBox = windowBox;
6
+ exports.startWidgetBoxReports = startWidgetBoxReports;
7
+ const frame_protocol_1 = require("./frame-protocol");
8
+ /** Room around what's painted, in px, for shadows and focus rings. */
9
+ exports.BOX_MARGIN = 8;
10
+ /** Elements past this many aren't looked at: a widget that big is measured by what's found. */
11
+ const MAX_ELEMENTS = 3000;
12
+ /** Elements that paint by being what they are. */
13
+ const PAINTED_TAGS = new Set([
14
+ "IMG",
15
+ "SVG",
16
+ "CANVAS",
17
+ "VIDEO",
18
+ "AUDIO",
19
+ "IFRAME",
20
+ "INPUT",
21
+ "TEXTAREA",
22
+ "SELECT",
23
+ "BUTTON",
24
+ "PROGRESS",
25
+ "METER",
26
+ "HR",
27
+ ]);
28
+ function transparent(color) {
29
+ return (color === "transparent" ||
30
+ color === "" ||
31
+ /^rgba\(.*,\s*0\)$/.test(color) ||
32
+ /^rgba\(.*\/\s*0\)$/.test(color));
33
+ }
34
+ function hasOwnText(element) {
35
+ for (const node of element.childNodes) {
36
+ if (node.nodeType === Node.TEXT_NODE && node.textContent?.trim())
37
+ return true;
38
+ }
39
+ return false;
40
+ }
41
+ function paints(element, style) {
42
+ if (PAINTED_TAGS.has(element.tagName.toUpperCase()))
43
+ return true;
44
+ if (style.position === "fixed" && style.pointerEvents !== "none")
45
+ return true;
46
+ const image = style.backgroundImage;
47
+ if (!transparent(style.backgroundColor) || (image !== "" && image !== "none"))
48
+ return true;
49
+ if (style.boxShadow !== "none" && style.boxShadow !== "")
50
+ return true;
51
+ for (const side of ["Top", "Right", "Bottom", "Left"]) {
52
+ const width = Number.parseFloat(style[`border${side}Width`]);
53
+ if (width > 0 && style[`border${side}Style`] !== "none")
54
+ return true;
55
+ }
56
+ return hasOwnText(element);
57
+ }
58
+ /** Overflow values that cut what's outside the box. */
59
+ const CLIPPING = new Set(["hidden", "clip", "auto", "scroll"]);
60
+ function clips(style) {
61
+ return (CLIPPING.has(style.overflowX) || CLIPPING.has(style.overflowY) || CLIPPING.has(style.overflow));
62
+ }
63
+ /**
64
+ * The box a frame's content covers, in the frame's viewport coordinates, or `undefined` when it
65
+ * draws nothing.
66
+ *
67
+ * @param root - Where to look: the frame's body.
68
+ */
69
+ function paintedBox(root) {
70
+ let left = Number.POSITIVE_INFINITY;
71
+ let top = Number.POSITIVE_INFINITY;
72
+ let right = Number.NEGATIVE_INFINITY;
73
+ let bottom = Number.NEGATIVE_INFINITY;
74
+ let seen = 0;
75
+ const add = (rect) => {
76
+ if (rect.width <= 0 || rect.height <= 0)
77
+ return;
78
+ left = Math.min(left, rect.left);
79
+ top = Math.min(top, rect.top);
80
+ right = Math.max(right, rect.right);
81
+ bottom = Math.max(bottom, rect.bottom);
82
+ };
83
+ const visitChildren = (parent) => {
84
+ for (const element of parent.children) {
85
+ if (seen >= MAX_ELEMENTS)
86
+ return;
87
+ seen++;
88
+ const tag = element.tagName.toUpperCase();
89
+ if (tag === "SCRIPT" || tag === "STYLE" || tag === "TEMPLATE")
90
+ continue;
91
+ const style = getComputedStyle(element);
92
+ if (style.display === "none" || style.visibility === "hidden")
93
+ continue;
94
+ if (Number.parseFloat(style.opacity) === 0)
95
+ continue;
96
+ const rect = element.getBoundingClientRect();
97
+ if (clips(style) && rect.width > 0 && rect.height > 0) {
98
+ add(rect);
99
+ continue;
100
+ }
101
+ if (paints(element, style))
102
+ add(rect);
103
+ visitChildren(element);
104
+ }
105
+ };
106
+ visitChildren(root);
107
+ if (left === Number.POSITIVE_INFINITY)
108
+ return undefined;
109
+ return { x: left, y: top, width: right - left, height: bottom - top };
110
+ }
111
+ /**
112
+ * The box to report: what's painted, moved into the window's coordinates by where the frame is,
113
+ * grown by the margin, rounded out to whole pixels and kept inside the window.
114
+ *
115
+ * @param painted - From {@link paintedBox}.
116
+ * @param placement - Where the host put the frame.
117
+ */
118
+ function windowBox(painted, placement) {
119
+ if (!painted)
120
+ return null;
121
+ const left = Math.max(0, Math.floor(painted.x + placement.x - exports.BOX_MARGIN));
122
+ const top = Math.max(0, Math.floor(painted.y + placement.y - exports.BOX_MARGIN));
123
+ const right = Math.min(placement.viewportWidth, Math.ceil(painted.x + placement.x + painted.width + exports.BOX_MARGIN));
124
+ const bottom = Math.min(placement.viewportHeight, Math.ceil(painted.y + placement.y + painted.height + exports.BOX_MARGIN));
125
+ if (right <= left || bottom <= top)
126
+ return null;
127
+ return { x: left, y: top, width: right - left, height: bottom - top };
128
+ }
129
+ /** How soon after a change the box is measured again, in ms: changes in a burst measure once. */
130
+ const MEASURE_DELAY_MS = 16;
131
+ /**
132
+ * In a global widget's frame: report the box its content covers whenever it may have changed (the
133
+ * DOM or a style changed, the frame moved or resized, a transition ended), and when an element in
134
+ * it captures the pointer or lets it go. Mutations, not animation frames, drive it: a browser may
135
+ * stop rendering a frame that shows next to nothing.
136
+ *
137
+ * @param host - The channel to the host.
138
+ * @param where - Where the host has put the frame now.
139
+ */
140
+ function startWidgetBoxReports(host, where) {
141
+ let last = "";
142
+ let timer;
143
+ const measure = () => {
144
+ timer = undefined;
145
+ const placement = where();
146
+ if (!placement)
147
+ return;
148
+ const box = windowBox(paintedBox(document.body), placement);
149
+ const key = JSON.stringify(box);
150
+ if (key === last)
151
+ return;
152
+ last = key;
153
+ host.notify(frame_protocol_1.FrameNotice.widgetBox, { box });
154
+ };
155
+ const soon = () => {
156
+ if (timer === undefined)
157
+ timer = setTimeout(measure, MEASURE_DELAY_MS);
158
+ };
159
+ // The body's own style changes when the host moves the frame: measured again too.
160
+ const mutations = new MutationObserver(soon);
161
+ mutations.observe(document.body, {
162
+ subtree: true,
163
+ childList: true,
164
+ attributes: true,
165
+ characterData: true,
166
+ });
167
+ const resizes = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(soon);
168
+ resizes?.observe(document.body);
169
+ window.addEventListener("resize", soon);
170
+ window.addEventListener("transitionend", soon, true);
171
+ // An image getting its size changes no DOM, but its box. Its load doesn't bubble, and never
172
+ // reaches the window, even while capturing: the document's capture sees it. (A video sends
173
+ // `loadedmetadata` instead, which isn't listened for.)
174
+ document.addEventListener("load", soon, true);
175
+ window.addEventListener("animationend", soon, true);
176
+ const captured = () => host.notify(frame_protocol_1.FrameNotice.widgetCapture, { active: true });
177
+ const released = () => host.notify(frame_protocol_1.FrameNotice.widgetCapture, { active: false });
178
+ window.addEventListener("gotpointercapture", captured, true);
179
+ window.addEventListener("lostpointercapture", released, true);
180
+ soon();
181
+ return () => {
182
+ if (timer !== undefined)
183
+ clearTimeout(timer);
184
+ mutations.disconnect();
185
+ resizes?.disconnect();
186
+ window.removeEventListener("resize", soon);
187
+ window.removeEventListener("transitionend", soon, true);
188
+ document.removeEventListener("load", soon, true);
189
+ window.removeEventListener("animationend", soon, true);
190
+ window.removeEventListener("gotpointercapture", captured, true);
191
+ window.removeEventListener("lostpointercapture", released, true);
192
+ };
193
+ }