Gallery · Two-way widgets

A dial the rest of the notebook can read

An anywidget dial built in a Python cell, shared as a notebook variable by one line, and read by C# as if it had always been one. Turn the dial and C# sees the new cutoff; write the variable and the dial moves.

threshold-dial.verso Python · C# · 13 cells Read-only preview Download

A dial the rest of the notebook can read

A widget is a control drawn in the browser with a kernel behind it. This one is a Python class carrying about eighty lines of JavaScript, and once it exists a single line shares its value with every other language in the notebook. A C# cell then reads that value as an ordinary variable, and writing the variable turns the dial.

This page is a recording of a run, so the dial redraws when you turn it and nobody is listening. Download the notebook for the half that talks back.

The widget is a Python class

The trait is the whole interface. value is an ordinary integer traitlet marked to synchronise, and the JavaScript beside it reads and writes that one name. Nothing here knows about the notebook yet.

[1]
codePython
1import anywidget
2import traitlets
3
4
5class Dial(anywidget.AnyWidget):
6 """A round control whose position is an ordinary traitlet."""
7
8 value = traitlets.Int(40).tag(sync=True)
9
10 _esm = """
11export default {
12 render({ model, el }) {
13 const SIZE = 176, MID = SIZE / 2, R = 62;
14 const LENGTH = 2 * Math.PI * R, SWEEP = 0.75, SPAN = 270;
15 const NS = "http://www.w3.org/2000/svg";
16
17 const svg = document.createElementNS(NS, "svg");
18 svg.setAttribute("viewBox", `0 0 ${SIZE} ${SIZE}`);
19 svg.setAttribute("width", SIZE);
20 svg.setAttribute("height", SIZE);
21 svg.setAttribute("role", "slider");
22 svg.setAttribute("tabindex", "0");
23 svg.setAttribute("aria-label", "Threshold");
24 svg.setAttribute("aria-valuemin", "0");
25 svg.setAttribute("aria-valuemax", "100");
26 svg.style.cssText = "display:block;margin:0 auto;touch-action:none;cursor:grab";
27
28 function arc(stroke) {
29 const ring = document.createElementNS(NS, "circle");
30 ring.setAttribute("cx", MID);
31 ring.setAttribute("cy", MID);
32 ring.setAttribute("r", R);
33 ring.setAttribute("fill", "none");
34 ring.setAttribute("stroke", stroke);
35 ring.setAttribute("stroke-width", "13");
36 ring.setAttribute("stroke-linecap", "round");
37 ring.setAttribute("transform", `rotate(135 ${MID} ${MID})`);
38 svg.appendChild(ring);
39 return ring;
40 }
41
42 const track = arc("var(--verso-border-default, #d6d9df)");
43 track.setAttribute("stroke-dasharray", `${LENGTH * SWEEP} ${LENGTH}`);
44 const filled = arc("var(--verso-accent-primary, #4f7cff)");
45
46 const reading = document.createElementNS(NS, "text");
47 reading.setAttribute("x", MID);
48 reading.setAttribute("y", MID + 4);
49 reading.setAttribute("text-anchor", "middle");
50 reading.setAttribute("fill", "var(--verso-fg-default, #22252b)");
51 reading.style.cssText = "font:600 36px system-ui,-apple-system,sans-serif";
52 svg.appendChild(reading);
53
54 const caption = document.createElementNS(NS, "text");
55 caption.setAttribute("x", MID);
56 caption.setAttribute("y", MID + 30);
57 caption.setAttribute("text-anchor", "middle");
58 caption.setAttribute("fill", "var(--verso-fg-muted, #71767f)");
59 caption.style.cssText = "font:11px system-ui,sans-serif;letter-spacing:.14em";
60 caption.textContent = "THRESHOLD";
61 svg.appendChild(caption);
62
63 function draw() {
64 const value = model.get("value");
65 filled.setAttribute("stroke-dasharray", `${LENGTH * SWEEP * value / 100} ${LENGTH}`);
66 reading.textContent = value;
67 svg.setAttribute("aria-valuenow", value);
68 }
69
70 function set(next) {
71 next = Math.round(Math.min(100, Math.max(0, next)));
72 if (next === model.get("value")) return;
73 model.set("value", next);
74 model.save_changes();
75 }
76
77 function fromPointer(event) {
78 const box = svg.getBoundingClientRect();
79 const x = event.clientX - box.left - box.width / 2;
80 const y = event.clientY - box.top - box.height / 2;
81 const degrees = Math.atan2(x, -y) * 180 / Math.PI;
82 set((Math.min(SPAN / 2, Math.max(-SPAN / 2, degrees)) + SPAN / 2) / SPAN * 100);
83 }
84
85 svg.addEventListener("pointerdown", function (event) {
86 svg.setPointerCapture(event.pointerId);
87 svg.style.cursor = "grabbing";
88 fromPointer(event);
89 });
90 svg.addEventListener("pointermove", function (event) {
91 if (svg.hasPointerCapture(event.pointerId)) fromPointer(event);
92 });
93 svg.addEventListener("pointerup", function () { svg.style.cursor = "grab"; });
94 svg.addEventListener("keydown", function (event) {
95 const step = { ArrowLeft: -1, ArrowDown: -1, ArrowRight: 1, ArrowUp: 1 }[event.key];
96 if (!step) return;
97 event.preventDefault();
98 set(model.get("value") + step * (event.shiftKey ? 10 : 1));
99 });
100
101 model.on("change:value", draw);
102 draw();
103 el.appendChild(svg);
104 }
105};
106"""
107
108
109dial = Dial()
110turned = []
111dial.observe(lambda change: turned.append(change["new"]), names="value")
112
113f"A dial sitting at {dial.value}, with nothing watching it yet."
✓completed
'A dial sitting at 40, with nothing watching it yet.'

One line shares it

#!bind takes an expression naming the object, the trait to follow, and the name to share it under. Nothing about the widget changes; the trait simply becomes a variable the whole notebook can see.

[2]
codePython
1#!bind dial.value as threshold
✓completed
'threshold' now follows dial.value. Any kernel can read it, and writing it moves the widget.

C# reads it as a variable

There is no bridge to write and no message to handle. threshold is in the shared variable store, so C# reads it the way it reads anything else.

[3]
codeC#
1var cutoff = Variables.Get<long>("threshold");
2
3var stations = new[]
4{
5 (Station: "Ridgeway", Reading: 71),
6 (Station: "Calder Fell", Reading: 48),
7 (Station: "Ostergaard", Reading: 93),
8 (Station: "Pine Hollow", Reading: 27),
9 (Station: "Bitterroot", Reading: 62),
10 (Station: "Kestrel Bay", Reading: 84),
11};
12
13stations.Where(station => station.Reading >= cutoff)
14 .Select(station => new { station.Station, station.Reading })
✓completed
WhereSelectArrayIterator<ValueTuple<String, Int32>, <>f__AnonymousType0#2<String, Int32>> (5 items)
StationReading
Ridgeway71
Calder Fell48
Ostergaard93
Bitterroot62
Kestrel Bay84

And writes it back

The same variable works in the other direction. Setting it from C# moves the dial and runs the observe callback the Python cell registered, which is the part that makes this a control rather than a reading.

[4]
codeC#
1Variables.Set("threshold", 62L);
2
3"The dial is at 62 now, and Python heard about it."
✓completed
The dial is at 62 now, and Python heard about it.

Here it is

The dial below was drawn after that C# cell ran, which is why it reads 62 rather than the 40 it was built with. turned is the record the observe callback kept, and it holds one entry: a value settles after a single trip in whichever direction it started, so nothing bounces between the two sides.

[5]
codePython
1print("dial.value:", dial.value)
2print("every value the trait was set to:", turned)
3
4dial
✓completed
dial.value: 62
every value the trait was set to: [62]
[6]
codePython
1#!bind --list
✓completed
Widget traits shared as variables:
  threshold  <-  dial.value

Make it yours

Change value = traitlets.Int(40) to traitlets.Float and the dial reports decimals, because the trait is the only thing that decides what the value is. Add a second trait and bind that too. Or leave the dial alone and bind a trait of something you already have: what #!bind asks of an object is whether it has a trait by that name and whether it will call back when the trait changes, so any traitlets.HasTraits object works.

A trait holding another widget is refused, which covers layout and style, and so is a value too large to keep re-sending on every turn of the dial. #!bind --remove threshold stops the two following each other and leaves the variable holding the value it last had.

Run it yourself

Nothing on this page is executable; the outputs were baked in by a real run. Download the notebook and it runs anywhere Verso does: VS Code, the browser, or the terminal.

dotnet tool install --global Verso.Cli
verso serve threshold-dial.verso

What this shows

An anywidget dial built in a Python cell, shared as a notebook variable by one line, and read by C# as if it had always been one. Turn the dial and C# sees the new cutoff; write the variable and the dial moves.

Every language in this notebook reads and writes the same variable store, so a value produced in one cell is simply there in the next, whatever the language.