@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,186 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pieceRevision = void 0;
4
+ exports.setPieceMock = setPieceMock;
5
+ exports.handleDataContextId = handleDataContextId;
6
+ exports.resolvePiece = resolvePiece;
7
+ exports.loadPieceComponent = loadPieceComponent;
8
+ exports.resetPieceResolutions = resetPieceResolutions;
9
+ const peers_sdk_1 = require("@peers-app/peers-sdk");
10
+ const globals_1 = require("../globals");
11
+ const implement_piece_1 = require("./implement-piece");
12
+ const piece_host_1 = require("./piece-host");
13
+ /**
14
+ * Bumps when anything a resolution depends on may have changed: a package reload, a change to
15
+ * the Packages or PackageVersions rows of a group a piece was resolved for, or a package there
16
+ * starting, stopping, or changing version on this device.
17
+ */
18
+ exports.pieceRevision = (0, peers_sdk_1.observable)(0);
19
+ let revisionSubscribed = false;
20
+ const watchedGroups = new Set();
21
+ const bump = () => {
22
+ resolutions.clear();
23
+ (0, exports.pieceRevision)((0, exports.pieceRevision)() + 1);
24
+ };
25
+ function watchRevision(dataContextId) {
26
+ if (!revisionSubscribed) {
27
+ revisionSubscribed = true;
28
+ globals_1.packageReloaded.subscribe(bump);
29
+ }
30
+ if (watchedGroups.has(dataContextId))
31
+ return;
32
+ watchedGroups.add(dataContextId);
33
+ (0, piece_host_1.watchProviders)(dataContextId, bump);
34
+ void (0, peers_sdk_1.getUserContext)()
35
+ .then((userContext) => {
36
+ const dataContext = userContext.getDataContext(dataContextId);
37
+ (0, peers_sdk_1.Packages)(dataContext).dataChanged.subscribe(bump);
38
+ (0, peers_sdk_1.PackageVersions)(dataContext).dataChanged.subscribe(bump);
39
+ })
40
+ .catch(() => {
41
+ // No user context (a test, or before sign-in): resolutions refresh on reload only.
42
+ watchedGroups.delete(dataContextId);
43
+ });
44
+ }
45
+ /** Stand-ins registered by `mockPiece`, by piece key. */
46
+ const mocks = new Map();
47
+ /** @internal Register a stand-in for a piece; see `mockPiece`. */
48
+ function setPieceMock(contractId, version, piece, component) {
49
+ const key = (0, implement_piece_1.pieceKey)(contractId, version, piece.name);
50
+ mocks.set(key, { component, piece });
51
+ bump();
52
+ return () => {
53
+ if (mocks.get(key)?.component === component)
54
+ mocks.delete(key);
55
+ bump();
56
+ };
57
+ }
58
+ /** The group a handle's piece shows for: the one it names, else the active group. */
59
+ async function handleDataContextId(handle) {
60
+ const named = handle.dataContextId;
61
+ if (typeof named === "string")
62
+ return named;
63
+ if (typeof named === "function")
64
+ return named();
65
+ return (0, piece_host_1.defaultDataContextId)();
66
+ }
67
+ /** Resolutions in progress or done, by group, piece and provider; cleared on every change. */
68
+ const resolutions = new Map();
69
+ /**
70
+ * Find who draws a piece in a group, without loading any UI code: the provider (the one the
71
+ * handle names, else the group's active one), the version this device runs, and the piece's
72
+ * declaration for the embedder's version. This is the one place a provider is chosen; the
73
+ * admin's default and users' overrides belong here.
74
+ *
75
+ * @param handle - The piece.
76
+ * @param dataContextId - The group, from {@link handleDataContextId}.
77
+ */
78
+ function resolvePiece(handle, dataContextId) {
79
+ const key = `${dataContextId}|${(0, implement_piece_1.pieceKey)(handle.contractId, handle.version, handle.name)}|${handle.providerPackageId ?? ""}`;
80
+ let resolution = resolutions.get(key);
81
+ if (!resolution) {
82
+ watchRevision(dataContextId);
83
+ resolution = resolveNow(handle, dataContextId).catch((error) => ({
84
+ status: "unavailable",
85
+ dataContextId,
86
+ reason: "failed",
87
+ message: error instanceof Error ? error.message : String(error),
88
+ retry: bump,
89
+ }));
90
+ resolutions.set(key, resolution);
91
+ }
92
+ return resolution;
93
+ }
94
+ async function resolveNow(handle, dataContextId) {
95
+ const { contractId, version, name } = handle;
96
+ const unavailable = (reason, message) => ({
97
+ status: "unavailable",
98
+ dataContextId,
99
+ reason,
100
+ message,
101
+ ...(reason === "failed" ? { retry: bump } : {}),
102
+ });
103
+ const mock = mocks.get((0, implement_piece_1.pieceKey)(contractId, version, name));
104
+ if (mock) {
105
+ return {
106
+ status: "available",
107
+ dataContextId,
108
+ providerPackageId: "mock",
109
+ packageVersionId: "mock",
110
+ implementation: { contractId, version },
111
+ piece: mock.piece,
112
+ };
113
+ }
114
+ const providers = await (0, piece_host_1.listProviders)(dataContextId, contractId, version);
115
+ const provider = handle.providerPackageId
116
+ ? providers.find((candidate) => candidate.packageId === handle.providerPackageId)
117
+ : (providers.find((candidate) => candidate.active) ?? providers[0]);
118
+ if (!provider) {
119
+ // Only a running package registers its UI contracts, so one that doesn't run isn't listed.
120
+ const idle = await (0, piece_host_1.installedProvider)(dataContextId, contractId, version, handle.providerPackageId).catch(() => undefined);
121
+ if (idle && !idle.older) {
122
+ return unavailable("not-running", `${idle.name} doesn't run here: ${idle.reason}`);
123
+ }
124
+ if (idle?.older ||
125
+ (await hasOlderProvider(dataContextId, contractId, version, handle.providerPackageId))) {
126
+ return unavailable("older", `This group's provider of it is older than version ${version}`);
127
+ }
128
+ return unavailable("missing", handle.providerPackageId
129
+ ? `That provider doesn't provide version ${version} in this group`
130
+ : "Nothing in this group provides it");
131
+ }
132
+ const definition = await (0, piece_host_1.contractDefinition)(dataContextId, contractId, version);
133
+ if (definition.kind !== "ui") {
134
+ return unavailable("failed", `${definition.name} v${version} isn't a UI contract`);
135
+ }
136
+ const piece = definition.pieces?.find((candidate) => candidate.name === name);
137
+ if (!piece) {
138
+ return unavailable("failed", `${definition.name} v${version} has no piece "${name}"`);
139
+ }
140
+ const runtime = await (0, piece_host_1.providerRuntime)(dataContextId, provider.packageId);
141
+ if (!runtime.running) {
142
+ return unavailable("not-running", `${provider.name} doesn't run here: ${runtime.reason}`);
143
+ }
144
+ return {
145
+ status: "available",
146
+ dataContextId,
147
+ providerPackageId: provider.packageId,
148
+ packageVersionId: runtime.packageVersionId,
149
+ implementation: provider.implementation ?? { contractId, version },
150
+ piece,
151
+ };
152
+ }
153
+ /** Whether the group has a provider of an older version of the contract. */
154
+ async function hasOlderProvider(dataContextId, contractId, version, providerPackageId) {
155
+ // A handful of versions back covers real contracts; each check is one local catalog call.
156
+ for (let older = version - 1; older >= Math.max(1, version - 8); older--) {
157
+ const providers = await (0, piece_host_1.listProviders)(dataContextId, contractId, older);
158
+ if (providers.some((p) => !providerPackageId || p.packageId === providerPackageId))
159
+ return true;
160
+ }
161
+ return false;
162
+ }
163
+ /**
164
+ * The component that draws an available piece: from its provider's UI bundle (loaded once per
165
+ * version), under the UI contract version the provider implements.
166
+ *
167
+ * @param available - From {@link resolvePiece}.
168
+ * @param name - The piece's name.
169
+ */
170
+ async function loadPieceComponent(available, name) {
171
+ const { contractId, version } = available.implementation;
172
+ const mock = mocks.get((0, implement_piece_1.pieceKey)(contractId, version, name));
173
+ if (mock && available.providerPackageId === "mock")
174
+ return mock.component;
175
+ const pieces = await (0, piece_host_1.loadVersionPieces)(available.dataContextId, available.providerPackageId, available.packageVersionId);
176
+ const component = pieces.get((0, implement_piece_1.pieceKey)(contractId, version, name));
177
+ if (!component) {
178
+ throw new Error(`The provider's UI registered no component for "${name}" (${contractId}@${version}); export it with implementPiece in exportUIs({ pieces })`);
179
+ }
180
+ return component;
181
+ }
182
+ /** Forget every resolution and stand-in: for tests. */
183
+ function resetPieceResolutions() {
184
+ mocks.clear();
185
+ bump();
186
+ }
@@ -0,0 +1,77 @@
1
+ import React from "react";
2
+ import { type IPieceAvailable } from "./piece-resolution";
3
+ import { type PopoverAnchor } from "./popover-surface";
4
+ import type { IPieceHandle, IPieceUnavailable, PieceHandleProps, PieceHandlers } from "./types";
5
+ /** Where a piece stands for an embedder: still being found, available, or unavailable. */
6
+ export type PieceState = {
7
+ status: "idle";
8
+ } | {
9
+ status: "loading";
10
+ } | ({
11
+ status: "available";
12
+ } & IPieceAvailable) | ({
13
+ status: "unavailable";
14
+ } & IPieceUnavailable);
15
+ /**
16
+ * Whether a piece is available, without drawing it or loading its provider's UI: Tasks asks it
17
+ * to leave out the "+" when the group has no label picker. It follows changes to the group's
18
+ * packages and to reloads.
19
+ *
20
+ * @param handle - The piece, from a UI contract client.
21
+ * @param options.enabled - False to skip the lookup, as a closed popover does.
22
+ */
23
+ export declare function usePiece(handle: IPieceHandle, options?: {
24
+ enabled?: boolean;
25
+ }): PieceState;
26
+ /** The size of the box a piece draws in. */
27
+ export interface IPieceSize {
28
+ /** Width in CSS pixels. */
29
+ width: number;
30
+ /** Height in CSS pixels. */
31
+ height: number;
32
+ }
33
+ /**
34
+ * The size of the box this piece draws in, for a piece that adapts to its box rather than the
35
+ * window: window breakpoints give the wrong answer inside a panel. Zero until measured.
36
+ */
37
+ export declare function usePieceSize(): IPieceSize;
38
+ /** What `<Piece>` takes. */
39
+ export interface IPieceProps<T, N extends string> {
40
+ /** The piece, from a UI contract client: `client.pieces.picker`. */
41
+ of: IPieceHandle<T, N>;
42
+ /** What the piece gets: plain data, checked against its declared props. */
43
+ props: PieceHandleProps<IPieceHandle<T, N>>;
44
+ /** Handlers for the piece's emits, and `open` for a link or mention it shows. */
45
+ on?: PieceHandlers<T, N>;
46
+ /**
47
+ * What to show when the piece can't show, given why. Without it, a view shows one short line
48
+ * and a popover shows nothing.
49
+ */
50
+ fallback?: (unavailable: IPieceUnavailable) => React.ReactNode;
51
+ /** What a view shows while it loads; a quiet placeholder by default. */
52
+ loading?: () => React.ReactNode;
53
+ /** The box's name, for screen readers. */
54
+ label?: string;
55
+ /** A view fills its box (`fill`, the default) or takes its own height (`content`). */
56
+ height?: "fill" | "content";
57
+ /** A popover's anchor. Passing `anchor` or `open` makes it a popover. */
58
+ anchor?: PopoverAnchor;
59
+ /** Whether a popover is open. Nothing loads until it first opens. */
60
+ open?: boolean;
61
+ /**
62
+ * A popover asked to close: Escape, a click outside, the piece's own `close`, or, without a
63
+ * `fallback`, the piece can't show.
64
+ */
65
+ onClose?: () => void;
66
+ }
67
+ /**
68
+ * Embed a piece of a UI contract the package consumes: a view in this box, or a popover from an
69
+ * anchor. The provider's code draws it, acting as its own package; the embedder passes plain
70
+ * data in and gets the declared emits back. When it can't show, `fallback` says why.
71
+ *
72
+ * ```tsx
73
+ * <Piece of={taskDetails.pieces.details} props={{ taskId }} on={{ open: openBeside }}
74
+ * label="Task details" fallback={() => <TitleAndOpenInTasks />} />
75
+ * ```
76
+ */
77
+ export declare function Piece<T, N extends string>(props: IPieceProps<T, N>): import("react/jsx-runtime").JSX.Element | null;
@@ -0,0 +1,358 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.usePiece = usePiece;
37
+ exports.usePieceSize = usePieceSize;
38
+ exports.Piece = Piece;
39
+ const jsx_runtime_1 = require("react/jsx-runtime");
40
+ const peers_sdk_1 = require("@peers-app/peers-sdk");
41
+ const react_1 = __importStar(require("react"));
42
+ const use_observable_1 = require("../hooks/use-observable");
43
+ const mentions_client_1 = require("../mentions/mentions-client");
44
+ const host_ui_contract_1 = require("./host-ui-contract");
45
+ const piece_resolution_1 = require("./piece-resolution");
46
+ const popover_surface_1 = require("./popover-surface");
47
+ /**
48
+ * Whether a piece is available, without drawing it or loading its provider's UI: Tasks asks it
49
+ * to leave out the "+" when the group has no label picker. It follows changes to the group's
50
+ * packages and to reloads.
51
+ *
52
+ * @param handle - The piece, from a UI contract client.
53
+ * @param options.enabled - False to skip the lookup, as a closed popover does.
54
+ */
55
+ function usePiece(handle, options = {}) {
56
+ const enabled = options.enabled ?? true;
57
+ const key = (0, host_ui_contract_1.pieceHandleKey)(handle);
58
+ const [revision] = (0, use_observable_1.useObservable)(piece_resolution_1.pieceRevision);
59
+ const [found, setFound] = (0, react_1.useState)();
60
+ const handleRef = (0, react_1.useRef)(handle);
61
+ handleRef.current = handle;
62
+ // A group named by id is in `key`. A function, or the active group when none is named, can
63
+ // give another group without anything else changing, so it's read again on each render.
64
+ const groupCheck = typeof handle.dataContextId === "string" ? undefined : {};
65
+ // Checks are numbered, and one's answer stands unless a later check's already does: a screen
66
+ // that keeps re-rendering still gets an answer, and an earlier one never replaces a later one.
67
+ const asked = (0, react_1.useRef)(0);
68
+ const answered = (0, react_1.useRef)(0);
69
+ (0, react_1.useEffect)(() => {
70
+ if (!enabled)
71
+ return;
72
+ const check = ++asked.current;
73
+ void (async () => {
74
+ const current = handleRef.current;
75
+ let resolution;
76
+ try {
77
+ resolution = await (0, piece_resolution_1.resolvePiece)(current, await (0, piece_resolution_1.handleDataContextId)(current));
78
+ }
79
+ catch (error) {
80
+ resolution = {
81
+ status: "unavailable",
82
+ dataContextId: "",
83
+ reason: "failed",
84
+ message: error instanceof Error ? error.message : String(error),
85
+ retry: () => (0, piece_resolution_1.pieceRevision)((0, piece_resolution_1.pieceRevision)() + 1),
86
+ };
87
+ // A failed group getter has no cached resolution, and the render showing its failure
88
+ // checks again: keep the failure shown, even if its message differs, so a getter that
89
+ // keeps failing settles instead of rendering and checking without end.
90
+ if (found?.key === key &&
91
+ found.resolution.status === "unavailable" &&
92
+ found.resolution.dataContextId === "") {
93
+ resolution = found.resolution;
94
+ }
95
+ }
96
+ if (check < answered.current)
97
+ return;
98
+ answered.current = check;
99
+ // Resolutions are cached, so an unchanged one keeps this state and renders nothing new.
100
+ setFound((previous) => previous?.key === key && previous.resolution === resolution
101
+ ? previous
102
+ : { key, resolution });
103
+ })();
104
+ }, [key, revision, enabled, groupCheck]);
105
+ if (!enabled)
106
+ return { status: "idle" };
107
+ if (!found || found.key !== key)
108
+ return { status: "loading" };
109
+ const { resolution } = found;
110
+ if (resolution.status === "available")
111
+ return resolution;
112
+ const { status: _status, dataContextId: _dc, ...unavailable } = resolution;
113
+ return { status: "unavailable", ...unavailable };
114
+ }
115
+ const PieceSizeContext = (0, react_1.createContext)({ width: 0, height: 0 });
116
+ /**
117
+ * The size of the box this piece draws in, for a piece that adapts to its box rather than the
118
+ * window: window breakpoints give the wrong answer inside a panel. Zero until measured.
119
+ */
120
+ function usePieceSize() {
121
+ return (0, react_1.useContext)(PieceSizeContext);
122
+ }
123
+ /** How deep pieces can be drawn inside pieces. */
124
+ const MAX_PIECE_DEPTH = 4;
125
+ /** The pieces a piece is drawn inside, outermost first, as `<contractId>/<name>`. */
126
+ const PieceAncestry = (0, react_1.createContext)([]);
127
+ /**
128
+ * Embed a piece of a UI contract the package consumes: a view in this box, or a popover from an
129
+ * anchor. The provider's code draws it, acting as its own package; the embedder passes plain
130
+ * data in and gets the declared emits back. When it can't show, `fallback` says why.
131
+ *
132
+ * ```tsx
133
+ * <Piece of={taskDetails.pieces.details} props={{ taskId }} on={{ open: openBeside }}
134
+ * label="Task details" fallback={() => <TitleAndOpenInTasks />} />
135
+ * ```
136
+ */
137
+ function Piece(props) {
138
+ const isPopover = props.open !== undefined || props.anchor !== undefined;
139
+ const ancestry = (0, react_1.useContext)(PieceAncestry);
140
+ const self = `${props.of.contractId}/${props.of.name}`;
141
+ const refused = ancestry.includes(self)
142
+ ? `Piece "${props.of.name}" can't be drawn inside itself`
143
+ : ancestry.length >= MAX_PIECE_DEPTH
144
+ ? `Pieces can be drawn only ${MAX_PIECE_DEPTH} deep`
145
+ : undefined;
146
+ const inside = (0, react_1.useMemo)(() => [...ancestry, self], [ancestry, self]);
147
+ const state = usePiece(props.of, { enabled: !refused && (!isPopover || props.open === true) });
148
+ const [attempt, setAttempt] = (0, react_1.useState)(0);
149
+ const available = state.status === "available" ? state : undefined;
150
+ const availableKey = available
151
+ ? `${available.dataContextId}|${available.providerPackageId}|${available.packageVersionId}|${available.implementation.contractId}@${available.implementation.version}/${props.of.name}`
152
+ : "";
153
+ const [loaded, setLoaded] = (0, react_1.useState)();
154
+ (0, react_1.useEffect)(() => {
155
+ if (!available)
156
+ return;
157
+ let cancelled = false;
158
+ const key = `${availableKey}#${attempt}`;
159
+ (0, piece_resolution_1.loadPieceComponent)(available, props.of.name).then((component) => !cancelled && setLoaded({ key, component }), (error) => {
160
+ if (cancelled)
161
+ return;
162
+ console.error(`Couldn't load piece "${props.of.name}"`, error);
163
+ setLoaded({ key, error: error instanceof Error ? error : new Error(String(error)) });
164
+ });
165
+ return () => {
166
+ cancelled = true;
167
+ };
168
+ // A refreshed resolution can name a rebuilt bundle under the same version. Ordinary
169
+ // renders keep the cached resolution, so only invalidations re-check its bundle file.
170
+ }, [available, attempt, props.of.name]);
171
+ const onRef = (0, react_1.useRef)(props.on);
172
+ onRef.current = props.on;
173
+ const closeRef = (0, react_1.useRef)(props.onClose);
174
+ closeRef.current = props.onClose;
175
+ const emit = (0, react_1.useMemo)(() => (available ? emitters(available.piece, onRef) : undefined), [available?.piece]);
176
+ const checked = (0, react_1.useMemo)(() => (available ? checkProps(props.props, available.piece) : undefined), [available?.piece, props.props, attempt]);
177
+ if (isPopover && !props.open)
178
+ return null;
179
+ const retry = () => setAttempt((value) => value + 1);
180
+ const unavailable = (value, inSurface = false) => {
181
+ if (props.fallback) {
182
+ const shown = (0, jsx_runtime_1.jsx)(jsx_runtime_1.Fragment, { children: props.fallback(value) });
183
+ // A popover's fallback shows where the popover would, with its keyboard handling.
184
+ if (!isPopover || inSurface)
185
+ return shown;
186
+ return ((0, jsx_runtime_1.jsx)(popover_surface_1.PopoverSurface, { anchor: props.anchor, label: props.label, onClose: () => closeRef.current?.(), children: shown }));
187
+ }
188
+ // Shown open with nothing in it, a popover would only hold the keyboard.
189
+ if (isPopover)
190
+ return (0, jsx_runtime_1.jsx)(ClosePopover, { close: closeRef });
191
+ return (0, jsx_runtime_1.jsx)(PieceUnavailableLine, { unavailable: value });
192
+ };
193
+ if (refused)
194
+ return unavailable({ reason: "failed", message: refused, retry });
195
+ if (state.status === "unavailable")
196
+ return unavailable(state);
197
+ const current = loaded?.key === `${availableKey}#${attempt}` ? loaded : undefined;
198
+ if (!available || !current) {
199
+ if (isPopover)
200
+ return null;
201
+ if (props.loading)
202
+ return (0, jsx_runtime_1.jsx)(PieceLoading, { render: props.loading });
203
+ return (0, jsx_runtime_1.jsx)("div", { className: "peers-piece-loading", "aria-busy": "true", style: { minHeight: 24 } });
204
+ }
205
+ if (current.error || !current.component) {
206
+ return unavailable({
207
+ reason: "failed",
208
+ message: current.error?.message ?? "The piece didn't load",
209
+ retry,
210
+ });
211
+ }
212
+ if (checked && "error" in checked) {
213
+ console.error(`Props for piece "${props.of.name}" were refused: ${checked.error}`);
214
+ return unavailable({ reason: "failed", message: checked.error, retry });
215
+ }
216
+ const Component = current.component;
217
+ const body = ((0, jsx_runtime_1.jsx)(PieceErrorBoundary, { resetKey: Component, name: props.of.name, onRetry: retry, render: (value) => unavailable(value, true), children: (0, jsx_runtime_1.jsx)(PieceAncestry.Provider, { value: inside, children: (0, jsx_runtime_1.jsx)(Component, { props: checked?.value ?? {}, emit: emit ?? {}, close: () => closeRef.current?.(), groupId: available.dataContextId }) }) }, attempt));
218
+ if (isPopover) {
219
+ return ((0, jsx_runtime_1.jsx)(popover_surface_1.PopoverSurface, { anchor: props.anchor, label: props.label, onClose: () => closeRef.current?.(), children: body }));
220
+ }
221
+ return ((0, jsx_runtime_1.jsx)(PieceBox, { label: props.label, height: props.height ?? "fill", contractId: props.of.contractId, name: props.of.name, children: body }));
222
+ }
223
+ /** Props as a piece gets them: a plain-data copy, checked against the declared props. */
224
+ function checkProps(value, piece) {
225
+ let snapshot;
226
+ try {
227
+ snapshot = (0, peers_sdk_1.snapshotPackageValue)(value ?? {});
228
+ }
229
+ catch (error) {
230
+ return {
231
+ error: `Props must be plain data (ids, options, short text): ${error instanceof Error ? error.message : String(error)}`,
232
+ };
233
+ }
234
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) {
235
+ return { error: "Props must be an object" };
236
+ }
237
+ // Every shape the declaration gives, nested fields and allowed values included: the embedder
238
+ // was built against this version, so a misfit is its mistake.
239
+ const parsed = (0, peers_sdk_1.fieldsToShapeSchema)(piece.propsFields).passthrough().safeParse(snapshot);
240
+ if (!parsed.success) {
241
+ return {
242
+ error: `Props don't fit piece "${piece.name}": ${parsed.error.issues
243
+ .map((issue) => `${issue.path.join(".") || "props"} ${issue.message}`)
244
+ .join("; ")}`,
245
+ };
246
+ }
247
+ return { value: parsed.data };
248
+ }
249
+ /**
250
+ * The emit functions a piece's component gets: each declared emit, checked against its payload
251
+ * fields and passed to the embedder's handler; `open`, which the host handles unless the
252
+ * embedder does; and a no-op for any other name, so an emit the embedder's version doesn't know
253
+ * is dropped.
254
+ */
255
+ function emitters(piece, onRef) {
256
+ const declared = {};
257
+ for (const emit of piece.emits) {
258
+ // A provider serving this version through a newer one sends payloads that fit this one's.
259
+ const schema = (0, peers_sdk_1.fieldsToShapeSchema)(emit.payloadFields).passthrough();
260
+ declared[emit.name] = (payload) => {
261
+ let value;
262
+ try {
263
+ value = (0, peers_sdk_1.snapshotPackageValue)(payload ?? {});
264
+ }
265
+ catch (error) {
266
+ console.error(`Piece "${piece.name}" sent "${emit.name}" with a value that isn't data`, error);
267
+ return;
268
+ }
269
+ const parsed = schema.safeParse(value);
270
+ if (!parsed.success) {
271
+ console.error(`Piece "${piece.name}" sent "${emit.name}" with a payload that doesn't fit its declaration`, parsed.error.issues);
272
+ return;
273
+ }
274
+ onRef.current?.[emit.name]?.(parsed.data);
275
+ };
276
+ }
277
+ declared.open = (target) => {
278
+ const { kind, id, groupId } = (target ?? {});
279
+ if (typeof kind !== "string" || typeof id !== "string")
280
+ return;
281
+ const handler = onRef.current?.open;
282
+ const handled = handler?.({ kind, id, ...(typeof groupId === "string" ? { groupId } : {}) });
283
+ if (!handler || handled === false) {
284
+ void (0, mentions_client_1.openMention)({ kind, id }, typeof groupId === "string" ? groupId : undefined).catch((error) => console.error(`Couldn't open ${kind} ${id}`, error));
285
+ }
286
+ };
287
+ return new Proxy(declared, {
288
+ get: (target, name) => typeof name === "string" ? (target[name] ?? (() => undefined)) : undefined,
289
+ });
290
+ }
291
+ /** The box a view draws in: marked with its contract and piece, and measured for `usePieceSize`. */
292
+ function PieceBox(props) {
293
+ const box = (0, react_1.useRef)(null);
294
+ const [size, setSize] = (0, react_1.useState)({ width: 0, height: 0 });
295
+ (0, react_1.useLayoutEffect)(() => {
296
+ const element = box.current;
297
+ if (!element || typeof ResizeObserver === "undefined")
298
+ return;
299
+ const observer = new ResizeObserver(([entry]) => {
300
+ if (entry)
301
+ setSize({ width: entry.contentRect.width, height: entry.contentRect.height });
302
+ });
303
+ observer.observe(element);
304
+ return () => observer.disconnect();
305
+ }, []);
306
+ return ((0, jsx_runtime_1.jsx)("div", { ref: box, className: "peers-piece", ...(props.label ? { role: "region", "aria-label": props.label } : {}), "data-ui-contract": props.contractId, "data-piece": props.name, style: props.height === "fill"
307
+ ? {
308
+ height: "100%",
309
+ minHeight: 0,
310
+ display: "flex",
311
+ flexDirection: "column",
312
+ overflow: "auto",
313
+ }
314
+ : undefined, children: (0, jsx_runtime_1.jsx)(PieceSizeContext.Provider, { value: size, children: props.children }) }));
315
+ }
316
+ /** The embedder's loading placeholder. */
317
+ function PieceLoading({ render }) {
318
+ return render();
319
+ }
320
+ /** A view's default fallback: one short line, and Retry for a piece that failed. */
321
+ function PieceUnavailableLine({ unavailable }) {
322
+ return ((0, jsx_runtime_1.jsxs)("div", { className: "peers-piece-unavailable small text-muted", "data-reason": unavailable.reason, children: [unavailable.message, unavailable.retry ? ((0, jsx_runtime_1.jsx)("button", { type: "button", className: "btn btn-link btn-sm p-0 ms-2", onClick: unavailable.retry, children: "Retry" })) : null] }));
323
+ }
324
+ /** A popover that can't show and has no fallback asks its embedder to close it, once. */
325
+ function ClosePopover({ close }) {
326
+ (0, react_1.useEffect)(() => {
327
+ close.current?.();
328
+ }, [close]);
329
+ return null;
330
+ }
331
+ /**
332
+ * Catches a piece that throws while drawing, and shows its fallback with Retry. Another
333
+ * component (`resetKey`), as a rebuilt bundle gives, draws again without one.
334
+ */
335
+ class PieceErrorBoundary extends react_1.default.Component {
336
+ state = {};
337
+ static getDerivedStateFromError(error) {
338
+ return { error: error instanceof Error ? error : new Error(String(error)) };
339
+ }
340
+ componentDidCatch(error, info) {
341
+ console.error(`Piece "${this.props.name}" threw`, error, info.componentStack);
342
+ }
343
+ componentDidUpdate(previous) {
344
+ if (this.state.error && previous.resetKey !== this.props.resetKey) {
345
+ this.setState({ error: undefined });
346
+ }
347
+ }
348
+ render() {
349
+ if (this.state.error) {
350
+ return this.props.render({
351
+ reason: "failed",
352
+ message: `It stopped working: ${this.state.error.message}`,
353
+ retry: this.props.onRetry,
354
+ });
355
+ }
356
+ return this.props.children;
357
+ }
358
+ }
@@ -0,0 +1,21 @@
1
+ import type React from "react";
2
+ /** Where a popover opens from: an element (or a ref to one), or a rectangle in the window. */
3
+ export type PopoverAnchor = HTMLElement | null | undefined | {
4
+ readonly current: HTMLElement | null;
5
+ } | Pick<DOMRect, "top" | "left" | "bottom" | "right" | "width" | "height">;
6
+ /**
7
+ * A surface that floats above every screen, placed below its anchor (above it when there's no
8
+ * room) and kept inside the window. While open it holds the keyboard: focus moves into it, Tab
9
+ * stays in it, Escape or a click outside closes it, and focus goes back to the anchor after.
10
+ *
11
+ * @param props.anchor - Where it opens from.
12
+ * @param props.onClose - Called on Escape or a click outside.
13
+ * @param props.label - Its name, for screen readers.
14
+ * @param props.children - Its content.
15
+ */
16
+ export declare function PopoverSurface(props: {
17
+ anchor: PopoverAnchor;
18
+ onClose: () => void;
19
+ label?: string;
20
+ children: React.ReactNode;
21
+ }): React.ReactPortal;