Redefining a cell #26
-
The docs allude to the ability to redefine an existing cell: "The Runtime API provides some additional logic on top of the Observable Runtime to run the notebook, allowing cells to be redefined at runtime, and implementing the notebook standard library, including the display and view functions which are scoped per-cell." Are there any examples of how to do that? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
The following pattern seems to work: const scope: Map<string, Variable> = main._scope;
const existing = scope.get(`cell ${cellId}`);
if (existing) {
existing.define(data.value.inputs, data.value.body);
} else {
define({ root: container, expanded: [], variables: [] }, { id: cellId, ...data.value });
} |
Beta Was this translation helpful? Give feedback.
-
...and notebook support for html files in vscode kinda works! ![]() |
Beta Was this translation helpful? Give feedback.
-
Something like this: import type {DefineState, Definition} from "@observablehq/notebook-kit/runtime";
import {define} from "@observablehq/notebook-kit/runtime";
const main = document.querySelector("main")!;
const stateById = new Map<number, DefineState>();
export function add(definition: Definition): void {
const {id} = definition;
let state = stateById.get(id);
if (state) {
state.variables.forEach((v) => v.delete());
state.variables = [];
} else {
const root = main.appendChild(document.createElement("div"));
state = {root, expanded: [], variables: []};
stateById.set(id, state);
}
define(state, definition);
}
export function remove(id: number): void {
const state = stateById.get(id)!;
state.root.remove();
state.variables.forEach((v) => v.delete());
stateById.delete(id);
} Your other answer was pretty close. Just note that a cell can define multiple variables, so you want to clean up all of them. |
Beta Was this translation helpful? Give feedback.
Something like this: