@openartifactsai/editor-kit 0.0.0-stage → 0.23.0-rc.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 (120) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +143 -2
  4. package/package.json +67 -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 +37 -0
  9. package/src/FoldToolbar.d.ts +58 -0
  10. package/src/FoldToolbar.js +438 -0
  11. package/src/PanelEdge.d.ts +20 -0
  12. package/src/PanelEdge.js +74 -0
  13. package/src/VideoShrinkNotice.d.ts +10 -0
  14. package/src/VideoShrinkNotice.js +81 -0
  15. package/src/WheelZoomItem.d.ts +12 -0
  16. package/src/WheelZoomItem.js +18 -0
  17. package/src/agent.d.ts +68 -0
  18. package/src/agent.js +113 -0
  19. package/src/announce.d.ts +21 -0
  20. package/src/announce.js +31 -0
  21. package/src/chrome.d.ts +208 -0
  22. package/src/chrome.js +148 -0
  23. package/src/clipboard.d.ts +19 -0
  24. package/src/clipboard.js +48 -0
  25. package/src/collab/CommentList.d.ts +32 -0
  26. package/src/collab/CommentList.js +165 -0
  27. package/src/collab/CommentViews.d.ts +131 -0
  28. package/src/collab/CommentViews.js +619 -0
  29. package/src/collab/HistoryViews.d.ts +38 -0
  30. package/src/collab/HistoryViews.js +103 -0
  31. package/src/collab/PresenceViews.d.ts +53 -0
  32. package/src/collab/PresenceViews.js +48 -0
  33. package/src/collab/cds/cds.d.ts +151 -0
  34. package/src/collab/cds/cds.js +231 -0
  35. package/src/collab/cds/comment-card.d.ts +113 -0
  36. package/src/collab/cds/comment-card.js +230 -0
  37. package/src/collab/cds/comment-composer.d.ts +35 -0
  38. package/src/collab/cds/comment-composer.js +125 -0
  39. package/src/collab/cds/comments-css.d.ts +2 -0
  40. package/src/collab/cds/comments-css.js +3 -0
  41. package/src/collab/cds/comments.css +504 -0
  42. package/src/collab/cds/edge-piles.d.ts +69 -0
  43. package/src/collab/cds/edge-piles.js +178 -0
  44. package/src/collab/cds/layer.d.ts +41 -0
  45. package/src/collab/cds/layer.js +144 -0
  46. package/src/collab/cds/markdown.d.ts +20 -0
  47. package/src/collab/cds/markdown.js +534 -0
  48. package/src/collab/cds/shield.d.ts +28 -0
  49. package/src/collab/cds/shield.js +114 -0
  50. package/src/collab/cds/time.d.ts +2 -0
  51. package/src/collab/cds/time.js +41 -0
  52. package/src/collab/collab.d.ts +102 -0
  53. package/src/collab/collab.js +121 -0
  54. package/src/collab/comments.d.ts +272 -0
  55. package/src/collab/comments.js +596 -0
  56. package/src/collab/history-wiring.d.ts +32 -0
  57. package/src/collab/history-wiring.js +53 -0
  58. package/src/collab/history.d.ts +59 -0
  59. package/src/collab/history.js +96 -0
  60. package/src/collab/mentions/mention-list.d.ts +63 -0
  61. package/src/collab/mentions/mention-list.js +257 -0
  62. package/src/collab/mentions.d.ts +112 -0
  63. package/src/collab/mentions.js +164 -0
  64. package/src/collab/peer-colors.d.ts +123 -0
  65. package/src/collab/peer-colors.js +273 -0
  66. package/src/collab/pins.d.ts +70 -0
  67. package/src/collab/pins.js +44 -0
  68. package/src/collab/presence.d.ts +92 -0
  69. package/src/collab/presence.js +158 -0
  70. package/src/design-systems.d.ts +46 -0
  71. package/src/design-systems.js +61 -0
  72. package/src/downloads.d.ts +31 -0
  73. package/src/downloads.js +46 -0
  74. package/src/file-drop.d.ts +33 -0
  75. package/src/file-drop.js +36 -0
  76. package/src/find.d.ts +64 -0
  77. package/src/find.js +147 -0
  78. package/src/follow.d.ts +141 -0
  79. package/src/follow.js +389 -0
  80. package/src/index.d.ts +32 -0
  81. package/src/index.js +32 -0
  82. package/src/keys.d.ts +18 -0
  83. package/src/keys.js +42 -0
  84. package/src/menu-fit.d.ts +12 -0
  85. package/src/menu-fit.js +9 -0
  86. package/src/merge.d.ts +23 -0
  87. package/src/merge.js +116 -0
  88. package/src/page-link.d.ts +33 -0
  89. package/src/page-link.js +75 -0
  90. package/src/project-sync.d.ts +161 -0
  91. package/src/project-sync.js +319 -0
  92. package/src/react.d.ts +20 -0
  93. package/src/react.js +20 -0
  94. package/src/read-retries.d.ts +55 -0
  95. package/src/read-retries.js +125 -0
  96. package/src/right-drag-pan.d.ts +128 -0
  97. package/src/right-drag-pan.js +253 -0
  98. package/src/roles.d.ts +39 -0
  99. package/src/roles.js +27 -0
  100. package/src/session.d.ts +56 -0
  101. package/src/session.js +57 -0
  102. package/src/shell.d.ts +60 -0
  103. package/src/shell.js +111 -0
  104. package/src/stash.d.ts +26 -0
  105. package/src/stash.js +69 -0
  106. package/src/styles.css +17 -0
  107. package/src/toolbar-fold.d.ts +106 -0
  108. package/src/toolbar-fold.js +130 -0
  109. package/src/video-shrink/index.d.ts +8 -0
  110. package/src/video-shrink/index.js +7 -0
  111. package/src/video-shrink/plan.d.ts +92 -0
  112. package/src/video-shrink/plan.js +133 -0
  113. package/src/video-shrink/protocol.d.ts +29 -0
  114. package/src/video-shrink/protocol.js +2 -0
  115. package/src/video-shrink/queue.d.ts +69 -0
  116. package/src/video-shrink/queue.js +287 -0
  117. package/src/video-shrink/worker.d.ts +8 -0
  118. package/src/video-shrink/worker.js +223 -0
  119. package/src/wheel-zoom.d.ts +14 -0
  120. package/src/wheel-zoom.js +48 -0
@@ -0,0 +1,253 @@
1
+ /**
2
+ * Dragging a canvas with the right mouse button. A right press that travels a
3
+ * few pixels pans the view and does nothing else: the selection stays as it
4
+ * was and no menu opens. One that does not travel is the right-click it always
5
+ * was: once the button is up, the press goes on to the editor and the menu
6
+ * opens where it was pressed.
7
+ *
8
+ * Browsers ask for the menu at different times: macOS and Linux send
9
+ * `contextmenu` right after the press, Windows after the release. So the press
10
+ * is held back until it is known which it is, the menu asked for meanwhile is
11
+ * stopped, and on a release without travel the press is sent again (and, when
12
+ * the menu was already asked for, the menu too). A `contextmenu` that follows
13
+ * a pan is stopped.
14
+ *
15
+ * {@link rightPressStep} is the decision, without a DOM; {@link installRightDragPan}
16
+ * wires it to a canvas element.
17
+ */
18
+ /** Distance a right press travels before it pans, CSS px. */
19
+ export const RIGHT_PAN_THRESHOLD = 4;
20
+ /** How long after a pan a late `contextmenu` (Windows sends it after the release) is still stopped, ms. */
21
+ export const RIGHT_PAN_QUIET_MS = 500;
22
+ /** No right press. */
23
+ export const RIGHT_PRESS_IDLE = { phase: 'idle', quietUntil: Number.NEGATIVE_INFINITY };
24
+ /** The next state of a right press, and what to do with the event that moved it there. */
25
+ export function rightPressStep(state, input) {
26
+ switch (input.type) {
27
+ case 'press':
28
+ // A second press while one is held (another pointer) is let alone.
29
+ if (state.phase === 'held' || state.phase === 'panning')
30
+ return { state, effect: { do: 'pass' } };
31
+ return { state: { phase: 'held', id: input.id, x: input.x, y: input.y, menu: false }, effect: { do: 'stop' } };
32
+ case 'move':
33
+ if (state.phase === 'held' && state.id === input.id) {
34
+ const dx = input.x - state.x;
35
+ const dy = input.y - state.y;
36
+ if (Math.hypot(dx, dy) < RIGHT_PAN_THRESHOLD)
37
+ return { state, effect: { do: 'stop' } };
38
+ return { state: { phase: 'panning', id: input.id, x: input.x, y: input.y }, effect: { do: 'pan', dx, dy, start: true } };
39
+ }
40
+ if (state.phase === 'panning' && state.id === input.id) {
41
+ return { state: { ...state, x: input.x, y: input.y }, effect: { do: 'pan', dx: input.x - state.x, dy: input.y - state.y, start: false } };
42
+ }
43
+ return { state, effect: { do: 'pass' } };
44
+ case 'release':
45
+ if (state.phase === 'held' && state.id === input.id) {
46
+ // Not asked for yet (Windows): the browser asks after the release, and that is let through.
47
+ return { state: RIGHT_PRESS_IDLE, effect: { do: 'click', menu: state.menu } };
48
+ }
49
+ if (state.phase === 'panning' && state.id === input.id) {
50
+ return { state: { phase: 'idle', quietUntil: input.time + RIGHT_PAN_QUIET_MS }, effect: { do: 'end' } };
51
+ }
52
+ return { state, effect: { do: 'pass' } };
53
+ case 'cancel':
54
+ if ((state.phase === 'held' || state.phase === 'panning') && state.id === input.id) {
55
+ return { state: { phase: 'idle', quietUntil: input.time + RIGHT_PAN_QUIET_MS }, effect: { do: state.phase === 'panning' ? 'end' : 'stop' } };
56
+ }
57
+ return { state, effect: { do: 'pass' } };
58
+ case 'menu':
59
+ if (state.phase === 'held')
60
+ return { state: { ...state, menu: true }, effect: { do: 'stop' } };
61
+ if (state.phase === 'panning')
62
+ return { state, effect: { do: 'stop' } };
63
+ return input.time < state.quietUntil ? { state: RIGHT_PRESS_IDLE, effect: { do: 'stop' } } : { state, effect: { do: 'pass' } };
64
+ }
65
+ }
66
+ /** Set on `<html>` while a right-button pan runs; the grabbing cursor is drawn from it. */
67
+ export const RIGHT_PAN_ATTRIBUTE = 'data-right-drag-pan';
68
+ const RIGHT_BUTTON = 2;
69
+ const RIGHT_BUTTONS_MASK = 2;
70
+ const TYPING = 'input, textarea, select, [contenteditable]:not([contenteditable="false"])';
71
+ /** Events this module sent itself: they go through untouched. */
72
+ const sentAgain = new WeakSet();
73
+ function grabbingStyle(doc) {
74
+ if (doc.getElementById('open-artifacts-right-drag-pan'))
75
+ return;
76
+ const style = doc.createElement('style');
77
+ style.id = 'open-artifacts-right-drag-pan';
78
+ style.textContent = `html[${RIGHT_PAN_ATTRIBUTE}], html[${RIGHT_PAN_ATTRIBUTE}] * { cursor: grabbing !important; }`;
79
+ doc.head.append(style);
80
+ }
81
+ /**
82
+ * Lets the right mouse button drag `surface` (see the top of this file).
83
+ * Listens on the window, in the capture phase, so the press is held back
84
+ * before the editor's own handlers (React's included) see it. Returns the
85
+ * uninstaller.
86
+ */
87
+ export function installRightDragPan(surface, options) {
88
+ const doc = surface.ownerDocument;
89
+ const win = doc.defaultView;
90
+ if (!win)
91
+ return () => { };
92
+ grabbingStyle(doc);
93
+ let state = RIGHT_PRESS_IDLE;
94
+ /** The held press, to send again on a right-click. */
95
+ let press = null;
96
+ let menuTimer;
97
+ const panning = (on, pointerId) => {
98
+ if (on) {
99
+ doc.documentElement.setAttribute(RIGHT_PAN_ATTRIBUTE, '');
100
+ try {
101
+ if (pointerId !== undefined)
102
+ surface.setPointerCapture(pointerId);
103
+ }
104
+ catch {
105
+ // The pointer is gone already.
106
+ }
107
+ }
108
+ else {
109
+ doc.documentElement.removeAttribute(RIGHT_PAN_ATTRIBUTE);
110
+ try {
111
+ if (pointerId !== undefined && surface.hasPointerCapture(pointerId))
112
+ surface.releasePointerCapture(pointerId);
113
+ }
114
+ catch {
115
+ // Nothing to release.
116
+ }
117
+ }
118
+ options.onPanning?.(on);
119
+ };
120
+ /** The held press goes on to the editor, and the menu opens if it was asked for. */
121
+ const click = (menu) => {
122
+ const held = press;
123
+ press = null;
124
+ if (!held)
125
+ return;
126
+ const at = held.target instanceof Node && held.target.isConnected ? held.target : doc.elementFromPoint(held.clientX, held.clientY);
127
+ if (!at)
128
+ return;
129
+ const again = new PointerEvent('pointerdown', held);
130
+ sentAgain.add(again);
131
+ at.dispatchEvent(again);
132
+ if (!menu)
133
+ return;
134
+ // After the release has reached the editor, as a right-click on Windows would have it.
135
+ clearTimeout(menuTimer);
136
+ menuTimer = setTimeout(() => {
137
+ const target = at.isConnected ? at : doc.elementFromPoint(held.clientX, held.clientY);
138
+ if (!target)
139
+ return;
140
+ const ask = new MouseEvent('contextmenu', {
141
+ bubbles: true,
142
+ cancelable: true,
143
+ composed: true,
144
+ view: win,
145
+ button: RIGHT_BUTTON,
146
+ buttons: 0,
147
+ clientX: held.clientX,
148
+ clientY: held.clientY,
149
+ screenX: held.screenX,
150
+ screenY: held.screenY,
151
+ shiftKey: held.shiftKey,
152
+ altKey: held.altKey,
153
+ ctrlKey: held.ctrlKey,
154
+ metaKey: held.metaKey,
155
+ });
156
+ sentAgain.add(ask);
157
+ target.dispatchEvent(ask);
158
+ });
159
+ };
160
+ const apply = (event, input) => {
161
+ const before = state;
162
+ const step = rightPressStep(state, input);
163
+ state = step.state;
164
+ const { effect } = step;
165
+ switch (effect.do) {
166
+ case 'pass':
167
+ return;
168
+ case 'stop':
169
+ event.stopPropagation();
170
+ if (event.type === 'contextmenu')
171
+ event.preventDefault();
172
+ if (input.type === 'cancel')
173
+ press = null;
174
+ return;
175
+ case 'pan':
176
+ event.stopPropagation();
177
+ if (effect.start)
178
+ panning(true, before.phase === 'held' ? before.id : undefined);
179
+ options.pan(effect.dx, effect.dy);
180
+ return;
181
+ case 'end':
182
+ event.stopPropagation();
183
+ press = null;
184
+ panning(false, before.phase === 'panning' ? before.id : undefined);
185
+ return;
186
+ case 'click':
187
+ // The release itself goes on, after the press it follows.
188
+ click(effect.menu);
189
+ return;
190
+ }
191
+ };
192
+ const onDown = (event) => {
193
+ if (sentAgain.has(event) || event.button !== RIGHT_BUTTON || event.pointerType === 'touch')
194
+ return;
195
+ const target = event.target;
196
+ if (!(target instanceof Element) || !surface.contains(target) || target.closest(TYPING))
197
+ return;
198
+ if (options.accepts && !options.accepts(event))
199
+ return;
200
+ if (state.phase === 'held' || state.phase === 'panning')
201
+ return;
202
+ press = event;
203
+ apply(event, { type: 'press', id: event.pointerId, x: event.clientX, y: event.clientY, time: event.timeStamp });
204
+ };
205
+ const onMove = (event) => {
206
+ if (state.phase !== 'held' && state.phase !== 'panning')
207
+ return;
208
+ if (event.pointerId !== state.id)
209
+ return;
210
+ // The release happened where no one heard it: a pan ends, a press opens no menu.
211
+ if ((event.buttons & RIGHT_BUTTONS_MASK) === 0) {
212
+ apply(event, { type: 'cancel', id: event.pointerId, time: event.timeStamp });
213
+ return;
214
+ }
215
+ apply(event, { type: 'move', id: event.pointerId, x: event.clientX, y: event.clientY, time: event.timeStamp });
216
+ };
217
+ const onUp = (event) => {
218
+ if (sentAgain.has(event))
219
+ return;
220
+ apply(event, { type: 'release', id: event.pointerId, x: event.clientX, y: event.clientY, time: event.timeStamp });
221
+ };
222
+ const onCancel = (event) => {
223
+ apply(event, { type: 'cancel', id: event.pointerId, time: event.timeStamp });
224
+ };
225
+ const onMenu = (event) => {
226
+ if (sentAgain.has(event))
227
+ return;
228
+ apply(event, { type: 'menu', time: event.timeStamp });
229
+ };
230
+ const onBlur = () => {
231
+ if (state.phase === 'panning')
232
+ panning(false, state.id);
233
+ state = RIGHT_PRESS_IDLE;
234
+ press = null;
235
+ };
236
+ const capture = { capture: true };
237
+ win.addEventListener('pointerdown', onDown, capture);
238
+ win.addEventListener('pointermove', onMove, capture);
239
+ win.addEventListener('pointerup', onUp, capture);
240
+ win.addEventListener('pointercancel', onCancel, capture);
241
+ win.addEventListener('contextmenu', onMenu, capture);
242
+ win.addEventListener('blur', onBlur);
243
+ return () => {
244
+ clearTimeout(menuTimer);
245
+ onBlur();
246
+ win.removeEventListener('pointerdown', onDown, capture);
247
+ win.removeEventListener('pointermove', onMove, capture);
248
+ win.removeEventListener('pointerup', onUp, capture);
249
+ win.removeEventListener('pointercancel', onCancel, capture);
250
+ win.removeEventListener('contextmenu', onMenu, capture);
251
+ win.removeEventListener('blur', onBlur);
252
+ };
253
+ }
package/src/roles.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * What each role may do in an artifact, the way the host's sharing rules
3
+ * allow it, so an editor only offers what the server will accept:
4
+ *
5
+ * - owner: everything, including sending requests to the agent, saving
6
+ * files to the computer that shares the artifact and calling its
7
+ * connectors (`mcp`);
8
+ * - editor (a guest who may edit): changes the artifact, removes comments
9
+ * and restores versions, but cannot reach the owner's agent or downloads;
10
+ * - commenter: comments (add, reply, resolve, move) on a read-only artifact;
11
+ * - viewer: reads only.
12
+ *
13
+ * Pure.
14
+ */
15
+ import type { Role } from '@openartifactsai/runtime';
16
+ /** What a viewer may do. */
17
+ export interface RoleAbilities {
18
+ /** Change the artifact (owner or editor). */
19
+ canEdit: boolean;
20
+ /** Add, reply to, resolve and move comments (anyone but a plain viewer). */
21
+ canComment: boolean;
22
+ /** Delete comment threads (owner or editor). */
23
+ canRemoveComments: boolean;
24
+ /** Restore a past version (owner or editor). */
25
+ canRestore: boolean;
26
+ /** Send requests to the agent: Ask, "Send to agent" on a comment (the owner alone). */
27
+ canAsk: boolean;
28
+ /**
29
+ * Save files through the host's downloads, on the sharing computer (the owner alone; guests get a browser download).
30
+ * Every role on a host whose downloads save in the browser (see `hostAbilities`).
31
+ */
32
+ canSaveToHost: boolean;
33
+ /** Call the connectors (MCP servers) set up on the sharing computer (the owner alone). */
34
+ canUseConnectors: boolean;
35
+ }
36
+ /** The abilities of a role. An unknown role reads only. */
37
+ export declare function roleAbilities(role: Role | string): RoleAbilities;
38
+ /** How the chrome names a read-only role (`null`: the viewer can edit). */
39
+ export declare function readOnlyLabel(role: Role | string): string | null;
package/src/roles.js ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * What each role may do in an artifact, the way the host's sharing rules
3
+ * allow it, so an editor only offers what the server will accept:
4
+ *
5
+ * - owner: everything, including sending requests to the agent, saving
6
+ * files to the computer that shares the artifact and calling its
7
+ * connectors (`mcp`);
8
+ * - editor (a guest who may edit): changes the artifact, removes comments
9
+ * and restores versions, but cannot reach the owner's agent or downloads;
10
+ * - commenter: comments (add, reply, resolve, move) on a read-only artifact;
11
+ * - viewer: reads only.
12
+ *
13
+ * Pure.
14
+ */
15
+ /** The abilities of a role. An unknown role reads only. */
16
+ export function roleAbilities(role) {
17
+ const owner = role === 'owner';
18
+ const edits = owner || role === 'editor';
19
+ const comments = edits || role === 'commenter';
20
+ return { canEdit: edits, canComment: comments, canRemoveComments: edits, canRestore: edits, canAsk: owner, canSaveToHost: owner, canUseConnectors: owner };
21
+ }
22
+ /** How the chrome names a read-only role (`null`: the viewer can edit). */
23
+ export function readOnlyLabel(role) {
24
+ if (roleAbilities(role).canEdit)
25
+ return null;
26
+ return role === 'commenter' ? 'Comment only' : 'View only';
27
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * An editor's connection to its host: installs `window.openartifacts` (unless
3
+ * a host already did), resolves the capabilities the editor names, reads the
4
+ * viewer and their role, and connects to the Open Artifacts Shell framing the
5
+ * page. Each editor keeps its own `Session` shape (which capabilities it
6
+ * needs, which one it cannot work without) and builds it from
7
+ * {@link connectHost}. Pure (no DOM until called).
8
+ */
9
+ import { type CapabilityMap, type CapabilityName, type ShellConnection, type Viewer } from '@openartifactsai/runtime';
10
+ import { type RoleAbilities } from './roles.js';
11
+ /** The viewer a host that names no one gets: reads only. */
12
+ export declare const GUEST_VIEWER: Readonly<Viewer>;
13
+ /** The named capabilities; a missing one is `null`. */
14
+ export type HostCapabilities<N extends CapabilityName> = {
15
+ [K in N]: CapabilityMap[K] | null;
16
+ };
17
+ /** What {@link connectHost} resolves. */
18
+ export interface HostConnection<N extends CapabilityName> {
19
+ caps: HostCapabilities<N>;
20
+ viewer: Viewer;
21
+ /** What the viewer's role allows. */
22
+ abilities: RoleAbilities;
23
+ /** The Open Artifacts Shell framing this page, if any. */
24
+ shell: ShellConnection | null;
25
+ }
26
+ /**
27
+ * Connects to the host and resolves `names` (plus `user`, for the viewer). `shell`: a Shell connection the page already
28
+ * opened (`null` when it knows there is none); omitted, this connects to the Shell itself.
29
+ */
30
+ export declare function connectHost<const N extends Exclude<CapabilityName, 'user'>>(names: readonly N[], shell?: ShellConnection | null): Promise<HostConnection<N>>;
31
+ /**
32
+ * The role's abilities on this host. A host whose `downloads` saves in the browser (a cloud host) takes every role's
33
+ * files and decides there whether the person may export (a viewer only when the owner allows it), so the page sends
34
+ * them all through it instead of starting a download of its own.
35
+ */
36
+ export declare function hostAbilities(role: Viewer['role'], downloads: Pick<CapabilityMap['downloads'], 'browser'> | null | undefined): RoleAbilities;
37
+ /**
38
+ * Whether the person may start an export that the editor otherwise keeps for the owner: the owner, or anyone on a host
39
+ * whose `downloads` saves in the browser (the host refuses a viewer there unless the owner allows it).
40
+ */
41
+ export declare function mayExportHere(role: Viewer['role'], downloads: Pick<CapabilityMap['downloads'], 'browser'> | null | undefined): boolean;
42
+ /** Holds an editor's session once it started. */
43
+ export interface SessionSlot<S> {
44
+ /** The session; throws before it started. */
45
+ session(): S;
46
+ /** The session, or `null` before it started (code that may run early). */
47
+ maybeSession(): S | null;
48
+ /** Stores the started session and returns it. */
49
+ set(session: S): S;
50
+ }
51
+ /** A {@link SessionSlot}. */
52
+ export declare function sessionSlot<S>(): SessionSlot<S>;
53
+ /** The artifact path of a project path. */
54
+ export declare const artifactPath: (path: string) => string;
55
+ /** The project path of an artifact path, or `null` outside `project/`. */
56
+ export declare const projectPath: (path: string) => string | null;
package/src/session.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * An editor's connection to its host: installs `window.openartifacts` (unless
3
+ * a host already did), resolves the capabilities the editor names, reads the
4
+ * viewer and their role, and connects to the Open Artifacts Shell framing the
5
+ * page. Each editor keeps its own `Session` shape (which capabilities it
6
+ * needs, which one it cannot work without) and builds it from
7
+ * {@link connectHost}. Pure (no DOM until called).
8
+ */
9
+ import { connectShell, createPageProvider, installRuntime } from '@openartifactsai/runtime';
10
+ import { roleAbilities } from "./roles.js";
11
+ /** The viewer a host that names no one gets: reads only. */
12
+ export const GUEST_VIEWER = Object.freeze({ id: 'viewer', name: 'Viewer', role: 'viewer' });
13
+ /**
14
+ * Connects to the host and resolves `names` (plus `user`, for the viewer). `shell`: a Shell connection the page already
15
+ * opened (`null` when it knows there is none); omitted, this connects to the Shell itself.
16
+ */
17
+ export async function connectHost(names, shell) {
18
+ const runtime = installRuntime(createPageProvider());
19
+ const [user, ...granted] = await Promise.all([runtime.use('user'), ...names.map((name) => runtime.use(name))]);
20
+ const caps = Object.fromEntries(names.map((name, i) => [name, granted[i] ?? null]));
21
+ const viewer = (await user?.me()) ?? { ...GUEST_VIEWER };
22
+ const abilities = hostAbilities(viewer.role, caps.downloads);
23
+ return { caps, viewer, abilities, shell: shell === undefined ? connectShell() : shell };
24
+ }
25
+ /**
26
+ * The role's abilities on this host. A host whose `downloads` saves in the browser (a cloud host) takes every role's
27
+ * files and decides there whether the person may export (a viewer only when the owner allows it), so the page sends
28
+ * them all through it instead of starting a download of its own.
29
+ */
30
+ export function hostAbilities(role, downloads) {
31
+ const abilities = roleAbilities(role);
32
+ return downloads?.browser === true ? { ...abilities, canSaveToHost: true } : abilities;
33
+ }
34
+ /**
35
+ * Whether the person may start an export that the editor otherwise keeps for the owner: the owner, or anyone on a host
36
+ * whose `downloads` saves in the browser (the host refuses a viewer there unless the owner allows it).
37
+ */
38
+ export function mayExportHere(role, downloads) {
39
+ return role === 'owner' || downloads?.browser === true;
40
+ }
41
+ /** A {@link SessionSlot}. */
42
+ export function sessionSlot() {
43
+ let current = null;
44
+ return {
45
+ session() {
46
+ if (current === null)
47
+ throw new Error('The session has not started.');
48
+ return current;
49
+ },
50
+ maybeSession: () => current,
51
+ set: (session) => (current = session),
52
+ };
53
+ }
54
+ /** The artifact path of a project path. */
55
+ export const artifactPath = (path) => `project/${path}`;
56
+ /** The project path of an artifact path, or `null` outside `project/`. */
57
+ export const projectPath = (path) => (path.startsWith('project/') ? path.slice('project/'.length) : null);
package/src/shell.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The bridge to an Open Artifacts Shell framing the page.
3
+ *
4
+ * The Shell draws the shared top bar (save state, comments, export, Ask)
5
+ * from one report the page sends whole. An editor builds that report one of
6
+ * two ways:
7
+ *
8
+ * - from one function that reads every store: {@link chromeReporter} sends
9
+ * it only when it changed (Design, Slides, Design System);
10
+ * - from parts different services own (sync owns `saved`, collaboration
11
+ * owns `comments`, export owns `formats`): {@link createShellBridge}
12
+ * merges the parts, sends one report per microtask and fans the Shell's
13
+ * commands out to every handler (Whiteboard).
14
+ *
15
+ * Outside a Shell every call is a no-op. Pure (no DOM).
16
+ */
17
+ import { type StoreApi, type UseBoundStore } from 'zustand';
18
+ import type { ChromeCommand, ChromeDraw, ChromeExportItem, ChromeReport, ShellConnection } from '@openartifactsai/runtime';
19
+ /** The agent part of a report, from the agent status every editor watches. */
20
+ export declare function agentChrome(status: {
21
+ available: boolean;
22
+ busy: boolean;
23
+ }): NonNullable<ChromeReport['agent']>;
24
+ /**
25
+ * A function that builds the report with `build` and sends it to `shell`
26
+ * when it differs from the last one sent.
27
+ */
28
+ export declare function chromeReporter(shell: ShellConnection, build: () => ChromeReport): () => void;
29
+ /** What the Shell draws for the page (empty outside a Shell). */
30
+ export interface ShellDrawsState {
31
+ draws: ReadonlySet<ChromeDraw>;
32
+ /** A Shell frames this page. */
33
+ framed: boolean;
34
+ }
35
+ /**
36
+ * A handler of Shell commands; may answer an `exports` request with items.
37
+ * Every command reaches every handler, `follow` too (sent where the report
38
+ * has `following`, with a key from its `peers` or `null` to stop).
39
+ */
40
+ export type ShellCommandHandler = (command: ChromeCommand) => ChromeExportItem[] | void;
41
+ /** A bridge made by {@link createShellBridge}. */
42
+ export interface ShellBridge {
43
+ /** What the Shell draws for this page; components hide their own copy of what it draws. */
44
+ useShellDraws: UseBoundStore<StoreApi<ShellDrawsState>>;
45
+ /**
46
+ * Sets parts of the report (keys set to `undefined` are removed) and sends
47
+ * the merged report on the next microtask.
48
+ */
49
+ setShellReport(part: Partial<ChromeReport>): void;
50
+ /** Adds a Shell command handler; returns a function that removes it. The first handler that returns export items answers an `exports` request. */
51
+ onShellCommand(handler: ShellCommandHandler): () => void;
52
+ /**
53
+ * Connects to the Shell, if one frames the page: tracks what it draws,
54
+ * dispatches its commands and tells it the page merges file changes live
55
+ * (so it never reloads the frame under the viewer). Returns a stop function.
56
+ */
57
+ startShell(): () => void;
58
+ }
59
+ /** A report-by-parts bridge; `shell` reads the connection (`null` outside a Shell or before the session started). */
60
+ export declare function createShellBridge(shell: () => ShellConnection | null | undefined): ShellBridge;
package/src/shell.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The bridge to an Open Artifacts Shell framing the page.
3
+ *
4
+ * The Shell draws the shared top bar (save state, comments, export, Ask)
5
+ * from one report the page sends whole. An editor builds that report one of
6
+ * two ways:
7
+ *
8
+ * - from one function that reads every store: {@link chromeReporter} sends
9
+ * it only when it changed (Design, Slides, Design System);
10
+ * - from parts different services own (sync owns `saved`, collaboration
11
+ * owns `comments`, export owns `formats`): {@link createShellBridge}
12
+ * merges the parts, sends one report per microtask and fans the Shell's
13
+ * commands out to every handler (Whiteboard).
14
+ *
15
+ * Outside a Shell every call is a no-op. Pure (no DOM).
16
+ */
17
+ import { create } from 'zustand';
18
+ /** The agent part of a report, from the agent status every editor watches. */
19
+ export function agentChrome(status) {
20
+ return { available: status.available, listening: status.available, busy: status.busy };
21
+ }
22
+ /**
23
+ * A function that builds the report with `build` and sends it to `shell`
24
+ * when it differs from the last one sent.
25
+ */
26
+ export function chromeReporter(shell, build) {
27
+ let last = '';
28
+ return () => {
29
+ const next = build();
30
+ const text = JSON.stringify(next);
31
+ if (text === last)
32
+ return;
33
+ last = text;
34
+ shell.report(next);
35
+ };
36
+ }
37
+ /** A report-by-parts bridge; `shell` reads the connection (`null` outside a Shell or before the session started). */
38
+ export function createShellBridge(shell) {
39
+ const useShellDraws = create()(() => ({ draws: new Set(), framed: false }));
40
+ let report = {};
41
+ let scheduled = false;
42
+ let active = null;
43
+ let generation = 0;
44
+ const handlers = new Set();
45
+ function send() {
46
+ scheduled = false;
47
+ active?.report(report);
48
+ }
49
+ function setShellReport(part) {
50
+ const next = { ...report };
51
+ let changed = false;
52
+ for (const [key, value] of Object.entries(part)) {
53
+ if (JSON.stringify(next[key]) === JSON.stringify(value))
54
+ continue;
55
+ changed = true;
56
+ if (value === undefined)
57
+ delete next[key];
58
+ else
59
+ next[key] = value;
60
+ }
61
+ if (!changed)
62
+ return;
63
+ report = next;
64
+ if (active && !scheduled) {
65
+ scheduled = true;
66
+ const owner = generation;
67
+ queueMicrotask(() => { if (owner === generation)
68
+ send(); });
69
+ }
70
+ }
71
+ function onShellCommand(handler) {
72
+ handlers.add(handler);
73
+ return () => void handlers.delete(handler);
74
+ }
75
+ function startShell() {
76
+ const connection = shell();
77
+ const owner = ++generation;
78
+ scheduled = false;
79
+ active = connection ?? null;
80
+ if (!connection)
81
+ return () => { if (generation === owner)
82
+ report = {}; };
83
+ useShellDraws.setState({ draws: connection.draws, framed: true });
84
+ const stops = [
85
+ connection.onHello((draws) => useShellDraws.setState({ draws })),
86
+ connection.onCommand((command) => {
87
+ let answer;
88
+ for (const handler of [...handlers]) {
89
+ const result = handler(command);
90
+ if (answer === undefined && Array.isArray(result))
91
+ answer = result;
92
+ }
93
+ return answer ?? (command.cmd === 'exports' ? [] : undefined);
94
+ }),
95
+ connection.onFilesChanged(() => true),
96
+ ];
97
+ send();
98
+ return () => {
99
+ for (const stop of stops)
100
+ stop();
101
+ if (generation !== owner)
102
+ return;
103
+ generation++;
104
+ active = null;
105
+ scheduled = false;
106
+ report = {};
107
+ useShellDraws.setState({ draws: new Set(), framed: false });
108
+ };
109
+ }
110
+ return { useShellDraws, setShellReport, onShellCommand, startShell };
111
+ }
package/src/stash.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Unsaved-work recovery, the shared part: while edits wait to be saved, an
3
+ * editor copies what differs from the saved files to `localStorage` (a
4
+ * "stash"); if the tab closes before the save lands, the next visit offers
5
+ * it back. What a stash holds and how it is restored is the editor's; this
6
+ * module keeps the storage guarded, the age limit and the debounce.
7
+ */
8
+ /** How long a stash is kept, ms (three days). */
9
+ export declare const STASH_KEEP_MS: number;
10
+ /** True while a stash written at `at` may still be offered (not too old, not from the future). */
11
+ export declare function stashFresh(at: number, now: number): boolean;
12
+ /** A stored JSON value under one key, every access guarded. */
13
+ export interface StoredJson<T> {
14
+ read(): T | null;
15
+ /** Writes `value`; `null` clears. */
16
+ write(value: T | null): void;
17
+ clear(): void;
18
+ }
19
+ /**
20
+ * A JSON value stored under `key` (e.g. `open-artifacts-design:recovery:<path>`).
21
+ * `parse` validates what is read back (`null`: unusable). Storage that is
22
+ * missing, full or blocked reads as empty and ignores writes.
23
+ */
24
+ export declare function storedJson<T>(key: string, parse: (value: unknown) => T | null, storage?: () => Storage | undefined): StoredJson<T>;
25
+ /** JSON compared by value (key order and spacing aside), text otherwise. */
26
+ export declare function normalizeJson(text: string): string;