Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ package-lock.json.bak
# Built JS bundles (regenerated by `npm run build`; shipped in the wheel via hatch).
# ** so nested widgets (e.g. lonboard/<name>/dist/) are ignored too.
src/manywidgets/**/dist/
# The npm build of the JS runtime (packages/core -> the `manywidgets` package).
packages/*/dist/

# Python
__pycache__/
Expand Down
133 changes: 133 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Changelog

All notable changes to manywidgets. Upgrade steps for each release are in
[UPGRADING.md](UPGRADING.md).

## Unreleased

### Added

- **A JS runtime for custom widgets, with no build step.** A widget's `_esm`
(inline string or file) can now `import { widget, extend, applyTheme,
getWidget, mountChild } from "manywidgets";`. `BaseWidget` resolves the import
when it loads `_esm`, including on hot reload. A widget that does not import
`"manywidgets"` is passed to anywidget unchanged.
- `widget(render)`: `model.set` saves, `model.on("value", fn)` is removed on
cleanup, `model.widget("trait")` / `model.widgets("trait")` reach other
widgets (`get`, `set`, `on`, `send`, `mount`), `ctx.theme` resolves theme
tokens for canvas code, `theme=` / `style=` are applied automatically, and a
JS error shows as a readable box in the cell.
- `mount(el, { fill: true })` makes a mounted child (a map, a chart) fill its
mount element; no height workarounds.
- `extend(Base, { … })` with `import Base from "manywidgets:super"` extends
the parent class's JS. Hooks the built-ins publish: `Stat.format(value)`,
`Chart.configure(config)` (tick callbacks, plugins and other functions JSON
options cannot hold), `Table.formatCell(value, column, row)` and
`GeoMap.onMap(map)` (the MapLibre map, once loaded).
- `widget({ initialize, render })`: `initialize` runs once per widget whether
or not it is displayed, for widgets that connect other widgets.
- lonboard helpers: `flyTo(map, { longitude, latitude, zoom, duration })`,
`syncCameras(maps)` (returns a stop function with `.pause(ms)`),
`lngLatAt(viewState, x, y, width, height)` and
`pointAt(viewState, lng, lat, width, height)`.
- `mw-*` classes (`mw-button`, `mw-card`, `mw-chip`, `mw-switch`, `mw-tile`,
`mw-input`, `mw-label`, `mw-row`, `mw-stack`, `mw-muted`, `mw-status`) style custom
widgets like the built-ins.
- **`mw.link((src, "field"), (dst, "field.or.path"), js=None, both=False)`**:
browser-side links with a JavaScript transform or a nested target. Works for
any ipywidgets/anywidget endpoints and does not need to be displayed.
- **`mw.dev()`**: turns on hot reload for file-based widgets from inside a
notebook. New `watchfiles` dependency in the `dev` extra.
- **`mw.asset`** is public (`_esm = mw.asset(__file__, "gauge.js")`).
- **CLI**: `manywidgets new widget <name> [--dir DIR] [--bundled]` and
`manywidgets doctor [path]` (checks the static-export plugin pinned in
`myst.yml`).
- Kit: `mw-range` and `mw-tooltip` classes; tokens `--mw-toggle-thumb-color`,
`--mw-chip-pressed-bg/-color/-border`, `--mw-label-color/-size/-weight/-transform/-spacing`,
`--mw-tooltip-bg/-color`.
- `light_theme()`, `dark_theme()` and `radix_theme()` accept `Theme` fields as
keywords (`dark_theme(accent="green", color_surface="#101211")`).
- `manywidgets doctor` says that `Fullscreen` does not open with a plugin older
than v0.3.2.
- `show_status=False` on `FilterBinder`, `Binder` and the `Link` widget hides
the status line.
- `--mw-widget-margin` token: the space around every built-in widget (default
`10px 0`).
- Docs: a notebook-first [Create your own widget](docs/guides/create-your-own-widget.md)
guide, a [Theming](docs/guides/theming.md) guide, and
[Contributing a widget](docs/guides/contributing-a-widget.md). Every widget
page lists the widget's CSS class names; the agent skill is rewritten around
the same material and gains a theming reference.
- The runtime is also built as the npm package `manywidgets`
(`packages/core`, ESM + type declarations). Not published yet.

### Fixed

- A token set in a custom widget's own `_css` lost to the built-in defaults
when the widget was top-level; the defaults now have zero specificity.
- `ctx.theme.color(...)` returned nothing on the first draw in a live notebook
(the view is not attached yet); `theme.on(fn)` now also fires once on attach.

- `Binder` did not work in a live kernel ("widget model not found"): the browser
looked the widgets up by `widget_id`, which a live widget manager does not
know. Links now reference widgets by model id.
- `Row`, `Column`, `Grid` and `GridItem` ignored `theme=` / `style=`. They now
apply them, and the theme cascades to their children (live too: a child view
is themed by its container even though it renders before it is attached).
- `grid_item/dist/widget.js` was missing from the wheel build's
`ensured-targets`.
- Docs said space-separated event names fail and `save_changes()` must be
wrapped in static export; both have worked since plugin v0.2.0.

### Changed

- **An explicit theme beats the page.** `light_theme()` / `dark_theme()` /
`radix_theme()` no longer defer their colours to the page's `--myst-color-*`
/ `--jp-*` variables, so they have a visible effect on MyST sites and in
JupyterLab. Widgets with no theme, or a partial `Theme(...)`, still follow
the page. See UPGRADING.md.
- **`mount()` / `mountChild()` render the child into a wrapper element** inside
the element you pass, so a child can no longer replace that element's classes
or set theme variables on it.
- The `Toggle` / `LayerToggle` thumb is white (`--mw-toggle-thumb-color`)
instead of the surface colour.
- **Every built-in widget is written with the runtime** (`widget()`): listeners,
timers and observers are removed when a view closes, and the per-widget
static-export workarounds are gone.
- **`LayerToggle`, `LayerFilter` and `FilterBinder` work without being
displayed** (static export: plugin v0.4.0+). They do their work in
`initialize`; their UI is optional.
- **No more polling.** `LayerToggle`, `LayerFilter`, `FilterBinder` and
`MapCompare` re-applied their state every 50–100 ms; they now react to change
events.
- **`MapCompare`** keeps its maps in step with `syncCameras` (zero-duration
fly-to messages driven by `view_state` changes), sizes them with
`mount(el, { fill: true })` instead of `!important` CSS, and writes `position`
while the divider is dragged.
- `LayerToggle`, `LayerFilter` and `MapFlyer` are drawn with theme tokens and
follow `theme=` / `style=`.
- `FilterBinder` and link status lines: new text (`filter: …`, `link: …`), the
`mw-status` class, no inline styles. See UPGRADING.md for the before/after.
- `_myst_child_traits` is removed from the built-in containers.
- `theme.on(fn)` also calls `fn` once when the widget is first attached.
- Each built-in's bundled JS grew by about 14 kB (the runtime is inlined).

- The docs site pins `myst-anywidget-static-export` v0.3.2; the `Fullscreen`
workaround for the plugin's registry key (fixed in v0.3.2) is removed.
`Fullscreen` deep links (`?fullscreen=…`) need plugin v0.3.2 or later.
- A subclass that extends its parent's JS (`manywidgets:super`) has its `_css`
appended to the parent's rather than replacing it.

### Deprecated

- `Binder`: use `mw.link`. It keeps working (as a thin wrapper over the same
code) and emits a `DeprecationWarning`.
- JS helpers `safeSaveChanges`, `onChanges` and `resolveModel` remain as thin
aliases and log one console warning per page when called. Use
`model.save_changes()`, `model.on("a b", fn)` and `model.widget("trait")` /
`getWidget(...)`.

### Removed

- `getStaticRegistry` and `findAllInRegistry` from `@manywidgets/core`
(internal; the runtime now reaches a static page only through `host`).
103 changes: 75 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ render statically (no kernel) via the
[`myst-anywidget-static-export`](https://github.com/developmentseed/myst-anywidget-static-export)
MyST plugin.

> **Status:** early but feature-complete for v1 — `Chart`, input controls (`Slider`,
> `RangeSlider`, `Dropdown`, `Toggle`, `Button`, `NumberInput`), value displays
> (`Stat`, `NumberDisplay`, `Text`), `Table`, `GeoMap` (a MapLibre map with GeoJSON,
> XYZ-tile and client-styled grid-raster layers), layout containers (`Row`,
> `Column`, `Grid`), the `Binder` linking primitive, and optional lonboard interop
> (`LayerToggle`, `FilterBinder`, `LayerFilter`).
> **Status:** early. Widgets: `Chart`, input controls (`Slider`, `RangeSlider`,
> `Dropdown`, `Toggle`, `Button`, `NumberInput`), value displays (`Stat`,
> `NumberDisplay`, `Text`, `Legend`), `Table`, `GeoMap` (a MapLibre map with
> GeoJSON, XYZ-tile and client-styled grid-raster layers), layout (`Row`,
> `Column`, `Grid`, `GridItem`, `Fullscreen`), linking (`mw.link`), optional
> lonboard interop (`LayerToggle`, `LayerFilter`, `FilterBinder`, `MapFlyer`,
> `MapCompare`), and a small JS runtime for writing your own widgets in a
> notebook with no build step.

## Install

Expand All @@ -25,8 +27,8 @@ pip install "manywidgets[lonboard]"
## Quick start

```python
from manywidgets import Chart, Slider, Binder
import numpy as np
from manywidgets import Chart

chart = Chart(title="Demo", x_label="x", y_label="y", height=320)
chart.add_series(x=np.linspace(0, 10, 100), y=np.sin(np.linspace(0, 10, 100)), name="sin")
Expand All @@ -42,31 +44,69 @@ from manywidgets import (
Stat, NumberDisplay, Text, Legend, # value displays
Table, # sortable, selectable table of records
GeoMap, GridLayer, # MapLibre map: GeoJSON, XYZ tiles, quantized grid rasters
Row, Column, Grid, # layout (arrange + keep children linked)
Binder, # linking with transforms / nested paths
Row, Column, Grid, GridItem, Fullscreen, # layout (arrange + keep children linked)
link, # linking with transforms / nested paths
BaseWidget, asset, dev, # for your own widgets
themes, # theme= values
)

# Optional lonboard interop (pip install "manywidgets[lonboard]")
from manywidgets.lonboard import LayerToggle, FilterBinder, LayerFilter
from manywidgets.lonboard import LayerToggle, LayerFilter, FilterBinder, MapFlyer, MapCompare
```

## Linking widgets

Two complementary tools — see [`docs/guides/linking.md`](docs/guides/linking.md):
Links run in the browser, so they work live and in a static export. See
[`docs/guides/linking.md`](docs/guides/linking.md).

```python
import manywidgets as mw
from ipywidgets import jsdlink

# 1. jslink / jsdlink — the canonical, kernel-free pass-through link.
slider = Slider(label="Amplitude", min=0, max=5, value=1)
jsdlink((slider, "value"), (chart, "title")) # browser-side, works live + static
slider = mw.Slider(label="Height", min=2, max=6, value=3)

# 2. Binder — for transforms / nested paths jslink can't express.
Binder(source=slider, source_field="value",
target=chart, target_field="height",
multiplier=100, offset=200)
# same value: ipywidgets' jsdlink / jslink
jsdlink((slider, "value"), (mw.Stat(label="Height"), "value"))

# a computed value, or a nested target: mw.link (needs no display)
mw.link((slider, "value"), (chart, "height"), js="v * 100")
```

## Your own widgets

A widget of your own is a Python class and a few lines of JavaScript, written
in a notebook cell. No Node.js, no build step:

```python
import traitlets
import manywidgets as mw

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

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

Counter()
```

It links, themes, nests in layouts and exports statically like a built-in.
[`docs/guides/create-your-own-widget.md`](docs/guides/create-your-own-widget.md)
goes from this to files, folders (`manywidgets new widget gauge`), reaching
other widgets from JS, and extending a built-in widget
(`Chart.configure`, `GeoMap.onMap`, `Table.formatCell`, `Stat.format`).
Theming is in [`docs/guides/theming.md`](docs/guides/theming.md).

## Agent skill

manywidgets ships an [agent skill](src/manywidgets/skill/SKILL.md) so coding
Expand All @@ -85,16 +125,23 @@ per-widget API reference is generated from widget traits — never hand-edited.

## How it works / design

Every widget extends a thin `BaseWidget` (auto-assigns a stable `widget_id`) and
follows the TypeScript "golden example" structure: `src/index.ts` bundled by
esbuild into `dist/widget.js`, styling via the `_css` trait. Cross-widget
resolution and the static-export safety rules live once in a shared
`@manywidgets/core` TypeScript module that esbuild inlines into each widget.
Every widget extends a thin `BaseWidget` (a stable `widget_id`, `theme=` /
`style=`, and the `"manywidgets"` JS import) and is a plain anywidget. The
built-ins are TypeScript (`src/index.ts`, bundled by esbuild into
`dist/widget.js`) and are written with the same small runtime
(`packages/core`: `widget()`, `extend()`, `model.widget()`, `mount()`, theming)
that custom widgets import.

The package has **no code dependency** on the static-export plugin. The runtime
talks to an exported page through the documented `host` object the plugin
passes to each widget (`host.protocol` 1, plugin v0.4.0 or later); a single
compatibility path covers older plugins. `manywidgets doctor` checks the plugin
pinned in a `myst.yml`.

## Upgrading

This package has **no code dependency** on the static-export plugin — it just
follows the rules the plugin needs (wrap `save_changes`, never inject `<link>`
into the mount element, vanilla DOM, buffer-free core widgets, link via
`jslink`/`Binder`). The docs site references the plugin by release URL only.
See [UPGRADING.md](UPGRADING.md) for what to change between versions (including the
manywidgets ↔ static-export plugin compatibility table) and [CHANGELOG.md](CHANGELOG.md).

## Development

Expand Down Expand Up @@ -125,7 +172,7 @@ python -m ipykernel install --user --name manywidgets-venv
npm run docs:gen # generate docs/widgets/*.ipynb from each widget's doc.md
jupyter nbconvert --to notebook --execute --inplace docs/examples/*.ipynb docs/widgets/*.ipynb
cd docs && npx myst build --html && cd ..
npm run serve # serve over HTTP at http://localhost:8000 (NOT file://)
npm run serve # serve over HTTP at http://localhost:3030 (NOT file://)
```

> Serve the built site over HTTP — opening the HTML via `file://` breaks asset and
Expand Down
Loading
Loading