diff --git a/doc/whats-new.rst b/doc/whats-new.rst index a1d52b28ed5..1583564522e 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -105,6 +105,8 @@ Bug fixes - Fix bug in time parsing failing to fall back to cftime. This was causing time variables with a time unit of `'msecs'` to fail to parse. (:pull:`3998`) By `Ryan May `_. +- Fix html repr in untrusted notebooks: fallback to plain text repr. (:pull:`4053`) + By `Benoit Bovy `_. Documentation ~~~~~~~~~~~~~ diff --git a/xarray/core/formatting_html.py b/xarray/core/formatting_html.py index 6e345582ed0..69832d6ca3d 100644 --- a/xarray/core/formatting_html.py +++ b/xarray/core/formatting_html.py @@ -222,14 +222,20 @@ def array_section(obj): ) -def _obj_repr(header_components, sections): +def _obj_repr(obj, header_components, sections): + """Return HTML repr of an xarray object. + + If CSS is not injected (untrusted notebook), fallback to the plain text repr. + + """ header = f"
{''.join(h for h in header_components)}
" sections = "".join(f"
  • {s}
  • " for s in sections) return ( "
    " f"{ICONS_SVG}" - "
    " + f"
    {escape(repr(obj))}
    " + "" @@ -257,7 +263,7 @@ def array_repr(arr): sections.append(attr_section(arr.attrs)) - return _obj_repr(header_components, sections) + return _obj_repr(arr, header_components, sections) def dataset_repr(ds): @@ -272,4 +278,4 @@ def dataset_repr(ds): attr_section(ds.attrs), ] - return _obj_repr(header_components, sections) + return _obj_repr(ds, header_components, sections) diff --git a/xarray/static/css/style.css b/xarray/static/css/style.css index acfe85d5ac7..39cd6d6755f 100644 --- a/xarray/static/css/style.css +++ b/xarray/static/css/style.css @@ -26,10 +26,16 @@ body.vscode-dark { } .xr-wrap { + display: block; min-width: 300px; max-width: 700px; } +.xr-text-repr-fallback { + /* fallback to plain text repr when CSS is not injected (untrusted notebook) */ + display: none; +} + .xr-header { padding-top: 6px; padding-bottom: 6px; diff --git a/xarray/static/html/icons-svg-inline.html b/xarray/static/html/icons-svg-inline.html index c44f89c4304..b0e837a26cd 100644 --- a/xarray/static/html/icons-svg-inline.html +++ b/xarray/static/html/icons-svg-inline.html @@ -1,13 +1,11 @@ -Show/Hide data repr -Show/Hide attributes diff --git a/xarray/tests/test_formatting_html.py b/xarray/tests/test_formatting_html.py index 94653016416..90e74f1f78f 100644 --- a/xarray/tests/test_formatting_html.py +++ b/xarray/tests/test_formatting_html.py @@ -139,6 +139,13 @@ def test_repr_of_dataset(dataset): assert "<IA>" in formatted +def test_repr_text_fallback(dataset): + formatted = fh.dataset_repr(dataset) + + # Just test that the "pre" block used for fallback to plain text is present. + assert "
    " in formatted
    +
    +
     def test_variable_repr_html():
         v = xr.Variable(["time", "x"], [[1, 2, 3], [4, 5, 6]], {"foo": "bar"})
         assert hasattr(v, "_repr_html_")