@zikojs/notebook 0.1.0 → 0.2.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,6 +1,6 @@
1
1
  {
2
2
  "name": "@zikojs/notebook",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "publishConfig": {
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
@@ -4,6 +4,7 @@ import { marked } from "marked";
4
4
  import { Button } from "./ui.js";
5
5
  import { createCodeEditor } from "./codeEditor.js";
6
6
  import { evaluateCodeAsync } from "./transform.js";
7
+ import { call_with_optional_props } from 'ziko/dom/internal-utils'
7
8
 
8
9
  import {
9
10
  Check,
@@ -28,7 +29,7 @@ export function Header({ state, actions }) {
28
29
  const { runAllBtn, clearBtn, addCodeBtn, addMdBtn, deleteActiveBtn, exportBtn, statusBadge, statusText } = state;
29
30
 
30
31
  return div({ class: "header" },
31
- div({ class: "brand" }, "Jupyter VanJS Notebook", statusBadge),
32
+ div({ class: "brand" }, "</>", statusBadge),
32
33
  div({ class: "toolbar" },
33
34
  runAllBtn, clearBtn, addCodeBtn, addMdBtn, deleteActiveBtn, exportBtn
34
35
  )
@@ -146,9 +147,7 @@ export function CellItem({ cellData, app }) {
146
147
  return root;
147
148
  }
148
149
 
149
- // --- MAIN NOTEBOOK APP CLASS ---
150
-
151
- export class NotebookApp {
150
+ export class UINotebook {
152
151
  constructor({
153
152
  cells: initialCells = [],
154
153
  importMap = {},
@@ -159,6 +158,17 @@ export class NotebookApp {
159
158
  minLines = 3,
160
159
  maxCells = Infinity
161
160
  } = {}) {
161
+ // 1. Generate unique UUID for this notebook instance
162
+ this.id = crypto.randomUUID ? crypto.randomUUID() : 'nb_' + Math.random().toString(36).substring(2, 9);
163
+
164
+ // 2. Initialize the global scope map if not already present
165
+ if (!window.__notebook_scope_map) {
166
+ window.__notebook_scope_map = new Map();
167
+ }
168
+
169
+ // 3. Register this instance's isolated scope
170
+ this.resetScope();
171
+
162
172
  this.importMap = importMap;
163
173
  this.codeMirrorConfig = codeMirrorConfig;
164
174
  this.codeMirrorPlugins = codeMirrorPlugins;
@@ -290,7 +300,11 @@ export class NotebookApp {
290
300
  let hasError = false;
291
301
 
292
302
  try {
293
- await evaluateCodeAsync(code, cellData._outputRef, app.importMap);
303
+ // Retrieve this specific instance's compatible scope from window.__notebook_scope_map
304
+ const scope = app.getScope();
305
+
306
+ // Pass either the scope object or the instance ID (app.id) to evaluateCodeAsync
307
+ await evaluateCodeAsync(code, cellData._outputRef, app.importMap, scope);
294
308
  } catch (err) {
295
309
  hasError = true;
296
310
  van.add(cellData._outputRef, div({ class: "error-output" }, err.toString()));
@@ -376,7 +390,7 @@ export class NotebookApp {
376
390
  cellData._controlsEl.replaceChildren(...buttons);
377
391
  }
378
392
 
379
- // --- STATE MUTATORS ---
393
+ // --- STATE & SCOPE MUTATORS ---
380
394
 
381
395
  _renderAllCells() {
382
396
  this.cellsContainer.replaceChildren(...this.cells_state.map(c => c._dom || this._buildCellDom(c)));
@@ -486,7 +500,19 @@ export class NotebookApp {
486
500
  }
487
501
 
488
502
  resetScope() {
489
- window.__notebook_scope = Object.create(null);
503
+ if (!window.__notebook_scope_map) {
504
+ window.__notebook_scope_map = new Map();
505
+ }
506
+ const newScope = Object.create(null);
507
+ window.__notebook_scope_map.set(this.id, newScope);
508
+ return newScope;
509
+ }
510
+
511
+ getScope() {
512
+ if (!window.__notebook_scope_map || !window.__notebook_scope_map.has(this.id)) {
513
+ return this.resetScope();
514
+ }
515
+ return window.__notebook_scope_map.get(this.id);
490
516
  }
491
517
 
492
518
  getNotebookData({ inputs = true, outputs = true } = {}) {
@@ -497,4 +523,7 @@ export class NotebookApp {
497
523
  return exportedCell;
498
524
  });
499
525
  }
500
- }
526
+ }
527
+
528
+
529
+ 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
  }