Skip to content
Open
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: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
All notable changes to `dash` will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/).

## [UNRELEASED]

### Fixed
- [#4174](https://github.com/plotly/dash/pull/4174) Fix `dcc.Graph` discarding earlier layout changes when multiple `Plotly.relayout` calls run before React delivers the updated figure prop. Fixes [#4172](https://github.com/plotly/dash/issues/4172).

## [4.5.1] - 2026-11-19

### Removed
Expand Down
35 changes: 26 additions & 9 deletions components/dash-core-components/src/fragments/Graph.react.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
this._hasPlotted = false;
this._prevGd = null;
this._queue = Promise.resolve();
this._pendingFigures = [];

this.parentElement = React.createRef();

Expand Down Expand Up @@ -505,7 +506,12 @@
// copy and the figure prop (used as the base for Patch
// updates) would otherwise go stale.
if (eventData && gd.layout) {
const {figure = {}} = this.props;
// React may batch several relayouts before delivering props.
// Build on the latest sync rather than losing its changes.
const figure =
this._pendingFigures[this._pendingFigures.length - 1] ??

Check warning on line 512 in components/dash-core-components/src/fragments/Graph.react.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `.at(…)` over `[….length - index]`.

See more on https://sonarcloud.io/project/issues?id=plotly_dash&issues=AaIIaPjWzYQn1b-68ov4&open=AaIIaPjWzYQn1b-68ov4&pullRequest=4174
this.props.figure ??
{};
const updates = {};
for (const eventKey of Object.keys(eventData)) {
// 'xaxis.range[0]' -> 'xaxis', 'shapes[1].x0' -> 'shapes'
Expand All @@ -521,15 +527,15 @@
}
}
if (Object.keys(updates).length) {
setProps({
figure: {
...figure,
layout: {
...figure?.layout,
...updates,
},
const syncedFigure = {
...figure,
layout: {
...figure?.layout,
...updates,
},
});
};
this._pendingFigures.push(syncedFigure);
setProps({figure: syncedFigure});
}
}
});
Expand Down Expand Up @@ -571,13 +577,24 @@
UNSAFE_componentWillReceiveProps(nextProps) {
const idChanged = this.props.id !== nextProps.id;
if (idChanged) {
this._pendingFigures = [];
/*
* then the dom needs to get re-rendered with a new ID.
* the graph will get updated in componentDidUpdate
*/
return;
}

if (this.props.figure !== nextProps.figure) {
// An acknowledgement may skip batched figures or arrive before
// a later sync. An external figure supersedes all pending syncs.
const syncedIndex = this._pendingFigures.indexOf(nextProps.figure);
this._pendingFigures =
syncedIndex === -1
? []
: this._pendingFigures.slice(syncedIndex + 1);
}

let p = this._queue;

if (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import pytest
from dash import Dash, Input, Output, dcc, html


@pytest.mark.parametrize("nested", [False, True], ids=["consecutive", "nested"])
def test_grls001_consecutive_relayouts(dash_duo, nested):
app = Dash(__name__)
app.layout = html.Div(
[
html.Button("Replace figure", id="replace"),
dcc.Graph(
id="graph",
figure={
"data": [{"y": [-8, 3, 16, 5]}],
"layout": {"width": 600, "height": 400},
},
),
]
)

@app.callback(
Output("graph", "figure"),
Input("replace", "n_clicks"),
prevent_initial_call=True,
)
def replace(_):
return {
"data": [{"y": [10, 11, 12, 13]}],
"layout": {
"width": 600,
"height": 400,
"title": {"text": "Replacement"},
"yaxis": {"range": [9, 14]},
},
}

dash_duo.start_server(app)
dash_duo.wait_for_element("#graph .main-svg")
dash_duo.driver.execute_async_script(
"""
const nested = arguments[0];
const done = arguments[arguments.length - 1];
const gd = document.querySelector('#graph .js-plotly-plot');
if (nested) {
gd.once('plotly_relayout', () => {
Plotly.relayout(gd, {'xaxis.range': [0, 1]});
});
}
Plotly.relayout(gd, {'yaxis.range': [0, 5]});
if (!nested) {
Plotly.relayout(gd, {'xaxis.range': [0, 1]});
}
// Wait for the sync-triggered Plotly.react and subsequent frames.
gd.once('plotly_afterplot', () => {
requestAnimationFrame(() => requestAnimationFrame(done));
});
""",
nested,
)
ranges = dash_duo.driver.execute_script("""
const gd = document.querySelector('#graph .js-plotly-plot');
const figure = window.dash_component_api.getLayout('graph').props.figure;
return [gd._fullLayout.yaxis.range, gd._fullLayout.xaxis.range,
figure.layout.yaxis?.range, figure.layout.xaxis?.range];
""")
assert ranges == [[0, 5], [0, 1], [0, 5], [0, 1]]

dash_duo.find_element("#replace").click()
dash_duo.wait_for_text_to_equal("#graph .gtitle", "Replacement")
dash_duo.driver.execute_async_script("""
const done = arguments[arguments.length - 1];
const gd = document.querySelector('#graph .js-plotly-plot');
Plotly.relayout(gd, {'xaxis.range': [1, 2]});
gd.once('plotly_afterplot', () => {
requestAnimationFrame(() => requestAnimationFrame(done));
});
""")
figure = dash_duo.driver.execute_script(
"return window.dash_component_api.getLayout('graph').props.figure;"
)
assert figure["data"][0]["y"] == [10, 11, 12, 13]
assert figure["layout"]["title"]["text"] == "Replacement"
assert figure["layout"]["yaxis"]["range"] == [9, 14]
assert figure["layout"]["xaxis"]["range"] == [1, 2]
assert dash_duo.get_logs() == []
79 changes: 79 additions & 0 deletions components/dash-core-components/tests/unit/graph/relayout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import PlotlyGraph from '../../../src/fragments/Graph.react';

function setup() {
const figure = {
data: [{y: [1, 2, 3]}],
layout: {title: {text: 'original'}},
};
const props = {id: 'graph', figure, setProps: jest.fn()};
const graph = new PlotlyGraph(props);
const events: Record<string, (data: object) => void> = {};
const gd = {
layout: {...figure.layout} as Record<string, object>,
on: (name: string, handler: (data: object) => void) => {
events[name] = handler;
},
};
Object.assign(graph.gd, {current: gd});
graph.plot = jest.fn(() => Promise.resolve());
graph.amendTraces = jest.fn(promise => promise);
graph.bindEvents();
const relayout = (key: string, value: object) => {
gd.layout[key] = value;
events.plotly_relayout({[key]: value});
return props.setProps.mock.calls
.filter(([update]) => update.figure)
.pop()[0].figure;
};
const receive = (figure = graph.props.figure) => {
const nextProps = {...graph.props, figure};
// eslint-disable-next-line new-cap
graph.UNSAFE_componentWillReceiveProps(nextProps);
Object.assign(graph, {props: nextProps});
};
return {figure, graph, props, relayout, receive};
}

describe('relayout figure synchronization', () => {
it('keeps changes from consecutive events before props arrive', () => {
const {figure, relayout} = setup();
relayout('yaxis', {range: [0, 5]});
const synced = relayout('xaxis', {range: [0, 1]});
expect(synced.layout.yaxis.range).toEqual([0, 5]);
expect(synced.layout.xaxis.range).toEqual([0, 1]);
expect(synced.data).toBe(figure.data);
expect(figure.layout).toEqual({title: {text: 'original'}});
});

it('retains pending changes through unrelated prop updates', () => {
const {relayout, receive} = setup();
relayout('yaxis', {range: [0, 5]});
receive();
const synced = relayout('xaxis', {range: [0, 1]});
expect(synced.layout.yaxis.range).toEqual([0, 5]);
});

it('retains later changes when an earlier sync is acknowledged', () => {
const {relayout, receive} = setup();
const first = relayout('yaxis', {range: [0, 5]});
relayout('xaxis', {range: [0, 1]});
receive(first);
const synced = relayout('title', {text: 'updated'});
expect(synced.layout.yaxis.range).toEqual([0, 5]);
expect(synced.layout.xaxis.range).toEqual([0, 1]);
});

it('uses an external figure as the base for subsequent events', () => {
const {relayout, receive} = setup();
relayout('yaxis', {range: [0, 5]});
const external = {
data: [{y: [5, 4, 3]}],
layout: {title: {text: 'external'}},
};
receive(external);
const synced = relayout('xaxis', {range: [0, 1]});
expect(synced.data).toBe(external.data);
expect(synced.layout.title.text).toBe('external');
expect(synced.layout.yaxis).toBeUndefined();
});
});