Skip to content

Clean up widget authoring experience - #31

Draft
batpad wants to merge 2 commits into
mainfrom
widget-authoring-api
Draft

batpad wants to merge 2 commits into
mainfrom
widget-authoring-api

Conversation

@batpad

@batpad batpad commented Dec 3, 2026

Copy link
Copy Markdown
Member

Companion PR to developmentseed/myst-anywidget-static-export#5

The overall aim is to arrive at an easy-to-understand lightweight structure and API for widget authors, whether its simple widgets defined inline in a notebook, or more complex widgets. The aim is to remove all copy-paste boilerpalte and present a clean API.

I worked through the definition of the user API for widget construction with Claude, and then worked backwards from that for changes in the static export plugin and then here.

AI summary of changes:

Custom widgets without copy-paste: a JS runtime in the wheel, mw.link, extend, theming everywhere

Why

Writing a widget outside this package was painful:

  • The shared JS helpers in packages/core shipped nowhere, so every custom app copied
    about 150 lines of them, and the copies drifted.
  • Each app then added its own workarounds: polling loops, map-height fixes, hand-rolled
    camera sync, and re-implemented button and card CSS.
  • Binder did not work in a live kernel, layout containers ignored theme=, and the
    docs contradicted the code in several places.

This PR gives notebook authors a small, importable runtime and removes the workarounds
at their source. It keeps the anywidget model and vocabulary: plain
export default { render }, BaseWidget, _esm, _css, traitlets and jslink /
jsdlink all work unchanged.

What an author writes now

class Counter(mw.BaseWidget):
    _esm = """
    import { widget } from "manywidgets";

    export default widget(({ model, el }) => {
      const btn = document.createElement("button");
      btn.className = "mw-button";
      btn.onclick = () => model.set("value", model.get("value") + 1);
      const draw = () => { btn.textContent = `count is ${model.get("value")}`; };
      model.on("value", draw);
      draw();
      el.append(btn);
    });
    """
    value = traitlets.Int(0).tag(sync=True)

No Node, no build step, no vendored file. The same code runs in JupyterLab and in a
static export.

What changes

A JS runtime, delivered inside the wheel

  • import { … } from "manywidgets" works in an inline _esm string or a .js file.
    BaseWidget resolves the import when it loads _esm, including on hot reload. A
    widget that does not import "manywidgets" is passed to anywidget untouched.
  • The runtime is inlined into the widget's JS and installed once per page per version,
    so exported pages stay self-contained and need no extra network request.
  • widget(render) or widget({ initialize, render }):
    • model.set saves; model.on("value", fn) is removed on cleanup.
    • theme= / style= are applied automatically.
    • A JS error shows as a readable box in the cell.
  • model.widget("trait") / model.widgets("trait") reach other widgets through one
    small handle: get, set, on, send, mount(el, { fill: true }).
  • extend(Base, { … }) with import Base from "manywidgets:super" extends a parent
    class's JS. Built-ins publish hooks: Stat.format, Chart.configure,
    Table.formatCell, GeoMap.onMap.
  • lonboard helpers: flyTo, syncCameras, lngLatAt, pointAt.
  • mw-* classes (mw-button, mw-card, mw-chip, mw-switch, mw-tile, …) style a
    custom widget like the built-ins.
  • The same code builds as the npm package manywidgets (packages/core) for authors
    who want TypeScript or npm dependencies. It is not published yet.

Python

  • mw.link((src, "field"), (dst, "field.or.path"), js=None, both=False): a browser-side
    link with a JavaScript transform or a nested target. It works live and static and does
    not need to be displayed.
  • mw.dev() turns on hot reload from inside a notebook.
  • mw.asset is public.
  • CLI: manywidgets new widget <name> [--dir DIR] [--bundled] and
    manywidgets doctor (checks the plugin pinned in myst.yml).

Built-in widgets

  • Every built-in is rewritten on widget().
  • No more polling: LayerToggle, LayerFilter, FilterBinder and MapCompare react to
    change events instead of re-applying state every 50–100 ms.
  • LayerToggle, LayerFilter and FilterBinder work without being displayed.
  • MapCompare syncs cameras with syncCameras and sizes its maps with
    mount(el, { fill: true }) instead of !important CSS.

Bugs fixed

  • Binder failed in a live kernel with "widget model not found".
  • Row, Column, Grid and GridItem ignored theme= / style=; they now apply them
    and cascade to children.
  • A token set in a custom widget's own _css lost to the built-in defaults.
  • grid_item/dist/widget.js was missing from the wheel's ensured-targets.
  • Docs claimed space-separated event names fail and save_changes() needs wrapping in
    static export; neither is true.

Behaviour changes to be aware of

Change Who notices
An explicit light_theme() / dark_theme() / radix_theme() now overrides the page's colours Sites where these themes previously had little visible effect
mount() renders the child into a wrapper element CSS such as .slot > .child
FilterBinder and link status lines have new text and the mw-status class CSS or tests matching the old text
The Toggle / LayerToggle thumb is white Custom themes that relied on the surface colour
A subclass using manywidgets:super has its _css appended to the parent's Subclasses that expected to replace it
Each built-in's JS grew by about 14 kB (the runtime is inlined) Page weight

Deprecated and removed

  • Deprecated, still working: Binder (use mw.link; emits a DeprecationWarning),
    and the JS helpers safeSaveChanges, onChanges and resolveModel (one console
    warning per page).
  • Removed: getStaticRegistry and findAllInRegistry (internal), and
    _myst_child_traits from the built-in containers.

Upgrading

UPGRADING.md (new) gives each step as before → after with a search pattern, and
CHANGELOG.md (new) has the full list. In short:

  • Install the new version and re-execute notebooks. Pages already exported keep the
    runtime they were built with.
  • Static export needs myst-anywidget-static-export v0.4.0 (host.protocol 1).
    With an older plugin, widgets still render in a reduced mode and the console says to
    update; anything that is not displayed (mw.link with js= or a dotted path,
    undisplayed LayerToggle / LayerFilter / FilterBinder) does not run there.
  • A live kernel needs nothing.
  • Custom widgets with a vendored copy of the old helpers keep working; deleting the copy
    is optional in this release.

Testing

  • npm test: 235 passing. npm run typecheck: clean.
  • pytest: 214 passed, 1 skipped.
  • Browser checks with Playwright, in live JupyterLab and in static builds against the
    plugin's v0.4.0 branch: inline widget, mw.link (transform, nested path, undisplayed),
    widget references with set / on / send / mount, extend, theme cascade, and
    the reduced mode against plugin v0.3.2.
  • The Python samples in the new guides were run live and static.
  • The three full-screen apps in manywidgets-playground were migrated to this API as the
    acceptance test: app.js shrank by 52–66% with the same behaviour.
  • Not tested: VS Code, and the --bundled scaffold in a browser.

Docs

  • docs/guides/create-your-own-widget.md is rewritten as a notebook-first guide.
  • New docs/guides/theming.md and docs/guides/contributing-a-widget.md (the in-package
    guide that used to live at the first path).
  • linking.md, static-export.md, lonboard.md, the README and the agent skill are
    updated; the skill gains a theming reference.

Known gaps

  • MapCompare's internal camera sync cannot be paused from outside. Flying both maps at
    once works, but there is no supported control for it.
  • handle.on on a lonboard layer trait stopped firing in one live probe; cause
    unconfirmed. Writes always work.
  • Buttons render with a 2px radius in JupyterLab regardless of tokens; untraced, may
    predate this PR.
  • The docs, the skill and manywidgets doctor point at plugin v0.4.0, which is not
    released yet. docs/myst.yml still pins v0.3.2 and should move at release.

Before release

  • Depends on the plugin PR (myst-anywidget-static-export, v0.4.0); release that first.
  • The version is not bumped in this PR.
  • Publish packages/core to npm as manywidgets (the name is unclaimed) so --bundled
    works without a local install.

This is a draft. There's a bunch of work to do here to cleanup, document the clean end-user interface, migrate all examples in manywidgets-playground and test everything. This will be a release with breaking changes, but I think it solves most of the major issues that required awkward hacks on the widget authoring side.

To complete this, I'll also publish a manywidgets package to npm so that it can be imported directly for frontend widget definitions (if using it inline in Python, one can also import it via the Python module).

I still need to parse a bunch of these changes - creating the PR as draft and then I'll work on whittling things down, etc. over the next days.

cc @zacdezgeo @dzole0311

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant