@peers-app/peers-ui 0.33.13 → 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.
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/mentions/mention-chip.d.ts +1 -1
- package/dist/mentions/mention-chip.js +2 -1
- package/dist/theme.css +32 -0
- package/dist/ui-contracts/host-ui-contract.d.ts +28 -0
- package/dist/ui-contracts/host-ui-contract.js +45 -0
- package/dist/ui-contracts/implement-piece.d.ts +24 -0
- package/dist/ui-contracts/implement-piece.js +44 -0
- package/dist/ui-contracts/index.d.ts +6 -0
- package/dist/ui-contracts/index.js +17 -0
- package/dist/ui-contracts/mock-piece.d.ts +36 -0
- package/dist/ui-contracts/mock-piece.js +56 -0
- package/dist/ui-contracts/piece-host.d.ts +99 -0
- package/dist/ui-contracts/piece-host.js +266 -0
- package/dist/ui-contracts/piece-resolution.d.ts +55 -0
- package/dist/ui-contracts/piece-resolution.js +186 -0
- package/dist/ui-contracts/piece.d.ts +77 -0
- package/dist/ui-contracts/piece.js +358 -0
- package/dist/ui-contracts/popover-surface.d.ts +21 -0
- package/dist/ui-contracts/popover-surface.js +169 -0
- package/dist/ui-contracts/types.d.ts +113 -0
- package/dist/ui-contracts/types.js +2 -0
- package/dist/ui-router/ui-loader.js +9 -3
- package/package.json +3 -3
|
@@ -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;
|
|
@@ -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 };
|