@zikojs/notebook 0.4.0 → 0.5.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.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -49,6 +49,9 @@
49
49
  "codemirror": "^6.0.2",
50
50
  "lucide": "^1.44.0",
51
51
  "marked": "^18.0.12",
52
+ "rehype-stringify": "^10.0.1",
53
+ "remark": "^15.0.1",
54
+ "remark-rehype": "^11.1.2",
52
55
  "vanjs-core": "^1.6.1",
53
56
  "zextra": "^1.15.0",
54
57
  "ziko": "^2.0.0-beta.15.1"
@@ -0,0 +1,178 @@
1
+ import van from "vanjs-core";
2
+ import { remark } from "remark";
3
+ import remarkRehype from "remark-rehype";
4
+ import rehypeStringify from "rehype-stringify";
5
+ import { createCodeEditor } from "./codeEditor.js";
6
+
7
+ import {
8
+ Check,
9
+ Copy,
10
+ Lock,
11
+ Unlock,
12
+ Code2,
13
+ FileText,
14
+ Pencil,
15
+ Play,
16
+ Plus,
17
+ Trash2,
18
+ PlayForward,
19
+ Eraser,
20
+ Download,
21
+ Loader2
22
+ } from './icons.js';
23
+
24
+ const { div, span, button } = van.tags;
25
+
26
+ import { tags } from 'ziko/dom'
27
+
28
+ export const Button = ({ class: className = "", title = "", disabled = false, onclick }, ...children) =>
29
+ button({ class: `btn ${className}`, title, disabled, onclick }, ...children);
30
+
31
+ export function Header({ store, actions }) {
32
+ globalThis.tt = tags.div({ class : 'ghh'}, span('jjjj'))
33
+ const statusBadge = span({ class: "status-badge" }, Loader2(), span('kkk'));
34
+ const runAllBtn = Button({ class: "btn-primary", onclick: actions.runAll }, PlayForward(), "Run All");
35
+ const clearBtn = Button({ onclick: actions.clearOutputs }, Eraser(), "Clear Outputs");
36
+ const addCodeBtn = Button({ onclick: actions.addCode }, Play(), "Add Code");
37
+ const addMdBtn = Button({ onclick: actions.addMarkdown }, FileText(), "Add Markdown");
38
+ const deleteActiveBtn = Button({ onclick: actions.deleteActive }, Trash2(), "Delete Active");
39
+ const exportBtn = Button({ onclick: actions.exportData }, Download(), "Export Data");
40
+
41
+ store.on('change:executionQueueState', (q) => {
42
+ statusBadge.style.display = q.isRunning ? "inline-flex" : "none";
43
+ statusBadge.lastChild.textContent = `Executing Queue (${q.currentIndex + 1}/${q.total})`;
44
+ [runAllBtn, clearBtn, deleteActiveBtn].forEach(b => { b.disabled = q.isRunning; });
45
+ const maxReached = store.get('cells').length >= store.get('maxCells');
46
+ addCodeBtn.disabled = q.isRunning || maxReached;
47
+ addMdBtn.disabled = q.isRunning || maxReached;
48
+ });
49
+
50
+ return div({ class: "header" },
51
+ div({ class: "brand" }, "</>", statusBadge),
52
+ div({ class: "toolbar" },
53
+ runAllBtn, clearBtn, addCodeBtn, addMdBtn, deleteActiveBtn, exportBtn
54
+ )
55
+ );
56
+ }
57
+
58
+ export function MarkdownView({ cellData, actions }) {
59
+ const content = tags.div().element;
60
+
61
+ // Process Markdown asynchronously using Remark + Rehype
62
+ remark()
63
+ .use(remarkRehype, { allowDangerousHtml: true })
64
+ .use(rehypeStringify)
65
+ .process(cellData.code || "*Empty Markdown Cell*")
66
+ .then((file) => {
67
+ content.innerHTML = String(file);
68
+ })
69
+ .catch((err) => {
70
+ content.innerHTML = `<div class="error-output">Markdown rendering error: ${err.message}</div>`;
71
+ });
72
+
73
+ const wrap = div({ class: "markdown-rendered-cell markdown-body" }, content);
74
+ wrap.onclick = () => actions.editMarkdown();
75
+ return wrap;
76
+ }
77
+
78
+ export function CellControls({ cellData, store, actions }) {
79
+ const controlsContainer = div({ class: "cell-controls" });
80
+
81
+ const renderButtons = () => {
82
+ const isQueueRunning = store.get('executionQueueState').isRunning;
83
+ const isMaxCellsReached = store.get('cells').length >= store.get('maxCells');
84
+ const isCopied = cellData._copiedFlag === true;
85
+
86
+ controlsContainer.replaceChildren(
87
+ Button({
88
+ class: `btn-icon ${isCopied ? "btn-active" : ""}`,
89
+ title: isCopied ? "Copied!" : "Copy Cell Content",
90
+ onclick: async () => {
91
+ await actions.copyCode();
92
+ cellData._copiedFlag = true;
93
+ renderButtons();
94
+ setTimeout(() => {
95
+ cellData._copiedFlag = false;
96
+ renderButtons();
97
+ }, 1500);
98
+ }
99
+ }, isCopied ? Check() : Copy()),
100
+
101
+ Button({
102
+ class: `btn-icon ${cellData.readonly ? "btn-active" : ""}`,
103
+ title: cellData.readonly ? "Make Editable" : "Make Read-Only",
104
+ disabled: isQueueRunning,
105
+ onclick: actions.toggleReadonly,
106
+ }, cellData.readonly ? Lock() : Unlock()),
107
+
108
+ Button({
109
+ class: `btn-icon ${cellData.type === "markdown" ? "btn-active" : ""}`,
110
+ title: `Switch to ${cellData.type === "code" ? "Markdown" : "JS Code"}`,
111
+ disabled: isQueueRunning || cellData.readonly,
112
+ onclick: actions.toggleType,
113
+ }, cellData.type === "code" ? FileText() : Code2()),
114
+
115
+ (cellData.type === "markdown" && !cellData.isEditingMarkdown)
116
+ ? Button({
117
+ class: "btn-icon",
118
+ title: "Edit Markdown",
119
+ disabled: isQueueRunning || cellData.readonly,
120
+ onclick: actions.editMarkdown
121
+ }, Pencil())
122
+ : Button({
123
+ class: "btn-icon btn-primary",
124
+ title: "Run & Advance (Shift+Enter)",
125
+ disabled: isQueueRunning,
126
+ onclick: () => actions.runCode(true)
127
+ }, Play()),
128
+
129
+ Button({
130
+ class: "btn-icon",
131
+ title: "Add Cell Below",
132
+ disabled: isQueueRunning || isMaxCellsReached,
133
+ onclick: actions.addBelow
134
+ }, Plus()),
135
+
136
+ Button({
137
+ class: "btn-icon",
138
+ title: "Delete Cell",
139
+ disabled: isQueueRunning,
140
+ onclick: actions.deleteCell
141
+ }, Trash2())
142
+ );
143
+ };
144
+
145
+ renderButtons();
146
+ store.on('change', renderButtons);
147
+
148
+ return controlsContainer;
149
+ }
150
+
151
+ export function CellItem({ cellData, app, store }) {
152
+ const outputRef = div({ class: "output-area" });
153
+ if (cellData.outputNode) outputRef.appendChild(cellData.outputNode);
154
+ cellData._outputRef = outputRef;
155
+
156
+ const actions = app._cellActions(cellData);
157
+ cellData._actions = actions;
158
+ cellData._editor = createCodeEditor(app, cellData, actions);
159
+
160
+ const inPrompt = span({ class: "prompt" });
161
+ const outPrompt = span({ class: "prompt out" });
162
+ const bodySlot = div({ style: "display:contents;" });
163
+ const controlsEl = CellControls({ cellData, store, actions });
164
+
165
+ const outputGrid = div({ class: "cell-output-grid" }, outPrompt, div({ class: "output-wrapper" }, outputRef));
166
+ const inputGrid = div({ class: "cell-input-grid" }, inPrompt, bodySlot, controlsEl);
167
+ const root = div({ class: "cell" }, inputGrid, outputGrid);
168
+ root.onclick = () => app.setActiveCell(cellData.id);
169
+
170
+ cellData._dom = root;
171
+ cellData._inPrompt = inPrompt;
172
+ cellData._outPrompt = outPrompt;
173
+ cellData._bodySlot = bodySlot;
174
+ cellData._outputGrid = outputGrid;
175
+
176
+ app._refreshCell(cellData);
177
+ return root;
178
+ }
package/src/main.js CHANGED
@@ -1,528 +1,2 @@
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)
1
+ import './index.css';
2
+ export { UINotebook } from './notebook.js';
@@ -0,0 +1,341 @@
1
+ import van from "vanjs-core";
2
+ import { NotebookStore } from "./store.js";
3
+ import { Header, CellItem, MarkdownView } from "./components.js";
4
+ import { evaluateCodeAsync } from "./transform.js";
5
+
6
+ const { div } = van.tags;
7
+
8
+ export class UINotebook {
9
+ constructor({
10
+ cells: initialCells = [],
11
+ importMap = {},
12
+ runCells = true,
13
+ codeMirrorConfig = {},
14
+ codeMirrorPlugins = [],
15
+ minLines = 3,
16
+ maxCells = Infinity
17
+ } = {}) {
18
+ this.id = crypto.randomUUID ? crypto.randomUUID() : 'nb_' + Math.random().toString(36).substring(2, 9);
19
+
20
+ if (!window.__notebook_scope_map) {
21
+ window.__notebook_scope_map = new Map();
22
+ }
23
+ this.resetScope();
24
+
25
+ this.importMap = importMap;
26
+ this.codeMirrorConfig = codeMirrorConfig;
27
+ this.codeMirrorPlugins = codeMirrorPlugins;
28
+ this.minLines = minLines;
29
+ this.maxCells = maxCells;
30
+
31
+ const startingCells = maxCells !== Infinity ? initialCells.slice(0, maxCells) : initialCells;
32
+ const nextCellId = startingCells.length ? Math.max(...startingCells.map(c => c.id || 0)) + 1 : 1;
33
+
34
+ this.store = new NotebookStore({
35
+ cells: startingCells.map(cell => ({
36
+ id: cell.id || nextCellId++,
37
+ type: cell.type || "code",
38
+ code: cell.code || "",
39
+ readonly: cell.readonly ?? false,
40
+ isEditingMarkdown: cell.readonly ? false : (cell.isEditingMarkdown ?? true),
41
+ execCount: cell.execCount ?? null,
42
+ outputNode: cell.outputNode || null,
43
+ hasDomOutput: cell.hasDomOutput ?? false,
44
+ _copiedFlag: false,
45
+ _dom: null, _editor: null, _actions: null,
46
+ _inPrompt: null, _outPrompt: null, _bodySlot: null, _outputGrid: null, _outputRef: null
47
+ })),
48
+ activeCellId: startingCells.length ? startingCells[0].id : null,
49
+ executionCounter: 1,
50
+ executionQueueState: { isRunning: false, currentIndex: 0, total: 0 },
51
+ maxCells: this.maxCells
52
+ });
53
+
54
+ this.nextCellId = nextCellId;
55
+
56
+ this.notebookGlobalShortcuts = {
57
+ deleteActive: () => this.deleteCell(this.store.get('activeCellId')),
58
+ addMdBelow: () => this.addCell("markdown", "", this.store.get('activeCellId')),
59
+ addCodeBelow: () => this.addCell("code", "", this.store.get('activeCellId'))
60
+ };
61
+
62
+ this.cellsContainer = div({ class: "cells-container" });
63
+ this.header = Header({
64
+ store: this.store,
65
+ actions: {
66
+ runAll: () => this.runAllCells(),
67
+ clearOutputs: () => this.clearOutputs(),
68
+ addCode: () => this.addCell("code", "", this.store.get('activeCellId')),
69
+ addMarkdown: () => this.addCell("markdown", "", this.store.get('activeCellId')),
70
+ deleteActive: () => this.deleteCell(this.store.get('activeCellId')),
71
+ exportData: () => console.log("Notebook Data Export:", this.getNotebookData())
72
+ }
73
+ });
74
+
75
+ this.element = div(this.header, div({ class: "notebook" }, this.cellsContainer));
76
+
77
+ this._renderAllCells();
78
+
79
+ this.store.on('change:activeCellId', (newId, oldId) => {
80
+ if (oldId !== null) {
81
+ const prev = this.store.get('cells').find(c => c.id === oldId);
82
+ if (prev) this._refreshCell(prev);
83
+ }
84
+ const next = this.store.get('cells').find(c => c.id === newId);
85
+ if (next) this._refreshCell(next);
86
+ });
87
+
88
+ if (runCells) {
89
+ setTimeout(() => { this.runAllCells(); }, 200);
90
+ }
91
+ }
92
+
93
+ _isMaxCellsReached() { return this.store.get('cells').length >= this.maxCells; }
94
+
95
+ _cellActions(cellData) {
96
+ const app = this;
97
+ return {
98
+ setActive: () => app.setActiveCell(cellData.id),
99
+ runCode: async (autoNext = true) => {
100
+ const code = cellData._editor.getValue();
101
+ cellData.code = code;
102
+
103
+ if (cellData.type === "markdown") {
104
+ cellData.isEditingMarkdown = false;
105
+ if (autoNext) app.nextCell(cellData.id, "markdown");
106
+ else app._refreshCell(cellData);
107
+ return;
108
+ }
109
+
110
+ if (!code.trim()) return;
111
+
112
+ cellData._outputRef.innerHTML = "";
113
+ let hasError = false;
114
+
115
+ try {
116
+ const scope = app.getScope();
117
+ await evaluateCodeAsync(code, cellData._outputRef, app.importMap, scope);
118
+ } catch (err) {
119
+ hasError = true;
120
+ van.add(cellData._outputRef, div({ class: "error-output" }, err.toString()));
121
+ }
122
+
123
+ const counter = this.store.get('executionCounter');
124
+ this.store.set('executionCounter', counter + 1);
125
+ cellData.execCount = counter;
126
+ cellData.hasDomOutput = cellData._outputRef.childNodes.length > 0 || hasError;
127
+
128
+ const container = div({ class: "output-area" });
129
+ while (cellData._outputRef.firstChild) container.appendChild(cellData._outputRef.firstChild);
130
+ cellData.outputNode = container;
131
+ cellData._outputRef.appendChild(container);
132
+
133
+ if (autoNext && !hasError) app.nextCell(cellData.id, "code");
134
+ else app._refreshCell(cellData);
135
+ },
136
+ copyCode: async () => {
137
+ const textToCopy = cellData._editor.getValue() || cellData.code;
138
+ try {
139
+ await navigator.clipboard.writeText(textToCopy);
140
+ } catch (err) {
141
+ const textArea = document.createElement("textarea");
142
+ textArea.value = textToCopy;
143
+ document.body.appendChild(textArea);
144
+ textArea.select();
145
+ document.execCommand("copy");
146
+ document.body.removeChild(textArea);
147
+ }
148
+ },
149
+ toggleReadonly: () => {
150
+ cellData.readonly = !cellData.readonly;
151
+ if (cellData.readonly && cellData.type === "markdown") cellData.isEditingMarkdown = false;
152
+ app._refreshCell(cellData);
153
+ },
154
+ toggleType: () => {
155
+ if (cellData.readonly) return;
156
+ cellData.type = cellData.type === "code" ? "markdown" : "code";
157
+ cellData.isEditingMarkdown = true;
158
+ cellData.hasDomOutput = false;
159
+ app._refreshCell(cellData);
160
+ },
161
+ editMarkdown: () => {
162
+ if (cellData.readonly) return;
163
+ cellData.isEditingMarkdown = true;
164
+ app._refreshCell(cellData);
165
+ },
166
+ addBelow: () => app.addCell(cellData.type, null, cellData.id),
167
+ deleteCell: () => app.deleteCell(cellData.id)
168
+ };
169
+ }
170
+
171
+ _buildCellDom(cellData) {
172
+ return CellItem({ cellData, app: this, store: this.store });
173
+ }
174
+
175
+ _refreshCell(cellData) {
176
+ const activeId = this.store.get('activeCellId');
177
+ const isActive = activeId === cellData.id;
178
+ cellData._dom.className = `cell ${isActive ? "active" : ""} ${cellData.readonly ? "readonly" : ""}`.trim();
179
+
180
+ const countText = cellData.execCount ? `[${cellData.execCount}]` : "[ ]";
181
+ const isMarkdownView = cellData.type === "markdown" && !cellData.isEditingMarkdown;
182
+
183
+ cellData._inPrompt.textContent = cellData.type === "code" ? `In ${countText}:` : "";
184
+
185
+ cellData._editor.sync(isActive, isMarkdownView);
186
+ cellData._bodySlot.replaceChildren(
187
+ isMarkdownView ? MarkdownView({ cellData, actions: cellData._actions }) : cellData._editor.dom
188
+ );
189
+
190
+ const showOutput = cellData.type === "code" && cellData.hasDomOutput;
191
+ cellData._outputGrid.style.display = showOutput ? "grid" : "none";
192
+ cellData._outPrompt.textContent = `Out ${countText}:`;
193
+ }
194
+
195
+ _renderAllCells() {
196
+ const cells = this.store.get('cells');
197
+ this.cellsContainer.replaceChildren(...cells.map(c => c._dom || this._buildCellDom(c)));
198
+ }
199
+
200
+ setActiveCell(id) {
201
+ const currentActiveId = this.store.get('activeCellId');
202
+ if (currentActiveId === id) return;
203
+
204
+ // Check all cells and close editing mode for any markdown cells that are losing focus
205
+ this.store.get('cells').forEach(c => {
206
+ if (c.type === "markdown" && c.isEditingMarkdown) {
207
+ c.isEditingMarkdown = false;
208
+ this._refreshCell(c);
209
+ }
210
+ });
211
+
212
+ this.store.set('activeCellId', id);
213
+ }
214
+
215
+ focusCell(targetId) {
216
+ // Close editing on other markdown cells before focusing
217
+ this.store.get('cells').forEach(c => {
218
+ if (c.type === "markdown" && c.isEditingMarkdown && c.id !== targetId) {
219
+ c.isEditingMarkdown = false;
220
+ this._refreshCell(c);
221
+ }
222
+ });
223
+
224
+ const target = this.store.get('cells').find(c => c.id === targetId);
225
+ if (target && target.type === "markdown" && !target.readonly) {
226
+ target.isEditingMarkdown = true;
227
+ }
228
+ this.store.set('activeCellId', targetId);
229
+ }
230
+
231
+ addCell(type = "code", initialCode = null, afterId = null, readonly = false) {
232
+ const cells = [...this.store.get('cells')];
233
+ if (cells.length >= this.maxCells) {
234
+ console.warn(`Cannot create cell: Maximum cell limit (${this.maxCells}) reached.`);
235
+ return null;
236
+ }
237
+
238
+ const newId = this.nextCellId++;
239
+ const defaultText = type === "markdown" ? "### New Markdown Cell\nClick to edit..." : "";
240
+ const newCell = {
241
+ id: newId, type, code: initialCode !== null ? initialCode : defaultText, readonly,
242
+ isEditingMarkdown: !readonly && type === "markdown" && initialCode === null,
243
+ execCount: null, outputNode: null, hasDomOutput: false, _copiedFlag: false,
244
+ _dom: null, _editor: null, _actions: null,
245
+ _inPrompt: null, _outPrompt: null, _bodySlot: null, _outputGrid: null, _outputRef: null
246
+ };
247
+
248
+ if (afterId === null) {
249
+ cells.push(newCell);
250
+ } else {
251
+ const index = cells.findIndex(c => c.id === afterId);
252
+ cells.splice(index + 1, 0, newCell);
253
+ }
254
+
255
+ this.store.set('cells', cells);
256
+ this._renderAllCells();
257
+ this.focusCell(newId);
258
+ return newId;
259
+ }
260
+
261
+ deleteCell(id) {
262
+ const cells = this.store.get('cells');
263
+ if (cells.length <= 1) return;
264
+ const index = cells.findIndex(c => c.id === id);
265
+ const updatedCells = cells.filter(c => c.id !== id);
266
+
267
+ this.store.set('cells', updatedCells);
268
+ this._renderAllCells();
269
+ const nextActiveIndex = Math.min(index, updatedCells.length - 1);
270
+ this.focusCell(updatedCells[nextActiveIndex].id);
271
+ }
272
+
273
+ nextCell(currentId, defaultType) {
274
+ const cells = this.store.get('cells');
275
+ const idx = cells.findIndex(c => c.id === currentId);
276
+ if (idx === cells.length - 1) this.addCell(defaultType, null, currentId);
277
+ else this.focusCell(cells[idx + 1].id);
278
+ }
279
+
280
+ async runCell(id) {
281
+ const cell = this.store.get('cells').find(c => c.id === id);
282
+ if (cell && cell._actions) await cell._actions.runCode(false);
283
+ }
284
+
285
+ async runAllCells() {
286
+ const cells = this.store.get('cells');
287
+ const codeCells = cells.filter(c => c.type === "code");
288
+ if (codeCells.length === 0) return;
289
+
290
+ this.store.set('executionQueueState', { isRunning: true, currentIndex: 0, total: codeCells.length });
291
+
292
+ for (const cell of cells) {
293
+ if (cell.type === "code" && cell._actions) {
294
+ this.store.set('executionQueueState', {
295
+ isRunning: true,
296
+ currentIndex: codeCells.indexOf(cell),
297
+ total: codeCells.length
298
+ });
299
+ await cell._actions.runCode(false);
300
+ }
301
+ }
302
+
303
+ this.store.set('executionQueueState', { isRunning: false, currentIndex: 0, total: 0 });
304
+ }
305
+
306
+ clearOutputs() {
307
+ this.store.get('cells').forEach(cell => {
308
+ cell.execCount = null;
309
+ cell.outputNode = null;
310
+ cell.hasDomOutput = false;
311
+ if (cell._outputRef) cell._outputRef.innerHTML = "";
312
+ });
313
+ this.store.set('executionCounter', 1);
314
+ this.store.get('cells').forEach(c => this._refreshCell(c));
315
+ }
316
+
317
+ resetScope() {
318
+ if (!window.__notebook_scope_map) {
319
+ window.__notebook_scope_map = new Map();
320
+ }
321
+ const newScope = Object.create(null);
322
+ window.__notebook_scope_map.set(this.id, newScope);
323
+ return newScope;
324
+ }
325
+
326
+ getScope() {
327
+ if (!window.__notebook_scope_map || !window.__notebook_scope_map.has(this.id)) {
328
+ return this.resetScope();
329
+ }
330
+ return window.__notebook_scope_map.get(this.id);
331
+ }
332
+
333
+ getNotebookData({ inputs = true, outputs = true } = {}) {
334
+ return this.store.get('cells').map(cell => {
335
+ const exportedCell = { id: cell.id, type: cell.type, readonly: cell.readonly, order: cell.execCount };
336
+ if (inputs) exportedCell.code = cell.code;
337
+ if (outputs) exportedCell.outputHtml = cell.outputNode ? cell.outputNode.innerHTML : null;
338
+ return exportedCell;
339
+ });
340
+ }
341
+ }
package/src/store.js ADDED
@@ -0,0 +1,38 @@
1
+ export class NotebookStore {
2
+ constructor(initialState = {}) {
3
+ this.state = initialState;
4
+ this.listeners = new Map();
5
+ }
6
+
7
+ on(event, callback) {
8
+ if (!this.listeners.has(event)) {
9
+ this.listeners.set(event, new Set());
10
+ }
11
+ this.listeners.get(event).add(callback);
12
+ return () => this.off(event, callback);
13
+ }
14
+
15
+ off(event, callback) {
16
+ if (this.listeners.has(event)) {
17
+ this.listeners.get(event).delete(callback);
18
+ }
19
+ }
20
+
21
+ emit(event, payload) {
22
+ if (this.listeners.has(event)) {
23
+ for (const cb of this.listeners.get(event)) {
24
+ cb(payload);
25
+ }
26
+ }
27
+ }
28
+
29
+ set(key, value) {
30
+ this.state[key] = value;
31
+ this.emit(`change:${key}`, value);
32
+ this.emit('change', this.state);
33
+ }
34
+
35
+ get(key) {
36
+ return this.state[key];
37
+ }
38
+ }
package/src/ui.js DELETED
@@ -1,6 +0,0 @@
1
- import van from "vanjs-core";
2
-
3
- const { button } = van.tags;
4
-
5
- export const Button = ({ class: className = "", title = "", disabled = false, onclick }, ...children) =>
6
- button({ class: `btn ${className}`, title, disabled, onclick }, ...children);