Skip to content

Rework wasm feature and make it work with getrandom 0.3 #277

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 3 commits into from
Feb 1, 2025
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
2 changes: 2 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[target.wasm32-unknown-unknown]
rustflags = ['--cfg', 'getrandom_backend="wasm_js"']
10 changes: 4 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ jobs:
with:
components: clippy
targets: wasm32-unknown-unknown
# lint the main library workspace excluding the wasm feature
- run: cargo clippy --features plotly_ndarray,plotly_image,kaleido -- -D warnings
# lint the plotly library with wasm enabled
- run: cargo clippy --package plotly --features wasm --target wasm32-unknown-unknown -- -D warnings
# lint the main library workspace for non-wasm target
- run: cargo clippy --all-features -- -D warnings
# lint the non-wasm examples
- run: cd ${{ github.workspace }}/examples && cargo clippy --workspace --exclude "wasm*" -- -D warnings
# lint the plotly library for wasm target
- run: cargo clippy --package plotly --target wasm32-unknown-unknown -- -D warnings
# lint the wasm examples
- run: cd ${{ github.workspace }}/examples && cargo clippy --target wasm32-unknown-unknown --package "wasm*"

Expand Down Expand Up @@ -83,8 +83,6 @@ jobs:
with:
components: llvm-tools-preview
- uses: taiki-e/install-action@cargo-llvm-cov
# we are skipping anything to do with wasm here
- run: cargo llvm-cov --workspace --features plotly_ndarray,plotly_image,kaleido --lcov --output-path lcov.info
- uses: codecov/codecov-action@v3

build_examples:
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ 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.13.0] - 2025-02-xx
### Changed
- [[#277](https://github.com/plotly/plotly.rs/pull/277)] Removed `wasm` feature flag and put evrything behind target specific dependencies. Added `.cargo/config.toml` for configuration flags needed by `getrandom` version 0.3 on `wasm` targets.

## [0.12.1] - 2025-01-02
### Fixed
- [[#269](https://github.com/plotly/plotly.rs/pull/269)] Fix publishing to crates.io issue
Expand Down
2 changes: 1 addition & 1 deletion docs/book/src/fundamentals/shapes.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use plotly::layout::{
ShapeType,
};
use plotly::{Bar, color::NamedColor, Plot, Scatter};
use rand::thread_rng;
use rand::rng;
use rand_distr::{Distribution, Normal};
```

Expand Down
2 changes: 1 addition & 1 deletion examples/3d_charts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ edition = "2021"

[dependencies]
ndarray = "0.16"
rand = "0.8"
rand = "0.9"
plotly = { path = "../../plotly" }
4 changes: 2 additions & 2 deletions examples/3d_charts/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,8 @@ fn colorscale_plot(show: bool) -> Plot {
let _color: Vec<usize> = (0..z.len()).collect();
let _color: Vec<u8> = (0..z.len()).map(|x| x as u8).collect();
let _color: Vec<i16> = {
let mut rng = rand::thread_rng();
(0..z.len()).map(|_| rng.gen_range(0..100)).collect()
let mut rng = rand::rng();
(0..z.len()).map(|_| rng.random_range(0..100)).collect()
};

let color_max = color.iter().fold(f64::MIN, |acc, x| acc.max(*x as f64));
Expand Down
4 changes: 2 additions & 2 deletions examples/basic_charts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ edition = "2021"
[dependencies]
ndarray = "0.16"
plotly = { path = "../../plotly" }
rand = "0.8"
rand_distr = "0.4"
rand = "0.9"
rand_distr = "0.5"
10 changes: 7 additions & 3 deletions examples/basic_charts/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn simple_scatter_plot(show: bool) -> Plot {
// ANCHOR: line_and_scatter_plots
fn line_and_scatter_plots(show: bool) -> Plot {
let n: usize = 100;
let mut rng = rand::thread_rng();
let mut rng = rand::rng();
let random_x: Vec<f64> = Array::linspace(0., 1., n).into_raw_vec_and_offset().0;
let random_y0: Vec<f64> = Normal::new(5., 1.)
.unwrap()
Expand Down Expand Up @@ -273,8 +273,12 @@ fn colored_and_styled_scatter_plot(show: bool) -> Plot {
// ANCHOR: large_data_sets
fn large_data_sets(show: bool) -> Plot {
let n: usize = 100_000;
let mut rng = rand::thread_rng();
let r: Vec<f64> = Uniform::new(0., 1.).sample_iter(&mut rng).take(n).collect();
let mut rng = rand::rng();
let r: Vec<f64> = Uniform::new(0., 1.)
.unwrap()
.sample_iter(&mut rng)
.take(n)
.collect();
let theta: Vec<f64> = Normal::new(0., 2. * std::f64::consts::PI)
.unwrap()
.sample_iter(&mut rng)
Expand Down
2 changes: 1 addition & 1 deletion examples/customization/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ edition = "2021"

[dependencies]
build_html = "2.5.0"
rand = "0.8"
rand = "0.9"
ndarray = "0.16"
plotly = { path = "../../plotly" }
7 changes: 2 additions & 5 deletions examples/customization/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,11 @@ fn write_html(html_data: &str) -> String {
use std::env;
use std::{fs::File, io::Write};

use rand::{
distributions::{Alphanumeric, DistString},
thread_rng,
};
use rand::distr::{Alphanumeric, SampleString};

// Set up the temp file with a unique filename.
let mut temp = env::temp_dir();
let mut plot_name = Alphanumeric.sample_string(&mut thread_rng(), 22);
let mut plot_name = Alphanumeric.sample_string(&mut rand::rng(), 22);
plot_name.push_str(".html");
plot_name = format!("plotly_{}", plot_name);
temp.push(plot_name);
Expand Down
4 changes: 2 additions & 2 deletions examples/shapes/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ edition = "2021"
[dependencies]
ndarray = "0.16"
plotly = { path = "../../plotly" }
rand = "0.8"
rand_distr = "0.4"
rand = "0.9"
rand_distr = "0.5"
3 changes: 1 addition & 2 deletions examples/shapes/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use plotly::{
},
Bar, Plot, Scatter,
};
use rand::thread_rng;
use rand_distr::{num_traits::Float, Distribution, Normal};

// ANCHOR: filled_area_chart
Expand Down Expand Up @@ -433,7 +432,7 @@ fn circles_positioned_relative_to_the_axes(show: bool) -> Plot {

// ANCHOR: highlighting_clusters_of_scatter_points_with_circle_shapes
fn highlighting_clusters_of_scatter_points_with_circle_shapes(show: bool) -> Plot {
let mut rng = thread_rng();
let mut rng = rand::rng();
let x0 = Normal::new(2., 0.45)
.unwrap()
.sample_iter(&mut rng)
Expand Down
4 changes: 2 additions & 2 deletions examples/statistical_charts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ edition = "2021"
[dependencies]
ndarray = "0.16"
plotly = { path = "../../plotly" }
rand = "0.8"
rand_distr = "0.4"
rand = "0.9"
rand_distr = "0.5"
16 changes: 8 additions & 8 deletions examples/statistical_charts/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,9 @@ fn colored_and_styled_error_bars(show: bool) -> Plot {
// Box Plots
// ANCHOR: basic_box_plot
fn basic_box_plot(show: bool) -> Plot {
let mut rng = rand::thread_rng();
let uniform1 = Uniform::new(0.0, 1.0);
let uniform2 = Uniform::new(1.0, 2.0);
let mut rng = rand::rng();
let uniform1 = Uniform::new(0.0, 1.0).unwrap();
let uniform2 = Uniform::new(1.0, 2.0).unwrap();
let n = 50;

let mut y0 = Vec::with_capacity(n);
Expand Down Expand Up @@ -407,8 +407,8 @@ fn grouped_horizontal_box_plot(show: bool) -> Plot {
fn fully_styled_box_plot(show: bool) -> Plot {
let rnd_sample = |num, mul| -> Vec<f64> {
let mut v: Vec<f64> = Vec::with_capacity(num);
let mut rng = rand::thread_rng();
let uniform = Uniform::new(0.0, mul);
let mut rng = rand::rng();
let uniform = Uniform::new(0.0, mul).unwrap();
for _ in 0..num {
v.push(uniform.sample(&mut rng));
}
Expand Down Expand Up @@ -478,7 +478,7 @@ fn fully_styled_box_plot(show: bool) -> Plot {

// Histograms
fn sample_normal_distribution(n: usize, mean: f64, std_dev: f64) -> Vec<f64> {
let mut rng = rand::thread_rng();
let mut rng = rand::rng();
let dist = Normal::new(mean, std_dev).unwrap();
let mut v = Vec::<f64>::with_capacity(n);
for _idx in 1..n {
Expand All @@ -488,8 +488,8 @@ fn sample_normal_distribution(n: usize, mean: f64, std_dev: f64) -> Vec<f64> {
}

fn sample_uniform_distribution(n: usize, lb: f64, ub: f64) -> Vec<f64> {
let mut rng = rand::thread_rng();
let dist = Uniform::new(lb, ub);
let mut rng = rand::rng();
let dist = Uniform::new(lb, ub).unwrap();
let mut v = Vec::<f64>::with_capacity(n);
for _idx in 1..n {
v.push(dist.sample(&mut rng));
Expand Down
2 changes: 1 addition & 1 deletion examples/wasm-yew-minimal/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ authors = [
edition = "2021"

[dependencies]
plotly = { path = "../../plotly", features = ["wasm"] }
plotly = { path = "../../plotly" }
yew = "0.21"
yew-hooks = "0.3"
log = "0.4"
Expand Down
14 changes: 7 additions & 7 deletions plotly/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,14 @@ plotly_ndarray = ["ndarray"]
plotly_image = ["image"]
plotly_embed_js = []

wasm = ["getrandom", "js-sys", "wasm-bindgen", "wasm-bindgen-futures"]
with-axum = ["rinja/with-axum", "rinja_axum"]

[dependencies]
rinja = { version = "0.3", features = ["serde_json"] }
rinja_axum = { version = "0.3", optional = true }
dyn-clone = "1"
erased-serde = "0.4"
getrandom = { version = "0.2", features = ["js"], optional = true }
image = { version = "0.25", optional = true }
js-sys = { version = "0.3", optional = true }
plotly_derive = { version = "0.12", path = "../plotly_derive" }
plotly_kaleido = { version = "0.12", path = "../plotly_kaleido", optional = true }
ndarray = { version = "0.16", optional = true }
Expand All @@ -40,9 +37,12 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_repr = "0.1"
serde_with = ">=2, <4"
rand = "0.8"
wasm-bindgen = { version = "0.2", optional = true }
wasm-bindgen-futures = { version = "0.4", optional = true }
rand = "0.9"

[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = { version = "0.3", features = ["wasm_js"] }
wasm-bindgen-futures = { version = "0.4" }
wasm-bindgen = { version = "0.2" }

[dev-dependencies]
csv = "1.1"
Expand All @@ -51,5 +51,5 @@ itertools = ">=0.10, <0.15"
itertools-num = "0.1"
ndarray = "0.16"
plotly_kaleido = { path = "../plotly_kaleido", features = ["download"] }
rand_distr = "0.4"
rand_distr = "0.5"
base64 = "0.22"
2 changes: 1 addition & 1 deletion plotly/src/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
//! context, where it is assumed that a remote copy of the Javascript Plotly
//! library is available, (i.e. via a CDN).

use js_sys::Object;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::js_sys::Object;

use crate::Plot;

Expand Down
6 changes: 3 additions & 3 deletions plotly/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,17 @@ extern crate rand;
extern crate rinja;
extern crate serde;

#[cfg(all(feature = "kaleido", feature = "wasm"))]
#[cfg(all(feature = "kaleido", target_family = "wasm"))]
compile_error!(
r#"The "kaleido" and "wasm" features are mutually exclusive and cannot be activated at the same time. Please disable one or the other."#
r#"The "kaleido" feature is not available on "wasm" targets. Please compile without this feature for the wasm target family."#
);

#[cfg(feature = "plotly_ndarray")]
pub mod ndarray;
#[cfg(feature = "plotly_ndarray")]
pub use crate::ndarray::ArrayTraces;

#[cfg(feature = "wasm")]
#[cfg(target_family = "wasm")]
pub mod bindings;

pub mod common;
Expand Down
21 changes: 11 additions & 10 deletions plotly/src/plot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::{fs::File, io::Write, path::Path};
use dyn_clone::DynClone;
use erased_serde::Serialize as ErasedSerialize;
use rand::{
distributions::{Alphanumeric, DistString},
thread_rng,
distr::{Alphanumeric, SampleString},
rng,
};
use rinja::Template;
use serde::Serialize;
Expand Down Expand Up @@ -254,7 +254,7 @@ impl Plot {

// Set up the temp file with a unique filename.
let mut temp = env::temp_dir();
let mut plot_name = Alphanumeric.sample_string(&mut thread_rng(), 22);
let mut plot_name = Alphanumeric.sample_string(&mut rng(), 22);
plot_name.push_str(".html");
plot_name = format!("plotly_{}", plot_name);
temp.push(plot_name);
Expand Down Expand Up @@ -296,7 +296,7 @@ impl Plot {

// Set up the temp file with a unique filename.
let mut temp = env::temp_dir();
let mut plot_name = Alphanumeric.sample_string(&mut thread_rng(), 22);
let mut plot_name = Alphanumeric.sample_string(&mut rng(), 22);
plot_name.push_str(".html");
plot_name = format!("plotly_{}", plot_name);
temp.push(plot_name);
Expand Down Expand Up @@ -354,13 +354,13 @@ impl Plot {
pub fn to_inline_html(&self, plot_div_id: Option<&str>) -> String {
let plot_div_id = match plot_div_id {
Some(id) => id.to_string(),
None => Alphanumeric.sample_string(&mut thread_rng(), 20),
None => Alphanumeric.sample_string(&mut rng(), 20),
};
self.render_inline(&plot_div_id)
}

fn to_jupyter_notebook_html(&self) -> String {
let plot_div_id = Alphanumeric.sample_string(&mut thread_rng(), 20);
let plot_div_id = Alphanumeric.sample_string(&mut rng(), 20);

let tmpl = JupyterNotebookPlotTemplate {
plot: self,
Expand Down Expand Up @@ -534,10 +534,11 @@ impl Plot {
serde_json::to_string(self).unwrap()
}

#[cfg(feature = "wasm")]
#[cfg(target_family = "wasm")]
/// Convert a `Plot` to a native Javasript `js_sys::Object`.
pub fn to_js_object(&self) -> js_sys::Object {
use wasm_bindgen::JsCast;
pub fn to_js_object(&self) -> wasm_bindgen_futures::js_sys::Object {
use wasm_bindgen_futures::js_sys;
use wasm_bindgen_futures::wasm_bindgen::JsCast;
// The only reason this could fail is if to_json() produces structurally
// incorrect JSON. That would be a bug, and would require fixing in the
// to_json()/serialization methods, rather than here
Expand Down Expand Up @@ -734,7 +735,7 @@ mod tests {

#[test]
#[ignore] // Don't really want it to try and open a browser window every time we run a test.
#[cfg(not(feature = "wasm"))]
#[cfg(not(target_family = "wasm"))]
fn show_image() {
let plot = create_test_plot();
plot.show_image(ImageFormat::PNG, 1024, 680);
Expand Down
2 changes: 1 addition & 1 deletion plotly/src/traces/histogram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ where
///
/// fn ndarray_to_traces() {
/// let n: usize = 1_250;
/// let mut rng = rand::thread_rng();
/// let mut rng = rand::rng();
/// let t: Array<f64, Ix1> = Array::range(0., 10., 10. / n as f64);
/// let mut ys: Array<f64, Ix2> = Array::zeros((n, 4));
/// let mut count = 0.;
Expand Down
Loading