@zikojs/notebook 0.1.0 → 0.3.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.
package/package.json CHANGED
@@ -1,11 +1,17 @@
1
1
  {
2
2
  "name": "@zikojs/notebook",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },
9
+ "scripts": {
10
+ "test": "echo \"Error: no test specified\" && exit 1",
11
+ "dev": "cross-env NODE_ENV=development rollup --config rollup.config.js",
12
+ "watch": "cross-env NODE_ENV=development rollup --config rollup.config.js -w",
13
+ "build": "cross-env NODE_ENV=production rollup --config rollup.config.js"
14
+ },
9
15
  "author": "zakaria elalaoui",
10
16
  "repository": {
11
17
  "type": "git",
@@ -20,6 +26,13 @@
20
26
  ".": {
21
27
  "import": "./src/index.js",
22
28
  "types": "./src/index.d.ts"
29
+ },
30
+ "./no-css": {
31
+ "import": "./src/main.js",
32
+ "types": "./src/index.d.ts"
33
+ },
34
+ "./style":{
35
+ "import": "./src/index.css"
23
36
  }
24
37
  },
25
38
  "files": [
@@ -43,13 +56,7 @@
43
56
  "lucide": "^1.44.0",
44
57
  "marked": "^18.0.12",
45
58
  "vanjs-core": "^1.6.1",
46
- "zextra": "^1.15.0",
47
- "ziko": "latest"
48
- },
49
- "scripts": {
50
- "test": "echo \"Error: no test specified\" && exit 1",
51
- "dev": "cross-env NODE_ENV=development rollup --config rollup.config.js",
52
- "watch": "cross-env NODE_ENV=development rollup --config rollup.config.js -w",
53
- "build": "cross-env NODE_ENV=production rollup --config rollup.config.js"
59
+ "zextra": "catalog:",
60
+ "ziko": "catalog:"
54
61
  }
55
- }
62
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { UIElement } from 'ziko/dom/UIElement'
2
+ export declare function Notebook() : UIElement
package/src/index.js CHANGED
@@ -1,500 +1,2 @@
1
1
  import './index.css'
2
- import van from "vanjs-core";
3
- import { marked } from "marked";
4
- import { Button } from "./ui.js";
5
- import { createCodeEditor } from "./codeEditor.js";
6
- import { evaluateCodeAsync } from "./transform.js";
7
-
8
- import {
9
- Check,
10
- Copy,
11
- Lock,
12
- Unlock,
13
- Code2,
14
- FileText,
15
- Pencil,
16
- Play,
17
- Plus,
18
- Trash2,
19
- PlayForward,
20
- Eraser,
21
- Download,
22
- Loader2
23
- } from './icons.js'
24
-
25
- const { div, span } = van.tags;
26
-
27
- export function Header({ state, actions }) {
28
- const { runAllBtn, clearBtn, addCodeBtn, addMdBtn, deleteActiveBtn, exportBtn, statusBadge, statusText } = state;
29
-
30
- return div({ class: "header" },
31
- div({ class: "brand" }, "Jupyter VanJS Notebook", statusBadge),
32
- div({ class: "toolbar" },
33
- runAllBtn, clearBtn, addCodeBtn, addMdBtn, deleteActiveBtn, exportBtn
34
- )
35
- );
36
- }
37
-
38
- export function MarkdownView({ cellData, actions }) {
39
- const content = div();
40
- content.innerHTML = marked.parse(cellData.code || "*Empty Markdown Cell*");
41
-
42
- const wrap = div({ class: "markdown-rendered-cell markdown-body" }, content);
43
- wrap.onclick = () => actions.editMarkdown();
44
- return wrap;
45
- }
46
-
47
- export function CellControls({ cellData, state, actions }) {
48
- const isQueueRunning = state.executionQueueState_state.isRunning;
49
- const isMaxCellsReached = state.cells_state.length >= state.maxCells;
50
- const isCopied = cellData._copiedFlag_state === true;
51
-
52
- const handleCopy = async () => {
53
- await actions.copyCode();
54
- cellData._copiedFlag_state = true;
55
- state.refreshControls(cellData);
56
- setTimeout(() => {
57
- cellData._copiedFlag_state = false;
58
- state.refreshControls(cellData);
59
- }, 1500);
60
- };
61
-
62
- return [
63
- Button({
64
- class: `btn-icon ${isCopied ? "btn-active" : ""}`,
65
- title: isCopied ? "Copied!" : "Copy Cell Content",
66
- onclick: handleCopy
67
- },
68
- isCopied ? Check() : Copy()
69
- ),
70
- Button({
71
- class: `btn-icon ${cellData.readonly ? "btn-active" : ""}`,
72
- title: cellData.readonly ? "Make Editable" : "Make Read-Only",
73
- disabled: isQueueRunning,
74
- onclick: actions.toggleReadonly,
75
- },
76
- cellData.readonly ? Lock() : Unlock()
77
- ),
78
- Button({
79
- class: `btn-icon ${cellData.type === "markdown" ? "btn-active" : ""}`,
80
- title: `Switch to ${cellData.type === "code" ? "Markdown" : "JS Code"}`,
81
- disabled: isQueueRunning || cellData.readonly,
82
- onclick: actions.toggleType,
83
- },
84
- cellData.type === "code" ? FileText() : Code2()
85
- ),
86
- (cellData.type === "markdown" && !cellData.isEditingMarkdown)
87
- ? Button(
88
- {
89
- class: "btn-icon",
90
- title: "Edit Markdown",
91
- disabled: isQueueRunning || cellData.readonly,
92
- onclick: actions.editMarkdown
93
- },
94
- Pencil()
95
- )
96
- : Button({
97
- class: "btn-icon btn-primary",
98
- title: "Run & Advance (Shift+Enter)",
99
- disabled: isQueueRunning,
100
- onclick: () => actions.runCode(true)
101
- },
102
- Play()
103
- ),
104
- Button({
105
- class: "btn-icon",
106
- title: "Add Cell Below",
107
- disabled: isQueueRunning || isMaxCellsReached,
108
- onclick: actions.addBelow
109
- }, Plus()),
110
- Button({
111
- class: "btn-icon",
112
- title: "Delete Cell",
113
- disabled: isQueueRunning,
114
- onclick: actions.deleteCell
115
- }, Trash2())
116
- ];
117
- }
118
-
119
- export function CellItem({ cellData, app }) {
120
- const outputRef = div({ class: "output-area" });
121
- if (cellData.outputNode) outputRef.appendChild(cellData.outputNode);
122
- cellData._outputRef = outputRef;
123
-
124
- const actions = app._cellActions(cellData);
125
- cellData._actions = actions;
126
- cellData._editor = createCodeEditor(app, cellData, actions);
127
-
128
- const inPrompt = span({ class: "prompt" });
129
- const outPrompt = span({ class: "prompt out" });
130
- const bodySlot = div({ style: "display:contents;" });
131
- const controlsEl = div({ class: "cell-controls" });
132
-
133
- const outputGrid = div({ class: "cell-output-grid" }, outPrompt, div({ class: "output-wrapper" }, outputRef));
134
- const inputGrid = div({ class: "cell-input-grid" }, inPrompt, bodySlot, controlsEl);
135
- const root = div({ class: "cell" }, inputGrid, outputGrid);
136
- root.onclick = () => app.setActiveCell(cellData.id);
137
-
138
- cellData._dom = root;
139
- cellData._inPrompt = inPrompt;
140
- cellData._outPrompt = outPrompt;
141
- cellData._bodySlot = bodySlot;
142
- cellData._controlsEl = controlsEl;
143
- cellData._outputGrid = outputGrid;
144
-
145
- app._refreshCell(cellData);
146
- return root;
147
- }
148
-
149
- // --- MAIN NOTEBOOK APP CLASS ---
150
-
151
- export class NotebookApp {
152
- constructor({
153
- cells: initialCells = [],
154
- importMap = {},
155
- runCells = true,
156
- codeMirrorConfig = {},
157
- markedPlugins = [],
158
- codeMirrorPlugins = [],
159
- minLines = 3,
160
- maxCells = Infinity
161
- } = {}) {
162
- this.importMap = importMap;
163
- this.codeMirrorConfig = codeMirrorConfig;
164
- this.codeMirrorPlugins = codeMirrorPlugins;
165
- this.minLines = minLines;
166
- this.maxCells = maxCells;
167
-
168
- if (Array.isArray(markedPlugins) && markedPlugins.length > 0) {
169
- markedPlugins.forEach(plugin => marked.use(plugin));
170
- }
171
-
172
- const startingCells = maxCells !== Infinity ? initialCells.slice(0, maxCells) : initialCells;
173
-
174
- this.nextCellId_state = startingCells.length ? Math.max(...startingCells.map(c => c.id || 0)) + 1 : 1;
175
-
176
- this.cells_state = startingCells.map(cell => ({
177
- id: cell.id || this.nextCellId_state++,
178
- type: cell.type || "code",
179
- code: cell.code || "",
180
- readonly: cell.readonly ?? false,
181
- isEditingMarkdown: cell.readonly ? false : (cell.isEditingMarkdown ?? true),
182
- execCount: cell.execCount ?? null,
183
- outputNode: cell.outputNode || null,
184
- hasDomOutput: cell.hasDomOutput ?? false,
185
- _copiedFlag_state: false,
186
- _dom: null, _editor: null, _actions: null,
187
- _inPrompt: null, _outPrompt: null, _bodySlot: null, _controlsEl: null, _outputGrid: null, _outputRef: null
188
- }));
189
-
190
- this.activeCellId_state = this.cells_state.length ? this.cells_state[0].id : null;
191
- this.executionCounter_state = 1;
192
- this.executionQueueState_state = { isRunning: false, currentIndex: 0, total: 0 };
193
-
194
- this.notebookGlobalShortcuts = {
195
- deleteActive: () => this.deleteCell(this.activeCellId_state),
196
- addMdBelow: () => this.addCell("markdown", "", this.activeCellId_state),
197
- addCodeBelow: () => this.addCell("code", "", this.activeCellId_state)
198
- };
199
-
200
- this.cellsContainer = div({ class: "cells-container" });
201
- this.header = this._buildHeader();
202
- this.element = div(this.header, div({ class: "notebook" }, this.cellsContainer));
203
-
204
- this._renderAllCells();
205
-
206
- if (runCells) {
207
- setTimeout(() => { this.runAllCells(); }, 200);
208
- }
209
- }
210
-
211
- _isMaxCellsReached() { return this.cells_state.length >= this.maxCells; }
212
-
213
- // --- HEADER BUILDER ---
214
-
215
- _buildHeader() {
216
- this.runAllBtn = Button({
217
- class: "btn-primary",
218
- onclick: () => this.runAllCells(),
219
- }, PlayForward(), "Run All"
220
- );
221
- this.clearBtn = Button({
222
- onclick: () => this.clearOutputs()
223
- }, Eraser(), "Clear Outputs");
224
- this.addCodeBtn = Button({
225
- onclick: () => this.addCell("code", "", this.activeCellId_state),
226
- }, Play(), "Add Code");
227
- this.addMdBtn = Button({
228
- onclick: () => this.addCell("markdown", "", this.activeCellId_state),
229
- }, FileText(), "Add Markdown");
230
- this.deleteActiveBtn = Button({
231
- onclick: () => this.deleteCell(this.activeCellId_state)
232
- }, Trash2(), "Delete Active");
233
- this.exportBtn = Button({
234
- onclick: () => console.log("Notebook Data Export:", this.getNotebookData())
235
- }, Download(), "Export Data");
236
-
237
- this.statusText = span();
238
- this.statusBadge = span({
239
- class: "status-badge",
240
- style: "display:none;"
241
- }, Loader2(), this.statusText);
242
-
243
- const header = Header({
244
- state: {
245
- runAllBtn: this.runAllBtn,
246
- clearBtn: this.clearBtn,
247
- addCodeBtn: this.addCodeBtn,
248
- addMdBtn: this.addMdBtn,
249
- deleteActiveBtn: this.deleteActiveBtn,
250
- exportBtn: this.exportBtn,
251
- statusBadge: this.statusBadge,
252
- statusText: this.statusText
253
- }
254
- });
255
-
256
- this._updateHeaderUI();
257
- return header;
258
- }
259
-
260
- _updateHeaderUI() {
261
- const q = this.executionQueueState_state;
262
- this.statusBadge.style.display = q.isRunning ? "inline-flex" : "none";
263
- this.statusText.textContent = `Executing Queue (${q.currentIndex + 1}/${q.total})`;
264
- [this.runAllBtn, this.clearBtn, this.deleteActiveBtn].forEach(b => { b.disabled = q.isRunning; });
265
- const maxReached = this._isMaxCellsReached();
266
- this.addCodeBtn.disabled = q.isRunning || maxReached;
267
- this.addMdBtn.disabled = q.isRunning || maxReached;
268
- }
269
-
270
- // --- CELL ACTIONS & DOM ---
271
-
272
- _cellActions(cellData) {
273
- const app = this;
274
- return {
275
- setActive: () => app.setActiveCell(cellData.id),
276
- runCode: async (autoNext = true) => {
277
- const code = cellData._editor.getValue();
278
- cellData.code = code;
279
-
280
- if (cellData.type === "markdown") {
281
- cellData.isEditingMarkdown = false;
282
- if (autoNext) app.nextCell(cellData.id, "markdown");
283
- else app._refreshCell(cellData);
284
- return;
285
- }
286
-
287
- if (!code.trim()) return;
288
-
289
- cellData._outputRef.innerHTML = "";
290
- let hasError = false;
291
-
292
- try {
293
- await evaluateCodeAsync(code, cellData._outputRef, app.importMap);
294
- } catch (err) {
295
- hasError = true;
296
- van.add(cellData._outputRef, div({ class: "error-output" }, err.toString()));
297
- }
298
-
299
- cellData.execCount = app.executionCounter_state++;
300
- cellData.hasDomOutput = cellData._outputRef.childNodes.length > 0 || hasError;
301
-
302
- const container = div({ class: "output-area" });
303
- while (cellData._outputRef.firstChild) container.appendChild(cellData._outputRef.firstChild);
304
- cellData.outputNode = container;
305
- cellData._outputRef.appendChild(container);
306
-
307
- if (autoNext && !hasError) app.nextCell(cellData.id, "code");
308
- else app._refreshCell(cellData);
309
- },
310
- copyCode: async () => {
311
- const textToCopy = cellData._editor.getValue() || cellData.code;
312
- try {
313
- await navigator.clipboard.writeText(textToCopy);
314
- } catch (err) {
315
- const textArea = document.createElement("textarea");
316
- textArea.value = textToCopy;
317
- document.body.appendChild(textArea);
318
- textArea.select();
319
- document.execCommand("copy");
320
- document.body.removeChild(textArea);
321
- }
322
- },
323
- toggleReadonly: () => {
324
- cellData.readonly = !cellData.readonly;
325
- if (cellData.readonly && cellData.type === "markdown") cellData.isEditingMarkdown = false;
326
- app._refreshCell(cellData);
327
- },
328
- toggleType: () => {
329
- if (cellData.readonly) return;
330
- cellData.type = cellData.type === "code" ? "markdown" : "code";
331
- cellData.isEditingMarkdown = true;
332
- cellData.hasDomOutput = false;
333
- app._refreshCell(cellData);
334
- },
335
- editMarkdown: () => {
336
- if (cellData.readonly) return;
337
- cellData.isEditingMarkdown = true;
338
- app._refreshCell(cellData);
339
- },
340
- addBelow: () => app.addCell(cellData.type, null, cellData.id),
341
- deleteCell: () => app.deleteCell(cellData.id)
342
- };
343
- }
344
-
345
- _buildCellDom(cellData) {
346
- return CellItem({ cellData, app: this });
347
- }
348
-
349
- _refreshCell(cellData) {
350
- const isActive = this.activeCellId_state === cellData.id;
351
- cellData._dom.className = `cell ${isActive ? "active" : ""} ${cellData.readonly ? "readonly" : ""}`.trim();
352
-
353
- const countText = cellData.execCount ? `[${cellData.execCount}]` : "[ ]";
354
- const isMarkdownView = cellData.type === "markdown" && !cellData.isEditingMarkdown;
355
-
356
- cellData._inPrompt.textContent = cellData.type === "code" ? `In ${countText}:` : "";
357
-
358
- cellData._editor.sync(isActive, isMarkdownView);
359
- cellData._bodySlot.replaceChildren(
360
- isMarkdownView ? MarkdownView({ cellData, actions: cellData._actions }) : cellData._editor.dom
361
- );
362
-
363
- this._refreshCellControls(cellData);
364
-
365
- const showOutput = cellData.type === "code" && cellData.hasDomOutput;
366
- cellData._outputGrid.style.display = showOutput ? "grid" : "none";
367
- cellData._outPrompt.textContent = `Out ${countText}:`;
368
- }
369
-
370
- _refreshCellControls(cellData) {
371
- const buttons = CellControls({
372
- cellData,
373
- state: this,
374
- actions: cellData._actions
375
- });
376
- cellData._controlsEl.replaceChildren(...buttons);
377
- }
378
-
379
- // --- STATE MUTATORS ---
380
-
381
- _renderAllCells() {
382
- this.cellsContainer.replaceChildren(...this.cells_state.map(c => c._dom || this._buildCellDom(c)));
383
- this._updateHeaderUI();
384
- }
385
-
386
- setActiveCell(id) {
387
- if (this.activeCellId_state === id) return;
388
- const current = this.cells_state.find(c => c.id === this.activeCellId_state);
389
- if (current && current.type === "markdown" && current.isEditingMarkdown) current.isEditingMarkdown = false;
390
- this.activeCellId_state = id;
391
- if (current) this._refreshCell(current);
392
- const next = this.cells_state.find(c => c.id === id);
393
- if (next) this._refreshCell(next);
394
- }
395
-
396
- focusCell(targetId) {
397
- const prevId = this.activeCellId_state;
398
- this.activeCellId_state = targetId;
399
- const target = this.cells_state.find(c => c.id === targetId);
400
- if (target && target.type === "markdown" && !target.readonly) target.isEditingMarkdown = true;
401
- if (prevId !== targetId) {
402
- const prevCell = this.cells_state.find(c => c.id === prevId);
403
- if (prevCell) this._refreshCell(prevCell);
404
- }
405
- if (target) this._refreshCell(target);
406
- }
407
-
408
- addCell(type = "code", initialCode = null, afterId = null, readonly = false) {
409
- if (this.cells_state.length >= this.maxCells) {
410
- console.warn(`Cannot create cell: Maximum cell limit (${this.maxCells}) reached.`);
411
- return null;
412
- }
413
-
414
- const newId = this.nextCellId_state++;
415
- const defaultText = type === "markdown" ? "### New Markdown Cell\nClick to edit..." : "";
416
- const newCell = {
417
- id: newId, type, code: initialCode !== null ? initialCode : defaultText, readonly,
418
- isEditingMarkdown: !readonly && type === "markdown" && initialCode === null,
419
- execCount: null, outputNode: null, hasDomOutput: false, _copiedFlag_state: false,
420
- _dom: null, _editor: null, _actions: null,
421
- _inPrompt: null, _outPrompt: null, _bodySlot: null, _controlsEl: null, _outputGrid: null, _outputRef: null
422
- };
423
-
424
- if (afterId === null) {
425
- this.cells_state.push(newCell);
426
- } else {
427
- const index = this.cells_state.findIndex(c => c.id === afterId);
428
- this.cells_state.splice(index + 1, 0, newCell);
429
- }
430
-
431
- this._renderAllCells();
432
- this.focusCell(newId);
433
- return newId;
434
- }
435
-
436
- deleteCell(id) {
437
- if (this.cells_state.length <= 1) return;
438
- const index = this.cells_state.findIndex(c => c.id === id);
439
- this.cells_state = this.cells_state.filter(c => c.id !== id);
440
- this._renderAllCells();
441
- const nextActiveIndex = Math.min(index, this.cells_state.length - 1);
442
- this.focusCell(this.cells_state[nextActiveIndex].id);
443
- }
444
-
445
- nextCell(currentId, defaultType) {
446
- const idx = this.cells_state.findIndex(c => c.id === currentId);
447
- if (idx === this.cells_state.length - 1) this.addCell(defaultType, null, currentId);
448
- else this.focusCell(this.cells_state[idx + 1].id);
449
- }
450
-
451
- async runCell(id) {
452
- const cell = this.cells_state.find(c => c.id === id);
453
- if (cell && cell._actions) await cell._actions.runCode(false);
454
- }
455
-
456
- async runAllCells() {
457
- const codeCells = this.cells_state.filter(c => c.type === "code");
458
- if (codeCells.length === 0) return;
459
-
460
- this.executionQueueState_state = { isRunning: true, currentIndex: 0, total: codeCells.length };
461
- this._updateHeaderUI();
462
- this.cells_state.forEach(c => this._refreshCellControls(c));
463
-
464
- for (const cell of this.cells_state) {
465
- if (cell.type === "code" && cell._actions) {
466
- this.executionQueueState_state = { ...this.executionQueueState_state, currentIndex: codeCells.indexOf(cell) };
467
- this._updateHeaderUI();
468
- await cell._actions.runCode(false);
469
- }
470
- }
471
-
472
- this.executionQueueState_state = { isRunning: false, currentIndex: 0, total: 0 };
473
- this._updateHeaderUI();
474
- this.cells_state.forEach(c => this._refreshCellControls(c));
475
- }
476
-
477
- clearOutputs() {
478
- this.cells_state.forEach(cell => {
479
- cell.execCount = null;
480
- cell.outputNode = null;
481
- cell.hasDomOutput = false;
482
- if (cell._outputRef) cell._outputRef.innerHTML = "";
483
- });
484
- this.executionCounter_state = 1;
485
- this.cells_state.forEach(c => this._refreshCell(c));
486
- }
487
-
488
- resetScope() {
489
- window.__notebook_scope = Object.create(null);
490
- }
491
-
492
- getNotebookData({ inputs = true, outputs = true } = {}) {
493
- return this.cells_state.map(cell => {
494
- const exportedCell = { id: cell.id, type: cell.type, readonly: cell.readonly, order: cell.execCount };
495
- if (inputs) exportedCell.code = cell.code;
496
- if (outputs) exportedCell.outputHtml = cell.outputNode ? cell.outputNode.innerHTML : null;
497
- return exportedCell;
498
- });
499
- }
500
- }
2
+ export * from './main.js'
package/src/main.js ADDED
@@ -0,0 +1,528 @@
1
+ import van from "vanjs-core";
2
+ import { marked } from "marked";
3
+ import { Button } from "./ui.js";
4
+ import { createCodeEditor } from "./codeEditor.js";
5
+ import { evaluateCodeAsync } from "./transform.js";
6
+ import { call_with_optional_props } from 'ziko/dom/internal-utils'
7
+
8
+ import {
9
+ Check,
10
+ Copy,
11
+ Lock,
12
+ Unlock,
13
+ Code2,
14
+ FileText,
15
+ Pencil,
16
+ Play,
17
+ Plus,
18
+ Trash2,
19
+ PlayForward,
20
+ Eraser,
21
+ Download,
22
+ Loader2
23
+ } from './icons.js'
24
+
25
+ const { div, span } = van.tags;
26
+
27
+ export function Header({ state, actions }) {
28
+ const { runAllBtn, clearBtn, addCodeBtn, addMdBtn, deleteActiveBtn, exportBtn, statusBadge, statusText } = state;
29
+
30
+ return div({ class: "header" },
31
+ div({ class: "brand" }, "</>", statusBadge),
32
+ div({ class: "toolbar" },
33
+ runAllBtn, clearBtn, addCodeBtn, addMdBtn, deleteActiveBtn, exportBtn
34
+ )
35
+ );
36
+ }
37
+
38
+ export function MarkdownView({ cellData, actions }) {
39
+ const content = div();
40
+ content.innerHTML = marked.parse(cellData.code || "*Empty Markdown Cell*");
41
+
42
+ const wrap = div({ class: "markdown-rendered-cell markdown-body" }, content);
43
+ wrap.onclick = () => actions.editMarkdown();
44
+ return wrap;
45
+ }
46
+
47
+ export function CellControls({ cellData, state, actions }) {
48
+ const isQueueRunning = state.executionQueueState_state.isRunning;
49
+ const isMaxCellsReached = state.cells_state.length >= state.maxCells;
50
+ const isCopied = cellData._copiedFlag_state === true;
51
+
52
+ const handleCopy = async () => {
53
+ await actions.copyCode();
54
+ cellData._copiedFlag_state = true;
55
+ state.refreshControls(cellData);
56
+ setTimeout(() => {
57
+ cellData._copiedFlag_state = false;
58
+ state.refreshControls(cellData);
59
+ }, 1500);
60
+ };
61
+
62
+ return [
63
+ Button({
64
+ class: `btn-icon ${isCopied ? "btn-active" : ""}`,
65
+ title: isCopied ? "Copied!" : "Copy Cell Content",
66
+ onclick: handleCopy
67
+ },
68
+ isCopied ? Check() : Copy()
69
+ ),
70
+ Button({
71
+ class: `btn-icon ${cellData.readonly ? "btn-active" : ""}`,
72
+ title: cellData.readonly ? "Make Editable" : "Make Read-Only",
73
+ disabled: isQueueRunning,
74
+ onclick: actions.toggleReadonly,
75
+ },
76
+ cellData.readonly ? Lock() : Unlock()
77
+ ),
78
+ Button({
79
+ class: `btn-icon ${cellData.type === "markdown" ? "btn-active" : ""}`,
80
+ title: `Switch to ${cellData.type === "code" ? "Markdown" : "JS Code"}`,
81
+ disabled: isQueueRunning || cellData.readonly,
82
+ onclick: actions.toggleType,
83
+ },
84
+ cellData.type === "code" ? FileText() : Code2()
85
+ ),
86
+ (cellData.type === "markdown" && !cellData.isEditingMarkdown)
87
+ ? Button(
88
+ {
89
+ class: "btn-icon",
90
+ title: "Edit Markdown",
91
+ disabled: isQueueRunning || cellData.readonly,
92
+ onclick: actions.editMarkdown
93
+ },
94
+ Pencil()
95
+ )
96
+ : Button({
97
+ class: "btn-icon btn-primary",
98
+ title: "Run & Advance (Shift+Enter)",
99
+ disabled: isQueueRunning,
100
+ onclick: () => actions.runCode(true)
101
+ },
102
+ Play()
103
+ ),
104
+ Button({
105
+ class: "btn-icon",
106
+ title: "Add Cell Below",
107
+ disabled: isQueueRunning || isMaxCellsReached,
108
+ onclick: actions.addBelow
109
+ }, Plus()),
110
+ Button({
111
+ class: "btn-icon",
112
+ title: "Delete Cell",
113
+ disabled: isQueueRunning,
114
+ onclick: actions.deleteCell
115
+ }, Trash2())
116
+ ];
117
+ }
118
+
119
+ export function CellItem({ cellData, app }) {
120
+ const outputRef = div({ class: "output-area" });
121
+ if (cellData.outputNode) outputRef.appendChild(cellData.outputNode);
122
+ cellData._outputRef = outputRef;
123
+
124
+ const actions = app._cellActions(cellData);
125
+ cellData._actions = actions;
126
+ cellData._editor = createCodeEditor(app, cellData, actions);
127
+
128
+ const inPrompt = span({ class: "prompt" });
129
+ const outPrompt = span({ class: "prompt out" });
130
+ const bodySlot = div({ style: "display:contents;" });
131
+ const controlsEl = div({ class: "cell-controls" });
132
+
133
+ const outputGrid = div({ class: "cell-output-grid" }, outPrompt, div({ class: "output-wrapper" }, outputRef));
134
+ const inputGrid = div({ class: "cell-input-grid" }, inPrompt, bodySlot, controlsEl);
135
+ const root = div({ class: "cell" }, inputGrid, outputGrid);
136
+ root.onclick = () => app.setActiveCell(cellData.id);
137
+
138
+ cellData._dom = root;
139
+ cellData._inPrompt = inPrompt;
140
+ cellData._outPrompt = outPrompt;
141
+ cellData._bodySlot = bodySlot;
142
+ cellData._controlsEl = controlsEl;
143
+ cellData._outputGrid = outputGrid;
144
+
145
+ app._refreshCell(cellData);
146
+ return root;
147
+ }
148
+
149
+ export class UINotebook {
150
+ constructor({
151
+ cells: initialCells = [],
152
+ importMap = {},
153
+ runCells = true,
154
+ codeMirrorConfig = {},
155
+ markedPlugins = [],
156
+ codeMirrorPlugins = [],
157
+ minLines = 3,
158
+ maxCells = Infinity
159
+ } = {}) {
160
+ // 1. Generate unique UUID for this notebook instance
161
+ this.id = crypto.randomUUID ? crypto.randomUUID() : 'nb_' + Math.random().toString(36).substring(2, 9);
162
+
163
+ // 2. Initialize the global scope map if not already present
164
+ if (!window.__notebook_scope_map) {
165
+ window.__notebook_scope_map = new Map();
166
+ }
167
+
168
+ // 3. Register this instance's isolated scope
169
+ this.resetScope();
170
+
171
+ this.importMap = importMap;
172
+ this.codeMirrorConfig = codeMirrorConfig;
173
+ this.codeMirrorPlugins = codeMirrorPlugins;
174
+ this.minLines = minLines;
175
+ this.maxCells = maxCells;
176
+
177
+ if (Array.isArray(markedPlugins) && markedPlugins.length > 0) {
178
+ markedPlugins.forEach(plugin => marked.use(plugin));
179
+ }
180
+
181
+ const startingCells = maxCells !== Infinity ? initialCells.slice(0, maxCells) : initialCells;
182
+
183
+ this.nextCellId_state = startingCells.length ? Math.max(...startingCells.map(c => c.id || 0)) + 1 : 1;
184
+
185
+ this.cells_state = startingCells.map(cell => ({
186
+ id: cell.id || this.nextCellId_state++,
187
+ type: cell.type || "code",
188
+ code: cell.code || "",
189
+ readonly: cell.readonly ?? false,
190
+ isEditingMarkdown: cell.readonly ? false : (cell.isEditingMarkdown ?? true),
191
+ execCount: cell.execCount ?? null,
192
+ outputNode: cell.outputNode || null,
193
+ hasDomOutput: cell.hasDomOutput ?? false,
194
+ _copiedFlag_state: false,
195
+ _dom: null, _editor: null, _actions: null,
196
+ _inPrompt: null, _outPrompt: null, _bodySlot: null, _controlsEl: null, _outputGrid: null, _outputRef: null
197
+ }));
198
+
199
+ this.activeCellId_state = this.cells_state.length ? this.cells_state[0].id : null;
200
+ this.executionCounter_state = 1;
201
+ this.executionQueueState_state = { isRunning: false, currentIndex: 0, total: 0 };
202
+
203
+ this.notebookGlobalShortcuts = {
204
+ deleteActive: () => this.deleteCell(this.activeCellId_state),
205
+ addMdBelow: () => this.addCell("markdown", "", this.activeCellId_state),
206
+ addCodeBelow: () => this.addCell("code", "", this.activeCellId_state)
207
+ };
208
+
209
+ this.cellsContainer = div({ class: "cells-container" });
210
+ this.header = this._buildHeader();
211
+ this.element = div(this.header, div({ class: "notebook" }, this.cellsContainer));
212
+
213
+ this._renderAllCells();
214
+
215
+ if (runCells) {
216
+ setTimeout(() => { this.runAllCells(); }, 200);
217
+ }
218
+ }
219
+
220
+ _isMaxCellsReached() { return this.cells_state.length >= this.maxCells; }
221
+
222
+ // --- HEADER BUILDER ---
223
+
224
+ _buildHeader() {
225
+ this.runAllBtn = Button({
226
+ class: "btn-primary",
227
+ onclick: () => this.runAllCells(),
228
+ }, PlayForward(), "Run All"
229
+ );
230
+ this.clearBtn = Button({
231
+ onclick: () => this.clearOutputs()
232
+ }, Eraser(), "Clear Outputs");
233
+ this.addCodeBtn = Button({
234
+ onclick: () => this.addCell("code", "", this.activeCellId_state),
235
+ }, Play(), "Add Code");
236
+ this.addMdBtn = Button({
237
+ onclick: () => this.addCell("markdown", "", this.activeCellId_state),
238
+ }, FileText(), "Add Markdown");
239
+ this.deleteActiveBtn = Button({
240
+ onclick: () => this.deleteCell(this.activeCellId_state)
241
+ }, Trash2(), "Delete Active");
242
+ this.exportBtn = Button({
243
+ onclick: () => console.log("Notebook Data Export:", this.getNotebookData())
244
+ }, Download(), "Export Data");
245
+
246
+ this.statusText = span();
247
+ this.statusBadge = span({
248
+ class: "status-badge",
249
+ style: "display:none;"
250
+ }, Loader2(), this.statusText);
251
+
252
+ const header = Header({
253
+ state: {
254
+ runAllBtn: this.runAllBtn,
255
+ clearBtn: this.clearBtn,
256
+ addCodeBtn: this.addCodeBtn,
257
+ addMdBtn: this.addMdBtn,
258
+ deleteActiveBtn: this.deleteActiveBtn,
259
+ exportBtn: this.exportBtn,
260
+ statusBadge: this.statusBadge,
261
+ statusText: this.statusText
262
+ }
263
+ });
264
+
265
+ this._updateHeaderUI();
266
+ return header;
267
+ }
268
+
269
+ _updateHeaderUI() {
270
+ const q = this.executionQueueState_state;
271
+ this.statusBadge.style.display = q.isRunning ? "inline-flex" : "none";
272
+ this.statusText.textContent = `Executing Queue (${q.currentIndex + 1}/${q.total})`;
273
+ [this.runAllBtn, this.clearBtn, this.deleteActiveBtn].forEach(b => { b.disabled = q.isRunning; });
274
+ const maxReached = this._isMaxCellsReached();
275
+ this.addCodeBtn.disabled = q.isRunning || maxReached;
276
+ this.addMdBtn.disabled = q.isRunning || maxReached;
277
+ }
278
+
279
+ // --- CELL ACTIONS & DOM ---
280
+
281
+ _cellActions(cellData) {
282
+ const app = this;
283
+ return {
284
+ setActive: () => app.setActiveCell(cellData.id),
285
+ runCode: async (autoNext = true) => {
286
+ const code = cellData._editor.getValue();
287
+ cellData.code = code;
288
+
289
+ if (cellData.type === "markdown") {
290
+ cellData.isEditingMarkdown = false;
291
+ if (autoNext) app.nextCell(cellData.id, "markdown");
292
+ else app._refreshCell(cellData);
293
+ return;
294
+ }
295
+
296
+ if (!code.trim()) return;
297
+
298
+ cellData._outputRef.innerHTML = "";
299
+ let hasError = false;
300
+
301
+ try {
302
+ // Retrieve this specific instance's compatible scope from window.__notebook_scope_map
303
+ const scope = app.getScope();
304
+
305
+ // Pass either the scope object or the instance ID (app.id) to evaluateCodeAsync
306
+ await evaluateCodeAsync(code, cellData._outputRef, app.importMap, scope);
307
+ } catch (err) {
308
+ hasError = true;
309
+ van.add(cellData._outputRef, div({ class: "error-output" }, err.toString()));
310
+ }
311
+
312
+ cellData.execCount = app.executionCounter_state++;
313
+ cellData.hasDomOutput = cellData._outputRef.childNodes.length > 0 || hasError;
314
+
315
+ const container = div({ class: "output-area" });
316
+ while (cellData._outputRef.firstChild) container.appendChild(cellData._outputRef.firstChild);
317
+ cellData.outputNode = container;
318
+ cellData._outputRef.appendChild(container);
319
+
320
+ if (autoNext && !hasError) app.nextCell(cellData.id, "code");
321
+ else app._refreshCell(cellData);
322
+ },
323
+ copyCode: async () => {
324
+ const textToCopy = cellData._editor.getValue() || cellData.code;
325
+ try {
326
+ await navigator.clipboard.writeText(textToCopy);
327
+ } catch (err) {
328
+ const textArea = document.createElement("textarea");
329
+ textArea.value = textToCopy;
330
+ document.body.appendChild(textArea);
331
+ textArea.select();
332
+ document.execCommand("copy");
333
+ document.body.removeChild(textArea);
334
+ }
335
+ },
336
+ toggleReadonly: () => {
337
+ cellData.readonly = !cellData.readonly;
338
+ if (cellData.readonly && cellData.type === "markdown") cellData.isEditingMarkdown = false;
339
+ app._refreshCell(cellData);
340
+ },
341
+ toggleType: () => {
342
+ if (cellData.readonly) return;
343
+ cellData.type = cellData.type === "code" ? "markdown" : "code";
344
+ cellData.isEditingMarkdown = true;
345
+ cellData.hasDomOutput = false;
346
+ app._refreshCell(cellData);
347
+ },
348
+ editMarkdown: () => {
349
+ if (cellData.readonly) return;
350
+ cellData.isEditingMarkdown = true;
351
+ app._refreshCell(cellData);
352
+ },
353
+ addBelow: () => app.addCell(cellData.type, null, cellData.id),
354
+ deleteCell: () => app.deleteCell(cellData.id)
355
+ };
356
+ }
357
+
358
+ _buildCellDom(cellData) {
359
+ return CellItem({ cellData, app: this });
360
+ }
361
+
362
+ _refreshCell(cellData) {
363
+ const isActive = this.activeCellId_state === cellData.id;
364
+ cellData._dom.className = `cell ${isActive ? "active" : ""} ${cellData.readonly ? "readonly" : ""}`.trim();
365
+
366
+ const countText = cellData.execCount ? `[${cellData.execCount}]` : "[ ]";
367
+ const isMarkdownView = cellData.type === "markdown" && !cellData.isEditingMarkdown;
368
+
369
+ cellData._inPrompt.textContent = cellData.type === "code" ? `In ${countText}:` : "";
370
+
371
+ cellData._editor.sync(isActive, isMarkdownView);
372
+ cellData._bodySlot.replaceChildren(
373
+ isMarkdownView ? MarkdownView({ cellData, actions: cellData._actions }) : cellData._editor.dom
374
+ );
375
+
376
+ this._refreshCellControls(cellData);
377
+
378
+ const showOutput = cellData.type === "code" && cellData.hasDomOutput;
379
+ cellData._outputGrid.style.display = showOutput ? "grid" : "none";
380
+ cellData._outPrompt.textContent = `Out ${countText}:`;
381
+ }
382
+
383
+ _refreshCellControls(cellData) {
384
+ const buttons = CellControls({
385
+ cellData,
386
+ state: this,
387
+ actions: cellData._actions
388
+ });
389
+ cellData._controlsEl.replaceChildren(...buttons);
390
+ }
391
+
392
+ // --- STATE & SCOPE MUTATORS ---
393
+
394
+ _renderAllCells() {
395
+ this.cellsContainer.replaceChildren(...this.cells_state.map(c => c._dom || this._buildCellDom(c)));
396
+ this._updateHeaderUI();
397
+ }
398
+
399
+ setActiveCell(id) {
400
+ if (this.activeCellId_state === id) return;
401
+ const current = this.cells_state.find(c => c.id === this.activeCellId_state);
402
+ if (current && current.type === "markdown" && current.isEditingMarkdown) current.isEditingMarkdown = false;
403
+ this.activeCellId_state = id;
404
+ if (current) this._refreshCell(current);
405
+ const next = this.cells_state.find(c => c.id === id);
406
+ if (next) this._refreshCell(next);
407
+ }
408
+
409
+ focusCell(targetId) {
410
+ const prevId = this.activeCellId_state;
411
+ this.activeCellId_state = targetId;
412
+ const target = this.cells_state.find(c => c.id === targetId);
413
+ if (target && target.type === "markdown" && !target.readonly) target.isEditingMarkdown = true;
414
+ if (prevId !== targetId) {
415
+ const prevCell = this.cells_state.find(c => c.id === prevId);
416
+ if (prevCell) this._refreshCell(prevCell);
417
+ }
418
+ if (target) this._refreshCell(target);
419
+ }
420
+
421
+ addCell(type = "code", initialCode = null, afterId = null, readonly = false) {
422
+ if (this.cells_state.length >= this.maxCells) {
423
+ console.warn(`Cannot create cell: Maximum cell limit (${this.maxCells}) reached.`);
424
+ return null;
425
+ }
426
+
427
+ const newId = this.nextCellId_state++;
428
+ const defaultText = type === "markdown" ? "### New Markdown Cell\nClick to edit..." : "";
429
+ const newCell = {
430
+ id: newId, type, code: initialCode !== null ? initialCode : defaultText, readonly,
431
+ isEditingMarkdown: !readonly && type === "markdown" && initialCode === null,
432
+ execCount: null, outputNode: null, hasDomOutput: false, _copiedFlag_state: false,
433
+ _dom: null, _editor: null, _actions: null,
434
+ _inPrompt: null, _outPrompt: null, _bodySlot: null, _controlsEl: null, _outputGrid: null, _outputRef: null
435
+ };
436
+
437
+ if (afterId === null) {
438
+ this.cells_state.push(newCell);
439
+ } else {
440
+ const index = this.cells_state.findIndex(c => c.id === afterId);
441
+ this.cells_state.splice(index + 1, 0, newCell);
442
+ }
443
+
444
+ this._renderAllCells();
445
+ this.focusCell(newId);
446
+ return newId;
447
+ }
448
+
449
+ deleteCell(id) {
450
+ if (this.cells_state.length <= 1) return;
451
+ const index = this.cells_state.findIndex(c => c.id === id);
452
+ this.cells_state = this.cells_state.filter(c => c.id !== id);
453
+ this._renderAllCells();
454
+ const nextActiveIndex = Math.min(index, this.cells_state.length - 1);
455
+ this.focusCell(this.cells_state[nextActiveIndex].id);
456
+ }
457
+
458
+ nextCell(currentId, defaultType) {
459
+ const idx = this.cells_state.findIndex(c => c.id === currentId);
460
+ if (idx === this.cells_state.length - 1) this.addCell(defaultType, null, currentId);
461
+ else this.focusCell(this.cells_state[idx + 1].id);
462
+ }
463
+
464
+ async runCell(id) {
465
+ const cell = this.cells_state.find(c => c.id === id);
466
+ if (cell && cell._actions) await cell._actions.runCode(false);
467
+ }
468
+
469
+ async runAllCells() {
470
+ const codeCells = this.cells_state.filter(c => c.type === "code");
471
+ if (codeCells.length === 0) return;
472
+
473
+ this.executionQueueState_state = { isRunning: true, currentIndex: 0, total: codeCells.length };
474
+ this._updateHeaderUI();
475
+ this.cells_state.forEach(c => this._refreshCellControls(c));
476
+
477
+ for (const cell of this.cells_state) {
478
+ if (cell.type === "code" && cell._actions) {
479
+ this.executionQueueState_state = { ...this.executionQueueState_state, currentIndex: codeCells.indexOf(cell) };
480
+ this._updateHeaderUI();
481
+ await cell._actions.runCode(false);
482
+ }
483
+ }
484
+
485
+ this.executionQueueState_state = { isRunning: false, currentIndex: 0, total: 0 };
486
+ this._updateHeaderUI();
487
+ this.cells_state.forEach(c => this._refreshCellControls(c));
488
+ }
489
+
490
+ clearOutputs() {
491
+ this.cells_state.forEach(cell => {
492
+ cell.execCount = null;
493
+ cell.outputNode = null;
494
+ cell.hasDomOutput = false;
495
+ if (cell._outputRef) cell._outputRef.innerHTML = "";
496
+ });
497
+ this.executionCounter_state = 1;
498
+ this.cells_state.forEach(c => this._refreshCell(c));
499
+ }
500
+
501
+ resetScope() {
502
+ if (!window.__notebook_scope_map) {
503
+ window.__notebook_scope_map = new Map();
504
+ }
505
+ const newScope = Object.create(null);
506
+ window.__notebook_scope_map.set(this.id, newScope);
507
+ return newScope;
508
+ }
509
+
510
+ getScope() {
511
+ if (!window.__notebook_scope_map || !window.__notebook_scope_map.has(this.id)) {
512
+ return this.resetScope();
513
+ }
514
+ return window.__notebook_scope_map.get(this.id);
515
+ }
516
+
517
+ getNotebookData({ inputs = true, outputs = true } = {}) {
518
+ return this.cells_state.map(cell => {
519
+ const exportedCell = { id: cell.id, type: cell.type, readonly: cell.readonly, order: cell.execCount };
520
+ if (inputs) exportedCell.code = cell.code;
521
+ if (outputs) exportedCell.outputHtml = cell.outputNode ? cell.outputNode.innerHTML : null;
522
+ return exportedCell;
523
+ });
524
+ }
525
+ }
526
+
527
+
528
+ export const Notebook = call_with_optional_props(UINotebook)
package/src/transform.js CHANGED
@@ -21,19 +21,19 @@ export const rewriteImportNode = (node, code, importMapConfig) => {
21
21
  else if (spec.type === "ImportSpecifier") namedImports.push({ imported: spec.imported.name, local: spec.local.name });
22
22
  });
23
23
 
24
- if (namespaceId) return `window.__notebook_scope.${namespaceId} = await import("${source}");`;
24
+ if (namespaceId) return `__scope.${namespaceId} = await import("${source}");`;
25
25
 
26
26
  const tmp = `__mod_${node.start}`;
27
27
  let lines = [`const ${tmp} = await import("${source}");`];
28
28
 
29
29
  if (defaultImportName && namedImports.length === 0) {
30
- lines.push(`window.__notebook_scope.${defaultImportName} = ${tmp}.default ?? ${tmp};`);
30
+ lines.push(`__scope.${defaultImportName} = ${tmp}.default ?? ${tmp};`);
31
31
  return lines.join("\n");
32
32
  }
33
33
 
34
- if (defaultImportName) lines.push(`window.__notebook_scope.${defaultImportName} = ${tmp}.default ?? ${tmp};`);
34
+ if (defaultImportName) lines.push(`__scope.${defaultImportName} = ${tmp}.default ?? ${tmp};`);
35
35
  namedImports.forEach(({ imported, local }) => {
36
- lines.push(`window.__notebook_scope.${local} = ${tmp}.${imported} !== undefined ? ${tmp}.${imported} : (${tmp}.default ?? ${tmp});`);
36
+ lines.push(`__scope.${local} = ${tmp}.${imported} !== undefined ? ${tmp}.${imported} : (${tmp}.default ?? ${tmp});`);
37
37
  });
38
38
 
39
39
  return lines.join("\n");
@@ -53,7 +53,7 @@ export const transformImportsAndScope = (code, importMapConfig) => {
53
53
  if (decl.id.type === "Identifier") {
54
54
  const varName = decl.id.name;
55
55
  const initCode = decl.init ? code.slice(decl.init.start, decl.init.end) : "undefined";
56
- replacementCode += `window.__notebook_scope.${varName} = ${initCode};\n`;
56
+ replacementCode += `__scope.${varName} = ${initCode};\n`;
57
57
  } else if (decl.id.type === "ObjectPattern") {
58
58
  const initCode = decl.init ? code.slice(decl.init.start, decl.init.end) : "undefined";
59
59
  const tempVar = `__destruct_obj_${decl.start}`;
@@ -62,7 +62,7 @@ export const transformImportsAndScope = (code, importMapConfig) => {
62
62
  if (prop.value && prop.value.type === "Identifier") {
63
63
  const localName = prop.value.name;
64
64
  const keyName = prop.key.type === "Identifier" ? prop.key.name : prop.key.value;
65
- replacementCode += `window.__notebook_scope.${localName} = ${tempVar}.${keyName}; `;
65
+ replacementCode += `__scope.${localName} = ${tempVar}.${keyName}; `;
66
66
  }
67
67
  });
68
68
  replacementCode += `})();\n`;
@@ -73,7 +73,7 @@ export const transformImportsAndScope = (code, importMapConfig) => {
73
73
  decl.id.elements.forEach((elem, index) => {
74
74
  if (elem && elem.type === "Identifier") {
75
75
  const localName = elem.name;
76
- replacementCode += `window.__notebook_scope.${localName} = ${tempVar}[${index}]; `;
76
+ replacementCode += `__scope.${localName} = ${tempVar}[${index}]; `;
77
77
  }
78
78
  });
79
79
  replacementCode += `})();\n`;
@@ -83,11 +83,11 @@ export const transformImportsAndScope = (code, importMapConfig) => {
83
83
  } else if (node.type === "FunctionDeclaration" && node.id) {
84
84
  const funcName = node.id.name;
85
85
  const funcBody = code.slice(node.start, node.end);
86
- modifications.push({ start: node.start, end: node.end, replacement: `window.__notebook_scope.${funcName} = ${funcBody.replace(/^function\s+\w+/, "function")}` });
86
+ modifications.push({ start: node.start, end: node.end, replacement: `__scope.${funcName} = ${funcBody.replace(/^function\s+\w+/, "function")}` });
87
87
  } else if (node.type === "ClassDeclaration" && node.id) {
88
88
  const className = node.id.name;
89
89
  const classBody = code.slice(node.start, node.end);
90
- modifications.push({ start: node.start, end: node.end, replacement: `window.__notebook_scope.${className} = ${classBody.replace(/^class\s+\w+/, "class")}` });
90
+ modifications.push({ start: node.start, end: node.end, replacement: `__scope.${className} = ${classBody.replace(/^class\s+\w+/, "class")}` });
91
91
  }
92
92
  });
93
93
 
@@ -101,18 +101,19 @@ export const transformImportsAndScope = (code, importMapConfig) => {
101
101
  }
102
102
  };
103
103
 
104
- export const evaluateCodeAsync = async (code, TARGET, importMapConfig) => {
104
+ export const evaluateCodeAsync = async (code, TARGET, importMapConfig, scope) => {
105
+ const validScope = scope || Object.create(null);
105
106
  const compiledCode = transformImportsAndScope(code, importMapConfig);
106
107
 
107
- const runCell = new Function("TARGET", "van", `
108
+ const runCell = new Function("TARGET", "van", "__scope", `
108
109
  return (async () => {
109
- with (window.__notebook_scope) {
110
+ with (__scope) {
110
111
  ${compiledCode}
111
112
  }
112
113
  })();
113
114
  `);
114
115
 
115
- const result = await runCell(TARGET, van);
116
+ const result = await runCell(TARGET, van, validScope);
116
117
  if (result !== undefined && result !== null) {
117
118
  van.add(TARGET, result);
118
119
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 ZAKARIA ELALAOUI
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.