Public
Edited
Nov 17, 2024
1 fork
Importers
6 stars
Insert cell
Insert cell
Insert cell
javascriptPlugin = esmCodeMirror("lang-javascript")
Insert cell
viewof editor = CodeMirror("const foo = () => 4.5\n", {
extensions: [
javascriptPlugin.javascript(),
codemirror.basicSetup,
myDefaultTheme
]
})
Insert cell
editor
Insert cell
viewof texarea = Inputs.bind(
Inputs.textarea({
label: "bidirecitonal binding"
}),
viewof editor
)
Insert cell
Insert cell
Insert cell
Insert cell
CodeMirror = (doc = "", config = {}) => {
const extensions = config.extensions ?? [];

const updateViewOf = codemirror.EditorView.updateListener.of((update) => {
if (doc !== view.state.doc.toString()) {
doc = view.state.doc.toString();
container.dispatchEvent(new Event("input", { bubbles: true }));
}
});

const view = new codemirror.EditorView({
doc,
extensions: [updateViewOf, ...extensions]
});
const el = view.dom;
const container = htl.html`<div><span onInput=${(evt) =>
evt.stopPropagation()}>${el}`;
Object.defineProperty(container, "value", {
enumerable: true,
get: () => doc,
set: (newContent = "") => {
const change = calcChange(doc, newContent, view.state.selection);
doc = newContent;
view.dispatch(change);
}
});
return container;
}
Insert cell
calcChange("abcddddddefg", "abcddddddefg", { ranges: [{ from: 8 }] })
Insert cell
calcChange = (previous, next, selection) => {
// Find where to start inserting
for (
var insertOffset = 0;
insertOffset < selection.ranges[0].from;
insertOffset++
) {
if (previous[insertOffset] !== next[insertOffset]) break;
}

// Find where the insert ends
for (
var endOffset = 0;
endOffset < previous.length - selection.ranges[0].from;
endOffset++
) {
if (
previous[previous.length - endOffset - 1] !==
next[next.length - endOffset - 1]
)
break;
}
const insert = next.substring(insertOffset, next.length - endOffset);
const cursor = Math.min(insertOffset + insert.length, next.length);
return {
changes: [
{
from: insertOffset,
to: previous.length - endOffset,
insert
}
],
selection: {
anchor: cursor,
head: cursor
}
};
}
Insert cell
Insert cell
myDefaultTheme = codemirror.EditorView.theme({
"&": {
fontFamily: 'Consolas, "Roboto Mono", monospace',
fontSize: "14px",
height: "200px",
border: "1px solid #ddd"
}
})
Insert cell
Insert cell
esmImport = (pkg) =>
import(
/*`https://unpkg.com/${pkg}/dist/index.js?module`*/
`https://jspm.dev/${pkg}`
) /*broken: import(`https://cdn.skypack.dev/${pkg}`)*/
Insert cell
Insert cell
codemirror = esmImport(`codemirror`)
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more