From 1bff64537f26474b3de27e8d5bb2aeb8a02b0193 Mon Sep 17 00:00:00 2001 From: Luyu Cheng <2239547+chengluyu@users.noreply.github.com> Date: Fri, 24 Oct 2025 08:52:21 +0800 Subject: [PATCH 1/6] Introduce related field effects and states --- editor/blockAttributes.js | 39 ++++++++++++++++++++++++++++++++ editor/decoration.js | 44 +++++++++++++++++++++++++++++------- editor/index.css | 4 ++++ editor/index.js | 39 ++++++++++++++++++++++++++++++-- runtime/index.js | 47 +++++++++++++++++++++++++++++---------- 5 files changed, 151 insertions(+), 22 deletions(-) create mode 100644 editor/blockAttributes.js diff --git a/editor/blockAttributes.js b/editor/blockAttributes.js new file mode 100644 index 0000000..4b67fd5 --- /dev/null +++ b/editor/blockAttributes.js @@ -0,0 +1,39 @@ +import {StateField, StateEffect} from "@codemirror/state"; + +/** + * Effect to set block attributes + * @type {StateEffect<{from: number, to: number, attributes: Object}[]>} + */ +export const setBlockAttributesEffect = StateEffect.define(); + +/** + * StateField that stores block attributes keyed by line ranges + * Structure: Array of {from, to, attributes} + * @type {StateField<{from: number, to: number, attributes: Object}[]>} + */ +export const blockAttributesField = StateField.define({ + create() { + return []; + }, + update(blocks, tr) { + // If document changed, map existing blocks to new positions + if (tr.docChanged) { + blocks = blocks.map(block => ({ + from: tr.changes.mapPos(block.from), + to: tr.changes.mapPos(block.to), + attributes: block.attributes, + })); + } + + // Check for setBlockAttributesEffect + for (const effect of tr.effects) { + if (effect.is(setBlockAttributesEffect)) { + blocks = effect.value; + } + } + + return blocks; + }, +}); + +export const blockAttributes = blockAttributesField.extension; diff --git a/editor/decoration.js b/editor/decoration.js index 6d8d038..5b2272d 100644 --- a/editor/decoration.js +++ b/editor/decoration.js @@ -1,21 +1,46 @@ import {Decoration, ViewPlugin, ViewUpdate, EditorView} from "@codemirror/view"; import {outputLinesField} from "./outputLines"; -import {RangeSetBuilder} from "@codemirror/state"; +import {blockAttributesField} from "./blockAttributes"; +import {RangeSet, RangeSetBuilder} from "@codemirror/state"; const highlight = Decoration.line({attributes: {class: "cm-output-line"}}); const errorHighlight = Decoration.line({attributes: {class: "cm-output-line cm-error-line"}}); +const compactLineDecoration = Decoration.line({attributes: {class: "cm-output-line cm-compact-line"}}); // const linePrefix = Decoration.mark({attributes: {class: "cm-output-line-prefix"}}); // const lineContent = Decoration.mark({attributes: {class: "cm-output-line-content"}}); -function createWidgets(lines) { - const builder = new RangeSetBuilder(); +function createWidgets(lines, blockAttributes, state) { + // Build the range set for output lines. + const builder1 = new RangeSetBuilder(); + // Add output line decorations for (const {from, type} of lines) { - if (type === "output") builder.add(from, from, highlight); - else if (type === "error") builder.add(from, from, errorHighlight); + if (type === "output") builder1.add(from, from, highlight); + else if (type === "error") builder1.add(from, from, errorHighlight); // builder.add(from, from + 3, linePrefix); // builder.add(from + 4, to, lineContent); } - return builder.finish(); + const set1 = builder1.finish(); + + // Build the range set for block attributes. + const builder2 = new RangeSetBuilder(); + // Add block attribute decorations + for (const {from, to, attributes} of blockAttributes) { + // Apply decorations to each line in the block range + const startLine = state.doc.lineAt(from); + const endLine = state.doc.lineAt(to); + + for (let lineNum = startLine.number; lineNum <= endLine.number; lineNum++) { + const line = state.doc.line(lineNum); + if (attributes.compact === true) { + builder2.add(line.from, line.from, compactLineDecoration); + } + } + } + const set2 = builder2.finish(); + + // Range sets are required to be sorted. Fortunately, they provide a method + // to merge multiple range sets into a single sorted range set. + return RangeSet.join([set1, set2]); } export const outputDecoration = ViewPlugin.fromClass( @@ -28,14 +53,17 @@ export const outputDecoration = ViewPlugin.fromClass( /** @param {EditorView} view */ constructor(view) { - this.#decorations = createWidgets(view.state.field(outputLinesField)); + const outputLines = view.state.field(outputLinesField); + const blockAttributes = view.state.field(blockAttributesField); + this.#decorations = createWidgets(outputLines, blockAttributes, view.state); } /** @param {ViewUpdate} update */ update(update) { const newOutputLines = update.state.field(outputLinesField); + const newBlockAttributes = update.state.field(blockAttributesField); // A possible optimization would be to only update the changed lines. - this.#decorations = createWidgets(newOutputLines); + this.#decorations = createWidgets(newOutputLines, newBlockAttributes, update.state); } }, {decorations: (v) => v.decorations}, diff --git a/editor/index.css b/editor/index.css index 29cdb12..110964f 100644 --- a/editor/index.css +++ b/editor/index.css @@ -143,6 +143,10 @@ /*background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='4' height='4' viewBox='0 0 4 4'%3E%3Cpath fill='%237d7d7d' fill-opacity='0.4' d='M1 3h1v1H1V3zm2-2h1v1H3V1z'%3E%3C/path%3E%3C/svg%3E");*/ } + .cm-output-line.cm-compact-line { + line-height: 1; + } + /* We can't see background color, which is conflict with selection background color. * So we use svg pattern to simulate the background color. */ diff --git a/editor/index.js b/editor/index.js index 2b1d2bd..2e9ab1c 100644 --- a/editor/index.js +++ b/editor/index.js @@ -11,6 +11,7 @@ import * as eslint from "eslint-linter-browserify"; import {createRuntime} from "../runtime/index.js"; import {outputDecoration} from "./decoration.js"; import {outputLines} from "./outputLines.js"; +import {blockAttributes, setBlockAttributesEffect} from "./blockAttributes.js"; // import {outputProtection} from "./protection.js"; import {dispatch as d3Dispatch} from "d3-dispatch"; import {controls} from "./controls/index.js"; @@ -68,6 +69,7 @@ export function createEditor(container, options) { ]), javascriptLanguage.data.of({autocomplete: rechoCompletion}), outputLines, + blockAttributes, outputDecoration, controls(runtimeRef), // Disable this for now, because it prevents copying/pasting the code. @@ -89,9 +91,42 @@ export function createEditor(container, options) { window.addEventListener("keyup", onKeyUp); } - function dispatch(changes) { + function dispatch({changes, blockAttributes: blockAttrs}) { + // Map block attributes through the changes to get correct final positions + const effects = []; + + if (blockAttrs && blockAttrs.length > 0) { + // We need to map the block positions through the changes + // Create a simplified change set mapper + const sortedChanges = [...changes].sort((a, b) => a.from - b.from); + + const mapPos = (pos) => { + let mapped = pos; + for (const change of sortedChanges) { + if (change.from <= pos) { + const inserted = change.insert ? change.insert.length : 0; + const deleted = change.to ? change.to - change.from : 0; + mapped += inserted - deleted; + } + } + return mapped; + }; + + const mappedBlockAttrs = blockAttrs.map(({from, to, attributes}) => ({ + from: mapPos(from), + to: mapPos(to), + attributes, + })); + + effects.push(setBlockAttributesEffect.of(mappedBlockAttrs)); + } + // Mark this transaction as from runtime so that it will not be filtered out. - view.dispatch({changes, annotations: [Transaction.remote.of("runtime")]}); + view.dispatch({ + changes, + effects, + annotations: [Transaction.remote.of("runtime")], + }); } function onChange(update) { diff --git a/runtime/index.js b/runtime/index.js index 86a63c5..637306e 100644 --- a/runtime/index.js +++ b/runtime/index.js @@ -125,7 +125,16 @@ export function createRuntime(initialCode) { } } - dispatch(changes); + // Collect block attributes - we need to map positions through the changes + const blockAttributes = nodes + .filter((node) => Object.keys(node.state.attributes).length > 0) + .map((node) => ({ + from: node.start, + to: node.end, + attributes: node.state.attributes, + })); + + dispatch(changes, blockAttributes); }, 0); function setCode(newCode) { @@ -136,8 +145,8 @@ export function createRuntime(initialCode) { isRunning = value; } - function dispatch(changes) { - dispatcher.call("changes", null, changes); + function dispatch(changes, blockAttributes = []) { + dispatcher.call("changes", null, {changes, blockAttributes}); } function onChanges(callback) { @@ -294,7 +303,14 @@ export function createRuntime(initialCode) { for (const node of enter) { const vid = uid(); const {inputs, body, outputs, error = null} = node.transpiled; - const state = {values: [], variables: [], error: null, syntaxError: error, doc: false}; + const state = { + values: [], + variables: [], + error: null, + syntaxError: error, + doc: false, + attributes: Object.create(null), + }; node.state = state; const v = main.variable(observer(state), {shadow: {}}); if (inputs.includes("echo")) { @@ -304,14 +320,21 @@ export function createRuntime(initialCode) { inputs.filter((i) => i !== "echo" && i !== "clear"), () => { const version = v._version; // Capture version on input change. - return (value, ...args) => { - if (version < docVersion) throw new Error("stale echo"); - else if (state.variables[0] !== v) throw new Error("stale echo"); - else if (version > docVersion) clear(state); - docVersion = version; - echo(state, value, ...args); - return args.length ? [value, ...args] : value; - }; + return Object.assign( + function (value, ...args) { + if (version < docVersion) throw new Error("stale echo"); + else if (state.variables[0] !== v) throw new Error("stale echo"); + else if (version > docVersion) clear(state); + docVersion = version; + echo(state, value, ...args); + return args.length ? [value, ...args] : value; + }, + { + set: function (key, value) { + state.attributes[key] = value; + }, + }, + ); }, ); v._shadow.set("echo", vd); From 721b59f57449c1c9abb66d972e09e3eb307331db Mon Sep 17 00:00:00 2001 From: Luyu Cheng <2239547+chengluyu@users.noreply.github.com> Date: Fri, 24 Oct 2025 16:21:35 +0800 Subject: [PATCH 2/6] Initialize block metadata using runtime --- editor/blockAttributes.js | 39 ---- editor/blockMetadata.ts | 54 ++++++ editor/decoration.js | 46 +++-- editor/index.css | 12 ++ editor/index.js | 37 +--- lib/IntervalTree.ts | 369 +++++++++++++++++++++++++++++++++++ runtime/index.js | 94 ++++++--- test/IntervalTree.spec.js | 395 ++++++++++++++++++++++++++++++++++++++ 8 files changed, 929 insertions(+), 117 deletions(-) delete mode 100644 editor/blockAttributes.js create mode 100644 editor/blockMetadata.ts create mode 100644 lib/IntervalTree.ts create mode 100644 test/IntervalTree.spec.js diff --git a/editor/blockAttributes.js b/editor/blockAttributes.js deleted file mode 100644 index 4b67fd5..0000000 --- a/editor/blockAttributes.js +++ /dev/null @@ -1,39 +0,0 @@ -import {StateField, StateEffect} from "@codemirror/state"; - -/** - * Effect to set block attributes - * @type {StateEffect<{from: number, to: number, attributes: Object}[]>} - */ -export const setBlockAttributesEffect = StateEffect.define(); - -/** - * StateField that stores block attributes keyed by line ranges - * Structure: Array of {from, to, attributes} - * @type {StateField<{from: number, to: number, attributes: Object}[]>} - */ -export const blockAttributesField = StateField.define({ - create() { - return []; - }, - update(blocks, tr) { - // If document changed, map existing blocks to new positions - if (tr.docChanged) { - blocks = blocks.map(block => ({ - from: tr.changes.mapPos(block.from), - to: tr.changes.mapPos(block.to), - attributes: block.attributes, - })); - } - - // Check for setBlockAttributesEffect - for (const effect of tr.effects) { - if (effect.is(setBlockAttributesEffect)) { - blocks = effect.value; - } - } - - return blocks; - }, -}); - -export const blockAttributes = blockAttributesField.extension; diff --git a/editor/blockMetadata.ts b/editor/blockMetadata.ts new file mode 100644 index 0000000..2fd826d --- /dev/null +++ b/editor/blockMetadata.ts @@ -0,0 +1,54 @@ +import {StateField, StateEffect} from "@codemirror/state"; + +export const blockMetadataEffect = StateEffect.define(); + +type BlockMetadata = { + output: {from: number; to: number} | null; + source: {from: number; to: number}; + attributes: Record; +}; + +export const blockMetadataField = StateField.define({ + create() { + return []; + }, + update(blocks, tr) { + // Find if the block attributes effect is present. + let blocksFromEffect: BlockMetadata[] | null = null; + for (const effect of tr.effects) { + if (effect.is(blockMetadataEffect)) { + blocksFromEffect = effect.value; + break; + } + } + + if (blocksFromEffect === null) { + // If the block attributes effect is not present, then this transaction + // is made by the user, we need to update the block attributes accroding + // to the latest syntax tree. TODO + return blocks; + } else { + // Otherwise, we need to update the block attributes according to the + // metadata sent from the runtime. Most importantly, we need to translate + // the position of each block after the changes has been made. + for (const block of blocksFromEffect) { + if (block.output === null) { + const from = tr.changes.mapPos(block.source.from, -1); + const to = tr.changes.mapPos(block.source.from, 1); + block.output = {from, to: to - 1}; + } else { + const from = tr.changes.mapPos(block.output.from, -1); + const to = tr.changes.mapPos(block.output.to, 1); + block.output = {from, to: to - 1}; + } + block.source = { + from: tr.changes.mapPos(block.source.from, 1), + to: tr.changes.mapPos(block.source.to, 1), + }; + } + return blocksFromEffect; + } + }, +}); + +export const blockMetadata = blockMetadataField.extension; diff --git a/editor/decoration.js b/editor/decoration.js index 5b2272d..9e4913a 100644 --- a/editor/decoration.js +++ b/editor/decoration.js @@ -1,15 +1,18 @@ import {Decoration, ViewPlugin, ViewUpdate, EditorView} from "@codemirror/view"; import {outputLinesField} from "./outputLines"; -import {blockAttributesField} from "./blockAttributes"; +import {blockMetadataField} from "./blockMetadata"; import {RangeSet, RangeSetBuilder} from "@codemirror/state"; const highlight = Decoration.line({attributes: {class: "cm-output-line"}}); const errorHighlight = Decoration.line({attributes: {class: "cm-output-line cm-error-line"}}); const compactLineDecoration = Decoration.line({attributes: {class: "cm-output-line cm-compact-line"}}); +const debugGreenDecoration = Decoration.mark({attributes: {class: "cm-debug-mark green"}}); +const debugRedDecoration = Decoration.mark({attributes: {class: "cm-debug-mark red"}}); +const debugBlueDecoration = Decoration.mark({attributes: {class: "cm-debug-mark blue"}}); // const linePrefix = Decoration.mark({attributes: {class: "cm-output-line-prefix"}}); // const lineContent = Decoration.mark({attributes: {class: "cm-output-line-content"}}); -function createWidgets(lines, blockAttributes, state) { +function createWidgets(lines, blockMetadata, state) { // Build the range set for output lines. const builder1 = new RangeSetBuilder(); // Add output line decorations @@ -24,23 +27,40 @@ function createWidgets(lines, blockAttributes, state) { // Build the range set for block attributes. const builder2 = new RangeSetBuilder(); // Add block attribute decorations - for (const {from, to, attributes} of blockAttributes) { + for (const {output, attributes} of blockMetadata) { // Apply decorations to each line in the block range - const startLine = state.doc.lineAt(from); - const endLine = state.doc.lineAt(to); + const startLine = state.doc.lineAt(output.from); + const endLine = state.doc.lineAt(output.to); + console.log("from:", output.from); + console.log("to:", output.to); + console.log("startLine:", startLine); + console.log("endLine:", endLine); - for (let lineNum = startLine.number; lineNum <= endLine.number; lineNum++) { - const line = state.doc.line(lineNum); - if (attributes.compact === true) { + if (attributes.compact === true) { + for (let lineNum = startLine.number; lineNum <= endLine.number; lineNum++) { + const line = state.doc.line(lineNum); builder2.add(line.from, line.from, compactLineDecoration); } } } const set2 = builder2.finish(); + const builder3 = new RangeSetBuilder(); + for (const {output} of blockMetadata) { + if (output === null) continue; + builder3.add(output.from, output.to, debugRedDecoration); + } + const set3 = builder3.finish(); + + const builder4 = new RangeSetBuilder(); + for (const {source} of blockMetadata) { + builder4.add(source.from, source.to, debugGreenDecoration); + } + const set4 = builder4.finish(); + // Range sets are required to be sorted. Fortunately, they provide a method // to merge multiple range sets into a single sorted range set. - return RangeSet.join([set1, set2]); + return RangeSet.join([set1, set2, set3, set4]); } export const outputDecoration = ViewPlugin.fromClass( @@ -54,16 +74,16 @@ export const outputDecoration = ViewPlugin.fromClass( /** @param {EditorView} view */ constructor(view) { const outputLines = view.state.field(outputLinesField); - const blockAttributes = view.state.field(blockAttributesField); - this.#decorations = createWidgets(outputLines, blockAttributes, view.state); + const blockMetadata = view.state.field(blockMetadataField); + this.#decorations = createWidgets(outputLines, blockMetadata, view.state); } /** @param {ViewUpdate} update */ update(update) { const newOutputLines = update.state.field(outputLinesField); - const newBlockAttributes = update.state.field(blockAttributesField); + const blockMetadata = update.state.field(blockMetadataField); // A possible optimization would be to only update the changed lines. - this.#decorations = createWidgets(newOutputLines, newBlockAttributes, update.state); + this.#decorations = createWidgets(newOutputLines, blockMetadata, update.state); } }, {decorations: (v) => v.decorations}, diff --git a/editor/index.css b/editor/index.css index 110964f..45579fb 100644 --- a/editor/index.css +++ b/editor/index.css @@ -147,6 +147,18 @@ line-height: 1; } + .cm-debug-mark { + &.red { + background-color: #e4002440; + } + &.green { + background-color: #009a5753; + } + &.blue { + background-color: #0088f653; + } + } + /* We can't see background color, which is conflict with selection background color. * So we use svg pattern to simulate the background color. */ diff --git a/editor/index.js b/editor/index.js index 2e9ab1c..704b3fe 100644 --- a/editor/index.js +++ b/editor/index.js @@ -11,7 +11,7 @@ import * as eslint from "eslint-linter-browserify"; import {createRuntime} from "../runtime/index.js"; import {outputDecoration} from "./decoration.js"; import {outputLines} from "./outputLines.js"; -import {blockAttributes, setBlockAttributesEffect} from "./blockAttributes.js"; +import {blockMetadata, blockMetadataEffect} from "./blockMetadata.ts"; // import {outputProtection} from "./protection.js"; import {dispatch as d3Dispatch} from "d3-dispatch"; import {controls} from "./controls/index.js"; @@ -69,7 +69,7 @@ export function createEditor(container, options) { ]), javascriptLanguage.data.of({autocomplete: rechoCompletion}), outputLines, - blockAttributes, + blockMetadata, outputDecoration, controls(runtimeRef), // Disable this for now, because it prevents copying/pasting the code. @@ -91,41 +91,12 @@ export function createEditor(container, options) { window.addEventListener("keyup", onKeyUp); } - function dispatch({changes, blockAttributes: blockAttrs}) { - // Map block attributes through the changes to get correct final positions - const effects = []; - - if (blockAttrs && blockAttrs.length > 0) { - // We need to map the block positions through the changes - // Create a simplified change set mapper - const sortedChanges = [...changes].sort((a, b) => a.from - b.from); - - const mapPos = (pos) => { - let mapped = pos; - for (const change of sortedChanges) { - if (change.from <= pos) { - const inserted = change.insert ? change.insert.length : 0; - const deleted = change.to ? change.to - change.from : 0; - mapped += inserted - deleted; - } - } - return mapped; - }; - - const mappedBlockAttrs = blockAttrs.map(({from, to, attributes}) => ({ - from: mapPos(from), - to: mapPos(to), - attributes, - })); - - effects.push(setBlockAttributesEffect.of(mappedBlockAttrs)); - } - + function dispatch({changes, effects}) { // Mark this transaction as from runtime so that it will not be filtered out. view.dispatch({ changes, effects, - annotations: [Transaction.remote.of("runtime")], + annotations: [Transaction.remote.of(true)], }); } diff --git a/lib/IntervalTree.ts b/lib/IntervalTree.ts new file mode 100644 index 0000000..82f199e --- /dev/null +++ b/lib/IntervalTree.ts @@ -0,0 +1,369 @@ +/** + * Represents an interval with a low and high endpoint. + */ +export interface Interval { + low: number; + high: number; +} + +/** + * Represents an interval with associated data. + */ +export type IntervalEntry = { + interval: Interval; + data: T; +}; + +/** + * Represents a node in the interval tree. + */ +class IntervalTreeNode { + interval: Interval; + data: T; + max: number; // Maximum high value in subtree + left: IntervalTreeNode | null = null; + right: IntervalTreeNode | null = null; + height: number = 1; + + constructor(interval: Interval, data: T) { + this.interval = interval; + this.data = data; + this.max = interval.high; + } +} + +/** + * A balanced interval tree implementation using AVL tree balancing. + * Supports efficient insertion, deletion, and overlap queries. + */ +export class IntervalTree { + private root: IntervalTreeNode | null = null; + private size: number = 0; + + /** + * Creates an IntervalTree from an array using a mapping function. + * @param items - The array of items to map + * @param mapper - Function that maps each item to an interval and data value + * @returns A new IntervalTree containing all mapped intervals + */ + static from(items: S[], mapper: (item: S, index: number) => IntervalEntry | null): IntervalTree { + const tree = new IntervalTree(); + for (let i = 0, n = items.length; i < n; i++) { + const item = items[i]; + const mapped = mapper(item, i); + if (mapped) tree.insert(mapped.interval, mapped.data); + } + return tree; + } + + /** + * Returns the number of intervals in the tree. + */ + get length(): number { + return this.size; + } + + /** + * Returns true if the tree is empty. + */ + isEmpty(): boolean { + return this.root === null; + } + + /** + * Inserts an interval with associated data into the tree. + */ + insert(interval: Interval, data: T): void { + if (interval.low > interval.high) { + throw new Error("Invalid interval: low must be less than or equal to high"); + } + this.root = this.insertNode(this.root, interval, data); + this.size++; + } + + private insertNode(node: IntervalTreeNode | null, interval: Interval, data: T): IntervalTreeNode { + // Standard BST insertion + if (node === null) { + return new IntervalTreeNode(interval, data); + } + + if (interval.low < node.interval.low) { + node.left = this.insertNode(node.left, interval, data); + } else { + node.right = this.insertNode(node.right, interval, data); + } + + // Update height and max + node.height = 1 + Math.max(this.getHeight(node.left), this.getHeight(node.right)); + node.max = Math.max(node.interval.high, Math.max(this.getMax(node.left), this.getMax(node.right))); + + // Balance the tree + return this.balance(node); + } + + /** + * Deletes an interval from the tree. + * Returns true if the interval was found and deleted, false otherwise. + */ + delete(interval: Interval): boolean { + const initialSize = this.size; + this.root = this.deleteNode(this.root, interval); + return this.size < initialSize; + } + + private deleteNode(node: IntervalTreeNode | null, interval: Interval): IntervalTreeNode | null { + if (node === null) { + return null; + } + + if (interval.low < node.interval.low) { + node.left = this.deleteNode(node.left, interval); + } else if (interval.low > node.interval.low) { + node.right = this.deleteNode(node.right, interval); + } else if (interval.high === node.interval.high) { + // Found the node to delete + this.size--; + + // Node with only one child or no child + if (node.left === null) { + return node.right; + } else if (node.right === null) { + return node.left; + } + + // Node with two children: get inorder successor + const successor = this.findMin(node.right); + node.interval = successor.interval; + node.data = successor.data; + node.right = this.deleteNode(node.right, successor.interval); + } else { + // Continue searching + node.right = this.deleteNode(node.right, interval); + } + + // Update height and max + node.height = 1 + Math.max(this.getHeight(node.left), this.getHeight(node.right)); + node.max = Math.max(node.interval.high, Math.max(this.getMax(node.left), this.getMax(node.right))); + + // Balance the tree + return this.balance(node); + } + + private findMin(node: IntervalTreeNode): IntervalTreeNode { + while (node.left !== null) { + node = node.left; + } + return node; + } + + /** + * Searches for all intervals that overlap with the given interval. + */ + search(interval: Interval): Array> { + const results: Array> = []; + this.searchNode(this.root, interval, results); + return results; + } + + private searchNode(node: IntervalTreeNode | null, interval: Interval, results: Array>): void { + if (node === null) { + return; + } + + // Check if intervals overlap + if (this.doOverlap(node.interval, interval)) { + results.push({interval: node.interval, data: node.data}); + } + + // If left child exists and its max >= interval.low, search left + if (node.left !== null && node.left.max >= interval.low) { + this.searchNode(node.left, interval, results); + } + + // Search right subtree if it can contain overlapping intervals + if (node.right !== null && node.interval.low <= interval.high) { + this.searchNode(node.right, interval, results); + } + } + + /** + * Finds any one interval that overlaps with the given interval. + * Returns null if no overlapping interval is found. + */ + findAny(interval: Interval): IntervalEntry | null { + return this.findAnyNode(this.root, interval); + } + + private findAnyNode(node: IntervalTreeNode | null, interval: Interval): IntervalEntry | null { + if (node === null) { + return null; + } + + // Check if current node overlaps + if (this.doOverlap(node.interval, interval)) { + return {interval: node.interval, data: node.data}; + } + + // If left child can contain overlapping interval, search left first + if (node.left !== null && node.left.max >= interval.low) { + return this.findAnyNode(node.left, interval); + } + + // Otherwise search right + return this.findAnyNode(node.right, interval); + } + + /** + * Finds the first interval that contains the given point. + * Returns null if no interval contains the point. + */ + contains(point: number): IntervalEntry | null { + return this.containsNode(this.root, point); + } + + private containsNode(node: IntervalTreeNode | null, point: number): IntervalEntry | null { + if (node === null) { + return null; + } + + // Check if current node contains the point + if (node.interval.low <= point && point <= node.interval.high) { + return {interval: node.interval, data: node.data}; + } + + // If left child exists and its max >= point, search left first + if (node.left !== null && node.left.max >= point) { + return this.containsNode(node.left, point); + } + + // Otherwise search right + return this.containsNode(node.right, point); + } + + /** + * Returns all intervals in the tree. + */ + toArray(): Array> { + const results: Array> = []; + this.inorderTraversal(this.root, results); + return results; + } + + private inorderTraversal(node: IntervalTreeNode | null, results: Array>): void { + if (node === null) { + return; + } + this.inorderTraversal(node.left, results); + results.push({interval: node.interval, data: node.data}); + this.inorderTraversal(node.right, results); + } + + /** + * Clears all intervals from the tree. + */ + clear(): void { + this.root = null; + this.size = 0; + } + + // AVL tree balancing methods + + private getHeight(node: IntervalTreeNode | null): number { + return node === null ? 0 : node.height; + } + + private getMax(node: IntervalTreeNode | null): number { + return node === null ? -Infinity : node.max; + } + + private getBalanceFactor(node: IntervalTreeNode): number { + return this.getHeight(node.left) - this.getHeight(node.right); + } + + private balance(node: IntervalTreeNode): IntervalTreeNode { + const balanceFactor = this.getBalanceFactor(node); + + // Left heavy + if (balanceFactor > 1) { + if (this.getBalanceFactor(node.left!) < 0) { + // Left-Right case + node.left = this.rotateLeft(node.left!); + } + // Left-Left case + return this.rotateRight(node); + } + + // Right heavy + if (balanceFactor < -1) { + if (this.getBalanceFactor(node.right!) > 0) { + // Right-Left case + node.right = this.rotateRight(node.right!); + } + // Right-Right case + return this.rotateLeft(node); + } + + return node; + } + + private rotateLeft(node: IntervalTreeNode): IntervalTreeNode { + const newRoot = node.right!; + node.right = newRoot.left; + newRoot.left = node; + + // Update heights + node.height = 1 + Math.max(this.getHeight(node.left), this.getHeight(node.right)); + newRoot.height = 1 + Math.max(this.getHeight(newRoot.left), this.getHeight(newRoot.right)); + + // Update max values + node.max = Math.max(node.interval.high, Math.max(this.getMax(node.left), this.getMax(node.right))); + newRoot.max = Math.max(newRoot.interval.high, Math.max(this.getMax(newRoot.left), this.getMax(newRoot.right))); + + return newRoot; + } + + private rotateRight(node: IntervalTreeNode): IntervalTreeNode { + const newRoot = node.left!; + node.left = newRoot.right; + newRoot.right = node; + + // Update heights + node.height = 1 + Math.max(this.getHeight(node.left), this.getHeight(node.right)); + newRoot.height = 1 + Math.max(this.getHeight(newRoot.left), this.getHeight(newRoot.right)); + + // Update max values + node.max = Math.max(node.interval.high, Math.max(this.getMax(node.left), this.getMax(node.right))); + newRoot.max = Math.max(newRoot.interval.high, Math.max(this.getMax(newRoot.left), this.getMax(newRoot.right))); + + return newRoot; + } + + private doOverlap(a: Interval, b: Interval): boolean { + return a.low <= b.high && b.low <= a.high; + } + + /** + * Returns true if the tree is balanced (for testing purposes). + */ + isBalanced(): boolean { + return this.checkBalance(this.root) !== -1; + } + + private checkBalance(node: IntervalTreeNode | null): number { + if (node === null) { + return 0; + } + + const leftHeight = this.checkBalance(node.left); + if (leftHeight === -1) return -1; + + const rightHeight = this.checkBalance(node.right); + if (rightHeight === -1) return -1; + + if (Math.abs(leftHeight - rightHeight) > 1) { + return -1; + } + + return Math.max(leftHeight, rightHeight) + 1; + } +} diff --git a/runtime/index.js b/runtime/index.js index 637306e..723038d 100644 --- a/runtime/index.js +++ b/runtime/index.js @@ -6,6 +6,8 @@ import {dispatch as d3Dispatch} from "d3-dispatch"; import * as stdlib from "./stdlib.js"; import {OUTPUT_MARK, ERROR_MARK} from "./constant.js"; import {Inspector} from "./inspect.js"; +import {blockMetadataEffect} from "../editor/blockMetadata.ts"; +import {IntervalTree} from "../lib/IntervalTree.ts"; const OUTPUT_PREFIX = `//${OUTPUT_MARK}`; @@ -95,9 +97,13 @@ export function createRuntime(initialCode) { const refresh = debounce((code) => { const changes = removeChanges(code); + const removedIntervals = IntervalTree.from(changes, ({from, to}, index) => + from === to ? null : {interval: {low: from, high: to - 1}, data: index}, + ); // Insert new outputs const nodes = Array.from(nodesByKey.values()).flat(Infinity); + const blocks = []; for (const node of nodes) { const start = node.start; const {values} = node.state; @@ -121,20 +127,28 @@ export function createRuntime(initialCode) { } const prefix = error ? ERROR_PREFIX : OUTPUT_PREFIX; const prefixed = addPrefix(output, prefix); - changes.push({from: start, insert: prefixed + "\n"}); + // Search for existing changes and update the inserted text if found. + const entry = removedIntervals.contains(start - 1); + let outputRange = null; + if (entry === null) { + changes.push({from: start, insert: prefixed + "\n"}); + } else { + const change = changes[entry.data]; + change.insert = prefixed + "\n"; + outputRange = {from: change.from, to: change.to}; + } + blocks.push({ + source: {from: node.start, to: node.end}, + output: outputRange, + attributes: node.state.attributes, + }); } } - // Collect block attributes - we need to map positions through the changes - const blockAttributes = nodes - .filter((node) => Object.keys(node.state.attributes).length > 0) - .map((node) => ({ - from: node.start, - to: node.end, - attributes: node.state.attributes, - })); + // Attach block positions and attributes as effects to the transaction. + const effects = [blockMetadataEffect.of(blocks)]; - dispatch(changes, blockAttributes); + dispatch(changes, effects); }, 0); function setCode(newCode) { @@ -145,8 +159,8 @@ export function createRuntime(initialCode) { isRunning = value; } - function dispatch(changes, blockAttributes = []) { - dispatcher.call("changes", null, {changes, blockAttributes}); + function dispatch(changes, effects = []) { + dispatcher.call("changes", null, {changes, effects}); } function onChanges(callback) { @@ -205,30 +219,45 @@ export function createRuntime(initialCode) { } } + /** + * Get the changes that remove the output lines from the code. + * @param {string} code The code to remove changes from. + * @returns {{from: number, to: number, insert: ""}[]} An array of changes. + */ function removeChanges(code) { - const changes = []; - - const oldOutputs = code - .split("\n") - .map((l, i) => [l, i]) - .filter(([l]) => l.startsWith(OUTPUT_PREFIX) || l.startsWith(ERROR_PREFIX)) - .map(([_, i]) => i); - - const lineOf = (i) => { - const lines = code.split("\n"); - const line = lines[i]; - const from = lines.slice(0, i).join("\n").length; - const to = from + line.length; - return {from, to}; - }; + function matchAt(index) { + return code.startsWith(OUTPUT_PREFIX, index) || code.startsWith(ERROR_PREFIX, index); + } - for (const i of oldOutputs) { - const line = lineOf(i); - const from = line.from; - const to = line.to + 1 > code.length ? line.to : line.to + 1; - changes.push({from, to, insert: ""}); + /** Line number ranges (left-closed and right-open) of lines that contain output or error. */ + const lineNumbers = matchAt(0) ? [{begin: 0, end: 1}] : []; + /** + * The index of the first character of each line. + * If the code ends with a newline, the last index is the length of the code. + */ + const lineStartIndices = [0]; + let nextNewlineIndex = code.indexOf("\n", 0); + while (0 <= nextNewlineIndex && nextNewlineIndex < code.length) { + lineStartIndices.push(nextNewlineIndex + 1); + if (matchAt(nextNewlineIndex + 1)) { + const lineNumber = lineStartIndices.length - 1; + if (lineNumbers.length > 0 && lineNumber === lineNumbers[lineNumbers.length - 1].end) { + // Extend the last line number range. + lineNumbers[lineNumbers.length - 1].end += 1; + } else { + // Append a new line number range. + lineNumbers.push({begin: lineNumber, end: lineNumber + 1}); + } + } + nextNewlineIndex = code.indexOf("\n", nextNewlineIndex + 1); } + const changes = lineNumbers.map(({begin, end}) => ({ + from: lineStartIndices[begin], + to: lineStartIndices[end], + insert: "", + })); + return changes; } @@ -332,6 +361,7 @@ export function createRuntime(initialCode) { { set: function (key, value) { state.attributes[key] = value; + return this; }, }, ); diff --git a/test/IntervalTree.spec.js b/test/IntervalTree.spec.js new file mode 100644 index 0000000..876c0a4 --- /dev/null +++ b/test/IntervalTree.spec.js @@ -0,0 +1,395 @@ +import {it, expect, describe, beforeEach} from "vitest"; +import {IntervalTree} from "../lib/IntervalTree.ts"; + +describe("IntervalTree", () => { + let tree; + + beforeEach(() => { + tree = new IntervalTree(); + }); + + describe("static from method", () => { + it("should create tree from array of objects with mapper", () => { + const events = [ + {name: "Event A", start: 10, end: 20}, + {name: "Event B", start: 15, end: 25}, + {name: "Event C", start: 30, end: 40}, + ]; + + const tree = IntervalTree.from(events, (event) => ({ + interval: {low: event.start, high: event.end}, + data: event.name, + })); + + expect(tree.length).toBe(3); + expect(tree.isBalanced()).toBe(true); + + const results = tree.search({low: 18, high: 22}); + expect(results.length).toBe(2); + expect(results.map((r) => r.data).sort()).toEqual(["Event A", "Event B"]); + }); + + it("should create tree from array of numbers", () => { + const numbers = [1, 2, 3, 4, 5]; + + const tree = IntervalTree.from(numbers, (num) => ({ + interval: {low: num, high: num + 10}, + data: num * 2, + })); + + expect(tree.length).toBe(5); + // Intervals: [1,11], [2,12], [3,13], [4,14], [5,15] + // Searching [12, 13] overlaps with [2,12], [3,13], [4,14], [5,15] + const results = tree.search({low: 12, high: 13}); + expect(results.map((r) => r.data).sort((a, b) => a - b)).toEqual([4, 6, 8, 10]); + }); + + it("should create empty tree from empty array", () => { + const tree = IntervalTree.from([], (item) => ({ + interval: {low: 0, high: 0}, + data: item, + })); + + expect(tree.isEmpty()).toBe(true); + expect(tree.length).toBe(0); + }); + + it("should handle complex data types", () => { + const tasks = [ + {id: 1, timeRange: [0, 100], priority: "high"}, + {id: 2, timeRange: [50, 150], priority: "medium"}, + {id: 3, timeRange: [120, 200], priority: "low"}, + ]; + + const tree = IntervalTree.from(tasks, (task) => ({ + interval: {low: task.timeRange[0], high: task.timeRange[1]}, + data: {id: task.id, priority: task.priority}, + })); + + expect(tree.length).toBe(3); + + // Intervals: [0,100], [50,150], [120,200] + // Searching [75, 125] overlaps with all three + const results = tree.search({low: 75, high: 125}); + expect(results.length).toBe(3); + expect(results.find((r) => r.data.id === 1)).toBeDefined(); + expect(results.find((r) => r.data.id === 2)).toBeDefined(); + expect(results.find((r) => r.data.id === 3)).toBeDefined(); + }); + }); + + describe("basic operations", () => { + it("should create an empty tree", () => { + expect(tree.isEmpty()).toBe(true); + expect(tree.length).toBe(0); + }); + + it("should insert intervals", () => { + tree.insert({low: 15, high: 20}, "data1"); + expect(tree.isEmpty()).toBe(false); + expect(tree.length).toBe(1); + + tree.insert({low: 10, high: 30}, "data2"); + expect(tree.length).toBe(2); + }); + + it("should reject invalid intervals", () => { + expect(() => tree.insert({low: 20, high: 10}, "data")).toThrow( + "Invalid interval: low must be less than or equal to high", + ); + }); + + it("should allow single-point intervals", () => { + tree.insert({low: 5, high: 5}, "point"); + expect(tree.length).toBe(1); + }); + + it("should delete intervals", () => { + tree.insert({low: 15, high: 20}, "data1"); + tree.insert({low: 10, high: 30}, "data2"); + tree.insert({low: 17, high: 19}, "data3"); + + const deleted = tree.delete({low: 10, high: 30}); + expect(deleted).toBe(true); + expect(tree.length).toBe(2); + + const notDeleted = tree.delete({low: 100, high: 200}); + expect(notDeleted).toBe(false); + expect(tree.length).toBe(2); + }); + + it("should clear the tree", () => { + tree.insert({low: 15, high: 20}, "data1"); + tree.insert({low: 10, high: 30}, "data2"); + tree.clear(); + expect(tree.isEmpty()).toBe(true); + expect(tree.length).toBe(0); + }); + }); + + describe("contains method", () => { + beforeEach(() => { + tree.insert({low: 15, high: 20}, "interval1"); + tree.insert({low: 10, high: 30}, "interval2"); + tree.insert({low: 17, high: 19}, "interval3"); + tree.insert({low: 5, high: 20}, "interval4"); + tree.insert({low: 12, high: 15}, "interval5"); + tree.insert({low: 30, high: 40}, "interval6"); + }); + + it("should find an interval containing a point", () => { + const result = tree.contains(18); + expect(result).not.toBeNull(); + expect(result.interval.low).toBeLessThanOrEqual(18); + expect(result.interval.high).toBeGreaterThanOrEqual(18); + }); + + it("should return null when no interval contains the point", () => { + const result = tree.contains(45); + expect(result).toBeNull(); + }); + + it("should find interval at lower boundary", () => { + const result = tree.contains(15); + expect(result).not.toBeNull(); + expect(result.interval.low).toBeLessThanOrEqual(15); + expect(result.interval.high).toBeGreaterThanOrEqual(15); + }); + + it("should find interval at upper boundary", () => { + const result = tree.contains(40); + expect(result).not.toBeNull(); + expect(result.data).toBe("interval6"); + }); + + it("should find single-point interval", () => { + tree.clear(); + tree.insert({low: 25, high: 25}, "point"); + const result = tree.contains(25); + expect(result).not.toBeNull(); + expect(result.data).toBe("point"); + }); + + it("should return null for point just outside intervals", () => { + tree.clear(); + tree.insert({low: 10, high: 20}, "range"); + expect(tree.contains(9)).toBeNull(); + expect(tree.contains(21)).toBeNull(); + }); + + it("should work with negative numbers", () => { + tree.clear(); + tree.insert({low: -100, high: -50}, "negative"); + tree.insert({low: -10, high: 10}, "crosses-zero"); + + const result1 = tree.contains(-75); + expect(result1).not.toBeNull(); + expect(result1.data).toBe("negative"); + + const result2 = tree.contains(0); + expect(result2).not.toBeNull(); + expect(result2.data).toBe("crosses-zero"); + }); + + it("should handle overlapping intervals efficiently", () => { + tree.clear(); + // Insert multiple overlapping intervals + tree.insert({low: 0, high: 100}, "large"); + tree.insert({low: 40, high: 60}, "medium"); + tree.insert({low: 48, high: 52}, "small"); + + // Should find at least one + const result = tree.contains(50); + expect(result).not.toBeNull(); + expect(result.interval.low).toBeLessThanOrEqual(50); + expect(result.interval.high).toBeGreaterThanOrEqual(50); + }); + }); + + describe("overlap detection", () => { + beforeEach(() => { + tree.insert({low: 15, high: 20}, "interval1"); + tree.insert({low: 10, high: 30}, "interval2"); + tree.insert({low: 17, high: 19}, "interval3"); + tree.insert({low: 5, high: 20}, "interval4"); + tree.insert({low: 12, high: 15}, "interval5"); + tree.insert({low: 30, high: 40}, "interval6"); + }); + + it("should find all overlapping intervals", () => { + const results = tree.search({low: 14, high: 16}); + expect(results.length).toBe(4); + + const dataValues = results.map((r) => r.data).sort(); + expect(dataValues).toEqual(["interval1", "interval2", "interval4", "interval5"]); + }); + + it("should find single overlapping interval", () => { + const result = tree.findAny({low: 35, high: 37}); + expect(result).not.toBeNull(); + expect(result.data).toBe("interval6"); + }); + + it("should return empty array when no overlaps exist", () => { + const results = tree.search({low: 41, high: 50}); + expect(results.length).toBe(0); + }); + + it("should return null when no single overlap exists", () => { + const result = tree.findAny({low: 41, high: 50}); + expect(result).toBeNull(); + }); + + it("should detect overlap with single-point intervals", () => { + tree.clear(); + tree.insert({low: 10, high: 10}, "point"); + tree.insert({low: 5, high: 15}, "range"); + + const results = tree.search({low: 10, high: 10}); + expect(results.length).toBe(2); + }); + + it("should detect edge overlaps", () => { + tree.clear(); + tree.insert({low: 10, high: 20}, "edge1"); + + // Overlaps at left edge + const leftEdge = tree.search({low: 5, high: 10}); + expect(leftEdge.length).toBe(1); + + // Overlaps at right edge + const rightEdge = tree.search({low: 20, high: 25}); + expect(rightEdge.length).toBe(1); + + // No overlap just outside + const noOverlap = tree.search({low: 21, high: 25}); + expect(noOverlap.length).toBe(0); + }); + }); + + describe("tree structure", () => { + it("should maintain balance after insertions", () => { + // Insert intervals in sorted order (worst case for unbalanced tree) + for (let i = 0; i < 100; i++) { + tree.insert({low: i, high: i + 5}, `data${i}`); + } + expect(tree.isBalanced()).toBe(true); + expect(tree.length).toBe(100); + }); + + it("should maintain balance after deletions", () => { + const intervals = []; + for (let i = 0; i < 50; i++) { + const interval = {low: i, high: i + 5}; + intervals.push(interval); + tree.insert(interval, `data${i}`); + } + + // Delete every other interval + for (let i = 0; i < 50; i += 2) { + tree.delete(intervals[i]); + } + + expect(tree.isBalanced()).toBe(true); + expect(tree.length).toBe(25); + }); + }); + + describe("toArray", () => { + it("should return all intervals in sorted order", () => { + tree.insert({low: 15, high: 20}, "data1"); + tree.insert({low: 10, high: 30}, "data2"); + tree.insert({low: 17, high: 19}, "data3"); + tree.insert({low: 5, high: 8}, "data4"); + + const array = tree.toArray(); + expect(array.length).toBe(4); + + // Check that intervals are sorted by low value + for (let i = 0; i < array.length - 1; i++) { + expect(array[i].interval.low).toBeLessThanOrEqual(array[i + 1].interval.low); + } + }); + + it("should return empty array for empty tree", () => { + const array = tree.toArray(); + expect(array).toEqual([]); + }); + }); + + describe("complex scenarios", () => { + it("should handle many overlapping intervals", () => { + // Create many overlapping intervals centered around [50, 60] + for (let i = 0; i < 20; i++) { + tree.insert({low: 45 + i, high: 55 + i}, `overlap${i}`); + } + + const results = tree.search({low: 50, high: 60}); + expect(results.length).toBeGreaterThan(10); + }); + + it("should handle intervals with large ranges", () => { + tree.insert({low: 0, high: 1000000}, "large"); + tree.insert({low: 500, high: 600}, "small"); + + const results = tree.search({low: 550, high: 560}); + expect(results.length).toBe(2); + }); + + it("should handle negative intervals", () => { + tree.insert({low: -100, high: -50}, "negative1"); + tree.insert({low: -75, high: -25}, "negative2"); + tree.insert({low: -10, high: 10}, "crosses-zero"); + + const results = tree.search({low: -60, high: -40}); + expect(results.length).toBe(2); + + const crossResults = tree.search({low: -5, high: 5}); + expect(crossResults.length).toBe(1); + expect(crossResults[0].data).toBe("crosses-zero"); + }); + + it("should work with different data types", () => { + const tree2 = new IntervalTree(); + + tree2.insert({low: 1, high: 5}, {name: "Alice", age: 30}); + tree2.insert({low: 3, high: 7}, {name: "Bob", age: 25}); + + const results = tree2.search({low: 4, high: 6}); + expect(results.length).toBe(2); + expect(results.find((r) => r.data.name === "Alice")).toBeDefined(); + expect(results.find((r) => r.data.name === "Bob")).toBeDefined(); + }); + }); + + describe("stress test", () => { + it("should handle large number of random intervals efficiently", () => { + const intervals = []; + + // Insert 1000 random intervals + for (let i = 0; i < 1000; i++) { + const low = Math.floor(Math.random() * 10000); + const high = low + Math.floor(Math.random() * 100) + 1; + const interval = {low, high}; + intervals.push(interval); + tree.insert(interval, `data${i}`); + } + + expect(tree.length).toBe(1000); + expect(tree.isBalanced()).toBe(true); + + // Perform random searches + for (let i = 0; i < 100; i++) { + const searchLow = Math.floor(Math.random() * 10000); + const searchHigh = searchLow + Math.floor(Math.random() * 100) + 1; + const results = tree.search({low: searchLow, high: searchHigh}); + + // Verify all results actually overlap + for (const result of results) { + const overlaps = result.interval.low <= searchHigh && searchLow <= result.interval.high; + expect(overlaps).toBe(true); + } + } + }); + }); +}); From 89fda22d11e52ad3373fb2c89bb7ae20b73198a1 Mon Sep 17 00:00:00 2001 From: Luyu Cheng <2239547+chengluyu@users.noreply.github.com> Date: Wed, 29 Oct 2025 02:13:48 +0800 Subject: [PATCH 3/6] Implement automatic block updates when the user changes --- editor/blockIndicator.ts | 82 +++++++++++ editor/blockMetadata.ts | 293 ++++++++++++++++++++++++++++++++++++++- editor/decoration.js | 9 +- editor/index.css | 39 ++++++ editor/index.js | 11 +- runtime/index.js | 28 ++-- 6 files changed, 440 insertions(+), 22 deletions(-) create mode 100644 editor/blockIndicator.ts diff --git a/editor/blockIndicator.ts b/editor/blockIndicator.ts new file mode 100644 index 0000000..7609ab3 --- /dev/null +++ b/editor/blockIndicator.ts @@ -0,0 +1,82 @@ +import {GutterMarker, gutter} from "@codemirror/view"; +import {BlockMetadata, blockMetadataField} from "./blockMetadata"; + +export class BlockIndicator extends GutterMarker { + constructor(private className: string) { + super(); + } + toDOM() { + const div = document.createElement("div"); + div.className = this.className; + return div; + } +} + +const indicatorMarkers = { + output: { + head: new BlockIndicator("cm-block-indicator output head"), + tail: new BlockIndicator("cm-block-indicator output tail"), + sole: new BlockIndicator("cm-block-indicator output head tail"), + body: new BlockIndicator("cm-block-indicator output"), + }, + source: { + head: new BlockIndicator("cm-block-indicator source head"), + tail: new BlockIndicator("cm-block-indicator source tail"), + sole: new BlockIndicator("cm-block-indicator source head tail"), + body: new BlockIndicator("cm-block-indicator source"), + }, + error: { + head: new BlockIndicator("cm-block-indicator error head"), + tail: new BlockIndicator("cm-block-indicator error tail"), + sole: new BlockIndicator("cm-block-indicator error head tail"), + body: new BlockIndicator("cm-block-indicator error"), + }, +}; + +export const blockIndicator = gutter({ + class: "cm-blockIndicators", + lineMarker(view, line) { + const blocks = view.state.field(blockMetadataField, false); + if (blocks === undefined) return null; + const index = findEnclosingBlock(blocks, line.from); + if (index === null) return null; + const currentLine = view.state.doc.lineAt(line.from).number; + const sourceFirstLine = view.state.doc.lineAt(blocks[index].source.from).number; + const group = blocks[index].error + ? indicatorMarkers.error + : currentLine < sourceFirstLine + ? indicatorMarkers.output + : indicatorMarkers.source; + const blockFirstLine = view.state.doc.lineAt(blocks[index].from).number; + const blockLastLine = view.state.doc.lineAt(blocks[index].to).number; + if (blockFirstLine === currentLine) { + return blockLastLine === currentLine ? group.sole : group.head; + } else if (blockLastLine === currentLine) { + return group.tail; + } else { + return group.body; + } + }, + initialSpacer() { + return indicatorMarkers.source.body; + }, +}); + +function findEnclosingBlock(blocks: BlockMetadata[], pos: number): number | null { + let left = 0; + let right = blocks.length - 1; + + while (left <= right) { + const middle = (left + right) >>> 1; + const pivot = blocks[middle]; + if (pos < pivot.from) { + right = middle - 1; + } else if (pos > pivot.to) { + left = middle + 1; + } else { + return middle; + } + } + + return null; +} diff --git a/editor/blockMetadata.ts b/editor/blockMetadata.ts index 2fd826d..5b2e380 100644 --- a/editor/blockMetadata.ts +++ b/editor/blockMetadata.ts @@ -1,11 +1,287 @@ -import {StateField, StateEffect} from "@codemirror/state"; +import {StateField, StateEffect, Transaction} from "@codemirror/state"; +import {syntaxTree} from "@codemirror/language"; +import {OUTPUT_MARK, ERROR_MARK} from "../runtime/constant.js"; +import {EditorState} from "@codemirror/state"; + +const OUTPUT_MARK_CODE_POINT = OUTPUT_MARK.codePointAt(0); +const ERROR_MARK_CODE_POINT = ERROR_MARK.codePointAt(0); + +type Range = {from: number; to: number}; + +export function BlockMetadata(output: Range | null, source: Range, attributes: Record = {}) { + return { + output, + source, + get from() { + return this.output?.from ?? this.source.from; + }, + get to() { + return this.source.to; + }, + attributes, + error: false, + }; +} + +/** + * Detect blocks in a given range by traversing the syntax tree. + * Similar to how runtime/index.js uses acorn to parse blocks, but adapted for CodeMirror. + */ +function rebuiltBlocksWithinRange(state: EditorState, from: number, to: number): BlockMetadata[] { + const blocks: BlockMetadata[] = []; + + // Collect all top-level statements and their preceding output/error comment lines + const statementRanges: Range[] = []; + const outputRanges = new Map(); // Map statement position to output range + + syntaxTree(state).iterate({ + from, + to, + enter: (node) => { + // Detect top-level statements (direct children of Script) + if (node.node.parent?.name === "Script") { + // Check if this is a statement (not a comment) + const isStatement = + node.name.includes("Statement") || + node.name.includes("Declaration") || + node.name === "ExportDeclaration" || + node.name === "ImportDeclaration" || + node.name === "Block"; + + if (isStatement) { + statementRanges.push({from: node.from, to: node.to}); + } + } + + // Detect output/error comment lines (top-level line comments) + if (node.name === "LineComment" && node.node.parent?.name === "Script") { + const line = state.doc.lineAt(node.from); + // Check if the line comment covers the entire line + if (line.from === node.from && line.to === node.to) { + const codePoint = line.text.codePointAt(2); + if (codePoint === OUTPUT_MARK_CODE_POINT || codePoint === ERROR_MARK_CODE_POINT) { + // Find consecutive output/error lines + let outputStart = line.from; + let outputEnd = line.to; + + // Look backwards for more output/error lines + let currentLineNum = line.number - 1; + while (currentLineNum >= 1) { + const prevLine = state.doc.line(currentLineNum); + const prevCodePoint = prevLine.text.codePointAt(2); + if ( + prevLine.text.startsWith("//") && + (prevCodePoint === OUTPUT_MARK_CODE_POINT || prevCodePoint === ERROR_MARK_CODE_POINT) + ) { + outputStart = prevLine.from; + currentLineNum--; + } else { + break; + } + } + + // Look forwards for more output/error lines + currentLineNum = line.number + 1; + const totalLines = state.doc.lines; + while (currentLineNum <= totalLines) { + const nextLine = state.doc.line(currentLineNum); + const nextCodePoint = nextLine.text.codePointAt(2); + if ( + nextLine.text.startsWith("//") && + (nextCodePoint === OUTPUT_MARK_CODE_POINT || nextCodePoint === ERROR_MARK_CODE_POINT) + ) { + outputEnd = nextLine.to; + currentLineNum++; + } else { + break; + } + } + + // Find the next statement after these output lines + // The output belongs to the statement immediately following it + let nextStatementLine = currentLineNum; + if (nextStatementLine <= totalLines) { + const nextStmtLine = state.doc.line(nextStatementLine); + // Store this output range to be associated with the next statement + outputRanges.set(nextStmtLine.from, {from: outputStart, to: outputEnd}); + } + } + } + } + }, + }); + + // Build block metadata from statements + for (const range of statementRanges) { + blocks.push(BlockMetadata(outputRanges.get(range.from) ?? null, range)); + } + + return blocks; +} + +function updateBlocks(blocks: BlockMetadata[], tr: Transaction): void { + console.group("updateBlocks"); + + console.log("Original blocks:", structuredClone(blocks)); + + /** + * Find the block that contains the given position. If such block does not + * exist, return the nearest block that is right before or after the given + * position. When no blocks are before and after the given position, return + * `null`. + * @param pos the position we want to find + * @param side `-1` - lower bound, `1` - upper bound + */ + function findNearestBlock(pos: number, side: -1 | 1): number | null { + let left = 0; + let right = blocks.length; + + console.log(`pos = ${pos}, side = ${side}`); + + loop: while (left < right) { + console.log(`Search range [${left}, ${right})`); + const middle = (left + right) >>> 1; + const pivot = blocks[middle]; + + const from = pivot.output?.from ?? pivot.source.from; + const to = pivot.source.to; + console.log(`Pivot: ${middle} (from = ${from}, to = ${to})`); + + done: { + if (pos < from) { + console.log("Should go left"); + // Go left and search range [left, middle + 1) + if (middle === left) { + // We cannot move left anymore. + break done; + } else { + right = middle; + continue loop; + } + } else if (to <= pos) { + console.log("Should go right"); + // Go right and search range [middle, right) + if (middle === left) { + // We cannot move right anymore. + break done; + } else { + left = middle; + continue loop; + } + } else { + return middle; + } + } + if (side < 0) { + return left; + } else { + return left === 0 ? null : left - 1; + } + } + + return null; + } + + // Collect all ranges that need to be rescanned + type ChangedRange = {oldFrom: number; oldTo: number; newFrom: number; newTo: number}; + const changedRanges: ChangedRange[] = []; + tr.changes.iterChangedRanges((oldFrom, oldTo, newFrom, newTo) => { + changedRanges.push({oldFrom, oldTo, newFrom, newTo}); + }); + + if (changedRanges.length === 0) { + console.log("No changes detected"); + console.groupEnd(); + return; + } + + const affectedBlocks = new Set(); + + // Process changed ranges one by one, because ranges are disjoint. + for (const {oldFrom, oldTo, newFrom, newTo} of changedRanges) { + console.groupCollapsed(`Range ${oldFrom}-${oldTo} -> ${newFrom}-${newTo}`); + + // Step 1: Find the blocks that are affected by the change. + + const leftmost = findNearestBlock(oldFrom, -1); + const rightmost = findNearestBlock(oldTo, 1); + + console.log(`Affected block range: ${leftmost}-${rightmost}`); + + if (leftmost === null || rightmost === null || leftmost > rightmost) { + // No blocks are affected by this change, so we can skip it. + console.groupEnd(); + continue; + } + + // Step 2: Rebuild affected blocks. + + if (leftmost === rightmost) { + // The change affects only one block. We special case this scenario since + // we can possibly reuse the existing block attributes if the changed + // content is still a single block. + const block = blocks[leftmost]; + + const newBlockFrom = tr.changes.mapPos(block.from, -1); + const newBlockTo = tr.changes.mapPos(block.to, 1); + + console.log(`Only one block is affected. Rebuilting from ${block.from} to ${block.to}...`); + const rebuiltBlocks = rebuiltBlocksWithinRange(tr.state, newBlockFrom, newBlockTo); + + console.log(`Rebuilt blocks:`, rebuiltBlocks); + + if (rebuiltBlocks.length === 1) { + const newBlock = rebuiltBlocks[0]; + newBlock.attributes = block.attributes; + affectedBlocks.add(newBlock); + blocks[leftmost] = newBlock; + } else { + blocks.splice(leftmost, 1, ...rebuiltBlocks); + } + affectedBlocks.add(block); + } else { + // Multiple blocks are affected. + const rebuiltBlocks = rebuiltBlocksWithinRange(tr.state, newFrom, newTo); + rebuiltBlocks.forEach((block) => affectedBlocks.add(block)); + blocks.splice(leftmost, rightmost - leftmost + 1, ...rebuiltBlocks); + } + + console.groupEnd(); + } + + // Step 3: Map the unaffected blocks to new positions; + for (let i = 0, n = blocks.length; i < n; i++) { + const block = blocks[i]; + // Skip affected blocks as they have been updated. + if (affectedBlocks.has(block)) continue; + + // Map unaffected blocks to new positions + block.output = block.output + ? { + from: tr.changes.mapPos(block.output.from, -1), + to: tr.changes.mapPos(block.output.to, 1), + } + : null; + block.source = { + from: tr.changes.mapPos(block.source.from, -1), + to: tr.changes.mapPos(block.source.to, 1), + }; + } + + console.log("Updated blocks:", blocks); + + console.groupEnd(); +} export const blockMetadataEffect = StateEffect.define(); -type BlockMetadata = { - output: {from: number; to: number} | null; - source: {from: number; to: number}; +export type BlockMetadata = { + output: Range | null; + source: Range; + readonly from: number; + readonly to: number; attributes: Record; + error: boolean; }; export const blockMetadataField = StateField.define({ @@ -25,12 +301,14 @@ export const blockMetadataField = StateField.define({ if (blocksFromEffect === null) { // If the block attributes effect is not present, then this transaction // is made by the user, we need to update the block attributes accroding - // to the latest syntax tree. TODO + // to the latest syntax tree. + updateBlocks(blocks, tr); return blocks; } else { // Otherwise, we need to update the block attributes according to the // metadata sent from the runtime. Most importantly, we need to translate // the position of each block after the changes has been made. + console.group("Updating blocks from the effect"); for (const block of blocksFromEffect) { if (block.output === null) { const from = tr.changes.mapPos(block.source.from, -1); @@ -45,10 +323,13 @@ export const blockMetadataField = StateField.define({ from: tr.changes.mapPos(block.source.from, 1), to: tr.changes.mapPos(block.source.to, 1), }; + console.log(`output: ${block.output?.from} - ${block.output?.to}`); + console.log(`source: ${block.source.from} - ${block.source.to}`); } + console.groupEnd(); return blocksFromEffect; } }, }); -export const blockMetadata = blockMetadataField.extension; +export const blockMetadataExtension = blockMetadataField.extension; diff --git a/editor/decoration.js b/editor/decoration.js index 9e4913a..6c7c0df 100644 --- a/editor/decoration.js +++ b/editor/decoration.js @@ -25,17 +25,15 @@ function createWidgets(lines, blockMetadata, state) { const set1 = builder1.finish(); // Build the range set for block attributes. + console.groupCollapsed("Decorations for block attributes"); const builder2 = new RangeSetBuilder(); // Add block attribute decorations for (const {output, attributes} of blockMetadata) { + if (output === null) continue; // Apply decorations to each line in the block range const startLine = state.doc.lineAt(output.from); const endLine = state.doc.lineAt(output.to); - console.log("from:", output.from); - console.log("to:", output.to); - console.log("startLine:", startLine); - console.log("endLine:", endLine); - + console.log(`Make lines from ${startLine.number} to ${endLine.number} compact`); if (attributes.compact === true) { for (let lineNum = startLine.number; lineNum <= endLine.number; lineNum++) { const line = state.doc.line(lineNum); @@ -44,6 +42,7 @@ function createWidgets(lines, blockMetadata, state) { } } const set2 = builder2.finish(); + console.groupEnd(); const builder3 = new RangeSetBuilder(); for (const {output} of blockMetadata) { diff --git a/editor/index.css b/editor/index.css index 45579fb..a69a03d 100644 --- a/editor/index.css +++ b/editor/index.css @@ -159,6 +159,45 @@ } } + .cm-blockIndicators { + padding-left: 0.25rem; + + --gap-between-blocks: 2px; + } + + .cm-gutterElement .cm-block-indicator { + width: 0.25rem; + height: 100%; + + &.output { + background: #72aa006e; + } + + &.source { + background: #1f180021; + } + + &.error { + background: #df2600d1; + } + + &.head { + height: calc(100% - var(--gap-between-blocks)); + /*border-top-left-radius: 0.25rem; + border-top-right-radius: 0.25rem;*/ + + &:not(.tail) { + transform: translate(0, var(--gap-between-blocks)); + } + } + + &.tail { + height: calc(100% - var(--gap-between-blocks)); + /*border-bottom-left-radius: 0.25rem; + border-bottom-right-radius: 0.25rem;*/ + } + } + /* We can't see background color, which is conflict with selection background color. * So we use svg pattern to simulate the background color. */ diff --git a/editor/index.js b/editor/index.js index 704b3fe..d2ab2a3 100644 --- a/editor/index.js +++ b/editor/index.js @@ -11,13 +11,15 @@ import * as eslint from "eslint-linter-browserify"; import {createRuntime} from "../runtime/index.js"; import {outputDecoration} from "./decoration.js"; import {outputLines} from "./outputLines.js"; -import {blockMetadata, blockMetadataEffect} from "./blockMetadata.ts"; +import {blockMetadataExtension, blockMetadataEffect} from "./blockMetadata.ts"; // import {outputProtection} from "./protection.js"; import {dispatch as d3Dispatch} from "d3-dispatch"; import {controls} from "./controls/index.js"; import {rechoCompletion} from "./completion.js"; import {docStringTag} from "./docStringTag.js"; import {commentLink} from "./commentLink.js"; +import {blockIndicator} from "./blockIndicator.ts"; +import {lineNumbers} from "@codemirror/view"; // @see https://github.com/UziTech/eslint-linter-browserify/blob/master/example/script.js // @see https://codemirror.net/examples/lint/ @@ -38,10 +40,13 @@ export function createEditor(container, options) { const dispatcher = d3Dispatch("userInput"); const runtimeRef = {current: null}; + const myBasicSetup = Array.from(basicSetup); + myBasicSetup.splice(2, 0, blockIndicator); + const state = EditorState.create({ doc: code, extensions: [ - basicSetup, + myBasicSetup, javascript(), githubLightInit({ styles: [ @@ -69,7 +74,7 @@ export function createEditor(container, options) { ]), javascriptLanguage.data.of({autocomplete: rechoCompletion}), outputLines, - blockMetadata, + blockMetadataExtension, outputDecoration, controls(runtimeRef), // Disable this for now, because it prevents copying/pasting the code. diff --git a/runtime/index.js b/runtime/index.js index 723038d..d8f21b7 100644 --- a/runtime/index.js +++ b/runtime/index.js @@ -6,7 +6,7 @@ import {dispatch as d3Dispatch} from "d3-dispatch"; import * as stdlib from "./stdlib.js"; import {OUTPUT_MARK, ERROR_MARK} from "./constant.js"; import {Inspector} from "./inspect.js"; -import {blockMetadataEffect} from "../editor/blockMetadata.ts"; +import {BlockMetadata, blockMetadataEffect} from "../editor/blockMetadata.ts"; import {IntervalTree} from "../lib/IntervalTree.ts"; const OUTPUT_PREFIX = `//${OUTPUT_MARK}`; @@ -107,9 +107,10 @@ export function createRuntime(initialCode) { for (const node of nodes) { const start = node.start; const {values} = node.state; + let outputRange = null; + let error = false; if (values.length) { let output = ""; - let error = false; for (let i = 0; i < values.length; i++) { const line = values[i]; const n = line.length; @@ -129,7 +130,6 @@ export function createRuntime(initialCode) { const prefixed = addPrefix(output, prefix); // Search for existing changes and update the inserted text if found. const entry = removedIntervals.contains(start - 1); - let outputRange = null; if (entry === null) { changes.push({from: start, insert: prefixed + "\n"}); } else { @@ -137,14 +137,17 @@ export function createRuntime(initialCode) { change.insert = prefixed + "\n"; outputRange = {from: change.from, to: change.to}; } - blocks.push({ - source: {from: node.start, to: node.end}, - output: outputRange, - attributes: node.state.attributes, - }); } + // Add this block to the block metadata array. + const block = BlockMetadata(outputRange, {from: node.start, to: node.end}, node.state.attributes); + block.error = error; + blocks.push(block); } + blocks.sort((a, b) => a.from - b.from); + + console.log(blocks); + // Attach block positions and attributes as effects to the transaction. const effects = [blockMetadataEffect.of(blocks)]; @@ -195,6 +198,9 @@ export function createRuntime(initialCode) { function split(code) { try { + // The `parse` call here is actually unnecessary. Parsing the entire code + // is quite expensive. If we can perform the splitting operation through + // the editor's syntax tree, we can save the parsing here. return parse(code, {ecmaVersion: "latest", sourceType: "module"}).body; } catch (error) { console.error(error); @@ -282,6 +288,12 @@ export function createRuntime(initialCode) { const nodes = split(code); if (!nodes) return; + console.group("rerun"); + for (const node of nodes) { + console.log(`Node ${node.type} (${node.start}-${node.end})`); + } + console.groupEnd(); + for (const node of nodes) { const cell = code.slice(node.start, node.end); const transpiled = transpile(cell); From 7cc57c23729e3020456396318ffec7f7f92b30e2 Mon Sep 17 00:00:00 2001 From: Luyu Cheng <2239547+chengluyu@users.noreply.github.com> Date: Wed, 29 Oct 2025 15:00:11 +0800 Subject: [PATCH 4/6] Fix failed tests due to changes in `onChanges` --- test/snapshpts.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/snapshpts.spec.js b/test/snapshpts.spec.js index 1157c51..dd605d4 100644 --- a/test/snapshpts.spec.js +++ b/test/snapshpts.spec.js @@ -12,7 +12,7 @@ describe("snapshots", () => { console.error = () => {}; try { const runtime = createRuntime(state.doc.toString()); - runtime.onChanges((changes) => (state = state.update({changes}).state)); + runtime.onChanges((specs) => (state = state.update(specs).state)); runtime.run(); await new Promise((resolve) => setTimeout(resolve, 100)); } catch (error) {} From ddb5cd5cd9adae48d82dd875ed5619333d0df3ef Mon Sep 17 00:00:00 2001 From: Luyu Cheng <2239547+chengluyu@users.noreply.github.com> Date: Thu, 30 Oct 2025 01:18:23 +0800 Subject: [PATCH 5/6] Add the transaction viewer to the test page --- editor/index.js | 3 +- test/index.css | 40 +++ test/index.html | 2 +- test/main.js | 30 ++- test/transactionViewer.css | 305 +++++++++++++++++++++++ test/transactionViewer.js | 496 +++++++++++++++++++++++++++++++++++++ 6 files changed, 871 insertions(+), 5 deletions(-) create mode 100644 test/transactionViewer.css create mode 100644 test/transactionViewer.js diff --git a/editor/index.js b/editor/index.js index d2ab2a3..cc998ac 100644 --- a/editor/index.js +++ b/editor/index.js @@ -36,7 +36,7 @@ const eslintConfig = { }; export function createEditor(container, options) { - const {code, onError} = options; + const {code, onError, extensions = []} = options; const dispatcher = d3Dispatch("userInput"); const runtimeRef = {current: null}; @@ -82,6 +82,7 @@ export function createEditor(container, options) { docStringTag, commentLink, linter(esLint(new eslint.Linter(), eslintConfig)), + ...extensions, ], }); diff --git a/test/index.css b/test/index.css index 99016db..1cf70b0 100644 --- a/test/index.css +++ b/test/index.css @@ -1 +1,41 @@ @import "../editor/index.css"; + +body { + font-family: + system-ui, + -apple-system, + BlinkMacSystemFont, + "Segoe UI", + Roboto, + Oxygen, + Ubuntu, + Cantarell, + "Open Sans", + "Helvetica Neue", + sans-serif; + font-size: 16px; + + margin: 0; + padding: 0.5rem; + box-sizing: border-box; + display: flex; + flex-direction: row; + gap: 0.5rem; + height: 100vh; + width: 100vw; + + main { + flex: 1; + background: #55550003; + border: 1px solid #19130029; + padding: 0.75rem; + } + + aside { + width: 25rem; + padding: 0.75rem; + background: #25250007; + border: 1px solid #19130029; + overflow-y: auto; + } +} diff --git a/test/index.html b/test/index.html index 87fca19..3261143 100644 --- a/test/index.html +++ b/test/index.html @@ -5,9 +5,9 @@ Recho (Test) + -
diff --git a/test/main.js b/test/main.js index f0b60cf..98932dd 100644 --- a/test/main.js +++ b/test/main.js @@ -1,5 +1,15 @@ import * as jsTests from "./js/index.js"; import {createEditor} from "../editor/index.js"; +import {createTransactionViewer} from "./transactionViewer.js"; + +// The main and side panels +const mainPanel = document.createElement("main"); +mainPanel.id = "main-panel"; +document.body.append(mainPanel); + +const sidePanels = document.createElement("aside"); +sidePanels.id = "side-panels"; +document.body.append(sidePanels); // Select const select = createSelect(() => { @@ -9,26 +19,40 @@ const select = createSelect(() => { }); const options = Object.keys(jsTests).map(createOption); select.append(...options); -document.body.append(select); +mainPanel.append(select); const container = document.createElement("div"); container.id = "container"; -document.body.append(container); +mainPanel.append(container); // Init app name. const initialValue = new URL(location).searchParams.get("name"); if (jsTests[initialValue]) select.value = initialValue; let preEditor = null; +let transactionViewer = null; render(); async function render() { container.innerHTML = ""; if (preEditor) preEditor.destroy(); + if (transactionViewer) transactionViewer.destroy(); + + // Clear and reset side panels + sidePanels.innerHTML = ""; + + // Create transaction viewer + transactionViewer = createTransactionViewer(sidePanels); + const editorContainer = document.createElement("div"); const code = jsTests[select.value]; - const editor = createEditor(editorContainer, {code}); + const editor = createEditor(editorContainer, { + code, + extensions: [transactionViewer.plugin], + }); editor.run(); + preEditor = editor; + const runButton = document.createElement("button"); runButton.textContent = "Run"; runButton.onclick = () => editor.run(); diff --git a/test/transactionViewer.css b/test/transactionViewer.css new file mode 100644 index 0000000..23a9443 --- /dev/null +++ b/test/transactionViewer.css @@ -0,0 +1,305 @@ +/* Transaction Viewer Styles */ +.transaction-viewer { + font-size: 14px; + + display: flex; + flex-direction: column; + height: 100%; + + h3 { + margin: 0 0 0.75rem 0; + font-size: 1.1em; + font-weight: 600; + } +} + +.transaction-controls { + display: flex; + gap: 0.5rem; + align-items: center; + margin-bottom: 0.75rem; + padding-bottom: 0.75rem; + border-bottom: 1px solid #19130029; + + button { + padding: 0.25rem 0.5rem; + font-size: 12px; + border: 1px solid #19130029; + background: white; + border-radius: 3px; + cursor: pointer; + + &:hover { + background: #f6f6f6; + } + } + + label { + display: flex; + align-items: center; + gap: 0.25rem; + font-size: 12px; + cursor: pointer; + } +} + +.transaction-list-scrollable { + flex: 1; + min-height: 0; + overflow-y: auto; +} + +.transaction-list { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.no-transactions { + color: #666; + font-style: italic; + text-align: center; + padding: 2rem 0; +} + +.transaction-item { + border: 1px solid #d0d7de; + border-radius: 6px; + background: white; + padding: 0; + transition: all 0.2s; + + &[open] { + border-color: #8b949e; + } + + &.transaction-group { + border-color: #9a6dd7; + background: #faf8ff; + + &[open] { + border-color: #7c3aed; + } + + summary { + background: #f3e8ff; + + &:hover { + background: #e9d5ff; + } + } + } + + summary { + padding: 0.5rem; + cursor: pointer; + font-weight: 500; + font-family: ui-monospace, monospace; + font-size: 12px; + user-select: none; + background: #f6f8fa; + border-radius: 5px; + display: flex; + justify-content: space-between; + align-items: center; + gap: 0.5rem; + + &:hover { + background: #eaeef2; + } + } + + .tr-summary-left { + flex: 1; + min-width: 0; + } + + .tr-summary-right { + flex-shrink: 0; + color: #6e7781; + font-size: 11px; + } + + &.user-transaction summary { + background: #dff6dd; + + &:hover { + background: #c8f0c5; + } + } + + &.remote-transaction summary { + background: #fff8c5; + + &:hover { + background: #fff3b0; + } + } + + &.doc-changed summary { + font-weight: 600; + } +} + +.tr-details { + padding: 0.75rem; + font-size: 12px; + line-height: 1.5; +} + +.tr-field { + margin-bottom: 0.5rem; + + strong { + color: #1f2328; + } +} + +.tr-change { + margin-left: 1rem; + margin-bottom: 0.5rem; + padding: 0.5rem; + background: #f6f8fa; + border-radius: 4px; + font-size: 11px; + + code { + background: #ffffff; + padding: 0.125rem 0.25rem; + border-radius: 3px; + font-family: ui-monospace, monospace; + border: 1px solid #d0d7de; + } +} + +.deleted { + color: #cf222e; + margin-top: 0.25rem; +} + +.inserted { + color: #1a7f37; + margin-top: 0.25rem; +} + +.tr-annotation { + margin-left: 1rem; + padding: 0.25rem 0.5rem; + background: #dff6ff; + border-left: 3px solid #0969da; + font-family: ui-monospace, monospace; + font-size: 11px; + margin-bottom: 0.25rem; + border-radius: 3px; +} + +.tr-effect { + margin-left: 1rem; + padding: 0.25rem 0.5rem; + background: #fbefff; + border-left: 3px solid #8250df; + font-family: ui-monospace, monospace; + font-size: 11px; + margin-bottom: 0.25rem; + border-radius: 3px; +} + +.tr-selection { + margin-left: 1rem; + padding: 0.25rem 0.5rem; + background: #fff8c5; + border-left: 3px solid #bf8700; + font-family: ui-monospace, monospace; + font-size: 11px; + margin-bottom: 0.25rem; + border-radius: 3px; +} + +.tr-property { + margin-left: 1rem; + padding: 0.25rem 0.5rem; + background: #f6f8fa; + border-left: 3px solid #6e7781; + font-family: ui-monospace, monospace; + font-size: 11px; + margin-bottom: 0.25rem; + border-radius: 3px; +} + +.tr-effect-block-metadata { + background: #f3e8ff; + border-left-color: #a855f7; + padding: 0.5rem; +} + +.tr-effect-title { + font-weight: 600; + margin-bottom: 0.5rem; + color: #7c3aed; +} + +.tr-block-metadata { + margin-left: 0.5rem; + margin-top: 0.5rem; + padding: 0.5rem; + background: white; + border: 1px solid #e9d5ff; + border-radius: 3px; +} + +.tr-block-header { + font-weight: 600; + margin-bottom: 0.25rem; + color: #6b21a8; +} + +.tr-block-detail { + font-size: 11px; + margin-left: 0.5rem; + margin-bottom: 0.125rem; + color: #4b5563; +} + +.tr-block-error { + color: #dc2626; + font-weight: 600; +} + +.tr-grouped-list { + display: flex; + flex-direction: column; + gap: 0.25rem; +} + +.tr-grouped-item { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.375rem 0.5rem; + background: white; + border: 1px solid #e9d5ff; + border-radius: 4px; + font-size: 11px; + font-family: ui-monospace, monospace; +} + +.tr-grouped-index { + font-weight: 600; + color: #7c3aed; + min-width: 2.5rem; +} + +.tr-grouped-selection { + flex: 1; + color: #4b5563; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.tr-grouped-time { + color: #9ca3af; + font-size: 10px; + flex-shrink: 0; +} diff --git a/test/transactionViewer.js b/test/transactionViewer.js new file mode 100644 index 0000000..b7447e7 --- /dev/null +++ b/test/transactionViewer.js @@ -0,0 +1,496 @@ +import {ViewPlugin} from "@codemirror/view"; +import {Transaction} from "@codemirror/state"; +import {blockMetadataEffect} from "../editor/blockMetadata.ts"; + +// Maximum number of transactions to keep in history +const MAX_HISTORY = 100; + +/** + * Creates a transaction tracker plugin and UI viewer + */ +export function createTransactionViewer(container) { + const transactions = []; + const listeners = new Set(); + let nextIndex = 0; // Continuous index counter + + // Notify all listeners when transactions update + function notifyListeners() { + listeners.forEach((fn) => fn(transactions)); + } + + // Create the ViewPlugin to track transactions + const plugin = ViewPlugin.fromClass( + class { + constructor(view) { + // Capture initial state as transaction 0 + const initialTr = { + index: nextIndex++, + docChanged: false, + changes: [], + annotations: {}, + effects: [], + selection: view.state.selection.ranges.map((r) => ({ + from: r.from, + to: r.to, + anchor: r.anchor, + head: r.head, + })), + timestamp: Date.now(), + }; + transactions.push(initialTr); + notifyListeners(); + } + + update(update) { + // Process each transaction in the update + update.transactions.forEach((tr, idx) => { + const transactionData = extractTransactionData(tr, nextIndex++); + + // Add to history + transactions.push(transactionData); + + // Keep only the last MAX_HISTORY transactions + if (transactions.length > MAX_HISTORY) { + transactions.shift(); + } + }); + + if (update.transactions.length > 0) { + notifyListeners(); + } + } + }, + ); + + // Extract data from a transaction + function extractTransactionData(tr, index) { + const data = { + index, + docChanged: tr.docChanged, + changes: [], + annotations: {}, + effects: [], + selection: tr.state.selection.ranges.map((r) => ({ + from: r.from, + to: r.to, + anchor: r.anchor, + head: r.head, + })), + scrollIntoView: tr.scrollIntoView, + filter: tr.filter, + sequential: tr.sequential, + timestamp: Date.now(), + }; + + // Extract changes with line/column information + // Use startState for from/to positions (before the change) + tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => { + const fromLine = tr.startState.doc.lineAt(fromA); + const toLine = tr.startState.doc.lineAt(toA); + + data.changes.push({ + from: fromA, + to: toA, + fromLine: fromLine.number, + fromCol: fromA - fromLine.from, + toLine: toLine.number, + toCol: toA - toLine.from, + insert: inserted.toString(), + }); + }); + + // Extract annotations + const userEvent = tr.annotation(Transaction.userEvent); + if (userEvent !== undefined) { + data.annotations.userEvent = userEvent; + } + + const remote = tr.annotation(Transaction.remote); + if (remote !== undefined) { + data.annotations.remote = remote; + } + + // Check for other common annotations + const addToHistory = tr.annotation(Transaction.addToHistory); + if (addToHistory !== undefined) { + data.annotations.addToHistory = addToHistory; + } + + // Extract effects + for (const effect of tr.effects) { + const effectData = { + value: effect.value, + type: "StateEffect", + }; + + // Check if this is a blockMetadataEffect + if (effect.is(blockMetadataEffect)) { + effectData.type = "blockMetadataEffect"; + effectData.blockMetadata = effect.value; + } + + data.effects.push(effectData); + } + + return data; + } + + // Create the UI + const viewerElement = document.createElement("div"); + viewerElement.className = "transaction-viewer"; + viewerElement.innerHTML = ` +

Transactions

+
+ + +
+
+
+
+ `; + + const listElement = viewerElement.querySelector(".transaction-list"); + const clearButton = viewerElement.querySelector("#clear-transactions"); + const autoScrollCheckbox = viewerElement.querySelector("#auto-scroll"); + + clearButton.onclick = () => { + transactions.length = 0; + nextIndex = 0; // Reset the index counter + renderTransactions(); + }; + + function renderTransactions() { + listElement.innerHTML = ""; + + if (transactions.length === 0) { + listElement.innerHTML = '
No transactions yet
'; + return; + } + + // Group transactions - group consecutive selection transactions + const groups = []; + let currentGroup = null; + + // Process in reverse order (newest first) + for (let i = transactions.length - 1; i >= 0; i--) { + const tr = transactions[i]; + const isSelection = tr.annotations.userEvent === "select" || tr.annotations.userEvent === "select.pointer"; + + if (isSelection) { + if (currentGroup && currentGroup.type === "selection") { + // Add to existing selection group + currentGroup.transactions.push(tr); + } else { + // Start a new selection group + currentGroup = { + type: "selection", + transactions: [tr], + }; + groups.push(currentGroup); + } + } else { + // Non-selection transaction - add as individual + groups.push({ + type: "individual", + transaction: tr, + }); + currentGroup = null; + } + } + + // Render groups + for (const group of groups) { + if (group.type === "individual") { + const item = createTransactionItem(group.transaction); + listElement.appendChild(item); + } else { + const groupItem = createSelectionGroupItem(group.transactions); + listElement.appendChild(groupItem); + } + } + + // Auto-scroll to top (latest transaction) + if (autoScrollCheckbox.checked) { + listElement.scrollTop = 0; + } + } + + /** + * + * @param {import("@codemirror/state").TransactionSpec} tr + * @returns + */ + function createSelectionGroupItem(transactions) { + const item = document.createElement("details"); + item.className = "transaction-item transaction-group"; + + const count = transactions.length; + const firstTr = transactions[0]; + const lastTr = transactions[transactions.length - 1]; + + // Format timestamps + const firstTime = new Date(firstTr.timestamp); + const lastTime = new Date(lastTr.timestamp); + const firstTimeStr = + firstTime.toLocaleTimeString("en-US", { + hour12: false, + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) + + "." + + firstTime.getMilliseconds().toString().padStart(3, "0"); + const lastTimeStr = + lastTime.toLocaleTimeString("en-US", { + hour12: false, + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) + + "." + + lastTime.getMilliseconds().toString().padStart(3, "0"); + + const summaryLeft = `#${lastTr.index}-${firstTr.index} [select] (${count} transactions)`; + const summaryRight = `${lastTimeStr} - ${firstTimeStr}`; + + // Create list of individual transactions + const transactionsList = transactions + .map((tr) => { + const time = new Date(tr.timestamp); + const timeStr = + time.toLocaleTimeString("en-US", { + hour12: false, + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) + + "." + + time.getMilliseconds().toString().padStart(3, "0"); + + const selectionInfo = tr.selection + .map((range, idx) => { + const isCursor = range.from === range.to; + return isCursor ? `cursor at ${range.from}` : `${range.from}-${range.to}`; + }) + .join(", "); + + return ` +
+ #${tr.index} + ${selectionInfo} + ${timeStr} +
+ `; + }) + .join(""); + + item.innerHTML = ` + + ${summaryLeft} + ${summaryRight} + +
+
+ ${transactionsList} +
+
+ `; + + return item; + } + + function createTransactionItem(tr) { + const item = document.createElement("details"); + item.className = "transaction-item"; + + // Add classes based on transaction type + if (tr.annotations.userEvent) { + item.classList.add("user-transaction"); + } + if (tr.annotations.remote) { + item.classList.add("remote-transaction"); + } + if (tr.docChanged) { + item.classList.add("doc-changed"); + } + + // Format timestamp as HH:MM:SS.mmm + const time = new Date(tr.timestamp); + const timeStr = + time.toLocaleTimeString("en-US", { + hour12: false, + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) + + "." + + time.getMilliseconds().toString().padStart(3, "0"); + + let summaryLeft = `#${tr.index}`; + if (tr.annotations.userEvent) { + summaryLeft += ` [${tr.annotations.userEvent}]`; + } else if (tr.annotations.remote) { + summaryLeft += ` [remote: ${JSON.stringify(tr.annotations.remote)}]`; + } + if (tr.docChanged) { + summaryLeft += ` 📝`; + } + + const details = []; + + // Document changed + details.push(`
Doc Changed: ${tr.docChanged}
`); + + // Changes + if (tr.changes.length > 0) { + details.push(`
Changes:
`); + tr.changes.forEach((change, idx) => { + const deleted = change.to - change.from; + const inserted = change.insert.length; + const samePos = change.from === change.to; + const sameLine = change.fromLine === change.toLine; + + let posInfo = `pos ${change.from}-${change.to}`; + if (sameLine) { + posInfo += ` (L${change.fromLine}:${change.fromCol}-${change.toCol})`; + } else { + posInfo += ` (L${change.fromLine}:${change.fromCol} to L${change.toLine}:${change.toCol})`; + } + + details.push(` +
+
Change ${idx + 1}: ${posInfo}
+ ${deleted > 0 ? `
Deleted ${deleted} chars
` : ""} + ${inserted > 0 ? `
Inserted: ${escapeHtml(change.insert)}
` : ""} +
+ `); + }); + } else { + details.push(`
Changes: none
`); + } + + // Annotations + if (Object.keys(tr.annotations).length > 0) { + details.push(`
Annotations:
`); + for (const [key, value] of Object.entries(tr.annotations)) { + details.push(`
${key}: ${JSON.stringify(value)}
`); + } + } else { + details.push(`
Annotations: none
`); + } + + // Effects + if (Array.isArray(tr.effects) && tr.effects.length > 0) { + details.push(`
Effects: ${tr.effects.length}
`); + tr.effects.forEach((effect, idx) => { + if (effect.type === "blockMetadataEffect" && effect.blockMetadata) { + // Special handling for blockMetadataEffect + details.push(` + + `); + } else { + // Generic effect display + details.push(` +
+ Effect ${idx + 1} (${effect.type}): ${JSON.stringify(effect.value).substring(0, 100)} +
+ `); + } + }); + } else { + details.push(`
Effects: none
`); + } + + // Selection + details.push(`
Selection:
`); + tr.selection.forEach((range, idx) => { + const isCursor = range.from === range.to; + details.push(` +
+ Range ${idx + 1}: ${isCursor ? `cursor at ${range.from}` : `${range.from}-${range.to}`} + ${!isCursor ? `(anchor: ${range.anchor}, head: ${range.head})` : ""} +
+ `); + }); + + // Additional transaction properties + const additionalProps = []; + if (tr.scrollIntoView !== undefined) { + additionalProps.push(`scrollIntoView: ${tr.scrollIntoView}`); + } + if (tr.filter !== undefined) { + additionalProps.push(`filter: ${tr.filter}`); + } + if (tr.sequential !== undefined) { + additionalProps.push(`sequential: ${tr.sequential}`); + } + + if (additionalProps.length > 0) { + details.push(`
Other Properties:
`); + additionalProps.forEach((prop) => { + details.push(`
${prop}
`); + }); + } + + item.innerHTML = ` + + ${summaryLeft} + ${timeStr} + +
+ ${details.join("")} +
+ `; + + return item; + } + + function escapeHtml(text) { + const div = document.createElement("div"); + div.textContent = text; + return div.innerHTML; + } + + // Listen for transaction updates + listeners.add(renderTransactions); + + // Initial render + renderTransactions(); + + // Append to container + container.appendChild(viewerElement); + + return { + plugin, + destroy: () => { + listeners.clear(); + viewerElement.remove(); + }, + }; +} From f3a2202b2db69264ff345858feb8629924306995 Mon Sep 17 00:00:00 2001 From: Luyu Cheng <2239547+chengluyu@users.noreply.github.com> Date: Fri, 14 Nov 2025 15:12:14 +0800 Subject: [PATCH 6/6] Implement the playground using React --- package.json | 2 + pnpm-lock.yaml | 380 ++++++++++++++++++++- test/components/App.tsx | 50 +++ test/components/Editor.tsx | 129 +++++++ test/components/TestSelector.tsx | 30 ++ test/components/TransactionViewer.tsx | 471 ++++++++++++++++++++++++++ test/index.html | 5 +- test/main.tsx | 18 + test/store.ts | 61 ++++ test/styles.css | 41 +++ vite.config.js | 2 + 11 files changed, 1182 insertions(+), 7 deletions(-) create mode 100644 test/components/App.tsx create mode 100644 test/components/Editor.tsx create mode 100644 test/components/TestSelector.tsx create mode 100644 test/components/TransactionViewer.tsx create mode 100644 test/main.tsx create mode 100644 test/store.ts create mode 100644 test/styles.css diff --git a/package.json b/package.json index d590b79..29ecad5 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ }, "devDependencies": { "@tailwindcss/postcss": "^4.1.14", + "@vitejs/plugin-react": "^4.3.1", "clsx": "^2.1.1", "eslint": "^9.37.0", "eslint-config-prettier": "^10.1.8", @@ -77,6 +78,7 @@ "d3-require": "^1.3.0", "eslint-linter-browserify": "^9.37.0", "friendly-words": "^1.3.1", + "jotai": "^2.10.3", "next": "^15.5.6", "nstr": "^0.1.3", "object-inspect": "^1.13.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d53fa13..2dbdf11 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -80,9 +80,12 @@ importers: friendly-words: specifier: ^1.3.1 version: 1.3.1 + jotai: + specifier: ^2.10.3 + version: 2.15.1(@babel/core@7.28.5)(@babel/template@7.27.2)(react@19.2.0) next: specifier: ^15.5.6 - version: 15.5.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0) + version: 15.5.6(@babel/core@7.28.5)(react-dom@19.2.0(react@19.2.0))(react@19.2.0) nstr: specifier: ^0.1.3 version: 0.1.3 @@ -108,6 +111,9 @@ importers: '@tailwindcss/postcss': specifier: ^4.1.14 version: 4.1.14 + '@vitejs/plugin-react': + specifier: ^4.3.1 + version: 4.7.0(vite@7.1.10(jiti@2.6.1)(lightningcss@1.30.1)) clsx: specifier: ^2.1.1 version: 2.1.1 @@ -160,10 +166,93 @@ packages: '@asamuzakjp/css-color@3.2.0': resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==} + '@babel/code-frame@7.27.1': + resolution: {integrity: sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==} + engines: {node: '>=6.9.0'} + + '@babel/compat-data@7.28.5': + resolution: {integrity: sha512-6uFXyCayocRbqhZOB+6XcuZbkMNimwfVGFji8CTZnCzOHVGvDqzvitu1re2AU5LROliz7eQPhB8CpAMvnx9EjA==} + engines: {node: '>=6.9.0'} + + '@babel/core@7.28.5': + resolution: {integrity: sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==} + engines: {node: '>=6.9.0'} + + '@babel/generator@7.28.5': + resolution: {integrity: sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ==} + engines: {node: '>=6.9.0'} + + '@babel/helper-compilation-targets@7.27.2': + resolution: {integrity: sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==} + engines: {node: '>=6.9.0'} + + '@babel/helper-globals@7.28.0': + resolution: {integrity: sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-imports@7.27.1': + resolution: {integrity: sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-transforms@7.28.3': + resolution: {integrity: sha512-gytXUbs8k2sXS9PnQptz5o0QnpLL51SwASIORY6XaBKF88nsOT0Zw9szLqlSGQDP/4TljBAD5y98p2U1fqkdsw==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + + '@babel/helper-plugin-utils@7.27.1': + resolution: {integrity: sha512-1gn1Up5YXka3YYAHGKpbideQ5Yjf1tDa9qYcgysz+cNCXukyLl6DjPXhD3VRwSb8c0J9tA4b2+rHEZtc6R0tlw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-string-parser@7.27.1': + resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.28.5': + resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-option@7.27.1': + resolution: {integrity: sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==} + engines: {node: '>=6.9.0'} + + '@babel/helpers@7.28.4': + resolution: {integrity: sha512-HFN59MmQXGHVyYadKLVumYsA9dBFun/ldYxipEjzA4196jpLZd8UjEEBLkbEkvfYreDqJhZxYAWFPtrfhNpj4w==} + engines: {node: '>=6.9.0'} + + '@babel/parser@7.28.5': + resolution: {integrity: sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==} + engines: {node: '>=6.0.0'} + hasBin: true + + '@babel/plugin-transform-react-jsx-self@7.27.1': + resolution: {integrity: sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + + '@babel/plugin-transform-react-jsx-source@7.27.1': + resolution: {integrity: sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 + '@babel/runtime@7.28.4': resolution: {integrity: sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==} engines: {node: '>=6.9.0'} + '@babel/template@7.27.2': + resolution: {integrity: sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==} + engines: {node: '>=6.9.0'} + + '@babel/traverse@7.28.5': + resolution: {integrity: sha512-TCCj4t55U90khlYkVV/0TfkJkAkUg3jZFA3Neb7unZT8CPok7iiRfaX0F+WnqWqt7OxhOn0uBKXCw4lbL8W0aQ==} + engines: {node: '>=6.9.0'} + + '@babel/types@7.28.5': + resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==} + engines: {node: '>=6.9.0'} + '@codemirror/autocomplete@6.19.0': resolution: {integrity: sha512-61Hfv3cF07XvUxNeC3E7jhG8XNi1Yom1G0lRC936oLnlF+jrbrv8rc/J98XlYzcsAoTVupfsf5fLej1aI8kyIg==} @@ -818,6 +907,9 @@ packages: '@observablehq/runtime@6.0.0': resolution: {integrity: sha512-t3UXP69O0JK20HY/neF4/DDDSDorwo92As806Y1pNTgTmj1NtoPyVpesYzfH31gTFOFrXC2cArV+wLpebMk9eA==} + '@rolldown/pluginutils@1.0.0-beta.27': + resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} + '@rollup/rollup-android-arm-eabi@4.52.4': resolution: {integrity: sha512-BTm2qKNnWIQ5auf4deoetINJm2JzvihvGb9R6K/ETwKLql/Bb3Eg2H1FBp1gUb4YGbydMA3jcmQTR73q7J+GAA==} cpu: [arm] @@ -1048,6 +1140,18 @@ packages: '@tailwindcss/postcss@4.1.14': resolution: {integrity: sha512-BdMjIxy7HUNThK87C7BC8I1rE8BVUsfNQSI5siQ4JK3iIa3w0XyVvVL9SXLWO//CtYTcp1v7zci0fYwJOjB+Zg==} + '@types/babel__core@7.20.5': + resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==} + + '@types/babel__generator@7.27.0': + resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==} + + '@types/babel__template@7.4.4': + resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==} + + '@types/babel__traverse@7.28.0': + resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==} + '@types/chai@5.2.2': resolution: {integrity: sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg==} @@ -1091,6 +1195,12 @@ packages: '@ungap/structured-clone@1.3.0': resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==} + '@vitejs/plugin-react@4.7.0': + resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==} + engines: {node: ^14.18.0 || >=16.0.0} + peerDependencies: + vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 + '@vitest/expect@3.2.4': resolution: {integrity: sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==} @@ -1246,6 +1356,10 @@ packages: balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + baseline-browser-mapping@2.8.28: + resolution: {integrity: sha512-gYjt7OIqdM0PcttNYP2aVrr2G0bMALkBaoehD4BuRGjAOtipg0b6wHg1yNL+s5zSnLZZrGHOw4IrND8CD+3oIQ==} + hasBin: true + binary-extensions@2.3.0: resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} engines: {node: '>=8'} @@ -1267,6 +1381,11 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} + browserslist@4.28.0: + resolution: {integrity: sha512-tbydkR/CxfMwelN0vwdP/pLkDwyAASZ+VfWm4EOwlB6SWhx1sYnWLqo8N5j0rAzPfzfRaxt0mM/4wPU/Su84RQ==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + buffer-from@1.1.2: resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} @@ -1301,6 +1420,9 @@ packages: caniuse-lite@1.0.30001751: resolution: {integrity: sha512-A0QJhug0Ly64Ii3eIqHu5X51ebln3k4yTUkY1j8drqpWHVreg/VLijN48cZ1bYPiqOQuqpkIKnzr/Ul8V+p6Cw==} + caniuse-lite@1.0.30001754: + resolution: {integrity: sha512-x6OeBXueoAceOmotzx3PO4Zpt4rzpeIFsSr6AAePTZxSkXiYDUmpypEl7e2+8NCd9bD7bXjqyef8CJYPC1jfxg==} + cbor@8.1.0: resolution: {integrity: sha512-DwGjNW9omn6EwP70aXsn7FQJx5kO12tX0bZkaTjzdVFM6/7nhA4t0EENocKGx6D2Bch9PE2KzCUf5SceBdeijg==} engines: {node: '>=12.19'} @@ -1416,6 +1538,9 @@ packages: resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} engines: {node: '>= 0.6'} + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + convert-to-spaces@2.0.1: resolution: {integrity: sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -1565,6 +1690,9 @@ packages: ee-first@1.1.1: resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} + electron-to-chromium@1.5.251: + resolution: {integrity: sha512-lmyEOp4G0XT3qrYswNB4np1kx90k6QCXpnSHYv2xEsUuEu8JCobpDVYO6vMseirQyyCC6GCIGGxd5szMBa0tRA==} + emittery@1.2.0: resolution: {integrity: sha512-KxdRyyFcS85pH3dnU8Y5yFUm2YJdaHwcBZWrfG8o89ZY9a13/f9itbN+YG3ELbBo9Pg5zvIozstmuV8bX13q6g==} engines: {node: '>=14.16'} @@ -1833,6 +1961,10 @@ packages: resolution: {integrity: sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==} engines: {node: '>= 0.4'} + gensync@1.0.0-beta.2: + resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} + engines: {node: '>=6.9.0'} + get-caller-file@2.0.5: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} @@ -2128,6 +2260,24 @@ packages: resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} hasBin: true + jotai@2.15.1: + resolution: {integrity: sha512-yHT1HAZ3ba2Q8wgaUQ+xfBzEtcS8ie687I8XVCBinfg4bNniyqLIN+utPXWKQE93LMF5fPbQSVRZqgpcN5yd6Q==} + engines: {node: '>=12.20.0'} + peerDependencies: + '@babel/core': '>=7.0.0' + '@babel/template': '>=7.0.0' + '@types/react': '>=17.0.0' + react: '>=17.0.0' + peerDependenciesMeta: + '@babel/core': + optional: true + '@babel/template': + optional: true + '@types/react': + optional: true + react: + optional: true + js-string-escape@1.0.1: resolution: {integrity: sha512-Smw4xcfIQ5LVjAOuJCvN/zIodzA/BBSsluuoSykP+lUvScIi4U6RJLfwHet5cxFnCswUjISV8oAXaqaJDY3chg==} engines: {node: '>= 0.8'} @@ -2155,6 +2305,11 @@ packages: canvas: optional: true + jsesc@3.1.0: + resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} + engines: {node: '>=6'} + hasBin: true + json-buffer@3.0.1: resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} @@ -2164,6 +2319,11 @@ packages: json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + jsx-ast-utils@3.3.5: resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==} engines: {node: '>=4.0'} @@ -2273,6 +2433,9 @@ packages: lru-cache@10.4.3: resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==} + lru-cache@5.1.1: + resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + lucide-react@0.542.0: resolution: {integrity: sha512-w3hD8/SQB7+lzU2r4VdFyzzOzKnUjTZIF/MQJGSSvni7Llewni4vuViRppfRAa2guOsY5k4jZyxw/i9DQHv+dw==} peerDependencies: @@ -2418,6 +2581,9 @@ packages: sass: optional: true + node-releases@2.0.27: + resolution: {integrity: sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==} + nofilter@3.1.0: resolution: {integrity: sha512-l2NNj07e9afPnhAhvgVrCD/oy2Ai1yfLpuo3EpiO1jFTsB4sFz6oIfAfSZyQzVpkZQ9xS8ZS5g1jCBgq4Hwo0g==} engines: {node: '>=12.19'} @@ -2648,6 +2814,10 @@ packages: react-is@16.13.1: resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==} + react-refresh@0.17.0: + resolution: {integrity: sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==} + engines: {node: '>=0.10.0'} + react-tooltip@5.30.0: resolution: {integrity: sha512-Yn8PfbgQ/wmqnL7oBpz1QiDaLKrzZMdSUUdk7nVeGTwzbxCAJiJzR4VSYW+eIO42F1INt57sPUmpgKv0KwJKtg==} peerDependencies: @@ -3072,6 +3242,12 @@ packages: resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} engines: {node: '>= 0.8'} + update-browserslist-db@1.1.4: + resolution: {integrity: sha512-q0SPT4xyU84saUX+tomz1WLkxUbuaJnR1xWt17M7fJtEJigJeWUNGUqrauFXsHnqev9y9JTRGwk13tFBuKby4A==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} @@ -3254,6 +3430,9 @@ packages: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} + yallist@3.1.1: + resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + yallist@5.0.0: resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==} engines: {node: '>=18'} @@ -3289,8 +3468,120 @@ snapshots: '@csstools/css-tokenizer': 3.0.4 lru-cache: 10.4.3 + '@babel/code-frame@7.27.1': + dependencies: + '@babel/helper-validator-identifier': 7.28.5 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/compat-data@7.28.5': {} + + '@babel/core@7.28.5': + dependencies: + '@babel/code-frame': 7.27.1 + '@babel/generator': 7.28.5 + '@babel/helper-compilation-targets': 7.27.2 + '@babel/helper-module-transforms': 7.28.3(@babel/core@7.28.5) + '@babel/helpers': 7.28.4 + '@babel/parser': 7.28.5 + '@babel/template': 7.27.2 + '@babel/traverse': 7.28.5 + '@babel/types': 7.28.5 + '@jridgewell/remapping': 2.3.5 + convert-source-map: 2.0.0 + debug: 4.4.3 + gensync: 1.0.0-beta.2 + json5: 2.2.3 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color + + '@babel/generator@7.28.5': + dependencies: + '@babel/parser': 7.28.5 + '@babel/types': 7.28.5 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + jsesc: 3.1.0 + + '@babel/helper-compilation-targets@7.27.2': + dependencies: + '@babel/compat-data': 7.28.5 + '@babel/helper-validator-option': 7.27.1 + browserslist: 4.28.0 + lru-cache: 5.1.1 + semver: 6.3.1 + + '@babel/helper-globals@7.28.0': {} + + '@babel/helper-module-imports@7.27.1': + dependencies: + '@babel/traverse': 7.28.5 + '@babel/types': 7.28.5 + transitivePeerDependencies: + - supports-color + + '@babel/helper-module-transforms@7.28.3(@babel/core@7.28.5)': + dependencies: + '@babel/core': 7.28.5 + '@babel/helper-module-imports': 7.27.1 + '@babel/helper-validator-identifier': 7.28.5 + '@babel/traverse': 7.28.5 + transitivePeerDependencies: + - supports-color + + '@babel/helper-plugin-utils@7.27.1': {} + + '@babel/helper-string-parser@7.27.1': {} + + '@babel/helper-validator-identifier@7.28.5': {} + + '@babel/helper-validator-option@7.27.1': {} + + '@babel/helpers@7.28.4': + dependencies: + '@babel/template': 7.27.2 + '@babel/types': 7.28.5 + + '@babel/parser@7.28.5': + dependencies: + '@babel/types': 7.28.5 + + '@babel/plugin-transform-react-jsx-self@7.27.1(@babel/core@7.28.5)': + dependencies: + '@babel/core': 7.28.5 + '@babel/helper-plugin-utils': 7.27.1 + + '@babel/plugin-transform-react-jsx-source@7.27.1(@babel/core@7.28.5)': + dependencies: + '@babel/core': 7.28.5 + '@babel/helper-plugin-utils': 7.27.1 + '@babel/runtime@7.28.4': {} + '@babel/template@7.27.2': + dependencies: + '@babel/code-frame': 7.27.1 + '@babel/parser': 7.28.5 + '@babel/types': 7.28.5 + + '@babel/traverse@7.28.5': + dependencies: + '@babel/code-frame': 7.27.1 + '@babel/generator': 7.28.5 + '@babel/helper-globals': 7.28.0 + '@babel/parser': 7.28.5 + '@babel/template': 7.27.2 + '@babel/types': 7.28.5 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + '@babel/types@7.28.5': + dependencies: + '@babel/helper-string-parser': 7.27.1 + '@babel/helper-validator-identifier': 7.28.5 + '@codemirror/autocomplete@6.19.0': dependencies: '@codemirror/language': 6.11.3 @@ -4016,6 +4307,8 @@ snapshots: '@observablehq/runtime@6.0.0': {} + '@rolldown/pluginutils@1.0.0-beta.27': {} + '@rollup/rollup-android-arm-eabi@4.52.4': optional: true @@ -4200,6 +4493,27 @@ snapshots: postcss: 8.5.6 tailwindcss: 4.1.14 + '@types/babel__core@7.20.5': + dependencies: + '@babel/parser': 7.28.5 + '@babel/types': 7.28.5 + '@types/babel__generator': 7.27.0 + '@types/babel__template': 7.4.4 + '@types/babel__traverse': 7.28.0 + + '@types/babel__generator@7.27.0': + dependencies: + '@babel/types': 7.28.5 + + '@types/babel__template@7.4.4': + dependencies: + '@babel/parser': 7.28.5 + '@babel/types': 7.28.5 + + '@types/babel__traverse@7.28.0': + dependencies: + '@babel/types': 7.28.5 + '@types/chai@5.2.2': dependencies: '@types/deep-eql': 4.0.2 @@ -4245,6 +4559,18 @@ snapshots: '@ungap/structured-clone@1.3.0': {} + '@vitejs/plugin-react@4.7.0(vite@7.1.10(jiti@2.6.1)(lightningcss@1.30.1))': + dependencies: + '@babel/core': 7.28.5 + '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.5) + '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/core@7.28.5) + '@rolldown/pluginutils': 1.0.0-beta.27 + '@types/babel__core': 7.20.5 + react-refresh: 0.17.0 + vite: 7.1.10(jiti@2.6.1)(lightningcss@1.30.1) + transitivePeerDependencies: + - supports-color + '@vitest/expect@3.2.4': dependencies: '@types/chai': 5.2.2 @@ -4462,6 +4788,8 @@ snapshots: balanced-match@1.0.2: {} + baseline-browser-mapping@2.8.28: {} + binary-extensions@2.3.0: {} blueimp-md5@2.19.0: {} @@ -4494,6 +4822,14 @@ snapshots: dependencies: fill-range: 7.1.1 + browserslist@4.28.0: + dependencies: + baseline-browser-mapping: 2.8.28 + caniuse-lite: 1.0.30001754 + electron-to-chromium: 1.5.251 + node-releases: 2.0.27 + update-browserslist-db: 1.1.4(browserslist@4.28.0) + buffer-from@1.1.2: {} bytes@3.1.2: {} @@ -4523,6 +4859,8 @@ snapshots: caniuse-lite@1.0.30001751: {} + caniuse-lite@1.0.30001754: {} + cbor@8.1.0: dependencies: nofilter: 3.1.0 @@ -4659,6 +4997,8 @@ snapshots: content-type@1.0.5: {} + convert-source-map@2.0.0: {} + convert-to-spaces@2.0.1: {} cookie-signature@1.0.6: {} @@ -4801,6 +5141,8 @@ snapshots: ee-first@1.1.1: {} + electron-to-chromium@1.5.251: {} + emittery@1.2.0: {} emoji-regex@8.0.0: {} @@ -5215,6 +5557,8 @@ snapshots: generator-function@2.0.1: {} + gensync@1.0.0-beta.2: {} + get-caller-file@2.0.5: {} get-intrinsic@1.3.0: @@ -5523,6 +5867,12 @@ snapshots: jiti@2.6.1: {} + jotai@2.15.1(@babel/core@7.28.5)(@babel/template@7.27.2)(react@19.2.0): + optionalDependencies: + '@babel/core': 7.28.5 + '@babel/template': 7.27.2 + react: 19.2.0 + js-string-escape@1.0.1: {} js-tokens@4.0.0: {} @@ -5565,12 +5915,16 @@ snapshots: - supports-color - utf-8-validate + jsesc@3.1.0: {} + json-buffer@3.0.1: {} json-schema-traverse@0.4.1: {} json-stable-stringify-without-jsonify@1.0.1: {} + json5@2.2.3: {} + jsx-ast-utils@3.3.5: dependencies: array-includes: 3.1.9 @@ -5660,6 +6014,10 @@ snapshots: lru-cache@10.4.3: {} + lru-cache@5.1.1: + dependencies: + yallist: 3.1.1 + lucide-react@0.542.0(react@19.2.0): dependencies: react: 19.2.0 @@ -5775,7 +6133,7 @@ snapshots: negotiator@0.6.3: {} - next@15.5.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0): + next@15.5.6(@babel/core@7.28.5)(react-dom@19.2.0(react@19.2.0))(react@19.2.0): dependencies: '@next/env': 15.5.6 '@swc/helpers': 0.5.15 @@ -5783,7 +6141,7 @@ snapshots: postcss: 8.4.31 react: 19.2.0 react-dom: 19.2.0(react@19.2.0) - styled-jsx: 5.1.6(react@19.2.0) + styled-jsx: 5.1.6(@babel/core@7.28.5)(react@19.2.0) optionalDependencies: '@next/swc-darwin-arm64': 15.5.6 '@next/swc-darwin-x64': 15.5.6 @@ -5798,6 +6156,8 @@ snapshots: - '@babel/core' - babel-plugin-macros + node-releases@2.0.27: {} + nofilter@3.1.0: {} normalize-path@3.0.0: {} @@ -6014,6 +6374,8 @@ snapshots: react-is@16.13.1: {} + react-refresh@0.17.0: {} + react-tooltip@5.30.0(react-dom@19.2.0(react@19.2.0))(react@19.2.0): dependencies: '@floating-ui/dom': 1.7.4 @@ -6393,10 +6755,12 @@ snapshots: style-mod@4.1.3: {} - styled-jsx@5.1.6(react@19.2.0): + styled-jsx@5.1.6(@babel/core@7.28.5)(react@19.2.0): dependencies: client-only: 0.0.1 react: 19.2.0 + optionalDependencies: + '@babel/core': 7.28.5 supertap@3.0.1: dependencies: @@ -6552,6 +6916,12 @@ snapshots: unpipe@1.0.0: {} + update-browserslist-db@1.1.4(browserslist@4.28.0): + dependencies: + browserslist: 4.28.0 + escalade: 3.2.0 + picocolors: 1.1.1 + uri-js@4.4.1: dependencies: punycode: 2.3.1 @@ -6740,6 +7110,8 @@ snapshots: y18n@5.0.8: {} + yallist@3.1.1: {} + yallist@5.0.0: {} yargs-parser@21.1.1: {} diff --git a/test/components/App.tsx b/test/components/App.tsx new file mode 100644 index 0000000..874eb05 --- /dev/null +++ b/test/components/App.tsx @@ -0,0 +1,50 @@ +import {useEffect, useState} from "react"; +import {useAtom} from "jotai"; +import {selectedTestAtom} from "../store"; +import {TestSelector} from "./TestSelector"; +import {Editor} from "./Editor"; +import {TransactionViewer} from "./TransactionViewer"; +import * as testSamples from "../js/index.js"; +import type {ViewPlugin} from "@codemirror/view"; + +export function App() { + const [selectedTest, setSelectedTest] = useAtom(selectedTestAtom); + const [transactionViewerPlugin, setTransactionViewerPlugin] = useState | undefined>(); + + // Initialize from URL on mount + useEffect(() => { + const params = new URLSearchParams(window.location.search); + const testFromUrl = params.get("test"); + if (testFromUrl && testFromUrl in testSamples) { + setSelectedTest(testFromUrl); + } + }, [setSelectedTest]); + + // Get the current test code + const currentCode = (testSamples as Record)[selectedTest] || testSamples.helloWorld; + + return ( +
+ {/* Header */} +
+
+

Recho Playground

+ +
+
+ + {/* Main content */} +
+ {/* Editor panel */} +
+ +
+ + {/* Transaction viewer sidebar */} + +
+
+ ); +} diff --git a/test/components/Editor.tsx b/test/components/Editor.tsx new file mode 100644 index 0000000..0b261c6 --- /dev/null +++ b/test/components/Editor.tsx @@ -0,0 +1,129 @@ +import { useEffect, useRef, useState } from "react"; +import { Play, Square, RefreshCcw } from "lucide-react"; +import { createEditor } from "../../editor/index.js"; +import { cn } from "../../app/cn.js"; +import type { ViewPlugin } from "@codemirror/view"; + +interface EditorProps { + code: string; + transactionViewerPlugin?: ViewPlugin; + onError?: (error: Error) => void; +} + +function debounce(fn: (...args: any[]) => void, delay = 0) { + let timeout: ReturnType; + return (...args: any[]) => { + clearTimeout(timeout); + timeout = setTimeout(() => fn(...args), delay); + }; +} + +const onDefaultError = debounce(() => { + setTimeout(() => { + alert("Something unexpected happened. Please check the console for details."); + }, 100); +}, 0); + +export function Editor({ code, transactionViewerPlugin, onError = onDefaultError }: EditorProps) { + const containerRef = useRef(null); + const editorRef = useRef(null); + const [needRerun, setNeedRerun] = useState(false); + + useEffect(() => { + if (containerRef.current) { + containerRef.current.innerHTML = ""; + + const extensions = transactionViewerPlugin ? [transactionViewerPlugin] : []; + + editorRef.current = createEditor(containerRef.current, { + code, + extensions, + onError, + }); + + // Auto-run on mount + editorRef.current.run(); + } + + return () => { + if (editorRef.current) { + editorRef.current.destroy(); + } + }; + }, [code, transactionViewerPlugin, onError]); + + useEffect(() => { + const onInput = () => { + setNeedRerun(true); + }; + + if (editorRef.current) { + editorRef.current.on("userInput", onInput); + } + }, [code]); + + useEffect(() => { + const onKeyDown = (e: KeyboardEvent) => { + if (e.metaKey && e.key === "s") { + e.preventDefault(); + onRun(); + } + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, []); + + function onRun() { + setNeedRerun(false); + editorRef.current?.run(); + } + + function onStop() { + setNeedRerun(false); + editorRef.current?.stop(); + } + + function onRerun() { + setNeedRerun(false); + editorRef.current?.stop(); + editorRef.current?.run(); + } + + function metaKey() { + return typeof navigator !== "undefined" && navigator.userAgent.includes("Mac") ? "⌘" : "Ctrl"; + } + + return ( +
+
+
Editor
+
+ + + +
+
+
+
{code}
+
+
+ ); +} diff --git a/test/components/TestSelector.tsx b/test/components/TestSelector.tsx new file mode 100644 index 0000000..3dcd275 --- /dev/null +++ b/test/components/TestSelector.tsx @@ -0,0 +1,30 @@ +import { useAtom } from "jotai"; +import { selectedTestAtom, getTestSampleName } from "../store"; +import * as testSamples from "../js/index.js"; + +export function TestSelector() { + const [selectedTest, setSelectedTest] = useAtom(selectedTestAtom); + + const handleChange = (e: React.ChangeEvent) => { + const newTest = e.target.value; + setSelectedTest(newTest); + // Update URL + const url = new URL(window.location.href); + url.searchParams.set("test", newTest); + window.history.pushState({}, "", url); + }; + + return ( + + ); +} diff --git a/test/components/TransactionViewer.tsx b/test/components/TransactionViewer.tsx new file mode 100644 index 0000000..7df4b36 --- /dev/null +++ b/test/components/TransactionViewer.tsx @@ -0,0 +1,471 @@ +import { useState, useEffect, useRef } from "react"; +import { ViewPlugin } from "@codemirror/view"; +import { Transaction as CMTransaction } from "@codemirror/state"; +import { blockMetadataEffect } from "../../editor/blockMetadata.ts"; +import { cn } from "../../app/cn.js"; + +// Maximum number of transactions to keep in history +const MAX_HISTORY = 100; + +interface TransactionRange { + from: number; + to: number; + anchor: number; + head: number; +} + +interface TransactionChange { + from: number; + to: number; + fromLine: number; + fromCol: number; + toLine: number; + toCol: number; + insert: string; +} + +interface TransactionEffect { + value: any; + type: string; + blockMetadata?: any[]; +} + +interface TransactionData { + index: number; + docChanged: boolean; + changes: TransactionChange[]; + annotations: Record; + effects: TransactionEffect[]; + selection: TransactionRange[]; + scrollIntoView?: boolean; + filter?: boolean; + sequential?: boolean; + timestamp: number; +} + +interface TransactionGroup { + type: "individual" | "selection"; + transaction?: TransactionData; + transactions?: TransactionData[]; +} + +interface TransactionViewerProps { + onPluginCreate: (plugin: ViewPlugin) => void; +} + +export function TransactionViewer({ onPluginCreate }: TransactionViewerProps) { + const [transactions, setTransactions] = useState([]); + const [autoScroll, setAutoScroll] = useState(true); + const listRef = useRef(null); + const nextIndexRef = useRef(0); + + useEffect(() => { + const transactionsList: TransactionData[] = []; + const listeners = new Set<(transactions: TransactionData[]) => void>(); + + function notifyListeners() { + listeners.forEach((fn) => fn([...transactionsList])); + } + + function extractTransactionData(tr: CMTransaction, index: number): TransactionData { + const data: TransactionData = { + index, + docChanged: tr.docChanged, + changes: [], + annotations: {}, + effects: [], + selection: tr.state.selection.ranges.map((r) => ({ + from: r.from, + to: r.to, + anchor: r.anchor, + head: r.head, + })), + scrollIntoView: tr.scrollIntoView, + filter: tr.filter, + sequential: tr.sequential, + timestamp: Date.now(), + }; + + // Extract changes + tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => { + const fromLine = tr.startState.doc.lineAt(fromA); + const toLine = tr.startState.doc.lineAt(toA); + + data.changes.push({ + from: fromA, + to: toA, + fromLine: fromLine.number, + fromCol: fromA - fromLine.from, + toLine: toLine.number, + toCol: toA - toLine.from, + insert: inserted.toString(), + }); + }); + + // Extract annotations + const userEvent = tr.annotation(CMTransaction.userEvent); + if (userEvent !== undefined) { + data.annotations.userEvent = userEvent; + } + + const remote = tr.annotation(CMTransaction.remote); + if (remote !== undefined) { + data.annotations.remote = remote; + } + + const addToHistory = tr.annotation(CMTransaction.addToHistory); + if (addToHistory !== undefined) { + data.annotations.addToHistory = addToHistory; + } + + // Extract effects + for (const effect of tr.effects) { + const effectData: TransactionEffect = { + value: effect.value, + type: "StateEffect", + }; + + if (effect.is(blockMetadataEffect)) { + effectData.type = "blockMetadataEffect"; + effectData.blockMetadata = effect.value; + } + + data.effects.push(effectData); + } + + return data; + } + + const plugin = ViewPlugin.fromClass( + class { + constructor(view: any) { + const initialTr: TransactionData = { + index: nextIndexRef.current++, + docChanged: false, + changes: [], + annotations: {}, + effects: [], + selection: view.state.selection.ranges.map((r: any) => ({ + from: r.from, + to: r.to, + anchor: r.anchor, + head: r.head, + })), + timestamp: Date.now(), + }; + transactionsList.push(initialTr); + notifyListeners(); + } + + update(update: any) { + update.transactions.forEach((tr: CMTransaction) => { + const transactionData = extractTransactionData(tr, nextIndexRef.current++); + transactionsList.push(transactionData); + + if (transactionsList.length > MAX_HISTORY) { + transactionsList.shift(); + } + }); + + if (update.transactions.length > 0) { + notifyListeners(); + } + } + } + ); + + listeners.add((newTransactions) => { + setTransactions(newTransactions); + }); + + onPluginCreate(plugin); + + return () => { + listeners.clear(); + }; + }, [onPluginCreate]); + + useEffect(() => { + if (autoScroll && listRef.current) { + listRef.current.scrollTop = 0; + } + }, [transactions, autoScroll]); + + const handleClear = () => { + setTransactions([]); + nextIndexRef.current = 0; + }; + + const groupTransactions = (): TransactionGroup[] => { + const groups: TransactionGroup[] = []; + let currentGroup: TransactionGroup | null = null; + + for (let i = transactions.length - 1; i >= 0; i--) { + const tr = transactions[i]; + const isSelection = + tr.annotations.userEvent === "select" || tr.annotations.userEvent === "select.pointer"; + + if (isSelection) { + if (currentGroup && currentGroup.type === "selection") { + currentGroup.transactions!.push(tr); + } else { + currentGroup = { + type: "selection", + transactions: [tr], + }; + groups.push(currentGroup); + } + } else { + groups.push({ + type: "individual", + transaction: tr, + }); + currentGroup = null; + } + } + + return groups; + }; + + return ( +
+
+

Transactions

+
+ + +
+
+
+ {transactions.length === 0 ? ( +
No transactions yet
+ ) : ( + groupTransactions().map((group, idx) => + group.type === "individual" ? ( + + ) : ( + + ) + ) + )} +
+
+ ); +} + +function TransactionItem({ transaction: tr }: { transaction: TransactionData }) { + const [isOpen, setIsOpen] = useState(false); + + const formatTime = (timestamp: number) => { + const time = new Date(timestamp); + return ( + time.toLocaleTimeString("en-US", { + hour12: false, + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) + + "." + + time.getMilliseconds().toString().padStart(3, "0") + ); + }; + + let summaryLeft = `#${tr.index}`; + if (tr.annotations.userEvent) { + summaryLeft += ` [${tr.annotations.userEvent}]`; + } else if (tr.annotations.remote) { + summaryLeft += ` [remote: ${JSON.stringify(tr.annotations.remote)}]`; + } + if (tr.docChanged) { + summaryLeft += ` 📝`; + } + + return ( +
setIsOpen((e.target as HTMLDetailsElement).open)} + className={cn( + "mb-2 border border-gray-200 rounded text-xs", + tr.annotations.userEvent && "bg-blue-50", + tr.docChanged && "border-l-4 border-l-blue-500" + )} + > + + {summaryLeft} + {formatTime(tr.timestamp)} + +
+
+ Doc Changed: {tr.docChanged.toString()} +
+ + {tr.changes.length > 0 ? ( +
+ Changes: + {tr.changes.map((change, idx) => { + const deleted = change.to - change.from; + const inserted = change.insert.length; + const sameLine = change.fromLine === change.toLine; + + let posInfo = `pos ${change.from}-${change.to}`; + if (sameLine) { + posInfo += ` (L${change.fromLine}:${change.fromCol}-${change.toCol})`; + } else { + posInfo += ` (L${change.fromLine}:${change.fromCol} to L${change.toLine}:${change.toCol})`; + } + + return ( +
+
Change {idx + 1}: {posInfo}
+ {deleted > 0 &&
Deleted {deleted} chars
} + {inserted > 0 && ( +
+ Inserted: {change.insert} +
+ )} +
+ ); + })} +
+ ) : ( +
+ Changes: none +
+ )} + + {Object.keys(tr.annotations).length > 0 ? ( +
+ Annotations: + {Object.entries(tr.annotations).map(([key, value]) => ( +
+ {key}: {JSON.stringify(value)} +
+ ))} +
+ ) : ( +
+ Annotations: none +
+ )} + + {tr.effects.length > 0 ? ( +
+ Effects: {tr.effects.length} + {tr.effects.map((effect, idx) => ( +
+ {effect.type === "blockMetadataEffect" && effect.blockMetadata ? ( +
+
Effect {idx + 1}: blockMetadataEffect ({effect.blockMetadata.length} blocks)
+ {effect.blockMetadata.map((block: any, blockIdx: number) => ( +
+
Block {blockIdx + 1}:
+
+ {block.output !== null + ? `Output: ${block.output.from}-${block.output.to}` + : "Output: null"} +
+
Source: {block.source.from}-{block.source.to}
+ {Object.keys(block.attributes).length > 0 && ( +
Attributes: {JSON.stringify(block.attributes)}
+ )} + {block.error &&
Error: true
} +
+ ))} +
+ ) : ( +
Effect {idx + 1} ({effect.type}): {JSON.stringify(effect.value).substring(0, 100)}
+ )} +
+ ))} +
+ ) : ( +
+ Effects: none +
+ )} + +
+ Selection: + {tr.selection.map((range, idx) => { + const isCursor = range.from === range.to; + return ( +
+ Range {idx + 1}: {isCursor ? `cursor at ${range.from}` : `${range.from}-${range.to}`} + {!isCursor && ` (anchor: ${range.anchor}, head: ${range.head})`} +
+ ); + })} +
+
+
+ ); +} + +function SelectionGroupItem({ transactions }: { transactions: TransactionData[] }) { + const [isOpen, setIsOpen] = useState(false); + + const formatTime = (timestamp: number) => { + const time = new Date(timestamp); + return ( + time.toLocaleTimeString("en-US", { + hour12: false, + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }) + + "." + + time.getMilliseconds().toString().padStart(3, "0") + ); + }; + + const count = transactions.length; + const firstTr = transactions[0]; + const lastTr = transactions[transactions.length - 1]; + + const summaryLeft = `#${lastTr.index}-${firstTr.index} [select] (${count} transactions)`; + const summaryRight = `${formatTime(lastTr.timestamp)} - ${formatTime(firstTr.timestamp)}`; + + return ( +
setIsOpen((e.target as HTMLDetailsElement).open)} + className="mb-2 border border-gray-300 rounded text-xs bg-gray-50" + > + + {summaryLeft} + {summaryRight} + +
+ {transactions.map((tr) => { + const selectionInfo = tr.selection + .map((range) => { + const isCursor = range.from === range.to; + return isCursor ? `cursor at ${range.from}` : `${range.from}-${range.to}`; + }) + .join(", "); + + return ( +
+ #{tr.index} + {selectionInfo} + {formatTime(tr.timestamp)} +
+ ); + })} +
+
+ ); +} diff --git a/test/index.html b/test/index.html index 3261143..3de6502 100644 --- a/test/index.html +++ b/test/index.html @@ -4,10 +4,9 @@ Recho (Test) - - - +
+ diff --git a/test/main.tsx b/test/main.tsx new file mode 100644 index 0000000..bb9e3e9 --- /dev/null +++ b/test/main.tsx @@ -0,0 +1,18 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { Provider as JotaiProvider } from "jotai"; +import { App } from "./components/App"; +import "./styles.css"; + +const root = document.getElementById("root"); +if (!root) { + throw new Error("Root element not found"); +} + +createRoot(root).render( + + + + + +); diff --git a/test/store.ts b/test/store.ts new file mode 100644 index 0000000..70c6836 --- /dev/null +++ b/test/store.ts @@ -0,0 +1,61 @@ +import { atom } from "jotai"; + +// Types +export interface Transaction { + time: number; + docChanged: boolean; + selection: { from: number; to: number } | null; + effects: string[]; + annotations: string[]; +} + +export interface TestSample { + name: string; + code: string; +} + +// Atoms +export const selectedTestAtom = atom("helloWorld"); +export const transactionHistoryAtom = atom([]); +export const autoScrollAtom = atom(true); + +// Factory functions for state operations +export function createTransaction(data: { + time: number; + docChanged: boolean; + selection: { from: number; to: number } | null; + effects: string[]; + annotations: string[]; +}): Transaction { + return { + time: data.time, + docChanged: data.docChanged, + selection: data.selection, + effects: data.effects, + annotations: data.annotations, + }; +} + +export function addTransaction( + history: Transaction[], + transaction: Transaction +): Transaction[] { + const newHistory = [...history, transaction]; + // Keep max 100 transactions + if (newHistory.length > 100) { + return newHistory.slice(-100); + } + return newHistory; +} + +export function clearTransactionHistory(): Transaction[] { + return []; +} + +export function getTestSampleName(key: string): string { + // Convert camelCase to Title Case with spaces + return key + .replace(/([A-Z])/g, " $1") + .replace(/^./, (str) => str.toUpperCase()) + .trim(); +} diff --git a/test/styles.css b/test/styles.css new file mode 100644 index 0000000..37de1dd --- /dev/null +++ b/test/styles.css @@ -0,0 +1,41 @@ +@import "tailwindcss"; +@import "../editor/index.css"; +@import "@fontsource-variable/inter"; +@import "@fontsource-variable/spline-sans-mono"; + +@theme { + --default-font-family: "Inter Variable"; + --font-mono: "Spline Sans Mono Variable"; +} + +button { + cursor: pointer; +} + +.cm-gutters { + background-color: white !important; + border-right: none !important; + padding-left: 8px !important; +} + +.cm-editor.cm-focused { + outline: none !important; +} + +/* Details/Summary styling for transaction viewer */ +details summary { + list-style: none; +} + +details summary::-webkit-details-marker { + display: none; +} + +details summary::marker { + display: none; +} + +details[open] > summary { + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; +} diff --git a/vite.config.js b/vite.config.js index cb4a843..1abada3 100644 --- a/vite.config.js +++ b/vite.config.js @@ -1,7 +1,9 @@ import {defineConfig} from "vite"; +import react from "@vitejs/plugin-react"; export default defineConfig({ root: "test", + plugins: [react()], test: { environment: "jsdom", },