Public
Edited
Jan 19
Importers
1 star
Insert cell
Insert cell
Insert cell
Insert cell
CodeMirror("initial text", {})
Insert cell
Insert cell
CodeMirror = (doc = "", config = {}) => {
const extensions = config.extensions ?? [];

const updateViewOf = codemirror.EditorView.updateListener.of((update) => {
console.log(update);
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: () => view.state.doc.toString(),
set: (newContent = "") => {
const change = calcChange(
view.state.doc.toString(),
newContent,
view.state.selection
);
view.dispatch(change);
}
});
return container;
}
Insert cell
Insert cell
calcChange = (previous, next, selection) => {
// Find where to start inserting
const [insertOffset, endOffset] = findMiddle(previous, next);
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
function findMiddle(s1, s2) {
const n = s1.length,
m = s2.length;

// Step 1: Find the shared prefix
let prefixLen = 0;
while (prefixLen < n && prefixLen < m && s1[prefixLen] === s2[prefixLen]) {
prefixLen++;
}

// Step 2: Find the shared suffix
let suffixLen = 0;
while (
suffixLen < n - prefixLen &&
suffixLen < m - prefixLen &&
s1[n - suffixLen - 1] === s2[m - suffixLen - 1]
) {
suffixLen++;
}

return [prefixLen, suffixLen];
}
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
Insert cell
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