Live-Edit-Source
This example demonstrates how to create an interactive code editor with live evaluation and plotting. You'll see state management using Plot.initialState
, widget.state.update
, and Plot.onChange
, as well as live code evaluation using Python's exec
.
Callback function
Plot.dot
will render our samples as a scatter plot. We pass $state.thetas
and $state.samples
in columnar format.
(
initial_state
| Plot.onChange({"toEval": evaluate})
| Plot.html(
[
"form.!flex.flex-col.gap-3",
{
"onSubmit": js(
"e => { e.preventDefault(); $state.toEval = $state.source}"
)
},
samples_plot,
[
"textarea.whitespace-pre-wrap.text-[13px].lh-normal.p-3.rounded-md.bg-gray-100.flex-1.h-[300px].font-mono",
{
"rows": js("$state.source.split('\\n').length+1"),
"onChange": js("(e) => $state.source = e.target.value"),
"value": js("$state.source"),
"onKeyDown": js(
"(e) => { if (e.ctrlKey && e.key === 'Enter') { e.stopPropagation(); $state.toEval = $state.source } }"
),
},
],
[
"div.flex.items-stretch",
[
"button.flex-auto.!bg-blue-500.!hover:bg-blue-600.text-white.text-center.px-4.py-2.rounded-md.cursor-pointer",
{"type": "submit"},
"Evaluate and Plot",
],
[
"div.flex.items-center.p-2",
{
"onClick": lambda widget, _: widget.state.update(
{"source": initial_source}
)
},
"Reset Source",
],
],
]
)
)