Skip to content

make standalone plots work in offline (non-cdn) or online mode #243

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 1 commit into from
Nov 8, 2024
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
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.10.0] - 2024-10-29
## [0.10.1] - 2024-11-x
### Added
- [[#243](https://github.com/plotly/plotly.rs/pull/243)] Made `plotly_embed_js` embed all JS scripts when enabled.
Renamed `use_cdn_plotly` to `use_cdn_js`.
- [[#239](https://github.com/plotly/plotly.rs/pull/239)] Add Categorical Axis Ordering and Axis Category Array.

### Fixed
- [[#242](https://github.com/plotly/plotly.rs/issues/242)] Disable request for tex-svg.js file
- [[#237](https://github.com/plotly/plotly.rs/issues/237)] Add Categorical Axis ordering.

## [0.10.0] - 2024-09-16
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Add this to your `Cargo.toml`:
plotly = "0.10.0"
```

## Exporting an Interactive Plot
## Exporting a single Interactive Plot

Any figure can be saved as an HTML file using the `Plot.write_html()` method. These HTML files can be opened in any web browser to access the fully interactive figure.

Expand All @@ -78,12 +78,12 @@ plot.add_trace(trace);
plot.write_html("out.html");
```

By default, the Plotly JavaScript library will be included via CDN, which results in a smaller filesize, but slightly slower first load as the JavaScript library has to be downloaded first. To instead embed the JavaScript library (several megabytes in size) directly into the HTML file, the library must be compiled with the feature flag `plotly_embed_js`. Once enabled, by default the JavaScript library is directly embedded in the generated HTML file. It is still possible to use the CDN version, by using the `use_cdn_plotly` method.
By default, the Plotly JavaScript library and some [MathJax](https://docs.mathjax.org/en/latest/web/components/index.html) components will always be included via CDN, which results in smaller file-size, but slightly slower first load as the JavaScript libraries have to be downloaded first. Alternatively, to embed the JavaScript libraries (several megabytes in size) directly into the HTML file, `plotly-rs` must be compiled with the feature flag `plotly_embed_js`. With this feature flag the Plotly and MathJax JavaScript libraries are directly embedded in the generated HTML file. It is still possible to use the CDN version, by using the `use_cdn_js` method.

```rust
// <-- Create a `Plot` -->

plot.use_cdn_plotly();
plot.use_cdn_js();
plot.write_html("out.html");
```

Expand Down Expand Up @@ -207,7 +207,7 @@ By default, the CDN version of `plotly.js` is used in the library and in the gen

However, there are two downsides of using this feature flag, one is that the resulting html will be much larger, as a copy of the `plotly.min.js` library is embedded in each HTML file. The second, more relevant, is that a copy of the `plotly.min.js` library needs to be compiled in the `plotly-rs` library itself which increases the size by approx `3.5 Mb`.

When the feature is enabled, users can still opt in for the CDN version by using the method `use_cdn_plotly`.
When the feature is enabled, users can still opt in for the CDN version by using the method `use_cdn_js`.

Note that when using `Plot::to_inline_html()`, it is assumed that the `plotly.js` library is already in scope within the HTML file, so enabling this feature flag will have no effect.

Expand Down
1 change: 1 addition & 0 deletions plotly/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ exclude = ["target/*"]
kaleido = ["plotly_kaleido"]
plotly_ndarray = ["ndarray"]
plotly_image = ["image"]
# Embed JavaScript into library and templates for offline use
plotly_embed_js = []
wasm = ["getrandom", "js-sys", "wasm-bindgen", "wasm-bindgen-futures"]
with-axum = ["rinja/with-axum", "rinja_axum"]
Expand Down
61 changes: 42 additions & 19 deletions plotly/src/plot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::{Configuration, Layout};
#[template(path = "plot.html", escape = "none")]
struct PlotTemplate<'a> {
plot: &'a Plot,
plotly_js_source: String,
js_scripts: String,
}

#[derive(Template)]
Expand All @@ -24,7 +24,7 @@ struct PlotTemplate<'a> {
struct StaticPlotTemplate<'a> {
plot: &'a Plot,
format: ImageFormat,
plotly_js_source: String,
js_scripts: String,
width: usize,
height: usize,
}
Expand Down Expand Up @@ -182,26 +182,27 @@ pub struct Plot {
#[serde(rename = "config")]
configuration: Configuration,
#[serde(skip)]
plotly_js_source: String,
js_scripts: String,
}

impl Plot {
/// Create a new `Plot`.
pub fn new() -> Plot {
Plot {
traces: Traces::new(),
plotly_js_source: Self::plotly_js_source(),
js_scripts: Self::js_scripts(),
..Default::default()
}
}

/// Switch to CDN `plotly.js` in the generated HTML instead of the default
/// local `plotly.js` version. Method is only available when the feature
/// Switch to CDN for `plotly.js` and `MathJax` components in the standalone
/// HTML plots rather than using the default local copies of the
/// Javascript libraries. Method is only available when the feature
/// `plotly_embed_js` is enabled since without this feature the default
/// version used is always the CDN version.
/// versions used are always the CDN versions.
#[cfg(feature = "plotly_embed_js")]
pub fn use_cdn_plotly(&mut self) {
self.plotly_js_source = Self::cdn_plotly_js();
pub fn use_cdn_js(&mut self) {
self.js_scripts = Self::online_cdn_js();
}

/// Add a `Trace` to the `Plot`.
Expand Down Expand Up @@ -419,7 +420,7 @@ impl Plot {
fn render(&self) -> String {
let tmpl = PlotTemplate {
plot: self,
plotly_js_source: self.plotly_js_source.clone(),
js_scripts: self.js_scripts.clone(),
};
tmpl.render().unwrap()
}
Expand All @@ -429,7 +430,7 @@ impl Plot {
let tmpl = StaticPlotTemplate {
plot: self,
format,
plotly_js_source: self.plotly_js_source.clone(),
js_scripts: self.js_scripts.clone(),
width,
height,
};
Expand All @@ -444,21 +445,43 @@ impl Plot {
tmpl.render().unwrap()
}

fn plotly_js_source() -> String {
fn js_scripts() -> String {
if cfg!(feature = "plotly_embed_js") {
Self::local_plotly_js()
Self::offline_js_sources()
} else {
Self::cdn_plotly_js()
Self::online_cdn_js()
}
}

fn local_plotly_js() -> String {
let local_plotly = include_str!("../templates/plotly.min.js");
format!("<script type=\"text/javascript\">{}</script>", local_plotly).to_string()
fn offline_js_sources() -> String {
let local_plotly_js = include_str!("../templates/plotly.min.js");
let local_tex_mml_js = include_str!("../templates/tex-mml-chtml-3.2.0.js");
let local_tex_svg_js = include_str!("../templates/tex-svg-3.2.2.js");
format!(
"<script type=\"text/javascript\">{}</script>\n
<script type=\"text/javascript\">
/**
* tex-mml-chtml JS script
**/
{}
</script>\n
<script type=\"text/javascript\">
/**
* tex-svg JS script
**/
{}
</script>\n",
local_plotly_js, local_tex_mml_js, local_tex_svg_js
)
.to_string()
}

fn cdn_plotly_js() -> String {
r##"<script src="https://cdn.plot.ly/plotly-2.12.1.min.js"></script>"##.to_string()
fn online_cdn_js() -> String {
r##"<script src="https://cdn.plot.ly/plotly-2.12.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/es5/tex-svg.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/es5/tex-mml-chtml.js"></script>
"##
.to_string()
}

pub fn to_json(&self) -> String {
Expand Down
4 changes: 1 addition & 3 deletions plotly/templates/plot.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@

<body>
<div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/es5/tex-svg.js"></script>

{{plotly_js_source}}
{{js_scripts}}

<div id="plotly-html-element" class="plotly-graph-div" style="height:100%; width:100%;"></div>

Expand Down
6 changes: 2 additions & 4 deletions plotly/templates/static_plot.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,15 @@
</head>
<body>
<div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/es5/tex-mml-chtml.js"></script>

{{plotly_js_source}}
{{js_scripts}}

<div id="plotly-html-element" hidden></div>
<img id="plotly-img-element"></img>

<script type="module">
const graph_div = document.getElementById("plotly-html-element");
await Plotly.newPlot(graph_div, {{ plot|tojson|safe }});

const img_element = document.getElementById("plotly-img-element");
const data_url = await Plotly.toImage(
graph_div,
Expand Down
1 change: 1 addition & 0 deletions plotly/templates/tex-mml-chtml-3.2.0.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions plotly/templates/tex-svg-3.2.2.js

Large diffs are not rendered by default.

Loading