@marimo-team/islands 0.25.3-dev93 → 0.25.3-dev95

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.
@@ -0,0 +1,395 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { dequal } from "dequal";
4
+ import {
5
+ atom,
6
+ type Atom,
7
+ type createStore,
8
+ type WritableAtom,
9
+ } from "jotai/vanilla";
10
+ import { selectAtom } from "jotai/vanilla/utils";
11
+ import type { Document } from "../host/resources/document";
12
+ import * as Protocol from "@marimo-team/client/protocol";
13
+ import {
14
+ acknowledge,
15
+ type CellEdit,
16
+ createCell,
17
+ deleteCell,
18
+ type Draft,
19
+ type EditableCell,
20
+ type EditableDocument,
21
+ editCell,
22
+ EMPTY_DRAFT,
23
+ isEmptyDraft,
24
+ type Placement,
25
+ prune,
26
+ sameCell,
27
+ setOrder,
28
+ toChanges,
29
+ viewDocument,
30
+ } from "./draft";
31
+
32
+ /** Operations on a working draft, valid only during the edit callback. */
33
+ export interface DocumentEditor {
34
+ setCode(id: Protocol.CellId, code: string): void;
35
+ setName(id: Protocol.CellId, name: string): void;
36
+ updateConfig(id: Protocol.CellId, patch: Partial<Protocol.CellConfig>): void;
37
+ createCell(cell: Protocol.CellInput, placement?: Placement): void;
38
+ deleteCell(id: Protocol.CellId): void;
39
+ /** A permutation of the cells present at this point in the transaction. */
40
+ setOrder(order: readonly Protocol.CellId[]): void;
41
+ }
42
+
43
+ /** Synchronous; a thrown error discards the entire transaction. */
44
+ export type DocumentEdit = (editor: DocumentEditor) => void;
45
+
46
+ /** A captured edit request. Return this same object when reporting its result. */
47
+ export interface DocumentSubmission {
48
+ readonly notebookId: Protocol.NotebookId;
49
+ readonly changes: readonly Protocol.Change[];
50
+ }
51
+
52
+ type ResponseRevision = Pick<Protocol.Document, "notebook_id" | "version">;
53
+
54
+ interface PendingSubmission {
55
+ readonly submission: DocumentSubmission;
56
+ readonly draft: Draft;
57
+ readonly responseRevision: ResponseRevision | null;
58
+ }
59
+
60
+ interface ModelState {
61
+ readonly confirmed: Document | null;
62
+ readonly drafts: ReadonlyMap<Protocol.NotebookId, Draft>;
63
+ readonly pending: PendingSubmission | null;
64
+ }
65
+
66
+ /**
67
+ * Local edits over confirmed host state, with one submission in flight.
68
+ *
69
+ * A reset retains the submission so its receipt can reconcile a new snapshot.
70
+ * Switching notebook identity invalidates it, retaining each notebook's draft.
71
+ */
72
+ export interface DocumentModel {
73
+ /** Hold onto the selector; its value is stable until the cell changes. */
74
+ cellAtom(id: Protocol.CellId): Atom<EditableCell | undefined>;
75
+ readonly orderAtom: Atom<readonly Protocol.CellId[] | null>;
76
+ readonly appConfigAtom: Atom<Readonly<
77
+ Protocol.Document["app_config"]
78
+ > | null>;
79
+ /** Null when the document or source needed by a put is unavailable. */
80
+ readonly changesAtom: Atom<readonly Protocol.Change[] | null>;
81
+ /** Remains pending until both the response and its streamed revision arrive. */
82
+ readonly pendingAtom: Atom<DocumentSubmission | null>;
83
+ readonly editAtom: WritableAtom<null, [edit: DocumentEdit], void>;
84
+ /** Capture a request, or null when unavailable, unchanged, or already sending. */
85
+ readonly submitAtom: WritableAtom<null, [], DocumentSubmission | null>;
86
+ /**
87
+ * Report the response revision, or null for a rejected request.
88
+ *
89
+ * Success waits for a complete streamed document at that version or later.
90
+ * Duplicate replies and replies for another notebook are ignored. Retry an
91
+ * uncertain request with the same body and idempotency key; do not reject it
92
+ * or capture a new request until its outcome is known.
93
+ */
94
+ readonly settleAtom: WritableAtom<
95
+ null,
96
+ [submission: DocumentSubmission, responseRevision: ResponseRevision | null],
97
+ void
98
+ >;
99
+ /** Stop observing the source and invalidate pending work. Safe to repeat. */
100
+ dispose(): void;
101
+ }
102
+
103
+ function draftOf(state: ModelState): Draft {
104
+ return state.confirmed === null
105
+ ? EMPTY_DRAFT
106
+ : (state.drafts.get(state.confirmed.revision.notebook_id) ?? EMPTY_DRAFT);
107
+ }
108
+
109
+ function withDraft(state: ModelState, draft: Draft): ModelState {
110
+ if (state.confirmed === null || draft === draftOf(state)) {
111
+ return state;
112
+ }
113
+ const drafts = new Map(state.drafts);
114
+ const notebookId = state.confirmed.revision.notebook_id;
115
+ if (isEmptyDraft(draft)) {
116
+ drafts.delete(notebookId);
117
+ } else {
118
+ drafts.set(notebookId, draft);
119
+ }
120
+ return { ...state, drafts };
121
+ }
122
+
123
+ /** Publish the confirmed document and any released fields together. */
124
+ function reconcile(state: ModelState): ModelState {
125
+ const { confirmed, pending } = state;
126
+ if (confirmed === null) {
127
+ return state;
128
+ }
129
+ let draft = draftOf(state);
130
+ if (
131
+ pending !== null &&
132
+ pending.responseRevision !== null &&
133
+ confirmed.revision.version >= pending.responseRevision.version
134
+ ) {
135
+ draft = acknowledge(draft, pending.draft);
136
+ state = { ...state, pending: null };
137
+ }
138
+ return withDraft(state, prune(confirmed, draft, state.pending?.draft));
139
+ }
140
+
141
+ /** Create once per source and store; the owner must dispose the model. */
142
+ export function createDocumentModel(
143
+ store: ReturnType<typeof createStore>,
144
+ source: Atom<Document | null>,
145
+ ): DocumentModel {
146
+ const stateAtom = atom<ModelState>({
147
+ confirmed: store.get(source),
148
+ drafts: new Map(),
149
+ pending: null,
150
+ });
151
+ let disposed = false;
152
+ const documentAtom = atom((get): EditableDocument | null => {
153
+ const state = get(stateAtom);
154
+ return state.confirmed === null
155
+ ? null
156
+ : viewDocument(state.confirmed, draftOf(state));
157
+ });
158
+ const cellAtom = (id: Protocol.CellId) =>
159
+ selectAtom(
160
+ documentAtom,
161
+ (document) => document?.cells.get(id),
162
+ (a, b) =>
163
+ a === b || (a !== undefined && b !== undefined && sameCell(a, b)),
164
+ );
165
+ const orderAtom = selectAtom(
166
+ documentAtom,
167
+ (document) => document?.order ?? null,
168
+ dequal,
169
+ );
170
+ const appConfigAtom = selectAtom(
171
+ stateAtom,
172
+ (state) => state.confirmed?.revision.app_config ?? null,
173
+ dequal,
174
+ );
175
+ const changesAtom = atom((get): readonly Protocol.Change[] | null => {
176
+ const state = get(stateAtom);
177
+ return state.confirmed === null
178
+ ? null
179
+ : toChanges(state.confirmed, draftOf(state));
180
+ });
181
+ const pendingAtom = atom((get) => get(stateAtom).pending?.submission ?? null);
182
+
183
+ const unsubscribe = store.sub(source, () => {
184
+ const confirmed = store.get(source);
185
+ store.set(stateAtom, (state) =>
186
+ reconcile({
187
+ ...state,
188
+ confirmed,
189
+ pending:
190
+ confirmed !== null &&
191
+ state.pending !== null &&
192
+ confirmed.revision.notebook_id !== state.pending.submission.notebookId
193
+ ? null
194
+ : state.pending,
195
+ }),
196
+ );
197
+ });
198
+
199
+ let editing = false;
200
+ const editAtom = atom(null, (get, set, edit: DocumentEdit) => {
201
+ if (editing) {
202
+ throw new Error("Document transactions cannot be nested");
203
+ }
204
+ const state = get(stateAtom);
205
+ if (disposed || state.confirmed === null) {
206
+ return;
207
+ }
208
+ editing = true;
209
+ try {
210
+ const draft = editDocument(
211
+ state.confirmed,
212
+ draftOf(state),
213
+ edit,
214
+ state.pending?.draft,
215
+ );
216
+ if (
217
+ disposed ||
218
+ get(stateAtom) !== state ||
219
+ get(source) !== state.confirmed
220
+ ) {
221
+ throw new Error("The document changed during the transaction");
222
+ }
223
+ set(stateAtom, withDraft(state, draft));
224
+ } finally {
225
+ editing = false;
226
+ }
227
+ });
228
+
229
+ const submitAtom = atom(null, (get, set): DocumentSubmission | null => {
230
+ const state = get(stateAtom);
231
+ if (disposed || state.confirmed === null || state.pending !== null) {
232
+ return null;
233
+ }
234
+ const draft = draftOf(state);
235
+ const changes = toChanges(state.confirmed, draft);
236
+ if (changes === null) {
237
+ return null;
238
+ }
239
+ if (changes.length === 0) {
240
+ set(stateAtom, withDraft(state, EMPTY_DRAFT));
241
+ return null;
242
+ }
243
+ const submission = {
244
+ notebookId: state.confirmed.revision.notebook_id,
245
+ changes,
246
+ };
247
+ set(stateAtom, {
248
+ ...state,
249
+ pending: { submission, draft, responseRevision: null },
250
+ });
251
+ return submission;
252
+ });
253
+
254
+ const settleAtom = atom(
255
+ null,
256
+ (
257
+ get,
258
+ set,
259
+ submission: DocumentSubmission,
260
+ responseRevision: ResponseRevision | null,
261
+ ) => {
262
+ const state = get(stateAtom);
263
+ if (
264
+ disposed ||
265
+ state.pending?.submission !== submission ||
266
+ state.pending.responseRevision !== null
267
+ ) {
268
+ return;
269
+ }
270
+ if (
271
+ responseRevision !== null &&
272
+ responseRevision.notebook_id !== submission.notebookId
273
+ ) {
274
+ throw new Error("Edit response belongs to another notebook");
275
+ }
276
+ set(
277
+ stateAtom,
278
+ reconcile({
279
+ ...state,
280
+ pending:
281
+ responseRevision === null
282
+ ? null
283
+ : { ...state.pending, responseRevision },
284
+ }),
285
+ );
286
+ },
287
+ );
288
+
289
+ return {
290
+ cellAtom,
291
+ orderAtom,
292
+ appConfigAtom,
293
+ changesAtom,
294
+ pendingAtom,
295
+ editAtom,
296
+ submitAtom,
297
+ settleAtom,
298
+ dispose() {
299
+ if (!disposed) {
300
+ disposed = true;
301
+ unsubscribe();
302
+ store.set(stateAtom, {
303
+ confirmed: null,
304
+ drafts: new Map(),
305
+ pending: null,
306
+ });
307
+ }
308
+ },
309
+ };
310
+ }
311
+
312
+ function editDocument(
313
+ confirmed: Document,
314
+ draft: Draft,
315
+ edit: DocumentEdit,
316
+ sent: Draft = EMPTY_DRAFT,
317
+ ): Draft {
318
+ let next = draft;
319
+ let active = true;
320
+
321
+ function assertActive() {
322
+ if (!active) {
323
+ throw new Error("The document transaction has ended");
324
+ }
325
+ }
326
+
327
+ function hasCell(id: Protocol.CellId): boolean {
328
+ const local = next.cells.get(id);
329
+ return (
330
+ local?.kind === "create" ||
331
+ (local?.kind !== "delete" && confirmed.cells.has(id))
332
+ );
333
+ }
334
+
335
+ function requireCell(id: Protocol.CellId) {
336
+ assertActive();
337
+ if (!hasCell(id)) {
338
+ throw new Error(`Cell ${id} does not exist`);
339
+ }
340
+ }
341
+
342
+ function updateCell(id: Protocol.CellId, patch: CellEdit) {
343
+ requireCell(id);
344
+ next = editCell(confirmed, next, id, patch);
345
+ }
346
+
347
+ const editor: DocumentEditor = {
348
+ setCode: (id, code) => updateCell(id, { code }),
349
+ setName: (id, name) => updateCell(id, { name }),
350
+ updateConfig: (id, patch) =>
351
+ updateCell(id, { config: Protocol.CellConfig.partial().parse(patch) }),
352
+ createCell: (cell, placement = {}) => {
353
+ assertActive();
354
+ if (confirmed.cells.has(cell.id) || hasCell(cell.id)) {
355
+ throw new Error(`Cell ${cell.id} already exists`);
356
+ }
357
+ if (placement.after !== undefined && placement.before !== undefined) {
358
+ throw new Error("Specify either before or after for cell placement");
359
+ }
360
+ const anchor = placement.after ?? placement.before;
361
+ if (anchor !== undefined) {
362
+ requireCell(anchor);
363
+ }
364
+ next = createCell(next, cell, { ...placement });
365
+ },
366
+ deleteCell: (id) => {
367
+ requireCell(id);
368
+ next = deleteCell(next, id, sent);
369
+ },
370
+ setOrder: (order) => {
371
+ assertActive();
372
+ const { cells } = viewDocument(confirmed, next);
373
+ if (
374
+ order.length !== cells.size ||
375
+ new Set(order).size !== cells.size ||
376
+ order.some((id) => !cells.has(id))
377
+ ) {
378
+ throw new Error("Cell order must contain every cell exactly once");
379
+ }
380
+ next = setOrder(next, order);
381
+ },
382
+ };
383
+
384
+ try {
385
+ const result: unknown = edit(editor);
386
+ if (result instanceof Promise) {
387
+ // Observe a rejected async callback without publishing its partial draft.
388
+ result.catch(() => undefined);
389
+ throw new Error("Document edit callbacks must be synchronous");
390
+ }
391
+ return next;
392
+ } finally {
393
+ active = false;
394
+ }
395
+ }