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
improvement: use vegafusion for datasource panel when available (#4068)
Myles Scolnick44f9160b4004
diff --git a/marimo/_data/charts.py b/marimo/_data/charts.pyindex 8d33a70771..eacfeea2d8 100644--- a/marimo/_data/charts.py+++ b/marimo/_data/charts.py@@ -6,8 +6,11 @@ from dataclasses import dataclassfrom textwrap import dedentfrom typing import Any, cast+import narwhals.stable.v1 as nw+from marimo._data.models import DataTypefrom marimo._utils import assert_never+from marimo._utils.narwhals_utils import can_narwhalify@abc.abstractmethod@@ -17,7 +20,12 @@ class ChartBuilder:raise NotImplementedErrordef altair_json(self, data: Any, column: str) -> str:- return cast(str, self.altair(data, column).to_json())+ import altair as alt # type: ignore[import-not-found]++ if alt.data_transformers.active.startswith("vegafusion"):+ return cast(str, self.altair(data, column).to_json(format="vega"))+ else:+ return cast(str, self.altair(data, column).to_json())@abc.abstractmethoddef altair_code(self, data: str, column: str) -> str:@@ -32,7 +40,7 @@ class ChartParams:class NumberChartBuilder(ChartBuilder):def altair(self, data: Any, column: str) -> Any:- import altair as alt # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501+ import altair as alt # type: ignore[import-not-found]return (alt.Chart(data)@@ -136,14 +144,53 @@ class StringChartBuilder(ChartBuilder):class DateChartBuilder(ChartBuilder):+ DEFAULT_DATE_FORMAT = "%Y-%m-%d"++ def _guess_date_format(self, data: Any, column: str) -> str:+ """Guess the appropriate date format based on the range of dates in the column."""+ if not can_narwhalify(data, eager_only=True):+ return "%Y-%m-%d"++ df = nw.from_native(data, eager_only=True)++ # Get min and max dates using narwhals+ min_date = df[column].min()+ max_date = df[column].max()++ # Calculate the difference in days+ time_diff = max_date - min_date+ if not hasattr(time_diff, "days"):+ return self.DEFAULT_DATE_FORMAT++ days_diff = time_diff.days++ # Choose format based on the range+ if days_diff > 365 * 10: # More than 10 years+ return "%Y" # Year only+ elif days_diff > 365: # More than a year+ return "%Y-%m" # Year and month+ elif days_diff > 31: # More than a month+ return "%Y-%m-%d" # Full date+ elif days_diff > 1: # More than a day+ return "%Y-%m-%d %H" # Date and time (hours)+ else:+ return "%Y-%m-%d %H:%M" # Date and time (hours, minutes)+def altair(self, data: Any, column: str) -> Any:import altair as alt # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501return (alt.Chart(data)- .mark_line(point={"filled": False, "fill": "white"})+ .mark_bar().encode(- x=alt.X(column, type="temporal"),+ x=alt.X(+ column,+ type="temporal",+ bin=alt.Bin(maxbins=20),+ axis=alt.Axis(+ format=self._guess_date_format(data, column)+ ),+ ),y=alt.Y("count()", type="quantitative"),).properties(width="container")@@ -153,9 +200,14 @@ class DateChartBuilder(ChartBuilder):return f"""_chart = (alt.Chart({data})- .mark_line(point={{"filled": False, "fill": "white"}})+ .mark_bar().encode(- x=alt.X("{column}", type="temporal"),+ x=alt.X(+ "{column}",+ type="temporal",+ bin=alt.Bin(maxbins=20),+ axis=alt.Axis(format="%Y-%m-%d")+ ),y=alt.Y("count()", type="quantitative"),).properties(width="container")diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.pyindex 5115d9423e..efde5b3e95 100644--- a/marimo/_data/preview_column.py+++ b/marimo/_data/preview_column.py@@ -187,27 +187,44 @@ def _get_altair_chart()chart_max_rows_errors = False- try:++ def get_chart_json() -> str:+ # Filter the data to the column we wantcolumn_data = table.select_columns([request.column_name]).data++ # If we have vegafusion and vl-convert-python, use it+ if (+ DependencyManager.vegafusion.has()+ and DependencyManager.vl_convert_python.has()+ ):+ with alt.data_transformers.enable("vegafusion"):+ return chart_builder.altair_json(+ column_data,+ request.column_name,+ )+# Date types don't serialize well to csv,# so we don't transform them- if (+ dont_use_csv = (column_type == "date"or column_type == "datetime"or column_type == "time"- ):+ )+ if dont_use_csv:# Default max_rows is 5_000, but we can support more.with alt.data_transformers.enable("default", max_rows=20_000):- chart_json = chart_builder.altair_json(- column_data,- request.column_name,- )- else:- with alt.data_transformers.enable("marimo_inline_csv"):- chart_json = chart_builder.altair_json(+ return chart_builder.altair_json(column_data,request.column_name,)+ with alt.data_transformers.enable("marimo_inline_csv"):+ return chart_builder.altair_json(+ column_data,+ request.column_name,+ )++ try:+ chart_json = get_chart_json()except MaxRowsError:chart_json = Nonechart_max_rows_errors = Truediff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 0a3a102382..caf2c910f2 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -188,6 +188,8 @@ class DependencyManager:groq = Dependency("groq")panel = Dependency("panel")sqlalchemy = Dependency("sqlalchemy")+ vegafusion = Dependency("vegafusion")+ vl_convert_python = Dependency("vl_convert")# Version requirements to properly support the new superfences introduced in# pymdown#2470diff --git a/marimo/_plugins/ui/_impl/tables/utils.py b/marimo/_plugins/ui/_impl/tables/utils.pyindex 7b8e3e9fdf..68d960b638 100644--- a/marimo/_plugins/ui/_impl/tables/utils.py+++ b/marimo/_plugins/ui/_impl/tables/utils.py@@ -45,7 +45,7 @@ def get_table_manager_or_none(data: Any) -> TableManager[Any] | None:return manager(data)# Fallback to generic NarwhalsTableManager- if can_narwhalify(data):+ if can_narwhalify(data, eager_only=False):return NarwhalsTableManager.from_dataframe(data)return Nonediff --git a/marimo/_smoke_tests/altair/vegafusion_histograms.py b/marimo/_smoke_tests/altair/vegafusion_histograms.pynew file mode 100644index 0000000000..899b9ef8eb--- /dev/null+++ b/marimo/_smoke_tests/altair/vegafusion_histograms.py@@ -0,0 +1,135 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "altair==5.5.0",+# "marimo",+# "numpy==2.2.3",+# "openai==1.66.2",+# "pandas==2.2.3",+# "polars==1.24.0",+# "vegafusion==2.0.2",+# "vl-convert-python==1.7.0",+# ]+# ///++import marimo++__generated_with = "0.11.18"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ return (mo,)+++def _(alt, flights):+ _chart = (+ alt.Chart(flights)+ .mark_line(point={"filled": False, "fill": "white"})+ .encode(+ x=alt.X("date", type="temporal"),+ y=alt.Y("count()", type="quantitative"),+ )+ .properties(width="container")+ )+ _chart+ return+++def _(mo):+ mo.md(r"""# Histograms with vegafusion""")+ return+++def _():+ import polars as pl+ import altair as alt+ import vegafusion as vf++ # Requires vl-convert-python as well++ alt.data_transformers.enable("vegafusion")++ # Comment out to disable duckdb connection+ # vf.runtime.set_connection("duckdb")++ flights = pl.read_parquet(+ "https://vegafusion-datasets.s3.amazonaws.com/vega/flights_1m.parquet"+ )+ return alt, flights, pl, vf+++def _(alt, flights):+ delay_hist = (+ alt.Chart(flights)+ .mark_bar()+ .encode(alt.X("delay", bin=alt.Bin(maxbins=30)), alt.Y("count()"))+ )+ delay_hist+ return (delay_hist,)+++def _(flights, mo):+ mo.ui.table(flights[0:100], show_column_summaries=True)+ return+++def _(alt, flights, mo):+ columns = flights.columns+ charts = []+ for col in columns:+ if flights[col].dtype.is_numeric() or flights[col].dtype.is_temporal():+ charts.append(+ alt.Chart(flights)+ .mark_bar()+ .encode(+ alt.X(col, bin=alt.Bin(maxbins=15), axis=None),+ alt.Y("count()", axis=None),+ # Color nulls differently+ color=alt.condition(+ f"datum.bin_maxbins_15_{col}_range === null",+ alt.value("#FDA4AF"), # orange for nulls+ alt.value("#027864"), # mint for non-nulls+ ),+ tooltip=[col, "count()"],+ )+ )+ else:+ # aggregate+ charts.append(+ alt.Chart(flights)+ .mark_bar()+ .encode(+ alt.X(col),+ alt.Y("count()"),+ # Color nulls differently+ color=alt.condition(+ f"datum.{col} === null",+ alt.value("#FDA4AF"), # orange for nulls+ alt.value("#027864"), # mint for non-nulls+ ),+ tooltip=[col, "count()"],+ )+ )+ mo.hstack(charts)+ return charts, col, columns+++def _(delay_hist, mo):+ mo.md(+ f"Total buckets **{len(delay_hist.to_dict(format='vega')['data'][0]['values'])}**"+ )+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/altair/vegafusion_nb.py b/marimo/_smoke_tests/altair/vegafusion_nb.pyindex 28d9cf4c22..315bff6fb7 100644--- a/marimo/_smoke_tests/altair/vegafusion_nb.py+++ b/marimo/_smoke_tests/altair/vegafusion_nb.py@@ -4,15 +4,15 @@# "pandas==2.2.3",# "altair==5.5.0",# "marimo",-# "vegafusion==2.0.1",# "pyarrow==18.1.0",# "vl-convert-python==1.7.0",+# "vegafusion==2.0.2",# ]# ///import marimo-__generated_with = "0.10.9"+__generated_with = "0.11.18"app = marimo.App(width="medium")diff --git a/marimo/_smoke_tests/charts/histograms.py b/marimo/_smoke_tests/charts/histograms.pynew file mode 100644index 0000000000..3e01922b6f--- /dev/null+++ b/marimo/_smoke_tests/charts/histograms.py@@ -0,0 +1,68 @@+import marimo++__generated_with = "0.11.18"+app = marimo.App(width="full")++[email protected](hide_code=True)+def _(mo):+ mo.md(r"""This is some experimental work to see if we can pre-aggregate column charts on the backend for performance. We are trying to use the dataframe of choice, to avoid additional dependencies.""")+ return++[email protected](hide_code=True)+def _(pl):+ df = pl.read_csv("hf://datasets/scikit-learn/Fish/Fish.csv")+ df+ return (df,)++[email protected](hide_code=True)+def _(alt, charts, mo):+ _charts = []+ for _col, data in charts.items():+ chart = mo.ui.altair_chart(+ alt.Chart(alt.Data(values=data))+ .mark_bar()+ .encode(+ x=alt.X("breakpoint:Q", bin=alt.Bin(maxbins=10), title=f"{_col}"),+ y="count:Q",+ )+ .properties(title=f"Histogram of {_col}"),+ chart_selection=None,+ legend_selection=None,+ )+ _charts.append(chart)+ mo.hstack(_charts)+ return chart, data+++def _(df, pl):+ charts = {}+ for col in df.columns:+ if df[col].dtype in [pl.datatypes.Float64, pl.datatypes.Int64]:+ hist_data = df[col].hist().to_dicts()+ charts[col] = hist_data++ charts.keys()+ return charts, col, hist_data+++def _(df):+ res = df["Weight"].hist().to_dicts()+ res[0]+ return (res,)+++def _():+ import marimo as mo+ import polars as pl+ import altair as alt+ return alt, mo, pl+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.pyindex a17fc94f90..06a510ca18 100644--- a/marimo/_utils/narwhals_utils.py+++ b/marimo/_utils/narwhals_utils.py@@ -42,7 +42,9 @@ def assert_narwhals_series(series: nw.Series) -> None:raise ValueError(f"Unsupported series type. Got {type(series)}")-def can_narwhalify(obj: Any, eager_only: bool = False) -> TypeGuard[IntoFrame]:+def can_narwhalify(+ obj: Any, *, eager_only: bool = False+) -> TypeGuard[IntoFrame]:"""Check if the given object can be narwhalified."""diff --git a/pyproject.toml b/pyproject.tomlindex f31d6dd762..7a9f077d35 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -86,6 +86,7 @@ sql = [# List of deps that are recommended for most users# in order to unlock all features in marimo+# This includes the `sql` depsrecommended = ["duckdb>=1.0.0", # SQL cells"altair>=5.4.0", # Plotting in datasource viewer@@ -94,6 +95,8 @@ recommended = ["openai>=1.55.3", # AI features"ruff", # Formatting"nbformat>=5.7.0", # Export as IPYNB+ "vegafusion>=2.0.0", # Performant charting+ "vl-convert-python>=1.0.0", # Required by vegafusion]dev = [@@ -235,6 +238,7 @@ extra-dependencies = ["pytest-asyncio~=0.25.2",# For testing mo.ui.chart, table, ..."vl-convert-python",+ "vegafusion","pyarrow","pyarrow_hotfix","altair>=5.4.0",diff --git a/tests/_data/snapshots/charts.txt b/tests/_data/snapshots/charts.txtindex f7d5075f51..f5e39e624a 100644--- a/tests/_data/snapshots/charts.txt+++ b/tests/_data/snapshots/charts.txt@@ -13,9 +13,14 @@ _chart# date_chart = (alt.Chart(df)- .mark_line(point={"filled": False, "fill": "white"})+ .mark_bar().encode(- x=alt.X("some_column", type="temporal"),+ x=alt.X(+ "some_column",+ type="temporal",+ bin=alt.Bin(maxbins=20),+ axis=alt.Axis(format="%Y-%m-%d")+ ),y=alt.Y("count()", type="quantitative"),).properties(width="container")@@ -25,9 +30,14 @@ _chart# datetime_chart = (alt.Chart(df)- .mark_line(point={"filled": False, "fill": "white"})+ .mark_bar().encode(- x=alt.X("some_column", type="temporal"),+ x=alt.X(+ "some_column",+ type="temporal",+ bin=alt.Bin(maxbins=20),+ axis=alt.Axis(format="%Y-%m-%d")+ ),y=alt.Y("count()", type="quantitative"),).properties(width="container")@@ -37,9 +47,14 @@ _chart# time_chart = (alt.Chart(df)- .mark_line(point={"filled": False, "fill": "white"})+ .mark_bar().encode(- x=alt.X("some_column", type="temporal"),+ x=alt.X(+ "some_column",+ type="temporal",+ bin=alt.Bin(maxbins=20),+ axis=alt.Axis(format="%Y-%m-%d")+ ),y=alt.Y("count()", type="quantitative"),).properties(width="container")diff --git a/tests/_data/snapshots/charts_json.txt b/tests/_data/snapshots/charts_json.txtindex 99f854f5d6..b8f8a1cf9f 100644--- a/tests/_data/snapshots/charts_json.txt+++ b/tests/_data/snapshots/charts_json.txt@@ -66,6 +66,12 @@},"encoding": {"x": {+ "axis": {+ "format": "%Y-%m-%d"+ },+ "bin": {+ "maxbins": 20+ },"field": "some_column","type": "temporal"},@@ -75,11 +81,7 @@}},"mark": {- "point": {- "fill": "white",- "filled": false- },- "type": "line"+ "type": "bar"},"width": "container"}@@ -111,6 +113,12 @@},"encoding": {"x": {+ "axis": {+ "format": "%Y-%m-%d"+ },+ "bin": {+ "maxbins": 20+ },"field": "some_column","type": "temporal"},@@ -120,11 +128,7 @@}},"mark": {- "point": {- "fill": "white",- "filled": false- },- "type": "line"+ "type": "bar"},"width": "container"}@@ -156,6 +160,12 @@},"encoding": {"x": {+ "axis": {+ "format": "%Y-%m-%d"+ },+ "bin": {+ "maxbins": 20+ },"field": "some_column","type": "temporal"},@@ -165,11 +175,7 @@}},"mark": {- "point": {- "fill": "white",- "filled": false- },- "type": "line"+ "type": "bar"},"width": "container"}diff --git a/tests/_data/snapshots/column_preview_bool_chart_code.txt b/tests/_data/snapshots/column_preview_bool_chart_code.txtnew file mode 100644index 0000000000..bcca6c4606--- /dev/null+++ b/tests/_data/snapshots/column_preview_bool_chart_code.txt@@ -0,0 +1,10 @@+_chart = (+ alt.Chart(table)+ .mark_bar()+ .encode(+ x=alt.X("bool_col", type="nominal"),+ y=alt.Y("count()", type="quantitative"),+ )+ .properties(width="container")+)+_chart\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_bool_chart_spec.txt b/tests/_data/snapshots/column_preview_bool_chart_spec.txtnew file mode 100644index 0000000000..b415b85e34--- /dev/null+++ b/tests/_data/snapshots/column_preview_bool_chart_spec.txt@@ -0,0 +1,29 @@+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",+ "config": {+ "view": {+ "continuousHeight": 300,+ "continuousWidth": 300+ }+ },+ "data": {+ "format": {+ "type": "csv"+ },+ "url": "data:text/csv;base64,Ym9vbF9jb2wKVHJ1ZQpGYWxzZQpUcnVlCg=="+ },+ "encoding": {+ "x": {+ "field": "bool_col",+ "type": "nominal"+ },+ "y": {+ "aggregate": "count",+ "type": "quantitative"+ }+ },+ "mark": {+ "type": "bar"+ },+ "width": "container"+}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_bool_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_bool_chart_spec_with_vegafusion.txtnew file mode 100644index 0000000000..ba9b633f21--- /dev/null+++ b/tests/_data/snapshots/column_preview_bool_chart_spec_with_vegafusion.txt@@ -0,0 +1,170 @@+{+ "$schema": "https://vega.github.io/schema/vega/v5.json",+ "autosize": {+ "contains": "padding",+ "type": "fit-x"+ },+ "axes": [+ {+ "aria": false,+ "domain": false,+ "grid": true,+ "gridScale": "x",+ "labels": false,+ "maxExtent": 0,+ "minExtent": 0,+ "orient": "left",+ "scale": "y",+ "tickCount": {+ "signal": "ceil(height/40)"+ },+ "ticks": false,+ "zindex": 0+ },+ {+ "grid": false,+ "labelAlign": "right",+ "labelAngle": 270,+ "labelBaseline": "middle",+ "orient": "bottom",+ "scale": "x",+ "title": "bool_col",+ "zindex": 0+ },+ {+ "grid": false,+ "labelOverlap": true,+ "orient": "left",+ "scale": "y",+ "tickCount": {+ "signal": "ceil(height/40)"+ },+ "title": "Count of Records",+ "zindex": 0+ }+ ],+ "background": "white",+ "data": [+ {+ "name": "source_0",+ "values": [+ {+ "__count": 2,+ "bool_col": true+ },+ {+ "__count": 1,+ "bool_col": false+ }+ ]+ },+ {+ "name": "source_0_x_domain_bool_col",+ "values": [+ {+ "bool_col": true+ },+ {+ "bool_col": false+ }+ ]+ },+ {+ "name": "source_0_y_domain___count",+ "values": [+ {+ "max": 2,+ "min": 1+ }+ ]+ }+ ],+ "height": 300,+ "marks": [+ {+ "encode": {+ "update": {+ "fill": {+ "value": "#4c78a8"+ },+ "width": {+ "signal": "max(0.25, bandwidth('x'))"+ },+ "x": {+ "field": "bool_col",+ "scale": "x"+ },+ "y": {+ "field": "__count",+ "scale": "y"+ },+ "y2": {+ "scale": "y",+ "value": 0+ }+ }+ },+ "from": {+ "data": "source_0"+ },+ "name": "marks",+ "style": [+ "bar"+ ],+ "type": "rect"+ }+ ],+ "padding": 5,+ "scales": [+ {+ "domain": {+ "data": "source_0_x_domain_bool_col",+ "field": "bool_col",+ "sort": true+ },+ "name": "x",+ "paddingInner": 0.1,+ "paddingOuter": 0.05,+ "range": [+ 0,+ {+ "signal": "width"+ }+ ],+ "type": "band"+ },+ {+ "domain": [+ {+ "signal": "(data(\"source_0_y_domain___count\")[0] || {}).min"+ },+ {+ "signal": "(data(\"source_0_y_domain___count\")[0] || {}).max"+ }+ ],+ "name": "y",+ "nice": true,+ "range": [+ {+ "signal": "height"+ },+ 0+ ],+ "type": "linear",+ "zero": true+ }+ ],+ "signals": [+ {+ "init": "isFinite(containerSize()[0]) ? containerSize()[0] : 300",+ "name": "width",+ "on": [+ {+ "events": "window:resize",+ "update": "isFinite(containerSize()[0]) ? containerSize()[0] : 300"+ }+ ]+ }+ ],+ "style": "cell"+}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_categorical_chart_code.txt b/tests/_data/snapshots/column_preview_categorical_chart_code.txtnew file mode 100644index 0000000000..2c416729b2--- /dev/null+++ b/tests/_data/snapshots/column_preview_categorical_chart_code.txt@@ -0,0 +1,10 @@+_chart = (+ alt.Chart(table)+ .mark_bar()+ .encode(+ y=alt.Y("category_col", type="nominal"),+ x=alt.X("count()", type="quantitative"),+ )+ .properties(width="container")+)+_chart\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_categorical_chart_spec.txt b/tests/_data/snapshots/column_preview_categorical_chart_spec.txtnew file mode 100644index 0000000000..c36ef1a766--- /dev/null+++ b/tests/_data/snapshots/column_preview_categorical_chart_spec.txt@@ -0,0 +1,29 @@+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",+ "config": {+ "view": {+ "continuousHeight": 300,+ "continuousWidth": 300+ }+ },+ "data": {+ "format": {+ "type": "csv"+ },+ "url": "data:text/csv;base64,Y2F0ZWdvcnlfY29sCmNhdDEKY2F0MgpjYXQxCg=="+ },+ "encoding": {+ "x": {+ "aggregate": "count",+ "type": "quantitative"+ },+ "y": {+ "field": "category_col",+ "type": "nominal"+ }+ },+ "mark": {+ "type": "bar"+ },+ "width": "container"+}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_categorical_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_categorical_chart_spec_with_vegafusion.txtnew file mode 100644index 0000000000..01a1d01e92--- /dev/null+++ b/tests/_data/snapshots/column_preview_categorical_chart_spec_with_vegafusion.txt@@ -0,0 +1,174 @@+{+ "$schema": "https://vega.github.io/schema/vega/v5.json",+ "autosize": {+ "contains": "padding",+ "type": "fit-x"+ },+ "axes": [+ {+ "aria": false,+ "domain": false,+ "grid": true,+ "gridScale": "y",+ "labels": false,+ "maxExtent": 0,+ "minExtent": 0,+ "orient": "bottom",+ "scale": "x",+ "tickCount": {+ "signal": "ceil(width/40)"+ },+ "ticks": false,+ "zindex": 0+ },+ {+ "grid": false,+ "labelFlush": true,+ "labelOverlap": true,+ "orient": "bottom",+ "scale": "x",+ "tickCount": {+ "signal": "ceil(width/40)"+ },+ "title": "Count of Records",+ "zindex": 0+ },+ {+ "grid": false,+ "orient": "left",+ "scale": "y",+ "title": "category_col",+ "zindex": 0+ }+ ],+ "background": "white",+ "data": [+ {+ "name": "source_0",+ "values": [+ {+ "__count": 2,+ "category_col": "cat1"+ },+ {+ "__count": 1,+ "category_col": "cat2"+ }+ ]+ },+ {+ "name": "source_0_x_domain___count",+ "values": [+ {+ "max": 2,+ "min": 1+ }+ ]+ },+ {+ "name": "source_0_y_domain_category_col",+ "values": [+ {+ "category_col": "cat1"+ },+ {+ "category_col": "cat2"+ }+ ]+ }+ ],+ "marks": [+ {+ "encode": {+ "update": {+ "fill": {+ "value": "#4c78a8"+ },+ "height": {+ "signal": "max(0.25, bandwidth('y'))"+ },+ "x": {+ "field": "__count",+ "scale": "x"+ },+ "x2": {+ "scale": "x",+ "value": 0+ },+ "y": {+ "field": "category_col",+ "scale": "y"+ }+ }+ },+ "from": {+ "data": "source_0"+ },+ "name": "marks",+ "style": [+ "bar"+ ],+ "type": "rect"+ }+ ],+ "padding": 5,+ "scales": [+ {+ "domain": [+ {+ "signal": "(data(\"source_0_x_domain___count\")[0] || {}).min"+ },+ {+ "signal": "(data(\"source_0_x_domain___count\")[0] || {}).max"+ }+ ],+ "name": "x",+ "nice": true,+ "range": [+ 0,+ {+ "signal": "width"+ }+ ],+ "type": "linear",+ "zero": true+ },+ {+ "domain": {+ "data": "source_0_y_domain_category_col",+ "field": "category_col",+ "sort": true+ },+ "name": "y",+ "paddingInner": 0.1,+ "paddingOuter": 0.05,+ "range": {+ "step": {+ "signal": "y_step"+ }+ },+ "type": "band"+ }+ ],+ "signals": [+ {+ "init": "isFinite(containerSize()[0]) ? containerSize()[0] : 300",+ "name": "width",+ "on": [+ {+ "events": "window:resize",+ "update": "isFinite(containerSize()[0]) ? containerSize()[0] : 300"+ }+ ]+ },+ {+ "name": "y_step",+ "value": 20+ },+ {+ "name": "height",+ "update": "bandspace(domain('y').length, 0.1, 0.05) * y_step"+ }+ ],+ "style": "cell"+}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_date_chart_code.txt b/tests/_data/snapshots/column_preview_date_chart_code.txtindex 72e0a9eeaf..1aa5bcfb46 100644--- a/tests/_data/snapshots/column_preview_date_chart_code.txt+++ b/tests/_data/snapshots/column_preview_date_chart_code.txt@@ -1,8 +1,13 @@_chart = (alt.Chart(table)- .mark_line(point={"filled": False, "fill": "white"})+ .mark_bar().encode(- x=alt.X("date_col", type="temporal"),+ x=alt.X(+ "date_col",+ type="temporal",+ bin=alt.Bin(maxbins=20),+ axis=alt.Axis(format="%Y-%m-%d")+ ),y=alt.Y("count()", type="quantitative"),).properties(width="container")diff --git a/tests/_data/snapshots/column_preview_date_chart_spec.txt b/tests/_data/snapshots/column_preview_date_chart_spec.txtdeleted file mode 100644index cdd7d93989..0000000000--- a/tests/_data/snapshots/column_preview_date_chart_spec.txt+++ /dev/null@@ -1,43 +0,0 @@-{- "$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",- "config": {- "view": {- "continuousHeight": 300,- "continuousWidth": 300- }- },- "data": {- "name": "data-4a2dbd9282d213a7f98ae5fa5685735d"- },- "datasets": {- "data-4a2dbd9282d213a7f98ae5fa5685735d": [- {- "date_col": "2021-01-01T00:00:00"- },- {- "date_col": "2021-01-02T00:00:00"- },- {- "date_col": "2021-01-03T00:00:00"- }- ]- },- "encoding": {- "x": {- "field": "date_col",- "type": "temporal"- },- "y": {- "aggregate": "count",- "type": "quantitative"- }- },- "mark": {- "point": {- "fill": "white",- "filled": false- },- "type": "line"- },- "width": "container"-}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_float_chart_code.txt b/tests/_data/snapshots/column_preview_float_chart_code.txtnew file mode 100644index 0000000000..517879cdd8--- /dev/null+++ b/tests/_data/snapshots/column_preview_float_chart_code.txt@@ -0,0 +1,10 @@+_chart = (+ alt.Chart(table)+ .mark_bar()+ .encode(+ x=alt.X("float_col", type="quantitative", bin=True),+ y=alt.Y("count()", type="quantitative"),+ )+ .properties(width="container")+)+_chart\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_float_chart_spec.txt b/tests/_data/snapshots/column_preview_float_chart_spec.txtnew file mode 100644index 0000000000..04df1082e4--- /dev/null+++ b/tests/_data/snapshots/column_preview_float_chart_spec.txt@@ -0,0 +1,30 @@+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",+ "config": {+ "view": {+ "continuousHeight": 300,+ "continuousWidth": 300+ }+ },+ "data": {+ "format": {+ "type": "csv"+ },+ "url": "data:text/csv;base64,ZmxvYXRfY29sCjEuMQoyLjIKMy4zCg=="+ },+ "encoding": {+ "x": {+ "bin": true,+ "field": "float_col",+ "type": "quantitative"+ },+ "y": {+ "aggregate": "count",+ "type": "quantitative"+ }+ },+ "mark": {+ "type": "bar"+ },+ "width": "container"+}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_float_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_float_chart_spec_with_vegafusion.txtnew file mode 100644index 0000000000..6f0ef64826--- /dev/null+++ b/tests/_data/snapshots/column_preview_float_chart_spec_with_vegafusion.txt@@ -0,0 +1,187 @@+{+ "$schema": "https://vega.github.io/schema/vega/v5.json",+ "autosize": {+ "contains": "padding",+ "type": "fit-x"+ },+ "axes": [+ {+ "aria": false,+ "domain": false,+ "grid": true,+ "gridScale": "x",+ "labels": false,+ "maxExtent": 0,+ "minExtent": 0,+ "orient": "left",+ "scale": "y",+ "tickCount": {+ "signal": "ceil(height/40)"+ },+ "ticks": false,+ "zindex": 0+ },+ {+ "grid": false,+ "labelFlush": true,+ "labelOverlap": true,+ "orient": "bottom",+ "scale": "x",+ "tickCount": {+ "signal": "ceil(width/10)"+ },+ "title": "float_col (binned)",+ "zindex": 0+ },+ {+ "grid": false,+ "labelOverlap": true,+ "orient": "left",+ "scale": "y",+ "tickCount": {+ "signal": "ceil(height/40)"+ },+ "title": "Count of Records",+ "zindex": 0+ }+ ],+ "background": "white",+ "data": [+ {+ "name": "source_0",+ "values": [+ {+ "__count": 1,+ "bin_maxbins_10_float_col": 1.0,+ "bin_maxbins_10_float_col_end": 1.5+ },+ {+ "__count": 1,+ "bin_maxbins_10_float_col": 2.0,+ "bin_maxbins_10_float_col_end": 2.5+ },+ {+ "__count": 1,+ "bin_maxbins_10_float_col": 3.0,+ "bin_maxbins_10_float_col_end": 3.5+ }+ ]+ },+ {+ "name": "source_0_y_domain___count",+ "values": [+ {+ "max": 1,+ "min": 1+ }+ ]+ }+ ],+ "height": 300,+ "marks": [+ {+ "encode": {+ "update": {+ "fill": {+ "value": "#4c78a8"+ },+ "x": {+ "field": "bin_maxbins_10_float_col_end",+ "offset": {+ "signal": "0.5 + (abs(scale(\"x\", datum[\"bin_maxbins_10_float_col_end\"]) - scale(\"x\", datum[\"bin_maxbins_10_float_col\"])) < 0.25 ? 0.5 * (0.25 - (abs(scale(\"x\", datum[\"bin_maxbins_10_float_col_end\"]) - scale(\"x\", datum[\"bin_maxbins_10_float_col\"])))) : -0.5)"+ },+ "scale": "x"+ },+ "x2": {+ "field": "bin_maxbins_10_float_col",+ "offset": {+ "signal": "0.5 + (abs(scale(\"x\", datum[\"bin_maxbins_10_float_col_end\"]) - scale(\"x\", datum[\"bin_maxbins_10_float_col\"])) < 0.25 ? -0.5 * (0.25 - (abs(scale(\"x\", datum[\"bin_maxbins_10_float_col_end\"]) - scale(\"x\", datum[\"bin_maxbins_10_float_col\"])))) : 0.5)"+ },+ "scale": "x"+ },+ "y": {+ "field": "__count",+ "scale": "y"+ },+ "y2": {+ "scale": "y",+ "value": 0+ }+ }+ },+ "from": {+ "data": "source_0"+ },+ "name": "marks",+ "style": [+ "bar"+ ],+ "type": "rect"+ }+ ],+ "padding": 5,+ "scales": [+ {+ "bins": {+ "signal": "bin_maxbins_10_float_col_bins"+ },+ "domain": {+ "signal": "[bin_maxbins_10_float_col_bins.start, bin_maxbins_10_float_col_bins.stop]"+ },+ "name": "x",+ "range": [+ 0,+ {+ "signal": "width"+ }+ ],+ "type": "linear",+ "zero": false+ },+ {+ "domain": [+ {+ "signal": "(data(\"source_0_y_domain___count\")[0] || {}).min"+ },+ {+ "signal": "(data(\"source_0_y_domain___count\")[0] || {}).max"+ }+ ],+ "name": "y",+ "nice": true,+ "range": [+ {+ "signal": "height"+ },+ 0+ ],+ "type": "linear",+ "zero": true+ }+ ],+ "signals": [+ {+ "name": "bin_maxbins_10_float_col_bins",+ "value": {+ "fields": [+ "float_col"+ ],+ "fname": "bin_float_col",+ "start": 1.0,+ "step": 0.5,+ "stop": 3.5+ }+ },+ {+ "init": "isFinite(containerSize()[0]) ? containerSize()[0] : 300",+ "name": "width",+ "on": [+ {+ "events": "window:resize",+ "update": "isFinite(containerSize()[0]) ? containerSize()[0] : 300"+ }+ ]+ }+ ],+ "style": "cell"+}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_chart_code.txt b/tests/_data/snapshots/column_preview_int_chart_code.txtsimilarity index 100%rename from tests/_data/snapshots/column_preview_chart_code.txtrename to tests/_data/snapshots/column_preview_int_chart_code.txtdiff --git a/tests/_data/snapshots/column_preview_chart_spec.txt b/tests/_data/snapshots/column_preview_int_chart_spec.txtsimilarity index 100%rename from tests/_data/snapshots/column_preview_chart_spec.txtrename to tests/_data/snapshots/column_preview_int_chart_spec.txtdiff --git a/tests/_data/snapshots/column_preview_int_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_int_chart_spec_with_vegafusion.txtnew file mode 100644index 0000000000..a922e5e655--- /dev/null+++ b/tests/_data/snapshots/column_preview_int_chart_spec_with_vegafusion.txt@@ -0,0 +1,187 @@+{+ "$schema": "https://vega.github.io/schema/vega/v5.json",+ "autosize": {+ "contains": "padding",+ "type": "fit-x"+ },+ "axes": [+ {+ "aria": false,+ "domain": false,+ "grid": true,+ "gridScale": "x",+ "labels": false,+ "maxExtent": 0,+ "minExtent": 0,+ "orient": "left",+ "scale": "y",+ "tickCount": {+ "signal": "ceil(height/40)"+ },+ "ticks": false,+ "zindex": 0+ },+ {+ "grid": false,+ "labelFlush": true,+ "labelOverlap": true,+ "orient": "bottom",+ "scale": "x",+ "tickCount": {+ "signal": "ceil(width/10)"+ },+ "title": "A (binned)",+ "zindex": 0+ },+ {+ "grid": false,+ "labelOverlap": true,+ "orient": "left",+ "scale": "y",+ "tickCount": {+ "signal": "ceil(height/40)"+ },+ "title": "Count of Records",+ "zindex": 0+ }+ ],+ "background": "white",+ "data": [+ {+ "name": "source_0",+ "values": [+ {+ "__count": 1,+ "bin_maxbins_10_A": 1.0,+ "bin_maxbins_10_A_end": 1.2+ },+ {+ "__count": 1,+ "bin_maxbins_10_A": 2.0,+ "bin_maxbins_10_A_end": 2.2+ },+ {+ "__count": 1,+ "bin_maxbins_10_A": 2.8,+ "bin_maxbins_10_A_end": 3.0+ }+ ]+ },+ {+ "name": "source_0_y_domain___count",+ "values": [+ {+ "max": 1,+ "min": 1+ }+ ]+ }+ ],+ "height": 300,+ "marks": [+ {+ "encode": {+ "update": {+ "fill": {+ "value": "#4c78a8"+ },+ "x": {+ "field": "bin_maxbins_10_A_end",+ "offset": {+ "signal": "0.5 + (abs(scale(\"x\", datum[\"bin_maxbins_10_A_end\"]) - scale(\"x\", datum[\"bin_maxbins_10_A\"])) < 0.25 ? 0.5 * (0.25 - (abs(scale(\"x\", datum[\"bin_maxbins_10_A_end\"]) - scale(\"x\", datum[\"bin_maxbins_10_A\"])))) : -0.5)"+ },+ "scale": "x"+ },+ "x2": {+ "field": "bin_maxbins_10_A",+ "offset": {+ "signal": "0.5 + (abs(scale(\"x\", datum[\"bin_maxbins_10_A_end\"]) - scale(\"x\", datum[\"bin_maxbins_10_A\"])) < 0.25 ? -0.5 * (0.25 - (abs(scale(\"x\", datum[\"bin_maxbins_10_A_end\"]) - scale(\"x\", datum[\"bin_maxbins_10_A\"])))) : 0.5)"+ },+ "scale": "x"+ },+ "y": {+ "field": "__count",+ "scale": "y"+ },+ "y2": {+ "scale": "y",+ "value": 0+ }+ }+ },+ "from": {+ "data": "source_0"+ },+ "name": "marks",+ "style": [+ "bar"+ ],+ "type": "rect"+ }+ ],+ "padding": 5,+ "scales": [+ {+ "bins": {+ "signal": "bin_maxbins_10_A_bins"+ },+ "domain": {+ "signal": "[bin_maxbins_10_A_bins.start, bin_maxbins_10_A_bins.stop]"+ },+ "name": "x",+ "range": [+ 0,+ {+ "signal": "width"+ }+ ],+ "type": "linear",+ "zero": false+ },+ {+ "domain": [+ {+ "signal": "(data(\"source_0_y_domain___count\")[0] || {}).min"+ },+ {+ "signal": "(data(\"source_0_y_domain___count\")[0] || {}).max"+ }+ ],+ "name": "y",+ "nice": true,+ "range": [+ {+ "signal": "height"+ },+ 0+ ],+ "type": "linear",+ "zero": true+ }+ ],+ "signals": [+ {+ "name": "bin_maxbins_10_A_bins",+ "value": {+ "fields": [+ "A"+ ],+ "fname": "bin_A",+ "start": 1.0,+ "step": 0.2,+ "stop": 3.0+ }+ },+ {+ "init": "isFinite(containerSize()[0]) ? containerSize()[0] : 300",+ "name": "width",+ "on": [+ {+ "events": "window:resize",+ "update": "isFinite(containerSize()[0]) ? containerSize()[0] : 300"+ }+ ]+ }+ ],+ "style": "cell"+}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_str_chart_code.txt b/tests/_data/snapshots/column_preview_str_chart_code.txtnew file mode 100644index 0000000000..6a74b3c662--- /dev/null+++ b/tests/_data/snapshots/column_preview_str_chart_code.txt@@ -0,0 +1,10 @@+_chart = (+ alt.Chart(table)+ .mark_bar()+ .encode(+ y=alt.Y("B", type="nominal"),+ x=alt.X("count()", type="quantitative"),+ )+ .properties(width="container")+)+_chart\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_str_chart_spec.txt b/tests/_data/snapshots/column_preview_str_chart_spec.txtnew file mode 100644index 0000000000..89e5ab3052--- /dev/null+++ b/tests/_data/snapshots/column_preview_str_chart_spec.txt@@ -0,0 +1,29 @@+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json",+ "config": {+ "view": {+ "continuousHeight": 300,+ "continuousWidth": 300+ }+ },+ "data": {+ "format": {+ "type": "csv"+ },+ "url": "data:text/csv;base64,QgphCmEKYQo="+ },+ "encoding": {+ "x": {+ "aggregate": "count",+ "type": "quantitative"+ },+ "y": {+ "field": "B",+ "type": "nominal"+ }+ },+ "mark": {+ "type": "bar"+ },+ "width": "container"+}\ No newline at end of filediff --git a/tests/_data/snapshots/column_preview_str_chart_spec_with_vegafusion.txt b/tests/_data/snapshots/column_preview_str_chart_spec_with_vegafusion.txtnew file mode 100644index 0000000000..6913d463c5--- /dev/null+++ b/tests/_data/snapshots/column_preview_str_chart_spec_with_vegafusion.txt@@ -0,0 +1,167 @@+{+ "$schema": "https://vega.github.io/schema/vega/v5.json",+ "autosize": {+ "contains": "padding",+ "type": "fit-x"+ },+ "axes": [+ {+ "aria": false,+ "domain": false,+ "grid": true,+ "gridScale": "y",+ "labels": false,+ "maxExtent": 0,+ "minExtent": 0,+ "orient": "bottom",+ "scale": "x",+ "tickCount": {+ "signal": "ceil(width/40)"+ },+ "ticks": false,+ "zindex": 0+ },+ {+ "grid": false,+ "labelFlush": true,+ "labelOverlap": true,+ "orient": "bottom",+ "scale": "x",+ "tickCount": {+ "signal": "ceil(width/40)"+ },+ "title": "Count of Records",+ "zindex": 0+ },+ {+ "grid": false,+ "orient": "left",+ "scale": "y",+ "title": "B",+ "zindex": 0+ }+ ],+ "background": "white",+ "data": [+ {+ "name": "source_0",+ "values": [+ {+ "B": "a",+ "__count": 3+ }+ ]+ },+ {+ "name": "source_0_x_domain___count",+ "values": [+ {+ "max": 3,+ "min": 3+ }+ ]+ },+ {+ "name": "source_0_y_domain_B",+ "values": [+ {+ "B": "a"+ }+ ]+ }+ ],+ "marks": [+ {+ "encode": {+ "update": {+ "fill": {+ "value": "#4c78a8"+ },+ "height": {+ "signal": "max(0.25, bandwidth('y'))"+ },+ "x": {+ "field": "__count",+ "scale": "x"+ },+ "x2": {+ "scale": "x",+ "value": 0+ },+ "y": {+ "field": "B",+ "scale": "y"+ }+ }+ },+ "from": {+ "data": "source_0"+ },+ "name": "marks",+ "style": [+ "bar"+ ],+ "type": "rect"+ }+ ],+ "padding": 5,+ "scales": [+ {+ "domain": [+ {+ "signal": "(data(\"source_0_x_domain___count\")[0] || {}).min"+ },+ {+ "signal": "(data(\"source_0_x_domain___count\")[0] || {}).max"+ }+ ],+ "name": "x",+ "nice": true,+ "range": [+ 0,+ {+ "signal": "width"+ }+ ],+ "type": "linear",+ "zero": true+ },+ {+ "domain": {+ "data": "source_0_y_domain_B",+ "field": "B",+ "sort": true+ },+ "name": "y",+ "paddingInner": 0.1,+ "paddingOuter": 0.05,+ "range": {+ "step": {+ "signal": "y_step"+ }+ },+ "type": "band"+ }+ ],+ "signals": [+ {+ "init": "isFinite(containerSize()[0]) ? containerSize()[0] : 300",+ "name": "width",+ "on": [+ {+ "events": "window:resize",+ "update": "isFinite(containerSize()[0]) ? containerSize()[0] : 300"+ }+ ]+ },+ {+ "name": "y_step",+ "value": 20+ },+ {+ "name": "height",+ "update": "bandspace(domain('y').length, 0.1, 0.05) * y_step"+ }+ ],+ "style": "cell"+}\ No newline at end of filediff --git a/tests/_data/test_charts.py b/tests/_data/test_charts.pyindex a3ff29e2af..8bd3943d3e 100644--- a/tests/_data/test_charts.py+++ b/tests/_data/test_charts.py@@ -1,12 +1,19 @@from __future__ import annotationsimport ast+from datetime import datetime+from typing import Anyimport pytest-from marimo._data.charts import ChartBuilder, get_chart_builder+from marimo._data.charts import (+ ChartBuilder,+ DateChartBuilder,+ get_chart_builder,+)from marimo._data.models import DataTypefrom marimo._dependencies.dependencies import DependencyManager+from tests._data.mocks import DFType, create_dataframesfrom tests.mocks import snapshotterTYPES: list[tuple[DataType, bool]] = [@@ -100,3 +107,84 @@ def test_charts_altair_json_bad_data():# Validate it is valid JSONalt.Chart.from_json(code)snapshot("charts_json_bad_data.txt", code)++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ ("data", "expected_format"),+ [+ # More than 10 years+ (+ ({"dates": [datetime(2000, 1, 1), datetime(2020, 1, 1)]}),+ "%Y",+ ),+ # More than a year+ (+ ({"dates": [datetime(2020, 1, 1), datetime(2021, 6, 1)]}),+ "%Y-%m",+ ),+ # More than a month+ (+ ({"dates": [datetime(2020, 1, 1), datetime(2020, 2, 15)]}),+ "%Y-%m-%d",+ ),+ # More than a day+ (+ (+ {+ "dates": [+ datetime(2020, 1, 1, 0, 0),+ datetime(2020, 1, 2, 12, 0),+ ]+ }+ ),+ "%Y-%m-%d %H:%M",+ ),+ # Less than a day+ (+ (+ {+ "dates": [+ datetime(2020, 1, 1, 0, 0, 0),+ datetime(2020, 1, 1, 12, 30, 45),+ ]+ }+ ),+ "%Y-%m-%d %H:%M",+ ),+ ],+)+def test_date_chart_builder_guess_date_format_with_dataframes(+ data: dict[str, list[Any]], expected_format: str+):+ NON_EAGER_LIBS: list[DFType] = ["ibis", "duckdb"]++ eager_dfs = create_dataframes(data, exclude=NON_EAGER_LIBS)+ assert len(eager_dfs) > 0++ builder = DateChartBuilder()+ for df in eager_dfs:+ assert builder._guess_date_format(df, "dates") == expected_format, (+ f"Expected {expected_format} for {type(df)}"+ )++ non_eager_dfs = create_dataframes(data, include=NON_EAGER_LIBS)+ for df in non_eager_dfs:+ assert (+ builder._guess_date_format(df, "dates")+ == DateChartBuilder.DEFAULT_DATE_FORMAT+ ), f"Expected {DateChartBuilder.DEFAULT_DATE_FORMAT} for {type(df)}"++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_date_chart_builder_guess_date_format_with_non_narwhalifiable_data():+ builder = DateChartBuilder()++ # Test with non-narwhalifiable data+ class NonNarwhalifiableData:+ pass++ assert (+ builder._guess_date_format(NonNarwhalifiableData(), "dates")+ == "%Y-%m-%d"+ )diff --git a/tests/_data/test_preview_column.py b/tests/_data/test_preview_column.pyindex 68a859c471..42ab4bcf0a 100644--- a/tests/_data/test_preview_column.py+++ b/tests/_data/test_preview_column.py@@ -1,7 +1,7 @@from __future__ import annotations-import sysfrom typing import TYPE_CHECKING+from unittest.mock import patchimport pytest@@ -14,6 +14,7 @@ from marimo._plugins.ui._impl.charts.altair_transformer import (register_transformers,)from marimo._runtime.requests import PreviewDatasetColumnRequest+from marimo._utils.platform import is_windowsfrom tests.mocks import snapshotterif TYPE_CHECKING:@@ -43,11 +44,21 @@ def cleanup() -> Generator[None, None, None]:@pytest.mark.skipif(not HAS_DF_DEPS, reason="optional dependencies not installed")- sys.platform == "win32",- reason="Windows encodes base64 differently",[email protected](is_windows(), reason="Windows encodes base64 differently")+ ("column_name", "snapshot_prefix"),+ [+ ("A", "column_preview_int"),+ ("B", "column_preview_str"),+ ("date_col", "column_preview_date"),+ ("float_col", "column_preview_float"),+ ("bool_col", "column_preview_bool"),+ ("category_col", "column_preview_categorical"),+ ],)-def test_get_column_preview_dataframe() -> None:+def test_get_column_preview_dataframe(+ column_name: str, snapshot_prefix: str+) -> None:import pandas as pdregister_transformers()@@ -61,54 +72,72 @@ def test_get_column_preview_dataframe() -> None:pd.Timestamp("2021-01-02"),pd.Timestamp("2021-01-03"),],+ "float_col": [1.1, 2.2, 3.3],+ "bool_col": [True, False, True],+ "category_col": pd.Categorical(["cat1", "cat2", "cat1"]),})- result = get_column_preview_dataframe(- df,- request=PreviewDatasetColumnRequest(- source="source",- table_name="table",- column_name="A",- source_type="local",- ),- )- assert result is not None- assert result.chart_code is not None- assert result.chart_spec is not None- assert result.summary is not None- assert result.error is None-- snapshot("column_preview_chart_code.txt", result.chart_code)- snapshot("column_preview_chart_spec.txt", result.chart_spec)-- result = get_column_preview_dataframe(+ # Patch DependencyManager to simulate vegafusion not being available+ with patch("marimo._data.preview_column.DependencyManager") as mock_dm:+ # Keep altair available but make vegafusion unavailable+ mock_dm.altair.has.return_value = True+ mock_dm.vegafusion.has.return_value = False+ mock_dm.vl_convert_python.has.return_value = True++ result = get_column_preview_dataframe(+ df,+ request=PreviewDatasetColumnRequest(+ source="source",+ table_name="table",+ column_name=column_name,+ source_type="local",+ ),+ )+ assert result is not None+ assert result.chart_code is not None+ assert result.chart_spec is not None+ assert result.summary is not None+ assert result.error is None++ snapshot(f"{snapshot_prefix}_chart_code.txt", result.chart_code)+ # Skip date_col because of timezone+ if column_name != "date_col":+ snapshot(f"{snapshot_prefix}_chart_spec.txt", result.chart_spec)++ # Verify vegafusion was checked+ mock_dm.vegafusion.has.assert_called_once()++ result_with_vegafusion = get_column_preview_dataframe(df,request=PreviewDatasetColumnRequest(source="source",table_name="table",- column_name="date_col",+ column_name=column_name,source_type="local",),)- assert result is not None- assert result.chart_code is not None- assert result.chart_spec is not None- assert result.summary is not None- assert result.error is None+ assert result_with_vegafusion is not None+ assert result_with_vegafusion.chart_code is not None+ assert result_with_vegafusion.chart_spec is not None+ assert result_with_vegafusion.summary is not None+ assert result_with_vegafusion.error is None- snapshot("column_preview_date_chart_code.txt", result.chart_code)- snapshot("column_preview_date_chart_spec.txt", result.chart_spec)+ # Skip date_col because of timezone+ if column_name != "date_col":+ snapshot(+ f"{snapshot_prefix}_chart_spec_with_vegafusion.txt",+ result_with_vegafusion.chart_spec,+ )+ assert result_with_vegafusion.chart_code == result.chart_code+ assert result_with_vegafusion.chart_spec != result.chart_spec@pytest.mark.skipif(not HAS_SQL_DEPS, reason="optional dependencies not installed")- sys.platform == "win32",- reason="Windows encodes base64 differently",-)[email protected](is_windows(), reason="Windows encodes base64 differently")def test_get_column_preview_for_duckdb() -> None:import duckdb@@ -152,10 +181,7 @@ def test_get_column_preview_for_duckdb() -> None:@pytest.mark.skipif(not HAS_SQL_DEPS, reason="optional dependencies not installed")- sys.platform == "win32",- reason="Windows encodes base64 differently",-)[email protected](is_windows(), reason="Windows encodes base64 differently")def test_get_column_preview_for_duckdb_categorical() -> None:import duckdb@@ -193,10 +219,7 @@ def test_get_column_preview_for_duckdb_categorical() -> None:@pytest.mark.skipif(not HAS_SQL_DEPS, reason="optional dependencies not installed")- sys.platform == "win32",- reason="Windows encodes base64 differently",-)[email protected](is_windows(), reason="Windows encodes base64 differently")def test_get_column_preview_for_duckdb_date() -> None:import datetime@@ -232,10 +255,7 @@ def test_get_column_preview_for_duckdb_date() -> None:@pytest.mark.skipif(not HAS_SQL_DEPS, reason="optional dependencies not installed")- sys.platform == "win32",- reason="Windows encodes base64 differently",-)[email protected](is_windows(), reason="Windows encodes base64 differently")def test_get_column_preview_for_duckdb_datetime() -> None:import datetime@@ -274,10 +294,7 @@ def test_get_column_preview_for_duckdb_datetime() -> None:@pytest.mark.skipif(not HAS_SQL_DEPS, reason="optional dependencies not installed")- sys.platform == "win32",- reason="Windows encodes base64 differently",-)[email protected](is_windows(), reason="Windows encodes base64 differently")def test_get_column_preview_for_duckdb_time() -> None:import datetime@@ -315,10 +332,7 @@ def test_get_column_preview_for_duckdb_time() -> None:@pytest.mark.skipif(not HAS_SQL_DEPS, reason="optional dependencies not installed")- sys.platform == "win32",- reason="Windows encodes base64 differently",-)[email protected](is_windows(), reason="Windows encodes base64 differently")def test_get_column_preview_for_duckdb_bool() -> None:import duckdb