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