# WidgetFlow API


`WidgetFlow` is a marimo display helper rather than an AnyWidget. It lays live widgets (or any renderable: charts, images, `mo.stat`, ...) out as a layered DAG in the style of FormulaDAG. You pass the widgets and the arrows between them as pairs of the same objects. You can also skip the edge list: `WidgetFlow.from_widgets([...])` reads the edges off marimo's dataflow graph and captions each widget with its variable name. The widgets stay live and reactive, because the flow only arranges references to them.


The layout is in your hands where it matters. Edges take labels, colours, dashes and explicit `exit`/`enter` ports, and ported arrows route around the other widgets. `beside` puts a widget next to the one it feeds, `layers` pins a widget to a later layer, and `align` packs every layer onto one shared grid, so a chain of widgets down a column gets straight arrows. `notes` hang an explanatory note beside a widget.


Parts of the flow can be hidden and brought back. Widgets in `collapsible` get a hover button that folds them to a pill showing their caption. `groups` draw a dashed frame whose tab folds a whole stretch of the flow into one pill, and the arrows in and out of the group re-aim at the pill. Folding happens in the browser, so nothing is laid out again and every widget keeps its state. Nest one `WidgetFlow` inside another to treat a sub-flow as a single node.


See also: WidgetDAG for a simpler column layout, FormulaDAG for formulas wired by `\use{name}`, and Hint for a single arrow from a note to a widget.


Lay live widgets out as a DAG, in the style of `FormulaDAG`.


Pass the widgets (or any renderable: charts, images, `mo.stat`, ...) as a list, and the arrows between them as pairs of those same objects. The widgets stay live and reactive; this only arranges references to them. To skip the edge list, `WidgetFlow.from_widgets` reads the arrows off marimo's own dataflow graph.


This is a marimo-only display helper: the arrow overlay reaches into marimo's rendered DOM, so it does not work in plain Jupyter.



Widgets are referred to by the objects themselves, so options that name a widget take `(widget, value)` pairs rather than dicts: charts and marimo UI elements can't be dict keys.


The look is tweakable from CSS: `--wf-edge`, `--wf-note`, `--wf-ink`, `--wf-layer-gap` and `--wf-node-gap` on the `.wf` root.

 Example

```
WidgetFlow(
    [n_points, noise, data_chart, degree, fit_chart],
    edges=[
        (n_points, data_chart),
        (noise, data_chart, "σ"),
        (data_chart, fit_chart, {"label": "x, y", "color": "#c2410c"}),
        (degree, fit_chart, {"enter": "right"}),
    ],
    notes=[(noise, "std of the gaussian noise")],
)
```


Left-align the layers and put `degree` right of the chart it feeds:


```
WidgetFlow.from_widgets(
    [n_points, noise, data_chart, degree, fit_chart],
    align="left",
    beside=[(degree, fit_chart)],
)
```


Let the data chart fold away, and fold the fitting step as a whole, starting folded:


```
WidgetFlow.from_widgets(
    [n_points, noise, data_chart, degree, fit_chart],
    collapsible=[data_chart],
    groups=[("fit", [degree, fit_chart], "collapsed")],
)
```

  Source code in `wigglystuff/widget_flow.py`

```
def __init__(
    self,
    nodes,
    edges,
    *,
    direction="down",
    notes=None,
    ports=None,
    labels=False,
    layers=None,
    beside=None,
    align="center",
    collapsible=None,
    collapsed=None,
    groups=None,
    theme="auto",
):
    if direction not in DIRECTIONS:
        raise ValueError(f"direction must be one of {DIRECTIONS}, got {direction!r}.")
    if align not in ALIGNS[direction]:
        raise ValueError(
            f"with direction={direction!r}, align must be one of "
            f"{ALIGNS[direction]}, got {align!r}."
        )
    if theme not in ("auto", "light", "dark"):
        raise ValueError("theme must be 'auto', 'light', or 'dark'.")
    self.nodes = list(nodes)
    self.direction = direction
    self.align = align
    self.theme = theme
    self._key = {}
    for i, obj in enumerate(self.nodes):
        if id(obj) in self._key:
            raise ValueError(f"nodes[{i}] appears more than once in nodes.")
        self._key[id(obj)] = f"n{i}"

    # edges and their options, keyed "nA->nB"
    self._edges = []
    opts = {}
    for e in edges:
        if len(e) not in (2, 3):
            raise ValueError("each edge must be (src, dst) or (src, dst, label_or_opts).")
        s, d = self._key_of(e[0], "edge"), self._key_of(e[1], "edge")
        if (s, d) in self._edges:
            raise ValueError(f"edge {self._name(s, d)} is given more than once.")
        self._edges.append((s, d))
        if len(e) == 3 and e[2] is not None:
            opts[f"{s}->{d}"] = self._edge_opts(e[2], self._name(s, d))
    _check_acyclic(
        list(self._key.values()), self._edges, describe=lambda k: f"nodes[{k[1:]}]"
    )

    # beside: {widget key: anchor key}, in the order given, and the
    # widgets that go before their anchor rather than after it
    self.beside = {}
    self._before = set()
    for entry in beside or []:
        if len(entry) not in (2, 3):
            raise ValueError(
                "each beside entry must be a (widget, anchor) pair or a "
                '(widget, anchor, "before"/"after") triple.'
            )
        w, a = self._key_of(entry[0], "beside"), self._key_of(entry[1], "beside")
        side = entry[2] if len(entry) == 3 else "after"
        if side not in ("before", "after"):
            raise ValueError(f'beside side must be "before" or "after", got {side!r}.')
        if w == a:
            raise ValueError(f"nodes[{w[1:]}] can't be placed beside itself.")
        if w in self.beside:
            raise ValueError(f"nodes[{w[1:]}] appears in beside more than once.")
        self.beside[w] = a
        if side == "before":
            self._before.add(w)
    for w, a in self.beside.items():
        if a in self.beside:
            raise ValueError(
                f"nodes[{a[1:]}] is an anchor in beside but is itself placed "
                "beside another widget; anchor every widget on one that isn't."
            )
    # a beside widget shares its anchor's layer, so for layering the two
    # are one node; a path anchor -> ... -> widget makes that impossible
    try:
        _check_acyclic(
            [k for k in self._key.values() if k not in self.beside],
            self._layer_edges(),
            describe=lambda k: f"nodes[{k[1:]}]",
        )
    except ValueError:
        raise ValueError(
            "beside puts a widget in its anchor's layer, but the edges connect "
            "the two through other widgets, so one must sit above the other."
        ) from None

    for p in ports or []:
        if len(p) != 3:
            raise ValueError("each port must be a (src, dst, opts) triple.")
        s, d = self._key_of(p[0], "port"), self._key_of(p[1], "port")
        if (s, d) not in self._edges:
            raise ValueError(f"port given for an arrow that isn't drawn ({self._name(s, d)}).")
        opts.setdefault(f"{s}->{d}", {}).update(self._edge_opts(p[2], self._name(s, d)))
    self.edges = [(self.nodes[int(s[1:])], self.nodes[int(d[1:])]) for s, d in self._edges]

    self.edge_labels, self.edge_styles, self.ports = {}, {}, {}
    default_exit, default_enter = _DEFAULT_SIDES[direction]
    for key, o in opts.items():
        if o.get("label") is not None:
            self.edge_labels[key] = str(o["label"])
        style = {k: o[k] for k in ("color", "dashed") if o.get(k)}
        if style:
            self.edge_styles[key] = style
        ends = {k: o[k] for k in ("exit", "enter") if k in o}
        # an end on its default side with no position is no port at all:
        # the arrow is drawn like any other
        if ends.get("exit") == {"side": default_exit, "at": None}:
            del ends["exit"]
        if ends.get("enter") == {"side": default_enter, "at": None}:
            del ends["enter"]
        if ends:
            self.ports[key] = ends
    # an arrow between a beside widget and its anchor runs within one
    # layer, so it always takes the freely routed path, between the
    # sides that face each other unless its opts named others
    for s, d in self._edges:
        if self.beside.get(s) == d:
            w, sides = s, _FACING[direction]
        elif self.beside.get(d) == s:
            w, sides = d, _FACING[direction][::-1]
        else:
            continue
        if w in self._before:
            sides = sides[::-1]
        key = f"{s}->{d}"
        given = {k: v for k, v in opts.get(key, {}).items() if k in ("exit", "enter")}
        self.ports[key] = {
            "exit": given.get("exit", {"side": sides[0], "at": None}),
            "enter": given.get("enter", {"side": sides[1], "at": None}),
        }

    self.notes = {}
    for obj, text in notes or []:
        k = self._key_of(obj, "note")
        if k in self.notes:
            raise ValueError(f"nodes[{k[1:]}] has more than one note.")
        self.notes[k] = text

    if labels is True:
        names = self._globals_names()
        self.labels = {self._key[i]: n for i, n in names.items()}
    elif labels is False or labels is None:
        self.labels = {}
    else:
        self.labels = {self._key_of(o, "label"): str(t) for o, t in labels}

    self.layers = {}
    for obj, n in layers or []:
        if not isinstance(n, int) or n < 0:
            raise ValueError(f"layers values must be non-negative ints, got {n!r}.")
        k = self._key_of(obj, "layers")
        if k in self.beside:
            raise ValueError(
                f"nodes[{k[1:]}] is placed beside another widget, so it takes "
                "that widget's layer; pin the anchor in layers instead."
            )
        self.layers[k] = n

    self.collapsed = {self._key_of(o, "collapsed") for o in collapsed or []}
    self.collapsible = {self._key_of(o, "collapsible") for o in collapsible or []}
    self.collapsible |= self.collapsed

    # groups: {"g0": {"label": ..., "members": [keys in node order]}}; a
    # folded group starts out in self.collapsed under its own key
    self.groups = {}
    grouped = {}
    for i, entry in enumerate(groups or []):
        if len(entry) not in (2, 3) or (len(entry) == 3 and entry[2] != "collapsed"):
            raise ValueError(
                'each group must be a (label, widgets) pair or a '
                '(label, widgets, "collapsed") triple.'
            )
        label, members = str(entry[0]), {self._key_of(o, "group") for o in entry[1]}
        if not members:
            raise ValueError(f"group {label!r} has no widgets.")
        for k in members:
            if k in grouped:
                raise ValueError(
                    f"nodes[{k[1:]}] is in both group {grouped[k]!r} and group {label!r}."
                )
            grouped[k] = label
        # folding swaps the group for one pill, which only works if no
        # outside widget sits on a path between two of its widgets
        between = (self._reach(members, up=False) & self._reach(members, up=True)) - members
        if between:
            k = min(between, key=lambda k: int(k[1:]))
            raise ValueError(
                f"group {label!r} must include nodes[{k[1:]}]: it sits on a path "
                "between two of the group's widgets."
            )
        g = f"g{i}"
        self.groups[g] = {
            "label": label,
            "members": sorted(members, key=lambda k: int(k[1:])),
        }
        if len(entry) == 3:
            self.collapsed.add(g)
```


## downstream


```
downstream(widget)
```


Every node `widget` feeds, directly or not, in node order.

 Source code in `wigglystuff/widget_flow.py`

```
def downstream(self, widget):
    """Every node ``widget`` feeds, directly or not, in node order."""
    return self._lineage(widget, up=False)
```


## from_widgets `classmethod`


```
from_widgets(widgets, *, labels=True, **kwargs)
```


Build a `WidgetFlow` whose arrows come from marimo's dataflow graph.


One widget points at another when the cell defining the second depends on the cell defining the first (transitively reduced, so a chain `a -> b -> c` gets no shortcut `a -> c`). Each widget is captioned with its variable name unless you pass `labels=False` or a dict. Every other keyword is passed to `WidgetFlow`.


```
WidgetFlow.from_widgets([paint, angle, kernel, conv], direction="right")
```


This needs each widget to be a top-level variable in its own cell: marimo's graph is cell-level, so two variables computed in one cell can't be ordered, and inline expressions aren't variables at all. For those, pass `edges` to `WidgetFlow` yourself. Requires a running marimo kernel.

 Source code in `wigglystuff/widget_flow.py`

```
@classmethod
def from_widgets(cls, widgets, *, labels=True, **kwargs):
    """Build a ``WidgetFlow`` whose arrows come from marimo's dataflow graph.

    One widget points at another when the cell defining the second depends
    on the cell defining the first (transitively reduced, so a chain
    ``a -> b -> c`` gets no shortcut ``a -> c``). Each widget is captioned
    with its variable name unless you pass ``labels=False`` or a dict.
    Every other keyword is passed to ``WidgetFlow``.

    ```python
    WidgetFlow.from_widgets([paint, angle, kernel, conv], direction="right")
    ```

    This needs each widget to be a top-level variable in its own cell:
    marimo's graph is cell-level, so two variables computed in one cell
    can't be ordered, and inline expressions aren't variables at all. For
    those, pass ``edges`` to ``WidgetFlow`` yourself. Requires a running
    marimo kernel.
    """
    edges, names = _infer_edges(list(widgets), caller="WidgetFlow.from_widgets")
    if labels is True:
        labels = [(w, names[id(w)]) for w in widgets]
    return cls(widgets, edges, labels=labels, **kwargs)
```


## upstream


```
upstream(widget)
```


Every node that feeds `widget`, directly or not, in node order.

 Source code in `wigglystuff/widget_flow.py`

```
def upstream(self, widget):
    """Every node that feeds ``widget``, directly or not, in node order."""
    return self._lineage(widget, up=True)
```


## Folding parts of the flow


```
WidgetFlow(
    [drawing, X, noise, X_noisy, Z, weights, Y, angle, plots],
    edges=[...],
    collapsible=[drawing, plots],              # hover button on these
    groups=[("Z → Y", [Z, weights, Y, angle])],  # dashed frame + tab
    collapsed=[plots],                         # start folded
)
```


A group must include every widget on a path between two of its own widgets, because the pill replaces them all. Arrows that end up joining the same pair of nodes once the group folds stay separate when they land in different spots.


## Notes


`WidgetFlow` is a marimo-only display helper. Its arrow overlay reaches into marimo's rendered DOM to draw in the same coordinate space as the widgets, so it does not work in plain Jupyter. In Jupyter it raises a clear error instead of printing a silent repr.
