Skip to content

Load plotly.js from plotly.py #2610

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
All notable changes to `dash` will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/).

## [UNRELEASED]
## Changed

- [#2610](https://github.com/plotly/dash/pull/2610) Load plotly.js bundle/version from plotly.py

## [2.12.1] - 2023-08-16

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import json
import os as _os
import sys as _sys

import dash as _dash

from ._imports_ import * # noqa: F401, F403, E402
Expand Down Expand Up @@ -121,33 +122,6 @@
"namespace": "dash",
"dynamic": True,
},
{
"relative_package_path": "dcc/plotly.min.js",
"external_url": (
"https://unpkg.com/dash-core-components@{}"
"/dash_core_components/plotly.min.js"
).format(__version__),
"namespace": "dash",
"async": "eager",
},
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also delete the following two entries, async-plotlyjs.js and its .map? And I guess we can remove the prebuild:js command in dcc's package.json that creates the plotly.min.js file referenced here, right?

{
"relative_package_path": "dcc/async-plotlyjs.js",
"external_url": (
"https://unpkg.com/dash-core-components@{}"
"/dash_core_components/async-plotlyjs.js"
).format(__version__),
"namespace": "dash",
"async": "lazy",
},
{
"relative_package_path": "dcc/async-plotlyjs.js.map",
"external_url": (
"https://unpkg.com/dash-core-components@{}"
"/dash_core_components/async-plotlyjs.js.map"
).format(__version__),
"namespace": "dash",
"dynamic": True,
},
]
)

Expand Down
11 changes: 0 additions & 11 deletions components/dash-core-components/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions components/dash-core-components/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"test": "run-s -c lint test:intg test:pyimport",
"test:intg": "pytest --nopercyfinalize --headless tests/integration ",
"test:pyimport": "python -m unittest tests/test_dash_import.py",
"prebuild:js": "cp node_modules/plotly.js-dist-min/plotly.min.js dash_core_components_base/plotly.min.js",
"build:js": "webpack --mode production",
"build:backends": "dash-generate-components ./src/components dash_core_components -p package-info.json && cp dash_core_components_base/** dash_core_components/ && dash-generate-components ./src/components dash_core_components -p package-info.json -k RangeSlider,Slider,Dropdown,RadioItems,Checklist,DatePickerSingle,DatePickerRange,Input,Link --r-prefix 'dcc' --r-suggests 'dash,dashHtmlComponents,jsonlite,plotly' --jl-prefix 'dcc' && black dash_core_components",
"build": "run-s prepublishOnly build:js build:backends",
Expand All @@ -49,7 +48,6 @@
"mathjax": "^3.2.2",
"moment": "^2.29.4",
"node-polyfill-webpack-plugin": "^2.0.1",
"plotly.js-dist-min": "2.25.2",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call!

"prop-types": "^15.8.1",
"ramda": "^0.29.0",
"rc-slider": "^9.7.5",
Expand Down
29 changes: 24 additions & 5 deletions components/dash-core-components/src/utils/LazyLoader/plotly.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
export default () => Promise.resolve(window.Plotly ||
import(/* webpackChunkName: "plotlyjs" */ 'plotly.js-dist-min').then(({ default: Plotly }) => {
window.Plotly = Plotly;
return Plotly;
}));
export default () => {
return Promise.resolve(window.Plotly || new Promise((resolve, reject) => {
/* eslint-disable prefer-const */
let timeoutId;

const element = document.createElement('script');
element.src = window._dashPlotlyJSURL;
element.async = true;
element.onload = () => {
clearTimeout(timeoutId);
resolve();
};
element.onerror = (error) => {
clearTimeout(timeoutId);
reject(error);
};

timeoutId = setTimeout(() => {
element.src = '';
reject(new Error(`plotly.js did not load after 30 seconds`));
}, 3 * 10 * 1000);

document.querySelector('body').appendChild(element);
}));
}
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ def show_relayout_data(data):

dash_dcc.start_server(app)

time.sleep(1)

# use this opportunity to test restyleData, since there are multiple
# traces on this graph
legendToggle = dash_dcc.find_element(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ def update_tooltip_content(hoverData):
assert 175 < coords[0] < 185, "x0 is about 200 minus half a marker size"
assert 175 < coords[1] < 185, "y0 is about 200 minus half a marker size"

elem = dash_dcc.find_element("#graph .nsewdrag")

ActionChains(dash_dcc.driver).move_to_element_with_offset(
elem, 5, elem.size["height"] - 5
).perform()
Expand Down
8 changes: 8 additions & 0 deletions dash/dash-renderer/src/APIController.react.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ const UnconnectedContainer = props => {
}
});

useEffect(() => {
if (config.serve_locally) {
window._dashPlotlyJSURL = `${config.requests_pathname_prefix}_dash-component-suites/plotly/package_data/plotly.min.js`;
} else {
window._dashPlotlyJSURL = config.plotlyjs_url;
}
}, []);

let content;
if (
layoutRequest.status &&
Expand Down
2 changes: 2 additions & 0 deletions dash/dash-renderer/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ type Config = {
'Content-Type': string;
};
};
serve_locally?: boolean;
plotlyjs_url?: string;
};

export default function getConfigFromDOM(): Config {
Expand Down
26 changes: 26 additions & 0 deletions dash/dash.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,8 @@ class Dash:
if not added previously.
"""

_plotlyjs_url: str

def __init__( # pylint: disable=too-many-statements
self,
name=None,
Expand Down Expand Up @@ -588,6 +590,8 @@ def _handle_error(_):
_get_app.APP = self
self.enable_pages()

self._setup_plotlyjs()

def _add_url(self, name, view_func, methods=("GET",)):
full_name = self.config.routes_pathname_prefix + name

Expand Down Expand Up @@ -619,6 +623,25 @@ def _setup_routes(self):
# catch-all for front-end routes, used by dcc.Location
self._add_url("<path:path>", self.index)

def _setup_plotlyjs(self):
# pylint: disable=import-outside-toplevel
from plotly.offline import get_plotlyjs_version

url = f"https://cdn.plot.ly/plotly-{get_plotlyjs_version()}.min.js"

# pylint: disable=protected-access
dcc._js_dist.extend(
[
{
"relative_package_path": "package_data/plotly.min.js",
"external_url": url,
"namespace": "plotly",
"async": "eager",
}
]
)
self._plotlyjs_url = url

@property
def layout(self):
return self._layout
Expand Down Expand Up @@ -702,7 +725,10 @@ def _config(self):
"suppress_callback_exceptions": self.config.suppress_callback_exceptions,
"update_title": self.config.update_title,
"children_props": ComponentRegistry.children_props,
"serve_locally": self.config.serve_locally,
}
if not self.config.serve_locally:
config["plotlyjs_url"] = self._plotlyjs_url
if self._dev_tools.hot_reload:
config["hot_reload"] = {
# convert from seconds to msec as used by js `setInterval`
Expand Down
20 changes: 2 additions & 18 deletions tests/integration/test_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,6 @@ def get_script_sources(dash_duo):
return [s.get_attribute("src") for s in dash_duo.find_elements("script")]


def hasSyncPlotlyJs(dash_duo):
return any("dash/dcc/plotly" in s for s in get_script_sources(dash_duo))


def hasAsyncPlotlyJs(dash_duo):
return any("dash/dcc/async-plotlyjs" in s for s in get_script_sources(dash_duo))


def hasWindowPlotly(dash_duo):
return dash_duo.driver.execute_script("return !!window.Plotly")

Expand All @@ -34,14 +26,11 @@ def test_scri001_scripts(dash_duo, is_eager):
dev_tools_hot_reload=False,
)

assert hasWindowPlotly(dash_duo) is is_eager

# Wait for the graph to appear
dash_duo.find_element(".js-plotly-plot")

assert hasSyncPlotlyJs(dash_duo) is is_eager

# Webpack 5 deletes the script tag immediately after evaluating it
# https://github.com/plotly/dash/pull/1685#issuecomment-877199466
assert hasAsyncPlotlyJs(dash_duo) is False
assert hasWindowPlotly(dash_duo) is True


Expand All @@ -67,16 +56,11 @@ def load_chart(n_clicks):
# Give time for the async dependency to be requested (if any)
time.sleep(2)

assert hasSyncPlotlyJs(dash_duo) is False
assert hasAsyncPlotlyJs(dash_duo) is False
assert hasWindowPlotly(dash_duo) is False

dash_duo.find_element("#btn").click()

# Wait for the graph to appear
dash_duo.find_element(".js-plotly-plot")

assert hasSyncPlotlyJs(dash_duo) is False
# Again, webpack 5 deletes the script tag immediately after evaluating it
assert hasAsyncPlotlyJs(dash_duo) is False
assert hasWindowPlotly(dash_duo) is True
1 change: 1 addition & 0 deletions tests/unit/test_old_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ def filter_dir(package):
"package_name",
"f",
"express",
"get_plotlyjs_version",
]
return sorted(
[
Expand Down