@metablock/notebook is a typescript library for creating interactive notebooks. It is based on web components and the marked library. The library takes markdown text and renders it in a container element. As we'll see below, any javascript code is executed during the rendering process.
Code snippets
To write a code snippet, enclose the code with three backticks followed by the language name, for example
```js
const notebook = new Notebook();
notebook.options = {
mode: "dark",
highlightStyle: "",
codeClipboard: true,
};
```
renders as
const notebook = new Notebook();
notebook.options = {
mode: "dark",
highlightStyle: "",
codeClipboard: true,
};
It is possible to include content from public github repositories using the <github-repo>
tag, for example:
<github-repo
owner="quantmind"
repo="quantflow"
path="quantflow/utils/bs.py"
></github-repo>
displays the python code for Black-Scholes option pricing from the quantflow repo.
Math
To write math, enclose the math with three backticks followed by math
, for example,
```math
\begin{align}
d s_t = \mu s_t dt + \sigma s_t dW_t
\end{align}
```
produces
\begin{align} d s_t = \mu s_t dt + \sigma s_t dW_t \end{align}Inline math is also supported, for example d s_t = \mu s_t dt + \sigma s_t dW_t is produced via the inline markup
Math rendering is done using katex.
Javascript modules
To use an inline javascript module simply enclose it in the script
tag with the relevant attributes, for example
<script type="module" show-code>
import * as Plot from "https://cdn.jsdelivr.net/npm/@observablehq/plot/+esm";
const mandelbrot = (x, y) => {
for (let n = 0, zr = 0, zi = 0; n < 80; ++n) {
[zr, zi] = [zr * zr - zi * zi + x, 2 * zr * zi + y];
if (zr * zr + zi * zi > 4) return n;
}
};
class FractalPlot extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
connectedCallback() {
const options = {
height: 500,
margin: 0,
marks: [
Plot.raster({
fill: mandelbrot,
pixelSize: 1 / devicePixelRatio,
x1: -2,
x2: 1,
y1: -1.164,
y2: 1.164,
}),
],
};
this.shadowRoot.appendChild(Plot.plot(options));
}
}
customElements.define("fractal-plot", FractalPlot);
</script>
displays the code above (thanks to the show-code
attribute)
and loads the code in the browser so that a fractal plot is rendered via
<fractal-plot></fractal-plot>
You can import a module from a URL too, along the same lines as the example above:
<script
type="module"
src="https://assets.metablock.io/blocks/6abc4e83f5c64a1d831c6e1abc3ea92b/bundles/81173f9fb9f646cdbacce82b637aa699/blog/metablock-notebook/particles.js"
></script>
<connected-particles></connected-particles>
Original code from this observable notebook.
Editor
The editor components allow to display an interactive editor for code, math, and markdown. It uses the codemirror library for code editing.
<editor-component></editor-component>
with initial content and line numbers:
<editor-component line-numbers> Just a test </editor-component>