A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
mo.ui.altair_chart (#162)
Myles Scolnick359cd8834e16
diff --git a/docs/_static/css/custom.css b/docs/_static/css/custom.cssindex 798de3aa5d..91c8a0a878 100644--- a/docs/_static/css/custom.css+++ b/docs/_static/css/custom.css@@ -56,6 +56,11 @@ dt em.sig-param:last-of-type::after {white-space: pre;}+.sig-param,+.sig-return-typehint {+ font-size: 0.875rem;+}+.sidebar-logo-container {height: 150px;}diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.mdindex 379ff0ba8c..92d5b3a5dc 100644--- a/docs/api/inputs/index.md+++ b/docs/api/inputs/index.md@@ -9,6 +9,7 @@batchbuttoncheckbox+ chartdatedictionarydropdown@@ -37,6 +38,7 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.marimo.ui.batchmarimo.ui.buttonmarimo.ui.checkbox+ marimo.ui.chartmarimo.ui.datemarimo.ui.dictionarymarimo.ui.dropdowndiff --git a/docs/api/plotting.md b/docs/api/plotting.mdindex 48b1e6f751..e57e9cb1fe 100644--- a/docs/api/plotting.md+++ b/docs/api/plotting.md@@ -1,37 +1,20 @@# Plotting-marimo supports all major plotting libraries, including matplotlib, seaborn,-plotly, and altair. Just import your plotting library of choice and use it+marimo supports most major plotting libraries, including Matplotlib, Seaborn,+Plotly, and Altair. Just import your plotting library of choice and use itas you normally would.-```{admonition} Reactive plots coming soon!-:class: admonition+For more information about plotting, see the [plotting guide](../guides/plotting.md).-We're working on a way to let you select data in a plot with your mouse, and-have your selection automatically passed to Python — stay tuned!-```--**Tip: outputting matplotlib plots.**-To output a matplotlib plot in a cell's output area, include its `Axes` or-`Figure` object as the last expression in your notebook. For example:--```python-plt.plot([1, 2])-# plt.gca() gets the current `Axes`-plt.gca()-```--or+## Reactive charts-```python-fig, ax = plt.subplots()+<!-- <iframe class="demo" src="https://components.marimo.io/?component=chart" frameborder="no"></iframe> -->-ax.plot([1, 2])-ax+```{eval-rst}+.. autofunction:: marimo.ui.altair_chart```-If you want to output the plot in the console area, use `plt.show()` or-`fig.show()`.+## matplotlib```{eval-rst}.. autofunction:: marimo.mpl.interactivediff --git a/docs/guides/index.md b/docs/guides/index.mdindex 12a2414aca..bb68437167 100644--- a/docs/guides/index.md+++ b/docs/guides/index.md@@ -9,6 +9,7 @@reactivityinteractivityoutputs+ plottingstateappsscripts@@ -23,6 +24,7 @@ These guides cover marimo's core concepts.| {doc}`reactivity` | How reactive execution works || {doc}`interactivity` | Using interactive UI elements || {doc}`outputs` | Markdown, plots, and other visual outputs |+| {doc}`plotting` | Interactive and reactive plots || {doc}`state` | Reacting to interactions with state || {doc}`apps` | Running notebooks as apps || {doc}`scripts` | Running notebooks as scripts |diff --git a/docs/guides/plotting.md b/docs/guides/plotting.mdnew file mode 100644index 0000000000..7b1eb102ad--- /dev/null+++ b/docs/guides/plotting.md@@ -0,0 +1,163 @@+# Plotting++marimo supports most major plotting libraries, including Matplotlib, Seaborn,+Plotly, and Altair. Just import your plotting library of choice and use it+as you normally would.++For Altair plots, marimo does something special: use [`mo.ui.altair_chart`](#reactive-plots)+to connect frontend selections to Python!+++```{admonition} Reactive plots!+:class: important++marimo supports reactive plots via+[`mo.ui.altair_chart`](../api/plotting.md#marimo.ui.altair_chart)! Select and+filter with your mouse, and marimo _automatically makes the selected data+available in Python as a Pandas dataframe_!+```+++## Reactive plots! ⚡++<!-- <iframe class="demo" src="https://components.marimo.io/?component=slider" frameborder="no"></iframe> -->++Use [`mo.ui.altair_chart`](../api/plotting.md#marimo.ui.altair_chart) to easily+create interactive, selectable plots: _selections you make on the frontend are+automatically made available as Pandas dataframes in Python._++```{admonition} Requirements+:class: warning+Reactive plots currently require Altair. Install it with `pip install altair`+In the future, we may make other plotting libraries reactive.+```+Wrap an Altair chart in [`mo.ui.altair_chart`](../api/plotting.md#marimo.ui.altair_chart)+to make it **reactive**: select data on the frontend, access it via the chart's+`value` attribute (`chart.value`).++_Reactive plots are just one way that marimo **makes your data tangible**._++### Example++```python+import marimo as mo+import altair as alt++# Load some data+cars = alt.load_dataset('cars')++# Create an Altair chart+chart = alt.Chart(cars)+ .mark_point() # Mark type+ .encode(+ x='Horsepower', # Encoding along the x-axis+ y='Miles_per_Gallon', # Encoding along the y-axis+ color='Origin', # Category encoding by color+)++# Make it reactive ⚡+chart = mo.ui.altair_chart(chart)+```++```python+# In a new cell, display the chart and its data filtered by the selection+mo.vstack([chart, chart.value.head()])+```++### Learning Altair++If you're new to **Altair**, we highly recommend exploring the+[Altair documentation](https://altair-viz.github.io/). Altair provides+a declarative, concise, and simple way to create highly interactive and+sophisticated plots.++Altair is based on [Vega-Lite](https://vega.github.io/vega-lite/), an+exceptional tool for creating interactive charts that serves as the backbone+for marimo's reactive charting capabilities.++#### Concepts++```{admonition} Learn by doing? Skip this section!+:class: warning++This section summarizes the main concepts used by Altair (and Vega-Lite).+Feel free to skip this section and return later.+```++Our choice to use the Vega-Lite specification was driven by its robust data+model, which is well-suited for data analysis. Some key concepts are summarized+below. (For a more detailed explanation, with examples, we recommend the+[Basic Statistical Visualization](https://altair-viz.github.io/getting_started/starting.html)+tutorial from Altair.)++- **Data Source**: This is the information that will be visualized in the+ chart. It can be provided in various formats such as a dataframe, a list of+ dictionaries, or a URL pointing to the data source.+- **Mark Type**: This refers to the visual representation used for each data+ point on the chart. The options include 'bar', 'dot', 'circle', 'area', and+ 'line'. Each mark type offers a different way to visualize and interpret the+ data.+- **Encoding**: This is the process of mapping various aspects or dimensions of+ the data to visual characteristics of the marks. Encodings can be of+ different types:+ - **Positional Encodings**: These are encodings like 'x' and 'y' that+ determine the position of the marks in the chart.+ - **Categorical Encodings**: These are encodings like 'color' and 'shape' that+ categorize data points. They are typically represented in a legend for easy+ reference.+- **Transformations**: These are operations that can be applied to the data+ before it is visualized, for example, filtering and aggregation. These+ transformations allow for more complex and nuanced visualizations.++**Automatically interactive.**+marimo adds interactivity automatically, based on the mark used and the+encodings. For example, if you use a `mark_point` and an `x` encoding, marimo+will automatically add a brush selection to the chart. If you add a `color`+encoding, marimo will add a legend and a click selection.++### Automatic Selections++By default [`mo.ui.altair_chart`](../api/plotting.md#marimo.ui.altair_chart)+will make the chart and legend selectable. Depending on the mark type, the+chart will either have a `point` or `interval` ("brush") selection. When using+non-positional encodings (color, size, etc),+[`mo.ui.altair_chart`](../api/plotting.md#marimo.ui.altair_chart) will also+make the legend selectable.++Selection configurable through `*_selection` params in+[`mo.ui.altair_chart`](../api/plotting.md#marimo.ui.altair_chart). See the [API+docs](../api/plotting.md#marimo.ui.altair_chart) for details.++```{admonition} Note+You may still add your own selection parameters via Altair or Vega-Lite.+marimo will not override your selections.+```++## matplotlib++To output a matplotlib plot in a cell's output area, include its `Axes` or+`Figure` object as the last expression in your notebook. For example:++```python+plt.plot([1, 2])+# plt.gca() gets the current `Axes`+plt.gca()+```++or++```python+fig, ax = plt.subplots()++ax.plot([1, 2])+ax+```++If you want to output the plot in the console area, use `plt.show()` or+`fig.show()`.++### Interactive plots++To make matplotlib plots interactive, use+[mo.mpl.interactive](../api/plotting.md#marimo.mpl.interactive).+(Matplotlib plots are not yet reactive.)diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.jsindex 3885dda82e..f2233caffe 100644--- a/frontend/.eslintrc.js+++ b/frontend/.eslintrc.js@@ -101,5 +101,11 @@ module.exports = {"testing-library/prefer-screen-queries": "off",},},+ {+ files: ["**/*.test.tsx", "**/*.test.ts"],+ rules: {+ "@typescript-eslint/no-non-null-assertion": "off",+ },+ },],};diff --git a/frontend/package.json b/frontend/package.jsonindex a1ae051f70..9b3f25ebdd 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -74,6 +74,7 @@"jotai": "^2.4.3","js-cookie": "^3.0.5","katex": "^0.16.9",+ "lodash-es": "^4.17.21","lucide-react": "^0.284.0","partysocket": "0.0.9","react-day-picker": "^8.8.2",@@ -83,9 +84,11 @@"react-hook-form": "^7.47.0","react-resizable-panels": "^0.0.55","react-use-event-hook": "^0.9.6",+ "react-vega": "^7.6.0","tailwind-merge": "^1.14.0","tailwindcss-animate": "^1.0.7","timestring": "^7.0.0",+ "vega-lite": "^5.15.0","vscode-languageserver-protocol": "^3.17.5","web-vitals": "^3.5.0","zod": "^3.22.2"@@ -133,6 +136,7 @@"@testing-library/react": "^14.0.0","@testing-library/user-event": "^14.5.1","@types/katex": "^0.16.3",+ "@types/lodash-es": "^4.17.9","@types/node": "^20.8.3","@types/react": "^18.2.25","@types/react-dom": "^18.2.11",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex df25557009..364900d43f 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -194,6 +194,9 @@ dependencies:katex:specifier: ^0.16.9version: 0.16.9+ lodash-es:+ specifier: ^4.17.21+ version: 4.17.21lucide-react:specifier: ^0.284.0version: 0.284.0([email protected])@@ -221,6 +224,9 @@ dependencies:react-use-event-hook:specifier: ^0.9.6version: 0.9.6([email protected])+ react-vega:+ specifier: ^7.6.0tailwind-merge:specifier: ^1.14.0version: 1.14.0@@ -230,6 +236,9 @@ dependencies:timestring:specifier: ^7.0.0version: 7.0.0+ vega-lite:+ specifier: ^5.15.0+ version: 5.15.0([email protected])vscode-languageserver-protocol:specifier: ^3.17.5version: 3.17.5@@ -283,6 +292,9 @@ devDependencies:'@types/katex':specifier: ^0.16.3version: 0.16.3+ '@types/lodash-es':+ specifier: ^4.17.9+ version: 4.17.9'@types/node':specifier: ^20.8.3version: 20.8.3@@ -842,7 +854,6 @@ packages:/@babel/[email protected](@babel/[email protected]):resolution: {integrity: sha512-p4zeefM72gpmEe2fkUr/OnOXpWEf8nAgk7ZYVqqfFiyIG7oFfVZcCrU64hWn5xp4tQ9LkV4bTIa5rD0KANpKNA==}engines: {node: '>=6.9.0'}- deprecated: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.peerDependencies:'@babel/core': ^7.0.0-0dependencies:@@ -5940,6 +5951,10 @@ packages:/@types/[email protected]:resolution: {integrity: sha512-frsJrz2t/CeGifcu/6uRo4b+SzAwT4NYCVPu1GN8IB9XTzrpPkGuV0tmh9mN+/L0PklAlsC3u5Fxt0ju00LXIw==}+ /@types/[email protected]:+ resolution: {integrity: sha512-MHmwBtCb7OCv1DSivz2UNJXPGU/1btAWRKlqJ2saEhVJkpkvqHMMaOpKg0v4sAbDWSQekHGvPVMM8nQ+Jen03Q==}+ dev: false+/@types/[email protected]:resolution: {integrity: sha512-ZUxbzKl0IfJILTS6t7ip5fQQM/J3TJYubDm3nMbgubNNYS62eXeUpoLUC8/7fJNiFYHTrGPQn7hspDUzIHX3UA==}dependencies:@@ -5995,6 +6010,12 @@ packages:resolution: {integrity: sha512-CeVMX9EhVUW8MWnei05eIRks4D5Wscw/W9Byz1s3PA+yJvcdvq9SaDjiUKvRvEgjpdTyJMjQA43ae4KTwsvOPg==}dev: true+ /@types/[email protected]:+ resolution: {integrity: sha512-ZTcmhiI3NNU7dEvWLZJkzG6ao49zOIjEgIE0RgV7wbPxU0f2xT3VSAHw2gmst8swH6V0YkLRGp4qPlX/6I90MQ==}+ dependencies:+ '@types/lodash': 4.14.194+ dev: true+/@types/[email protected]:resolution: {integrity: sha512-r22s9tAS7imvBt2lyHC9B8AGwWnXaYb1tY09oyLkXDs4vArpYJzw09nj8MLx5VfciBPGIb+ZwG0ssYnEPJxn/g==}dev: true@@ -6338,7 +6359,7 @@ packages:engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}dependencies:'@typescript-eslint/types': 5.62.0- eslint-visitor-keys: 3.4.3+ eslint-visitor-keys: 3.4.1dev: true/@vitejs/[email protected]([email protected]):@@ -6532,7 +6553,7 @@ packages:esbuild: '>=0.10.0'dependencies:esbuild: 0.18.16- tslib: 2.5.0+ tslib: 2.6.2dev: true/@yarnpkg/[email protected]:@@ -6827,21 +6848,21 @@ packages:resolution: {integrity: sha512-O0yuUDnZeQDL+ncNGlJ78BiO4jnYI3bvMsD5prT0/nsgijG/LpNBIr63gTjVTNsiGkgQhiyCShTgxt8oXOrklA==}engines: {node: '>=4'}dependencies:- tslib: 2.5.0+ tslib: 2.6.2dev: trueresolution: {integrity: sha512-c27loCv9QkZinsa5ProX751khO9DJl/AcB5c2KNtA6NRvHKS0PgLfcftz72KVq504vB0Gku5s2kUZzDBvQWvHg==}engines: {node: '>=4'}dependencies:- tslib: 2.5.0+ tslib: 2.6.2dev: trueresolution: {integrity: sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg==}engines: {node: '>=4'}dependencies:- tslib: 2.5.0+ tslib: 2.6.2dev: true@@ -7383,7 +7404,6 @@ packages:string-width: 4.2.3strip-ansi: 6.0.1wrap-ansi: 7.0.0- dev: trueresolution: {integrity: sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==}@@ -7816,6 +7836,137 @@ packages:resolution: {integrity: sha512-I7K1Uu0MBPzaFKg4nI5Q7Vs2t+3gWWW648spaF+Rg7pI9ds18Ugn+lvg4SHczUdKlHI5LWBXyqfS8+DufyBsgQ==}+ resolution: {integrity: sha512-yEEyEAbDrF8C6Ob2myOBLjwBLck1Z89jMGFee0oPsn95GqjerpaOA4ch+vc2l0FNFFwMD5N7OCSEN5eAlsUbgQ==}+ engines: {node: '>=12'}+ dependencies:+ internmap: 2.0.3+ dev: false++ resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==}+ engines: {node: '>=12'}+ dependencies:+ internmap: 2.0.3+ dev: false++ resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==}+ engines: {node: '>=12'}+ dev: false++ resolution: {integrity: sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==}+ engines: {node: '>=12'}+ dependencies:+ delaunator: 5.0.0+ dev: false++ resolution: {integrity: sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==}+ engines: {node: '>=12'}+ dev: false++ resolution: {integrity: sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==}+ engines: {node: '>=12'}+ hasBin: true+ dependencies:+ commander: 7.2.0+ iconv-lite: 0.6.3+ rw: 1.3.3+ dev: false++ resolution: {integrity: sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==}+ engines: {node: '>=12'}+ dependencies:+ d3-dispatch: 3.0.1+ d3-quadtree: 3.0.1+ d3-timer: 3.0.1+ dev: false++ resolution: {integrity: sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==}+ engines: {node: '>=12'}+ dev: false++ resolution: {integrity: sha512-p0bK60CEzph1iqmnxut7d/1kyTmm3UWtPlwdkM31AU+LW+BXazd5zJdoCn7VFxNCHXRngPHRnsNn5uGjLRGndg==}+ engines: {node: '>=12'}+ hasBin: true+ dependencies:+ commander: 7.2.0+ d3-array: 3.2.4+ d3-geo: 3.1.0+ dev: false++ resolution: {integrity: sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==}+ engines: {node: '>=12'}+ dependencies:+ d3-array: 3.2.4+ dev: false++ resolution: {integrity: sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==}+ engines: {node: '>=12'}+ dev: false++ resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==}+ engines: {node: '>=12'}+ dependencies:+ d3-color: 3.1.0+ dev: false++ resolution: {integrity: sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==}+ engines: {node: '>=12'}+ dev: false++ resolution: {integrity: sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==}+ engines: {node: '>=12'}+ dev: false++ resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==}+ engines: {node: '>=12'}+ dependencies:+ d3-array: 3.2.4+ d3-format: 3.1.0+ d3-interpolate: 3.0.1+ d3-time: 3.1.0+ d3-time-format: 4.1.0+ dev: false++ resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==}+ engines: {node: '>=12'}+ dependencies:+ d3-path: 3.1.0+ dev: false++ resolution: {integrity: sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==}+ engines: {node: '>=12'}+ dependencies:+ d3-time: 3.1.0+ dev: false++ resolution: {integrity: sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==}+ engines: {node: '>=12'}+ dependencies:+ d3-array: 3.2.4+ dev: false++ resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==}+ engines: {node: '>=12'}+ dev: false+resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==}dev: true@@ -7968,6 +8119,12 @@ packages:slash: 3.0.0dev: true+ resolution: {integrity: sha512-AyLvtyJdbv/U1GkiS6gUUzclRoAY4Gs75qkMygJJhU75LW4DNuSF2RMzpxs9jw9Oz1BobHjTdkG3zdP55VxAqw==}+ dependencies:+ robust-predicates: 3.0.2+ dev: false+resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}engines: {node: '>=0.4.0'}@@ -8622,6 +8779,11 @@ packages:engines: {node: '>=10'}dev: true+ resolution: {integrity: sha512-pZnmmLwYzf+kWaM/Qgrvpen51upAktaaiI01nsJD/Yr3lMOdNtq0cxkrrg16w64VtisN6okbs7Q8AfGqj4c9fA==}+ engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}+ dev: true+resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==}engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}@@ -8840,6 +9002,10 @@ packages:micromatch: 4.0.5dev: true+ resolution: {integrity: sha512-vf6IHUX2SBcA+5/+4883dsIjpBTqmfBjmYiWK1savxQmFk4JfBMLa7ynTYOs1Rolp/T1betJxHiGD3g1Mn8lUQ==}+ dev: false+resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==}@@ -9095,7 +9261,6 @@ packages:resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}engines: {node: 6.* || 8.* || >= 10.*}- dev: trueresolution: {integrity: sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==}@@ -9583,6 +9748,11 @@ packages:side-channel: 1.0.4dev: true+ resolution: {integrity: sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==}+ engines: {node: '>=12'}+ dev: false+resolution: {integrity: sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==}dependencies:@@ -10162,6 +10332,10 @@ packages:resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}+ resolution: {integrity: sha512-Rc2suX5meI0S3bfdZuA7JMFBGkJ875ApfVyq2WHELjBiiG22My/l7/8zPpH/CfFVQHuVLd8NLR0nv6vi0BYYKA==}+ dev: false+resolution: {integrity: sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==}hasBin: true@@ -10256,7 +10430,7 @@ packages:dependencies:copy-anything: 2.0.6parse-node-version: 1.0.1- tslib: 2.5.0+ tslib: 2.6.2optionalDependencies:errno: 0.1.8graceful-fs: 4.2.10@@ -10344,6 +10518,10 @@ packages:dependencies:p-locate: 5.0.0+ resolution: {integrity: sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==}+ dev: false+resolution: {integrity: sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow==}dev: true@@ -12122,6 +12300,22 @@ packages:react: 18.2.0dev: false+ resolution: {integrity: sha512-2oMML4wH9qWLnZPRxJm06ozwrVN/K+nkjqdI5/ofWWsrBnnH4iB9rRKrsV8px0nlWgZrwfdCH4g5RUiyyJHWSA==}+ peerDependencies:+ react: ^16 || ^17 || ^18+ vega: '*'+ vega-lite: '*'+ dependencies:+ '@types/react': 18.2.25+ fast-deep-equal: 3.1.3+ prop-types: 15.8.1+ react: 18.2.0+ vega: 5.25.0+ vega-embed: 6.23.0([email protected])([email protected])+ vega-lite: 5.15.0([email protected])+ dev: false+resolution: {integrity: sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==}engines: {node: '>=0.10.0'}@@ -12214,7 +12408,7 @@ packages:ast-types: 0.15.2esprima: 4.0.1source-map: 0.6.1- tslib: 2.5.0+ tslib: 2.6.2dev: true@@ -12225,7 +12419,7 @@ packages:ast-types: 0.16.1esprima: 4.0.1source-map: 0.6.1- tslib: 2.5.0+ tslib: 2.6.2dev: true@@ -12329,7 +12523,6 @@ packages:resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}engines: {node: '>=0.10.0'}- dev: trueresolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}@@ -12417,6 +12610,10 @@ packages:dependencies:glob: 7.2.0+ resolution: {integrity: sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==}+ dev: false+resolution: {integrity: sha512-d7zhvo1OUY2SXSM6pfNjgD5+d0Nz87CUp4mt8l/GgVP3oBsPwzNvSzyu1me6BSG9JIgWNTVcafIXBIyM8yQ3yw==}engines: {node: '>=14.18.0', npm: '>=8.0.0'}@@ -12439,6 +12636,10 @@ packages:dependencies:queue-microtask: 1.2.3+ resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==}+ dev: false+resolution: {integrity: sha512-F2+gxDshqmIub1KdvZkaEfGDwLNpPvk9Fs6LD/MyQxNgMds/WH9OdDDXOmxUZpME+iSK3rQCctkL0DYyytUqMg==}dependencies:@@ -13306,6 +13507,13 @@ packages:engines: {node: '>=0.6'}dev: true+ resolution: {integrity: sha512-605uxS6bcYxGXw9qi62XyrV6Q3xwbndjachmNxu8HWTtVPxZfEJN9fd/SZS1Q54Sn2y0TMyMxFj/cJINqGHrKw==}+ hasBin: true+ dependencies:+ commander: 2.20.3+ dev: false+resolution: {integrity: sha512-G9fqXWoYFZgTc2z8Q5zaHy/vJMjm+WV0AkAeHxVCQiEB1b+dGvWzFW6QV07cY5jQ5gRkeid2qIkzkxUnmoQZUQ==}engines: {node: '>=6'}@@ -13366,6 +13574,9 @@ packages:resolution: {integrity: sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg==}+ resolution: {integrity: sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==}+resolution: {integrity: sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==}engines: {node: '>= 6'}@@ -13648,6 +13859,390 @@ packages:engines: {node: '>= 0.8'}dev: true+ resolution: {integrity: sha512-OkJ9CACVcN9R5Pi9uF6MZBF06pO6qFpDYHWSKBJsdHP5o724KrsgR6UvbnXFH82FdsiTOff/HqjuaG8C7FL+9Q==}+ dev: false++ resolution: {integrity: sha512-yesvlMcwRwxrtAd9IYjuxWJJuAMI0sl7JvAFfYtuDkkGDtqfLXUcCzHIATqW6igVIE7tWwGxnbfvQLhLNgK44Q==}+ dependencies:+ d3-array: 3.2.4+ vega-dataflow: 5.7.5+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-EdsIl6gouH67+8B0f22Owr2tKDiMPNNR8lEvJDcxmFw02nXd8juimclpLvjPQriqn6ta+3Dn5txqfD117H04YA==}+ dependencies:+ vega-format: 1.1.1+ vega-loader: 4.5.1+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-8Iava57LdROsatqsOhMLErHYaBpZBB7yZJlSVU3/xOK3l8Ft5WFnj5fm3OOAVML97/0yULE7LRVjXW5hV3fSpg==}+ peerDependencies:+ vega: ^5.21.0+ vega-lite: '*'+ dependencies:+ fast-json-patch: 3.1.1+ json-stringify-pretty-compact: 3.0.0+ semver: 7.5.4+ tslib: 2.6.2+ vega: 5.25.0+ vega-interpreter: 1.0.5+ vega-lite: 5.15.0([email protected])+ vega-schema-url-parser: 2.2.0+ vega-themes: 2.14.0([email protected])([email protected])+ vega-tooltip: 0.33.0+ dev: false+ bundledDependencies:+ - yallist++ resolution: {integrity: sha512-c3J0LYkgYeXQxwnYkEzL15cCFBYPRaYUon8O2SZ6O4PhH4dfFTXBzSyT8+gh8AhBd572l2yGDfxpEYA6pOqdjg==}+ dependencies:+ d3-array: 3.2.4+ d3-interpolate: 3.0.1+ vega-dataflow: 5.7.5+ vega-scale: 7.3.0+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-K5zd7s5tjr1LiOOkjGpcVls8GsH/f2CWCrWcpKy74gTCp+llCdwz0Enqo013ZlGaRNjfgD/o1caJRt3GSaec4A==}+ dev: false++ resolution: {integrity: sha512-u8Rzja/cn2PEUkhQN3zUj3REwNewTA92ExrcASNKUJPCciMkHJEjESwFYuI6DWMCq4hQElQ92iosOAtwzsSTqA==}+ dependencies:+ '@types/estree': 1.0.1+ vega-util: 1.17.2+ dev: false++ resolution: {integrity: sha512-aE2TlP264HXM1r3fl58AvZdKUWBNOGkIvn4EWyqeJdgO2vz46zSU7x7TzPG4ZLuo44cDRU5Ng3I1eQk23Asz6A==}+ dependencies:+ d3-force: 3.0.0+ vega-dataflow: 5.7.5+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-Rll7YgpYbsgaAa54AmtEWrxaJqgOh5fXlvM2wewO4trb9vwM53KBv4Q/uBWCLK3LLGeBXIF6gjDt2LFuJAUtkQ==}+ dependencies:+ d3-array: 3.2.4+ d3-format: 3.1.0+ d3-time-format: 4.1.0+ vega-time: 2.1.1+ vega-util: 1.17.2+ dev: false++ resolution: {integrity: sha512-YE1Xl3Qi28kw3vdXVYgKFMo20ttd3+SdKth1jUNtBDGGdrOpvPxxFhZkVqX+7FhJ5/1UkDoAYs/cZY0nRKiYgA==}+ dependencies:+ d3-array: 3.2.4+ d3-color: 3.1.0+ d3-geo: 3.1.0+ vega-dataflow: 5.7.5+ vega-expression: 5.1.0+ vega-scale: 7.3.0+ vega-scenegraph: 4.10.2+ vega-selections: 5.4.1+ vega-statistics: 1.9.0+ vega-time: 2.1.1+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-s4WeZAL5M3ZUV27/eqSD3v0FyJz3PlP31XNSLFy4AJXHxHUeXT3qLiDHoVQnW5Om+uBCPDtTT1ROx1smGIf2aA==}+ dependencies:+ d3-array: 3.2.4+ d3-color: 3.1.0+ d3-geo: 3.1.0+ vega-canvas: 1.2.7+ vega-dataflow: 5.7.5+ vega-projection: 1.6.0+ vega-statistics: 1.9.0+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-h5mbrDtPKHBBQ9TYbvEb/bCqmGTlUX97+4CENkyH21tJs7naza319B15KRK0NWOHuhbGhFmF8T0696tg+2c8XQ==}+ dependencies:+ d3-hierarchy: 3.1.2+ vega-dataflow: 5.7.5+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-po6oTOmeQqr1tzTCdD15tYxAQLeUnOVirAysgVEemzl+vfmvcEP7jQmlc51jz0jMA+WsbmE6oJywisQPu/H0Bg==}+ dev: false++ resolution: {integrity: sha512-n/ackJ5lc0Xs9PInCaGumYn2awomPjJ87EMVT47xNgk2bHmJoZV1Ve/1PUM6Eh/KauY211wPMrNp/9Im+7Ripg==}+ dependencies:+ vega-canvas: 1.2.7+ vega-dataflow: 5.7.5+ vega-scenegraph: 4.10.2+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-Eac4VBhdtwbJQWH8m2OaRba/YVZbUHlmTAiPfiF3XIapJ73rcs+gHZBE1DfYgfoGjBN+5YJUMvdgm4UE7j/Ncg==}+ engines: {node: '>=18'}+ hasBin: true+ peerDependencies:+ vega: ^5.24.0+ dependencies:+ json-stringify-pretty-compact: 3.0.0+ tslib: 2.6.2+ vega: 5.25.0+ vega-event-selector: 3.0.1+ vega-expression: 5.1.0+ vega-util: 1.17.2+ yargs: 17.7.2+ dev: false++ resolution: {integrity: sha512-qy5x32SaT0YkEujQM2yKqvLGV9XWQ2aEDSugBFTdYzu/1u4bxdUSRDREOlrJ9Km3RWIOgFiCkobPmFxo47SKuA==}+ dependencies:+ d3-dsv: 3.0.1+ node-fetch: 2.6.7+ topojson-client: 3.1.0+ vega-format: 1.1.1+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-as+QnX8Qxe9q51L1C2sVBd+YYYctP848+zEvkBT2jlI2g30aZ6Uv7sKsq7QTL6DUbhXQKR0XQtzlanckSFdaOQ==}+ dependencies:+ vega-dataflow: 5.7.5+ vega-event-selector: 3.0.1+ vega-functions: 5.13.2+ vega-scale: 7.3.0+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-LGUaO/kpOEYuTlul+x+lBzyuL9qmMwP1yShdUWYLW+zXoeyGbs5OZW+NbPPwLYqJr5lpXDr/vGztFuA/6g2xvQ==}+ dependencies:+ d3-geo: 3.1.0+ d3-geo-projection: 4.0.0+ vega-scale: 7.3.0+ dev: false++ resolution: {integrity: sha512-6TZoPlhV/280VbxACjRKqlE0Nv48z5g4CSNf1FmGGTWS1rQtElPTranSoVW4d7ET5eVQ6f9QLxNAiALptvEq+g==}+ dependencies:+ d3-array: 3.2.4+ vega-dataflow: 5.7.5+ vega-statistics: 1.9.0+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-0dDYXyFLQcxPQ2OQU0WuBVYLRZnm+/CwVu6i6N4idS7R9VXIX5581EkCh3pZ20pQ/+oaA7oJ0pR9rJgJ6rukRQ==}+ dependencies:+ vega-dataflow: 5.7.5+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-pMOAI2h+e1z7lsqKG+gMfR6NKN2sTcyjZbdJwntooW0uFHwjLGjMSY7kSd3nSEquF0HQ8qF7zR6gs1eRwlGimw==}+ dependencies:+ d3-array: 3.2.4+ d3-interpolate: 3.0.1+ d3-scale: 4.0.2+ vega-time: 2.1.1+ vega-util: 1.17.2+ dev: false++ resolution: {integrity: sha512-R8m6voDZO5+etwNMcXf45afVM3XAtokMqxuDyddRl9l1YqSJfS+3u8hpolJ50c2q6ZN20BQiJwKT1o0bB7vKkA==}+ dependencies:+ d3-path: 3.1.0+ d3-shape: 3.2.0+ vega-canvas: 1.2.7+ vega-loader: 4.5.1+ vega-scale: 7.3.0+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-yAtdBnfYOhECv9YC70H2gEiqfIbVkq09aaE4y/9V/ovEFmH9gPKaEgzIZqgT7PSPQjKhsNkb6jk6XvSoboxOBw==}+ dev: false++ resolution: {integrity: sha512-EtYc4DvA+wXqBg9tq+kDomSoVUPCmQfS7hUxy2qskXEed79YTimt3Hcl1e1fW226I4AVDBEqTTKebmKMzbSgAA==}+ dependencies:+ d3-array: 3.2.2+ vega-expression: 5.1.0+ vega-util: 1.17.2+ dev: false++ resolution: {integrity: sha512-GAqS7mkatpXcMCQKWtFu1eMUKLUymjInU0O8kXshWaQrVWjPIO2lllZ1VNhdgE0qGj4oOIRRS11kzuijLshGXQ==}+ dependencies:+ d3-array: 3.2.4+ dev: false++ resolution: {integrity: sha512-9dLmsUER7gJrDp8SEYKxBFmXmpyzLlToKIjxq3HCvYjz8cnNrRGyAhvIlKWOB3ZnGvfYV+vnv3ZRElSNL31nkA==}+ peerDependencies:+ vega: '*'+ vega-lite: '*'+ dependencies:+ vega: 5.25.0+ vega-lite: 5.15.0([email protected])+ dev: false++ resolution: {integrity: sha512-z1qbgyX0Af2kQSGFbApwBbX2meenGvsoX8Nga8uyWN8VIbiySo/xqizz1KrP6NbB6R+x5egKmkjdnyNThPeEWA==}+ dependencies:+ d3-array: 3.2.4+ d3-time: 3.1.0+ vega-util: 1.17.2+ dev: false++ resolution: {integrity: sha512-jMcvH2lP20UfyvO2KAEdloiwRyasikaiLuNFhzwrrzf2RamGTxP4G7B2OZ2QENfrGUH05Z9ei5tn/eErdzOaZQ==}+ dependencies:+ vega-util: 1.17.2+ dev: false++ resolution: {integrity: sha512-sJELfEuYQ238PRG+GOqQch8D69RYnJevYSGLsRGQD2LxNz3j+GlUX6Pid+gUEH5HJy22Q5L0vsTl2ZNhIr4teQ==}+ dependencies:+ d3-array: 3.2.4+ vega-dataflow: 5.7.5+ vega-statistics: 1.9.0+ vega-time: 2.1.1+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-fW02GElYoqweCCaPqH6iH44UZnzXiX9kbm1qyecjU3k5s0vtufLI7Yuz/a/uL37mEAqTMQplBBAlk0T9e2e1Dw==}+ dependencies:+ '@types/geojson': 7946.0.4+ vega-event-selector: 3.0.1+ vega-expression: 5.1.0+ vega-util: 1.17.2+ dev: false++ resolution: {integrity: sha512-omNmGiZBdjm/jnHjZlywyYqafscDdHaELHx1q96n5UOz/FlO9JO99P4B3jZg391EFG8dqhWjQilSf2JH6F1mIw==}+ dev: false++ resolution: {integrity: sha512-NxEq4ZD4QwWGRrl2yDLnBRXM9FgCI+vvYb3ZC2+nVDtkUxOlEIKZsMMw31op5GZpfClWLbjCT3mVvzO2xaTF+g==}+ dependencies:+ vega-dataflow: 5.7.5+ vega-scenegraph: 4.10.2+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-RoWxuoEMI7xVQJhPqNeLEHCezudsf3QkVMhH5tCovBqwBADQGqq9iWyax3ZzdyX1+P3eBgm7cnLvpqtN2hU8kA==}+ dependencies:+ d3-array: 3.2.4+ d3-timer: 3.0.1+ vega-dataflow: 5.7.5+ vega-format: 1.1.1+ vega-functions: 5.13.2+ vega-runtime: 6.1.4+ vega-scenegraph: 4.10.2+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-zzi+fxU/SBad4irdLLsG3yhZgXWZezraGYVQfZFWe8kl7W/EHUk+Eqk/eetn4bDeJ6ltQskX+UXH3OP5Vh0Q0Q==}+ dependencies:+ d3-delaunay: 6.0.4+ vega-dataflow: 5.7.5+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-oeZLlnjiusLAU5vhk0IIdT5QEiJE0x6cYoGNq1th+EbwgQp153t4r026fcib9oq15glHFOzf81a8hHXHSJm1Jw==}+ dependencies:+ vega-canvas: 1.2.7+ vega-dataflow: 5.7.5+ vega-scale: 7.3.0+ vega-statistics: 1.9.0+ vega-util: 1.17.2+ transitivePeerDependencies:+ - encoding+ dev: false++ resolution: {integrity: sha512-lr+uj0mhYlSN3JOKbMNp1RzZBenWp9DxJ7kR3lha58AFNCzzds7pmFa7yXPbtbaGhB7Buh/t6n+Bzk3Y0VnF5g==}+ dependencies:+ vega-crossfilter: 4.1.1+ vega-dataflow: 5.7.5+ vega-encode: 4.9.2+ vega-event-selector: 3.0.1+ vega-expression: 5.1.0+ vega-force: 4.2.0+ vega-format: 1.1.1+ vega-functions: 5.13.2+ vega-geo: 4.4.1+ vega-hierarchy: 4.1.1+ vega-label: 1.2.1+ vega-loader: 4.5.1+ vega-parser: 6.2.0+ vega-projection: 1.6.0+ vega-regression: 1.2.0+ vega-runtime: 6.1.4+ vega-scale: 7.3.0+ vega-scenegraph: 4.10.2+ vega-statistics: 1.9.0+ vega-time: 2.1.1+ vega-transforms: 4.10.2+ vega-typings: 0.24.2+ vega-util: 1.17.2+ vega-view: 5.11.1+ vega-view-transforms: 4.5.9+ vega-voronoi: 4.2.1+ vega-wordcloud: 4.1.4+ transitivePeerDependencies:+ - encoding+ dev: false+resolution: {integrity: sha512-nlBMJ9x6n7/Amaz6F3zJ97EBwR2FkzhBRxF5e+jE6LA3yi6Wtc2lyTij1OnDMIr34v5g/tVQtsVAzhT0jc5ygA==}engines: {node: '>=v14.18.0'}@@ -14091,7 +14686,6 @@ packages:resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}engines: {node: '>=10'}- dev: trueresolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}@@ -14116,7 +14710,6 @@ packages:resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}engines: {node: '>=12'}- dev: trueresolution: {integrity: sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==}@@ -14144,6 +14737,19 @@ packages:yargs-parser: 21.1.1dev: true+ resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}+ engines: {node: '>=12'}+ dependencies:+ cliui: 8.0.1+ escalade: 3.1.1+ get-caller-file: 2.0.5+ require-directory: 2.1.1+ string-width: 4.2.3+ y18n: 5.0.8+ yargs-parser: 21.1.1+ dev: false+resolution: {integrity: sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==}dependencies:diff --git a/frontend/public/mockServiceWorker.js b/frontend/public/mockServiceWorker.jsindex 0f24d51586..51d85eeebf 100644--- a/frontend/public/mockServiceWorker.js+++ b/frontend/public/mockServiceWorker.js@@ -2,7 +2,7 @@/* tslint:disable *//**- * Mock Service Worker (1.3.1).+ * Mock Service Worker (1.3.2).* @see https://github.com/mswjs/msw* - Please do NOT modify this file.* - Please do NOT serve this file on production.diff --git a/frontend/src/hooks/useDeppCompareMemoize.ts b/frontend/src/hooks/useDeppCompareMemoize.tsnew file mode 100644index 0000000000..1f53b79d6d--- /dev/null+++ b/frontend/src/hooks/useDeppCompareMemoize.ts@@ -0,0 +1,21 @@+/* Copyright 2023 Marimo. All rights reserved. */+import React from "react";+import { dequal } from "dequal";++/**+ * Deep compare memoize hook+ *+ * Useful when you want to memoize a react hook that has an object as a dependency+ * that you want to compare by value instead of reference.+ *+ * Useful when the re-render if more expensive than the deep compare.+ */+export function useDeepCompareMemoize<T>(value: T) {+ const ref = React.useRef<T>(value);++ if (!dequal(value, ref.current)) {+ ref.current = value;+ }++ return ref.current;+}diff --git a/frontend/src/plugins/impl/vega/VegaPlugin.tsx b/frontend/src/plugins/impl/vega/VegaPlugin.tsxnew file mode 100644index 0000000000..a16715eaa7--- /dev/null+++ b/frontend/src/plugins/impl/vega/VegaPlugin.tsx@@ -0,0 +1,155 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { z } from "zod";++import { SignalListeners, VegaLite, View } from "react-vega";+import { IPlugin, IPluginProps } from "@/plugins/types";+import { makeSelectable } from "./make-selectable";+import { useMemo, useRef, useState } from "react";+import { getSelectionParamNames } from "./params";+import { VegaLiteSpec } from "./types";+import { Alert, AlertTitle } from "@/components/ui/alert";+import { useDeepCompareMemoize } from "@/hooks/useDeppCompareMemoize";+import { useDebugMounting, usePropsDidChange } from "@/hooks/debug";+import { debounce } from "lodash-es";+import useEvent from "react-use-event-hook";+import { Logger } from "@/utils/Logger";++import "./vega.css";++interface Data {+ spec: VegaLiteSpec;+ chartSelection: boolean | "point" | "interval";+ fieldSelection: boolean | string[];+}++interface T {+ [channel: string]: {+ // List of selected items+ vlPoint?: { or: unknown[] };+ // Either a range or a list of values+ [field: string]:+ | [number, number]+ | string[]+ | number[]+ | { or: unknown[] }+ | undefined;+ };+}++export class VegaPlugin implements IPlugin<T, Data> {+ tagName = "marimo-vega";++ validator = z.object({+ spec: z+ .object({})+ .passthrough()+ .transform((spec) => spec as unknown as VegaLiteSpec),+ chartSelection: z+ .union([z.boolean(), z.literal("point"), z.literal("interval")])+ .default(true),+ fieldSelection: z.union([z.boolean(), z.array(z.string())]).default(true),+ });++ render(props: IPluginProps<T, Data>): JSX.Element {+ return (+ <VegaComponent+ value={props.value}+ setValue={props.setValue}+ {...props.data}+ />+ );+ }+}++interface VegaComponentProps<T> extends Data {+ value: T;+ setValue: (value: T) => void;+}++export const VegaComponent = ({+ value,+ setValue,+ chartSelection,+ fieldSelection,+ spec,+}: VegaComponentProps<T>): JSX.Element => {+ const vegaView = useRef<View>();+ const [error, setError] = useState<Error>();++ // Debug+ useDebugMounting("VegaComponent");+ usePropsDidChange("VegaComponent", {+ value,+ setValue,+ chartSelection,+ fieldSelection,+ spec,+ });++ // Aggressively memoize the spec, so Vega doesn't re-render/re-mount the component+ const selectableSpec = useMemo(() => {+ return makeSelectable(spec, { chartSelection, fieldSelection });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [useDeepCompareMemoize(spec), chartSelection, fieldSelection]);+ const names = useMemo(+ () => getSelectionParamNames(selectableSpec),+ [selectableSpec]+ );++ // Update the value when the selection changes+ // Keep the old value from other signals+ const handleUpdateValue = useEvent((newValue: T) => {+ setValue({ ...value, ...newValue });+ });++ const signalListeners = useMemo(+ () =>+ names.reduce((acc, name) => {+ // Debounce each signal listener, otherwise we may create expensive requests+ acc[name] = debounce((signalName, signalValue) => {+ Logger.debug("[Vega signal]", signalName, signalValue);+ handleUpdateValue({+ [signalName]: signalValue,+ });+ }, 100);+ return acc;+ }, {} as SignalListeners),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [useDeepCompareMemoize(names), setValue]+ );++ const handleError = useEvent((error) => {+ Logger.error(error);+ Logger.debug(selectableSpec);+ setError(error);+ });++ const handleNewView = useEvent((view) => {+ Logger.debug("[Vega view] created", view);+ vegaView.current = view;+ setError(undefined);+ });++ return (+ <>+ {error && (+ <Alert variant="destructive">+ <AlertTitle>{error.message}</AlertTitle>+ <div className="text-md">{error.stack}</div>+ </Alert>+ )}+ <VegaLite+ spec={selectableSpec}+ actions={actions}+ signalListeners={signalListeners}+ onError={handleError}+ onNewView={handleNewView}+ />+ </>+ );+};++const actions = {+ source: false,+ compiled: false,+};diff --git a/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap b/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snapnew file mode 100644index 0000000000..4532ad1af4--- /dev/null+++ b/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap@@ -0,0 +1,462 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`makeSelectable > should return correctly if existing legend selection 1`] = `+{+ "config": {+ "view": {+ "continuousHeight": 300,+ },+ },+ "data": {+ "url": "https://cdn.jsdelivr.net/npm/[email protected]/data/unemployment-across-industries.json",+ },+ "encoding": {+ "color": {+ "field": "series",+ "scale": {+ "scheme": "category20b",+ },+ "type": "nominal",+ },+ "opacity": {+ "condition": {+ "test": {+ "and": [+ {+ "param": "param_1",+ },+ {+ "param": "legend_selection_series",+ },+ {+ "param": "select_point",+ },+ ],+ },+ "value": 1,+ },+ "value": 0.2,+ },+ "x": {+ "axis": {+ "domain": false,+ "format": "%Y",+ "tickSize": 0,+ },+ "field": "date",+ "timeUnit": "yearmonth",+ "type": "temporal",+ },+ "y": {+ "aggregate": "sum",+ "axis": null,+ "field": "count",+ "stack": "center",+ "type": "quantitative",+ },+ },+ "mark": {+ "cursor": "pointer",+ "tooltip": true,+ "type": "area",+ },+ "params": [+ {+ "bind": "legend",+ "name": "param_1",+ "select": {+ "fields": [+ "series",+ ],+ "type": "point",+ },+ },+ {+ "bind": "legend",+ "name": "legend_selection_series",+ "select": {+ "fields": [+ "series",+ ],+ "type": "point",+ },+ },+ {+ "name": "select_point",+ "select": {+ "encodings": [+ "color",+ ],+ "type": "point",+ },+ },+ ],+}+`;++exports[`makeSelectable > should return correctly if mark is a string 1`] = `+{+ "encoding": {+ "opacity": {+ "condition": {+ "test": {+ "and": [+ {+ "param": "select_point",+ },+ {+ "param": "select_interval",+ },+ ],+ },+ "value": 1,+ },+ "value": 0.2,+ },+ },+ "mark": {+ "cursor": "pointer",+ "tooltip": true,+ "type": "point",+ },+ "params": [+ {+ "name": "select_point",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "type": "point",+ },+ },+ {+ "name": "select_interval",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "mark": {+ "fill": "#669EFF",+ "fillOpacity": 0.07,+ "stroke": "#669EFF",+ "strokeOpacity": 0.4,+ },+ "type": "interval",+ },+ },+ ],+}+`;++exports[`makeSelectable > should return correctly if mark is not string 1`] = `+{+ "encoding": {+ "opacity": {+ "condition": {+ "test": {+ "and": [+ {+ "param": "select_point",+ },+ {+ "param": "select_interval",+ },+ ],+ },+ "value": 1,+ },+ "value": 0.2,+ },+ },+ "mark": {+ "cursor": "pointer",+ "tooltip": true,+ "type": "point",+ },+ "params": [+ {+ "name": "select_point",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "type": "point",+ },+ },+ {+ "name": "select_interval",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "mark": {+ "fill": "#669EFF",+ "fillOpacity": 0.07,+ "stroke": "#669EFF",+ "strokeOpacity": 0.4,+ },+ "type": "interval",+ },+ },+ ],+}+`;++exports[`makeSelectable > should return correctly if overlapping encodings 1`] = `+{+ "config": {+ "view": {+ "continuousHeight": 300,+ },+ },+ "data": {+ "url": "data/cars.json",+ },+ "encoding": {+ "color": {+ "field": "Origin",+ "type": "nominal",+ },+ "opacity": {+ "condition": {+ "test": {+ "and": [+ {+ "param": "legend_selection_Origin",+ },+ {+ "param": "select_point",+ },+ {+ "param": "select_interval",+ },+ ],+ },+ "value": 1,+ },+ "value": 0.2,+ },+ "x": {+ "field": "Horsepower",+ "type": "quantitative",+ },+ "y": {+ "field": "Miles_per_Gallon",+ "type": "quantitative",+ },+ },+ "mark": {+ "cursor": "pointer",+ "tooltip": true,+ "type": "point",+ },+ "params": [+ {+ "bind": "legend",+ "name": "legend_selection_Origin",+ "select": {+ "fields": [+ "Origin",+ ],+ "type": "point",+ },+ },+ {+ "name": "select_point",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "type": "point",+ },+ },+ {+ "name": "select_interval",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "mark": {+ "fill": "#669EFF",+ "fillOpacity": 0.07,+ "stroke": "#669EFF",+ "strokeOpacity": 0.4,+ },+ "type": "interval",+ },+ },+ ],+}+`;++exports[`makeSelectable > should return correctly with multiple encodings 1`] = `+{+ "encoding": {+ "color": {+ "field": "colorField",+ "type": "nominal",+ },+ "opacity": {+ "condition": {+ "test": {+ "and": [+ {+ "param": "legend_selection_colorField",+ },+ {+ "param": "legend_selection_sizeField",+ },+ {+ "param": "select_point",+ },+ {+ "param": "select_interval",+ },+ ],+ },+ "value": 1,+ },+ "value": 0.2,+ },+ "size": {+ "field": "sizeField",+ "type": "quantitative",+ },+ },+ "mark": {+ "cursor": "pointer",+ "tooltip": true,+ "type": "point",+ },+ "params": [+ {+ "bind": "legend",+ "name": "legend_selection_colorField",+ "select": {+ "fields": [+ "colorField",+ ],+ "type": "point",+ },+ },+ {+ "bind": "legend",+ "name": "legend_selection_sizeField",+ "select": {+ "fields": [+ "sizeField",+ ],+ "type": "point",+ },+ },+ {+ "name": "select_point",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "type": "point",+ },+ },+ {+ "name": "select_interval",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "mark": {+ "fill": "#669EFF",+ "fillOpacity": 0.07,+ "stroke": "#669EFF",+ "strokeOpacity": 0.4,+ },+ "type": "interval",+ },+ },+ ],+}+`;++exports[`makeSelectable > should skip field selection if empty or false 1`] = `+{+ "config": {+ "view": {+ "continuousHeight": 300,+ },+ },+ "data": {+ "url": "data/cars.json",+ },+ "encoding": {+ "color": {+ "field": "Origin",+ "type": "nominal",+ },+ "opacity": {+ "condition": {+ "test": {+ "and": [+ {+ "param": "select_point",+ },+ {+ "param": "select_interval",+ },+ ],+ },+ "value": 1,+ },+ "value": 0.2,+ },+ "x": {+ "field": "Horsepower",+ "type": "quantitative",+ },+ "y": {+ "field": "Miles_per_Gallon",+ "type": "quantitative",+ },+ },+ "mark": {+ "cursor": "pointer",+ "tooltip": true,+ "type": "point",+ },+ "params": [+ {+ "name": "select_point",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "type": "point",+ },+ },+ {+ "name": "select_interval",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "mark": {+ "fill": "#669EFF",+ "fillOpacity": 0.07,+ "stroke": "#669EFF",+ "strokeOpacity": 0.4,+ },+ "type": "interval",+ },+ },+ ],+}+`;diff --git a/frontend/src/plugins/impl/vega/__tests__/encodings.test.ts b/frontend/src/plugins/impl/vega/__tests__/encodings.test.tsnew file mode 100644index 0000000000..6f5ddda65f--- /dev/null+++ b/frontend/src/plugins/impl/vega/__tests__/encodings.test.ts@@ -0,0 +1,144 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { expect, describe, it } from "vitest";+import { findEncodedFields, makeEncodingInteractive } from "../encodings";+import { EncodingType, Encodings, VegaLiteSpec } from "../types";++describe("findEncodedFields", () => {+ it("should return an empty array when spec is undefined", () => {+ expect(findEncodedFields(undefined!)).toEqual([]);+ });++ it("should return an empty array when encoding is not in spec", () => {+ expect(findEncodedFields({} as VegaLiteSpec)).toEqual([]);+ });++ it("should return an array of fields that are encoded", () => {+ const spec = {+ mark: "point",+ encoding: {+ color: {+ field: "colorField",+ type: "nominal",+ },+ size: {+ field: "sizeField",+ type: "quantitative",+ },+ },+ } as VegaLiteSpec;++ expect(findEncodedFields(spec)).toEqual(["colorField", "sizeField"]);+ });++ it("should return an array of fields that are encoded in condition", () => {+ const spec = {+ encoding: {+ color: {+ condition: {+ field: "colorField",+ type: "nominal",+ test: { and: [{ param: "select" }] },+ },+ value: "grey",+ },+ size: {+ field: "sizeField",+ type: "quantitative",+ },+ },+ } as VegaLiteSpec;++ expect(findEncodedFields(spec)).toEqual(["colorField", "sizeField"]);+ });++ it("should return an empty array when encoding type is not allowed", () => {+ const spec = {+ encoding: {+ x: {+ field: "xField",+ type: "quantitative",+ },+ y: {+ field: "yField",+ type: "quantitative",+ },+ },+ } as VegaLiteSpec;++ expect(findEncodedFields(spec)).toEqual([]);+ });+});++describe("makeEncodingInteractive", () => {+ it("should return the original encodings when key is not in the allowed list", () => {+ const encodings: Encodings = {+ x: {+ field: "someField",+ type: "quantitative",+ },+ };++ expect(makeEncodingInteractive("x", encodings, ["param1"])).toEqual(+ encodings+ );+ });++ it.each([+ "color",+ "fill",+ "fillOpacity",+ "opacity",+ "shape",+ "size",+ ] as EncodingType[])("should return updated encodings for %s", (type) => {+ const encodings: Encodings = {+ [type]: {+ field: "someField",+ type: "quantitative",+ },+ };++ const expected = {+ ...encodings,+ opacity: {+ condition: {+ test: {+ and: [{ param: "param1" }],+ },+ value: 1,+ },+ value: 0.2,+ },+ };++ expect(makeEncodingInteractive(type, encodings, ["param1"])).toEqual(+ expected+ );+ });++ it("should return updated encodings for multiple parameters", () => {+ const encodings: Encodings = {+ opacity: {+ field: "someField",+ type: "quantitative",+ },+ };++ const expected = {+ ...encodings,+ opacity: {+ condition: {+ test: {+ and: [{ param: "param1" }, { param: "param2" }],+ },+ value: 1,+ },+ value: 0.2,+ },+ };++ expect(+ makeEncodingInteractive("color", encodings, ["param1", "param2"])+ ).toEqual(expected);+ });+});diff --git a/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts b/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.tsnew file mode 100644index 0000000000..dbcfee5271--- /dev/null+++ b/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts@@ -0,0 +1,195 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { expect, describe, it } from "vitest";+import { makeSelectable } from "../make-selectable";+import { VegaLiteSpec } from "../types";++describe("makeSelectable", () => {+ it("should return correctly if mark is not string", () => {+ const spec = {+ mark: {+ type: "point",+ },+ } as VegaLiteSpec;+ expect(makeSelectable(spec, {})).toMatchSnapshot();+ });++ it("should return correctly if mark is a string", () => {+ const spec = {+ mark: "point",+ } as VegaLiteSpec;+ expect(makeSelectable(spec, {})).toMatchSnapshot();+ });++ it("should return the same spec if selection is false", () => {+ const spec = {+ mark: "point",+ } as VegaLiteSpec;+ expect(+ makeSelectable(spec, {+ chartSelection: false,+ fieldSelection: false,+ })+ ).toEqual(spec);+ });++ it("should return the same spec for not-defined and true", () => {+ const spec = {+ mark: "point",+ } as VegaLiteSpec;+ expect(+ makeSelectable(spec, {+ chartSelection: true,+ fieldSelection: true,+ })+ ).toEqual(makeSelectable(spec, {}));+ });++ it("should return the same spec if mark is not in spec", () => {+ const spec1 = {+ mark: "point",+ } as VegaLiteSpec;+ const spec2 = {+ mark: {+ type: "point",+ },+ } as VegaLiteSpec;+ expect(makeSelectable(spec1, {})).toEqual(makeSelectable(spec2, {}));+ });++ it("should return correctly if overlapping encodings", () => {+ const spec = {+ config: {+ view: {+ continuousHeight: 300,+ },+ },+ data: { url: "data/cars.json" },+ encoding: {+ color: {+ field: "Origin",+ type: "nominal",+ },+ x: {+ field: "Horsepower",+ type: "quantitative",+ },+ y: {+ field: "Miles_per_Gallon",+ type: "quantitative",+ },+ },+ mark: {+ type: "point",+ },+ } as VegaLiteSpec;+ expect(+ makeSelectable(spec, {+ chartSelection: true,+ fieldSelection: true,+ })+ ).toMatchSnapshot();+ });++ it("should skip field selection if empty or false", () => {+ const spec = {+ config: {+ view: {+ continuousHeight: 300,+ },+ },+ data: { url: "data/cars.json" },+ encoding: {+ color: {+ field: "Origin",+ type: "nominal",+ },+ x: {+ field: "Horsepower",+ type: "quantitative",+ },+ y: {+ field: "Miles_per_Gallon",+ type: "quantitative",+ },+ },+ mark: {+ type: "point",+ },+ } as VegaLiteSpec;++ expect(+ makeSelectable(spec, { chartSelection: true, fieldSelection: false })+ ).toMatchSnapshot();++ // These are the same+ expect(+ makeSelectable(spec, { chartSelection: true, fieldSelection: false })+ ).toEqual(+ makeSelectable(spec, { chartSelection: true, fieldSelection: [] })+ );+ });++ it("should return correctly with multiple encodings", () => {+ const spec = {+ mark: "point",+ encoding: {+ color: {+ field: "colorField",+ type: "nominal",+ },+ size: {+ field: "sizeField",+ type: "quantitative",+ },+ },+ } as VegaLiteSpec;++ expect(makeSelectable(spec, {})).toMatchSnapshot();+ });++ it("should return correctly if existing legend selection", () => {+ const spec = {+ config: {+ view: {+ continuousHeight: 300,+ },+ },+ data: {+ url: "https://cdn.jsdelivr.net/npm/[email protected]/data/unemployment-across-industries.json",+ },+ encoding: {+ color: {+ field: "series",+ scale: { scheme: "category20b" },+ type: "nominal",+ },+ opacity: {+ condition: { param: "param_1", value: 1 },+ value: 0.2,+ },+ x: {+ axis: { domain: false, format: "%Y", tickSize: 0 },+ field: "date",+ timeUnit: "yearmonth",+ type: "temporal",+ },+ y: {+ aggregate: "sum",+ axis: null,+ field: "count",+ stack: "center",+ type: "quantitative",+ },+ },+ mark: { type: "area" },+ params: [+ {+ bind: "legend",+ name: "param_1",+ select: { fields: ["series"], type: "point" },+ },+ ],+ } as VegaLiteSpec;+ expect(makeSelectable(spec, {})).toMatchSnapshot();+ });+});diff --git a/frontend/src/plugins/impl/vega/__tests__/params.test.ts b/frontend/src/plugins/impl/vega/__tests__/params.test.tsnew file mode 100644index 0000000000..d9700d8416--- /dev/null+++ b/frontend/src/plugins/impl/vega/__tests__/params.test.ts@@ -0,0 +1,52 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { expect, describe, it } from "vitest";+import { getDirectionOfBar } from "../params";+import { VegaLiteUnitSpec } from "../types";++describe("getDirectionOfBar", () => {+ it("should return undefined if spec is not provided", () => {+ expect(getDirectionOfBar(undefined!)).toBeUndefined();+ });++ it("should return undefined if mark is not in spec", () => {+ const spec = { encoding: {} } as VegaLiteUnitSpec;+ expect(getDirectionOfBar(spec)).toBeUndefined();+ });++ it('should return "vertical" if xEncoding type is "nominal"', () => {+ const spec = {+ mark: {},+ encoding: { x: { type: "nominal" } },+ } as VegaLiteUnitSpec;+ expect(getDirectionOfBar(spec)).toBe("vertical");+ });++ it('should return "horizontal" if yEncoding type is "nominal"', () => {+ const spec = {+ mark: {},+ encoding: { y: { type: "nominal" } },+ } as VegaLiteUnitSpec;+ expect(getDirectionOfBar(spec)).toBe("horizontal");+ });++ it('should return "horizontal" if xEncoding has "aggregate"', () => {+ const spec = {+ mark: {},+ encoding: { x: { aggregate: "sum" } },+ } as VegaLiteUnitSpec;+ expect(getDirectionOfBar(spec)).toBe("horizontal");+ });++ it('should return "vertical" if yEncoding has "aggregate"', () => {+ const spec = {+ mark: {},+ encoding: { y: { aggregate: "sum" } },+ } as VegaLiteUnitSpec;+ expect(getDirectionOfBar(spec)).toBe("vertical");+ });++ it("should return undefined if no conditions are met", () => {+ const spec = { mark: {}, encoding: { x: {}, y: {} } } as VegaLiteUnitSpec;+ expect(getDirectionOfBar(spec)).toBeUndefined();+ });+});diff --git a/frontend/src/plugins/impl/vega/encodings.ts b/frontend/src/plugins/impl/vega/encodings.tsnew file mode 100644index 0000000000..8548fc731c--- /dev/null+++ b/frontend/src/plugins/impl/vega/encodings.ts@@ -0,0 +1,110 @@+/* Copyright 2023 Marimo. All rights reserved. */+import {+ EncodingType,+ Encodings,+ Field,+ SharedCompositeEncoding,+ VegaLiteSpec,+} from "./types";++/**+ * Vega has multiple types of encodings: x, y, color, size, etc.+ *+ * For all the non-xy encodings, we want to find all the fields that are encoded.+ * These are the encodings that are placed on the legend and thus selectable.+ */+export function findEncodedFields(spec: VegaLiteSpec): string[] {+ if (!spec || !("encoding" in spec)) {+ return [];+ }++ const { encoding } = spec;+ if (!encoding) {+ return [];+ }++ const encodings = Object.entries(encoding);++ // We need to find the field from:+ // "color": {+ // "condition": {+ // "field": "?",+ // "type": "nominal",+ // "test": {"and": [{"param": "select"}]}+ // },+ // "value": "grey"+ // },+ // OR+ // "size": {"field": "?", "type": "quantitative"},++ return encodings.flatMap((entry) => {+ const [key, encoding] = entry as [keyof Encodings, Encodings];+ if (!encoding) {+ return [];+ }+ if (!ALLOWED_ENCODING_TYPES.has(key as EncodingType)) {+ return [];+ }++ if ("field" in encoding && typeof encoding.field === "string") {+ return [encoding.field];+ }++ if (+ "condition" in encoding &&+ encoding.condition &&+ typeof encoding.condition === "object" &&+ "field" in encoding.condition &&+ encoding.condition.field &&+ typeof encoding.condition.field === "string"+ ) {+ return [encoding.condition.field];+ }++ return [];+ });+}++// We can add more encodings here if we want to support more+const ALLOWED_ENCODING_TYPES = new Set<EncodingType>([+ "color",+ "fill",+ "fillOpacity",+ "opacity",+ "shape",+ "size",+]);++export function makeEncodingInteractive(+ key: EncodingType,+ encodings: SharedCompositeEncoding<Field>,+ paramNames: string[]+): SharedCompositeEncoding<Field> {+ const test = {+ and: paramNames.map((paramName) => ({+ param: paramName,+ })),+ };++ switch (key) {+ // For most encodings, we want to update the opacity of the mark+ case "color":+ case "fill":+ case "fillOpacity":+ case "opacity":+ case "shape":+ case "size":+ return {+ ...encodings,+ opacity: {+ condition: {+ test: test,+ value: 1,+ },+ value: 0.2,+ },+ };+ default:+ return encodings;+ }+}diff --git a/frontend/src/plugins/impl/vega/make-selectable.ts b/frontend/src/plugins/impl/vega/make-selectable.tsnew file mode 100644index 0000000000..9263c955eb--- /dev/null+++ b/frontend/src/plugins/impl/vega/make-selectable.ts@@ -0,0 +1,149 @@+/* Copyright 2023 Marimo. All rights reserved. */+import {+ GenericVegaSpec,+ Mark,+ SelectionType,+ VegaLiteSpec,+ VegaLiteUnitSpec,+} from "./types";+import { findEncodedFields, makeEncodingInteractive } from "./encodings";+import { Params } from "./params";+import { Marks } from "./marks";++export function makeSelectable<T extends VegaLiteSpec>(+ spec: T,+ opts: {+ chartSelection?: boolean | "interval" | "point";+ fieldSelection?: boolean | string[];+ }+): T {+ // Both default to true+ const { chartSelection = true, fieldSelection = true } = opts;++ // Disable selection if both are false+ if (!chartSelection && !fieldSelection) {+ return spec;+ }++ if ("vconcat" in spec) {+ const subSpecs = spec.vconcat.map((subSpec) =>+ "mark" in subSpec ? makeChartInteractive(subSpec) : subSpec+ );+ return { ...spec, vconcat: subSpecs };+ }++ if ("hconcat" in spec) {+ const subSpecs = spec.hconcat.map((subSpec) =>+ "mark" in subSpec ? makeChartInteractive(subSpec) : subSpec+ );+ return { ...spec, hconcat: subSpecs };+ }++ if (!("mark" in spec)) {+ return spec;+ }++ let resolvedSpec: VegaLiteUnitSpec = spec;+ resolvedSpec = makeLegendSelectable(resolvedSpec, fieldSelection);+ resolvedSpec = makeChartSelectable(resolvedSpec, chartSelection);+ resolvedSpec = makeChartInteractive(resolvedSpec);++ return resolvedSpec as T;+}++/**+ * Given a spec, add the necessary parameters to make the legend selectable.+ */+function makeLegendSelectable(+ spec: VegaLiteUnitSpec,+ fieldSelection: boolean | string[]+): VegaLiteUnitSpec {+ // If fieldSelection is false, we don't do anything+ if (fieldSelection === false) {+ return spec;+ }++ let legendFields = findEncodedFields(spec);+ // If fieldSelection is an array, we filter the fields+ if (Array.isArray(fieldSelection)) {+ legendFields = legendFields.filter((field) =>+ fieldSelection.includes(field)+ );+ }++ const legendParams = legendFields.map((field) => Params.legend(field));+ const nextParams = [...(spec.params || []), ...legendParams];++ return {+ ...spec,+ params: nextParams,+ } as VegaLiteUnitSpec;+}++/**+ * Given a spec, add the necessary parameters to make the chart selectable.+ */+function makeChartSelectable(+ spec: VegaLiteUnitSpec,+ chartSelection: boolean | "interval" | "point"+): VegaLiteUnitSpec {+ // If chartSelection is false, we don't do anything+ if (chartSelection === false) {+ return spec;+ }++ const mark = Marks.getMarkType(spec.mark);+ const resolvedChartSelection =+ chartSelection === true ? getBestSelectionForMark(mark) : [chartSelection];++ if (!resolvedChartSelection) {+ return spec;+ }++ const params = resolvedChartSelection.map((selectionType) =>+ selectionType === "interval" ? Params.interval(spec) : Params.point(spec)+ );++ const nextParams = [...(spec.params || []), ...params];++ return {+ ...spec,+ params: nextParams,+ } as VegaLiteUnitSpec;+}++function makeChartInteractive<T extends GenericVegaSpec>(spec: T): T {+ const prevEncodings = "encoding" in spec ? spec.encoding : undefined;+ const params = spec.params || [];+ const paramNames = params.map((param) => param.name);++ if (params.length === 0) {+ return spec;+ }++ return {+ ...spec,+ mark: Marks.makeClickable(spec.mark),+ encoding: makeEncodingInteractive(+ "opacity",+ prevEncodings || {},+ paramNames+ ),+ };+}++function getBestSelectionForMark(mark: Mark): SelectionType[] | undefined {+ switch (mark) {+ case "text":+ case "arc":+ case "area":+ return ["point"];+ case "bar":+ return ["point", "interval"];+ // there is no best selection for line+ case "line":+ return undefined;+ default:+ return ["point", "interval"];+ }+}diff --git a/frontend/src/plugins/impl/vega/marks.ts b/frontend/src/plugins/impl/vega/marks.tsnew file mode 100644index 0000000000..e39b9b1dab--- /dev/null+++ b/frontend/src/plugins/impl/vega/marks.ts@@ -0,0 +1,21 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { AnyMark, Mark } from "./types";++export const Marks = {+ getMarkType(mark: AnyMark): Mark {+ const type = typeof mark === "string" ? mark : mark.type;+ if (type === "boxplot" || type === "errorband" || type === "errorbar") {+ throw new Error("Not supported");+ }+ return type;+ },+ makeClickable(mark: AnyMark): AnyMark {+ const type = typeof mark === "string" ? mark : mark.type;+ if (type in Mark) {+ return typeof mark === "string"+ ? { type: mark, cursor: "pointer", tooltip: true }+ : ({ ...mark, type, cursor: "pointer", tooltip: true } as AnyMark);+ }+ return mark;+ },+};diff --git a/frontend/src/plugins/impl/vega/params.ts b/frontend/src/plugins/impl/vega/params.tsnew file mode 100644index 0000000000..667e7478bd--- /dev/null+++ b/frontend/src/plugins/impl/vega/params.ts@@ -0,0 +1,136 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { Marks } from "./marks";+import {+ Mark,+ SelectionParameter,+ SingleDefUnitChannel,+ VegaLiteSpec,+ VegaLiteUnitSpec,+} from "./types";++const ParamNames = {+ LEGEND_SELECTION: "legend_selection",+ SELECT: "select",+ HIGHLIGHT: "highlight",+};++export const Params = {+ highlight() {+ return {+ name: ParamNames.HIGHLIGHT,+ select: { type: "point", on: "mouseover" },+ };+ },+ interval(spec: VegaLiteUnitSpec): SelectionParameter<"interval"> {+ return {+ name: `${ParamNames.SELECT}_interval`,+ select: {+ type: "interval",+ encodings: getEncodingAxisForMark(spec),+ mark: {+ fill: "#669EFF",+ fillOpacity: 0.07,+ stroke: "#669EFF",+ strokeOpacity: 0.4,+ },+ },+ };+ },+ point(spec: VegaLiteUnitSpec): SelectionParameter<"point"> {+ return {+ name: `${ParamNames.SELECT}_point`,+ select: {+ type: "point",+ encodings: getEncodingAxisForMark(spec),+ },+ };+ },+ legend(field: string): SelectionParameter<"point"> {+ return {+ name: `${ParamNames.LEGEND_SELECTION}_${field}`,+ select: {+ type: "point",+ fields: [field],+ },+ bind: "legend",+ };+ },+};++export function getEncodingAxisForMark(+ spec: VegaLiteUnitSpec+): SingleDefUnitChannel[] | undefined {+ const mark = Marks.getMarkType(spec.mark);+ switch (mark) {+ case Mark.image:+ case Mark.trail:+ return undefined;+ case Mark.area:+ case Mark.arc:+ return ["color"];+ case Mark.bar: {+ const direction = getDirectionOfBar(spec);+ return direction === "horizontal"+ ? ["y"]+ : direction === "vertical"+ ? ["x"]+ : undefined;+ }+ case Mark.circle:+ case Mark.geoshape:+ case Mark.line:+ case Mark.point:+ case Mark.rect:+ case Mark.rule:+ case Mark.square:+ case Mark.text:+ case Mark.tick:+ return ["x", "y"];+ }+}++export function getSelectionParamNames(spec: VegaLiteSpec): string[] {+ const params = spec.params;+ if (params && params.length > 0) {+ return params+ .filter((param) => {+ return "select" in param && param.select !== undefined;+ })+ .map((param) => {+ return param.name;+ });+ }+ return [];+}++/**+ * Returns the direction of the bar chart.+ */+export function getDirectionOfBar(+ spec: VegaLiteUnitSpec+): "horizontal" | "vertical" | undefined {+ if (!spec || !("mark" in spec)) {+ return undefined;+ }++ const xEncoding = spec.encoding?.x;+ const yEncoding = spec.encoding?.y;++ if (xEncoding && "type" in xEncoding && xEncoding.type === "nominal") {+ return "vertical";+ }++ if (yEncoding && "type" in yEncoding && yEncoding.type === "nominal") {+ return "horizontal";+ }++ if (xEncoding && "aggregate" in xEncoding) {+ return "horizontal";+ }++ if (yEncoding && "aggregate" in yEncoding) {+ return "vertical";+ }++ return undefined;+}diff --git a/frontend/src/plugins/impl/vega/types.ts b/frontend/src/plugins/impl/vega/types.tsnew file mode 100644index 0000000000..fe3064c9f0--- /dev/null+++ b/frontend/src/plugins/impl/vega/types.ts@@ -0,0 +1,24 @@+/* Copyright 2023 Marimo. All rights reserved. */+import type {+ TopLevelUnitSpec,+ GenericUnitSpec,+} from "vega-lite/build/src/spec/unit";+import type { Encoding } from "vega-lite/build/src/encoding";+import type { Field } from "vega-lite/build/src/channeldef";++export type { SharedCompositeEncoding } from "vega-lite/build/src/compositemark";+export type { AnyMark, MarkDef } from "vega-lite/build/src/mark";+export { Mark } from "vega-lite/build/src/mark";+export type { TopLevelSpec as VegaLiteSpec } from "vega-lite";+export { type Field } from "vega-lite/build/src/channeldef";+export type { SingleDefUnitChannel } from "vega-lite/build/src/channel";+export type {+ SelectionParameter,+ SelectionType,+} from "vega-lite/build/src/selection";++export type VegaLiteUnitSpec = TopLevelUnitSpec<Field>;+// eslint-disable-next-line @typescript-eslint/no-explicit-any+export type GenericVegaSpec = GenericUnitSpec<any, any, any>;+export type EncodingType = keyof Encoding<Field>;+export type Encodings = Encoding<Field>;diff --git a/frontend/src/plugins/impl/vega/utils.ts b/frontend/src/plugins/impl/vega/utils.tsnew file mode 100644index 0000000000..f1e1f301ab--- /dev/null+++ b/frontend/src/plugins/impl/vega/utils.ts@@ -0,0 +1,17 @@+/* Copyright 2023 Marimo. All rights reserved. */+export function mergeAsArrays<T>(+ left: T | T[] | undefined,+ right: T | T[] | undefined+): T[] {+ return [...toArray(left), ...toArray(right)];+}++function toArray<T>(value: T | T[] | undefined): T[] {+ if (!value) {+ return [];+ }+ if (Array.isArray(value)) {+ return value;+ }+ return [value];+}diff --git a/frontend/src/plugins/impl/vega/vega.css b/frontend/src/plugins/impl/vega/vega.cssnew file mode 100644index 0000000000..bb92672936--- /dev/null+++ b/frontend/src/plugins/impl/vega/vega.css@@ -0,0 +1,13 @@+.vega-embed {+ width: 100%;+ height: 100%;+ min-width: 300px;+ flex: 1;+}++/* This may have bad performance, but it's the only way I can get the vega chart to fill the space. */+div:has(> marimo-ui-element > marimo-vega) {+ display: block !important;+ flex: 1;+ min-width: 450px;+}diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex bbcc9ad9a0..c4d5fcc400 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -27,6 +27,7 @@ import { TexPlugin } from "./layout/TexPlugin";import { RefreshPlugin } from "./impl/RefreshPlugin";import { MicrophonePlugin } from "./impl/MicrophonePlugin";import { DownloadPlugin } from "./layout/DownloadPlugin";+import { VegaPlugin } from "./impl/vega/VegaPlugin";// List of UI pluginsconst UI_PLUGINS: Array<IPlugin<any, unknown>> = [@@ -47,6 +48,7 @@ const UI_PLUGINS: Array<IPlugin<any, unknown>> = [new SwitchPlugin(),new TextAreaPlugin(),new TextInputPlugin(),+ new VegaPlugin(),];// List of output / layout pluginsdiff --git a/frontend/src/stories/__fixtures__/vega.ts b/frontend/src/stories/__fixtures__/vega.tsnew file mode 100644index 0000000000..76c596e5a4--- /dev/null+++ b/frontend/src/stories/__fixtures__/vega.ts@@ -0,0 +1,225 @@+/* Copyright 2023 Marimo. All rights reserved. */++import { VegaLiteSpec } from "@/plugins/impl/vega/types";++export const BAR_CHART: VegaLiteSpec = {+ data: {+ values: [+ { a: "A", b: 28 },+ { a: "B", b: 55 },+ { a: "C", b: 43 },+ { a: "D", b: 91 },+ { a: "E", b: 81 },+ { a: "F", b: 53 },+ { a: "G", b: 19 },+ { a: "H", b: 87 },+ { a: "I", b: 52 },+ ],+ },+ mark: "bar",+ encoding: {+ x: { field: "a", type: "ordinal" },+ y: { field: "b", type: "quantitative" },+ },+};++export const LINE_CHART: VegaLiteSpec = {+ data: {+ values: [+ { a: "A", b: 28 },+ { a: "B", b: 55 },+ { a: "C", b: 43 },+ { a: "D", b: 91 },+ { a: "E", b: 81 },+ { a: "F", b: 53 },+ { a: "G", b: 19 },+ { a: "H", b: 87 },+ { a: "I", b: 52 },+ ],+ },+ mark: "line",+ encoding: {+ x: { field: "a", type: "ordinal" },+ y: { field: "b", type: "quantitative" },+ },+};++export const POINT_CHART: VegaLiteSpec = {+ data: {+ url: "https://raw.githubusercontent.com/vega/vega/main/docs/data/cars.json",+ },+ mark: "point",+ encoding: {+ x: { field: "Horsepower", type: "quantitative" },+ y: { field: "Miles_per_Gallon", type: "quantitative" },+ },+};++export const AREA_CHART: VegaLiteSpec = {+ data: {+ url: "https://raw.githubusercontent.com/vega/vega/main/docs/data/unemployment-across-industries.json",+ },+ mark: "area",+ encoding: {+ x: {+ timeUnit: "yearmonth",+ field: "date",+ type: "temporal",+ axis: {+ format: "%Y",+ },+ },+ y: {+ aggregate: "sum",+ field: "count",+ type: "quantitative",+ axis: {+ title: "sum of persons unemployed",+ },+ },+ color: {+ field: "series",+ type: "nominal",+ scale: {+ scheme: "category20b",+ },+ },+ },+};++export const PIE_CHART: VegaLiteSpec = {+ data: {+ values: [+ { category: "A", value: 0.4 },+ { category: "B", value: 0.6 },+ ],+ },+ mark: "arc",+ encoding: {+ theta: { field: "value", type: "quantitative" },+ color: { field: "category", type: "nominal" },+ },+};++export const DONUT_CHART: VegaLiteSpec = {+ data: {+ values: [+ { category: "A", value: 0.4 },+ { category: "B", value: 0.6 },+ ],+ },+ mark: "arc",+ encoding: {+ theta: { field: "value", type: "quantitative" },+ color: { field: "category", type: "nominal" },+ stroke: { value: "white" },+ },+};++export const STACKED_BAR_CHART: VegaLiteSpec = {+ data: {+ url: "https://raw.githubusercontent.com/vega/vega/master/docs/data/barley.json",+ },+ mark: "bar",+ encoding: {+ x: { field: "variety" },+ y: { aggregate: "sum", field: "yield" },+ color: { field: "site" },+ },+};++export const TICK_CHART: VegaLiteSpec = {+ ...POINT_CHART,+ mark: "tick",+};++export const CIRCLE_CHART: VegaLiteSpec = {+ ...POINT_CHART,+ encoding: {+ ...POINT_CHART.encoding,+ color: {+ field: "Origin",+ type: "nominal",+ },+ },+ mark: "circle",+};++export const CIRCLE_2_CHART: VegaLiteSpec = {+ $schema: "https://vega.github.io/schema/vega-lite/v5.14.1.json",+ config: {+ view: { continuousHeight: 300, continuousWidth: 300 },+ scale: { bandPaddingInner: 0.2 },+ },+ data: {+ url: "https://raw.githubusercontent.com/vega/vega-lite-v1/master/data/iris.json",+ },+ encoding: {+ color: {+ field: "species",+ type: "nominal",+ },+ size: { field: "petalWidth", type: "quantitative" },+ x: {+ field: "sepalLength",+ scale: { zero: false },+ type: "quantitative",+ },+ y: {+ field: "sepalWidth",+ scale: { padding: 1, zero: false },+ type: "quantitative",+ },+ },+ mark: { type: "circle" },+};++export const SQUARE_CHART: VegaLiteSpec = {+ ...POINT_CHART,+ mark: "square",+};++export const RECT_CHART: VegaLiteSpec = {+ data: {+ url: "https://raw.githubusercontent.com/vega/vega/master/docs/data/movies.json",+ },+ transform: [+ {+ filter: {+ and: [+ { field: "IMDB Rating", valid: true },+ { field: "Rotten Tomatoes Rating", valid: true },+ ],+ },+ },+ ],+ mark: "rect",+ width: 300,+ height: 200,+ encoding: {+ x: {+ bin: { maxbins: 60 },+ field: "IMDB Rating",+ type: "quantitative",+ },+ y: {+ bin: { maxbins: 40 },+ field: "Rotten Tomatoes Rating",+ type: "quantitative",+ },+ color: {+ aggregate: "count",+ type: "quantitative",+ },+ },+ config: {+ view: {+ stroke: "transparent",+ },+ },+};++export const RULE_CHART: VegaLiteSpec = {+ ...POINT_CHART,+ mark: "rule",+};diff --git a/frontend/src/stories/FileUpload.stories.mdx b/frontend/src/stories/file-upload.stories.mdxsimilarity index 100%rename from frontend/src/stories/FileUpload.stories.mdxrename to frontend/src/stories/file-upload.stories.mdxdiff --git a/frontend/src/stories/vega.stories.tsx b/frontend/src/stories/vega.stories.tsxnew file mode 100644index 0000000000..843a64f4e3--- /dev/null+++ b/frontend/src/stories/vega.stories.tsx@@ -0,0 +1,56 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { VegaComponent } from "@/plugins/impl/vega/VegaPlugin";+import { Meta } from "@storybook/react";+import {+ AREA_CHART,+ BAR_CHART,+ CIRCLE_2_CHART,+ CIRCLE_CHART,+ DONUT_CHART,+ LINE_CHART,+ PIE_CHART,+ POINT_CHART,+ RECT_CHART,+ RULE_CHART,+ SQUARE_CHART,+ STACKED_BAR_CHART,+ TICK_CHART,+} from "./__fixtures__/vega";+import { VegaLiteSpec } from "@/plugins/impl/vega/types";++const meta: Meta = {+ title: "Vega",+ args: {},+};+export default meta;++const selectionOptions = [true, false, "interval", "point"] as const;++const chartWithData = (spec: VegaLiteSpec) => (+ <div className="flex flex-col gap-4">+ {selectionOptions.map((selection) => (+ <VegaComponent+ key={String(selection)}+ setValue={console.log}+ value={{}}+ spec={spec}+ chartSelection={selection}+ fieldSelection={true}+ />+ ))}+ </div>+);++export const AreaChart = () => chartWithData(AREA_CHART);+export const BarChart = () => chartWithData(BAR_CHART);+export const CircleChart = () => chartWithData(CIRCLE_CHART);+export const Circle2Chart = () => chartWithData(CIRCLE_2_CHART);+export const DonutChart = () => chartWithData(DONUT_CHART);+export const LineChart = () => chartWithData(LINE_CHART);+export const PieChart = () => chartWithData(PIE_CHART);+export const PointScatterChart = () => chartWithData(POINT_CHART);+export const RectChart = () => chartWithData(RECT_CHART);+export const RuleChart = () => chartWithData(RULE_CHART);+export const SquareChart = () => chartWithData(SQUARE_CHART);+export const StackedBarChart = () => chartWithData(STACKED_BAR_CHART);+export const TickChart = () => chartWithData(TICK_CHART);diff --git a/marimo/_output/formatters/pandas_formatters.py b/marimo/_output/formatters/pandas_formatters.pyindex 707901c0cb..259be7d657 100644--- a/marimo/_output/formatters/pandas_formatters.py+++ b/marimo/_output/formatters/pandas_formatters.py@@ -1,6 +1,8 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations+from typing import Any+from marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.utils import flatten_string@@ -11,7 +13,7 @@ class PandasFormatter(FormatterFactory):return "pandas"def register(self) -> None:- import pandas as pd # type:ignore[import]+ import pandas as pdfrom marimo._output import formatting@@ -25,7 +27,7 @@ class PandasFormatter(FormatterFactory):)@formatting.formatter(pd.Series)- def _show_series(series: pd.Series) -> tuple[str, str]:+ def _show_series(series: pd.Series[Any]) -> tuple[str, str]:return ("text/html",flatten_string(series.to_frame().to_html()),diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.pyindex b627848150..753dc656f0 100644--- a/marimo/_plugins/ui/__init__.py+++ b/marimo/_plugins/ui/__init__.py@@ -5,6 +5,7 @@ This module contains a library of interactive UI elements."""__all__ = [+ "altair_chart","array","batch","button",@@ -27,6 +28,7 @@ __all__ = []+from marimo._plugins.ui._impl.altair_chart import altair_chartfrom marimo._plugins.ui._impl.array import arrayfrom marimo._plugins.ui._impl.batch import batchfrom marimo._plugins.ui._impl.dictionary import dictionarydiff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pynew file mode 100644index 0000000000..5869b9e1e1--- /dev/null+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -0,0 +1,254 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import json+import sys+from typing import (+ TYPE_CHECKING,+ Any,+ Callable,+ Dict,+ Final,+ List,+ Literal,+ Optional,+ Union,+)++from marimo import _loggers+from marimo._output.rich_help import mddoc+from marimo._plugins.ui._core.ui_element import UIElement+from marimo._utils import flatten++LOGGER = _loggers.marimo_logger()++if TYPE_CHECKING:+ import altair # type:ignore[import]+ import pandas as pd++# Selection is a dictionary of the form:+# {+# "signal_channel": {+# "field": ["value1", "value2", ...]+# }+# }+ChartSelection = Dict[str, Dict[str, Union[List[int], List[float], List[str]]]]+VegaSpec = Dict[str, Any]+++def _has_binning(spec: VegaSpec) -> bool:+ """Return True if the spec has binning."""+ if "encoding" not in spec:+ return False+ for encoding in spec["encoding"].values():+ if "bin" in encoding:+ return True+ return False+++def _to_dataframe(vega_spec: VegaSpec) -> pd.DataFrame:+ # Try to import pandas+ try:+ import pandas as pd+ except ImportError:+ LOGGER.error("Pandas is required to render Vega-Lite charts")+ raise ImportError(+ "Pandas is required to render Vega-Lite charts"+ ) from None++ data = vega_spec.get("data", {})+ if "url" in data:+ # If the data is defined as a URL,+ # use pandas to read the data from the URL+ if data["url"].endswith(".csv"):+ df = pd.read_csv(data["url"])+ elif data["url"].endswith(".json"):+ df = pd.read_json(data["url"])+ else:+ raise ValueError(+ f'Unsupported data format: {data["url"]}'+ ) from None+ elif "values" in data:+ # If the data is defined as an inline list,+ # convert the list to a DataFrame+ df = pd.DataFrame(data["values"])+ elif "name" in data:+ # If the data is defined as a named data source,+ # try to find the data source in the Vega-Lite spec+ name = data["name"]+ datasets = vega_spec.get("datasets", {})+ if name in datasets:+ df = pd.DataFrame(datasets[name])+ else:+ raise ValueError(f"Could not find data source {name}") from None+ else:+ raise ValueError("Data source not supported") from None+ return df+++def _filter_dataframe(+ df: pd.DataFrame, selection: ChartSelection+) -> pd.DataFrame:+ for _channel, fields in selection.items():+ # If vlPoint is in the selection,+ # then the selection is a point selection+ # otherwise, it is an interval selection+ is_point_selection = "vlPoint" in fields+ for field, values in fields.items():+ # Skip vlPoint and _vgsid_ field+ if field == "vlPoint" or field == "_vgsid_":+ continue+ if is_point_selection:+ df = df[df[field].isin(values)]+ elif len(values) == 1:+ df = df[df[field] == values[0]]+ # Range selection+ elif len(values) == 2 and isinstance(values[0], (int, float)):+ df = df[(df[field] >= values[0]) & (df[field] <= values[1])]+ # Multi-selection via range+ # This can happen when you use an interval selection+ # on categorical data+ elif len(values) > 1:+ df = df[df[field].isin(values)]+ else:+ raise ValueError(+ f"Invalid selection: {field}={values}"+ ) from None+ return df+++def _parse_spec(spec: Union[str, altair.Chart, VegaSpec]) -> VegaSpec:+ if spec is None or spec == "":+ return {}++ # Parse Altair chart, str, or dict+ try:+ try:+ import altair++ if isinstance(spec, altair.Chart):+ return json.loads(spec.to_json()) # type: ignore+ except ImportError:+ pass++ if isinstance(spec, dict):+ return spec+ elif isinstance(spec, str):+ return json.loads(spec) # type: ignore+ except json.JSONDecodeError as err:+ raise ValueError(f"Invalid Vega-Lite spec: {spec}") from err++ raise ValueError("Invalid Vega-Lite spec") from None+++@mddoc+class altair_chart(UIElement[ChartSelection, "pd.DataFrame"]):+ """Make reactive charts with Altair++ Use `mo.ui.altair_chart` to make Altair charts reactive: select chart data+ with your cursor on the frontend, get them as a Pandas dataframe in Python!++ **Example.**++ ```python+ import altair as alt+ import marimo as mo+ from vega_datasets import data++ chart = alt.Chart(data.cars()).mark_point().encode(+ x='Horsepower',+ y='Miles_per_Gallon',+ color='Origin',+ )++ chart = mo.ui.altair_chart(chart)+ ```++ ```+ # View the chart and selected data as a dataframe+ mo.hstack([chart, chart.value])+ ```++ **Attributes.**++ - `value`: a Pandas dataframe of the plot data filtered by the selections+ - `dataframe`: a Pandas dataframe of the unfiltered chart data+ - `selections`: the selection of the chart; this may be an interval along+ the name of an axis or a selection of points++ **Initialization Args.**++ - `chart`: An `altair.Chart`+ - `chart_selection`: optional selection type,+ `"point"`, `"interval"`, or a bool; defaults to `True` which will+ automatically detect the best selection type+ - `legend_selection`: optional list of legend fields (columns) for which to+ enable selecton, `True` to enable selection for all fields, or+ `False` to disable selection entirely+ - `label`: optional text label for the element+ - `on_change`: optional callback to run when this element's value changes+ """++ name: Final[str] = "marimo-vega"++ def __init__(+ self,+ figure: altair.Chart,+ chart_selection: Literal["point"] | Literal["interval"] | bool = True,+ legend_selection: list[str] | bool = True,+ *,+ label: str = "",+ on_change: Optional[Callable[[pd.DataFrame], None]] = None,+ ) -> None:+ vega_spec = _parse_spec(figure)+ self.dataframe = _to_dataframe(vega_spec)++ if label:+ vega_spec["title"] = label++ # Automatically add full width+ if "width" not in vega_spec:+ vega_spec["width"] = "container"+ if "vconcat" in vega_spec:+ for chart in vega_spec["vconcat"]:+ if "width" not in chart:+ chart["width"] = "container"+ # without autosize, vconcat will overflow+ if "autosize" not in vega_spec:+ vega_spec["autosize"] = "fit-x"++ # Selection for binned charts is not yet implemented+ if _has_binning(vega_spec):+ sys.stderr.write(+ "Binning + selection is not yet supported in "+ "marimo.ui.chart.\n"+ "If you'd like this feature, please file an issue: "+ "https://github.com/marimo-team/marimo/issues\n"+ )+ chart_selection = False+ legend_selection = False++ super().__init__(+ component_name="marimo-vega",+ initial_value={},+ label=label,+ args={+ "spec": vega_spec,+ "chart-selection": chart_selection,+ "field-selection": legend_selection,+ },+ on_change=on_change,+ )++ @property+ def selections(self) -> ChartSelection:+ return self._chart_selection++ def _convert_value(self, value: ChartSelection) -> Any:+ self._chart_selection = value+ flat, _ = flatten.flatten(value)+ if not value or not flat:+ import pandas as pd++ return pd.DataFrame()+ return _filter_dataframe(self.dataframe, value)diff --git a/marimo/_plugins/ui/_impl/microphone.py b/marimo/_plugins/ui/_impl/microphone.pyindex 014726dda4..f674764df6 100644--- a/marimo/_plugins/ui/_impl/microphone.py+++ b/marimo/_plugins/ui/_impl/microphone.py@@ -13,7 +13,7 @@ from marimo._plugins.ui._core.ui_element import UIElementclass microphone(UIElement[str, io.BytesIO]):"""An audio recorder element.- Use `mo.microphone` to record audio via the user's browser. The+ Use `mo.ui.microphone` to record audio via the user's browser. Theuser must grant permission to use the microphone.**Example.**diff --git a/marimo/_plugins/ui/_impl/test_altair_chart.py b/marimo/_plugins/ui/_impl/test_altair_chart.pynew file mode 100644index 0000000000..44bec2133c--- /dev/null+++ b/marimo/_plugins/ui/_impl/test_altair_chart.py@@ -0,0 +1,102 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import pandas as pd++from marimo._plugins.ui._impl.altair_chart import (+ ChartSelection,+ VegaSpec,+ _filter_dataframe,+ _to_dataframe,+)+++def test_to_data_frame() -> None:+ # Test with URL data source+ vega_spec_url: VegaSpec = {+ "data": {+ "url": "https://raw.githubusercontent.com/vega/vega/main/docs/data/cars.json"+ }+ }+ df_url = _to_dataframe(vega_spec_url)+ assert isinstance(df_url, pd.DataFrame)+ assert not df_url.empty++ # Test with inline list data source+ vega_spec_values: VegaSpec = {+ "data": {+ "values": [+ {"column1": "value1", "column2": "value2"},+ {"column1": "value3", "column2": "value4"},+ ]+ }+ }+ df_values = _to_dataframe(vega_spec_values)+ assert isinstance(df_values, pd.DataFrame)+ assert not df_values.empty+ assert len(df_values) == 2+ assert list(df_values.columns) == ["column1", "column2"]++ # Test with named data source+ vega_spec_values = {+ "data": {"name": "named_data_source"},+ "datasets": {+ "named_data_source": [+ {"column1": "value1", "column2": "value2"},+ {"column1": "value3", "column2": "value4"},+ ]+ },+ }+ df_values = _to_dataframe(vega_spec_values)+ assert isinstance(df_values, pd.DataFrame)+ assert not df_values.empty+ assert len(df_values) == 2+ assert list(df_values.columns) == ["column1", "column2"]++ # Test with unsupported data source+ vega_spec_unsupported = {"data": {"name": "named_data_source"}}+ try:+ _to_dataframe(vega_spec_unsupported)+ raise AssertionError("Expected ValueError was not raised")+ except ValueError:+ pass+++def test_filter_dataframe() -> None:+ df = pd.DataFrame(+ {+ "field": ["value1", "value2", "value3", "value4"],+ "color": ["red", "red", "blue", "blue"],+ "field_2": [1, 2, 3, 4],+ "field_3": [10, 20, 30, 40],+ }+ )++ # Define a point selection+ point_selection: ChartSelection = {+ "signal_channel_1": {"vlPoint": [1], "field": ["value1", "value2"]}+ }+ # Filter the DataFrame with the point selection+ assert len(_filter_dataframe(df, point_selection)) == 2++ # Define an interval selection+ interval_selection: ChartSelection = {+ "signal_channel_2": {"field_2": [1, 3]}+ }+ # Filter the DataFrame with the interval selection+ assert len(_filter_dataframe(df, interval_selection)) == 3++ # Define an interval selection with multiple fields+ multi_field_selection: ChartSelection = {+ "signal_channel_1": {"field_2": [1, 3], "field_3": [30, 40]}+ }+ # Filter the DataFrame with the multi-field selection+ assert len(_filter_dataframe(df, multi_field_selection)) == 1++ # Define an interval selection with multiple fields+ interval_and_point_selection: ChartSelection = {+ "signal_channel_1": {"field_2": [1, 3], "field_3": [20, 40]},+ "signal_channel_2": {"vlPoint": [1], "color": ["red"]},+ }+ # Filter the DataFrame with the multi-field selection+ assert len(_filter_dataframe(df, interval_and_point_selection)) == 1diff --git a/marimo/_smoke_tests/altair_charts.py b/marimo/_smoke_tests/altair_charts.pynew file mode 100644index 0000000000..91f912756a--- /dev/null+++ b/marimo/_smoke_tests/altair_charts.py@@ -0,0 +1,386 @@+import marimo++__generated_with = "0.1.24"+app = marimo.App(width="full")+++def __():+ import marimo as mo+ from vega_datasets import data+ import json+ import pandas as pd+ return data, json, mo, pd+++def __(data):+ # data+ cars = data.cars()+ employment = data.unemployment_across_industries.url+ iris = data.iris()+ return cars, employment, iris+++def __(mo):+ chart_selection_type = mo.ui.radio(+ ["default", "point", "interval"],+ label="Selection Type",+ value="default",+ )+ theme = mo.ui.radio(+ ["default", "dark", "latimes"], label="Theme", value="default"+ )+ legend_selection_type = mo.ui.radio(+ ["all", "none"], label="Legend Selection Type", value="all"+ )++ mo.hstack([chart_selection_type, legend_selection_type, theme]).callout()+ return chart_selection_type, legend_selection_type, theme+++def __(chart_selection_type, legend_selection_type, theme):+ import altair as alt++ alt.themes.enable(theme.value)+ chart_selection_value = (+ True+ if chart_selection_type.value == "default"+ else chart_selection_type.value+ )+ legend_selection_value = legend_selection_type.value == "all"+ None+ return alt, chart_selection_value, legend_selection_value+++def __(alt, cars, chart_selection_value, legend_selection_value, mo):+ _chart = (+ alt.Chart(cars)+ .mark_point()+ .encode(+ x="Horsepower",+ y="Miles_per_Gallon",+ color="Origin",+ )+ )+ chart1 = mo.ui.altair_chart(+ _chart,+ chart_selection=chart_selection_value,+ legend_selection=legend_selection_value,+ label="Cars",+ )+ return chart1,+++def __(mo):+ mo.md("# Basic Chart")+ return+++def __(alt, chart1, chart_selection_value, legend_selection_value, mo):+ mo.vstack(+ [+ chart1,+ mo.ui.altair_chart(+ alt.Chart(chart1.value)+ .mark_bar()+ .encode(+ x="Origin",+ y="count()",+ color="Origin",+ ),+ chart_selection=chart_selection_value,+ legend_selection=legend_selection_value,+ )+ if not chart1.value.empty+ else mo.md("No selection"),+ chart1.value.head(),+ ]+ )+ return+++def __(alt, chart_selection_value, employment, legend_selection_value, mo):+ # _selection = alt.selection_point(fields=["series"], bind="legend")++ _chart = (+ alt.Chart(employment)+ .mark_area()+ .encode(+ alt.X("yearmonth(date):T").axis(domain=False, format="%Y", tickSize=0),+ alt.Y("sum(count):Q").stack("center").axis(None),+ alt.Color("series:N").scale(scheme="category20b"),+ # opacity=alt.condition(_selection, alt.value(1), alt.value(0.9)),+ )+ )+ # ).add_params(_selection)+ chart2 = mo.ui.altair_chart(+ _chart,+ chart_selection=chart_selection_value,+ legend_selection=legend_selection_value,+ )+ return chart2,+++def __(mo):+ mo.md("# Another Chart")+ return+++def __(chart2, mo):+ mo.vstack([chart2, chart2.value.head(10)])+ return+++def __(alt, chart_selection_value, iris, legend_selection_value, mo):+ # _color_sel = alt.selection_point(fields=["species"], bind="legend")+ # _size_sel = alt.selection_point(fields=["petalWidth"], bind="legend")++ _chart = (+ alt.Chart(iris)+ .mark_circle()+ .encode(+ alt.X("sepalLength", scale=alt.Scale(zero=False)),+ alt.Y("sepalWidth", scale=alt.Scale(zero=False, padding=1)),+ color="species",+ size="petalWidth",+ # opacity=alt.condition(+ # _color_sel & _size_sel, alt.value(1), alt.value(0.2)+ # ),+ )+ # .add_params(_color_sel, _size_sel)+ )++ chart3 = mo.ui.altair_chart(+ _chart,+ chart_selection=chart_selection_value,+ legend_selection=legend_selection_value,+ )+ return chart3,+++def __(mo):+ mo.md("# Chart + Chart")+ return+++def __(chart3, mo):+ mo.hstack([chart3, chart3])+ return+++def __(mo):+ mo.md("# Chart + Table")+ return+++def __(chart3, mo):+ mo.hstack([chart3, chart3.value.head(10)])+ return+++def __(mo):+ mo.md("# Chart + Table returned as an array")+ return+++def __(chart3):+ [chart3, chart3.value.head(10)]+ return+++def __(alt, cars, chart_selection_value, legend_selection_value, mo):+ brush = alt.selection_interval()+ points = (+ alt.Chart(cars)+ .mark_point()+ .encode(+ x="Horsepower:Q",+ y="Miles_per_Gallon:Q",+ color=alt.condition(brush, "Origin:N", alt.value("lightgray")),+ )+ .add_params(brush)+ )+ bars = (+ alt.Chart(cars)+ .mark_bar()+ .encode(y="Origin:N", color="Origin:N", x="count(Origin):Q")+ .transform_filter(brush)+ )+ plot = points & bars+ chart4 = mo.ui.altair_chart(+ plot,+ chart_selection=chart_selection_value,+ legend_selection=legend_selection_value,+ )+ return bars, brush, chart4, plot, points+++def __(mo):+ mo.md("# Chart with transform")+ return+++def __(chart4, mo):+ mo.vstack([chart4, chart4.value.head(10)])+ return+++def __(mo):+ mo.md("# Bar chart")+ return+++def __(alt, data, mo):+ binned = mo.ui.altair_chart(+ alt.Chart(data.cars())+ .mark_bar()+ .encode(x=alt.X("Miles_per_Gallon:Q", bin=True), y="count()")+ )+ return binned,+++def __(alt, cars, mo):+ mean = mo.ui.altair_chart(+ alt.Chart(cars)+ .mark_bar()+ .encode(+ x="Cylinders:O",+ y="mean(Acceleration):Q",+ )+ )+ return mean,+++def __(mean, mo):+ mo.vstack([mean, mean.value])+ return+++def __(alt, data, mo):+ hist = (+ alt.Chart(data.cars())+ .mark_bar()+ .encode(x=alt.X("Miles_per_Gallon:Q"), y="count()")+ )+ hist = mo.ui.altair_chart(hist)+ return hist,+++def __(hist, mo):+ mo.vstack([hist, hist.value])+ return+++def __(mo):+ mo.md("# Pivot and horizontal bar chart")+ return+++def __(alt, mo, pd):+ df = pd.DataFrame.from_records(+ [+ {"country": "Norway", "type": "gold", "count": 14},+ {"country": "Norway", "type": "silver", "count": 14},+ {"country": "Norway", "type": "bronze", "count": 11},+ {"country": "Germany", "type": "gold", "count": 14},+ {"country": "Germany", "type": "silver", "count": 10},+ {"country": "Germany", "type": "bronze", "count": 7},+ {"country": "Canada", "type": "gold", "count": 11},+ {"country": "Canada", "type": "silver", "count": 8},+ {"country": "Canada", "type": "bronze", "count": 10},+ ]+ )++ pivot = mo.ui.altair_chart(+ alt.Chart(df)+ .transform_pivot("type", groupby=["country"], value="count")+ .mark_bar()+ .encode(+ x="gold:Q",+ y="country:N",+ )+ )+ return df, pivot+++def __(mo, pivot):+ mo.vstack([pivot, pivot.value.head()])+ return+++def __(alt, data, mo):+ _source = data.population.url++ horizontal_bar = mo.ui.altair_chart(+ alt.Chart(_source)+ .mark_bar()+ .encode(+ alt.X("sum(people):Q").title("Population"),+ alt.Y("age:O"),+ )+ .transform_filter(alt.datum.year == 2000)+ .properties(height=alt.Step(20))+ )+ return horizontal_bar,+++def __(horizontal_bar, mo):+ mo.vstack([horizontal_bar, horizontal_bar.value.head()])+ return+++def __(alt, mo, pd):+ _source = pd.DataFrame(+ {"category": [1, 2, 3, 4, 5, 6], "value": [4, 6, 10, 3, 7, 8]}+ )++ pie = mo.ui.altair_chart(+ alt.Chart(_source)+ .mark_arc(innerRadius=50)+ .encode(+ theta="value",+ color="category:N",+ )+ )+ return pie,+++def __(mo, pie):+ mo.vstack([pie, pie.value])+ return+++if __name__ == "__main__":+ app.run()diff --git a/pyproject.toml b/pyproject.tomlindex 158830ecb0..0de6f49b21 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -55,6 +55,9 @@ dev = ["click < 8.1.4", # https://github.com/pallets/click/issues/2558"black~=23.3.0","build~=0.10.0",+ # For testing mo.ui.chart+ "pandas>=1.3.0",+ "pandas-stubs>=1.3.0","pytest~=7.4.0","mypy~=1.4.1","ruff~=0.0.275",