diff --git a/.cargo/config.toml b/.cargo/config.toml deleted file mode 100644 index 2e07606d..00000000 --- a/.cargo/config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[target.wasm32-unknown-unknown] -rustflags = ['--cfg', 'getrandom_backend="wasm_js"'] diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 33c8c1f3..e32ec3a8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -25,8 +25,9 @@ jobs: - run: cargo publish --allow-dirty -p plotly_kaleido - run: sleep 10 - run: cargo publish --allow-dirty -p plotly - - run: sleep 10 - - run: cargo publish --allow-dirty -p plotly_static --features webdriver_download,chromedriver + # plotly_static is not part of the same ecosystem yet so it doesn't use the same TOKEN + # - run: sleep 10 + # - run: cargo publish --allow-dirty -p plotly_static --features webdriver_download,chromedriver create-gh-release: name: Deploy to GH Releases diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d4d6751..85f3faad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,33 @@ 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.5] - 2025-07-31 + +### Fixed + +- [[#346](https://github.com/plotly/plotly.rs/pull/346)] Remove usage of `getrandom` for `rand` dependency and for this crate +- [[#345](https://github.com/plotly/plotly.rs/pull/345)] Re-export `ImageFormat` from `plotly_static` into `plotly` + +## [0.13.4] - 2025-07-17 + +### Fixed + +- [[#341](https://github.com/plotly/plotly.rs/pull/341)] Fix documentation related to `wasm` support + +### Changed +- [[#339](https://github.com/plotly/plotly.rs/pull/339)] Replace default Windows app with `explorer` + +## [0.13.3] - 2025-07-12 + +### Changed +- [[#335](https://github.com/plotly/plotly.rs/pull/335)] Add minimal animation support + +## [0.13.2] - 2025-07-12 + +### Fixed +- [[#336](https://github.com/plotly/plotly.rs/pull/336)] Fix `plotly_static` docs.rs build +- [[#327](https://github.com/plotly/plotly.rs/pull/327)] Fix book broken link + ## [0.13.1] - 2025-07-07 ### Fixed diff --git a/README.md b/README.md index 5349b200..461356c1 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,10 @@ * [Introduction](#introduction) * [Basic Usage](#basic-usage) - * [Exporting an Interactive Plot](#exporting-an-interactive-plot) - * [Exporting Static Images with Kaleido](#exporting-static-images-with-kaleido) - * [Usage Within a Wasm Environment](#usage-within-a-wasm-environment) + * [Exporting a single Interactive Plot](#exporting-a-single-interactive-plot) + * [Exporting Static Images with plotly_static (Recommended)](#exporting-static-images-with-plotly_static-recommended) + * [Exporting Static Images with Kaleido (legacy)](#exporting-static-images-with-kaleido-legacy) + * [Usage Within a WASM Environment](#usage-within-a-wasm-environment) * [Crate Feature Flags](#crate-feature-flags) * [Contributing](#contributing) * [Code of Conduct](#code-of-conduct) @@ -95,18 +96,6 @@ If you only want to view the plot in the browser quickly, use the `Plot.show()` plot.show(); // The default web browser will open, displaying an interactive plot ``` -## Exporting Static Images with Kaleido - -To save a plot as a static image, the `kaleido` feature is required as well as installing an **external dependency**. - -### Kaleido external dependency - -When developing applications for your host, enabling both `kaleido` and `kaleido_download` features will ensure that the `kaleido` binary is downloaded for your system's architecture at compile time. After download, it is unpacked into a specific path, e.g., on Linux this is `/home/USERNAME/.config/kaleido`. With these two features enabled, static images can be exported as described in the next section as long as the application runs on the same machine where it has been compiled on. - -When the applications developed with `plotly.rs` are intended for other targets or when the user wants to control where the `kaleido` binary is installed then Kaleido must be manually downloaded and installed. Setting the environment variable `KALEIDO_PATH=/path/installed/kaleido/` will ensure that applications that were built with the `kaleido` feature enabled can locate the `kaleido` executable and use it to generate static images. - -Kaleido binaries are available on Github [release page](https://github.com/plotly/Kaleido/releases). It currently supports Linux(`x86_64`), Windows(`x86_64`) and MacOS(`x86_64`/`aarch64`). - ## Exporting Static Images with plotly_static (Recommended) The recommended way to export static images is using the `plotly_static` backend, which uses a headless browser via WebDriver (Chrome or Firefox) for rendering. This is available via the `static_export_default` feature: @@ -119,7 +108,7 @@ plotly = { version = "0.13", features = ["static_export_default"] } This supports PNG, JPEG, WEBP, SVG, and PDF formats: ```rust -use plotly::{Plot, Scatter, ImageFormat}; +use plotly::{Plot, Scatter,ImageFormat}; let mut plot = Plot::new(); plot.add_trace(Scatter::new(vec![0, 1, 2], vec![2, 1, 0])); @@ -132,7 +121,7 @@ let svg_string = plot.to_svg(800, 600, 1.0)?; **Note:** This feature requires a WebDriver-compatible browser (Chrome or Firefox) as well as a Webdriver (chromedriver/geckodriver) to be available on the system. For advanced usage, see the [`plotly_static` crate documentation](https://docs.rs/plotly_static/). -## Exporting Static Images with Kaleido (to be deprecated) +## Exporting Static Images with Kaleido (legacy) Enable the `kaleido` feature and opt in for automatic downloading of the `kaleido` binaries by doing the following @@ -165,9 +154,19 @@ plot.add_trace(trace); plot.write_image("out.png", ImageFormat::PNG, 800, 600, 1.0); ``` -## Usage Within a Wasm Environment +### Kaleido external dependency + +When developing applications for your host, enabling both `kaleido` and `kaleido_download` features will ensure that the `kaleido` binary is downloaded for your system's architecture at compile time. After download, it is unpacked into a specific path, e.g., on Linux this is `/home/USERNAME/.config/kaleido`. With these two features enabled, static images can be exported as described in the next section as long as the application runs on the same machine where it has been compiled on. + +When the applications developed with `plotly.rs` are intended for other targets or when the user wants to control where the `kaleido` binary is installed then Kaleido must be manually downloaded and installed. Setting the environment variable `KALEIDO_PATH=/path/installed/kaleido/` will ensure that applications that were built with the `kaleido` feature enabled can locate the `kaleido` executable and use it to generate static images. -`Plotly.rs` can be used with a Wasm-based frontend framework. The needed dependencies are automatically enabled on `wasm32` targets. Note that the `kaleido` feature is not supported in Wasm environments and will throw a compilation error if enabled. +Kaleido binaries are available on Github [release page](https://github.com/plotly/Kaleido/releases). It currently supports Linux(`x86_64`), Windows(`x86_64`) and MacOS(`x86_64`/`aarch64`). + +## Usage Within a WASM Environment + +`Plotly.rs` can be used with a WASM-based frontend framework. Note that the `kaleido` and `plotly_static` static export features are not supported in WASM environments and will throw a compilation error if used. + +The needed dependencies are automatically enabled for `wasm32` targets at compile time and there is no longer a need for the custom `wasm` flag in this crate. First, make sure that you have the Plotly JavaScript library in your base HTML template: @@ -190,7 +189,6 @@ A simple `Plot` component would look as follows, using `Yew` as an example front use plotly::{Plot, Scatter}; use yew::prelude::*; - #[function_component(PlotComponent)] pub fn plot_component() -> Html { let p = yew_hooks::use_async::<_, _, ()>({ @@ -218,22 +216,23 @@ pub fn plot_component() -> Html { } ``` -More detailed standalone examples can be found in the [examples/](https://github.com/plotly/plotly.rs/tree/main/examples) directory. +More detailed standalone examples can be found in the [examples/wasm-yew](https://github.com/plotly/plotly.rs/tree/main/examples/wasm-yew) directory. # Crate Feature Flags The following feature flags are available: -### `kaleido` +### `static_export_default` -Adds plot save functionality to the following formats: `png`, `jpeg`, `webp`, `svg`, `pdf` and `eps`. +Since version `0.13.0` support for exporting to static images is based on using a new crate called `plotly_static` that uses WebDriver and browser automation for static export functionality. -Requires `Kaleido` to have been previously installed on the host machine. See the following feature flag and [Kaleido external dependency](#kaleido-external-dependency). +This feature flag automatically enables the usage of the `plotly_static` dependency as well as the `chromedriver` and `webdriver_download` features of that crate. For more details about these feature flags, refer to the `plotly_static` [documentation](plotly_static/README.md). -### `kaleido_download` +The other related features allow controlling other aspects of the `plotly_static` crate + - `static_export_chromedriver` + - `static_export_geckodriver` + - `static_export_wd_download` -Enable download and install of Kaleido binary at build time from [Kaleido releases](https://github.com/plotly/Kaleido/releases/) on the host machine. -See [Kaleido external dependency](#kaleido-external-dependency) for more details. ### `plotly_image` @@ -253,9 +252,16 @@ When the feature is enabled, users can still opt in for the CDN version by using 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. -### `wasm` +### `kaleido` (legacy) -Enables compilation for the `wasm32-unknown-unknown` target and provides access to a `bindings` module containing wrappers around functions exported by the plotly.js library. +Adds plot save functionality to the following formats: `png`, `jpeg`, `webp`, `svg`, `pdf` and `eps`. + +Requires `Kaleido` to have been previously installed on the host machine. See the following feature flag and [Kaleido external dependency](#kaleido-external-dependency). + +### `kaleido_download` (legacy) + +Enable download and install of Kaleido binary at build time from [Kaleido releases](https://github.com/plotly/Kaleido/releases/) on the host machine. +See [Kaleido external dependency](#kaleido-external-dependency) for more details. # Contributing diff --git a/docs/book/src/SUMMARY.md b/docs/book/src/SUMMARY.md index f53ab8c5..4b70fa75 100644 --- a/docs/book/src/SUMMARY.md +++ b/docs/book/src/SUMMARY.md @@ -35,3 +35,4 @@ - [Custom Controls](./recipes/custom_controls.md) - [Dropdowns](./recipes/custom_controls/dropdowns.md) - [Sliders](./recipes/custom_controls/sliders.md) + - [Animations](./recipes/custom_controls/animations.md) diff --git a/docs/book/src/fundamentals/static_image_export.md b/docs/book/src/fundamentals/static_image_export.md index 3eec1438..81dab8d0 100644 --- a/docs/book/src/fundamentals/static_image_export.md +++ b/docs/book/src/fundamentals/static_image_export.md @@ -57,8 +57,7 @@ plotly = { version = "0.13", features = ["static_export_default"] } ### Simple Export ```rust -use plotly::{Plot, Scatter}; -use plotly::plotly_static::ImageFormat; +use plotly::{Plot, Scatter, ImageFormat}; let mut plot = Plot::new(); plot.add_trace(Scatter::new(vec![1, 2, 3], vec![4, 5, 6])); @@ -198,11 +197,6 @@ let mut exporter = StaticExporterBuilder::default() - **Exporter Reuse**: Create a single `StaticExporter` and reuse it for multiple plots - **Parallel Usage**: Use unique ports for parallel operations (tests, etc.) - **Resource Management**: The exporter automatically manages WebDriver lifecycle -- **Format Selection**: Choose appropriate formats for your use case: - - PNG: Good quality, lossless - - JPEG: Smaller files, lossy - - SVG: Scalable, good for web - - PDF: Good for printing ## Complete Example diff --git a/docs/book/src/recipes/custom_controls.md b/docs/book/src/recipes/custom_controls.md index 0527e6f4..f6cb7ab4 100644 --- a/docs/book/src/recipes/custom_controls.md +++ b/docs/book/src/recipes/custom_controls.md @@ -6,3 +6,4 @@ This section covers interactive controls that can be added to plots to modify da |--------------|---------| | [Dropdown Menus and Buttons](./custom_controls/dropdowns.md) | ![Dropdown Example](./img/dropdown.png) | | [Sliders](./custom_controls/sliders.md) | ![Slider Example](./img/sliders.png) | +| [Animations](./custom_controls/animations.md) | ![Animation Example](./img/animation.png) | diff --git a/docs/book/src/recipes/custom_controls/animations.md b/docs/book/src/recipes/custom_controls/animations.md new file mode 100644 index 00000000..1914a70b --- /dev/null +++ b/docs/book/src/recipes/custom_controls/animations.md @@ -0,0 +1,12 @@ +# Animations + +Animations in Plotly.rs allow you to create dynamic, interactive visualizations that can play through different data states over time. + +## GDP vs. Life Expectancy Animation + +This example demonstrates an animation based on the Gapminder dataset, showing the relationship between GDP per capita and life expectancy across different continents over several decades. The animation is based on the JavaScript example https://plotly.com/javascript/gapminder-example/ and shows how to create buttons and sliders that interact with the animation mechanism. + +```rust,no_run +{{#include ../../../../../examples/custom_controls/src/main.rs:gdp_life_expectancy_animation_example}} +``` +{{#include ../../../../../examples/custom_controls/output/inline_gdp_life_expectancy_animation_example.html}} diff --git a/docs/book/src/recipes/img/animation.png b/docs/book/src/recipes/img/animation.png new file mode 100644 index 00000000..7c3b8dac Binary files /dev/null and b/docs/book/src/recipes/img/animation.png differ diff --git a/docs/book/src/recipes/subplots/subplots.md b/docs/book/src/recipes/subplots/subplots.md index c4e9fa73..9ed53066 100644 --- a/docs/book/src/recipes/subplots/subplots.md +++ b/docs/book/src/recipes/subplots/subplots.md @@ -24,7 +24,7 @@ The `to_inline_html` method is used to produce the html plot displayed in this p {{#include ../../../../../examples/subplots/src/main.rs:subplots_with_multiple_traces}} ``` -{{#include ../../../../../examples/subplots/output/inline_subplot_with_multiple_traces.html}} +{{#include ../../../../../examples/subplots/output/inline_subplots_with_multiple_traces.html}} ## Custom Sized Subplot diff --git a/examples/custom_controls/src/main.rs b/examples/custom_controls/src/main.rs index a82d2da7..1643b69d 100644 --- a/examples/custom_controls/src/main.rs +++ b/examples/custom_controls/src/main.rs @@ -7,8 +7,8 @@ use plotly::{ common::{Anchor, ColorScalePalette, Font, Mode, Pad, Title, Visible}, layout::{ update_menu::{ButtonBuilder, UpdateMenu, UpdateMenuDirection, UpdateMenuType}, - Axis, BarMode, Layout, Slider, SliderCurrentValue, SliderCurrentValueXAnchor, SliderStep, - SliderStepBuilder, + AnimationOptions, Axis, BarMode, Layout, Slider, SliderCurrentValue, + SliderCurrentValueXAnchor, SliderStep, SliderStepBuilder, }, Bar, HeatMap, Plot, Scatter, }; @@ -388,7 +388,7 @@ fn gdp_life_expectancy_slider_example(show: bool, file_name: &str) { visible[start..end].fill(Visible::True); SliderStepBuilder::new() - .label(format!("year = {year}")) + .label(year.to_string()) .value(year) .push_restyle(Scatter::::modify_visible(visible)) .push_relayout(Layout::modify_title(format!( @@ -409,8 +409,18 @@ fn gdp_life_expectancy_slider_example(show: bool, file_name: &str) { .title(Title::with_text("gdpPercap")) .type_(plotly::layout::AxisType::Log), ) - .y_axis(Axis::new().title(Title::with_text("lifeExp"))) - .sliders(vec![Slider::new().active(0).steps(steps)]); + .y_axis( + Axis::new() + .title(Title::with_text("lifeExp")) + .range(vec![30.0, 85.0]), // Fixed range for Life Expectancy + ) + .sliders(vec![Slider::new().active(0).steps(steps).current_value( + SliderCurrentValue::new() + .visible(true) + .prefix("Year: ") + .x_anchor(SliderCurrentValueXAnchor::Right) + .font(Font::new().size(20).color("rgb(102, 102, 102)")), + )]); plot.set_layout(layout); let path = write_example_to_html(&plot, file_name); if show { @@ -419,6 +429,291 @@ fn gdp_life_expectancy_slider_example(show: bool, file_name: &str) { } // ANCHOR_END: gdp_life_expectancy_slider_example +// ANCHOR: gdp_life_expectancy_animation_example +// GDP per Capita/Life Expectancy Animation (animated version of the slider +// example) +fn gdp_life_expectancy_animation_example(show: bool, file_name: &str) { + use plotly::{ + common::Font, + common::Pad, + common::Title, + layout::Axis, + layout::{ + update_menu::{ButtonBuilder, UpdateMenu, UpdateMenuDirection, UpdateMenuType}, + Animation, AnimationMode, Frame, FrameSettings, Slider, SliderCurrentValue, + SliderCurrentValueXAnchor, SliderStepBuilder, TransitionSettings, + }, + Layout, Plot, Scatter, + }; + + let data = load_gapminder_data(); + + // Get unique years and sort them + let years: Vec = data + .iter() + .map(|d| d.year) + .collect::>() + .into_iter() + .sorted() + .collect(); + + // Create color mapping for continents to match the Python plotly example + let continent_colors = HashMap::from([ + ("Asia".to_string(), "rgb(99, 110, 250)"), + ("Europe".to_string(), "rgb(239, 85, 59)"), + ("Africa".to_string(), "rgb(0, 204, 150)"), + ("Americas".to_string(), "rgb(171, 99, 250)"), + ("Oceania".to_string(), "rgb(255, 161, 90)"), + ]); + let continents: Vec = continent_colors.keys().cloned().sorted().collect(); + + let mut plot = Plot::new(); + let mut initial_traces = Vec::new(); + + for (frame_index, &year) in years.iter().enumerate() { + let mut frame_traces = plotly::Traces::new(); + + for continent in &continents { + let records: Vec<&GapminderData> = data + .iter() + .filter(|d| d.continent == *continent && d.year == year) + .collect(); + + if !records.is_empty() { + let x: Vec = records.iter().map(|r| r.gdp_per_cap).collect(); + let y: Vec = records.iter().map(|r| r.life_exp).collect(); + let size: Vec = records.iter().map(|r| r.pop).collect(); + let hover: Vec = records.iter().map(|r| r.country.clone()).collect(); + + let trace = Scatter::new(x, y) + .name(continent) + .mode(Mode::Markers) + .hover_text_array(hover) + .marker( + plotly::common::Marker::new() + .color(*continent_colors.get(continent).unwrap()) + .size_array(size.into_iter().map(|s| s as usize).collect()) + .size_mode(plotly::common::SizeMode::Area) + .size_ref(200000) + .size_min(4), + ); + + frame_traces.push(trace.clone()); + + // Store traces from first year for initial plot + if frame_index == 0 { + initial_traces.push(trace); + } + } + } + + // Create layout for this frame + let frame_layout = Layout::new() + .title(Title::with_text(format!( + "GDP vs. Life Expectancy ({year})" + ))) + .x_axis( + Axis::new() + .title(Title::with_text("gdpPercap")) + .type_(plotly::layout::AxisType::Log), + ) + .y_axis( + Axis::new() + .title(Title::with_text("lifeExp")) + .range(vec![30.0, 85.0]), // Fixed range for Life Expectancy + ); + + // Add frame with all traces for this year + plot.add_frame( + Frame::new() + .name(format!("frame{frame_index}")) + .data(frame_traces) + .layout(frame_layout), + ); + } + + // Add initial traces to the plot (all traces from first year) + for trace in initial_traces { + plot.add_trace(trace); + } + + // Create animation configuration for playing all frames + let play_animation = Animation::all_frames().options( + AnimationOptions::new() + .mode(AnimationMode::Immediate) + .frame(FrameSettings::new().duration(500).redraw(false)) + .transition(TransitionSettings::new().duration(300)) + .fromcurrent(true), + ); + + let play_button = ButtonBuilder::new() + .label("Play") + .animation(play_animation) + .build() + .unwrap(); + + let pause_animation = Animation::pause(); + + let pause_button = ButtonBuilder::new() + .label("Pause") + .animation(pause_animation) + .build() + .unwrap(); + + let updatemenu = UpdateMenu::new() + .ty(UpdateMenuType::Buttons) + .direction(UpdateMenuDirection::Right) + .buttons(vec![play_button, pause_button]) + .x(0.1) + .y(1.15) + .show_active(true) + .visible(true); + + // Create slider steps for each year + let mut slider_steps = Vec::new(); + for (i, &year) in years.iter().enumerate() { + let frame_animation = Animation::frames(vec![format!("frame{}", i)]).options( + AnimationOptions::new() + .mode(AnimationMode::Immediate) + .frame(FrameSettings::new().duration(300).redraw(false)) + .transition(TransitionSettings::new().duration(300)), + ); + let step = SliderStepBuilder::new() + .label(year.to_string()) + .value(year) + .animation(frame_animation) + .build() + .unwrap(); + slider_steps.push(step); + } + + let slider = Slider::new() + .pad(Pad::new(55, 0, 130)) + .current_value( + SliderCurrentValue::new() + .visible(true) + .prefix("Year: ") + .x_anchor(SliderCurrentValueXAnchor::Right) + .font(Font::new().size(20).color("rgb(102, 102, 102)")), + ) + .steps(slider_steps); + + // Set the layout with initial title, buttons, and slider + let layout = Layout::new() + .title(Title::with_text(format!( + "GDP vs. Life Expectancy ({}) - Click 'Play' to animate", + years[0] + ))) + .x_axis( + Axis::new() + .title(Title::with_text("gdpPercap")) + .type_(plotly::layout::AxisType::Log), + ) + .y_axis( + Axis::new() + .title(Title::with_text("lifeExp")) + .range(vec![30.0, 85.0]), // Fixed range for Life Expectancy + ) + .update_menus(vec![updatemenu]) + .sliders(vec![slider]); + + plot.set_layout(layout); + + let path = write_example_to_html(&plot, file_name); + if show { + plot.show_html(path); + } +} +// ANCHOR_END: gdp_life_expectancy_animation_example + +// ANCHOR: animation_randomize_example +/// Animation example based on the Plotly.js "Randomize" animation. +/// This demonstrates the new builder API for animation configuration. +fn animation_randomize_example(show: bool, file_name: &str) { + use plotly::{ + layout::update_menu::{ButtonBuilder, UpdateMenu, UpdateMenuDirection, UpdateMenuType}, + layout::{ + Animation, AnimationEasing, AnimationMode, Frame, FrameSettings, TransitionSettings, + }, + Plot, Scatter, + }; + + // Initial data + let x = vec![1, 2, 3]; + let y0 = vec![0.0, 0.5, 1.0]; + let y1 = vec![0.2, 0.8, 0.3]; + let y2 = vec![0.9, 0.1, 0.7]; + + let mut plot = Plot::new(); + let base = + Scatter::new(x.clone(), y0.clone()).line(plotly::common::Line::new().simplify(false)); + plot.add_trace(base.clone()); + + // Add frames with different y-values and auto-adjusting layouts + let mut trace0 = plotly::Traces::new(); + trace0.push(base); + + let mut trace1 = plotly::Traces::new(); + trace1.push(Scatter::new(x.clone(), y1.clone())); + + let mut trace2 = plotly::Traces::new(); + trace2.push(Scatter::new(x.clone(), y2.clone())); + + let animation = Animation::new().options( + AnimationOptions::new() + .mode(AnimationMode::Immediate) + .frame(FrameSettings::new().duration(500)) + .transition( + TransitionSettings::new() + .duration(500) + .easing(AnimationEasing::CubicInOut), + ), + ); + + let layout0 = plotly::Layout::new() + .title(Title::with_text("First frame")) + .y_axis(plotly::layout::Axis::new().range(vec![0.0, 1.0])); + let layout1 = plotly::Layout::new() + .title(Title::with_text("Second frame")) + .y_axis(plotly::layout::Axis::new().range(vec![0.0, 1.0])); + let layout2 = plotly::Layout::new() + .title(Title::with_text("Third frame")) + .y_axis(plotly::layout::Axis::new().range(vec![0.0, 1.0])); + + // Add frames using the new API + plot.add_frame(Frame::new().name("frame0").data(trace0).layout(layout0)) + .add_frame(Frame::new().name("frame1").data(trace1).layout(layout1)) + .add_frame(Frame::new().name("frame2").data(trace2).layout(layout2)); + + let randomize_button = ButtonBuilder::new() + .label("Animate") + .animation(animation) + .build() + .unwrap(); + + let updatemenu = UpdateMenu::new() + .ty(UpdateMenuType::Buttons) + .direction(UpdateMenuDirection::Right) + .buttons(vec![randomize_button]) + .x(0.1) + .y(1.15) + .show_active(true) + .visible(true); + + plot.set_layout( + Layout::new() + .title("Animation Example - Click 'Animate'") + .y_axis(Axis::new().title("Y Axis").range(vec![0.0, 1.0])) + .update_menus(vec![updatemenu]), + ); + + let path = plotly_utils::write_example_to_html(&plot, file_name); + if show { + plot.show_html(path); + } +} +// ANCHOR_END: animation_randomize_example + fn main() { // Change false to true on any of these lines to display the example. bar_plot_with_dropdown_for_different_data(false, "bar_plot"); @@ -429,4 +724,7 @@ fn main() { bar_chart_with_slider_customization(false, "bar_chart_with_slider_customization"); sinusoidal_slider_example(false, "sinusoidal_slider_example"); gdp_life_expectancy_slider_example(false, "gdp_life_expectancy_slider_example"); + // Animation examples + animation_randomize_example(false, "animation_randomize_example"); + gdp_life_expectancy_animation_example(false, "gdp_life_expectancy_animation_example"); } diff --git a/examples/customization/consistent_static_format_export/README.md b/examples/customization/consistent_static_format_export/README.md index f8fc63ba..b40a40ba 100644 --- a/examples/customization/consistent_static_format_export/README.md +++ b/examples/customization/consistent_static_format_export/README.md @@ -4,22 +4,9 @@ This example demonstrates exporting a plot to SVG, PNG, and PDF using plotly.rs This example is based on [GitHub Issue #171](https://github.com/plotly/plotly.rs/issues/171). - -**Summary:** - For consistent font rendering across browsers and export formats, always set the `font.family` property explicitly in your plot configuration. Relying on default or generic font settings can lead to differences in appearance, especially for font size and legend layout, depending on the browser or export backend. -**Recommendation:** - -Always set the `font.family` property (e.g., to `"Times New Roman, serif"`) for all text elements (titles, axes, legends) to ensure consistent results in all output formats. - -## Overview - -This example creates a line and scatter plot with custom styling, including: -- Large font sizes for titles, legends, and axes -- Custom legend positioning and styling -- Border shapes around the plot -- Export to multiple formats (PDF, SVG, PNG) +The issue reported in [#171](https://github.com/plotly/plotly.rs/issues/171)is solved when the `font.family` property is set explicitly (e.g., to `"Times New Roman, serif"`) for all text elements (titles, axes, legends) which ensures consistent results in all output formats across different browsers. ## Running the Example @@ -29,6 +16,6 @@ cargo run ``` This will generate three output files: -- `Data_plot.pdf` - PDF format (typically renders correctly) -- `Data_plot.svg` - SVG format (may have font/legend issues) -- `Data_plot.png` - PNG format (typically renders correctly) +- `Data_plot.png` +- `Data_plot.svg` - will render fonts differently when compared with PNG if font family not fully specified +- `Data_plot.pdf` - uses SVG for PDF generation and will inherit the same issue as SVG diff --git a/plotly/Cargo.toml b/plotly/Cargo.toml index 6f0c93a5..a744ceea 100644 --- a/plotly/Cargo.toml +++ b/plotly/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plotly" -version = "0.13.1" +version = "0.13.5" description = "A plotting library powered by Plotly.js" authors = [ "Ioannis Giagkiozis ", @@ -17,11 +17,6 @@ keywords = ["plot", "chart", "plotly"] exclude = ["target/*"] [features] -# DEPRECATED: kaleido feature will be removed in version 0.14.0. Use `static_export_*` features instead. -kaleido = ["plotly_kaleido"] -# DEPRECATED: kaleido_download feature will be removed in version 0.14.0. Use `static_export_wd_download` instead. -kaleido_download = ["plotly_kaleido/download"] - static_export_chromedriver = ["plotly_static", "plotly_static/chromedriver"] static_export_geckodriver = ["plotly_static", "plotly_static/geckodriver"] static_export_wd_download = ["plotly_static/webdriver_download"] @@ -31,6 +26,10 @@ static_export_default = [ "plotly_static/webdriver_download", ] +plotly_ndarray = ["ndarray"] +plotly_image = ["image"] +plotly_embed_js = [] + # All non-conflicting features all = [ "plotly_ndarray", @@ -41,9 +40,11 @@ all = [ # This is used for enabling extra debugging messages and debugging functionality debug = ["plotly_static?/debug"] -plotly_ndarray = ["ndarray"] -plotly_image = ["image"] -plotly_embed_js = [] +# DEPRECATED: kaleido feature will be removed in version 0.14.0. Use `static_export_*` features instead. +kaleido = ["plotly_kaleido"] +# DEPRECATED: kaleido_download feature will be removed in version 0.14.0. Use `static_export_wd_download` instead. +kaleido_download = ["plotly_kaleido/download"] + [dependencies] askama = { version = "0.14.0", features = ["serde_json"] } @@ -51,7 +52,7 @@ dyn-clone = "1" erased-serde = "0.4" image = { version = "0.25", optional = true } plotly_derive = { version = "0.13", path = "../plotly_derive" } -plotly_static = { version = "0.0.1", path = "../plotly_static", optional = true } +plotly_static = { version = "0.0", path = "../plotly_static", optional = true } plotly_kaleido = { version = "0.13", path = "../plotly_kaleido", optional = true } ndarray = { version = "0.16", optional = true } once_cell = "1" @@ -59,10 +60,12 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" serde_repr = "0.1" serde_with = ">=2, <4" -rand = "0.9" +rand = { version = "0.9", default-features = false, features = [ + "small_rng", + "alloc", +] } [target.'cfg(target_arch = "wasm32")'.dependencies] -getrandom = { version = "0.3", features = ["wasm_js"] } wasm-bindgen-futures = { version = "0.4" } wasm-bindgen = { version = "0.2" } serde-wasm-bindgen = { version = "0.6.3" } diff --git a/plotly/src/common/mod.rs b/plotly/src/common/mod.rs index cd866c3a..df2dc9ba 100644 --- a/plotly/src/common/mod.rs +++ b/plotly/src/common/mod.rs @@ -1180,7 +1180,10 @@ pub struct Marker { size_mode: Option, line: Option, gradient: Option, + /// Marker option specific for Scatter and other common traces color: Option>>, + /// Marker option specific for Pie charts to set the colors of the sectors + colors: Option>>, cauto: Option, cmin: Option, cmax: Option, @@ -1260,6 +1263,11 @@ impl Marker { self } + pub fn colors(mut self, colors: Vec) -> Self { + self.colors = Some(ColorArray(colors).into()); + self + } + pub fn color_array(mut self, colors: Vec) -> Self { self.color = Some(Dim::Vector(ColorArray(colors).into())); self @@ -2330,6 +2338,7 @@ mod tests { .line(Line::new()) .gradient(Gradient::new(GradientType::Radial, "#FFFFFF")) .color(NamedColor::Blue) + .colors(vec![NamedColor::Black, NamedColor::Blue]) .color_array(vec![NamedColor::Black, NamedColor::Blue]) .cauto(true) .cmin(0.0) @@ -2359,6 +2368,7 @@ mod tests { "line": {}, "gradient": {"type": "radial", "color": "#FFFFFF"}, "color": ["black", "blue"], + "colors": ["black", "blue"], "colorbar": {}, "cauto": true, "cmin": 0.0, diff --git a/plotly/src/layout/animation.rs b/plotly/src/layout/animation.rs new file mode 100644 index 00000000..06fa666d --- /dev/null +++ b/plotly/src/layout/animation.rs @@ -0,0 +1,474 @@ +//! Animation support for Plotly.rs +//! +//! This module provides animation configuration for Plotly.js updatemenu +//! buttons and slider steps, following the Plotly.js animation API +//! specification. + +use plotly_derive::FieldSetter; +use serde::ser::{SerializeSeq, Serializer}; +use serde::Serialize; + +use crate::{Layout, Traces}; + +/// A frame represents a single state in an animation sequence. +/// Based on Plotly.js frame_attributes.js specification +#[serde_with::skip_serializing_none] +#[derive(Serialize, Clone, FieldSetter)] +pub struct Frame { + /// An identifier that specifies the group to which the frame belongs, + /// used by animate to select a subset of frames + group: Option, + /// A label by which to identify the frame + name: Option, + /// A list of trace indices that identify the respective traces in the data + /// attribute + traces: Option>, + /// The name of the frame into which this frame's properties are merged + /// before applying. This is used to unify properties and avoid needing + /// to specify the same values for the same properties in multiple + /// frames. + baseframe: Option, + /// A list of traces this frame modifies. The format is identical to the + /// normal trace definition. + data: Option, + /// Layout properties which this frame modifies. The format is identical to + /// the normal layout definition. + layout: Option, +} + +impl Frame { + pub fn new() -> Self { + Default::default() + } +} + +/// Represents the animation arguments array for Plotly.js +/// Format: [frameNamesOrNull, animationOptions] +#[derive(Clone, Debug)] +pub struct Animation { + /// Frames sequence: null, [null], or array of frame names + frames: FrameListMode, + /// Animation options/configuration + options: AnimationOptions, +} + +impl Default for Animation { + fn default() -> Self { + Self { + frames: FrameListMode::All, + options: AnimationOptions::default(), + } + } +} + +impl Animation { + /// Create a new animation args with default values for options and + /// FramesMode set to all frames + pub fn new() -> Self { + Self::default() + } + + /// Create a animation for playing all frames (default) + pub fn all_frames() -> Self { + Self::new() + } + + /// Create a animation setup specifically for pausing a running animation + pub fn pause() -> Self { + Self { + frames: FrameListMode::Pause, + options: AnimationOptions::new() + .mode(AnimationMode::Immediate) + .frame(FrameSettings::new().duration(0).redraw(false)) + .transition(TransitionSettings::new().duration(0)), + } + } + + /// Create animation args for specific frames + pub fn frames(frames: Vec) -> Self { + Self { + frames: FrameListMode::Frames(frames), + ..Default::default() + } + } + + /// Set the animation options + pub fn options(mut self, options: AnimationOptions) -> Self { + self.options = options; + self + } +} + +impl Serialize for Animation { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut seq = serializer.serialize_seq(Some(2))?; + seq.serialize_element(&self.frames)?; + seq.serialize_element(&self.options)?; + seq.end() + } +} + +/// First argument in animation args - can be null, [null], or frame names +#[derive(Clone, Debug)] +pub enum FrameListMode { + /// null - animate all frames + All, + /// Array of frame names to animate + Frames(Vec), + /// special mode, [null], for pausing an animation + Pause, +} + +impl Serialize for FrameListMode { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + FrameListMode::All => serializer.serialize_unit(), + FrameListMode::Pause => { + let arr = vec![serde_json::Value::Null]; + arr.serialize(serializer) + } + FrameListMode::Frames(frames) => frames.serialize(serializer), + } + } +} + +/// Animation configuration options +/// Based on actual Plotly.js animation API from animation_attributes.js +#[serde_with::skip_serializing_none] +#[derive(Serialize, Clone, Debug, FieldSetter)] +pub struct AnimationOptions { + /// Frame animation settings + frame: Option, + /// Transition animation settings + transition: Option, + /// Animation mode + mode: Option, + /// Animation direction + direction: Option, + /// Play frames starting at the current frame instead of the beginning + fromcurrent: Option, +} + +impl AnimationOptions { + pub fn new() -> Self { + Default::default() + } +} + +/// Frame animation settings +#[serde_with::skip_serializing_none] +#[derive(Serialize, Clone, Debug, FieldSetter)] +pub struct FrameSettings { + /// The duration in milliseconds of each frame + duration: Option, + /// Redraw the plot at completion of the transition + redraw: Option, +} + +impl FrameSettings { + pub fn new() -> Self { + Default::default() + } +} + +/// Transition animation settings +#[serde_with::skip_serializing_none] +#[derive(Serialize, Clone, Debug, FieldSetter)] +pub struct TransitionSettings { + /// The duration of the transition, in milliseconds + duration: Option, + /// The easing function used for the transition + easing: Option, + /// Determines whether the figure's layout or traces smoothly transitions + ordering: Option, +} + +impl TransitionSettings { + pub fn new() -> Self { + Default::default() + } +} + +/// Animation modes +#[derive(Serialize, Debug, Clone, Copy, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum AnimationMode { + Immediate, + Next, + AfterAll, +} + +/// Animation directions +#[derive(Serialize, Debug, Clone, Copy, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum AnimationDirection { + Forward, + Reverse, +} + +/// Transition ordering options +#[derive(Serialize, Debug, Clone, Copy, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum TransitionOrdering { + #[serde(rename = "layout first")] + LayoutFirst, + #[serde(rename = "traces first")] + TracesFirst, +} + +/// Easing functions for animation transitions +#[derive(Serialize, Debug, Clone, Copy, PartialEq)] +#[serde(rename_all = "lowercase")] +pub enum AnimationEasing { + Linear, + Quad, + Cubic, + Sin, + Exp, + Circle, + Elastic, + Back, + Bounce, + #[serde(rename = "linear-in")] + LinearIn, + #[serde(rename = "quad-in")] + QuadIn, + #[serde(rename = "cubic-in")] + CubicIn, + #[serde(rename = "sin-in")] + SinIn, + #[serde(rename = "exp-in")] + ExpIn, + #[serde(rename = "circle-in")] + CircleIn, + #[serde(rename = "elastic-in")] + ElasticIn, + #[serde(rename = "back-in")] + BackIn, + #[serde(rename = "bounce-in")] + BounceIn, + #[serde(rename = "linear-out")] + LinearOut, + #[serde(rename = "quad-out")] + QuadOut, + #[serde(rename = "cubic-out")] + CubicOut, + #[serde(rename = "sin-out")] + SinOut, + #[serde(rename = "exp-out")] + ExpOut, + #[serde(rename = "circle-out")] + CircleOut, + #[serde(rename = "elastic-out")] + ElasticOut, + #[serde(rename = "back-out")] + BackOut, + #[serde(rename = "bounce-out")] + BounceOut, + #[serde(rename = "linear-in-out")] + LinearInOut, + #[serde(rename = "quad-in-out")] + QuadInOut, + #[serde(rename = "cubic-in-out")] + CubicInOut, + #[serde(rename = "sin-in-out")] + SinInOut, + #[serde(rename = "exp-in-out")] + ExpInOut, + #[serde(rename = "circle-in-out")] + CircleInOut, + #[serde(rename = "elastic-in-out")] + ElasticInOut, + #[serde(rename = "back-in-out")] + BackInOut, + #[serde(rename = "bounce-in-out")] + BounceInOut, +} + +#[cfg(test)] +mod tests { + use serde_json::{json, to_value}; + + use super::*; + use crate::Scatter; + + #[test] + fn serialize_animation_easing() { + let test_cases = [ + (AnimationEasing::Linear, "linear"), + (AnimationEasing::Cubic, "cubic"), + (AnimationEasing::CubicInOut, "cubic-in-out"), + (AnimationEasing::ElasticInOut, "elastic-in-out"), + ]; + + for (easing, expected) in test_cases { + assert_eq!( + to_value(easing).unwrap(), + json!(expected), + "Failed for {:?}", + easing + ); + } + } + + #[test] + fn serialize_animation_mode() { + let test_cases = [ + (AnimationMode::Immediate, "immediate"), + (AnimationMode::Next, "next"), + (AnimationMode::AfterAll, "afterall"), + ]; + + for (mode, expected) in test_cases { + assert_eq!( + to_value(mode).unwrap(), + json!(expected), + "Failed for {:?}", + mode + ); + } + } + + #[test] + fn serialize_animation_direction() { + let test_cases = [ + (AnimationDirection::Forward, "forward"), + (AnimationDirection::Reverse, "reverse"), + ]; + + for (direction, expected) in test_cases { + assert_eq!( + to_value(direction).unwrap(), + json!(expected), + "Failed for {:?}", + direction + ); + } + } + + #[test] + fn serialize_transition_ordering() { + let test_cases = [ + (TransitionOrdering::LayoutFirst, "layout first"), + (TransitionOrdering::TracesFirst, "traces first"), + ]; + + for (ordering, expected) in test_cases { + assert_eq!( + to_value(ordering).unwrap(), + json!(expected), + "Failed for {:?}", + ordering + ); + } + } + + #[test] + fn serialize_frame() { + let frame = Frame::new() + .name("test_frame") + .group("test_group") + .baseframe("base_frame"); + + let expected = json!({ + "name": "test_frame", + "group": "test_group", + "baseframe": "base_frame" + }); + + assert_eq!(to_value(frame).unwrap(), expected); + } + + #[test] + fn serialize_frame_with_data() { + let trace = Scatter::new(vec![1, 2, 3], vec![1, 2, 3]); + let mut traces = Traces::new(); + traces.push(trace); + + let frame = Frame::new().name("frame_with_data").data(traces); + + let expected = json!({ + "name": "frame_with_data", + "data": [ + { + "type": "scatter", + "x": [1, 2, 3], + "y": [1, 2, 3] + } + ] + }); + + assert_eq!(to_value(frame).unwrap(), expected); + } + + #[test] + fn serialize_animation() { + let test_cases = [ + ( + Animation::all_frames(), + json!(null), + "all frames should serialize to null", + ), + ( + Animation::pause(), + json!([null]), + "pause should serialize to [null]", + ), + ( + Animation::frames(vec!["frame1".to_string(), "frame2".to_string()]), + json!(["frame1", "frame2"]), + "specific frames should serialize to frame names array", + ), + ]; + + for (animation, expected_frames, description) in test_cases { + let json = to_value(animation).unwrap(); + assert_eq!(json[0], expected_frames, "{}", description); + assert!(json[1].is_object(), "Second element should be an object"); + } + } + + #[test] + fn serialize_animation_options_defaults() { + let options = AnimationOptions::new(); + assert_eq!(to_value(options).unwrap(), json!({})); + } + + #[test] + fn serialize_animation_options() { + let options = AnimationOptions::new() + .mode(AnimationMode::Immediate) + .direction(AnimationDirection::Forward) + .fromcurrent(false) + .frame(FrameSettings::new().duration(500).redraw(true)) + .transition( + TransitionSettings::new() + .duration(300) + .easing(AnimationEasing::CubicInOut) + .ordering(TransitionOrdering::LayoutFirst), + ); + + let expected = json!({ + "mode": "immediate", + "direction": "forward", + "fromcurrent": false, + "frame": { + "duration": 500, + "redraw": true + }, + "transition": { + "duration": 300, + "easing": "cubic-in-out", + "ordering": "layout first" + } + }); + + assert_eq!(to_value(options).unwrap(), expected); + } +} diff --git a/plotly/src/layout/mod.rs b/plotly/src/layout/mod.rs index a35d9626..0424b593 100644 --- a/plotly/src/layout/mod.rs +++ b/plotly/src/layout/mod.rs @@ -11,6 +11,7 @@ use crate::common::{Calendar, ColorScale, Font, Label, Orientation, Title}; pub mod themes; pub mod update_menu; +mod animation; mod annotation; mod axis; mod geo; @@ -24,6 +25,10 @@ mod shape; mod slider; // Re-export layout sub-module types +pub use self::animation::{ + Animation, AnimationDirection, AnimationEasing, AnimationMode, AnimationOptions, Frame, + FrameSettings, TransitionOrdering, TransitionSettings, +}; pub use self::annotation::{Annotation, ArrowSide, ClickToShow}; pub use self::axis::{ ArrayShow, Axis, AxisConstrain, AxisRange, AxisType, CategoryOrder, ColorAxis, @@ -59,6 +64,7 @@ pub enum ControlBuilderError { ValueSerializationError(String), InvalidRestyleObject(String), InvalidRelayoutObject(String), + AnimationSerializationError(String), } impl std::fmt::Display for ControlBuilderError { @@ -79,6 +85,9 @@ impl std::fmt::Display for ControlBuilderError { ControlBuilderError::InvalidRelayoutObject(s) => { write!(f, "Invalid relayout object: expected object but got {s}") } + ControlBuilderError::AnimationSerializationError(e) => { + write!(f, "Failed to serialize animation: {e}") + } } } } diff --git a/plotly/src/layout/slider.rs b/plotly/src/layout/slider.rs index bb5d3ef6..4ffd6af4 100644 --- a/plotly/src/layout/slider.rs +++ b/plotly/src/layout/slider.rs @@ -6,7 +6,7 @@ use serde_json::{Map, Value}; use crate::{ color::Color, common::{Anchor, Font, Pad}, - layout::ControlBuilderError, + layout::{Animation, ControlBuilderError}, private::NumOrString, Relayout, Restyle, }; @@ -90,11 +90,8 @@ impl SliderStep { /// Builder struct to create slider steps which can do restyles and/or relayouts #[derive(FieldSetter)] pub struct SliderStepBuilder { - #[field_setter(skip)] label: Option, - #[field_setter(skip)] name: Option, - #[field_setter(skip)] template_item_name: Option, visible: Option, #[field_setter(skip)] @@ -105,6 +102,9 @@ pub struct SliderStepBuilder { relayouts: Map, #[field_setter(skip)] error: Option, + /// Animation configuration + #[field_setter(skip)] + animation: Option, } impl SliderStepBuilder { @@ -112,21 +112,6 @@ impl SliderStepBuilder { Default::default() } - pub fn label>(mut self, label: S) -> Self { - self.label = Some(label.as_ref().to_string()); - self - } - - pub fn name>(mut self, name: S) -> Self { - self.name = Some(name.as_ref().to_string()); - self - } - - pub fn template_item_name>(mut self, template_item_name: S) -> Self { - self.template_item_name = Some(template_item_name.as_ref().to_string()); - self - } - pub fn push_restyle(mut self, restyle: impl Restyle) -> Self { if self.error.is_none() { if let Err(e) = self.try_push_restyle(restyle) { @@ -196,24 +181,37 @@ impl SliderStepBuilder { Ok(()) } - fn method_and_args( - restyles: Map, - relayouts: Map, - ) -> (SliderMethod, Value) { - match (restyles.is_empty(), relayouts.is_empty()) { - (true, true) => (SliderMethod::Skip, Value::Null), - (false, true) => (SliderMethod::Restyle, vec![restyles].into()), - (true, false) => (SliderMethod::Relayout, vec![relayouts].into()), - (false, false) => (SliderMethod::Update, vec![restyles, relayouts].into()), - } + /// Set the animation configuration for this slider step + pub fn animation(mut self, animation: Animation) -> Self { + self.animation = Some(animation); + self } - pub fn build(self) -> Result { if let Some(error) = self.error { return Err(error); } - let (method, args) = Self::method_and_args(self.restyles, self.relayouts); + let (method, args) = match ( + self.animation, + self.restyles.is_empty(), + self.relayouts.is_empty(), + ) { + // Animation takes precedence + (Some(animation), _, _) => ( + SliderMethod::Animate, + serde_json::to_value(animation) + .map_err(|e| ControlBuilderError::AnimationSerializationError(e.to_string()))?, + ), + // Regular restyle/relayout combinations + (None, true, true) => (SliderMethod::Skip, Value::Null), + (None, false, true) => (SliderMethod::Restyle, vec![self.restyles].into()), + (None, true, false) => (SliderMethod::Relayout, vec![self.relayouts].into()), + (None, false, false) => ( + SliderMethod::Update, + vec![self.restyles, self.relayouts].into(), + ), + }; + Ok(SliderStep { label: self.label, args: Some(args), @@ -420,16 +418,27 @@ mod tests { use serde_json::{json, to_value}; use super::*; - use crate::common::Anchor; - use crate::common::Visible; + use crate::common::{Anchor, Visible}; + use crate::layout::{Animation, AnimationMode, FrameSettings, TransitionSettings}; #[test] fn serialize_slider_method() { - assert_eq!(to_value(SliderMethod::Restyle).unwrap(), json!("restyle")); - assert_eq!(to_value(SliderMethod::Relayout).unwrap(), json!("relayout")); - assert_eq!(to_value(SliderMethod::Animate).unwrap(), json!("animate")); - assert_eq!(to_value(SliderMethod::Update).unwrap(), json!("update")); - assert_eq!(to_value(SliderMethod::Skip).unwrap(), json!("skip")); + let test_cases = [ + (SliderMethod::Restyle, "restyle"), + (SliderMethod::Relayout, "relayout"), + (SliderMethod::Animate, "animate"), + (SliderMethod::Update, "update"), + (SliderMethod::Skip, "skip"), + ]; + + for (method, expected) in test_cases { + assert_eq!( + to_value(method).unwrap(), + json!(expected), + "Failed for {:?}", + method + ); + } } #[test] @@ -544,34 +553,38 @@ mod tests { #[test] fn serialize_slider_current_value_x_anchor() { - assert_eq!( - to_value(SliderCurrentValueXAnchor::Left).unwrap(), - json!("left") - ); - assert_eq!( - to_value(SliderCurrentValueXAnchor::Center).unwrap(), - json!("center") - ); - assert_eq!( - to_value(SliderCurrentValueXAnchor::Right).unwrap(), - json!("right") - ); + let test_cases = [ + (SliderCurrentValueXAnchor::Left, "left"), + (SliderCurrentValueXAnchor::Center, "center"), + (SliderCurrentValueXAnchor::Right, "right"), + ]; + + for (anchor, expected) in test_cases { + assert_eq!( + to_value(&anchor).unwrap(), + json!(expected), + "Failed for {:?}", + anchor + ); + } } #[test] fn serialize_slider_transition_easing() { - assert_eq!( - to_value(SliderTransitionEasing::Linear).unwrap(), - json!("linear") - ); - assert_eq!( - to_value(SliderTransitionEasing::CubicInOut).unwrap(), - json!("cubic-in-out") - ); - assert_eq!( - to_value(SliderTransitionEasing::BounceIn).unwrap(), - json!("bounce-in") - ); + let test_cases = [ + (SliderTransitionEasing::Linear, "linear"), + (SliderTransitionEasing::CubicInOut, "cubic-in-out"), + (SliderTransitionEasing::BounceIn, "bounce-in"), + ]; + + for (easing, expected) in test_cases { + assert_eq!( + to_value(&easing).unwrap(), + json!(expected), + "Failed for {:?}", + easing + ); + } } #[test] @@ -665,13 +678,48 @@ mod tests { struct InvalidJsonObject; impl Relayout for InvalidJsonObject {} - let builder = SliderStepBuilder::new().push_relayout(InvalidJsonObject); - let err = builder.build().unwrap_err(); - match err { - ControlBuilderError::InvalidRelayoutObject(s) => { - assert!(s.contains("null")); - } + let result = SliderStepBuilder::new() + .label("Test") + .push_relayout(InvalidJsonObject) + .build(); + + assert!(result.is_err()); + match result.unwrap_err() { + ControlBuilderError::InvalidRelayoutObject(_) => {} _ => panic!("Expected InvalidRelayoutObject error"), } } + + #[test] + fn serialize_slider_step_builder_with_animation() { + let animation = Animation::frames(vec!["frame1".to_string()]).options( + crate::layout::AnimationOptions::new() + .mode(AnimationMode::Immediate) + .frame(FrameSettings::new().duration(300).redraw(false)) + .transition(TransitionSettings::new().duration(300)), + ); + + let slider_step = SliderStepBuilder::new() + .label("Animate to frame1") + .value("frame1") + .animation(animation) + .build() + .unwrap(); + + let expected = json!({ + "args": [ + ["frame1"], + { + "mode": "immediate", + "transition": {"duration": 300}, + "frame": {"duration": 300, "redraw": false} + } + ], + "method": "animate", + "label": "Animate to frame1", + "value": "frame1" + }); + + assert_eq!(to_value(slider_step).unwrap(), expected); + } } diff --git a/plotly/src/layout/update_menu.rs b/plotly/src/layout/update_menu.rs index 5fb9be08..5b794e7a 100644 --- a/plotly/src/layout/update_menu.rs +++ b/plotly/src/layout/update_menu.rs @@ -7,7 +7,7 @@ use serde_json::{Map, Value}; use crate::{ color::Color, common::{Anchor, Font, Pad}, - layout::ControlBuilderError, + layout::{Animation, ControlBuilderError}, Relayout, Restyle, }; @@ -92,11 +92,8 @@ impl Button { /// Builder struct to create buttons which can do restyles and/or relayouts #[derive(FieldSetter)] pub struct ButtonBuilder { - #[field_setter(skip)] label: Option, - #[field_setter(skip)] name: Option, - #[field_setter(skip)] template_item_name: Option, visible: Option, #[field_setter(default = "Map::new()")] @@ -105,6 +102,9 @@ pub struct ButtonBuilder { relayouts: Map, #[field_setter(skip)] error: Option, + // Animation configuration + #[field_setter(skip)] + animation: Option, } impl ButtonBuilder { @@ -112,21 +112,6 @@ impl ButtonBuilder { Default::default() } - pub fn label>(mut self, label: S) -> Self { - self.label = Some(label.as_ref().to_string()); - self - } - - pub fn name>(mut self, name: S) -> Self { - self.name = Some(name.as_ref().to_string()); - self - } - - pub fn template_item_name>(mut self, template_item_name: S) -> Self { - self.template_item_name = Some(template_item_name.as_ref().to_string()); - self - } - pub fn push_restyle(mut self, restyle: impl Restyle) -> Self { if self.error.is_none() { if let Err(e) = self.try_push_restyle(restyle) { @@ -172,16 +157,10 @@ impl ButtonBuilder { Ok(()) } - fn method_and_args( - restyles: Map, - relayouts: Map, - ) -> (ButtonMethod, Value) { - match (restyles.is_empty(), relayouts.is_empty()) { - (true, true) => (ButtonMethod::Skip, Value::Null), - (false, true) => (ButtonMethod::Restyle, vec![restyles].into()), - (true, false) => (ButtonMethod::Relayout, vec![relayouts].into()), - (false, false) => (ButtonMethod::Update, vec![restyles, relayouts].into()), - } + /// Sets the animation configuration for the button + pub fn animation(mut self, animation: Animation) -> Self { + self.animation = Some(animation); + self } pub fn build(self) -> Result { @@ -189,7 +168,27 @@ impl ButtonBuilder { return Err(error); } - let (method, args) = Self::method_and_args(self.restyles, self.relayouts); + let (method, args) = match ( + self.animation, + self.restyles.is_empty(), + self.relayouts.is_empty(), + ) { + // Animation takes precedence + (Some(animation), _, _) => { + let animation_args = serde_json::to_value(animation) + .map_err(|e| ControlBuilderError::AnimationSerializationError(e.to_string()))?; + (ButtonMethod::Animate, animation_args) + } + // Regular restyle/relayout combinations + (None, true, true) => (ButtonMethod::Skip, Value::Null), + (None, false, true) => (ButtonMethod::Restyle, vec![self.restyles].into()), + (None, true, false) => (ButtonMethod::Relayout, vec![self.relayouts].into()), + (None, false, false) => ( + ButtonMethod::Update, + vec![self.restyles, self.relayouts].into(), + ), + }; + Ok(Button { label: self.label, args: Some(args), @@ -454,4 +453,26 @@ mod tests { _ => panic!("Expected InvalidRelayoutObject error"), } } + + #[test] + fn serialize_animation_button_args() { + let animation = Animation::all_frames(); + + let button = ButtonBuilder::new() + .label("Animate") + .animation(animation) + .build() + .unwrap(); + + let args = button.args.unwrap(); + assert!(args.is_array(), "Animation button args must be an array"); + + // Verify the structure: [frameArg, options] + assert_eq!(args[0], json!(null)); // Should be null for all_frames + assert!( + args[1].is_object(), + "Second arg should be animation options object" + ); + assert_eq!(to_value(button.method.unwrap()).unwrap(), json!("animate")); + } } diff --git a/plotly/src/lib.rs b/plotly/src/lib.rs index 23290350..a06f04d5 100644 --- a/plotly/src/lib.rs +++ b/plotly/src/lib.rs @@ -56,11 +56,7 @@ pub mod traces; pub use common::color; pub use configuration::Configuration; pub use layout::Layout; -pub use plot::{Plot, Trace}; -#[cfg(feature = "kaleido")] -pub use plotly_kaleido::ImageFormat; -#[cfg(feature = "plotly_static")] -pub use plotly_static; +pub use plot::{Plot, Trace, Traces}; // Also provide easy access to modules which contain additional trace-specific types pub use traces::{ box_plot, contour, heat_map, histogram, image, mesh3d, sankey, scatter, scatter3d, @@ -75,6 +71,11 @@ pub use traces::{ pub trait Restyle: serde::Serialize {} pub trait Relayout {} +#[cfg(feature = "kaleido")] +pub use plotly_kaleido::ImageFormat; +#[cfg(feature = "plotly_static")] +pub use plotly_static::{self, ImageFormat}; + // Not public API. #[doc(hidden)] mod private; diff --git a/plotly/src/plot.rs b/plotly/src/plot.rs index 9a45f43e..130b75ea 100644 --- a/plotly/src/plot.rs +++ b/plotly/src/plot.rs @@ -1,3 +1,5 @@ +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; use std::{fs::File, io::Write, path::Path}; use askama::Template; @@ -9,11 +11,14 @@ use plotly_kaleido::ImageFormat; use plotly_static::ImageFormat; use rand::{ distr::{Alphanumeric, SampleString}, - rng, + rngs::SmallRng, + SeedableRng, }; use serde::Serialize; -use crate::{Configuration, Layout}; +use crate::{layout::Frame, Configuration, Layout}; + +static SEED_COUNTER: AtomicU64 = AtomicU64::new(0); #[derive(Template)] #[template(path = "plot.html", escape = "none")] @@ -158,6 +163,8 @@ pub struct Plot { layout: Layout, #[serde(rename = "config")] configuration: Configuration, + /// Animation frames + frames: Option>, #[serde(skip)] js_scripts: String, } @@ -219,6 +226,43 @@ impl Plot { &self.configuration } + /// Add a single frame to the animation sequence. + pub fn add_frame(&mut self, frame: Frame) -> &mut Self { + if self.frames.is_none() { + self.frames = Some(Vec::new()); + } + self.frames.as_mut().unwrap().push(frame); + self + } + + /// Add multiple frames to the animation sequence. + pub fn add_frames(&mut self, frames: &[Frame]) -> &mut Self { + if self.frames.is_none() { + self.frames = Some(frames.to_vec()); + } + self.frames.as_mut().unwrap().extend(frames.iter().cloned()); + self + } + + pub fn clear_frames(&mut self) -> &mut Self { + self.frames = None; + self + } + + pub fn frame_count(&self) -> usize { + self.frames.as_ref().map(|f| f.len()).unwrap_or(0) + } + + /// Get the animation frames as mutable reference + pub fn frames_mut(&mut self) -> Option<&mut Vec> { + self.frames.as_mut() + } + + /// Get the animation frames. + pub fn frames(&self) -> Option<&[Frame]> { + self.frames.as_deref() + } + /// Display the fully rendered HTML `Plot` in the default system browser. /// /// The HTML file is saved in a temp file, from which it is read and @@ -226,12 +270,12 @@ impl Plot { #[cfg(all(not(target_family = "wasm"), not(target_os = "android")))] pub fn show(&self) { use std::env; - let rendered = self.render(); // Set up the temp file with a unique filename. let mut temp = env::temp_dir(); - let mut plot_name = Alphanumeric.sample_string(&mut rng(), 22); + let mut plot_name = + Alphanumeric.sample_string(&mut SmallRng::seed_from_u64(Self::generate_seed()), 22); plot_name.push_str(".html"); plot_name = format!("plotly_{plot_name}"); temp.push(plot_name); @@ -274,7 +318,8 @@ 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 rng(), 22); + let mut plot_name = + Alphanumeric.sample_string(&mut SmallRng::seed_from_u64(Self::generate_seed()), 22); plot_name.push_str(".html"); plot_name = format!("plotly_{plot_name}"); temp.push(plot_name); @@ -332,13 +377,16 @@ 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 rng(), 20), + None => { + Alphanumeric.sample_string(&mut SmallRng::seed_from_u64(Self::generate_seed()), 20) + } }; self.render_inline(&plot_div_id) } fn to_jupyter_notebook_html(&self) -> String { - let plot_div_id = Alphanumeric.sample_string(&mut rng(), 20); + let plot_div_id = + Alphanumeric.sample_string(&mut SmallRng::seed_from_u64(Self::generate_seed()), 20); let tmpl = JupyterNotebookPlotTemplate { plot: self, @@ -825,11 +873,22 @@ impl Plot { #[cfg(target_os = "windows")] fn show_with_default_app(temp_path: &str) { use std::process::Command; - Command::new("cmd") - .args(&["/C", "start", &format!(r#"{}"#, temp_path)]) + Command::new("explorer") + .arg(temp_path) .spawn() .expect(DEFAULT_HTML_APP_NOT_FOUND); } + + /// Generate unique seeds for SmallRng such that file names and div names + /// are unique random for each call + pub(crate) fn generate_seed() -> u64 { + let time = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() as u64; + let counter = SEED_COUNTER.fetch_add(1, Ordering::Relaxed); + time ^ counter + } } impl PartialEq for Plot { @@ -901,6 +960,7 @@ mod tests { ], "layout": {}, "config": {}, + "frames": null, }); assert_eq!(to_value(plot).unwrap(), expected); @@ -927,6 +987,7 @@ mod tests { } }, "config": {}, + "frames": null, }); assert_eq!(to_value(plot).unwrap(), expected); diff --git a/plotly_derive/Cargo.toml b/plotly_derive/Cargo.toml index 306fac7f..159cc598 100644 --- a/plotly_derive/Cargo.toml +++ b/plotly_derive/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plotly_derive" -version = "0.13.1" +version = "0.13.5" description = "Internal proc macro crate for Plotly-rs." authors = ["Ioannis Giagkiozis "] license = "MIT" @@ -14,7 +14,7 @@ keywords = ["plot", "chart", "plotly"] quote = "1" syn = "2" proc-macro2 = "1" -darling = "0.20" +darling = "0.21" [lib] proc-macro = true diff --git a/plotly_kaleido/Cargo.toml b/plotly_kaleido/Cargo.toml index 002774b0..65fb87e7 100644 --- a/plotly_kaleido/Cargo.toml +++ b/plotly_kaleido/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plotly_kaleido" -version = "0.13.1" +version = "0.13.5" description = "Additional output format support for plotly using Kaleido" authors = [ "Ioannis Giagkiozis ", diff --git a/plotly_static/Cargo.toml b/plotly_static/Cargo.toml index 92a359fb..6b43502f 100644 --- a/plotly_static/Cargo.toml +++ b/plotly_static/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plotly_static" -version = "0.0.1" +version = "0.0.4" description = "Export Plotly graphs to static images using WebDriver" authors = ["Andrei Gherghescu andrei-ng@protonmail.com"] license = "MIT" @@ -25,21 +25,25 @@ serde = { version = "1.0", features = ["derive"] } rand = "0.9" serde_json = "1.0" base64 = "0.22" -fantoccini = "0.21" +fantoccini = "0.22" tokio = { version = "1", features = ["full"] } anyhow = "1.0" urlencoding = "2" -reqwest = { version = "0.11", features = ["blocking"] } +reqwest = { version = "0.12", features = ["blocking"] } [dev-dependencies] plotly_static = { path = "." } ndarray = { version = "0.16" } -env_logger = "0.10" +env_logger = "0.11" clap = { version = "4.0", features = ["derive"] } [build-dependencies] tokio = { version = "1", features = ["full"] } anyhow = "1.0" -dirs = "5.0" +dirs = "6.0" zip = "4.0" webdriver-downloader = "0.16" + +# Needed for docs.rs to build the documentation +[package.metadata.docs.rs] +features = ["chromedriver"] diff --git a/plotly_static/README.md b/plotly_static/README.md index 3fd15c7b..27eaa6e9 100644 --- a/plotly_static/README.md +++ b/plotly_static/README.md @@ -56,7 +56,7 @@ Add to your `Cargo.toml`: ```toml [dependencies] -plotly_static = { version = "0.0.1", features = ["chromedriver", "webdriver_download"] } +plotly_static = { version = "0.0.4", features = ["chromedriver", "webdriver_download"] } serde_json = "1.0" ``` @@ -151,8 +151,8 @@ Similar examples are available in the [Plotly.rs package](https://github.com/plo ## Documentation - [API Documentation](https://docs.rs/plotly_static/) -- [Static Image Export Guide](../../docs/book/src/fundamentals/static_image_export.md) +- [Static Image Export Guide](https://github.com/plotly/plotly.rs/tree/main/docs/book/src/fundamentals/static_image_export.md) ## License -This package is licensed under the MIT License. \ No newline at end of file +This package is licensed under the MIT License. diff --git a/plotly_static/examples/README.md b/plotly_static/examples/README.md index c10a2d85..959f62b1 100644 --- a/plotly_static/examples/README.md +++ b/plotly_static/examples/README.md @@ -8,17 +8,17 @@ This example demonstrates how to use the `plotly_static` crate with `clap` to cr Export a plot from a JSON file (using Chrome driver): ```bash -cargo run --example main --features chromedriver -- -i sample_plot.json -o my_plot -f png +cargo run --example generate_static --features chromedriver -- -i sample_plot.json -o my_plot -f png ``` Export a plot from a JSON file (using Firefox/Gecko driver): ```bash -cargo run --example main --features geckodriver -- -i sample_plot.json -o my_plot -f png +cargo run --example generate_static --features geckodriver -- -i sample_plot.json -o my_plot -f png ``` Export a plot from stdin: ```bash -cat sample_plot.json | cargo run --example main --features chromedriver -- -f svg -o output +cat sample_plot.json | cargo run --example generate_static --features chromedriver -- -f svg -o output ``` ### Web Driver Options @@ -31,10 +31,10 @@ The example supports two different web drivers for rendering plots: You must specify one of these features when running the example. For example: ```bash # Use Chrome driver -cargo run --example main --features chromedriver -- -i plot.json -o output.png +cargo run --example generate_static --features chromedriver -- -i plot.json -o output.png # Use Firefox driver -cargo run --example main --features geckodriver -- -i plot.json -o output.png +cargo run --example generate_static --features geckodriver -- -i plot.json -o output.png ``` ### Logging @@ -43,13 +43,13 @@ The example uses `env_logger` for logging. You can enable different log levels u ```bash # Enable info level logging -RUST_LOG=info cargo run --example main --features chromedriver -- -i sample_plot.json -o my_plot -f png +RUST_LOG=info cargo run --example generate_static --features chromedriver -- -i sample_plot.json -o my_plot -f png # Enable debug level logging for more verbose output -RUST_LOG=debug cargo run --example main --features geckodriver -- -i sample_plot.json -o my_plot -f png +RUST_LOG=debug cargo run --example generate_static --features geckodriver -- -i sample_plot.json -o my_plot -f png # Enable all logging levels -RUST_LOG=trace cargo run --example main --features chromedriver -- -i sample_plot.json -o my_plot -f png +RUST_LOG=trace cargo run --example generate_static --features chromedriver -- -i sample_plot.json -o my_plot -f png ``` ### Command Line Options @@ -66,18 +66,18 @@ RUST_LOG=trace cargo run --example main --features chromedriver -- -i sample_plo Export to PNG with custom dimensions: ```bash -cargo run --example main --features chromedriver -- -i sample_plot.json -o plot -f png --width 1200 --height 800 +cargo run --example generate_static --features chromedriver -- -i sample_plot.json -o plot -f png --width 1200 --height 800 ``` Export to SVG from stdin: ```bash echo '{"data":[{"type":"scatter","x":[1,2,3],"y":[4,5,6]}],"layout":{}}' | \ -cargo run --example main --features geckodriver -- -f svg -o scatter_plot +cargo run --example generate_static --features geckodriver -- -f svg -o scatter_plot ``` Export to PDF with high resolution: ```bash -cargo run --example main --features chromedriver -- -i sample_plot.json -o report -f pdf --width 1600 --height 1200 -s 2.0 +cargo run --example generate_static --features chromedriver -- -i sample_plot.json -o report -f pdf --width 1600 --height 1200 -s 2.0 ``` ### JSON Format diff --git a/plotly_static/src/lib.rs b/plotly_static/src/lib.rs index a2644703..f11c9432 100644 --- a/plotly_static/src/lib.rs +++ b/plotly_static/src/lib.rs @@ -74,7 +74,7 @@ //! //! ```toml //! [dependencies] -//! plotly_static = { version = "0.0.1", features = ["chromedriver", "webdriver_download"] } +//! plotly_static = { version = "0.0.4", features = ["chromedriver", "webdriver_download"] } //! ``` //! //! ## Advanced Usage