@open-artifact/editor-kit 0.0.0-stage → 0.1.0

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 (82) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +128 -2
  4. package/package.json +58 -4
  5. package/src/Announcer.d.ts +2 -0
  6. package/src/Announcer.js +8 -0
  7. package/src/FindBar.d.ts +31 -0
  8. package/src/FindBar.js +34 -0
  9. package/src/agent.d.ts +20 -0
  10. package/src/agent.js +40 -0
  11. package/src/announce.d.ts +18 -0
  12. package/src/announce.js +21 -0
  13. package/src/chrome.d.ts +180 -0
  14. package/src/chrome.js +108 -0
  15. package/src/collab/CommentList.d.ts +23 -0
  16. package/src/collab/CommentList.js +117 -0
  17. package/src/collab/CommentViews.d.ts +116 -0
  18. package/src/collab/CommentViews.js +531 -0
  19. package/src/collab/HistoryViews.d.ts +38 -0
  20. package/src/collab/HistoryViews.js +103 -0
  21. package/src/collab/PresenceViews.d.ts +52 -0
  22. package/src/collab/PresenceViews.js +46 -0
  23. package/src/collab/cds/cds.d.ts +148 -0
  24. package/src/collab/cds/cds.js +230 -0
  25. package/src/collab/cds/comment-card.d.ts +93 -0
  26. package/src/collab/cds/comment-card.js +211 -0
  27. package/src/collab/cds/comment-composer.d.ts +28 -0
  28. package/src/collab/cds/comment-composer.js +101 -0
  29. package/src/collab/cds/comments-css.d.ts +2 -0
  30. package/src/collab/cds/comments-css.js +3 -0
  31. package/src/collab/cds/comments.css +497 -0
  32. package/src/collab/cds/edge-piles.d.ts +69 -0
  33. package/src/collab/cds/edge-piles.js +178 -0
  34. package/src/collab/cds/layer.d.ts +41 -0
  35. package/src/collab/cds/layer.js +143 -0
  36. package/src/collab/cds/markdown.d.ts +17 -0
  37. package/src/collab/cds/markdown.js +507 -0
  38. package/src/collab/cds/shield.d.ts +28 -0
  39. package/src/collab/cds/shield.js +114 -0
  40. package/src/collab/cds/time.d.ts +2 -0
  41. package/src/collab/cds/time.js +41 -0
  42. package/src/collab/collab.d.ts +100 -0
  43. package/src/collab/collab.js +119 -0
  44. package/src/collab/comments.d.ts +147 -0
  45. package/src/collab/comments.js +287 -0
  46. package/src/collab/history-wiring.d.ts +32 -0
  47. package/src/collab/history-wiring.js +53 -0
  48. package/src/collab/history.d.ts +53 -0
  49. package/src/collab/history.js +94 -0
  50. package/src/collab/peer-colors.d.ts +123 -0
  51. package/src/collab/peer-colors.js +273 -0
  52. package/src/collab/pins.d.ts +70 -0
  53. package/src/collab/pins.js +44 -0
  54. package/src/collab/presence.d.ts +92 -0
  55. package/src/collab/presence.js +158 -0
  56. package/src/design-systems.d.ts +46 -0
  57. package/src/design-systems.js +61 -0
  58. package/src/downloads.d.ts +24 -0
  59. package/src/downloads.js +36 -0
  60. package/src/find.d.ts +64 -0
  61. package/src/find.js +147 -0
  62. package/src/index.d.ts +25 -0
  63. package/src/index.js +25 -0
  64. package/src/keys.d.ts +13 -0
  65. package/src/keys.js +20 -0
  66. package/src/merge.d.ts +23 -0
  67. package/src/merge.js +116 -0
  68. package/src/page-link.d.ts +33 -0
  69. package/src/page-link.js +75 -0
  70. package/src/project-sync.d.ts +118 -0
  71. package/src/project-sync.js +174 -0
  72. package/src/react.d.ts +16 -0
  73. package/src/react.js +16 -0
  74. package/src/roles.d.ts +33 -0
  75. package/src/roles.js +26 -0
  76. package/src/session.d.ts +42 -0
  77. package/src/session.js +37 -0
  78. package/src/shell.d.ts +56 -0
  79. package/src/shell.js +96 -0
  80. package/src/stash.d.ts +26 -0
  81. package/src/stash.js +66 -0
  82. package/src/styles.css +17 -0
@@ -0,0 +1,273 @@
1
+ /**
2
+ * People's colors that never clash (cursors, selections, frames, avatars):
3
+ * eight colors, picked so people online at once do not share one. Unlike
4
+ * the plain hash of `peerColor` (`presence.ts`), pages here *claim*
5
+ * their color over presence.
6
+ *
7
+ * Alone, a person wears the color their id hashes to ({@link peerColorFromId}),
8
+ * or the one they wore last time. With others online, each page *claims*
9
+ * its color: it publishes `{c, t}` (the color, and when it settled on it;
10
+ * `t` is `null` while it has not). The earliest claim keeps a color
11
+ * ({@link peerColorClaimPrecedes}); a later page that clashes moves on to
12
+ * the next free color in the palette. Pages of the same person adopt that
13
+ * person's earliest claim, so one person keeps one color across tabs.
14
+ *
15
+ * {@link createPeerColorKeeper} runs this for one page:
16
+ * - it settles {@link PEER_COLOR_SETTLE_MS} after the page shows, on the
17
+ * person's own earlier claim or else the least used free color;
18
+ * - every {@link PEER_COLOR_RECONCILE_MS} (and whenever peers change) it
19
+ * looks again: an earlier clash moves it on (a few times a minute at most);
20
+ * - a page hidden for {@link PEER_COLOR_RELEASE_MS} gives its claim up.
21
+ *
22
+ * One color stays reserved ({@link NEVER_GIVEN_PEER_COLORS}): the one
23
+ * nearest the agent's, so people never look like the agent.
24
+ *
25
+ * Pure (timers and storage are injected): unit-tested. {@link keptPeerColor}
26
+ * and {@link PEER_COLOR_TIMERS} are the browser's storage and timers for it.
27
+ */
28
+ /** The palette. Each reads with {@link inkOnPeerColor} text in light and dark themes. */
29
+ export const PEER_COLOR_PALETTE = ['#785ee8', '#dc3c3d', '#019c7f', '#fbb315', '#ce447d', '#10a122', '#257de0', '#d25f25'];
30
+ /** Colors never given to people: the purple nearest the agent's own color. */
31
+ export const NEVER_GIVEN_PEER_COLORS = ['#785ee8'];
32
+ /** How long after a page shows it settles its color, ms. */
33
+ export const PEER_COLOR_SETTLE_MS = 1500;
34
+ /** How often a page looks at its color again, ms. */
35
+ export const PEER_COLOR_RECONCILE_MS = 2000;
36
+ /** How long a hidden page keeps its claim, ms. */
37
+ export const PEER_COLOR_RELEASE_MS = 8000;
38
+ /** A gap in the reconcile beat this long means the computer slept, ms. */
39
+ const WAKE_GAP_MS = 10_000;
40
+ /** Within this long of waking, a hidden page gives its claim up at once, ms. */
41
+ const WOKE_RECENTLY_MS = 60_000;
42
+ /** Moves on from clashes are counted over this long, ms. */
43
+ const BUMP_WINDOW_MS = 60_000;
44
+ /** The palette from `start` on (wrapping), without `exclude`. */
45
+ export function rotatePeerColors(start, exclude = NEVER_GIVEN_PEER_COLORS) {
46
+ const from = Math.max(0, PEER_COLOR_PALETTE.indexOf(start));
47
+ return PEER_COLOR_PALETTE.map((_, offset) => PEER_COLOR_PALETTE[(from + offset) % PEER_COLOR_PALETTE.length]).filter((color) => !exclude.includes(color));
48
+ }
49
+ /** A palette color, lower-cased; `undefined` for anything else. */
50
+ export function normalizePeerColor(color) {
51
+ const lower = typeof color === 'string' ? color.toLowerCase() : '';
52
+ return PEER_COLOR_PALETTE.includes(lower) ? lower : undefined;
53
+ }
54
+ /** The color an id hashes to (never a reserved one): what a person wears alone. */
55
+ export function peerColorFromId(id) {
56
+ let hash = 0;
57
+ for (let index = 0; index < id.length; index += 1)
58
+ hash = (hash * 31 + id.charCodeAt(index)) >>> 0;
59
+ return rotatePeerColors(PEER_COLOR_PALETTE[hash % PEER_COLOR_PALETTE.length])[0] ?? PEER_COLOR_PALETTE[1];
60
+ }
61
+ /** The color a peer wears: the one it published, else its id's. */
62
+ export function peerColorFor(published, id) {
63
+ return normalizePeerColor(published) ?? peerColorFromId(id);
64
+ }
65
+ /** Text color on a `#rrggbb` background: near-black where white would read poorly (contrast under 3:1), else white. */
66
+ export function inkOnPeerColor(hex) {
67
+ const [red = 0, green = 0, blue = 0] = [1, 3, 5].map((offset) => {
68
+ const channel = parseInt(hex.slice(offset, offset + 2), 16) / 255;
69
+ return channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
70
+ });
71
+ return 1.05 / (0.2126 * red + 0.7152 * green + 0.0722 * blue + 0.05) < 3 ? '#0b0b0b' : '#ffffff';
72
+ }
73
+ /** `color` when free, else the palette color after it worn by the fewest of `taken`. */
74
+ export function leastUsedPeerColor(color, taken, neverGiven = NEVER_GIVEN_PEER_COLORS) {
75
+ if (!neverGiven.includes(color) && !taken.includes(color))
76
+ return color;
77
+ const count = (candidate) => taken.filter((item) => item === candidate).length;
78
+ return rotatePeerColors(color, neverGiven).reduce((best, candidate) => (count(candidate) < count(best) ? candidate : best));
79
+ }
80
+ /** True when claim `a` (by `aKey`) came before claim `b` (by `bKey`): earlier, or as early with the smaller key. */
81
+ export function peerColorClaimPrecedes(a, aKey, b, bKey) {
82
+ return a.t < b.t || (a.t === b.t && aKey < bKey);
83
+ }
84
+ /** Claims, earliest first (see {@link peerColorClaimPrecedes}). */
85
+ export function sortPeerColorClaims(claims) {
86
+ const ordered = [];
87
+ for (const claim of claims) {
88
+ const index = ordered.findIndex((other) => peerColorClaimPrecedes(claim, claim.key, other, other.key));
89
+ ordered.splice(index < 0 ? ordered.length : index, 0, claim);
90
+ }
91
+ return ordered;
92
+ }
93
+ /** Colors other people claim (this person's other pages aside). */
94
+ export function takenPeerColors(claims) {
95
+ return claims.filter((claim) => !claim.own).map((claim) => claim.c);
96
+ }
97
+ /** Keeps one page's color (see the module comment); `onChange` is told when it changes. */
98
+ export function createPeerColorKeeper(options, onChange = () => { }) {
99
+ const { now } = options;
100
+ const neverGiven = options.neverGiven ?? NEVER_GIVEN_PEER_COLORS;
101
+ const keptColor = normalizePeerColor(options.kept.read());
102
+ let worn = leastUsedPeerColor(keptColor !== undefined && !neverGiven.includes(keptColor) ? keptColor : peerColorFromId(options.id), [], neverGiven);
103
+ let wornSince = null;
104
+ let bumps = 0;
105
+ let lastBumpAt = -Infinity;
106
+ let cancelSettle;
107
+ let pendingRelease;
108
+ let lastTick = now();
109
+ let lastWakeAt = -Infinity;
110
+ let lastPublished;
111
+ const tickWoke = () => {
112
+ const at = now();
113
+ const woke = at - lastTick > WAKE_GAP_MS;
114
+ if (woke)
115
+ lastWakeAt = at;
116
+ lastTick = at;
117
+ return woke;
118
+ };
119
+ const wear = (color, since) => {
120
+ const changed = color !== worn;
121
+ [worn, wornSince] = [color, since];
122
+ if (since !== null)
123
+ options.kept.write(worn);
124
+ const published = `${worn} ${String(wornSince)}`;
125
+ if (published !== lastPublished) {
126
+ lastPublished = published;
127
+ options.publish({ c: worn, t: wornSince });
128
+ }
129
+ if (changed)
130
+ onChange();
131
+ };
132
+ const release = () => {
133
+ pendingRelease?.cancel();
134
+ pendingRelease = undefined;
135
+ wear(worn, null);
136
+ };
137
+ /** Usable claims, one per person and kind (their earliest page's). */
138
+ const claimsOf = (all) => {
139
+ const usable = all.filter((claim) => !neverGiven.includes(claim.c));
140
+ return usable.filter((b) => !usable.some((a) => a !== b && a.key === b.key && a.own === b.own && peerColorClaimPrecedes(a, a.peer, b, b.peer)));
141
+ };
142
+ /** Someone else claimed `color` before `claim`. */
143
+ const clashes = (claims, color, claim) => claims.some((other) => !other.own && other.c === color && peerColorClaimPrecedes(other, other.key, claim, options.id));
144
+ /**
145
+ * The color to move to from `color`: every clashing claim, earliest first,
146
+ * takes the next free color, and this page gets what is left.
147
+ */
148
+ const resolveClash = (all, claims, color, claim) => {
149
+ const self = { key: options.id, peer: options.peer, own: true, c: color, t: claim.t };
150
+ const ordered = sortPeerColorClaims([...claims.filter((other) => !other.own), self]);
151
+ const clashing = ordered.filter((a) => a === self || ordered.some((b) => b !== a && b.c === a.c && peerColorClaimPrecedes(b, b.key, a, a.key)));
152
+ const taken = new Set([color, ...takenPeerColors(all)]);
153
+ for (const entry of clashing) {
154
+ const next = rotatePeerColors(entry.c, neverGiven).find((candidate) => !taken.has(candidate));
155
+ if (next === undefined || entry === self)
156
+ return next;
157
+ taken.add(next);
158
+ }
159
+ return undefined;
160
+ };
161
+ const settle = () => {
162
+ cancelSettle = undefined;
163
+ const all = options.claims();
164
+ const claims = claimsOf(all);
165
+ const own = claims.find((claim) => claim.own);
166
+ if (own === undefined)
167
+ wear(leastUsedPeerColor(worn, takenPeerColors(all), neverGiven), now());
168
+ else
169
+ wear((clashes(claims, own.c, own) ? resolveClash(all, claims, own.c, own) : undefined) ?? own.c, own.t);
170
+ };
171
+ const reconcile = () => {
172
+ if (pendingRelease !== undefined)
173
+ return;
174
+ const all = options.claims();
175
+ const claims = claimsOf(all);
176
+ const own = claims.find((claim) => claim.own);
177
+ if (wornSince === null) {
178
+ if (own !== undefined && own.c !== worn)
179
+ wear(own.c, null);
180
+ return;
181
+ }
182
+ const mine = { t: wornSince };
183
+ // This person's earlier page wins (unless its color clashes and can move).
184
+ if (own !== undefined && peerColorClaimPrecedes(own, own.peer, mine, options.peer) && !(clashes(claims, own.c, own) && resolveClash(all, claims, own.c, own) !== undefined)) {
185
+ if (own.c !== worn || own.t !== wornSince)
186
+ wear(own.c, own.t);
187
+ return;
188
+ }
189
+ if (now() - lastBumpAt > BUMP_WINDOW_MS)
190
+ bumps = 0;
191
+ const next = clashes(claims, worn, mine) && bumps < rotatePeerColors(worn, neverGiven).length ? resolveClash(all, claims, worn, mine) : undefined;
192
+ if (next === undefined)
193
+ return;
194
+ [bumps, lastBumpAt] = [bumps + 1, now()];
195
+ wear(next, wornSince);
196
+ };
197
+ const stopTicking = options.every(() => {
198
+ if (tickWoke() && pendingRelease !== undefined)
199
+ release();
200
+ reconcile();
201
+ }, PEER_COLOR_RECONCILE_MS);
202
+ lastPublished = `${worn} null`;
203
+ options.publish({ c: worn, t: null });
204
+ return {
205
+ worn: () => worn,
206
+ heard: reconcile,
207
+ here() {
208
+ const pending = pendingRelease;
209
+ pendingRelease = undefined;
210
+ pending?.cancel();
211
+ const expired = pending !== undefined && now() - pending.at >= PEER_COLOR_RELEASE_MS;
212
+ if (expired)
213
+ wear(worn, null);
214
+ if (pending !== undefined && !expired)
215
+ return reconcile();
216
+ if (cancelSettle !== undefined || wornSince !== null)
217
+ return;
218
+ bumps = 0;
219
+ wear(worn, null);
220
+ cancelSettle = options.after(settle, PEER_COLOR_SETTLE_MS);
221
+ },
222
+ away() {
223
+ cancelSettle?.();
224
+ cancelSettle = undefined;
225
+ if (wornSince === null || pendingRelease !== undefined)
226
+ return;
227
+ tickWoke();
228
+ if (now() - lastWakeAt < WOKE_RECENTLY_MS)
229
+ return wear(worn, null);
230
+ pendingRelease = { at: now(), cancel: options.after(release, PEER_COLOR_RELEASE_MS) };
231
+ },
232
+ dispose() {
233
+ if (pendingRelease !== undefined)
234
+ release();
235
+ cancelSettle?.();
236
+ cancelSettle = undefined;
237
+ stopTicking();
238
+ },
239
+ };
240
+ }
241
+ /** The color a person settled on last time, kept in local storage under `key` (wrapped: storage may be missing or refuse). */
242
+ export function keptPeerColor(key) {
243
+ return {
244
+ read() {
245
+ try {
246
+ return globalThis.localStorage?.getItem(key) ?? null;
247
+ }
248
+ catch {
249
+ return null;
250
+ }
251
+ },
252
+ write(color) {
253
+ try {
254
+ globalThis.localStorage?.setItem(key, color);
255
+ }
256
+ catch {
257
+ // Not kept: the id's color is used next time.
258
+ }
259
+ },
260
+ };
261
+ }
262
+ /** The real clock and timers for {@link createPeerColorKeeper}. */
263
+ export const PEER_COLOR_TIMERS = {
264
+ now: () => Date.now(),
265
+ after(run, ms) {
266
+ const timer = setTimeout(run, ms);
267
+ return () => clearTimeout(timer);
268
+ },
269
+ every(run, ms) {
270
+ const timer = setInterval(run, ms);
271
+ return () => clearInterval(timer);
272
+ },
273
+ };
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Pin geometry shared by every editor's comments. Pure.
3
+ *
4
+ * Editor-agnostic: this folder
5
+ * imports only `@open-artifact/runtime`, `@open-artifact/ui`, React, zustand
6
+ * and lucide-react, never an editor's own stores. Where a comment sits is the
7
+ * editor's business; it hands these modules world points and boxes.
8
+ */
9
+ /** A point (world or screen px). */
10
+ export interface Point {
11
+ x: number;
12
+ y: number;
13
+ }
14
+ /** A box (world or screen px). */
15
+ export interface Box {
16
+ x: number;
17
+ y: number;
18
+ w: number;
19
+ h: number;
20
+ /** A dragged area (a highlight draws it dashed, as it was drawn). */
21
+ area?: boolean;
22
+ }
23
+ /** A pan-and-zoom camera: screen = world × zoom + (x, y). */
24
+ export interface Camera {
25
+ x: number;
26
+ y: number;
27
+ zoom: number;
28
+ }
29
+ /**
30
+ * How a stored anchor resolves against the document now:
31
+ *
32
+ * - `ok`: what it names is there.
33
+ * - `moved`: found again at another address (by a fingerprint).
34
+ * - `detached`: the element is gone; the thread falls back to its container.
35
+ * - `orphaned`: the container is gone too (the thread shows in the list only).
36
+ */
37
+ export type AnchorState = 'ok' | 'moved' | 'detached' | 'orphaned';
38
+ /** Where a thread's pin sits, as the editor resolved its anchor. */
39
+ export interface PinPlace {
40
+ world: Point;
41
+ state: AnchorState;
42
+ }
43
+ /** A world point on screen. */
44
+ export declare function toScreenPoint(camera: Camera, world: Point): Point;
45
+ /** A screen point in the world. */
46
+ export declare function toWorldPoint(camera: Camera, screen: Point): Point;
47
+ /** A world box on screen, as CSS `left/top/width/height`. */
48
+ export declare function screenBox(camera: Camera, r: Box): {
49
+ left: number;
50
+ top: number;
51
+ width: number;
52
+ height: number;
53
+ };
54
+ /**
55
+ * Pins that would sit on top of each other are fanned out: a pin within
56
+ * `gap` screen px of an earlier one moves right by `gap` until it is clear.
57
+ * Input order is kept; returns the shifted screen points.
58
+ */
59
+ export declare function spreadPins(points: readonly Point[], gap?: number): Point[];
60
+ /**
61
+ * Where a thread card opens next to its pin: to the right when it fits in
62
+ * the viewport, else to the left; kept inside vertically.
63
+ */
64
+ export declare function cardPosition(pin: Point, viewport: {
65
+ width: number;
66
+ height: number;
67
+ }, card?: {
68
+ w: number;
69
+ h: number;
70
+ }): Point;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Pin geometry shared by every editor's comments. Pure.
3
+ *
4
+ * Editor-agnostic: this folder
5
+ * imports only `@open-artifact/runtime`, `@open-artifact/ui`, React, zustand
6
+ * and lucide-react, never an editor's own stores. Where a comment sits is the
7
+ * editor's business; it hands these modules world points and boxes.
8
+ */
9
+ /** A world point on screen. */
10
+ export function toScreenPoint(camera, world) {
11
+ return { x: world.x * camera.zoom + camera.x, y: world.y * camera.zoom + camera.y };
12
+ }
13
+ /** A screen point in the world. */
14
+ export function toWorldPoint(camera, screen) {
15
+ const zoom = camera.zoom || 1;
16
+ return { x: (screen.x - camera.x) / zoom, y: (screen.y - camera.y) / zoom };
17
+ }
18
+ /** A world box on screen, as CSS `left/top/width/height`. */
19
+ export function screenBox(camera, r) {
20
+ return { left: r.x * camera.zoom + camera.x, top: r.y * camera.zoom + camera.y, width: r.w * camera.zoom, height: r.h * camera.zoom };
21
+ }
22
+ /**
23
+ * Pins that would sit on top of each other are fanned out: a pin within
24
+ * `gap` screen px of an earlier one moves right by `gap` until it is clear.
25
+ * Input order is kept; returns the shifted screen points.
26
+ */
27
+ export function spreadPins(points, gap = 20) {
28
+ const placed = [];
29
+ for (const p of points) {
30
+ let x = p.x;
31
+ for (let tries = 0; tries < 50 && placed.some((q) => Math.abs(q.x - x) < gap && Math.abs(q.y - p.y) < gap); tries++)
32
+ x += gap;
33
+ placed.push({ x, y: p.y });
34
+ }
35
+ return placed;
36
+ }
37
+ /**
38
+ * Where a thread card opens next to its pin: to the right when it fits in
39
+ * the viewport, else to the left; kept inside vertically.
40
+ */
41
+ export function cardPosition(pin, viewport, card = { w: 288, h: 320 }) {
42
+ const right = pin.x + 18 + card.w <= viewport.width - 8;
43
+ return { x: right ? pin.x + 18 : Math.max(8, pin.x - 14 - card.w), y: Math.max(8, Math.min(pin.y - 8, viewport.height - card.h)) };
44
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Live presence for any editor, over the `room` capability: who else has
3
+ * the artifact open, where their pointer is and what the editor says they
4
+ * are doing (selection, page, editing); and the agent, shown for a few
5
+ * seconds after it writes.
6
+ *
7
+ * Editor-agnostic: the editor's
8
+ * {@link PresenceAdapter} says what it publishes under its key and reads
9
+ * peers' values back. Peers' values were written by their browsers: the
10
+ * adapter's `parse` must check and clip them.
11
+ */
12
+ import type { ArtifactCapability, Peer, RoomCapability } from '@open-artifact/runtime';
13
+ import { type StoreApi, type UseBoundStore } from 'zustand';
14
+ import type { Point } from './pins.ts';
15
+ /** Peer colors (cursor, outline, avatar). */
16
+ export declare const PEER_COLORS: string[];
17
+ /** The agent's color. */
18
+ export declare const AGENT_COLOR = "#6e56cf";
19
+ /** How long the agent shows after it wrote (ms). */
20
+ export declare const AGENT_SHOWN_MS = 8000;
21
+ /** Most entries kept of any list read from a peer. */
22
+ export declare const PRESENCE_LIST_MAX = 50;
23
+ /** A stable color for a peer id. */
24
+ export declare function peerColor(id: string): string;
25
+ /** Checked readers for peers' values. */
26
+ export declare const peerValue: {
27
+ str: (value: unknown, max?: number) => string | null;
28
+ num: (value: unknown) => number | null;
29
+ strList: (value: unknown, max?: number) => string[];
30
+ point: (value: unknown) => Point | null;
31
+ };
32
+ /** A peer as an editor draws it. */
33
+ export interface PeerView<S> {
34
+ id: string;
35
+ name: string;
36
+ kind: 'person' | 'agent';
37
+ color: string;
38
+ /** Pointer on the surface (world px), `null` when it is elsewhere. */
39
+ cursor: Point | null;
40
+ /** The editor's own state of this peer, `null` when it published none (or it was malformed). */
41
+ state: S | null;
42
+ }
43
+ /**
44
+ * What an editor tells presence. `S` is what it publishes besides the pointer.
45
+ * The pointer goes out as `cursor` beside `S` (only when the editor gives
46
+ * {@link PresenceAdapter.pointer}).
47
+ */
48
+ export interface PresenceAdapter<S extends object> {
49
+ /** The presence key (one per editor type, e.g. `design`, `slides`). */
50
+ key: string;
51
+ /** This page's state now. */
52
+ snapshot(): S;
53
+ /** Reads a peer's value of {@link key} (already an object); `null` when unusable. */
54
+ parse(value: Record<string, unknown>): S | null;
55
+ /** Calls `changed` whenever {@link snapshot} may have changed; returns an unsubscribe. */
56
+ watch(changed: () => void): () => void;
57
+ /**
58
+ * The world point of a pointer event over the editor's surface; `null` when
59
+ * it is elsewhere. Omitted: the editor shares no pointer, nothing listens
60
+ * for one and the value goes out as {@link snapshot} alone (no `cursor`).
61
+ */
62
+ pointer?(event: PointerEvent): Point | null;
63
+ /** Least time between two sends of this page's value, ms (default 80). */
64
+ sendMs?: number;
65
+ /** Hears the room's peers (raw, this page included) after the store took them; `self` is this page's peer id. */
66
+ onPeers?(peers: readonly Peer[], self: string | null): void;
67
+ /** Maps a changed artifact path to what the editor tracks (a project path), or `null` to ignore it. */
68
+ wrotePath?(path: string): string | null;
69
+ }
70
+ /** The presence store. */
71
+ export interface PresenceState<S> {
72
+ available: boolean;
73
+ peers: PeerView<S>[];
74
+ /** The agent wrote these paths recently (as `wrotePath` mapped them); `null` when it has not. */
75
+ agentWrote: {
76
+ at: number;
77
+ paths: string[];
78
+ } | null;
79
+ }
80
+ /** Peers other than this page, as drawn (people first, then agents). */
81
+ export declare function peerViews<S>(peers: readonly Peer[], self: string | null, key: string, parse: (value: Record<string, unknown>) => S | null): PeerView<S>[];
82
+ /** One editor's presence. */
83
+ export interface PresenceController<S> {
84
+ readonly store: UseBoundStore<StoreApi<PresenceState<S>>>;
85
+ /** Starts publishing and listening; returns a function that stops it. */
86
+ start(input: {
87
+ room: RoomCapability | null;
88
+ artifact?: Pick<ArtifactCapability, 'onChange'> | null;
89
+ }): Promise<() => void>;
90
+ }
91
+ /** Creates an editor's presence. */
92
+ export declare function createPresence<S extends object>(adapter: PresenceAdapter<S>): PresenceController<S>;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Live presence for any editor, over the `room` capability: who else has
3
+ * the artifact open, where their pointer is and what the editor says they
4
+ * are doing (selection, page, editing); and the agent, shown for a few
5
+ * seconds after it writes.
6
+ *
7
+ * Editor-agnostic: the editor's
8
+ * {@link PresenceAdapter} says what it publishes under its key and reads
9
+ * peers' values back. Peers' values were written by their browsers: the
10
+ * adapter's `parse` must check and clip them.
11
+ */
12
+ import { create } from 'zustand';
13
+ /** Peer colors (cursor, outline, avatar). */
14
+ export const PEER_COLORS = ['#e5484d', '#0091ff', '#30a46c', '#f76b15', '#8e4ec6', '#d6409f', '#12a594', '#ad7f58'];
15
+ /** The agent's color. */
16
+ export const AGENT_COLOR = '#6e56cf';
17
+ /** How long the agent shows after it wrote (ms). */
18
+ export const AGENT_SHOWN_MS = 8000;
19
+ /** Pointer updates go out at most this often (ms). */
20
+ const SEND_MS = 80;
21
+ /** Most entries kept of any list read from a peer. */
22
+ export const PRESENCE_LIST_MAX = 50;
23
+ /** A stable color for a peer id. */
24
+ export function peerColor(id) {
25
+ let hash = 0;
26
+ for (let i = 0; i < id.length; i++)
27
+ hash = (hash * 31 + id.charCodeAt(i)) | 0;
28
+ return PEER_COLORS[Math.abs(hash) % PEER_COLORS.length];
29
+ }
30
+ /** Checked readers for peers' values. */
31
+ export const peerValue = {
32
+ str: (value, max = 512) => (typeof value === 'string' && value.length <= max ? value : null),
33
+ num: (value) => (typeof value === 'number' && Number.isFinite(value) ? value : null),
34
+ strList: (value, max = PRESENCE_LIST_MAX) => Array.isArray(value) ? value.map((v) => peerValue.str(v)).filter((v) => v !== null).slice(0, max) : [],
35
+ point: (value) => {
36
+ if (!value || typeof value !== 'object')
37
+ return null;
38
+ const v = value;
39
+ const x = peerValue.num(v.x);
40
+ const y = peerValue.num(v.y);
41
+ return x !== null && y !== null ? { x, y } : null;
42
+ },
43
+ };
44
+ /** Peers other than this page, as drawn (people first, then agents). */
45
+ export function peerViews(peers, self, key, parse) {
46
+ return peers
47
+ .filter((p) => p.id !== self)
48
+ .map((p) => {
49
+ const raw = p.state?.[key];
50
+ const value = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null;
51
+ return {
52
+ id: p.id,
53
+ name: (p.name || (p.kind === 'agent' ? 'Agent' : 'Guest')).slice(0, 60),
54
+ kind: p.kind,
55
+ color: p.kind === 'agent' ? AGENT_COLOR : peerColor(p.id),
56
+ cursor: value ? peerValue.point(value.cursor) : null,
57
+ state: value ? parse(value) : null,
58
+ };
59
+ })
60
+ .sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'person' ? -1 : 1));
61
+ }
62
+ /** Creates an editor's presence. */
63
+ export function createPresence(adapter) {
64
+ const store = create()(() => ({ available: false, peers: [], agentWrote: null }));
65
+ async function start({ room, artifact }) {
66
+ const stops = [];
67
+ // The agent's writes, whether or not there is a room.
68
+ let agentTimer = null;
69
+ if (artifact) {
70
+ stops.push(artifact.onChange((event) => {
71
+ if (event.author !== 'agent')
72
+ return;
73
+ const paths = Object.keys(event.changes)
74
+ .map((path) => (adapter.wrotePath ? adapter.wrotePath(path) : path))
75
+ .filter((p) => p !== null);
76
+ const previous = store.getState().agentWrote;
77
+ const recent = previous && Date.now() - previous.at < AGENT_SHOWN_MS ? previous.paths : [];
78
+ store.setState({ agentWrote: { at: Date.now(), paths: [...new Set([...recent, ...paths])].slice(0, PRESENCE_LIST_MAX) } });
79
+ if (agentTimer)
80
+ clearTimeout(agentTimer);
81
+ agentTimer = setTimeout(() => store.setState({ agentWrote: null }), AGENT_SHOWN_MS);
82
+ }));
83
+ stops.push(() => {
84
+ if (agentTimer)
85
+ clearTimeout(agentTimer);
86
+ });
87
+ }
88
+ if (!room)
89
+ return () => stops.forEach((stop) => stop());
90
+ store.setState({ available: true });
91
+ const self = await room.self().catch(() => null);
92
+ // This page's key: its state at once, then throttled (the pointer too).
93
+ const pointer = adapter.pointer?.bind(adapter);
94
+ const sendMs = adapter.sendMs ?? SEND_MS;
95
+ let cursor = null;
96
+ let last = '';
97
+ let timer = null;
98
+ const send = () => {
99
+ timer = null;
100
+ const value = pointer ? { ...adapter.snapshot(), cursor } : adapter.snapshot();
101
+ const text = JSON.stringify(value);
102
+ if (text === last)
103
+ return;
104
+ last = text;
105
+ room.presence({ [adapter.key]: value }).catch(() => undefined);
106
+ };
107
+ const schedule = () => {
108
+ if (!timer)
109
+ timer = setTimeout(send, sendMs);
110
+ };
111
+ send();
112
+ stops.push(adapter.watch(schedule));
113
+ const onMove = (event) => {
114
+ const world = pointer?.(event) ?? null;
115
+ if (!world) {
116
+ if (cursor) {
117
+ cursor = null;
118
+ schedule();
119
+ }
120
+ return;
121
+ }
122
+ cursor = { x: Math.round(world.x), y: Math.round(world.y) };
123
+ schedule();
124
+ };
125
+ const onLeave = () => {
126
+ cursor = null;
127
+ schedule();
128
+ };
129
+ const onVisibility = () => {
130
+ if (document.visibilityState === 'hidden')
131
+ onLeave();
132
+ };
133
+ if (pointer) {
134
+ window.addEventListener('pointermove', onMove, { passive: true });
135
+ document.addEventListener('pointerleave', onLeave);
136
+ document.addEventListener('visibilitychange', onVisibility);
137
+ }
138
+ stops.push(() => {
139
+ if (pointer) {
140
+ window.removeEventListener('pointermove', onMove);
141
+ document.removeEventListener('pointerleave', onLeave);
142
+ document.removeEventListener('visibilitychange', onVisibility);
143
+ }
144
+ if (timer)
145
+ clearTimeout(timer);
146
+ room.presence({ [adapter.key]: null }).catch(() => undefined);
147
+ });
148
+ // The peer list.
149
+ const heard = (peers) => {
150
+ store.setState({ peers: peerViews(peers, self, adapter.key, adapter.parse) });
151
+ adapter.onPeers?.(peers, self);
152
+ };
153
+ room.peers().then(heard, () => undefined);
154
+ stops.push(room.onPeers(heard));
155
+ return () => stops.forEach((stop) => stop());
156
+ }
157
+ return { store, start };
158
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Loading the design systems an artifact installed (Design, Slides): each
3
+ * copy lives under `project/ds/<folder>/`; its `tokens.json` is read,
4
+ * normalized and handed to the editor, which turns it into what its menus
5
+ * offer. The copies are read again when the installed list changes or a
6
+ * `tokens.json` under `project/ds/` changes; an older read that finishes
7
+ * late is dropped. Pure (no DOM).
8
+ */
9
+ import { type NormalizedTokens } from '@open-artifact/design-system-core';
10
+ import type { ArtifactCapability } from '@open-artifact/runtime';
11
+ /** Where installed systems live, as an artifact path. */
12
+ export declare const DS_DIR = "project/ds/";
13
+ /** An installed copy as an artifact's index records it. */
14
+ export interface InstalledRecord {
15
+ namespace: string;
16
+ version?: string | null;
17
+ copiedAt: string;
18
+ }
19
+ /** What one read of every copy found. */
20
+ export interface SystemsRead<S> {
21
+ systems: S[];
22
+ /** Namespaces whose copy could not be read (no tokens.json, or not JSON). */
23
+ missing: string[];
24
+ }
25
+ /** What an editor supplies to {@link createSystemsLoader}. */
26
+ export interface SystemsLoaderAdapter<R extends InstalledRecord, S> {
27
+ /** The artifact to read from (`null`: not connected yet, nothing is read). */
28
+ artifact(): ArtifactCapability | null;
29
+ /** The installed records now. */
30
+ records(): readonly R[];
31
+ /** Calls `listener` whenever the editor's document changes (the loader checks whether the records did). */
32
+ subscribe(listener: () => void): unknown;
33
+ /** Reads a copy's normalized tokens into what the editor offers. */
34
+ read(record: R, tokens: NormalizedTokens): S;
35
+ /** Stores a finished read. */
36
+ loaded(result: SystemsRead<S>): void;
37
+ }
38
+ /** A loader made by {@link createSystemsLoader}. */
39
+ export interface SystemsLoader {
40
+ /** Re-reads every copy now. */
41
+ reload(): Promise<void>;
42
+ /** Reads the copies and keeps them current. Later calls do nothing. */
43
+ start(): void;
44
+ }
45
+ /** The loader of an editor's installed design systems. */
46
+ export declare function createSystemsLoader<R extends InstalledRecord, S>(adapter: SystemsLoaderAdapter<R, S>): SystemsLoader;