@peers-app/peers-ui 0.34.6 → 0.34.8

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 (56) 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/components/markdown-editor/editor.d.ts +5 -4
  7. package/dist/components/markdown-editor/editor.js +10 -145
  8. package/dist/components/markdown-editor/lexical-editor.d.ts +3 -0
  9. package/dist/components/markdown-editor/lexical-editor.js +153 -0
  10. package/dist/components/markdown-render.d.ts +8 -0
  11. package/dist/components/markdown-render.js +143 -0
  12. package/dist/components/markdown-with-mentions.d.ts +1 -1
  13. package/dist/components/markdown-with-mentions.js +7 -129
  14. package/dist/components/trust-level-dropdown.d.ts +6 -1
  15. package/dist/components/trust-level-dropdown.js +43 -14
  16. package/dist/globals.d.ts +13 -2
  17. package/dist/globals.js +24 -2
  18. package/dist/index.d.ts +2 -1
  19. package/dist/index.js +9 -1
  20. package/dist/isolated-screens/config.js +1 -5
  21. package/dist/isolated-screens/focus-relay.d.ts +24 -0
  22. package/dist/isolated-screens/focus-relay.js +104 -0
  23. package/dist/isolated-screens/frame-document.d.ts +7 -0
  24. package/dist/isolated-screens/frame-document.js +11 -1
  25. package/dist/isolated-screens/frame-permissions.d.ts +11 -0
  26. package/dist/isolated-screens/frame-permissions.js +33 -0
  27. package/dist/isolated-screens/frame-protocol.d.ts +90 -0
  28. package/dist/isolated-screens/frame-protocol.js +49 -0
  29. package/dist/isolated-screens/frame-runtime.js +115 -16
  30. package/dist/isolated-screens/frame-viewport.d.ts +9 -0
  31. package/dist/isolated-screens/frame-viewport.js +36 -0
  32. package/dist/isolated-screens/global-widgets.d.ts +74 -0
  33. package/dist/isolated-screens/global-widgets.js +270 -0
  34. package/dist/isolated-screens/isolated-screen.d.ts +57 -1
  35. package/dist/isolated-screens/isolated-screen.js +266 -15
  36. package/dist/isolated-screens/piece-frames.js +57 -5
  37. package/dist/isolated-screens/piece-reach.d.ts +24 -0
  38. package/dist/isolated-screens/piece-reach.js +40 -13
  39. package/dist/isolated-screens/widget-box.d.ts +48 -0
  40. package/dist/isolated-screens/widget-box.js +193 -0
  41. package/dist/lazy-module.d.ts +17 -0
  42. package/dist/lazy-module.js +26 -0
  43. package/dist/operator-console/console-session.js +1 -9
  44. package/dist/operator-console/operator-console-state.js +5 -1
  45. package/dist/root-layout/root-layout-host.js +3 -1
  46. package/dist/screens/groups/group-members.js +7 -17
  47. package/dist/screens/invites/accept-invite.js +15 -4
  48. package/dist/screens/packages/package-info.js +2 -1
  49. package/dist/screens/packages/package-widgets-panel.d.ts +15 -0
  50. package/dist/screens/packages/package-widgets-panel.js +64 -0
  51. package/dist/tabs-layout/tabs-state.d.ts +5 -2
  52. package/dist/tabs-layout/tabs-state.js +41 -17
  53. package/dist/ui-contracts/piece-height.d.ts +8 -2
  54. package/dist/ui-contracts/piece-height.js +6 -1
  55. package/dist/ui-contracts/piece.js +1 -1
  56. package/package.json +4 -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 }) => {
@@ -299,6 +427,28 @@ class FrameSession {
299
427
  opts.pieceEvents()?.onEmit(name, payload);
300
428
  });
301
429
  channel.onNotify(frame_protocol_1.FrameNotice.pieceClose, () => opts.pieceEvents()?.onClose());
430
+ channel.onNotify(frame_protocol_1.FrameNotice.pieceDrawn, () => opts.pieceEvents()?.onDrawn?.());
431
+ // Tab across a piece over a slot: in from the screen, and back out to it.
432
+ channel.onNotify(frame_protocol_1.FrameNotice.pieceFocus, (payload) => {
433
+ // The user can move to another frame or a window control before the notice arrives.
434
+ if (document.activeElement !== opts.element)
435
+ return;
436
+ const edge = payload?.edge === "last" ? "last" : "first";
437
+ for (const session of liveSessions) {
438
+ const link = session.opts.slotOf?.();
439
+ if (link?.session === this && link.slotId === payload?.slotId)
440
+ session.focusFrom(edge);
441
+ }
442
+ });
443
+ channel.onNotify(frame_protocol_1.FrameNotice.focusLeave, (payload) => {
444
+ if (document.activeElement !== opts.element)
445
+ return;
446
+ const link = this.opts.slotOf?.();
447
+ if (!link?.session)
448
+ return;
449
+ const direction = payload?.direction === "previous" ? "previous" : "next";
450
+ link.session.focusBack(link.slotId, direction);
451
+ });
302
452
  channel.onNotify(frame_protocol_1.FrameNotice.size, ({ height, width }) => {
303
453
  if (typeof height !== "number" || !Number.isFinite(height) || height < 0)
304
454
  return;
@@ -442,10 +592,64 @@ class FrameSession {
442
592
  next[index] = change(slots[index]);
443
593
  this.opts.slots(next);
444
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
+ }
445
639
  /** Tell a piece slot's frame what happened in its piece. */
446
640
  slotNotify(type, payload) {
447
641
  this.channel.notify(type, payload);
448
642
  }
643
+ /** Focus came to this piece's frame from its screen's slot: at its first or last control. */
644
+ focusFrom(edge) {
645
+ this.opts.element.focus();
646
+ this.channel.notify(frame_protocol_1.HostNotice.focusEdge, { edge });
647
+ }
648
+ /** Tab left the piece over one of this screen's slots: focus beside the slot. */
649
+ focusBack(slotId, direction) {
650
+ this.opts.element.focus();
651
+ this.channel.notify(frame_protocol_1.HostNotice.pieceFocusLeave, { slotId, direction });
652
+ }
449
653
  /** Show a screen or a piece: sends the init now if the frame is ready, or once it says so. */
450
654
  async show(getContent) {
451
655
  const userContext = await (0, peers_sdk_1.getUserContext)();
@@ -462,16 +666,33 @@ class FrameSession {
462
666
  bundleCode: this.opts.bundle.code,
463
667
  ...(content.kind === "screen"
464
668
  ? { peersUIId: content.peersUIId, path: content.path }
465
- : {
466
- path: "",
467
- piece: {
468
- key: content.key,
469
- groupId: content.groupId,
470
- height: content.height,
471
- ...(content.width !== undefined ? { width: content.width } : {}),
472
- ...(content.emits ? { emits: content.emits } : {}),
473
- },
474
- }),
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
+ }),
475
696
  props: content.props,
476
697
  colorMode: (0, color_mode_dropdown_1.colorMode)() === "light" ? "light" : "dark",
477
698
  storage,
@@ -503,6 +724,8 @@ class FrameSession {
503
724
  return this.init !== undefined;
504
725
  }
505
726
  dispose() {
727
+ for (const hostId of [...this.commands])
728
+ this.unregisterCommand(hostId);
506
729
  liveSessions.delete(this);
507
730
  if (!liveSessions.size)
508
731
  document.removeEventListener("mousedown", relayHostPointers, true);
@@ -545,10 +768,12 @@ function PackageFrameElement(props) {
545
768
  tabIdRef.current = props.tabId;
546
769
  const eventsRef = (0, react_1.useRef)(props.pieceEvents);
547
770
  eventsRef.current = props.pieceEvents;
771
+ const widgetRef = (0, react_1.useRef)(props.widget);
772
+ widgetRef.current = props.widget;
548
773
  const frameRef = (0, react_1.useRef)(null);
549
774
  const sessionRef = (0, react_1.useRef)();
550
775
  const [frameId] = (0, react_1.useState)(() => (0, peers_sdk_1.newid)());
551
- 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"));
552
777
  const [failure, setFailure] = (0, react_1.useState)();
553
778
  const [slots] = (0, react_1.useState)(() => (0, peers_sdk_1.observable)([]));
554
779
  const [shownSlots] = (0, hooks_1.useObservable)(slots);
@@ -589,6 +814,8 @@ function PackageFrameElement(props) {
589
814
  const message = error instanceof Error ? error.message : String(error);
590
815
  if (eventsRef.current)
591
816
  eventsRef.current.onFailed(message);
817
+ else if (widgetRef.current)
818
+ widgetRef.current.events.onFailed(message);
592
819
  else
593
820
  setFailure(message);
594
821
  return;
@@ -604,6 +831,8 @@ function PackageFrameElement(props) {
604
831
  bundle,
605
832
  tabId: () => tabIdRef.current,
606
833
  pieceEvents: () => eventsRef.current,
834
+ widgetEvents: () => widgetRef.current?.events,
835
+ widgetPlacement: () => widgetRef.current?.placement,
607
836
  slots,
608
837
  slotOf: () => latest.current.slotOf?.(),
609
838
  restart: () => onReplaced.current(),
@@ -622,6 +851,11 @@ function PackageFrameElement(props) {
622
851
  sessionRef.current?.dispose();
623
852
  sessionRef.current = undefined;
624
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);
625
859
  };
626
860
  }, [frameId, slots]);
627
861
  // Another UI of the package, new props or a new path: the same frame shows it.
@@ -633,6 +867,12 @@ function PackageFrameElement(props) {
633
867
  session.setPath(content.path);
634
868
  void session.show(() => latest.current.content);
635
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]);
636
876
  if (failure !== undefined) {
637
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" })] }) }));
638
878
  }
@@ -642,10 +882,17 @@ function PackageFrameElement(props) {
642
882
  height: "100%",
643
883
  display: "block",
644
884
  };
645
- 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";
646
890
  if (content.kind === "piece" && content.width !== undefined) {
647
- // PopoverSurface positions the picker over other content and supplies no background.
648
- frameClass += " bg-body";
891
+ // PopoverSurface positions the picker over other content and supplies no background. Over a
892
+ // slot the frame stays clear until the piece paints its own on its first render, so the
893
+ // embedder's loading view in the slot shows through until then.
894
+ if (!props.slotOf)
895
+ frameClass += " bg-body";
649
896
  // Keep the viewport at the cap so vw units and media queries can't feed back into the
650
897
  // reported width. The piece draws at (0, 0), regardless of its embedder's writing direction.
651
898
  frameStyle.width = content.width;
@@ -653,7 +900,10 @@ function PackageFrameElement(props) {
653
900
  frameStyle.top = 0;
654
901
  frameStyle.left = 0;
655
902
  }
656
- 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, 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)))] }));
657
907
  }
658
908
  /**
659
909
  * A piece a framed screen embeds, drawn over the slot the screen reports: a frame of its own,
@@ -671,6 +921,7 @@ function PieceSlotFrame(props) {
671
921
  session.current?.slotNotify(frame_protocol_1.HostNotice.pieceEmit, { slotId, name, payload });
672
922
  },
673
923
  onClose: () => session.current?.slotNotify(frame_protocol_1.HostNotice.pieceClose, { slotId }),
924
+ onDrawn: () => session.current?.slotNotify(frame_protocol_1.HostNotice.pieceDrawn, { slotId }),
674
925
  onSize: (height, width) => session.current?.slotNotify(frame_protocol_1.HostNotice.pieceSize, width === undefined ? { slotId, height } : { slotId, height, width }),
675
926
  onFailed: (message) => session.current?.slotNotify(frame_protocol_1.HostNotice.pieceFailed, { slotId, message }),
676
927
  onKey: (key) => session.current?.slotNotify(frame_protocol_1.HostNotice.pieceKey, { slotId, ...key }),
@@ -11,6 +11,7 @@ const implement_piece_1 = require("../ui-contracts/implement-piece");
11
11
  const piece_height_1 = require("../ui-contracts/piece-height");
12
12
  const piece_host_1 = require("../ui-contracts/piece-host");
13
13
  const popover_surface_1 = require("../ui-contracts/popover-surface");
14
+ const focus_relay_1 = require("./focus-relay");
14
15
  const frame_component_1 = require("./frame-component");
15
16
  const frame_protocol_1 = require("./frame-protocol");
16
17
  const frame_realm_1 = require("./frame-realm");
@@ -72,6 +73,10 @@ function dispatchEscape(target, key) {
72
73
  }));
73
74
  }
74
75
  const inlineComponents = new Map();
76
+ /** Keep hooks used by the embedder's loading view on its own mount. */
77
+ function LoadingView({ render }) {
78
+ return render();
79
+ }
75
80
  /**
76
81
  * In the host's window: the component that draws a piece in a frame for its provider.
77
82
  *
@@ -94,6 +99,9 @@ function inlinePieceComponent(available, name) {
94
99
  const [bundle, setBundle] = (0, react_1.useState)();
95
100
  const [size, setSize] = (0, react_1.useState)();
96
101
  const [failed, setFailed] = (0, react_1.useState)();
102
+ // The embedder's loading view shows until the piece's frame has drawn the piece.
103
+ const loading = (0, react_1.useContext)(piece_height_1.PieceLoadingContext);
104
+ const [drawn, setDrawn] = (0, react_1.useState)(false);
97
105
  const latest = (0, react_1.useRef)(props);
98
106
  latest.current = props;
99
107
  (0, react_1.useEffect)(() => {
@@ -117,6 +125,7 @@ function inlinePieceComponent(available, name) {
117
125
  onClose: () => latest.current.close(),
118
126
  onSize: (height, width) => setSize({ height, width }),
119
127
  onFailed: (message) => setFailed(message),
128
+ onDrawn: () => setDrawn(true),
120
129
  // On the frame's box, inside any popover around it.
121
130
  onKey: (key) => dispatchEscape(box.current, key),
122
131
  }), []);
@@ -125,13 +134,17 @@ function inlinePieceComponent(available, name) {
125
134
  throw bundle;
126
135
  if (failed !== undefined)
127
136
  throw new Error(failed);
128
- if (!bundle)
137
+ if (!bundle) {
138
+ if (loading)
139
+ return (0, jsx_runtime_1.jsx)(LoadingView, { render: loading });
129
140
  return ((0, jsx_runtime_1.jsx)("div", { className: "peers-piece-loading", "aria-busy": "true", style: { minHeight: 24, width: inPopover ? popoverStartWidth(maxWidth) : undefined } }));
141
+ }
130
142
  const PackageFrame = (0, frame_component_1.packageFrameComponent)();
131
- return ((0, jsx_runtime_1.jsx)("div", { ref: box, style: {
143
+ return ((0, jsx_runtime_1.jsxs)("div", { ref: box, style: {
144
+ position: "relative",
132
145
  width: inPopover ? (size?.width ?? popoverStartWidth(maxWidth)) : "100%",
133
146
  height: mode === "content" ? (size?.height ?? 24) : "100%",
134
- }, children: (0, jsx_runtime_1.jsx)(PackageFrame, { pkg: bundle.pkg, bundle: bundle, content: content, pieceEvents: events, label: bundle.pkg.name }) }));
147
+ }, children: [(0, jsx_runtime_1.jsx)(PackageFrame, { pkg: bundle.pkg, bundle: bundle, content: content, pieceEvents: events, label: bundle.pkg.name }), loading && !drawn ? ((0, jsx_runtime_1.jsx)("div", { style: LOADING_OVER_FRAME, children: (0, jsx_runtime_1.jsx)(LoadingView, { render: loading }) })) : null] }));
135
148
  }
136
149
  const component = InlineFramedPiece;
137
150
  inlineComponents.set(key, component);
@@ -175,6 +188,8 @@ function visibleClip(element, rect) {
175
188
  */
176
189
  const LAYOUT_EVENTS = ["load", "transitionend", "animationend"];
177
190
  const slotComponents = new Map();
191
+ /** The embedder's loading view, over a piece's frame until the frame has drawn the piece. */
192
+ const LOADING_OVER_FRAME = { position: "absolute", inset: 0 };
178
193
  /**
179
194
  * Inside a framed screen: the component that holds a slot for a piece, which the host draws over
180
195
  * it in a frame for the provider.
@@ -196,6 +211,9 @@ function slotPieceComponent(available, name) {
196
211
  const slotRef = (0, react_1.useRef)(null);
197
212
  const [size, setSize] = (0, react_1.useState)();
198
213
  const [failed, setFailed] = (0, react_1.useState)();
214
+ // Keep the embedder's loading view in the slot until the host's frame reports its first draw.
215
+ const loading = (0, react_1.useContext)(piece_height_1.PieceLoadingContext);
216
+ const [drawn, setDrawn] = (0, react_1.useState)(false);
199
217
  const latest = (0, react_1.useRef)(props);
200
218
  latest.current = props;
201
219
  // The slot the host holds for this mount, once its mount request has been answered.
@@ -207,8 +225,27 @@ function slotPieceComponent(available, name) {
207
225
  // Each mount is a slot of its own, so a late answer to an earlier one never touches it.
208
226
  const slotId = (0, peers_sdk_1.newid)();
209
227
  let active = true;
228
+ setDrawn(false);
210
229
  const mine = (payload) => payload?.slotId === slotId;
211
230
  const stops = [
231
+ host.onNotify(frame_protocol_1.HostNotice.pieceDrawn, (payload) => {
232
+ if (!mine(payload))
233
+ return;
234
+ setDrawn(true);
235
+ // Focus that reached the slot first (Tab while the piece loaded, or a popover focusing
236
+ // it as it opened, whose Tab trap then refocuses it without a focus event) goes in now.
237
+ if (document.hasFocus() && document.activeElement === slotRef.current) {
238
+ host.notify(frame_protocol_1.FrameNotice.pieceFocus, { slotId, edge: "first" });
239
+ }
240
+ }),
241
+ // Tab left the piece drawn over this slot: on to the control after it, or back before it.
242
+ host.onNotify(frame_protocol_1.HostNotice.pieceFocusLeave, (payload) => {
243
+ const slot = slotRef.current;
244
+ // The host focused this screen as it sent this; focus the user moved since stays.
245
+ if (!mine(payload) || !slot || !document.hasFocus())
246
+ return;
247
+ (0, focus_relay_1.focusBeside)(slot, payload.direction === "previous" ? "previous" : "next");
248
+ }),
212
249
  host.onNotify(frame_protocol_1.HostNotice.pieceEmit, (payload) => {
213
250
  if (mine(payload))
214
251
  latest.current.emit[payload.name]?.(payload.payload);
@@ -336,10 +373,25 @@ function slotPieceComponent(available, name) {
336
373
  // The piece's error boundary shows the failure, with Retry.
337
374
  if (failed !== undefined)
338
375
  throw new Error(failed);
339
- return ((0, jsx_runtime_1.jsx)("div", { ref: slotRef, "data-peers-piece-slot": "", style: {
376
+ return (
377
+ // biome-ignore lint/a11y/noStaticElementInteractions: it stands in for the piece's frame, which the host draws over it, in the screen's Tab order.
378
+ (0, jsx_runtime_1.jsx)("div", { ref: slotRef, "data-peers-piece-slot": "",
379
+ // Tab stops here in the piece's place; the host moves focus into the piece's frame.
380
+ // biome-ignore lint/a11y/noNoninteractiveTabindex: as above; focus moves straight on into the frame.
381
+ tabIndex: 0, onFocus: (event) => {
382
+ const slotId = mounted.current;
383
+ // Until the piece has drawn its frame may have no controls, so focus waits here.
384
+ if (event.target !== event.currentTarget || !slotId || !drawn)
385
+ return;
386
+ const edge = (0, focus_relay_1.edgeEnteredFrom)(event.currentTarget, event.relatedTarget);
387
+ host?.notify(frame_protocol_1.FrameNotice.pieceFocus, { slotId, edge });
388
+ },
389
+ // A popover has no background of its own. The piece's frame paints it once drawn, and is
390
+ // clear before that, so the loading view shows; the slot paints it until then.
391
+ className: inPopover && !drawn ? "bg-body" : undefined, style: {
340
392
  width: inPopover ? (size?.width ?? popoverStartWidth(maxWidth)) : "100%",
341
393
  height: mode === "content" ? (size?.height ?? 24) : "100%",
342
- } }));
394
+ }, children: loading && !drawn ? (0, jsx_runtime_1.jsx)(LoadingView, { render: loading }) : null }));
343
395
  }
344
396
  const component = SlotFramedPiece;
345
397
  slotComponents.set(key, component);
@@ -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,35 +1,54 @@
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
  /**
6
7
  * Whether a framed screen's package may embed a UI contract's pieces: it consumes that UI
7
8
  * contract version (`pkg.consumes`, kept in the manifest's `uiConsumes`), or provides it itself.
8
- * Read from the manifest this device stored for the screen's version, once per version.
9
+ * Read from the manifest this device stored for the screen's version, once per version. A version
10
+ * with no stored manifest yet (a folder-loaded dev build) is read again next time, since
11
+ * promoting it stores its manifest under the same version id.
9
12
  */
10
13
  const known = new Map();
11
- 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) {
12
23
  const user = await (0, peers_sdk_1.getUserContext)();
13
- const dataContext = bundle.dataContextId === user.userId
24
+ const dataContext = dataContextId === user.userId
14
25
  ? user.userDataContext
15
- : user.groupDataContexts.get(bundle.dataContextId);
26
+ : user.groupDataContexts.get(dataContextId);
16
27
  if (!dataContext)
17
- throw new Error("The screen's package group is no longer available");
28
+ throw new Error("The package's group is no longer available");
18
29
  const [pv, row] = await Promise.all([
19
- (0, peers_sdk_1.PackageVersions)(dataContext).get(bundle.packageVersionId),
20
- (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),
21
32
  ]);
22
- const declared = new Set();
23
33
  if (!pv ||
24
34
  !row ||
25
35
  row.format !== peers_sdk_1.PACKAGE_VERSION_MANIFEST_FORMAT ||
26
36
  row.packageId !== pv.packageId ||
27
37
  row.packageBundleFileHash !== pv.packageBundleFileHash) {
28
- return declared;
38
+ return undefined;
29
39
  }
30
40
  const manifest = JSON.parse(row.manifest);
31
- if (!manifest || manifest.packageId !== pv.packageId || manifest.version !== pv.version)
32
- return declared;
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)
50
+ return undefined;
51
+ const declared = new Set();
33
52
  for (const entry of manifest.uiConsumes ?? [])
34
53
  declared.add(`${entry.contractId}@${entry.version}`);
35
54
  for (const entry of (0, peers_sdk_1.providedContracts)(manifest.uiProvides ?? [])) {
@@ -48,9 +67,17 @@ async function consumesUIContract(bundle, contractId, version) {
48
67
  const key = `${bundle.dataContextId}:${bundle.packageVersionId}`;
49
68
  let declared = known.get(key);
50
69
  if (!declared) {
51
- declared = readDeclared(bundle);
70
+ const read = readDeclared(bundle);
71
+ declared = read.then((found) => found ?? new Set());
52
72
  known.set(key, declared);
53
- declared.catch(() => known.delete(key));
73
+ // Keep only a read that found the manifest; read again after a failure or a missing one.
74
+ read.then((found) => {
75
+ if (!found && known.get(key) === declared)
76
+ known.delete(key);
77
+ }, () => {
78
+ if (known.get(key) === declared)
79
+ known.delete(key);
80
+ });
54
81
  }
55
82
  return (await declared).has(`${contractId}@${version}`);
56
83
  }