@zikojs/notebook 0.2.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.
Files changed (4) hide show
  1. package/package.json +17 -10
  2. package/src/index.js +1 -528
  3. package/src/main.js +528 -0
  4. package/LICENSE +0 -21
package/package.json CHANGED
@@ -1,11 +1,17 @@
1
1
  {
2
2
  "name": "@zikojs/notebook",
3
- "version": "0.2.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.js CHANGED
@@ -1,529 +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
- import { call_with_optional_props } from 'ziko/dom/internal-utils'
8
-
9
- import {
10
- Check,
11
- Copy,
12
- Lock,
13
- Unlock,
14
- Code2,
15
- FileText,
16
- Pencil,
17
- Play,
18
- Plus,
19
- Trash2,
20
- PlayForward,
21
- Eraser,
22
- Download,
23
- Loader2
24
- } from './icons.js'
25
-
26
- const { div, span } = van.tags;
27
-
28
- export function Header({ state, actions }) {
29
- const { runAllBtn, clearBtn, addCodeBtn, addMdBtn, deleteActiveBtn, exportBtn, statusBadge, statusText } = state;
30
-
31
- return div({ class: "header" },
32
- div({ class: "brand" }, "</>", statusBadge),
33
- div({ class: "toolbar" },
34
- runAllBtn, clearBtn, addCodeBtn, addMdBtn, deleteActiveBtn, exportBtn
35
- )
36
- );
37
- }
38
-
39
- export function MarkdownView({ cellData, actions }) {
40
- const content = div();
41
- content.innerHTML = marked.parse(cellData.code || "*Empty Markdown Cell*");
42
-
43
- const wrap = div({ class: "markdown-rendered-cell markdown-body" }, content);
44
- wrap.onclick = () => actions.editMarkdown();
45
- return wrap;
46
- }
47
-
48
- export function CellControls({ cellData, state, actions }) {
49
- const isQueueRunning = state.executionQueueState_state.isRunning;
50
- const isMaxCellsReached = state.cells_state.length >= state.maxCells;
51
- const isCopied = cellData._copiedFlag_state === true;
52
-
53
- const handleCopy = async () => {
54
- await actions.copyCode();
55
- cellData._copiedFlag_state = true;
56
- state.refreshControls(cellData);
57
- setTimeout(() => {
58
- cellData._copiedFlag_state = false;
59
- state.refreshControls(cellData);
60
- }, 1500);
61
- };
62
-
63
- return [
64
- Button({
65
- class: `btn-icon ${isCopied ? "btn-active" : ""}`,
66
- title: isCopied ? "Copied!" : "Copy Cell Content",
67
- onclick: handleCopy
68
- },
69
- isCopied ? Check() : Copy()
70
- ),
71
- Button({
72
- class: `btn-icon ${cellData.readonly ? "btn-active" : ""}`,
73
- title: cellData.readonly ? "Make Editable" : "Make Read-Only",
74
- disabled: isQueueRunning,
75
- onclick: actions.toggleReadonly,
76
- },
77
- cellData.readonly ? Lock() : Unlock()
78
- ),
79
- Button({
80
- class: `btn-icon ${cellData.type === "markdown" ? "btn-active" : ""}`,
81
- title: `Switch to ${cellData.type === "code" ? "Markdown" : "JS Code"}`,
82
- disabled: isQueueRunning || cellData.readonly,
83
- onclick: actions.toggleType,
84
- },
85
- cellData.type === "code" ? FileText() : Code2()
86
- ),
87
- (cellData.type === "markdown" && !cellData.isEditingMarkdown)
88
- ? Button(
89
- {
90
- class: "btn-icon",
91
- title: "Edit Markdown",
92
- disabled: isQueueRunning || cellData.readonly,
93
- onclick: actions.editMarkdown
94
- },
95
- Pencil()
96
- )
97
- : Button({
98
- class: "btn-icon btn-primary",
99
- title: "Run & Advance (Shift+Enter)",
100
- disabled: isQueueRunning,
101
- onclick: () => actions.runCode(true)
102
- },
103
- Play()
104
- ),
105
- Button({
106
- class: "btn-icon",
107
- title: "Add Cell Below",
108
- disabled: isQueueRunning || isMaxCellsReached,
109
- onclick: actions.addBelow
110
- }, Plus()),
111
- Button({
112
- class: "btn-icon",
113
- title: "Delete Cell",
114
- disabled: isQueueRunning,
115
- onclick: actions.deleteCell
116
- }, Trash2())
117
- ];
118
- }
119
-
120
- export function CellItem({ cellData, app }) {
121
- const outputRef = div({ class: "output-area" });
122
- if (cellData.outputNode) outputRef.appendChild(cellData.outputNode);
123
- cellData._outputRef = outputRef;
124
-
125
- const actions = app._cellActions(cellData);
126
- cellData._actions = actions;
127
- cellData._editor = createCodeEditor(app, cellData, actions);
128
-
129
- const inPrompt = span({ class: "prompt" });
130
- const outPrompt = span({ class: "prompt out" });
131
- const bodySlot = div({ style: "display:contents;" });
132
- const controlsEl = div({ class: "cell-controls" });
133
-
134
- const outputGrid = div({ class: "cell-output-grid" }, outPrompt, div({ class: "output-wrapper" }, outputRef));
135
- const inputGrid = div({ class: "cell-input-grid" }, inPrompt, bodySlot, controlsEl);
136
- const root = div({ class: "cell" }, inputGrid, outputGrid);
137
- root.onclick = () => app.setActiveCell(cellData.id);
138
-
139
- cellData._dom = root;
140
- cellData._inPrompt = inPrompt;
141
- cellData._outPrompt = outPrompt;
142
- cellData._bodySlot = bodySlot;
143
- cellData._controlsEl = controlsEl;
144
- cellData._outputGrid = outputGrid;
145
-
146
- app._refreshCell(cellData);
147
- return root;
148
- }
149
-
150
- export class UINotebook {
151
- constructor({
152
- cells: initialCells = [],
153
- importMap = {},
154
- runCells = true,
155
- codeMirrorConfig = {},
156
- markedPlugins = [],
157
- codeMirrorPlugins = [],
158
- minLines = 3,
159
- maxCells = Infinity
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
-
172
- this.importMap = importMap;
173
- this.codeMirrorConfig = codeMirrorConfig;
174
- this.codeMirrorPlugins = codeMirrorPlugins;
175
- this.minLines = minLines;
176
- this.maxCells = maxCells;
177
-
178
- if (Array.isArray(markedPlugins) && markedPlugins.length > 0) {
179
- markedPlugins.forEach(plugin => marked.use(plugin));
180
- }
181
-
182
- const startingCells = maxCells !== Infinity ? initialCells.slice(0, maxCells) : initialCells;
183
-
184
- this.nextCellId_state = startingCells.length ? Math.max(...startingCells.map(c => c.id || 0)) + 1 : 1;
185
-
186
- this.cells_state = startingCells.map(cell => ({
187
- id: cell.id || this.nextCellId_state++,
188
- type: cell.type || "code",
189
- code: cell.code || "",
190
- readonly: cell.readonly ?? false,
191
- isEditingMarkdown: cell.readonly ? false : (cell.isEditingMarkdown ?? true),
192
- execCount: cell.execCount ?? null,
193
- outputNode: cell.outputNode || null,
194
- hasDomOutput: cell.hasDomOutput ?? false,
195
- _copiedFlag_state: false,
196
- _dom: null, _editor: null, _actions: null,
197
- _inPrompt: null, _outPrompt: null, _bodySlot: null, _controlsEl: null, _outputGrid: null, _outputRef: null
198
- }));
199
-
200
- this.activeCellId_state = this.cells_state.length ? this.cells_state[0].id : null;
201
- this.executionCounter_state = 1;
202
- this.executionQueueState_state = { isRunning: false, currentIndex: 0, total: 0 };
203
-
204
- this.notebookGlobalShortcuts = {
205
- deleteActive: () => this.deleteCell(this.activeCellId_state),
206
- addMdBelow: () => this.addCell("markdown", "", this.activeCellId_state),
207
- addCodeBelow: () => this.addCell("code", "", this.activeCellId_state)
208
- };
209
-
210
- this.cellsContainer = div({ class: "cells-container" });
211
- this.header = this._buildHeader();
212
- this.element = div(this.header, div({ class: "notebook" }, this.cellsContainer));
213
-
214
- this._renderAllCells();
215
-
216
- if (runCells) {
217
- setTimeout(() => { this.runAllCells(); }, 200);
218
- }
219
- }
220
-
221
- _isMaxCellsReached() { return this.cells_state.length >= this.maxCells; }
222
-
223
- // --- HEADER BUILDER ---
224
-
225
- _buildHeader() {
226
- this.runAllBtn = Button({
227
- class: "btn-primary",
228
- onclick: () => this.runAllCells(),
229
- }, PlayForward(), "Run All"
230
- );
231
- this.clearBtn = Button({
232
- onclick: () => this.clearOutputs()
233
- }, Eraser(), "Clear Outputs");
234
- this.addCodeBtn = Button({
235
- onclick: () => this.addCell("code", "", this.activeCellId_state),
236
- }, Play(), "Add Code");
237
- this.addMdBtn = Button({
238
- onclick: () => this.addCell("markdown", "", this.activeCellId_state),
239
- }, FileText(), "Add Markdown");
240
- this.deleteActiveBtn = Button({
241
- onclick: () => this.deleteCell(this.activeCellId_state)
242
- }, Trash2(), "Delete Active");
243
- this.exportBtn = Button({
244
- onclick: () => console.log("Notebook Data Export:", this.getNotebookData())
245
- }, Download(), "Export Data");
246
-
247
- this.statusText = span();
248
- this.statusBadge = span({
249
- class: "status-badge",
250
- style: "display:none;"
251
- }, Loader2(), this.statusText);
252
-
253
- const header = Header({
254
- state: {
255
- runAllBtn: this.runAllBtn,
256
- clearBtn: this.clearBtn,
257
- addCodeBtn: this.addCodeBtn,
258
- addMdBtn: this.addMdBtn,
259
- deleteActiveBtn: this.deleteActiveBtn,
260
- exportBtn: this.exportBtn,
261
- statusBadge: this.statusBadge,
262
- statusText: this.statusText
263
- }
264
- });
265
-
266
- this._updateHeaderUI();
267
- return header;
268
- }
269
-
270
- _updateHeaderUI() {
271
- const q = this.executionQueueState_state;
272
- this.statusBadge.style.display = q.isRunning ? "inline-flex" : "none";
273
- this.statusText.textContent = `Executing Queue (${q.currentIndex + 1}/${q.total})`;
274
- [this.runAllBtn, this.clearBtn, this.deleteActiveBtn].forEach(b => { b.disabled = q.isRunning; });
275
- const maxReached = this._isMaxCellsReached();
276
- this.addCodeBtn.disabled = q.isRunning || maxReached;
277
- this.addMdBtn.disabled = q.isRunning || maxReached;
278
- }
279
-
280
- // --- CELL ACTIONS & DOM ---
281
-
282
- _cellActions(cellData) {
283
- const app = this;
284
- return {
285
- setActive: () => app.setActiveCell(cellData.id),
286
- runCode: async (autoNext = true) => {
287
- const code = cellData._editor.getValue();
288
- cellData.code = code;
289
-
290
- if (cellData.type === "markdown") {
291
- cellData.isEditingMarkdown = false;
292
- if (autoNext) app.nextCell(cellData.id, "markdown");
293
- else app._refreshCell(cellData);
294
- return;
295
- }
296
-
297
- if (!code.trim()) return;
298
-
299
- cellData._outputRef.innerHTML = "";
300
- let hasError = false;
301
-
302
- try {
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);
308
- } catch (err) {
309
- hasError = true;
310
- van.add(cellData._outputRef, div({ class: "error-output" }, err.toString()));
311
- }
312
-
313
- cellData.execCount = app.executionCounter_state++;
314
- cellData.hasDomOutput = cellData._outputRef.childNodes.length > 0 || hasError;
315
-
316
- const container = div({ class: "output-area" });
317
- while (cellData._outputRef.firstChild) container.appendChild(cellData._outputRef.firstChild);
318
- cellData.outputNode = container;
319
- cellData._outputRef.appendChild(container);
320
-
321
- if (autoNext && !hasError) app.nextCell(cellData.id, "code");
322
- else app._refreshCell(cellData);
323
- },
324
- copyCode: async () => {
325
- const textToCopy = cellData._editor.getValue() || cellData.code;
326
- try {
327
- await navigator.clipboard.writeText(textToCopy);
328
- } catch (err) {
329
- const textArea = document.createElement("textarea");
330
- textArea.value = textToCopy;
331
- document.body.appendChild(textArea);
332
- textArea.select();
333
- document.execCommand("copy");
334
- document.body.removeChild(textArea);
335
- }
336
- },
337
- toggleReadonly: () => {
338
- cellData.readonly = !cellData.readonly;
339
- if (cellData.readonly && cellData.type === "markdown") cellData.isEditingMarkdown = false;
340
- app._refreshCell(cellData);
341
- },
342
- toggleType: () => {
343
- if (cellData.readonly) return;
344
- cellData.type = cellData.type === "code" ? "markdown" : "code";
345
- cellData.isEditingMarkdown = true;
346
- cellData.hasDomOutput = false;
347
- app._refreshCell(cellData);
348
- },
349
- editMarkdown: () => {
350
- if (cellData.readonly) return;
351
- cellData.isEditingMarkdown = true;
352
- app._refreshCell(cellData);
353
- },
354
- addBelow: () => app.addCell(cellData.type, null, cellData.id),
355
- deleteCell: () => app.deleteCell(cellData.id)
356
- };
357
- }
358
-
359
- _buildCellDom(cellData) {
360
- return CellItem({ cellData, app: this });
361
- }
362
-
363
- _refreshCell(cellData) {
364
- const isActive = this.activeCellId_state === cellData.id;
365
- cellData._dom.className = `cell ${isActive ? "active" : ""} ${cellData.readonly ? "readonly" : ""}`.trim();
366
-
367
- const countText = cellData.execCount ? `[${cellData.execCount}]` : "[ ]";
368
- const isMarkdownView = cellData.type === "markdown" && !cellData.isEditingMarkdown;
369
-
370
- cellData._inPrompt.textContent = cellData.type === "code" ? `In ${countText}:` : "";
371
-
372
- cellData._editor.sync(isActive, isMarkdownView);
373
- cellData._bodySlot.replaceChildren(
374
- isMarkdownView ? MarkdownView({ cellData, actions: cellData._actions }) : cellData._editor.dom
375
- );
376
-
377
- this._refreshCellControls(cellData);
378
-
379
- const showOutput = cellData.type === "code" && cellData.hasDomOutput;
380
- cellData._outputGrid.style.display = showOutput ? "grid" : "none";
381
- cellData._outPrompt.textContent = `Out ${countText}:`;
382
- }
383
-
384
- _refreshCellControls(cellData) {
385
- const buttons = CellControls({
386
- cellData,
387
- state: this,
388
- actions: cellData._actions
389
- });
390
- cellData._controlsEl.replaceChildren(...buttons);
391
- }
392
-
393
- // --- STATE & SCOPE MUTATORS ---
394
-
395
- _renderAllCells() {
396
- this.cellsContainer.replaceChildren(...this.cells_state.map(c => c._dom || this._buildCellDom(c)));
397
- this._updateHeaderUI();
398
- }
399
-
400
- setActiveCell(id) {
401
- if (this.activeCellId_state === id) return;
402
- const current = this.cells_state.find(c => c.id === this.activeCellId_state);
403
- if (current && current.type === "markdown" && current.isEditingMarkdown) current.isEditingMarkdown = false;
404
- this.activeCellId_state = id;
405
- if (current) this._refreshCell(current);
406
- const next = this.cells_state.find(c => c.id === id);
407
- if (next) this._refreshCell(next);
408
- }
409
-
410
- focusCell(targetId) {
411
- const prevId = this.activeCellId_state;
412
- this.activeCellId_state = targetId;
413
- const target = this.cells_state.find(c => c.id === targetId);
414
- if (target && target.type === "markdown" && !target.readonly) target.isEditingMarkdown = true;
415
- if (prevId !== targetId) {
416
- const prevCell = this.cells_state.find(c => c.id === prevId);
417
- if (prevCell) this._refreshCell(prevCell);
418
- }
419
- if (target) this._refreshCell(target);
420
- }
421
-
422
- addCell(type = "code", initialCode = null, afterId = null, readonly = false) {
423
- if (this.cells_state.length >= this.maxCells) {
424
- console.warn(`Cannot create cell: Maximum cell limit (${this.maxCells}) reached.`);
425
- return null;
426
- }
427
-
428
- const newId = this.nextCellId_state++;
429
- const defaultText = type === "markdown" ? "### New Markdown Cell\nClick to edit..." : "";
430
- const newCell = {
431
- id: newId, type, code: initialCode !== null ? initialCode : defaultText, readonly,
432
- isEditingMarkdown: !readonly && type === "markdown" && initialCode === null,
433
- execCount: null, outputNode: null, hasDomOutput: false, _copiedFlag_state: false,
434
- _dom: null, _editor: null, _actions: null,
435
- _inPrompt: null, _outPrompt: null, _bodySlot: null, _controlsEl: null, _outputGrid: null, _outputRef: null
436
- };
437
-
438
- if (afterId === null) {
439
- this.cells_state.push(newCell);
440
- } else {
441
- const index = this.cells_state.findIndex(c => c.id === afterId);
442
- this.cells_state.splice(index + 1, 0, newCell);
443
- }
444
-
445
- this._renderAllCells();
446
- this.focusCell(newId);
447
- return newId;
448
- }
449
-
450
- deleteCell(id) {
451
- if (this.cells_state.length <= 1) return;
452
- const index = this.cells_state.findIndex(c => c.id === id);
453
- this.cells_state = this.cells_state.filter(c => c.id !== id);
454
- this._renderAllCells();
455
- const nextActiveIndex = Math.min(index, this.cells_state.length - 1);
456
- this.focusCell(this.cells_state[nextActiveIndex].id);
457
- }
458
-
459
- nextCell(currentId, defaultType) {
460
- const idx = this.cells_state.findIndex(c => c.id === currentId);
461
- if (idx === this.cells_state.length - 1) this.addCell(defaultType, null, currentId);
462
- else this.focusCell(this.cells_state[idx + 1].id);
463
- }
464
-
465
- async runCell(id) {
466
- const cell = this.cells_state.find(c => c.id === id);
467
- if (cell && cell._actions) await cell._actions.runCode(false);
468
- }
469
-
470
- async runAllCells() {
471
- const codeCells = this.cells_state.filter(c => c.type === "code");
472
- if (codeCells.length === 0) return;
473
-
474
- this.executionQueueState_state = { isRunning: true, currentIndex: 0, total: codeCells.length };
475
- this._updateHeaderUI();
476
- this.cells_state.forEach(c => this._refreshCellControls(c));
477
-
478
- for (const cell of this.cells_state) {
479
- if (cell.type === "code" && cell._actions) {
480
- this.executionQueueState_state = { ...this.executionQueueState_state, currentIndex: codeCells.indexOf(cell) };
481
- this._updateHeaderUI();
482
- await cell._actions.runCode(false);
483
- }
484
- }
485
-
486
- this.executionQueueState_state = { isRunning: false, currentIndex: 0, total: 0 };
487
- this._updateHeaderUI();
488
- this.cells_state.forEach(c => this._refreshCellControls(c));
489
- }
490
-
491
- clearOutputs() {
492
- this.cells_state.forEach(cell => {
493
- cell.execCount = null;
494
- cell.outputNode = null;
495
- cell.hasDomOutput = false;
496
- if (cell._outputRef) cell._outputRef.innerHTML = "";
497
- });
498
- this.executionCounter_state = 1;
499
- this.cells_state.forEach(c => this._refreshCell(c));
500
- }
501
-
502
- resetScope() {
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);
516
- }
517
-
518
- getNotebookData({ inputs = true, outputs = true } = {}) {
519
- return this.cells_state.map(cell => {
520
- const exportedCell = { id: cell.id, type: cell.type, readonly: cell.readonly, order: cell.execCount };
521
- if (inputs) exportedCell.code = cell.code;
522
- if (outputs) exportedCell.outputHtml = cell.outputNode ? cell.outputNode.innerHTML : null;
523
- return exportedCell;
524
- });
525
- }
526
- }
527
-
528
-
529
- export const Notebook = call_with_optional_props(UINotebook)
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/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.