@classcad/client 0.0.0-stage → 3.0.0-beta.20261119100608
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/README.md +20 -2
- package/bin/buerli-classcad.cjs +23 -0
- package/build/cjs/BuerliCadFacade.js +718 -0
- package/build/cjs/cclass/utils/assembly.js +687 -0
- package/build/cjs/cclass/utils/base.js +136 -0
- package/build/cjs/cclass/utils/index.js +99 -0
- package/build/cjs/cclass/utils/part.js +153 -0
- package/build/cjs/classcadEngine.js +33 -0
- package/build/cjs/createApi.js +71 -0
- package/build/cjs/createUnwrappedApi.js +43 -0
- package/build/cjs/facade.js +103 -0
- package/build/cjs/globals.js +157 -0
- package/build/cjs/index.js +102 -0
- package/build/cjs/io/AwvNodeClient.js +290 -0
- package/build/cjs/io/SocketIOClient.js +339 -0
- package/build/cjs/io/Transaction.js +134 -0
- package/build/cjs/io/WASMClient.js +433 -0
- package/build/cjs/io/WSClient.js +646 -0
- package/build/cjs/io/engineKey.js +202 -0
- package/build/cjs/re-export.js +35 -0
- package/build/cjs/session/host.js +479 -0
- package/build/cjs/session/identity.js +38 -0
- package/build/cjs/session/selection.js +283 -0
- package/build/cjs/session/share.js +229 -0
- package/build/cjs/session/types.js +23 -0
- package/build/cjs/test/SocketIOClient.spec.js +178 -0
- package/build/cjs/types/ComClient.js +10 -0
- package/build/cjs/utils/createRecursiveBufferGeometry.js +55 -0
- package/build/cjs/utils/createRecursiveScene.js +140 -0
- package/build/cjs/utils/getDifferentColoredMeshesFromEntity.js +24 -0
- package/build/cjs/utils/index.js +20 -0
- package/build/cjs/utils/polyline.js +65 -0
- package/build/cjs/utils/waitForSelect.js +29 -0
- package/build/esm/BuerliCadFacade.js +714 -0
- package/build/esm/cclass/utils/assembly.js +665 -0
- package/build/esm/cclass/utils/base.js +127 -0
- package/build/esm/cclass/utils/index.js +62 -0
- package/build/esm/cclass/utils/part.js +144 -0
- package/build/esm/classcadEngine.js +30 -0
- package/build/esm/createApi.js +66 -0
- package/build/esm/createUnwrappedApi.js +39 -0
- package/build/esm/facade.js +98 -0
- package/build/esm/globals.js +150 -0
- package/build/esm/index.js +80 -0
- package/build/esm/io/AwvNodeClient.js +286 -0
- package/build/esm/io/SocketIOClient.js +332 -0
- package/build/esm/io/Transaction.js +130 -0
- package/build/esm/io/WASMClient.js +429 -0
- package/build/esm/io/WSClient.js +642 -0
- package/build/esm/io/engineKey.js +196 -0
- package/build/esm/re-export.js +3 -0
- package/build/esm/session/host.js +474 -0
- package/build/esm/session/identity.js +34 -0
- package/build/esm/session/selection.js +277 -0
- package/build/esm/session/share.js +221 -0
- package/build/esm/session/types.js +20 -0
- package/build/esm/test/SocketIOClient.spec.js +178 -0
- package/build/esm/types/ComClient.js +7 -0
- package/build/esm/utils/createRecursiveBufferGeometry.js +51 -0
- package/build/esm/utils/createRecursiveScene.js +136 -0
- package/build/esm/utils/getDifferentColoredMeshesFromEntity.js +20 -0
- package/build/esm/utils/index.js +4 -0
- package/build/esm/utils/polyline.js +60 -0
- package/build/esm/utils/waitForSelect.js +23 -0
- package/build/types/BuerliCadFacade.d.ts +410 -0
- package/build/types/cclass/utils/assembly.d.ts +180 -0
- package/build/types/cclass/utils/base.d.ts +55 -0
- package/build/types/cclass/utils/index.d.ts +46 -0
- package/build/types/cclass/utils/part.d.ts +46 -0
- package/build/types/classcadEngine.d.ts +40 -0
- package/build/types/createApi.d.ts +65 -0
- package/build/types/createUnwrappedApi.d.ts +36 -0
- package/build/types/facade.d.ts +9 -0
- package/build/types/globals.d.ts +79 -0
- package/build/types/index.d.ts +82 -0
- package/build/types/io/AwvNodeClient.d.ts +182 -0
- package/build/types/io/SocketIOClient.d.ts +84 -0
- package/build/types/io/Transaction.d.ts +56 -0
- package/build/types/io/WASMClient.d.ts +239 -0
- package/build/types/io/WSClient.d.ts +242 -0
- package/build/types/io/engineKey.d.ts +137 -0
- package/build/types/re-export.d.ts +6 -0
- package/build/types/session/host.d.ts +108 -0
- package/build/types/session/identity.d.ts +46 -0
- package/build/types/session/selection.d.ts +164 -0
- package/build/types/session/share.d.ts +131 -0
- package/build/types/session/types.d.ts +113 -0
- package/build/types/test/SocketIOClient.spec.d.ts +0 -0
- package/build/types/types/ComClient.d.ts +307 -0
- package/build/types/utils/createRecursiveBufferGeometry.d.ts +8 -0
- package/build/types/utils/createRecursiveScene.d.ts +24 -0
- package/build/types/utils/getDifferentColoredMeshesFromEntity.d.ts +14 -0
- package/build/types/utils/index.d.ts +4 -0
- package/build/types/utils/polyline.d.ts +43 -0
- package/build/types/utils/waitForSelect.d.ts +4 -0
- package/doc/api/advanced/connection.md +488 -0
- package/doc/api/clients.md +2045 -0
- package/doc/api/engine-keys.md +230 -0
- package/doc/api/index.md +58 -0
- package/doc/api/modeling.md +682 -0
- package/doc/api/other.md +33 -0
- package/doc/api/session-sharing.md +706 -0
- package/package.json +60 -4
- package/test/classcadEngine.test.cjs +44 -0
- package/test/connect.test.cjs +81 -0
- package/test/engineKey.test.cjs +80 -0
- package/test/onClient.test.cjs +82 -0
- package/typedoc.json +8 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Session sharing — who the participants are.
|
|
2
|
+
//
|
|
3
|
+
// A session's protocol knows connections by their peer id and, on the host's
|
|
4
|
+
// side, by the invite they joined with. What a participant IS (which app, in
|
|
5
|
+
// which version, whose) it says itself, on the 'client' presence channel: once
|
|
6
|
+
// after connecting, and the server keeps the frame for those who join later.
|
|
7
|
+
// Give a WSClient an `identity` and it does so; every client collects what the
|
|
8
|
+
// others said (`identities`).
|
|
9
|
+
/**
|
|
10
|
+
* The presence channel identities are published on.
|
|
11
|
+
*
|
|
12
|
+
* @advanced
|
|
13
|
+
* @category Session Sharing
|
|
14
|
+
*/
|
|
15
|
+
export const CLIENT_CHANNEL = 'client';
|
|
16
|
+
/**
|
|
17
|
+
* A 'client' frame is remote input: only what has the right shape gets in.
|
|
18
|
+
*
|
|
19
|
+
* @internal
|
|
20
|
+
*/
|
|
21
|
+
export const sanitizeIdentity = (raw) => {
|
|
22
|
+
if (!raw || typeof raw !== 'object')
|
|
23
|
+
return null;
|
|
24
|
+
const data = raw;
|
|
25
|
+
if (typeof data.app !== 'string' || !data.app)
|
|
26
|
+
return null;
|
|
27
|
+
const text = (v) => (typeof v === 'string' && v ? v.slice(0, 80) : undefined);
|
|
28
|
+
return {
|
|
29
|
+
app: data.app.slice(0, 80),
|
|
30
|
+
version: text(data.version),
|
|
31
|
+
name: text(data.name),
|
|
32
|
+
kind: data.kind === 'agent' ? 'agent' : 'app',
|
|
33
|
+
};
|
|
34
|
+
};
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
// Session sharing — what the participants have selected.
|
|
2
|
+
//
|
|
3
|
+
// A selection is state of an app, not of the model: the engine knows nothing
|
|
4
|
+
// about it. In a shared session it is worth sharing all the same — it is how
|
|
5
|
+
// one participant points something out to another, and how an AI agent in the
|
|
6
|
+
// session learns what "this face" means. So it travels like the cameras do,
|
|
7
|
+
// as presence, on two channels:
|
|
8
|
+
//
|
|
9
|
+
// 'selection' what a participant has selected, published whenever it
|
|
10
|
+
// changes (and once after connecting; the server keeps the last
|
|
11
|
+
// frame for those who join later).
|
|
12
|
+
// 'select' a request to the others to select something. Right after it
|
|
13
|
+
// the sender publishes `{ id, done: true }`, so that the frame
|
|
14
|
+
// the server keeps asks for nothing.
|
|
15
|
+
//
|
|
16
|
+
// `syncSelection(client)` does both for a drawing: it publishes the drawing's
|
|
17
|
+
// selection (interaction.selected in the SDK's store) and selects what a peer
|
|
18
|
+
// asks for. Framework-free; the items carry the engine's own ids, so they mean
|
|
19
|
+
// the same in every app and in a script.
|
|
20
|
+
import { api as buerliApi, createInfo, getDrawing } from '@classcad/sdkjs';
|
|
21
|
+
/**
|
|
22
|
+
* The presence channel a participant's selection is published on.
|
|
23
|
+
*
|
|
24
|
+
* @advanced
|
|
25
|
+
* @category Session Sharing
|
|
26
|
+
*/
|
|
27
|
+
export const SELECTION_CHANNEL = 'selection';
|
|
28
|
+
/**
|
|
29
|
+
* The presence channel requests to select something are sent on.
|
|
30
|
+
*
|
|
31
|
+
* @advanced
|
|
32
|
+
* @category Session Sharing
|
|
33
|
+
*/
|
|
34
|
+
export const SELECT_CHANNEL = 'select';
|
|
35
|
+
/** A server relays presence frames of up to 8 KB; a selection is cut to fit, with room to spare. */
|
|
36
|
+
const MAX_FRAME_BYTES = 7000;
|
|
37
|
+
// The element types of a body's graphic, by what they are.
|
|
38
|
+
const FACES = new Set(['plane', 'cylinder', 'cone', 'sphere', 'nurbsSurface']);
|
|
39
|
+
const EDGES = new Set([
|
|
40
|
+
'line',
|
|
41
|
+
'arc',
|
|
42
|
+
'circle',
|
|
43
|
+
'nurbsCurve',
|
|
44
|
+
'curveLine',
|
|
45
|
+
'curveSpline',
|
|
46
|
+
'curveArc',
|
|
47
|
+
'curveCircle',
|
|
48
|
+
'loop',
|
|
49
|
+
]);
|
|
50
|
+
const VERTICES = new Set(['point', 'curvePoint']);
|
|
51
|
+
/** What an element of that type is; anything unknown (or no type at all) counts as a tree object. */
|
|
52
|
+
const kindOf = (type) => type === undefined
|
|
53
|
+
? 'object'
|
|
54
|
+
: FACES.has(type)
|
|
55
|
+
? 'face'
|
|
56
|
+
: EDGES.has(type)
|
|
57
|
+
? 'edge'
|
|
58
|
+
: VERTICES.has(type)
|
|
59
|
+
? 'vertex'
|
|
60
|
+
: 'object';
|
|
61
|
+
/** The element `graphicId` of a container: a face or edge from its map, or one of its points. */
|
|
62
|
+
const elementOf = (drawing, containerId, graphicId) => {
|
|
63
|
+
var _a, _b, _c;
|
|
64
|
+
const container = drawing.geometry.cache[containerId];
|
|
65
|
+
if (!container)
|
|
66
|
+
return undefined;
|
|
67
|
+
return ((_b = (_a = container.map) === null || _a === void 0 ? void 0 : _a[graphicId]) !== null && _b !== void 0 ? _b : (_c = container.points) === null || _c === void 0 ? void 0 : _c.find(p => p.graphicId === graphicId));
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* The drawing's selection (interaction.selected), as session items.
|
|
71
|
+
*
|
|
72
|
+
* @param drawingId - The drawing.
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* import { readSelection } from '@classcad/client'
|
|
76
|
+
*
|
|
77
|
+
* // Tells an assistant what "this" means: the selection, by the engine's ids
|
|
78
|
+
* const faces = readSelection(drawingId).filter(item => item.kind === 'face')
|
|
79
|
+
* const prompt = `Selected faces: ${faces.map(face => `${face.graphicId} (${face.type})`).join(', ')}`
|
|
80
|
+
* ```
|
|
81
|
+
* @advanced
|
|
82
|
+
* @category Session Sharing
|
|
83
|
+
*/
|
|
84
|
+
export function readSelection(drawingId) {
|
|
85
|
+
var _a;
|
|
86
|
+
const drawing = getDrawing(drawingId);
|
|
87
|
+
if (!drawing)
|
|
88
|
+
return [];
|
|
89
|
+
return ((_a = drawing.interaction.selected) !== null && _a !== void 0 ? _a : []).map(info => {
|
|
90
|
+
var _a;
|
|
91
|
+
const item = { kind: 'object', objectId: Number(info.objectId) };
|
|
92
|
+
if (info.prodRefId !== undefined && info.prodRefId !== null)
|
|
93
|
+
item.prodRefId = Number(info.prodRefId);
|
|
94
|
+
if (info.containerId !== undefined && info.graphicId !== undefined) {
|
|
95
|
+
item.containerId = Number(info.containerId);
|
|
96
|
+
item.graphicId = Number(info.graphicId);
|
|
97
|
+
const type = (_a = elementOf(drawing, item.containerId, item.graphicId)) === null || _a === void 0 ? void 0 : _a.type;
|
|
98
|
+
item.kind = kindOf(type);
|
|
99
|
+
if (type)
|
|
100
|
+
item.type = type;
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
const node = drawing.structure.tree[info.objectId];
|
|
104
|
+
if (node === null || node === void 0 ? void 0 : node.class)
|
|
105
|
+
item.type = node.class;
|
|
106
|
+
if (node === null || node === void 0 ? void 0 : node.name)
|
|
107
|
+
item.name = node.name;
|
|
108
|
+
}
|
|
109
|
+
return item;
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/** The product a solid is shown in when a request does not say: the part itself, or the first instance of it. */
|
|
113
|
+
const productOf = (drawing, solidId) => {
|
|
114
|
+
var _a;
|
|
115
|
+
const tree = drawing.structure.tree;
|
|
116
|
+
for (const node of Object.values(tree)) {
|
|
117
|
+
const solids = node === null || node === void 0 ? void 0 : node.solids;
|
|
118
|
+
if (!Array.isArray(solids) || !solids.includes(solidId))
|
|
119
|
+
continue;
|
|
120
|
+
const partId = node.id;
|
|
121
|
+
if (partId === drawing.structure.currentProduct || partId === drawing.structure.root)
|
|
122
|
+
return partId;
|
|
123
|
+
const instance = Object.values(tree).find(n => (n === null || n === void 0 ? void 0 : n.link) === partId);
|
|
124
|
+
return instance ? instance.id : partId;
|
|
125
|
+
}
|
|
126
|
+
return (_a = drawing.structure.currentProduct) !== null && _a !== void 0 ? _a : null;
|
|
127
|
+
};
|
|
128
|
+
/** Turns what a request names into the app's own selection entry, or null when it is not in the drawing (any more). */
|
|
129
|
+
const resolve = (drawing, target) => {
|
|
130
|
+
var _a;
|
|
131
|
+
if (target.graphicId === undefined || target.graphicId === null) {
|
|
132
|
+
if (target.objectId === undefined || !drawing.structure.tree[target.objectId])
|
|
133
|
+
return null;
|
|
134
|
+
return createInfo(Object.assign({ objectId: target.objectId }, (target.prodRefId != null ? { prodRefId: target.prodRefId } : {})));
|
|
135
|
+
}
|
|
136
|
+
// The container may be named; a body that was rebuilt since has another one, so look for the element then.
|
|
137
|
+
const cache = drawing.geometry.cache;
|
|
138
|
+
let containerId = target.containerId !== undefined && elementOf(drawing, target.containerId, target.graphicId)
|
|
139
|
+
? target.containerId
|
|
140
|
+
: undefined;
|
|
141
|
+
if (containerId === undefined) {
|
|
142
|
+
const found = Object.keys(cache).find(id => elementOf(drawing, Number(id), target.graphicId));
|
|
143
|
+
if (found === undefined)
|
|
144
|
+
return null;
|
|
145
|
+
containerId = Number(found);
|
|
146
|
+
}
|
|
147
|
+
const ownerId = cache[containerId].container.ownerId;
|
|
148
|
+
return createInfo({
|
|
149
|
+
objectId: ownerId,
|
|
150
|
+
prodRefId: (_a = target.prodRefId) !== null && _a !== void 0 ? _a : productOf(drawing, ownerId),
|
|
151
|
+
containerId,
|
|
152
|
+
graphicId: target.graphicId,
|
|
153
|
+
});
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* Selects `targets` in the drawing — what a peer asked for.
|
|
157
|
+
*
|
|
158
|
+
* Returns how many of them were found. `replace: false` adds to the selection.
|
|
159
|
+
*
|
|
160
|
+
* @param drawingId - The drawing.
|
|
161
|
+
* @param targets - What to select; targets that are not in the drawing (any more) are skipped.
|
|
162
|
+
* @param replace - `true` (default) replaces the selection, `false` adds to it.
|
|
163
|
+
* @example
|
|
164
|
+
* ```ts
|
|
165
|
+
* import { applySelection } from '@classcad/client'
|
|
166
|
+
*
|
|
167
|
+
* // Selects the faces a script found, adding them to what is selected
|
|
168
|
+
* const found = applySelection(drawingId, faceIds.map(graphicId => ({ graphicId })), false)
|
|
169
|
+
* if (found < faceIds.length) console.warn(`${faceIds.length - found} faces are not in the model any more`)
|
|
170
|
+
* ```
|
|
171
|
+
* @advanced
|
|
172
|
+
* @category Session Sharing
|
|
173
|
+
*/
|
|
174
|
+
export function applySelection(drawingId, targets, replace = true) {
|
|
175
|
+
var _a;
|
|
176
|
+
const drawing = getDrawing(drawingId);
|
|
177
|
+
if (!drawing)
|
|
178
|
+
return 0;
|
|
179
|
+
const found = [];
|
|
180
|
+
for (const target of targets) {
|
|
181
|
+
const info = target && typeof target === 'object' ? resolve(drawing, target) : null;
|
|
182
|
+
if (info && !found.some(f => f.uniqueIdent === info.uniqueIdent))
|
|
183
|
+
found.push(info);
|
|
184
|
+
}
|
|
185
|
+
const kept = replace
|
|
186
|
+
? []
|
|
187
|
+
: ((_a = drawing.interaction.selected) !== null && _a !== void 0 ? _a : []).filter(s => !found.some(f => f.uniqueIdent === s.uniqueIdent));
|
|
188
|
+
drawing.api.interaction.setSelected([...kept, ...found]);
|
|
189
|
+
return found.length;
|
|
190
|
+
}
|
|
191
|
+
/** Cuts a selection to what fits a presence frame. */
|
|
192
|
+
const frameOf = (items) => {
|
|
193
|
+
let shown = items;
|
|
194
|
+
while (shown.length > 0 && JSON.stringify(shown).length > MAX_FRAME_BYTES)
|
|
195
|
+
shown = shown.slice(0, Math.floor(shown.length * 0.8));
|
|
196
|
+
return { items: shown, total: items.length };
|
|
197
|
+
};
|
|
198
|
+
/**
|
|
199
|
+
* Shares the selection of a client's drawing with its session: publishes it on change, selects what a peer asks for.
|
|
200
|
+
*
|
|
201
|
+
* Call it when the client is created; it returns the function that stops it. On a client that
|
|
202
|
+
* is in no shared session it does nothing.
|
|
203
|
+
*
|
|
204
|
+
* @param client - The drawing's client, e.g. from {@link onClient}.
|
|
205
|
+
* @returns A function that stops sharing the selection.
|
|
206
|
+
* @example
|
|
207
|
+
* ```ts
|
|
208
|
+
* import { onClient, SELECTION_CHANNEL, syncSelection, WASMClient, WSClient } from '@classcad/client'
|
|
209
|
+
* import type { PresenceMessage, SelectionFrame } from '@classcad/client'
|
|
210
|
+
*
|
|
211
|
+
* // Every shared drawing shows its selection to the others, and selects what they ask for
|
|
212
|
+
* let stop: (() => void) | undefined
|
|
213
|
+
* onClient(client => {
|
|
214
|
+
* if (!(client instanceof WSClient || client instanceof WASMClient)) return
|
|
215
|
+
* stop?.()
|
|
216
|
+
* stop = syncSelection(client)
|
|
217
|
+
* // What the others have selected
|
|
218
|
+
* client.on('presence', (_client, msg: PresenceMessage) => {
|
|
219
|
+
* if (msg.channel === SELECTION_CHANNEL) highlightForPeer(msg.peerId, msg.data as SelectionFrame)
|
|
220
|
+
* })
|
|
221
|
+
* })
|
|
222
|
+
* ```
|
|
223
|
+
* @category Session Sharing
|
|
224
|
+
*/
|
|
225
|
+
export function syncSelection(client) {
|
|
226
|
+
let last = '';
|
|
227
|
+
let timer;
|
|
228
|
+
const publish = (again = false) => {
|
|
229
|
+
timer = undefined;
|
|
230
|
+
const frame = frameOf(readSelection(client.drawingId));
|
|
231
|
+
const text = JSON.stringify(frame);
|
|
232
|
+
if (text === last && !again)
|
|
233
|
+
return;
|
|
234
|
+
last = text;
|
|
235
|
+
client.sendPresence(SELECTION_CHANNEL, frame);
|
|
236
|
+
};
|
|
237
|
+
let previous;
|
|
238
|
+
const unsubscribe = buerliApi.subscribe(state => {
|
|
239
|
+
var _a, _b;
|
|
240
|
+
const selected = (_b = (_a = state.drawing.refs[client.drawingId]) === null || _a === void 0 ? void 0 : _a.interaction) === null || _b === void 0 ? void 0 : _b.selected;
|
|
241
|
+
if (selected === previous)
|
|
242
|
+
return;
|
|
243
|
+
previous = selected;
|
|
244
|
+
if (timer === undefined)
|
|
245
|
+
timer = setTimeout(publish, 30);
|
|
246
|
+
});
|
|
247
|
+
// Whoever is in the session, or joins later, learns the selection as it is.
|
|
248
|
+
const onConnected = () => publish(true);
|
|
249
|
+
// The last request of each peer that was followed: a frame seen twice asks once.
|
|
250
|
+
const followed = new Map();
|
|
251
|
+
const onPresence = (_client, msg) => {
|
|
252
|
+
if (msg.channel === 'leave')
|
|
253
|
+
return void followed.delete(msg.peerId);
|
|
254
|
+
if (msg.channel !== SELECT_CHANNEL)
|
|
255
|
+
return;
|
|
256
|
+
const request = msg.data;
|
|
257
|
+
if (!request || typeof request.id !== 'string' || request.done || !Array.isArray(request.items))
|
|
258
|
+
return;
|
|
259
|
+
if (followed.get(msg.peerId) === request.id)
|
|
260
|
+
return;
|
|
261
|
+
followed.set(msg.peerId, request.id);
|
|
262
|
+
applySelection(client.drawingId, request.items.slice(0, 500), request.replace !== false);
|
|
263
|
+
// Said even if nothing changed: the one who asked waits for the answer.
|
|
264
|
+
if (timer !== undefined)
|
|
265
|
+
clearTimeout(timer);
|
|
266
|
+
publish(true);
|
|
267
|
+
};
|
|
268
|
+
client.on('connected', onConnected);
|
|
269
|
+
client.on('presence', onPresence);
|
|
270
|
+
return () => {
|
|
271
|
+
if (timer !== undefined)
|
|
272
|
+
clearTimeout(timer);
|
|
273
|
+
unsubscribe();
|
|
274
|
+
client.removeListener('connected', onConnected);
|
|
275
|
+
client.removeListener('presence', onPresence);
|
|
276
|
+
};
|
|
277
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// Session sharing — the app-facing, framework-free store.
|
|
2
|
+
//
|
|
3
|
+
// Everything a UI needs to build its own token panel, without react-cad and
|
|
4
|
+
// without knowing the transport: the current state of a drawing's sharing
|
|
5
|
+
// (`getSessionShareState`), a subscription that fires on every change
|
|
6
|
+
// (`subscribeSessionShare`) — together they plug straight into React's
|
|
7
|
+
// `useSyncExternalStore` — plus share-link helpers. The actual work happens on
|
|
8
|
+
// the drawing's client (`AwvNodeClient` and its transports); this module only
|
|
9
|
+
// looks it up in the client cache and forwards.
|
|
10
|
+
import { api as buerliApi } from '@classcad/sdkjs';
|
|
11
|
+
import { Globals } from '../globals';
|
|
12
|
+
/**
|
|
13
|
+
* Query parameter carrying a share token, by {@link ShareKind}: `invite`.
|
|
14
|
+
*
|
|
15
|
+
* @advanced
|
|
16
|
+
* @category Session Sharing
|
|
17
|
+
*/
|
|
18
|
+
export const SHARE_PARAM = { invite: 'invite' };
|
|
19
|
+
/**
|
|
20
|
+
* The client that serves `drawingId`, or null before the drawing is connected.
|
|
21
|
+
*
|
|
22
|
+
* @param drawingId - The drawing.
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* import { getSessionShareClient } from '@classcad/client'
|
|
26
|
+
*
|
|
27
|
+
* // Ends the sharing of a drawing: every invite taken back, every guest cut off
|
|
28
|
+
* const client = getSessionShareClient(drawingId)
|
|
29
|
+
* for (const invite of client?.invites ?? []) await client?.revokeInvite(invite.invite)
|
|
30
|
+
* ```
|
|
31
|
+
* @advanced
|
|
32
|
+
* @category Session Sharing
|
|
33
|
+
*/
|
|
34
|
+
export function getSessionShareClient(drawingId) {
|
|
35
|
+
var _a;
|
|
36
|
+
return (_a = Globals.clientCache[drawingId]) !== null && _a !== void 0 ? _a : null;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Reads a share token from a page URL (`?invite=…`).
|
|
40
|
+
*
|
|
41
|
+
* Returns null when the page is a plain host. {@link buildShareUrl} has an example of both sides.
|
|
42
|
+
*
|
|
43
|
+
* @param search - The query string to read; by default the page's (`window.location.search`).
|
|
44
|
+
|
|
45
|
+
* @category Session Sharing
|
|
46
|
+
*/
|
|
47
|
+
export function getShareTokenFromUrl(search) {
|
|
48
|
+
const s = search !== null && search !== void 0 ? search : (typeof window !== 'undefined' ? window.location.search : '');
|
|
49
|
+
const params = new URLSearchParams(s);
|
|
50
|
+
for (const kind of Object.keys(SHARE_PARAM)) {
|
|
51
|
+
const token = params.get(SHARE_PARAM[kind]);
|
|
52
|
+
if (token)
|
|
53
|
+
return { kind, token };
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Builds the link to hand to a guest: the current page with the invite token as query parameter.
|
|
59
|
+
*
|
|
60
|
+
* A guest is another app window, or an MCP's `use_session`. `base` defaults to the page's origin + path.
|
|
61
|
+
*
|
|
62
|
+
* @param invite - The invite, as `createInvite` returns it.
|
|
63
|
+
* @param base - The page the link opens; by default the current one.
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* import { BuerliCadFacade, buildShareUrl, DEFAULT_SESSION_URL, getShareTokenFromUrl } from '@classcad/client'
|
|
67
|
+
* import { init, WASMClient, WSClient } from '@classcad/client'
|
|
68
|
+
*
|
|
69
|
+
* // One page, two roles: opened with a share link it joins as a guest, else it hosts the engine itself
|
|
70
|
+
* const shared = getShareTokenFromUrl()
|
|
71
|
+
* let client!: WASMClient | WSClient
|
|
72
|
+
* init(drawingId =>
|
|
73
|
+
* shared
|
|
74
|
+
* ? (client = new WSClient(DEFAULT_SESSION_URL, drawingId, { invite: shared.token }))
|
|
75
|
+
* : (client = new WASMClient(drawingId, { token: 'ccpk_…' })),
|
|
76
|
+
* )
|
|
77
|
+
* await new BuerliCadFacade().connect()
|
|
78
|
+
*
|
|
79
|
+
* // The host's button: a link to this page for a colleague
|
|
80
|
+
* shareButton.hidden = Boolean(shared)
|
|
81
|
+
* shareButton.onclick = async () => {
|
|
82
|
+
* const invite = await client.createInvite('edit')
|
|
83
|
+
* await navigator.clipboard.writeText(buildShareUrl(invite)) // https://my.app/editor?invite=…
|
|
84
|
+
* }
|
|
85
|
+
* ```
|
|
86
|
+
* @category Session Sharing
|
|
87
|
+
*/
|
|
88
|
+
export function buildShareUrl(invite, base) {
|
|
89
|
+
const b = base !== null && base !== void 0 ? base : (typeof window !== 'undefined' ? window.location : { origin: '', pathname: '' });
|
|
90
|
+
return `${b.origin}${b.pathname}?${SHARE_PARAM[invite.kind]}=${encodeURIComponent(invite.invite)}`;
|
|
91
|
+
}
|
|
92
|
+
const EMPTY_STATE = {
|
|
93
|
+
supported: false,
|
|
94
|
+
kind: null,
|
|
95
|
+
role: 'edit',
|
|
96
|
+
inviteName: '',
|
|
97
|
+
isGuest: false,
|
|
98
|
+
peers: [],
|
|
99
|
+
invites: [],
|
|
100
|
+
identities: {},
|
|
101
|
+
};
|
|
102
|
+
// Memoized per drawing so getSnapshot returns a stable object between changes
|
|
103
|
+
// (useSyncExternalStore requires that).
|
|
104
|
+
const snapshots = new Map();
|
|
105
|
+
function computeState(client) {
|
|
106
|
+
if (!client)
|
|
107
|
+
return EMPTY_STATE;
|
|
108
|
+
return {
|
|
109
|
+
supported: client.shareKind !== null,
|
|
110
|
+
kind: client.shareKind,
|
|
111
|
+
role: client.role,
|
|
112
|
+
inviteName: client.inviteName,
|
|
113
|
+
isGuest: getShareTokenFromUrl() !== null,
|
|
114
|
+
peers: client.peers,
|
|
115
|
+
invites: client.invites,
|
|
116
|
+
identities: client.identities,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Current sharing state of a drawing (stable object until something changes).
|
|
121
|
+
*
|
|
122
|
+
* @param drawingId - The drawing.
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts
|
|
125
|
+
* import { getSessionShareState, subscribeSessionShare } from '@classcad/client'
|
|
126
|
+
*
|
|
127
|
+
* // A badge without a framework: who is in the session, kept up to date
|
|
128
|
+
* const render = () => {
|
|
129
|
+
* const share = getSessionShareState(drawingId)
|
|
130
|
+
* const names = share.peers.map(peer => share.identities[peer.peerId]?.name ?? (peer.inviteName || 'Guest'))
|
|
131
|
+
* badge.hidden = !share.supported
|
|
132
|
+
* badge.textContent = share.isGuest ? `Guest (${share.role})` : `With you: ${names.join(', ') || 'nobody'}`
|
|
133
|
+
* }
|
|
134
|
+
* const unsubscribe = subscribeSessionShare(drawingId, render)
|
|
135
|
+
* ```
|
|
136
|
+
* @category Session Sharing
|
|
137
|
+
*/
|
|
138
|
+
export function getSessionShareState(drawingId) {
|
|
139
|
+
const client = getSessionShareClient(drawingId);
|
|
140
|
+
const cached = snapshots.get(String(drawingId));
|
|
141
|
+
if (cached && cached.client === client)
|
|
142
|
+
return cached.state;
|
|
143
|
+
const state = computeState(client);
|
|
144
|
+
snapshots.set(String(drawingId), { client, state });
|
|
145
|
+
return state;
|
|
146
|
+
}
|
|
147
|
+
/** Events on a client that change its sharing state. */
|
|
148
|
+
const SHARE_EVENTS = [
|
|
149
|
+
'connected',
|
|
150
|
+
'conn_error',
|
|
151
|
+
'session_joined',
|
|
152
|
+
'peers_changed',
|
|
153
|
+
'invites_changed',
|
|
154
|
+
'identities_changed',
|
|
155
|
+
];
|
|
156
|
+
/**
|
|
157
|
+
* Subscribes to sharing changes of a drawing: its client, connection, role, peers, invites and identities.
|
|
158
|
+
*
|
|
159
|
+
* It fires when the client is (re)created, connects or loses its connection, joins a session (`session_joined`),
|
|
160
|
+
* and when peers, invites or identities change. Returns the unsubscribe function.
|
|
161
|
+
*
|
|
162
|
+
* With {@link getSessionShareState} it fits React's `useSyncExternalStore`.
|
|
163
|
+
*
|
|
164
|
+
* @param drawingId - The drawing.
|
|
165
|
+
* @param callback - Called on every change; read the new state with {@link getSessionShareState}.
|
|
166
|
+
* @example
|
|
167
|
+
* ```tsx
|
|
168
|
+
* import { useSyncExternalStore } from 'react'
|
|
169
|
+
* import { getSessionShareState, subscribeSessionShare } from '@classcad/client'
|
|
170
|
+
*
|
|
171
|
+
* // A React hook for a drawing's sharing state
|
|
172
|
+
* export function useSessionShare(drawingId: string) {
|
|
173
|
+
* return useSyncExternalStore(
|
|
174
|
+
* onChange => subscribeSessionShare(drawingId, onChange),
|
|
175
|
+
* () => getSessionShareState(drawingId),
|
|
176
|
+
* )
|
|
177
|
+
* }
|
|
178
|
+
*
|
|
179
|
+
* export function Guests({ drawingId }: { drawingId: string }) {
|
|
180
|
+
* const { peers, invites } = useSessionShare(drawingId)
|
|
181
|
+
* return (
|
|
182
|
+
* <span>
|
|
183
|
+
* {peers.length} guests, {invites.length} invites
|
|
184
|
+
* </span>
|
|
185
|
+
* )
|
|
186
|
+
* }
|
|
187
|
+
* ```
|
|
188
|
+
* @category Session Sharing
|
|
189
|
+
*/
|
|
190
|
+
export function subscribeSessionShare(drawingId, callback) {
|
|
191
|
+
let attached = null;
|
|
192
|
+
const invalidate = () => {
|
|
193
|
+
snapshots.delete(String(drawingId));
|
|
194
|
+
callback();
|
|
195
|
+
};
|
|
196
|
+
const attach = () => {
|
|
197
|
+
const client = getSessionShareClient(drawingId);
|
|
198
|
+
if (client === attached)
|
|
199
|
+
return;
|
|
200
|
+
if (attached)
|
|
201
|
+
for (const ev of SHARE_EVENTS)
|
|
202
|
+
attached.removeListener(ev, invalidate);
|
|
203
|
+
attached = client;
|
|
204
|
+
if (attached)
|
|
205
|
+
for (const ev of SHARE_EVENTS)
|
|
206
|
+
attached.on(ev, invalidate);
|
|
207
|
+
invalidate();
|
|
208
|
+
};
|
|
209
|
+
attach();
|
|
210
|
+
// The client is created when the drawing connects (BuerliCadFacade.utils.connect)
|
|
211
|
+
// and dropped when the drawing goes away — both change the SDK's store, so a
|
|
212
|
+
// store subscription is enough to notice the client object changing.
|
|
213
|
+
const unsubStore = buerliApi.subscribe(() => attach());
|
|
214
|
+
return () => {
|
|
215
|
+
unsubStore();
|
|
216
|
+
if (attached)
|
|
217
|
+
for (const ev of SHARE_EVENTS)
|
|
218
|
+
attached.removeListener(ev, invalidate);
|
|
219
|
+
attached = null;
|
|
220
|
+
};
|
|
221
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Session sharing — transport-independent types.
|
|
2
|
+
//
|
|
3
|
+
// An sdkjs app shares its CAD session by minting invite tokens; a guest —
|
|
4
|
+
// another app, or a ClassCAD MCP — joins with `?invite=<token>`. Who owns the
|
|
5
|
+
// session depends on where the engine runs:
|
|
6
|
+
// • a ClassCAD server (WSClient): the server does. Guests join on its URL.
|
|
7
|
+
// • the page itself (WASMClient): the page does (session/host.ts). Nobody
|
|
8
|
+
// can connect to a page, so guests join at the session address of a
|
|
9
|
+
// broker that introduces them to the page: a ClassCAD MCP on the same
|
|
10
|
+
// machine, or the ClassCAD share relay, where they join from anywhere.
|
|
11
|
+
// • a ClassCAD MCP: the MCP does, and apps are its guests.
|
|
12
|
+
// The protocol is the same in all three, and so is the app-facing API
|
|
13
|
+
// (createInvite / revokeInvite / peers / presence / share link).
|
|
14
|
+
/**
|
|
15
|
+
* `Error.name` of the rejection when a client cannot share (no `shareKind`).
|
|
16
|
+
*
|
|
17
|
+
* @advanced
|
|
18
|
+
* @category Session Sharing
|
|
19
|
+
*/
|
|
20
|
+
export const SESSION_SHARING_UNSUPPORTED = 'SessionSharingUnsupported';
|