@peers-app/peers-ui 0.33.12 → 0.33.14

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 (51) hide show
  1. package/dist/apps-home/app-menu.d.ts +3 -1
  2. package/dist/apps-home/app-menu.js +2 -2
  3. package/dist/apps-home/app-status.d.ts +7 -0
  4. package/dist/apps-home/app-status.js +16 -0
  5. package/dist/apps-home/app-tile.d.ts +3 -1
  6. package/dist/apps-home/app-tile.js +10 -5
  7. package/dist/apps-home/apps-home.js +5 -13
  8. package/dist/apps-home/current-group-name.d.ts +5 -0
  9. package/dist/apps-home/current-group-name.js +19 -0
  10. package/dist/components/group-switcher.js +1 -1
  11. package/dist/components/markdown-editor/editor.d.ts +11 -5
  12. package/dist/components/markdown-editor/editor.js +4 -3
  13. package/dist/components/markdown-editor/mentions-plugin.d.ts +29 -10
  14. package/dist/components/markdown-editor/mentions-plugin.js +108 -92
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +2 -0
  17. package/dist/mentions/mention-chip.d.ts +1 -1
  18. package/dist/mentions/mention-chip.js +2 -1
  19. package/dist/mentions/mentions-client.d.ts +17 -3
  20. package/dist/mentions/mentions-client.js +36 -6
  21. package/dist/screens/packages/package-info.js +1 -1
  22. package/dist/screens/packages/package-runtime-status.d.ts +2 -2
  23. package/dist/screens/packages/package-runtime-status.js +3 -3
  24. package/dist/screens/packages/package-waiting.d.ts +31 -0
  25. package/dist/screens/packages/package-waiting.js +173 -0
  26. package/dist/screens/packages/packages-ipc.d.ts +62 -1
  27. package/dist/screens/packages/packages-ipc.js +105 -4
  28. package/dist/screens/setup-user.js +2 -2
  29. package/dist/theme.css +197 -0
  30. package/dist/ui-contracts/host-ui-contract.d.ts +28 -0
  31. package/dist/ui-contracts/host-ui-contract.js +45 -0
  32. package/dist/ui-contracts/implement-piece.d.ts +24 -0
  33. package/dist/ui-contracts/implement-piece.js +44 -0
  34. package/dist/ui-contracts/index.d.ts +6 -0
  35. package/dist/ui-contracts/index.js +17 -0
  36. package/dist/ui-contracts/mock-piece.d.ts +36 -0
  37. package/dist/ui-contracts/mock-piece.js +56 -0
  38. package/dist/ui-contracts/piece-host.d.ts +99 -0
  39. package/dist/ui-contracts/piece-host.js +266 -0
  40. package/dist/ui-contracts/piece-resolution.d.ts +55 -0
  41. package/dist/ui-contracts/piece-resolution.js +186 -0
  42. package/dist/ui-contracts/piece.d.ts +77 -0
  43. package/dist/ui-contracts/piece.js +358 -0
  44. package/dist/ui-contracts/popover-surface.d.ts +21 -0
  45. package/dist/ui-contracts/popover-surface.js +169 -0
  46. package/dist/ui-contracts/types.d.ts +113 -0
  47. package/dist/ui-contracts/types.js +2 -0
  48. package/dist/ui-router/runnable-version.d.ts +4 -1
  49. package/dist/ui-router/runnable-version.js +6 -3
  50. package/dist/ui-router/ui-loader.js +127 -37
  51. package/package.json +3 -3
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PopoverSurface = PopoverSurface;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const react_1 = require("react");
6
+ const react_dom_1 = require("react-dom");
7
+ const EDGE = 8;
8
+ const GAP = 4;
9
+ /** Above the app's own menus and sheets (the highest is the mention chooser, at 1080). */
10
+ const POPOVER_Z_INDEX = 1090;
11
+ function anchorElement(anchor) {
12
+ if (!anchor)
13
+ return undefined;
14
+ if (typeof HTMLElement !== "undefined" && anchor instanceof HTMLElement)
15
+ return anchor;
16
+ if ("current" in anchor)
17
+ return anchor.current ?? undefined;
18
+ return undefined;
19
+ }
20
+ function anchorRect(anchor) {
21
+ const element = anchorElement(anchor);
22
+ if (element)
23
+ return element.getBoundingClientRect();
24
+ if (anchor && "top" in anchor)
25
+ return anchor;
26
+ return { top: EDGE, left: EDGE, bottom: EDGE, right: EDGE, width: 0, height: 0 };
27
+ }
28
+ const FOCUSABLE = ':is(a[href], button, input, select, textarea, [tabindex], [contenteditable="true"]):not(:disabled):not([hidden]):not([type="hidden"]):not([tabindex^="-"])';
29
+ /** The controls Tab reaches in a surface, leaving out any CSS hides (where the browser can tell). */
30
+ function tabStops(surface) {
31
+ return [...surface.querySelectorAll(FOCUSABLE)].filter((element) => typeof element.checkVisibility !== "function" ||
32
+ element.checkVisibility({ checkVisibilityCSS: true }));
33
+ }
34
+ /** The surface a popover is opened from, when a piece in one opens it. */
35
+ const ParentSurface = (0, react_1.createContext)(undefined);
36
+ /**
37
+ * Whether `target` is in a popover opened from `box`, directly or through others: a click there
38
+ * isn't outside `box`. Each surface names the one it was opened from.
39
+ */
40
+ function inOpenedSurface(box, target) {
41
+ const start = target instanceof Element ? target : target.parentElement;
42
+ let surface = start?.closest(".peers-piece-popover");
43
+ for (let depth = 0; surface && surface !== box && depth < 16; depth++) {
44
+ const parent = surface.dataset.parentSurface;
45
+ if (!parent)
46
+ return false;
47
+ if (parent === box.dataset.surface)
48
+ return true;
49
+ // React's ids (`:r1:`) hold no quote or backslash, so they need no escaping here.
50
+ surface = document.querySelector(`.peers-piece-popover[data-surface="${parent}"]`);
51
+ }
52
+ return false;
53
+ }
54
+ /**
55
+ * A surface that floats above every screen, placed below its anchor (above it when there's no
56
+ * room) and kept inside the window. While open it holds the keyboard: focus moves into it, Tab
57
+ * stays in it, Escape or a click outside closes it, and focus goes back to the anchor after.
58
+ *
59
+ * @param props.anchor - Where it opens from.
60
+ * @param props.onClose - Called on Escape or a click outside.
61
+ * @param props.label - Its name, for screen readers.
62
+ * @param props.children - Its content.
63
+ */
64
+ function PopoverSurface(props) {
65
+ const { anchor, onClose, label, children } = props;
66
+ const surface = (0, react_1.useRef)(null);
67
+ const [position, setPosition] = (0, react_1.useState)();
68
+ const closeRef = (0, react_1.useRef)(onClose);
69
+ closeRef.current = onClose;
70
+ const id = (0, react_1.useId)();
71
+ const openedFrom = (0, react_1.useContext)(ParentSurface);
72
+ // Browsers don't focus inside a hidden surface, so focus moves in once it's placed and shows.
73
+ const placed = position !== undefined;
74
+ (0, react_1.useLayoutEffect)(() => {
75
+ const place = () => {
76
+ const box = surface.current;
77
+ if (!box)
78
+ return;
79
+ const rect = anchorRect(anchor);
80
+ const width = box.offsetWidth;
81
+ const height = box.offsetHeight;
82
+ const below = rect.bottom + GAP;
83
+ const top = below + height > window.innerHeight - EDGE && rect.top - GAP - height >= EDGE
84
+ ? rect.top - GAP - height
85
+ : Math.max(EDGE, Math.min(below, window.innerHeight - EDGE - height));
86
+ const left = Math.max(EDGE, Math.min(rect.left, window.innerWidth - EDGE - width));
87
+ setPosition((previous) => previous?.top === top && previous.left === left ? previous : { top, left });
88
+ };
89
+ place();
90
+ window.addEventListener("resize", place);
91
+ window.addEventListener("scroll", place, true);
92
+ // Content that grows after it opens, such as a list that loads, stays in the window too.
93
+ const growth = typeof ResizeObserver === "function" ? new ResizeObserver(place) : undefined;
94
+ if (surface.current)
95
+ growth?.observe(surface.current);
96
+ return () => {
97
+ window.removeEventListener("resize", place);
98
+ window.removeEventListener("scroll", place, true);
99
+ growth?.disconnect();
100
+ };
101
+ }, [anchor]);
102
+ (0, react_1.useEffect)(() => {
103
+ if (!placed)
104
+ return;
105
+ const opener = anchorElement(anchor) ?? document.activeElement;
106
+ const box = surface.current;
107
+ const first = box ? tabStops(box)[0] : undefined;
108
+ (first ?? box)?.focus();
109
+ const onPointerDown = (event) => {
110
+ const target = event.target;
111
+ if (!target || box?.contains(target) || anchorElement(anchor)?.contains(target)) {
112
+ return;
113
+ }
114
+ if (box && inOpenedSurface(box, target))
115
+ return;
116
+ closeRef.current();
117
+ };
118
+ document.addEventListener("mousedown", onPointerDown, true);
119
+ return () => {
120
+ document.removeEventListener("mousedown", onPointerDown, true);
121
+ // Back to where the user was, unless focus already moved somewhere else on purpose.
122
+ if (!document.activeElement ||
123
+ document.activeElement === document.body ||
124
+ box?.contains(document.activeElement)) {
125
+ opener?.focus?.();
126
+ }
127
+ };
128
+ // A new rectangle or ref wrapper doesn't change the element that opened the surface.
129
+ }, [placed, anchorElement(anchor)]);
130
+ const onKeyDown = (event) => {
131
+ if (event.key === "Escape") {
132
+ event.stopPropagation();
133
+ closeRef.current();
134
+ return;
135
+ }
136
+ if (event.key !== "Tab" || !surface.current)
137
+ return;
138
+ // Portal events bubble through React's tree: only this surface should handle its Tab.
139
+ event.stopPropagation();
140
+ const focusable = tabStops(surface.current);
141
+ if (!focusable.length) {
142
+ event.preventDefault();
143
+ return;
144
+ }
145
+ const first = focusable[0];
146
+ const last = focusable[focusable.length - 1];
147
+ // The surface itself has focus after a click on its text, or when it had no control yet.
148
+ const atStart = document.activeElement === first || document.activeElement === surface.current;
149
+ if (event.shiftKey && atStart) {
150
+ event.preventDefault();
151
+ last.focus();
152
+ }
153
+ else if (!event.shiftKey && document.activeElement === last) {
154
+ event.preventDefault();
155
+ first.focus();
156
+ }
157
+ };
158
+ return (0, react_dom_1.createPortal)((0, jsx_runtime_1.jsx)("div", { ref: surface, className: "peers-piece-popover", "data-surface": id, "data-parent-surface": openedFrom, role: "dialog", "aria-label": label, tabIndex: -1, onKeyDown: onKeyDown, style: {
159
+ position: "fixed",
160
+ zIndex: POPOVER_Z_INDEX,
161
+ top: position?.top ?? 0,
162
+ left: position?.left ?? 0,
163
+ // Hidden until placed, so it never flashes at the corner.
164
+ visibility: position ? "visible" : "hidden",
165
+ maxWidth: `calc(100vw - ${EDGE * 2}px)`,
166
+ maxHeight: `calc(100vh - ${EDGE * 2}px)`,
167
+ overflow: "auto",
168
+ }, children: (0, jsx_runtime_1.jsx)(ParentSurface.Provider, { value: id, children: children }) }), document.body);
169
+ }
@@ -0,0 +1,113 @@
1
+ import type { IPieceImplementation, IUIContractDeclaration, PieceEmitInputsOf, PieceEmitPayloadsOf, PiecePropsOf, UIContractPieceNamesOf } from "@peers-app/peers-sdk";
2
+ import type React from "react";
3
+ /**
4
+ * One piece of a UI contract, as a screen embeds it: from a {@link IHostUIContractClient}'s
5
+ * `pieces`. It names the UI contract version, the piece, and the group and provider the client
6
+ * was made for. Pass it to `<Piece of={…}>` or {@link usePiece}.
7
+ */
8
+ export interface IPieceHandle<T = unknown, N extends string = string> {
9
+ /** Marks a piece handle. */
10
+ readonly kind: "piece-handle";
11
+ /** The UI contract's id. */
12
+ readonly contractId: string;
13
+ /** The UI contract version the embedder consumes. */
14
+ readonly version: number;
15
+ /** The piece's name. */
16
+ readonly name: N;
17
+ /** The group whose provider draws the piece; the active group when absent. */
18
+ readonly dataContextId?: string | (() => Promise<string>);
19
+ /** A provider to use instead of the group's active one, as a hub names each of its providers. */
20
+ readonly providerPackageId?: string;
21
+ /** Type-only: the UI contract. Always undefined at runtime. */
22
+ readonly types?: {
23
+ contract: T;
24
+ };
25
+ }
26
+ /** Where a piece can be embedded from: a client's group and, for a hub, one provider. */
27
+ export interface IHostUIContractOptions {
28
+ /**
29
+ * The group whose provider draws the piece: its id, or a function that gives it. Absent, the
30
+ * active group. Pass the id of the group the piece's data belongs to, since the group switcher
31
+ * is going away, and make the client once per group. A function, or none, is read again each
32
+ * time the screen renders, so the piece follows it.
33
+ */
34
+ dataContextId?: string | (() => Promise<string>);
35
+ /** A provider to use instead of the group's active one. */
36
+ providerPackageId?: string;
37
+ }
38
+ /** A client for a UI contract: a handle for each of its pieces, by name. */
39
+ export interface IHostUIContractClient<T = unknown> {
40
+ /** The UI contract's id. */
41
+ readonly contractId: string;
42
+ /** The UI contract version. */
43
+ readonly version: number;
44
+ /** A handle for each piece, by name. */
45
+ readonly pieces: [UIContractPieceNamesOf<T>] extends [never] ? Record<string, IPieceHandle<T, string>> : {
46
+ readonly [N in UIContractPieceNamesOf<T>]: IPieceHandle<T, N>;
47
+ };
48
+ }
49
+ /** Why a piece can't show. */
50
+ export type PieceUnavailableReason = "missing" | "older" | "not-running" | "failed";
51
+ /** A piece that can't show: why, a sentence for people, and for `failed`, a way to try again. */
52
+ export interface IPieceUnavailable {
53
+ /**
54
+ * - `missing`: nothing in the group provides the UI contract;
55
+ * - `older`: the group's provider has the UI contract, but not this version;
56
+ * - `not-running`: the provider is installed but doesn't run here (waiting for a contract it
57
+ * requires, not approved on this device, turned off, or unsupported on this host);
58
+ * - `failed`: its UI didn't load, registered no component for the piece, or threw; or it's
59
+ * drawn inside itself, or more than four pieces deep.
60
+ */
61
+ reason: PieceUnavailableReason;
62
+ /** What's wrong, in a sentence. */
63
+ message: string;
64
+ /** For `failed`: load and draw it again. */
65
+ retry?: () => void;
66
+ }
67
+ /** What a piece's link or mention opens, sent with the built-in `open` emit. */
68
+ export interface IPieceOpenTarget {
69
+ /** The record's kind, such as `task`. */
70
+ kind: string;
71
+ /** The record's id. */
72
+ id: string;
73
+ /** The group it's in, when the piece knows. */
74
+ groupId?: string;
75
+ }
76
+ /** The emit functions a piece's component gets: one per declared emit, plus `open`. */
77
+ export type PieceEmitters<T, N extends UIContractPieceNamesOf<T>> = {
78
+ readonly [E in keyof PieceEmitInputsOf<T, N>]: (payload: PieceEmitInputsOf<T, N>[E]) => void;
79
+ } & {
80
+ /** Ask the embedder to open a record; the host opens it when the embedder doesn't. */
81
+ readonly open: (target: IPieceOpenTarget) => void;
82
+ };
83
+ /** What a piece's component gets. */
84
+ export interface PieceComponentProps<T extends IUIContractDeclaration<any, any, any>, N extends UIContractPieceNamesOf<T> = UIContractPieceNamesOf<T>> {
85
+ /** What the embedder passed: plain data, checked against the declared props. */
86
+ props: PiecePropsOf<T, N>;
87
+ /** Send a declared emit to the embedder, or `open` a record. */
88
+ emit: PieceEmitters<T, N>;
89
+ /** For a popover: close it. A view can call it too; its embedder decides what it means. */
90
+ close: () => void;
91
+ /** The group the piece was embedded for. */
92
+ groupId: string;
93
+ }
94
+ /** The handlers an embedder passes `<Piece on={…}>`, one per emit it cares about. */
95
+ export type PieceHandlers<T, N extends string> = N extends UIContractPieceNamesOf<T> ? {
96
+ readonly [E in keyof PieceEmitPayloadsOf<T, N>]?: (payload: PieceEmitPayloadsOf<T, N>[E]) => void;
97
+ } & {
98
+ /**
99
+ * A link or mention in the piece was clicked. Return `false` to let the host open it as
100
+ * usual, which is also what happens without this handler.
101
+ */
102
+ readonly open?: (target: IPieceOpenTarget) => unknown;
103
+ } : Record<string, ((payload: never) => unknown) | undefined>;
104
+ /** The props type a piece takes, for a handle. */
105
+ export type PieceHandleProps<H> = H extends IPieceHandle<infer T, infer N> ? N extends UIContractPieceNamesOf<T> ? PiecePropsOf<T, N> : Record<string, unknown> : never;
106
+ /** A registered piece's component, as a UI bundle exports it. */
107
+ export type PieceComponent = React.ComponentType<{
108
+ props: Record<string, unknown>;
109
+ emit: Record<string, (payload?: unknown) => void>;
110
+ close: () => void;
111
+ groupId: string;
112
+ }>;
113
+ export type { IPieceImplementation };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -13,8 +13,11 @@ import { type DataContext, type IPackage, type IPackageVersion } from "@peers-ap
13
13
  * with fields added (`appNavs`), and the row's signature covers only the row as it was signed.
14
14
  *
15
15
  * @param pkg - The package.
16
+ * @param servingPackageVersionId - A version that runs here while the selected one waits for a
17
+ * contract it requires: it's the version to show, so screens match the worker that answers
18
+ * them. It runs here, so the dev rule above doesn't apply to it; the group's checks still do.
16
19
  */
17
- export declare function resolveRunnableVersion(pkg: IPackage): Promise<{
20
+ export declare function resolveRunnableVersion(pkg: IPackage, servingPackageVersionId?: string): Promise<{
18
21
  pv: IPackageVersion;
19
22
  dataContext: DataContext;
20
23
  } | undefined>;
@@ -17,8 +17,11 @@ const peers_sdk_1 = require("@peers-app/peers-sdk");
17
17
  * with fields added (`appNavs`), and the row's signature covers only the row as it was signed.
18
18
  *
19
19
  * @param pkg - The package.
20
+ * @param servingPackageVersionId - A version that runs here while the selected one waits for a
21
+ * contract it requires: it's the version to show, so screens match the worker that answers
22
+ * them. It runs here, so the dev rule above doesn't apply to it; the group's checks still do.
20
23
  */
21
- async function resolveRunnableVersion(pkg) {
24
+ async function resolveRunnableVersion(pkg, servingPackageVersionId) {
22
25
  try {
23
26
  const dataContext = await (0, peers_sdk_1.getDefaultDataContext)();
24
27
  const stored = await (0, peers_sdk_1.Packages)(dataContext).get(pkg.packageId);
@@ -34,13 +37,13 @@ async function resolveRunnableVersion(pkg) {
34
37
  catch {
35
38
  /* use group default */
36
39
  }
37
- const pvId = devicePvId ?? stored.activePackageVersionId;
40
+ const pvId = servingPackageVersionId ?? devicePvId ?? stored.activePackageVersionId;
38
41
  if (!pvId)
39
42
  return undefined;
40
43
  const pv = await (0, peers_sdk_1.PackageVersions)(dataContext).get(pvId);
41
44
  if (!pv)
42
45
  return undefined;
43
- if (pv.versionTag === "dev" && !devicePvId) {
46
+ if (pv.versionTag === "dev" && !devicePvId && !servingPackageVersionId) {
44
47
  // Same reason resolveDevicePackageVersion unloads it with.
45
48
  throw new Error(`Only a dev version (v${pv.version}) is selected; activate it on this device to run it`);
46
49
  }
@@ -42,7 +42,10 @@ const react_1 = __importStar(require("react"));
42
42
  const loading_indicator_1 = require("../components/loading-indicator");
43
43
  const globals_1 = require("../globals");
44
44
  const hooks_1 = require("../hooks");
45
+ const package_waiting_1 = require("../screens/packages/package-waiting");
46
+ const packages_ipc_1 = require("../screens/packages/packages-ipc");
45
47
  require("../ui-defaults");
48
+ const piece_host_1 = require("../ui-contracts/piece-host");
46
49
  const bundle_files_1 = require("./bundle-files");
47
50
  const find_route_1 = require("./find-route");
48
51
  const routes_loader_1 = require("./routes-loader");
@@ -116,9 +119,16 @@ const UIRouter = (props) => {
116
119
  if (!matchingRoute) {
117
120
  return undefined;
118
121
  }
119
- return (0, jsx_runtime_1.jsx)(UILoader, { peersUIId: matchingRoute.peersUIId, props: props.props });
122
+ return ((0, jsx_runtime_1.jsx)(UILoader, { peersUIId: matchingRoute.peersUIId, props: props.props, screen: context.uiCategory === "screen" }));
120
123
  };
121
124
  exports.UIRouter = UIRouter;
125
+ /**
126
+ * Render one registered UI by id, loading its package's UI bundle first. Packages embed each
127
+ * other's UIs through it (`window.UILoader`).
128
+ *
129
+ * @param args.screen - It fills a whole screen: a waiting package then shows the screen that says
130
+ * why, instead of the line an embedded part shows.
131
+ */
122
132
  const UILoader = (args) => {
123
133
  if (!args.props) {
124
134
  args.props = {};
@@ -128,62 +138,140 @@ const UILoader = (args) => {
128
138
  props.__lastPackageReload = lastReloadTime;
129
139
  // Keep the same loader ancestor after the bundle enters the cache. Replacing it
130
140
  // on a path change would unmount the screen before its navigation guard can run.
131
- return (0, jsx_runtime_1.jsx)(UIAsyncLoader, { peersUIId: peersUIId, props: props }, peersUIId);
141
+ return (0, jsx_runtime_1.jsx)(UIAsyncLoader, { peersUIId: peersUIId, props: props, screen: args.screen }, peersUIId);
132
142
  };
133
- const uiLoadingPromises = {};
134
- function loadUIBundle(pkg, forceRefresh) {
135
- let importPromise = uiLoadingPromises[pkg.packageId];
136
- if (!importPromise || forceRefresh) {
137
- const sTime = Date.now();
138
- console.log(`loading ui bundle for ${pkg.name}`);
139
- importPromise = (async () => {
140
- const selected = await (0, runnable_version_1.resolveRunnableVersion)(pkg);
141
- const uiBundleFileId = selected?.pv.uiBundleFileId;
142
- if (!selected || !uiBundleFileId) {
143
- return;
144
- }
145
- const bundleCode = await (0, bundle_files_1.readBundleText)(selected.dataContext.dataContextId, uiBundleFileId);
146
- if (bundleCode) {
147
- if (selected.dataContext.groupId)
148
- (0, peers_sdk_1.assertPackageBundleIntegrity)(selected.pv, "ui", bundleCode);
143
+ /** Each package's latest UI bundle load, by package id. */
144
+ const uiLoads = {};
145
+ /**
146
+ * Read a package's UI bundle for the version this device runs, checked against that version in a
147
+ * group, without running any of it.
148
+ *
149
+ * @param servingPackageVersionId - The version that serves while the selected one waits, if one
150
+ * does: its UI is read instead.
151
+ */
152
+ async function readUIBundle(pkg, servingPackageVersionId) {
153
+ const selected = await (0, runnable_version_1.resolveRunnableVersion)(pkg, servingPackageVersionId);
154
+ const uiBundleFileId = selected?.pv.uiBundleFileId;
155
+ if (!selected || !uiBundleFileId)
156
+ return undefined;
157
+ const bundleCode = await (0, bundle_files_1.readBundleText)(selected.dataContext.dataContextId, uiBundleFileId);
158
+ if (bundleCode && selected.dataContext.groupId) {
159
+ (0, peers_sdk_1.assertPackageBundleIntegrity)(selected.pv, "ui", bundleCode);
160
+ }
161
+ return bundleCode
162
+ ? { code: bundleCode, packageVersionId: selected.pv.packageVersionId, uiBundleFileId }
163
+ : undefined;
164
+ }
165
+ /**
166
+ * Run a package's UI bundle once per version, registering its UIs. A load for another version, or
167
+ * one forced, replaces it; a load that's been replaced before its bundle arrives doesn't run it.
168
+ *
169
+ * @param opts.force - Load again even when this version's bundle already loaded.
170
+ * @param opts.read - A read of this version's bundle already under way (one started before the
171
+ * package was known not to be waiting); otherwise the bundle is read now.
172
+ * @param opts.servingPackageVersionId - The version that serves while the selected one waits, if
173
+ * one does; otherwise the selected version's bundle loads.
174
+ */
175
+ function loadUIBundle(pkg, opts) {
176
+ const serving = opts.servingPackageVersionId ?? "";
177
+ const current = uiLoads[pkg.packageId];
178
+ if (current && current.serving === serving && !opts.force)
179
+ return current.promise;
180
+ const sTime = Date.now();
181
+ console.log(`loading ui bundle for ${pkg.name}`);
182
+ const load = { serving, promise: Promise.resolve(), done: false };
183
+ load.promise = (async () => {
184
+ try {
185
+ const read = await (opts.read ?? readUIBundle(pkg, opts.servingPackageVersionId));
186
+ const bundleCode = read?.code;
187
+ // A newer load (another version, or a reload) took this one's place: settle with it.
188
+ const latest = uiLoads[pkg.packageId];
189
+ if (latest !== load)
190
+ return latest.promise;
191
+ if (read && bundleCode) {
149
192
  const exportUIs = (peerUIs) => {
150
193
  peerUIs?.uis?.forEach((ui) => {
151
194
  peersUIs[ui.peersUIId] = ui;
152
195
  });
196
+ // Its UI contracts' pieces too, so a piece of this version doesn't run it again.
197
+ (0, piece_host_1.recordLoadedPieces)(read.packageVersionId, read.uiBundleFileId, peerUIs);
153
198
  };
154
199
  const bundleFunction = new Function("exportUIs", bundleCode);
155
200
  await bundleFunction(exportUIs);
156
201
  }
157
202
  console.log(`finished loading ui bundle for ${pkg.name}: ${(Date.now() - sTime).toFixed(0)}ms, ${bundleCode ? (bundleCode.length / 1000).toFixed(0) : "0"} KB`);
158
- })().catch((err) => {
203
+ }
204
+ catch (err) {
159
205
  console.error(`Error while loading ui module for ${pkg.name}`, err);
160
206
  throw err;
161
- });
162
- uiLoadingPromises[pkg.packageId] = importPromise;
163
- }
164
- return importPromise;
207
+ }
208
+ finally {
209
+ load.done = true;
210
+ }
211
+ })();
212
+ uiLoads[pkg.packageId] = load;
213
+ return load.promise;
165
214
  }
166
215
  const UIAsyncLoader = (props) => {
167
216
  const { peersUIId } = props;
168
217
  const peersUI = peersUIs[peersUIId];
169
- const [loaded, setLoaded] = react_1.default.useState(false);
218
+ // The version whose UI this screen last saw load ("" for the selected one).
219
+ const [loaded, setLoaded] = (0, react_1.useState)();
170
220
  const [loadError, setLoadError] = react_1.default.useState(null);
171
221
  const allRoutes = _window.getPeersUIRoutes();
172
222
  const uiPackageId = allRoutes.find((r) => r.peersUIId === peersUIId)?.packageId;
173
223
  (0, hooks_1.useObservable)(routes_loader_1.allPackages);
174
224
  const pkg = (0, routes_loader_1.allPackages)().find((p) => p.packageId === uiPackageId);
225
+ // A screen of a package that waits for a contract it requires shows why, and runs none of the
226
+ // package's UI code. Its bundle is read alongside the check of whether it waits, and runs only
227
+ // once it's known not to. (A package that ran before it stopped keeps the UI it loaded, and a
228
+ // reload of it, after a change to its row or selection, can run that bundle again meanwhile;
229
+ // no screen shows it until the package starts.) While an update waits, the version that still
230
+ // serves is the one whose UI runs.
231
+ const gate = (0, packages_ipc_1.usePackageScreenGate)(pkg?.packageId);
232
+ const waiting = !!gate.missing;
233
+ const serving = gate.servingPackageVersionId;
234
+ const read = (0, react_1.useRef)();
175
235
  (0, react_1.useEffect)(() => {
176
- if (!pkg || peersUIs[peersUIId]?.content)
236
+ // A read made before the package was known to wait is dropped: by the time it starts, its
237
+ // selected version or its synced bundle may have changed.
238
+ if (waiting)
239
+ read.current = undefined;
240
+ if (!pkg || peersUIs[peersUIId]?.content || pkg.packageId in uiLoads || waiting)
177
241
  return;
242
+ if (read.current?.packageId === pkg.packageId && read.current.serving === serving)
243
+ return;
244
+ const bundle = readUIBundle(pkg, serving);
245
+ // A failed read is reported when the bundle is loaded, if it ever is.
246
+ bundle.catch(() => undefined);
247
+ read.current = { packageId: pkg.packageId, serving, bundle };
248
+ }, [peersUIId, pkg, waiting, serving]);
249
+ (0, react_1.useEffect)(() => {
250
+ if (!pkg || !gate.ready || waiting)
251
+ return;
252
+ // UI on hand is kept when it's this version's: loaded for it, or built in.
253
+ const current = uiLoads[pkg.packageId];
254
+ if (peersUIs[peersUIId]?.content && (current?.serving ?? "") === (serving ?? "")) {
255
+ if (!current || current.done)
256
+ return;
257
+ }
178
258
  const pkgRef = pkg;
259
+ const started = read.current?.packageId === pkgRef.packageId && read.current.serving === serving
260
+ ? read.current.bundle
261
+ : undefined;
262
+ // Used once: a later load of the same version reads it afresh.
263
+ read.current = undefined;
179
264
  setLoadError(null);
180
- loadUIBundle(pkgRef)
181
- .then(() => setLoaded(true))
265
+ loadUIBundle(pkgRef, { read: started, servingPackageVersionId: serving })
266
+ .then(() => setLoaded(serving ?? ""))
182
267
  .catch((error) => {
183
268
  console.error(`Failed to load UI bundle for package ${pkgRef.name}:`, error);
184
269
  setLoadError(error);
185
270
  });
186
- }, [peersUIId, pkg?.packageId, pkg?.name, pkg]);
271
+ }, [peersUIId, pkg?.packageId, pkg?.name, pkg, gate.ready, waiting, serving]);
272
+ if (pkg && gate.missing) {
273
+ return props.screen ? ((0, jsx_runtime_1.jsx)(package_waiting_1.PackageWaitingScreen, { packageId: pkg.packageId, missing: gate.missing })) : ((0, jsx_runtime_1.jsx)(package_waiting_1.PackageWaitingNotice, { packageId: pkg.packageId, missing: gate.missing }));
274
+ }
187
275
  if (!peersUI?.content && !pkg) {
188
276
  return (0, jsx_runtime_1.jsxs)("div", { children: ["Could not find package that owns peersUIId ", peersUIId] });
189
277
  }
@@ -205,10 +293,10 @@ const UIAsyncLoader = (props) => {
205
293
  maxHeight: "200px",
206
294
  }, children: [(0, jsx_runtime_1.jsx)("strong", { children: "Error:" }), " ", loadError.message || "Unknown error", loadError.stack && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)("br", {}), (0, jsx_runtime_1.jsx)("strong", { children: "Stack Trace:" }), (0, jsx_runtime_1.jsx)("br", {}), loadError.stack] }))] })] }), (0, jsx_runtime_1.jsx)("button", { type: "button", onClick: () => {
207
295
  setLoadError(null);
208
- setLoaded(false);
296
+ setLoaded(undefined);
209
297
  if (pkg) {
210
- loadUIBundle(pkg, true)
211
- .then(() => setLoaded(true))
298
+ loadUIBundle(pkg, { force: true, servingPackageVersionId: serving })
299
+ .then(() => setLoaded(serving ?? ""))
212
300
  .catch(setLoadError);
213
301
  }
214
302
  }, style: {
@@ -221,7 +309,7 @@ const UIAsyncLoader = (props) => {
221
309
  cursor: "pointer",
222
310
  }, children: "Retry Loading" })] }));
223
311
  }
224
- if (!peersUI?.content && !loaded) {
312
+ if (!peersUI?.content && loaded === undefined) {
225
313
  return (0, jsx_runtime_1.jsx)(loading_indicator_1.LoadingIndicator, {});
226
314
  }
227
315
  if (peersUI?.content) {
@@ -320,7 +408,10 @@ async function registerInternalPeersUI(props) {
320
408
  const reloadPackage = (0, peers_sdk_1.debounceByArgs)(async (packageId) => {
321
409
  const pkg = await (0, peers_sdk_1.Packages)().get(packageId);
322
410
  if (pkg) {
323
- await loadUIBundle(pkg, true);
411
+ // The same version as before: the selection's, or the one serving while an update waits. A
412
+ // screen that's open follows a change of the version that serves.
413
+ const servingPackageVersionId = uiLoads[packageId]?.serving || undefined;
414
+ await loadUIBundle(pkg, { force: true, servingPackageVersionId });
324
415
  console.log(`reloaded UI bundle for ${pkg.name}`);
325
416
  (0, globals_1.packageReloaded)(Date.now());
326
417
  }
@@ -341,20 +432,19 @@ function subscribeToPrefs(packageId) {
341
432
  });
342
433
  }
343
434
  (0, peers_sdk_1.getUserContext)().then((_userContext) => {
344
- for (const packageId of Object.keys(uiLoadingPromises)) {
435
+ for (const packageId of Object.keys(uiLoads)) {
345
436
  subscribeToPrefs(packageId);
346
437
  }
347
438
  (0, peers_sdk_1.Packages)().dataChanged.subscribe(async (evt) => {
348
439
  const pkg = evt.dataObject;
349
- const loadingPromise = uiLoadingPromises[pkg.packageId];
350
- if (!loadingPromise)
440
+ if (!(pkg.packageId in uiLoads))
351
441
  return;
352
442
  subscribeToPrefs(pkg.packageId);
353
443
  reloadPackage(pkg.packageId);
354
444
  });
355
445
  // A promotion changes only the selected version's row, and can let a refused screen load.
356
446
  (0, runnable_version_1.onSelectedPackageVersionChanged)((packageId) => {
357
- if (packageId in uiLoadingPromises)
447
+ if (packageId in uiLoads)
358
448
  reloadPackage(packageId);
359
449
  });
360
450
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peers-app/peers-ui",
3
- "version": "0.33.12",
3
+ "version": "0.33.14",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/peers-app/peers-ui.git"
@@ -36,7 +36,7 @@
36
36
  "lint:fix": "biome check --write ."
37
37
  },
38
38
  "peerDependencies": {
39
- "@peers-app/peers-sdk": "^0.33.12",
39
+ "@peers-app/peers-sdk": "^0.33.14",
40
40
  "bootstrap": "^5.3.3",
41
41
  "react": "^18.0.0",
42
42
  "react-dom": "^18.0.0"
@@ -47,7 +47,7 @@
47
47
  "@babel/preset-react": "^7.24.1",
48
48
  "@babel/preset-typescript": "^7.27.1",
49
49
  "@biomejs/biome": "2.3.11",
50
- "@peers-app/peers-sdk": "0.33.12",
50
+ "@peers-app/peers-sdk": "0.33.14",
51
51
  "@testing-library/dom": "^10.4.0",
52
52
  "@testing-library/jest-dom": "^6.6.3",
53
53
  "@testing-library/react": "^16.3.0",