From 26c187e74823109be40a4a8fdb636da051b799c4 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:59:18 +0100 Subject: [PATCH 01/16] Discard cartesian pan and zoombox drags on touchcancel dragElement listened for touchend but not for touchcancel. When the browser cancelled a touch drag, the pan preview and the zoombox stayed on screen, and gd._dragdata kept the drag offset. A later redraw then replayed the drag, so the traces sat away from the axis ranges. dragElement now accepts a cancelFn. On touchcancel it ends the drag and calls cancelFn instead of doneFn or clickFn. The cartesian dragbox removes the zoombox, and after a pan it redraws from gd.layout, which still holds the ranges from before the drag. --- draftlogs/PRNUMBER_fix.md | 1 + src/components/dragelement/index.js | 23 +++++++- src/plots/cartesian/dragbox.js | 22 +++++++ test/jasmine/tests/cartesian_interact_test.js | 58 +++++++++++++++++++ test/jasmine/tests/dragelement_test.js | 43 ++++++++++++++ 5 files changed, 145 insertions(+), 2 deletions(-) create mode 100644 draftlogs/PRNUMBER_fix.md diff --git a/draftlogs/PRNUMBER_fix.md b/draftlogs/PRNUMBER_fix.md new file mode 100644 index 00000000000..eb8f1ef6fbd --- /dev/null +++ b/draftlogs/PRNUMBER_fix.md @@ -0,0 +1 @@ +- Fix cartesian pan and zoombox drags that the browser cancels with `touchcancel`, which left the plot translated away from its axes [[#PRNUMBER](https://github.com/plotly/plotly.js/pull/PRNUMBER)], with thanks to @dominikvrbic for the contribution! diff --git a/src/components/dragelement/index.js b/src/components/dragelement/index.js index 16a75982f0c..538adedc0f7 100644 --- a/src/components/dragelement/index.js +++ b/src/components/dragelement/index.js @@ -69,6 +69,10 @@ dragElement.unhoverRaw = unhover.raw; * Provide custom clamping function for small displacements. * By default, clamping is done using `minDrag` to x and y displacements * independently. + * cancelFn (optional) function(dragged) + * executed on touchcancel instead of doneFn and clickFn. + * dragged is true if the touch moved more than minDrag. + * Without cancelFn, touchcancel does not end the interaction. */ dragElement.init = function init(options) { var gd = options.gd; @@ -151,6 +155,7 @@ dragElement.init = function init(options) { document.addEventListener('mouseup', onDone); document.addEventListener('touchend', onDone); + if (options.cancelFn) document.addEventListener('touchcancel', onCancel); if(options.dragmode !== false) { e.preventDefault(); @@ -187,17 +192,22 @@ dragElement.init = function init(options) { return; } - function onDone(e) { + function onCancel(e) { + onDone(e, true); + } + + function onDone(e, cancelled) { delete gd._dragdata; if(options.dragmode !== false) { - e.preventDefault(); + if (!cancelled) e.preventDefault(); document.removeEventListener('mousemove', onMove); document.removeEventListener('touchmove', onMove); } document.removeEventListener('mouseup', onDone); document.removeEventListener('touchend', onDone); + document.removeEventListener('touchcancel', onCancel); if(hasHover) { removeElement(dragCover); @@ -212,6 +222,15 @@ dragElement.init = function init(options) { } gd._dragging = false; + if (cancelled) { + const dragged = gd._dragged; + gd._dragged = false; + // a cancelled touch must not start a double-click train + gd._mouseDownTime = 0; + options.cancelFn(dragged); + return; + } + // don't count as a dblClick unless the mouseUp is also within // the dblclick delay if((new Date()).getTime() - gd._mouseDownTime > doubleClickDelay) { diff --git a/src/plots/cartesian/dragbox.js b/src/plots/cartesian/dragbox.js index 6f7c87a4576..153e032e7cb 100644 --- a/src/plots/cartesian/dragbox.js +++ b/src/plots/cartesian/dragbox.js @@ -183,6 +183,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { if(freeMode(dragModeNow)) dragOptions.minDrag = 1; else dragOptions.minDrag = undefined; + dragOptions.cancelFn = undefined; if(selectingOrDrawing(dragModeNow)) { dragOptions.xaxes = xaxes; dragOptions.yaxes = yaxes; @@ -208,6 +209,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { if(dragModeNow === 'zoom') { dragOptions.moveFn = zoomMove; dragOptions.doneFn = zoomDone; + dragOptions.cancelFn = () => removeZoombox(gd); // zoomMove takes care of the threshold, but we need to // minimize this so that constrained zoom boxes will flip @@ -218,6 +220,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { } else if(dragModeNow === 'pan') { dragOptions.moveFn = plotDrag; dragOptions.doneFn = dragTail; + dragOptions.cancelFn = cancelPan; } } } @@ -871,6 +874,25 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { ], gd); } + // cancelPan - drop the pan preview and redraw from gd.layout, + // which still holds the ranges from before the drag + function cancelPan(dragged) { + if (!dragged) return; + + updateSubplots([0, 0, pw, ph]); + + Lib.syncOrAsync( + [ + Plots.previousPromises, + () => { + gd._fullLayout._replotting = false; + Registry.call('redraw', gd); + } + ], + gd + ); + } + // updateSubplots - find all plot viewboxes that should be // affected by this drag, and update them. look for all plots // sharing an affected axis (including the one being dragged), diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index c3817896b41..1ef6adf4d34 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -11,6 +11,7 @@ var constants = require('../../../src/plots/cartesian/constants'); var createGraphDiv = require('../assets/create_graph_div'); var destroyGraphDiv = require('../assets/destroy_graph_div'); var mouseEvent = require('../assets/mouse_event'); +var touchEvent = require('../assets/touch_event'); var selectButton = require('../assets/modebar_button'); var drag = require('../assets/drag'); @@ -64,6 +65,21 @@ describe('zoom box element', function() { expect(d3SelectAll('.zoomlayer > .zoombox-corners').size()) .toEqual(0); }); + + it('should be removed on touchcancel', function () { + const relayoutCallback = jasmine.createSpy('relayoutCallback'); + gd.on('plotly_relayout', relayoutCallback); + + touchEvent('touchstart', 100, 200); + touchEvent('touchmove', 150, 250); + expect(d3SelectAll('.zoomlayer > .zoombox').size()).toEqual(1); + + touchEvent('touchcancel', 150, 250); + expect(d3SelectAll('.zoomlayer > .zoombox').size()).toEqual(0); + expect(d3SelectAll('.zoomlayer > .zoombox-corners').size()).toEqual(0); + expect(gd._dragdata).toBeUndefined(); + expect(relayoutCallback).not.toHaveBeenCalled(); + }); }); describe('main plot pan', function() { @@ -216,6 +232,48 @@ describe('main plot pan', function() { .then(done, done.fail); }); + it('should discard the pan preview on touchcancel', function (done) { + const relayoutCallback = jasmine.createSpy('relayoutCallback'); + + // pixel offset of the point at (1, 1) from where the axes place it + function pointOffset() { + const svg = gd.querySelector('.main-svg').getBoundingClientRect(); + const pt = gd.querySelectorAll('.scatterlayer .point')[1].getBoundingClientRect(); + const xa = gd._fullLayout.xaxis; + const ya = gd._fullLayout.yaxis; + return [ + pt.left + pt.width / 2 - svg.left - (xa._offset + xa.c2p(1)), + pt.top + pt.height / 2 - svg.top - (ya._offset + ya.c2p(1)) + ]; + } + + Plotly.newPlot(gd, [{ x: [0, 1, 2], y: [0, 1, 2] }], { + xaxis: { range: [0, 2] }, + yaxis: { range: [0, 2] }, + width: 500, + height: 500, + margin: { l: 50, r: 50, t: 50, b: 50 }, + dragmode: 'pan' + }) + .then(() => { + gd.on('plotly_relayout', relayoutCallback); + return drag.makeFns({ pos0: [250, 250], posN: [350, 250], touch: true }).start(); + }) + .then(() => { + expect(gd._fullLayout.xaxis.range[0]).toBeLessThan(0); + touchEvent('touchcancel', 350, 250); + }) + .then(delay(100)) + .then(() => { + expect(relayoutCallback).not.toHaveBeenCalled(); + expect(gd._dragdata).toBeUndefined(); + expect(gd.layout.xaxis.range).toBeCloseToArray([0, 2]); + expect(gd._fullLayout.xaxis.range).toBeCloseToArray([0, 2]); + expect(pointOffset()).toBeCloseToArray([0, 0], 1); + }) + .then(done, done.fail); + }); + it('should show/hide `cliponaxis: false` pts according to range', function(done) { function _assert(markerDisplay, textDisplay, barTextDisplay) { var gd3 = d3Select(gd); diff --git a/test/jasmine/tests/dragelement_test.js b/test/jasmine/tests/dragelement_test.js index 9f1252e74cc..85f0a4ac0aa 100644 --- a/test/jasmine/tests/dragelement_test.js +++ b/test/jasmine/tests/dragelement_test.js @@ -276,6 +276,49 @@ describe('dragElement', function() { expect(moveCalls).toBe(0); }); + + it('should call cancelFn instead of doneFn on touchcancel after touchmove', function () { + const calls = []; + dragElement.init({ + element: this.element, + gd: this.gd, + moveFn: () => {}, + doneFn: () => calls.push('doneFn'), + clickFn: () => calls.push('clickFn'), + cancelFn: (dragged) => calls.push(`cancelFn ${dragged}`) + }); + + touchEvent('touchstart', this.x, this.y); + touchEvent('touchmove', this.x + 10, this.y + 10); + expect(this.gd._dragdata).toBeDefined(); + + touchEvent('touchcancel', this.x + 10, this.y + 10); + expect(calls).toEqual(['cancelFn true']); + expect(this.gd._dragdata).toBeUndefined(); + expect(this.gd._dragging).toBe(false); + expect(this.gd._dragged).toBe(false); + expect(countCoverSlip()).toEqual(0); + + touchEvent('touchend', this.x + 10, this.y + 10); + expect(calls).toEqual(['cancelFn true']); + }); + + it('should not count a cancelled touch as the first click of a double click', function () { + const calls = []; + dragElement.init({ + element: this.element, + gd: this.gd, + clickFn: (numClicks) => calls.push(`clickFn ${numClicks}`), + cancelFn: (dragged) => calls.push(`cancelFn ${dragged}`) + }); + + touchEvent('touchstart', this.x, this.y); + touchEvent('touchcancel', this.x, this.y); + touchEvent('touchstart', this.x, this.y); + touchEvent('touchend', this.x, this.y); + + expect(calls).toEqual(['cancelFn false', 'clickFn 1']); + }); }); describe('dragElement.getCursor', function() { From bb519569a7a9b486e8c18a6e1679fb71f735c1f3 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:00:35 +0100 Subject: [PATCH 02/16] Name the draftlog after PR 8221 --- draftlogs/{PRNUMBER_fix.md => 8221_fix.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename draftlogs/{PRNUMBER_fix.md => 8221_fix.md} (100%) diff --git a/draftlogs/PRNUMBER_fix.md b/draftlogs/8221_fix.md similarity index 100% rename from draftlogs/PRNUMBER_fix.md rename to draftlogs/8221_fix.md From b6f50be851889b0c8c2b979bdbe34ef5017f61a6 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:01:14 +0100 Subject: [PATCH 03/16] Use PR 8221 in the draftlog link --- draftlogs/8221_fix.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/draftlogs/8221_fix.md b/draftlogs/8221_fix.md index eb8f1ef6fbd..b04c67ec29b 100644 --- a/draftlogs/8221_fix.md +++ b/draftlogs/8221_fix.md @@ -1 +1 @@ -- Fix cartesian pan and zoombox drags that the browser cancels with `touchcancel`, which left the plot translated away from its axes [[#PRNUMBER](https://github.com/plotly/plotly.js/pull/PRNUMBER)], with thanks to @dominikvrbic for the contribution! +- Fix cartesian pan and zoombox drags that the browser cancels with `touchcancel`, which left the plot translated away from its axes [[#8221](https://github.com/plotly/plotly.js/pull/8221)], with thanks to @dominikvrbic for the contribution! From 5ee0a8054faf05f80952e634a140378482ed3d31 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:40:06 +0100 Subject: [PATCH 04/16] End a drag only when its input ends Cancel the active drag when its touch ends with touchcancel. Release the listeners even when a component has no cancel callback. --- src/components/dragelement/index.js | 86 +++++++++++++++++--------- test/jasmine/assets/touch_event.js | 2 +- test/jasmine/tests/dragelement_test.js | 42 ++++++++++++- 3 files changed, 98 insertions(+), 32 deletions(-) diff --git a/src/components/dragelement/index.js b/src/components/dragelement/index.js index 538adedc0f7..d2a335d7bab 100644 --- a/src/components/dragelement/index.js +++ b/src/components/dragelement/index.js @@ -69,10 +69,10 @@ dragElement.unhoverRaw = unhover.raw; * Provide custom clamping function for small displacements. * By default, clamping is done using `minDrag` to x and y displacements * independently. - * cancelFn (optional) function(dragged) - * executed on touchcancel instead of doneFn and clickFn. - * dragged is true if the touch moved more than minDrag. - * Without cancelFn, touchcancel does not end the interaction. + * cancelFn (optional) function(dragged, removed) + * runs after the browser cancels the touch or its target leaves the plot. + * dragged is true if the input moved more than minDrag. + * removed is true if Plotly removed the drag target. */ dragElement.init = function init(options) { var gd = options.gd; @@ -113,7 +113,16 @@ dragElement.init = function init(options) { var clampFn = options.clampFn || _clampFn; + let moveEvent; + let endEvent; + let touchId; + function onStart(e) { + const active = gd._activeDragElement; + if (active) { + if (gd.contains(active)) return; + active._cancelDrag(); + } // make dragging and dragged into properties of gd // so that others can look at and modify them gd._dragged = false; @@ -153,23 +162,38 @@ dragElement.init = function init(options) { document.documentElement.style.cursor = window.getComputedStyle(element).cursor; } - document.addEventListener('mouseup', onDone); - document.addEventListener('touchend', onDone); - if (options.cancelFn) document.addEventListener('touchcancel', onCancel); + gd._activeDragElement = element; + element._cancelDrag = () => cancelDrag(true); + + const touch = e.changedTouches && e.changedTouches[0]; + touchId = touch && touch.identifier; + moveEvent = touch ? 'touchmove' : 'mousemove'; + endEvent = touch ? 'touchend' : 'mouseup'; + if (touch) document.addEventListener('touchcancel', onCancel); + document.addEventListener(endEvent, onDone); if(options.dragmode !== false) { e.preventDefault(); - document.addEventListener('mousemove', onMove); - document.addEventListener('touchmove', onMove, {passive: false}); + document.addEventListener(moveEvent, onMove, {passive: false}); } return; } + function getContact(e) { + if (touchId == null) return e; + const contacts = e.changedTouches; + for (let i = 0; i < contacts.length; i++) { + if (contacts[i].identifier === touchId) return contacts[i]; + } + } + function onMove(e) { + const contact = getContact(e); + if (!contact) return; e.preventDefault(); - var offset = pointerOffset(e); + const offset = pointerOffset(contact); var minDrag = options.minDrag || constants.MINDRAG; var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); var dx = dxdy[0]; @@ -193,28 +217,39 @@ dragElement.init = function init(options) { } function onCancel(e) { - onDone(e, true); + if (getContact(e)) cancelDrag(false); } - function onDone(e, cancelled) { - delete gd._dragdata; + function cancelDrag(removed) { + const dragged = gd._dragged; + endDrag(); + gd._dragging = false; + gd._dragged = false; + gd._mouseDownTime = 0; + if (options.cancelFn) options.cancelFn(dragged, removed); + } - if(options.dragmode !== false) { - if (!cancelled) e.preventDefault(); - document.removeEventListener('mousemove', onMove); - document.removeEventListener('touchmove', onMove); - } + function endDrag() { + delete element._cancelDrag; + delete gd._activeDragElement; + delete gd._dragdata; - document.removeEventListener('mouseup', onDone); - document.removeEventListener('touchend', onDone); + document.removeEventListener(moveEvent, onMove); + document.removeEventListener(endEvent, onDone); document.removeEventListener('touchcancel', onCancel); if(hasHover) { removeElement(dragCover); - } else if(cursor) { + } else if(cursor != null) { dragCover.documentElement.style.cursor = cursor; cursor = null; } + } + + function onDone(e) { + if (!getContact(e)) return; + endDrag(); + if (options.dragmode !== false) e.preventDefault(); if(!gd._dragging) { gd._dragged = false; @@ -222,15 +257,6 @@ dragElement.init = function init(options) { } gd._dragging = false; - if (cancelled) { - const dragged = gd._dragged; - gd._dragged = false; - // a cancelled touch must not start a double-click train - gd._mouseDownTime = 0; - options.cancelFn(dragged); - return; - } - // don't count as a dblClick unless the mouseUp is also within // the dblclick delay if((new Date()).getTime() - gd._mouseDownTime > doubleClickDelay) { diff --git a/test/jasmine/assets/touch_event.js b/test/jasmine/assets/touch_event.js index 05dcc3f414b..167b348b5f1 100644 --- a/test/jasmine/assets/touch_event.js +++ b/test/jasmine/assets/touch_event.js @@ -5,7 +5,7 @@ module.exports = function(type, x, y, opts) { var ev; var touchObj = new Touch({ - identifier: Date.now(), + identifier: opts && opts.identifier !== undefined ? opts.identifier : 1, target: el, clientX: x, clientY: y, diff --git a/test/jasmine/tests/dragelement_test.js b/test/jasmine/tests/dragelement_test.js index 85f0a4ac0aa..91afeb19c1a 100644 --- a/test/jasmine/tests/dragelement_test.js +++ b/test/jasmine/tests/dragelement_test.js @@ -32,7 +32,10 @@ describe('dragElement', function() { this.y = clientRect.top + clientRect.height / 2; }); - afterEach(destroyGraphDiv); + afterEach(function () { + this.gd._activeDragElement?._cancelDrag(); + destroyGraphDiv(); + }); function countCoverSlip() { return d3SelectAll('.dragcover').size(); @@ -303,6 +306,43 @@ describe('dragElement', function() { expect(calls).toEqual(['cancelFn true']); }); + it('should track the initiating contact until that contact ends', function () { + const move = jasmine.createSpy('move'); + const cancel = jasmine.createSpy('cancel'); + const done = jasmine.createSpy('done'); + dragElement.init({element: this.element, gd: this.gd, moveFn: move, cancelFn: cancel, doneFn: done}); + const event = (type, identifier, x) => touchEvent(type, this.x + x, this.y, {element: this.element, identifier}); + + event('touchstart', 1, 0); + event('touchmove', 1, 20); + event('touchstart', 2, 60); + event('touchmove', 2, 80); + event('touchcancel', 2, 80); + event('touchend', 2, 80); + mouseEvent('mouseup', this.x, this.y); + expect(this.gd._dragging).toBe(true); + expect(move.calls.allArgs()).toEqual([[20, 0]]); + expect(cancel).not.toHaveBeenCalled(); + expect(done).not.toHaveBeenCalled(); + + event('touchcancel', 1, 20); + expect(cancel.calls.allArgs()).toEqual([[true, false]]); + expect(this.gd._dragging).toBe(false); + }); + + it('should keep a mouse drag until mouseup when a touch is cancelled', function () { + const cancel = jasmine.createSpy('cancel'); + const done = jasmine.createSpy('done'); + dragElement.init({element: this.element, gd: this.gd, cancelFn: cancel, doneFn: done}); + mouseEvent('mousedown', this.x, this.y); + mouseEvent('mousemove', this.x + 20, this.y); + touchEvent('touchcancel', this.x, this.y); + expect(this.gd._dragging).toBe(true); + mouseEvent('mouseup', this.x, this.y); + expect(done).toHaveBeenCalledTimes(1); + expect(cancel).not.toHaveBeenCalled(); + }); + it('should not count a cancelled touch as the first click of a double click', function () { const calls = []; dragElement.init({ From 261e4d70d9ecaffa64208b47eb078a407b59daa4 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:43:53 +0100 Subject: [PATCH 05/16] Restore Cartesian touch previews inside the drag handler Keep preview ranges separate from input ranges. Restore the ranges and transforms on cancellation and report the original displayed ranges in the final preview event. --- src/plots/cartesian/dragbox.js | 174 ++++++--- src/plots/cartesian/index.js | 9 +- src/plots/cartesian/scale_zoom.js | 5 +- test/jasmine/tests/cartesian_interact_test.js | 369 +++++++++++++++--- 4 files changed, 459 insertions(+), 98 deletions(-) diff --git a/src/plots/cartesian/dragbox.js b/src/plots/cartesian/dragbox.js index 153e032e7cb..e4542d78895 100644 --- a/src/plots/cartesian/dragbox.js +++ b/src/plots/cartesian/dragbox.js @@ -83,6 +83,9 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { var hasScatterGl, hasSplom, hasSVG; // collected changes to be made to the plot by relayout at the end var updates; + let panStart; + let touchPreview; + const previewSubplots = new Set(); // scaling factors from css transform var scaleX; var scaleY; @@ -184,6 +187,8 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { else dragOptions.minDrag = undefined; dragOptions.cancelFn = undefined; + panStart = undefined; + touchPreview = undefined; if(selectingOrDrawing(dragModeNow)) { dragOptions.xaxes = xaxes; dragOptions.yaxes = yaxes; @@ -205,11 +210,27 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { clearAndResetSelect(); } - if(!allFixedRanges) { + if (allFixedRanges || dragModeNow === false) { + dragOptions.moveFn = undefined; + dragOptions.doneFn = undefined; + } else { + if (e.changedTouches) { + const ranges = {}; + for (const ax of Axes.list(gd, null, true)) { + ranges[ax._name + '.range[0]'] = ax.range[0]; + ranges[ax._name + '.range[1]'] = ax.range[1]; + } + touchPreview = {ranges, restored: undefined}; + } if(dragModeNow === 'zoom') { dragOptions.moveFn = zoomMove; dragOptions.doneFn = zoomDone; - dragOptions.cancelFn = () => removeZoombox(gd); + dragOptions.cancelFn = (_, removed) => { + removeZoombox(gd); + const restored = touchPreview && touchPreview.restored; + touchPreview = undefined; + if (!removed && restored) gd.emit('plotly_relayouting', restored); + }; // zoomMove takes care of the threshold, but we need to // minimize this so that constrained zoom boxes will flip @@ -221,6 +242,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { dragOptions.moveFn = plotDrag; dragOptions.doneFn = dragTail; dragOptions.cancelFn = cancelPan; + if (e.changedTouches) snapshotPan(); } } } @@ -228,18 +250,42 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { gd._fullLayout._redrag = function() { var dragDataNow = gd._dragdata; - if(dragDataNow && dragDataNow.element === dragger) { - var dragModeNow = gd._fullLayout.dragmode; - - if(!selectingOrDrawing(dragModeNow)) { - recomputeAxisLists(); - updateSubplots([0, 0, pw, ph]); - dragOptions.moveFn(dragDataNow.dx, dragDataNow.dy); - } + const move = dragOptions.moveFn; + if (dragDataNow && dragDataNow.element === dragger && (move === plotDrag || move === zoomMove)) { + recomputeAxisLists(); + scaleX = gd._fullLayout._invScaleX; + scaleY = gd._fullLayout._invScaleY; + if (panStart) snapshotPan(true); + updateSubplots(); + updates = {}; + if (!allFixedRanges) move(dragDataNow.dx, dragDataNow.dy); } }; }; + function snapshotPan(replaying) { + const axes = new Set([...xaxes, ...yaxes, ...links.xaxes, ...links.yaxes, + ...matches.xaxes, ...matches.yaxes]); + panStart = { + replayed: replaying, + axes: Array.from(axes, ax => ({ + ax, + range: (replaying && ax._r ? ax._r : ax.range).slice(), + inputRange: ax.range === ax._input.range ? ax._input.range : undefined + })) + }; + } + + function emitPreview() { + if (touchPreview) { + const restored = touchPreview.restored ||= {}; + for (const key of Object.keys(updates)) { + if (key in touchPreview.ranges) restored[key] = touchPreview.ranges[key]; + } + } + gd.emit('plotly_relayouting', updates); + } + function clearAndResetSelect() { // clear selection polygon cache (if any) dragOptions.plotinfo.selection = false; @@ -248,6 +294,8 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { } function clickFn(numClicks, evt) { + panStart = undefined; + touchPreview = undefined; var gd = dragOptions.gd; if(gd._fullLayout._activeShapeIndex >= 0) { gd._fullLayout._deactivateShape(gd); @@ -429,7 +477,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { updateZoombox(zb, corners, box, path0, dimmed, lum); computeZoomUpdates(); - gd.emit('plotly_relayouting', updates); + emitPreview(); dimmed = true; } @@ -561,7 +609,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { dx = dx * scaleX; dy = dy * scaleY; // If a transition is in progress, then disable any behavior: - if(gd._transitioningWithDuration) { + if (gd._transitioningWithDuration || allFixedRanges) { return; } @@ -594,9 +642,9 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { dragAxList(yaxes, dy); updateMatchedAxRange('y'); } - updateSubplots([spDx, spDy, pw, ph]); + updateSubplots([spDx, spDy, pw, ph], true); ticksAndAnnotations(); - gd.emit('plotly_relayouting', updates); + emitPreview(); return; } @@ -619,7 +667,10 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { // if l2r comes back false or undefined, it means we've dragged off // the end of valid ranges - so stop. - if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd; + if (newEnd !== false && newEnd !== undefined) { + if (axi.range === axi._input.range) axi.range = axi.range.slice(); + axi.range[end] = newEnd; + } } return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / (movedAx._rl[end] - movedAx._rl[otherEnd]); @@ -658,7 +709,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { // scale the other axis the same about its middle for(i = 0; i < xaxes.length; i++) { xaxes[i].range = xaxes[i]._r.slice(); - scaleZoom(xaxes[i], 1 - dy / ph); + scaleZoom(xaxes[i], 1 - dy / ph, undefined, false); } dx = dy * pw / ph; xStart = dx / 2; @@ -666,7 +717,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { if(matches.isSubplotConstrained || (!yActive && xActive.length === 1)) { for(i = 0; i < yaxes.length; i++) { yaxes[i].range = yaxes[i]._r.slice(); - scaleZoom(yaxes[i], 1 - dx / pw); + scaleZoom(yaxes[i], 1 - dx / pw, undefined, false); } dy = dx * ph / pw; yStart = dy / 2; @@ -690,9 +741,9 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { xSize = ySize * pw / ph; } } - updateSubplots([xStart, yStart, xSize, ySize]); + updateSubplots([xStart, yStart, xSize, ySize], true); ticksAndAnnotations(); - gd.emit('plotly_relayouting', updates); + emitPreview(); } function updateMatchedAxRange(axLetter, out) { @@ -858,10 +909,12 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { // dragTail - finish a drag event with a redraw function dragTail() { + panStart = undefined; + touchPreview = undefined; // put the subplot viewboxes back to default (Because we're going to) // be repositioning the data in the relayout. But DON'T call // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` - updateSubplots([0, 0, pw, ph]); + updateSubplots(); // since we may have been redrawing some things during the drag, we may have // accumulated MathJax promises - wait for them before we relayout. @@ -874,30 +927,52 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { ], gd); } - // cancelPan - drop the pan preview and redraw from gd.layout, - // which still holds the ranges from before the drag - function cancelPan(dragged) { - if (!dragged) return; + function cancelPan(_, removed) { + const snapshot = panStart; + const restored = touchPreview && touchPreview.restored; + panStart = undefined; + touchPreview = undefined; + if (removed || !snapshot || !restored) return; + + if (gd._transitioningWithDuration) { + gd.once('plotly_transitioned', () => finishPanCancel(restored)); + } else { + for (const {ax, range, inputRange} of snapshot.axes) { + const useInput = inputRange && inputRange[0] === range[0] && inputRange[1] === range[1]; + ax.range = useInput ? inputRange : range; + } + ticksAndAnnotations(); + finishPanCancel(restored, snapshot); + } + } - updateSubplots([0, 0, pw, ph]); + function finishPanCancel(restored, snapshot) { + const fullLayout = gd._fullLayout; + if (!fullLayout?._plots?.[plotinfo.id]) return; + if (!snapshot) { + recomputeAxisLists(); + ticksAndAnnotations(); + } - Lib.syncOrAsync( - [ - Plots.previousPromises, - () => { - gd._fullLayout._replotting = false; - Registry.call('redraw', gd); - } - ], - gd - ); + updateSubplots(); + if (hasSVG && (!snapshot || snapshot.replayed)) { + // An application update can draw SVG points with preview ranges. + Registry.subplotsRegistry.cartesian.plot(gd); + Plots.style(gd); + } + fullLayout._replotting = false; + Lib.syncOrAsync([ + Plots.previousPromises, + () => gd.emit('plotly_relayouting', restored) + ], gd); } // updateSubplots - find all plot viewboxes that should be // affected by this drag, and update them. look for all plots // sharing an affected axis (including the one being dragged), // includes also scattergl and splom logic. - function updateSubplots(viewBox) { + function updateSubplots(viewBox, previewPan) { + const reset = !viewBox; var fullLayout = gd._fullLayout; var plotinfos = fullLayout._plots; var subplots = fullLayout._subplots.cartesian; @@ -931,21 +1006,26 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { } if(hasSVG) { - var xScaleFactor = viewBox[2] / xa0._length; - var yScaleFactor = viewBox[3] / ya0._length; + const xScaleFactor = reset ? 1 : viewBox[2] / xa0._length; + const yScaleFactor = reset ? 1 : viewBox[3] / ya0._length; for(i = 0; i < subplots.length; i++) { sp = plotinfos[subplots[i]]; xa = sp.xaxis; ya = sp.yaxis; + if (reset && !previewSubplots.has(sp.id)) continue; + var editX2 = (editX || matches.isSubplotConstrained) && !xa.fixedrange && xaHash[xa._id]; var editY2 = (editY || matches.isSubplotConstrained) && !ya.fixedrange && yaHash[ya._id]; var xScaleFactor2, yScaleFactor2; var clipDx, clipDy; - if(editX2) { + if (reset) { + xScaleFactor2 = 1; + clipDx = 0; + } else if(editX2) { xScaleFactor2 = xScaleFactor; clipDx = ew || matches.isSubplotConstrained ? viewBox[0] : getShift(xa, xScaleFactor2); } else if(matches.xaHash[xa._id]) { @@ -958,7 +1038,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { getShift(xa, xScaleFactor2, {n: 'top', s: 'bottom'}[yActive]); } else { xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); - clipDx = scaleAndGetShift(xa, xScaleFactor2); + clipDx = scaleAndGetShift(xa, xScaleFactor2, !previewPan); } if(xScaleFactor2 > 1 && ( @@ -969,7 +1049,10 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { clipDx = 0; } - if(editY2) { + if (reset) { + yScaleFactor2 = 1; + clipDy = 0; + } else if(editY2) { yScaleFactor2 = yScaleFactor; clipDy = ns || matches.isSubplotConstrained ? viewBox[1] : getShift(ya, yScaleFactor2); } else if(matches.yaHash[ya._id]) { @@ -982,7 +1065,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { getShift(ya, yScaleFactor2, {e: 'right', w: 'left'}[xActive]); } else { yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); - clipDy = scaleAndGetShift(ya, yScaleFactor2); + clipDy = scaleAndGetShift(ya, yScaleFactor2, !previewPan); } if(yScaleFactor2 > 1 && ( @@ -1002,6 +1085,8 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { if(!xScaleFactor2) xScaleFactor2 = 1; if(!yScaleFactor2) yScaleFactor2 = 1; + if (!reset) previewSubplots.add(sp.id); + var plotDx = xa._offset - clipDx / xScaleFactor2; var plotDy = ya._offset - clipDy / yScaleFactor2; @@ -1033,6 +1118,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { sp.yScaleFactor = yScaleFactor2; } } + if (reset) previewSubplots.clear(); } // Find the appropriate scaling for this axis, if it's linked to the @@ -1050,10 +1136,10 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { return 0; } - function scaleAndGetShift(ax, scaleFactor) { + function scaleAndGetShift(ax, scaleFactor, updateInput) { if(scaleFactor) { ax.range = ax._r.slice(); - scaleZoom(ax, scaleFactor); + scaleZoom(ax, scaleFactor, undefined, updateInput); return getShift(ax, scaleFactor); } return 0; diff --git a/src/plots/cartesian/index.js b/src/plots/cartesian/index.js index e55a90b39e2..6b1865d0708 100644 --- a/src/plots/cartesian/index.js +++ b/src/plots/cartesian/index.js @@ -731,7 +731,14 @@ function purgeSubplotLayers(layers, fullLayout) { } function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll('g.' + subplotId).remove(); + const draggers = fullLayout._draggers.selectAll('g.' + subplotId); + draggers.selectAll('.drag').each(function() { + if (this._cancelDrag) { + this._cancelDrag(); + delete fullLayout._redrag; + } + }); + draggers.remove(); fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove(); } diff --git a/src/plots/cartesian/scale_zoom.js b/src/plots/cartesian/scale_zoom.js index cd08f4eed8b..3f156bc54c7 100644 --- a/src/plots/cartesian/scale_zoom.js +++ b/src/plots/cartesian/scale_zoom.js @@ -2,7 +2,7 @@ var FROM_BL = require('../../constants/alignment').FROM_BL; -module.exports = function scaleZoom(ax, factor, centerFraction) { +module.exports = function scaleZoom(ax, factor, centerFraction, updateInput = true) { if(centerFraction === undefined) { centerFraction = FROM_BL[ax.constraintoward || 'center']; } @@ -10,9 +10,10 @@ module.exports = function scaleZoom(ax, factor, centerFraction) { var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - ax.range = ax._input.range = [ + ax.range = [ ax.l2r(center + (rangeLinear[0] - center) * factor), ax.l2r(center + (rangeLinear[1] - center) * factor) ]; + if (updateInput) ax._input.range = ax.range; ax.setScale(); }; diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index 1ef6adf4d34..89baff1f39b 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -38,7 +38,10 @@ describe('zoom box element', function() { .then(done); }); - afterEach(destroyGraphDiv); + afterEach(function () { + gd._activeDragElement?._cancelDrag(); + destroyGraphDiv(); + }); it('should be appended to the zoom layer', function() { var x0 = 100; @@ -66,22 +69,80 @@ describe('zoom box element', function() { .toEqual(0); }); - it('should be removed on touchcancel', function () { - const relayoutCallback = jasmine.createSpy('relayoutCallback'); - gd.on('plotly_relayout', relayoutCallback); - - touchEvent('touchstart', 100, 200); - touchEvent('touchmove', 150, 250); - expect(d3SelectAll('.zoomlayer > .zoombox').size()).toEqual(1); - - touchEvent('touchcancel', 150, 250); - expect(d3SelectAll('.zoomlayer > .zoombox').size()).toEqual(0); - expect(d3SelectAll('.zoomlayer > .zoombox-corners').size()).toEqual(0); + it('should restore all preview ranges after it removes the zoom box', async function () { + await Plotly.react(gd, [{x: [0, 5, 10], y: [0, 5, 10]}], interactionLayout('zoom')); + const events = watchDragEvents(gd); + const point = getNodeCoords(gd.querySelector('.nsewdrag')); + const x = point.x; + const y = point.y; + const overlayAtPreview = []; + gd.on('plotly_relayouting', () => overlayAtPreview.push(!!gd.querySelector('.zoombox'))); + + touchEvent('touchstart', x, y); + touchEvent('touchmove', x + 70, y + 65); + touchEvent('touchmove', x, y + 90); + touchEvent('touchcancel', x, y + 90); + + expect(gd.querySelector('.zoombox-corners')).toBeNull(); expect(gd._dragdata).toBeUndefined(); - expect(relayoutCallback).not.toHaveBeenCalled(); + expect(overlayAtPreview).toEqual([true, true, false]); + expect(events).toEqual([ + ['plotly_relayouting', { + 'xaxis.range[0]': 5, 'xaxis.range[1]': 6.75, + 'yaxis.range[0]': 3.375, 'yaxis.range[1]': 5 + }], + ['plotly_relayouting', {'yaxis.range[0]': 2.75, 'yaxis.range[1]': 5}], + ['plotly_relayouting', originalPreview] + ]); + }); + + it('should keep empty in-motion zoom previews', async function () { + const layout = interactionLayout('zoom'); + layout.yaxis.scaleanchor = 'x'; + await Plotly.react(gd, [{x: [0, 5, 10], y: [0, 5, 10]}], layout); + const events = watchDragEvents(gd); + + touchEvent('touchstart', 250, 250); + touchEvent('touchmove', 252, 252); + touchEvent('touchmove', 300, 300); + touchEvent('touchcancel', 300, 300); + + expect(events).toEqual([ + ['plotly_relayouting', {}], + ['plotly_relayouting', { + 'xaxis.range[0]': 5, 'xaxis.range[1]': 6.25, + 'yaxis.range[0]': 3.75, 'yaxis.range[1]': 5 + }], + ['plotly_relayouting', originalPreview] + ]); }); }); +const originalPreview = { + 'xaxis.range[0]': 0, 'xaxis.range[1]': 10, + 'yaxis.range[0]': 0, 'yaxis.range[1]': 10 +}; + +function interactionLayout(dragmode) { + return { + dragmode, + xaxis: {range: [0, 10]}, + yaxis: {range: [0, 10]}, + width: 500, + height: 500, + margin: {l: 50, r: 50, t: 50, b: 50} + }; +} + +function watchDragEvents(gd) { + const events = []; + for (const name of ['plotly_relayouting', 'plotly_relayout', 'plotly_click', 'plotly_doubleclick', + 'plotly_beforeplot', 'plotly_afterplot', 'plotly_redraw']) { + gd.on(name, update => events.push([name, update])); + } + return events; +} + describe('main plot pan', function() { var gd, modeBar, relayoutCallback; @@ -89,7 +150,10 @@ describe('main plot pan', function() { gd = createGraphDiv(); }); - afterEach(destroyGraphDiv); + afterEach(function () { + gd._activeDragElement?._cancelDrag(); + destroyGraphDiv(); + }); it('should respond to pan interactions', function(done) { var mock = require('../../image/mocks/10.json'); @@ -232,46 +296,249 @@ describe('main plot pan', function() { .then(done, done.fail); }); - it('should discard the pan preview on touchcancel', function (done) { - const relayoutCallback = jasmine.createSpy('relayoutCallback'); - - // pixel offset of the point at (1, 1) from where the axes place it - function pointOffset() { - const svg = gd.querySelector('.main-svg').getBoundingClientRect(); - const pt = gd.querySelectorAll('.scatterlayer .point')[1].getBoundingClientRect(); - const xa = gd._fullLayout.xaxis; - const ya = gd._fullLayout.yaxis; - return [ - pt.left + pt.width / 2 - svg.left - (xa._offset + xa.c2p(1)), - pt.top + pt.height / 2 - svg.top - (ya._offset + ya.c2p(1)) - ]; + it('should restore the point positions before it emits the final pan preview', async function () { + await Plotly.newPlot(gd, [{x: [0, 5, 10], y: [0, 5, 10]}], interactionLayout('pan')); + const events = watchDragEvents(gd); + const point = gd.querySelectorAll('.scatterlayer .point')[1]; + const initial = getNodeCoords(point); + const pointAtPreview = []; + gd.on('plotly_relayouting', () => pointAtPreview.push(getNodeCoords(point))); + + touchEvent('touchstart', 250, 250); + touchEvent('touchmove', 300, 250); + touchEvent('touchmove', 350, 250); + expect(getNodeCoords(point).x).toBeCloseTo(initial.x + 100); + const restored = new Promise(resolve => gd.once('plotly_relayouting', resolve)); + touchEvent('touchcancel', 350, 250); + await restored; + + expect(gd._dragdata).toBeUndefined(); + expect(gd.layout.xaxis.range).toEqual([0, 10]); + expect(gd._fullLayout.xaxis.range).toEqual([0, 10]); + expect(pointAtPreview).toEqual([ + {x: initial.x + 50, y: initial.y}, + {x: initial.x + 100, y: initial.y}, + initial + ]); + expect(events).toEqual([ + ['plotly_relayouting', {...originalPreview, 'xaxis.range[0]': -1.25, 'xaxis.range[1]': 8.75}], + ['plotly_relayouting', {...originalPreview, 'xaxis.range[0]': -2.5, 'xaxis.range[1]': 7.5}], + ['plotly_relayouting', originalPreview] + ]); + }); + + for (const constrain of ['domain', 'range']) { + it('should restore an axis-end drag with constrain ' + constrain, async function () { + const layout = interactionLayout('pan'); + layout.yaxis.scaleanchor = 'x'; + layout.yaxis.constrain = constrain; + if (constrain === 'domain') layout.xaxis.range = [0, 20]; + await Plotly.newPlot(gd, [{x: [0, 5], y: [0, 5]}], layout); + const start = () => [gd.layout.xaxis, gd.layout.yaxis, gd._fullLayout.xaxis, gd._fullLayout.yaxis] + .map(ax => ax.range.slice()); + const initial = start(); + const beforeplot = jasmine.createSpy('beforeplot').and.returnValue(false); + gd.on('plotly_beforeplot', beforeplot); + const {x, y} = getNodeCoords(gd.querySelector('.edrag')); + touchEvent('touchstart', x, y); + touchEvent('touchmove', x + 40, y); + expect(start().slice(0, 2)).toEqual(initial.slice(0, 2)); + expect(start().slice(2)).not.toEqual(initial.slice(2)); + touchEvent('touchcancel', x + 40, y); + expect(start()).toEqual(initial); + expect(beforeplot).not.toHaveBeenCalled(); + }); + } + + for (const [name, update] of Object.entries({ + relayout: gd => Plotly.relayout(gd, {'xaxis.range': [1, 9]}), + react: gd => Plotly.react(gd, [{x: [2, 4, 8], y: [3, 5, 9], mode: 'markers'}], { + ...gd.layout, xaxis: {range: [1, 9]} + }), + resize: gd => { + gd.style.width = '560px'; + return Plotly.Plots.resize(gd); } + })) { + it(`should match an application ${name} without a pan`, async function () { + const data = [{x: [2, 5, 8], y: [2, 5, 8], mode: 'markers'}]; + const layout = interactionLayout('pan'); + if (name === 'resize') { + delete layout.width; + delete layout.height; + gd.style.width = '500px'; + gd.style.height = '500px'; + } + const draw = () => Plotly.newPlot(gd, Lib.extendDeep([], data), Lib.extendDeep({}, layout)); + const state = () => ({ + ranges: [gd._fullLayout.xaxis.range, gd._fullLayout.yaxis.range], + points: Array.from(gd.querySelectorAll('.scatterlayer .point'), point => getNodeCoords(point)), + width: gd._fullLayout.width + }); - Plotly.newPlot(gd, [{ x: [0, 1, 2], y: [0, 1, 2] }], { - xaxis: { range: [0, 2] }, - yaxis: { range: [0, 2] }, - width: 500, - height: 500, - margin: { l: 50, r: 50, t: 50, b: 50 }, - dragmode: 'pan' - }) - .then(() => { - gd.on('plotly_relayout', relayoutCallback); - return drag.makeFns({ pos0: [250, 250], posN: [350, 250], touch: true }).start(); - }) - .then(() => { - expect(gd._fullLayout.xaxis.range[0]).toBeLessThan(0); - touchEvent('touchcancel', 350, 250); - }) - .then(delay(100)) - .then(() => { - expect(relayoutCallback).not.toHaveBeenCalled(); + await draw(); + await update(gd); + const control = state(); + if (name === 'resize') gd.style.width = '500px'; + await draw(); + touchEvent('touchstart', 210, 210); + touchEvent('touchmove', 280, 250); + await update(gd); + const restored = new Promise(resolve => gd.once('plotly_relayouting', resolve)); + touchEvent('touchcancel', 280, 250); + expect(await restored).toEqual(originalPreview); + expect(state()).toEqual(control); + }); + } + + it('should restore marker positions after a trace animation ends', async function () { + const plot = () => Plotly.newPlot(gd, [{x: [2, 5, 8], y: [3, 5, 7], mode: 'markers'}], interactionLayout('pan')); + const animate = () => Plotly.animate(gd, {data: [{y: [2, 4, 6]}]}, { + transition: {duration: 100}, frame: {duration: 100, redraw: false} + }); + const points = () => Array.from(gd.querySelectorAll('.scatterlayer .point'), point => getNodeCoords(point)); + + await plot(); + await animate(); + const control = points(); + + await plot(); + touchEvent('touchstart', 250, 250); + touchEvent('touchmove', 315, 275); + const transitioning = new Promise(resolve => gd.once('plotly_transitioning', resolve)); + const animation = animate(); + await transitioning; + expect(gd._transitioningWithDuration).toBe(true); + const events = watchDragEvents(gd); + const restored = new Promise(resolve => gd.once('plotly_relayouting', resolve)); + touchEvent('touchcancel', 315, 275); + expect(gd._dragging).toBe(false); + expect(events).toEqual([]); + + await animation; + expect(await restored).toEqual(originalPreview); + expect(points()).toEqual(control); + expect(events).toEqual([['plotly_relayouting', originalPreview]]); + }); + + it('should commit the next pan after a legend drag and a pan were cancelled', async function () { + const layout = interactionLayout('pan'); + layout.showlegend = true; + layout.legend = {x: 0.8, y: 0.8}; + await Plotly.newPlot(gd, [{x: [0, 5, 10], y: [0, 5, 10]}], layout, {edits: {legendPosition: true}}); + const legend = gd.querySelector('g.legend'); + const {x, y} = getNodeCoords(legend); + const transform = legend.getAttribute('transform'); + const relayout = jasmine.createSpy('relayout'); + gd.on('plotly_relayout', relayout); + + touchEvent('touchstart', x, y, {element: legend}); + touchEvent('touchmove', x + 30, y + 30, {element: legend}); + expect(legend.getAttribute('transform')).not.toBe(transform); + touchEvent('touchcancel', x + 30, y + 30, {element: legend}); + expect(gd._dragging).toBe(false); + + touchEvent('touchstart', 250, 250); + touchEvent('touchmove', 300, 250); + touchEvent('touchcancel', 300, 250); + expect(relayout).not.toHaveBeenCalled(); + + const committed = new Promise(resolve => gd.once('plotly_relayout', resolve)); + touchEvent('touchstart', 250, 250); + touchEvent('touchmove', 330, 210); + touchEvent('touchend', 330, 210); + + expect(await committed).toEqual({ + 'xaxis.range[0]': -2, 'xaxis.range[1]': 8, + 'yaxis.range[0]': -1, 'yaxis.range[1]': 9 + }); + expect(gd.layout.legend).toEqual({x: 0.8, y: 0.8}); + expect(gd.layout.xaxis.range).toEqual([-2, 8]); + expect(gd.layout.yaxis.range).toEqual([-1, 9]); + }); + + for (const mode of ['pan', 'zoom']) { + it(`should release a ${mode} when react removes its subplot`, async function () { + const data = [ + {x: [0, 5, 10], y: [0, 5, 10]}, + {x: [0, 5, 10], y: [0, 5, 10], xaxis: 'x2', yaxis: 'y2'} + ]; + const layout = interactionLayout(mode); + await Plotly.newPlot(gd, data, { + ...layout, grid: {rows: 1, columns: 2, pattern: 'independent'}, + xaxis2: {range: [0, 10]}, yaxis2: {range: [0, 10]} + }); + const events = watchDragEvents(gd); + const {x, y} = getNodeCoords(gd.querySelector('.x2y2 .nsewdrag')); + mouseEvent('mousedown', x, y); + mouseEvent('mousemove', x + 35, y + 35); + expect(gd._dragdata).toBeDefined(); + let reactError; + await Plotly.react(gd, [data[0]], layout).catch(error => { reactError = error; }); + + expect(gd.querySelector('.x2y2 .nsewdrag')).toBeNull(); + expect(gd.querySelector('.zoombox')).toBeNull(); + expect(gd._dragging).toBe(false); + expect(gd._dragdata).toBeUndefined(); + events.length = 0; + mouseEvent('mousemove', x + 40, y + 40); + mouseEvent('mouseup', x + 40, y + 40); + expect(events).toEqual([]); + expect(reactError).toBeUndefined(); + }); + + for (const fixedrange of [false, true]) { + it(`should silently cancel an unmoved ${mode} with ${fixedrange ? 'fixed' : 'interactive'} axes`, async function () { + const layout = interactionLayout(mode); + layout.xaxis.fixedrange = fixedrange; + layout.yaxis.fixedrange = fixedrange; + await Plotly.newPlot(gd, [{x: [0, 5, 10], y: [0, 5, 10]}], layout); + const events = watchDragEvents(gd); + touchEvent('touchstart', 250, 250); + expect(gd._dragging).toBe(true); + touchEvent('touchcancel', 250, 250); + expect(gd._dragging).toBe(false); expect(gd._dragdata).toBeUndefined(); - expect(gd.layout.xaxis.range).toBeCloseToArray([0, 2]); - expect(gd._fullLayout.xaxis.range).toBeCloseToArray([0, 2]); - expect(pointOffset()).toBeCloseToArray([0, 0], 1); - }) - .then(done, done.fail); + expect(gd.querySelector('.zoombox')).toBeNull(); + expect(events).toEqual([]); + }); + } + } + + for (const endEvent of ['touchcancel', 'touchend']) { + it(`should reset the pan transform on ${endEvent} after axes become fixed`, async function () { + const data = [{x: [1, 5, 9], y: [1, 5, 9], mode: 'markers'}]; + await Plotly.newPlot(gd, data, interactionLayout('pan')); + const initial = getNodeCoords(gd.querySelector('.scatterlayer .point')); + touchEvent('touchstart', 250, 250); + touchEvent('touchmove', 350, 250); + expect(getNodeCoords(gd.querySelector('.scatterlayer .point')).x).toBeCloseTo(initial.x + 100); + await Plotly.relayout(gd, {'xaxis.fixedrange': true, 'yaxis.fixedrange': true}); + touchEvent(endEvent, 350, 250); + expect(getNodeCoords(gd.querySelector('.scatterlayer .point'))).toEqual(initial); + expect(gd.layout.xaxis.range).toEqual([0, 10]); + expect(gd.layout.yaxis.range).toEqual([0, 10]); + expect(gd._dragging).toBe(false); + }); + } + + it('should report the restored preview for inside ticks with autorange', async function () { + await Plotly.newPlot(gd, [{x: [0, 5], y: [0, 5]}], { + dragmode: 'pan', + xaxis: {autorange: true, ticklabelposition: 'inside'}, + yaxis: {autorange: true, ticklabelposition: 'inside'} + }); + const preview = jasmine.createSpy('preview'); + const committed = jasmine.createSpy('committed'); + gd.on('plotly_relayouting', preview); + gd.on('plotly_relayout', committed); + const initial = gd._fullLayout.xaxis.range.slice(); + touchEvent('touchstart', 200, 200); + touchEvent('touchmove', 250, 200); + touchEvent('touchcancel', 250, 200); + expect(preview.calls.count()).toBe(2); + expect(preview.calls.mostRecent().args[0]['xaxis.range[0]']).toBe(initial[0]); + expect(committed).not.toHaveBeenCalled(); }); it('should show/hide `cliponaxis: false` pts according to range', function(done) { From 1f57c0eddb6358cba8f29bea2496472fb075dafc Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:49:34 +0100 Subject: [PATCH 06/16] Keep an animated range when a pan is cancelled during the transition The transition rebuilds the axes from the layout. Report the ranges that it shows, not the ranges from before the pan. --- src/plots/cartesian/dragbox.js | 4 +++ test/jasmine/tests/cartesian_interact_test.js | 29 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/plots/cartesian/dragbox.js b/src/plots/cartesian/dragbox.js index e4542d78895..971df2c8f0e 100644 --- a/src/plots/cartesian/dragbox.js +++ b/src/plots/cartesian/dragbox.js @@ -950,8 +950,12 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { const fullLayout = gd._fullLayout; if (!fullLayout?._plots?.[plotinfo.id]) return; if (!snapshot) { + // The transition rebuilt the axes from the layout, which the preview did not change. recomputeAxisLists(); ticksAndAnnotations(); + for (const key of Object.keys(restored)) { + if (key in updates) restored[key] = updates[key]; + } } updateSubplots(); diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index 89baff1f39b..d1f9f7da111 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -421,6 +421,35 @@ describe('main plot pan', function() { expect(events).toEqual([['plotly_relayouting', originalPreview]]); }); + it('should keep the ranges of an axis animation that ends after the cancel', async function () { + const plot = () => Plotly.newPlot(gd, [{x: [2, 5, 8], y: [3, 5, 7], mode: 'markers'}], interactionLayout('pan')); + const animate = () => Plotly.animate(gd, {layout: {xaxis: {range: [2, 12]}}}, { + transition: {duration: 100}, frame: {duration: 100, redraw: false} + }); + const state = () => ({ + range: gd._fullLayout.xaxis.range.slice(), + points: Array.from(gd.querySelectorAll('.scatterlayer .point'), point => getNodeCoords(point)) + }); + + await plot(); + await animate(); + const control = state(); + + await plot(); + touchEvent('touchstart', 250, 250); + touchEvent('touchmove', 315, 275); + const transitioning = new Promise(resolve => gd.once('plotly_transitioning', resolve)); + const animation = animate(); + await transitioning; + const restored = new Promise(resolve => gd.once('plotly_relayouting', resolve)); + touchEvent('touchcancel', 315, 275); + + await animation; + expect(await restored).toEqual({...originalPreview, 'xaxis.range[0]': 2, 'xaxis.range[1]': 12}); + expect(state()).toEqual(control); + expect(gd.layout.xaxis.range).toEqual([2, 12]); + }); + it('should commit the next pan after a legend drag and a pan were cancelled', async function () { const layout = interactionLayout('pan'); layout.showlegend = true; From ebbf3c00ebb95cfb9df7c57d76941745e2f410da Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:49:45 +0100 Subject: [PATCH 07/16] Test that a plotly_beforeplot veto does not keep a cancelled pan The cancel restores the ranges, the points and the shapes without a plot call. --- test/jasmine/tests/cartesian_interact_test.js | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index d1f9f7da111..f1fbb8b1c44 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -350,6 +350,32 @@ describe('main plot pan', function() { }); } + it('should restore the pan when a plotly_beforeplot handler vetoes plots', async function () { + const layout = interactionLayout('pan'); + layout.shapes = [{type: 'rect', x0: 2, x1: 4, y0: 2, y1: 4}]; + await Plotly.newPlot(gd, [{x: [0, 5, 10], y: [0, 5, 10]}], layout); + const state = () => ({ + point: getNodeCoords(gd.querySelectorAll('.scatterlayer .point')[1]), + shape: gd.querySelector('.shapelayer path').getAttribute('d'), + ranges: [gd._fullLayout.xaxis.range.slice(), gd._fullLayout.yaxis.range.slice()] + }); + const initial = state(); + const beforeplot = jasmine.createSpy('beforeplot').and.returnValue(false); + gd.on('plotly_beforeplot', beforeplot); + const events = watchDragEvents(gd); + + touchEvent('touchstart', 250, 250); + touchEvent('touchmove', 320, 280); + expect(state()).not.toEqual(initial); + const restored = new Promise(resolve => gd.once('plotly_relayouting', resolve)); + touchEvent('touchcancel', 320, 280); + + expect(await restored).toEqual(originalPreview); + expect(state()).toEqual(initial); + expect(beforeplot).not.toHaveBeenCalled(); + expect(events.map(([name]) => name)).toEqual(['plotly_relayouting', 'plotly_relayouting']); + }); + for (const [name, update] of Object.entries({ relayout: gd => Plotly.relayout(gd, {'xaxis.range': [1, 9]}), react: gd => Plotly.react(gd, [{x: [2, 4, 8], y: [3, 5, 9], mode: 'markers'}], { From 3f65aa98d686cabd27fad79c4505d1e5dd5a7fa6 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:49:45 +0100 Subject: [PATCH 08/16] Release an active drag when a test removes its graph A failed spec can leave a drag active. Release it in destroyGraphDiv so that it does not affect the next spec in any suite. --- test/jasmine/assets/destroy_graph_div.js | 6 +++++- test/jasmine/tests/cartesian_interact_test.js | 10 ++-------- test/jasmine/tests/dragelement_test.js | 5 +---- 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/test/jasmine/assets/destroy_graph_div.js b/test/jasmine/assets/destroy_graph_div.js index a42669ac32e..ffd0c6f431d 100644 --- a/test/jasmine/assets/destroy_graph_div.js +++ b/test/jasmine/assets/destroy_graph_div.js @@ -4,6 +4,10 @@ module.exports = function destroyGraphDiv() { // remove both plain graphs and shadow DOM graph containers ['graph', 'shadowcontainer'].forEach(function(id) { var el = document.getElementById(id); - if(el) document.body.removeChild(el); + if(el) { + // release a drag that a failed spec left active, so it cannot affect the next spec + if(el._activeDragElement) el._activeDragElement._cancelDrag(); + document.body.removeChild(el); + } }); }; diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index f1fbb8b1c44..b890f35e3fe 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -38,10 +38,7 @@ describe('zoom box element', function() { .then(done); }); - afterEach(function () { - gd._activeDragElement?._cancelDrag(); - destroyGraphDiv(); - }); + afterEach(destroyGraphDiv); it('should be appended to the zoom layer', function() { var x0 = 100; @@ -150,10 +147,7 @@ describe('main plot pan', function() { gd = createGraphDiv(); }); - afterEach(function () { - gd._activeDragElement?._cancelDrag(); - destroyGraphDiv(); - }); + afterEach(destroyGraphDiv); it('should respond to pan interactions', function(done) { var mock = require('../../image/mocks/10.json'); diff --git a/test/jasmine/tests/dragelement_test.js b/test/jasmine/tests/dragelement_test.js index 91afeb19c1a..fa4222f0e7e 100644 --- a/test/jasmine/tests/dragelement_test.js +++ b/test/jasmine/tests/dragelement_test.js @@ -32,10 +32,7 @@ describe('dragElement', function() { this.y = clientRect.top + clientRect.height / 2; }); - afterEach(function () { - this.gd._activeDragElement?._cancelDrag(); - destroyGraphDiv(); - }); + afterEach(destroyGraphDiv); function countCoverSlip() { return d3SelectAll('.dragcover').size(); From 1d7b603a4ee0c06be53a63a6f0fd6984f3dd18e0 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:50:54 +0100 Subject: [PATCH 09/16] Add the other drag fixes to the draftlog --- draftlogs/8221_fix.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/draftlogs/8221_fix.md b/draftlogs/8221_fix.md index b04c67ec29b..fa0540c8fe2 100644 --- a/draftlogs/8221_fix.md +++ b/draftlogs/8221_fix.md @@ -1 +1,3 @@ - Fix cartesian pan and zoombox drags that the browser cancels with `touchcancel`, which left the plot translated away from its axes [[#8221](https://github.com/plotly/plotly.js/pull/8221)], with thanks to @dominikvrbic for the contribution! +- Fix a touch drag of a legend or another component that the browser cancels, which kept its listeners and changed the result of the next drag [[#8221](https://github.com/plotly/plotly.js/pull/8221)], with thanks to @dominikvrbic for the contribution! +- Fix a cartesian drag that stayed active after `Plotly.react` removed its subplot [[#8221](https://github.com/plotly/plotly.js/pull/8221)], with thanks to @dominikvrbic for the contribution! From e873512d55be75f55ca26617a50f4b209e25e211 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:57:11 +0100 Subject: [PATCH 10/16] Test that a cancelled axis pan restores its axis --- test/jasmine/tests/cartesian_interact_test.js | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index b890f35e3fe..d03c0641a87 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -344,6 +344,29 @@ describe('main plot pan', function() { }); } + for (const [dragger, dx, dy, axis] of [['ewdrag', 60, 0, 'xaxis'], ['nsdrag', 0, 60, 'yaxis']]) { + it(`should restore an axis pan on the ${dragger} dragger`, async function () { + await Plotly.newPlot(gd, [{x: [0, 5, 10], y: [0, 5, 10]}], interactionLayout('pan')); + const events = watchDragEvents(gd); + const point = gd.querySelectorAll('.scatterlayer .point')[1]; + const initial = getNodeCoords(point); + const {x, y} = getNodeCoords(gd.querySelector('.' + dragger)); + + touchEvent('touchstart', x, y); + touchEvent('touchmove', x + dx, y + dy); + expect(getNodeCoords(point)).not.toEqual(initial); + const restored = new Promise(resolve => gd.once('plotly_relayouting', resolve)); + touchEvent('touchcancel', x + dx, y + dy); + + const original = {[axis + '.range[0]']: 0, [axis + '.range[1]']: 10}; + expect(await restored).toEqual(original); + expect(getNodeCoords(point)).toEqual(initial); + expect(gd._fullLayout[axis].range).toEqual([0, 10]); + expect(events.length).toBe(2); + expect(events[1]).toEqual(['plotly_relayouting', original]); + }); + } + it('should restore the pan when a plotly_beforeplot handler vetoes plots', async function () { const layout = interactionLayout('pan'); layout.shapes = [{type: 'rect', x0: 2, x1: 4, y0: 2, y1: 4}]; From fd9d67bfb848d4ae0c4bfdd254d28f7a4489a420 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:07:38 +0100 Subject: [PATCH 11/16] Check the clip and plot transforms after axes become fixed during a pan The marker position alone does not show the translated clip path. --- test/jasmine/tests/cartesian_interact_test.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index d03c0641a87..dc649601f7b 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -581,13 +581,23 @@ describe('main plot pan', function() { it(`should reset the pan transform on ${endEvent} after axes become fixed`, async function () { const data = [{x: [1, 5, 9], y: [1, 5, 9], mode: 'markers'}]; await Plotly.newPlot(gd, data, interactionLayout('pan')); - const initial = getNodeCoords(gd.querySelector('.scatterlayer .point')); + const matrix = selector => { + const transform = gd.querySelector(selector).transform.baseVal.consolidate(); + const {a, b, c, d, e, f} = transform ? transform.matrix : {a: 1, b: 0, c: 0, d: 1, e: 0, f: 0}; + return [a, b, c, d, e, f]; + }; + const view = () => ({ + point: getNodeCoords(gd.querySelector('.scatterlayer .point')), + clip: matrix('.plotclip rect'), + plot: matrix('.overplot .xy') + }); + const initial = view(); touchEvent('touchstart', 250, 250); touchEvent('touchmove', 350, 250); - expect(getNodeCoords(gd.querySelector('.scatterlayer .point')).x).toBeCloseTo(initial.x + 100); + expect(view().point.x).toBeCloseTo(initial.point.x + 100); await Plotly.relayout(gd, {'xaxis.fixedrange': true, 'yaxis.fixedrange': true}); touchEvent(endEvent, 350, 250); - expect(getNodeCoords(gd.querySelector('.scatterlayer .point'))).toEqual(initial); + expect(view()).toEqual(initial); expect(gd.layout.xaxis.range).toEqual([0, 10]); expect(gd.layout.yaxis.range).toEqual([0, 10]); expect(gd._dragging).toBe(false); From 40247852d4dc855820ddeb4558bd4e51b5f1c130 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:32:12 +0100 Subject: [PATCH 12/16] Report the displayed ranges in the final preview after a cancel Pan and zoom use one path for the final plotly_relayouting. It runs after a transition ends and reports the ranges on the screen, also when an animation changed them during the drag. A drag without a nonempty preview emits no final event. --- src/plots/cartesian/dragbox.js | 91 +++++++++---------- test/jasmine/tests/cartesian_interact_test.js | 65 ++++++++++--- 2 files changed, 95 insertions(+), 61 deletions(-) diff --git a/src/plots/cartesian/dragbox.js b/src/plots/cartesian/dragbox.js index 971df2c8f0e..6a063790b60 100644 --- a/src/plots/cartesian/dragbox.js +++ b/src/plots/cartesian/dragbox.js @@ -84,7 +84,8 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { // collected changes to be made to the plot by relayout at the end var updates; let panStart; - let touchPreview; + // keys of the ranges that a touch preview reported + let previewKeys; const previewSubplots = new Set(); // scaling factors from css transform var scaleX; @@ -188,7 +189,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { dragOptions.cancelFn = undefined; panStart = undefined; - touchPreview = undefined; + previewKeys = undefined; if(selectingOrDrawing(dragModeNow)) { dragOptions.xaxes = xaxes; dragOptions.yaxes = yaxes; @@ -214,22 +215,15 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { dragOptions.moveFn = undefined; dragOptions.doneFn = undefined; } else { - if (e.changedTouches) { - const ranges = {}; - for (const ax of Axes.list(gd, null, true)) { - ranges[ax._name + '.range[0]'] = ax.range[0]; - ranges[ax._name + '.range[1]'] = ax.range[1]; - } - touchPreview = {ranges, restored: undefined}; - } + if (e.changedTouches) previewKeys = new Set(); if(dragModeNow === 'zoom') { dragOptions.moveFn = zoomMove; dragOptions.doneFn = zoomDone; dragOptions.cancelFn = (_, removed) => { removeZoombox(gd); - const restored = touchPreview && touchPreview.restored; - touchPreview = undefined; - if (!removed && restored) gd.emit('plotly_relayouting', restored); + const keys = previewKeys; + previewKeys = undefined; + if (!removed && keys?.size) afterTransition(() => emitFinalPreview(keys)); }; // zoomMove takes care of the threshold, but we need to @@ -277,15 +271,29 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { } function emitPreview() { - if (touchPreview) { - const restored = touchPreview.restored ||= {}; - for (const key of Object.keys(updates)) { - if (key in touchPreview.ranges) restored[key] = touchPreview.ranges[key]; - } - } + if (previewKeys) for (const key of Object.keys(updates)) previewKeys.add(key); gd.emit('plotly_relayouting', updates); } + // report the displayed ranges of every axis that a preview reported + function emitFinalPreview(keys) { + const fullLayout = gd._fullLayout; + const payload = {}; + for (const key of keys) { + const [name, end] = key.split('.range['); + if (fullLayout[name]) payload[key] = fullLayout[name].range[end[0]]; + } + gd.emit('plotly_relayouting', payload); + } + + function afterTransition(fn) { + const run = () => { + if (gd._fullLayout?._plots?.[plotinfo.id]) fn(); + }; + if (gd._transitioningWithDuration) gd.once('plotly_transitioned', run); + else run(); + } + function clearAndResetSelect() { // clear selection polygon cache (if any) dragOptions.plotinfo.selection = false; @@ -295,7 +303,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { function clickFn(numClicks, evt) { panStart = undefined; - touchPreview = undefined; + previewKeys = undefined; var gd = dragOptions.gd; if(gd._fullLayout._activeShapeIndex >= 0) { gd._fullLayout._deactivateShape(gd); @@ -910,7 +918,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { // dragTail - finish a drag event with a redraw function dragTail() { panStart = undefined; - touchPreview = undefined; + previewKeys = undefined; // put the subplot viewboxes back to default (Because we're going to) // be repositioning the data in the relayout. But DON'T call // ticksAndAnnotations again - it's unnecessary and would overwrite `updates` @@ -929,46 +937,33 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { function cancelPan(_, removed) { const snapshot = panStart; - const restored = touchPreview && touchPreview.restored; + const keys = previewKeys; panStart = undefined; - touchPreview = undefined; - if (removed || !snapshot || !restored) return; + previewKeys = undefined; + if (!removed && snapshot && keys?.size) afterTransition(() => restorePan(snapshot, keys)); + } - if (gd._transitioningWithDuration) { - gd.once('plotly_transitioned', () => finishPanCancel(restored)); + function restorePan(snapshot, keys) { + const fullLayout = gd._fullLayout; + // a transition rebuilds the axes from the layout, which the preview does not change + const rebuilt = snapshot.axes.some(({ax}) => fullLayout[ax._name] !== ax); + if (rebuilt) { + recomputeAxisLists(); } else { for (const {ax, range, inputRange} of snapshot.axes) { const useInput = inputRange && inputRange[0] === range[0] && inputRange[1] === range[1]; ax.range = useInput ? inputRange : range; } - ticksAndAnnotations(); - finishPanCancel(restored, snapshot); } - } - - function finishPanCancel(restored, snapshot) { - const fullLayout = gd._fullLayout; - if (!fullLayout?._plots?.[plotinfo.id]) return; - if (!snapshot) { - // The transition rebuilt the axes from the layout, which the preview did not change. - recomputeAxisLists(); - ticksAndAnnotations(); - for (const key of Object.keys(restored)) { - if (key in updates) restored[key] = updates[key]; - } - } - + ticksAndAnnotations(); updateSubplots(); - if (hasSVG && (!snapshot || snapshot.replayed)) { - // An application update can draw SVG points with preview ranges. + if (hasSVG && (rebuilt || snapshot.replayed)) { + // an update during the drag can draw SVG points with preview ranges Registry.subplotsRegistry.cartesian.plot(gd); Plots.style(gd); } fullLayout._replotting = false; - Lib.syncOrAsync([ - Plots.previousPromises, - () => gd.emit('plotly_relayouting', restored) - ], gd); + Lib.syncOrAsync([Plots.previousPromises, () => emitFinalPreview(keys)], gd); } // updateSubplots - find all plot viewboxes that should be diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index dc649601f7b..afd6751222f 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -429,7 +429,11 @@ describe('main plot pan', function() { await update(gd); const restored = new Promise(resolve => gd.once('plotly_relayouting', resolve)); touchEvent('touchcancel', 280, 250); - expect(await restored).toEqual(originalPreview); + const [xRange, yRange] = control.ranges; + expect(await restored).toEqual({ + 'xaxis.range[0]': xRange[0], 'xaxis.range[1]': xRange[1], + 'yaxis.range[0]': yRange[0], 'yaxis.range[1]': yRange[1] + }); expect(state()).toEqual(control); }); } @@ -464,33 +468,68 @@ describe('main plot pan', function() { expect(events).toEqual([['plotly_relayouting', originalPreview]]); }); - it('should keep the ranges of an axis animation that ends after the cancel', async function () { + for (const mode of ['pan', 'zoom']) { + for (const ended of [false, true]) { + it(`should report the animated ranges when a ${mode} is cancelled ${ended ? 'after' : 'during'} an axis animation`, async function () { + const plot = () => Plotly.newPlot(gd, [{x: [2, 5, 8], y: [3, 5, 7], mode: 'markers'}], interactionLayout(mode)); + const animate = () => Plotly.animate(gd, {layout: {xaxis: {range: [2, 12]}}}, { + transition: {duration: 100}, frame: {duration: 100, redraw: false} + }); + const state = () => ({ + range: gd._fullLayout.xaxis.range.slice(), + points: Array.from(gd.querySelectorAll('.scatterlayer .point'), point => getNodeCoords(point)) + }); + + await plot(); + await animate(); + const control = state(); + + await plot(); + touchEvent('touchstart', 250, 250); + touchEvent('touchmove', 315, 275); + const transitioning = new Promise(resolve => gd.once('plotly_transitioning', resolve)); + const animation = animate(); + await (ended ? animation : transitioning); + const order = []; + gd.on('plotly_transitioned', () => order.push('transitioned')); + gd.on('plotly_relayouting', () => order.push('relayouting')); + const final = new Promise(resolve => gd.once('plotly_relayouting', resolve)); + touchEvent('touchcancel', 315, 275); + expect(gd.querySelector('.zoombox')).toBeNull(); + + await animation; + expect(await final).toEqual({...originalPreview, 'xaxis.range[0]': 2, 'xaxis.range[1]': 12}); + expect(order).toEqual(ended ? ['relayouting'] : ['transitioned', 'relayouting']); + expect(state()).toEqual(control); + expect(gd.layout.xaxis.range).toEqual([2, 12]); + }); + } + } + + it('should emit no final preview when the pan moved only during a transition', async function () { const plot = () => Plotly.newPlot(gd, [{x: [2, 5, 8], y: [3, 5, 7], mode: 'markers'}], interactionLayout('pan')); - const animate = () => Plotly.animate(gd, {layout: {xaxis: {range: [2, 12]}}}, { + const animate = () => Plotly.animate(gd, {data: [{y: [2, 4, 6]}]}, { transition: {duration: 100}, frame: {duration: 100, redraw: false} }); - const state = () => ({ - range: gd._fullLayout.xaxis.range.slice(), - points: Array.from(gd.querySelectorAll('.scatterlayer .point'), point => getNodeCoords(point)) - }); + const points = () => Array.from(gd.querySelectorAll('.scatterlayer .point'), point => getNodeCoords(point)); await plot(); await animate(); - const control = state(); + const control = points(); await plot(); + const events = watchDragEvents(gd); touchEvent('touchstart', 250, 250); - touchEvent('touchmove', 315, 275); const transitioning = new Promise(resolve => gd.once('plotly_transitioning', resolve)); const animation = animate(); await transitioning; - const restored = new Promise(resolve => gd.once('plotly_relayouting', resolve)); + touchEvent('touchmove', 315, 275); touchEvent('touchcancel', 315, 275); + expect(gd._dragging).toBe(false); await animation; - expect(await restored).toEqual({...originalPreview, 'xaxis.range[0]': 2, 'xaxis.range[1]': 12}); - expect(state()).toEqual(control); - expect(gd.layout.xaxis.range).toEqual([2, 12]); + expect(events.filter(([name]) => name === 'plotly_relayouting')).toEqual([]); + expect(points()).toEqual(control); }); it('should commit the next pan after a legend drag and a pan were cancelled', async function () { From d76ab52df9eec74413bc3c26b6e9b24755b51f41 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:34:51 +0100 Subject: [PATCH 13/16] Replace a drag whose end event was lost A new press of the same mouse button, or a touch without the owning contact, cancels the active drag and starts a new one. The new drag measures from its own start. A Cartesian drag keeps its restore state for mouse input too, so that the cancel restores its preview. --- src/components/dragelement/index.js | 18 +++++-- src/plots/cartesian/dragbox.js | 6 +-- test/jasmine/tests/cartesian_interact_test.js | 30 +++++++++++ test/jasmine/tests/dragelement_test.js | 53 ++++++++++++++++++- 4 files changed, 100 insertions(+), 7 deletions(-) diff --git a/src/components/dragelement/index.js b/src/components/dragelement/index.js index d2a335d7bab..3d10d80cee0 100644 --- a/src/components/dragelement/index.js +++ b/src/components/dragelement/index.js @@ -116,12 +116,14 @@ dragElement.init = function init(options) { let moveEvent; let endEvent; let touchId; + let button; function onStart(e) { const active = gd._activeDragElement; if (active) { - if (gd.contains(active)) return; - active._cancelDrag(); + const removed = !gd.contains(active); + if (!removed && !active._lostEnd(e)) return; + active._cancelDrag(removed); } // make dragging and dragged into properties of gd // so that others can look at and modify them @@ -163,10 +165,12 @@ dragElement.init = function init(options) { } gd._activeDragElement = element; - element._cancelDrag = () => cancelDrag(true); + element._cancelDrag = (removed = true) => cancelDrag(removed); + element._lostEnd = lostEnd; const touch = e.changedTouches && e.changedTouches[0]; touchId = touch && touch.identifier; + button = e.button; moveEvent = touch ? 'touchmove' : 'mousemove'; endEvent = touch ? 'touchend' : 'mouseup'; if (touch) document.addEventListener('touchcancel', onCancel); @@ -180,6 +184,13 @@ dragElement.init = function init(options) { return; } + // A new press of the same mouse button, or a touch list without the owning contact, + // shows that the browser did not deliver the end of this drag. + function lostEnd(e) { + if (touchId == null) return !e.changedTouches && e.button === button; + return !!e.touches && !Array.from(e.touches).some(contact => contact.identifier === touchId); + } + function getContact(e) { if (touchId == null) return e; const contacts = e.changedTouches; @@ -231,6 +242,7 @@ dragElement.init = function init(options) { function endDrag() { delete element._cancelDrag; + delete element._lostEnd; delete gd._activeDragElement; delete gd._dragdata; diff --git a/src/plots/cartesian/dragbox.js b/src/plots/cartesian/dragbox.js index 6a063790b60..58a5c7bc4df 100644 --- a/src/plots/cartesian/dragbox.js +++ b/src/plots/cartesian/dragbox.js @@ -84,7 +84,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { // collected changes to be made to the plot by relayout at the end var updates; let panStart; - // keys of the ranges that a touch preview reported + // keys of the ranges that a preview reported let previewKeys; const previewSubplots = new Set(); // scaling factors from css transform @@ -215,7 +215,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { dragOptions.moveFn = undefined; dragOptions.doneFn = undefined; } else { - if (e.changedTouches) previewKeys = new Set(); + previewKeys = new Set(); if(dragModeNow === 'zoom') { dragOptions.moveFn = zoomMove; dragOptions.doneFn = zoomDone; @@ -236,7 +236,7 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { dragOptions.moveFn = plotDrag; dragOptions.doneFn = dragTail; dragOptions.cancelFn = cancelPan; - if (e.changedTouches) snapshotPan(); + snapshotPan(); } } } diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index afd6751222f..e763d1e37d7 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -532,6 +532,36 @@ describe('main plot pan', function() { expect(points()).toEqual(control); }); + it('should start a new pan after the mouseup of a pan was lost', async function () { + const pan = async lost => { + await Plotly.newPlot(gd, [{x: [2, 5, 8], y: [3, 5, 7], mode: 'markers'}], interactionLayout('pan')); + const element = gd.querySelector('.nsewdrag'); + const events = watchDragEvents(gd); + if (lost) { + mouseEvent('mousedown', 180, 250, {element}); + mouseEvent('mousemove', 200, 250, {element}); + } + const committed = new Promise(resolve => gd.once('plotly_relayout', resolve)); + mouseEvent('mousedown', 260, 230, {element}); + mouseEvent('mousemove', 290, 250, {element}); + mouseEvent('mouseup', 290, 250, {element}); + await committed; + return { + events, + ranges: [gd.layout.xaxis.range, gd.layout.yaxis.range], + points: Array.from(gd.querySelectorAll('.scatterlayer .point'), point => getNodeCoords(point)) + }; + }; + + const control = await pan(false); + const result = await pan(true); + expect(result.ranges).toEqual(control.ranges); + expect(result.points).toEqual(control.points); + expect(result.events.slice(0, 2).map(([name]) => name)).toEqual(['plotly_relayouting', 'plotly_relayouting']); + expect(result.events[1][1]).toEqual(originalPreview); + expect(result.events.slice(2)).toEqual(control.events); + }); + it('should commit the next pan after a legend drag and a pan were cancelled', async function () { const layout = interactionLayout('pan'); layout.showlegend = true; diff --git a/test/jasmine/tests/dragelement_test.js b/test/jasmine/tests/dragelement_test.js index fa4222f0e7e..17defdfbd7d 100644 --- a/test/jasmine/tests/dragelement_test.js +++ b/test/jasmine/tests/dragelement_test.js @@ -309,10 +309,13 @@ describe('dragElement', function() { const done = jasmine.createSpy('done'); dragElement.init({element: this.element, gd: this.gd, moveFn: move, cancelFn: cancel, doneFn: done}); const event = (type, identifier, x) => touchEvent(type, this.x + x, this.y, {element: this.element, identifier}); + const contact = (identifier, x) => new Touch({identifier, target: this.element, clientX: this.x + x, clientY: this.y}); event('touchstart', 1, 0); event('touchmove', 1, 20); - event('touchstart', 2, 60); + touchEvent('touchstart', this.x + 60, this.y, { + element: this.element, identifier: 2, touches: [contact(1, 20), contact(2, 60)] + }); event('touchmove', 2, 80); event('touchcancel', 2, 80); event('touchend', 2, 80); @@ -340,6 +343,54 @@ describe('dragElement', function() { expect(cancel).not.toHaveBeenCalled(); }); + function recordDrag(test) { + const calls = []; + dragElement.init({ + element: test.element, + gd: test.gd, + moveFn: (dx, dy) => calls.push(['move', dx, dy]), + doneFn: () => calls.push(['done']), + cancelFn: (dragged, removed) => calls.push(['cancel', dragged, removed]) + }); + return calls; + } + + it('should replace a mouse drag whose mouseup was lost', function () { + const calls = recordDrag(this); + const opts = {element: this.element}; + mouseEvent('mousedown', this.x, this.y, opts); + mouseEvent('mousemove', this.x + 20, this.y, opts); + mouseEvent('mousedown', this.x + 40, this.y, opts); + mouseEvent('mousemove', this.x + 70, this.y + 20, opts); + mouseEvent('mouseup', this.x + 70, this.y + 20, opts); + expect(calls).toEqual([['move', 20, 0], ['cancel', true, false], ['move', 30, 20], ['done']]); + expect(this.gd._dragging).toBe(false); + }); + + it('should keep a mouse drag when another mouse button is pressed', function () { + const calls = recordDrag(this); + const opts = {element: this.element}; + mouseEvent('mousedown', this.x, this.y, opts); + mouseEvent('mousemove', this.x + 20, this.y, opts); + mouseEvent('mousedown', this.x + 40, this.y, {element: this.element, button: 2}); + mouseEvent('mousemove', this.x + 70, this.y, opts); + mouseEvent('mouseup', this.x + 70, this.y, opts); + expect(calls).toEqual([['move', 20, 0], ['move', 70, 0], ['done']]); + }); + + it('should replace a touch drag whose touchend was lost', function () { + const calls = recordDrag(this); + const event = (type, identifier, x, y) => touchEvent(type, this.x + x, this.y + y, {element: this.element, identifier}); + event('touchstart', 1, 0, 0); + event('touchmove', 1, 20, 0); + event('touchstart', 3, 40, 0); + event('touchmove', 1, 60, 0); + event('touchmove', 3, 70, 20); + event('touchend', 3, 70, 20); + expect(calls).toEqual([['move', 20, 0], ['cancel', true, false], ['move', 30, 20], ['done']]); + expect(this.gd._dragging).toBe(false); + }); + it('should not count a cancelled touch as the first click of a double click', function () { const calls = []; dragElement.init({ From 3df6b6585c31d643f378c443c97afbd3f0cfd021 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:36:57 +0100 Subject: [PATCH 14/16] End an active drag when Plotly.purge or Plotly.newPlot clears the plot Before, a legend drag kept its document listeners and drag cover after a purge, and the next touchmove threw an error. --- src/plots/plots.js | 3 +++ test/jasmine/tests/cartesian_interact_test.js | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/plots/plots.js b/src/plots/plots.js index 9b1247f8800..0f0219365ee 100644 --- a/src/plots/plots.js +++ b/src/plots/plots.js @@ -1441,6 +1441,9 @@ plots.purge = function(gd) { // note: we DO NOT remove _context because it doesn't change when we insert // a new plot, and may have been set outside of our scope. + // end an active drag so that its document listeners do not outlive the plot + if(gd._activeDragElement) gd._activeDragElement._cancelDrag(); + var fullLayout = gd._fullLayout || {}; if(fullLayout._glcontainer !== undefined) { fullLayout._glcontainer.selectAll('.gl-canvas').remove(); diff --git a/test/jasmine/tests/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index e763d1e37d7..240e1b2ebc0 100644 --- a/test/jasmine/tests/cartesian_interact_test.js +++ b/test/jasmine/tests/cartesian_interact_test.js @@ -562,6 +562,33 @@ describe('main plot pan', function() { expect(result.events.slice(2)).toEqual(control.events); }); + for (const target of ['legend', 'pan']) { + for (const input of ['touch', 'mouse']) { + it(`should release a ${input} ${target} drag when Plotly.purge runs`, async function () { + const layout = interactionLayout('pan'); + layout.showlegend = true; + layout.legend = {x: 0.8, y: 0.8}; + await Plotly.newPlot(gd, [{x: [0, 5, 10], y: [0, 5, 10]}], layout, {edits: {legendPosition: true}}); + const element = gd.querySelector(target === 'legend' ? 'g.legend' : '.nsewdrag'); + const {x, y} = getNodeCoords(element); + const send = input === 'touch' ? touchEvent : mouseEvent; + const [start, move, end] = input === 'touch' ? + ['touchstart', 'touchmove', 'touchend'] : ['mousedown', 'mousemove', 'mouseup']; + + send(start, x, y, {element}); + send(move, x + 30, y + 30, {element}); + expect(gd._activeDragElement).toBe(element); + Plotly.purge(gd); + + expect(gd._activeDragElement).toBeUndefined(); + expect(document.querySelector('.dragcover')).toBeNull(); + send(move, x + 60, y + 60, {element: document.body}); + send(end, x + 60, y + 60, {element: document.body}); + expect(gd._dragdata).toBeUndefined(); + }); + } + } + it('should commit the next pan after a legend drag and a pan were cancelled', async function () { const layout = interactionLayout('pan'); layout.showlegend = true; From 6a3e7927ec97dd75a544a4ed5c617bffb4f08c00 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:41:45 +0100 Subject: [PATCH 15/16] Add the purge fix to the draftlog --- draftlogs/8221_fix.md | 1 + 1 file changed, 1 insertion(+) diff --git a/draftlogs/8221_fix.md b/draftlogs/8221_fix.md index fa0540c8fe2..e45f4867809 100644 --- a/draftlogs/8221_fix.md +++ b/draftlogs/8221_fix.md @@ -1,3 +1,4 @@ - Fix cartesian pan and zoombox drags that the browser cancels with `touchcancel`, which left the plot translated away from its axes [[#8221](https://github.com/plotly/plotly.js/pull/8221)], with thanks to @dominikvrbic for the contribution! - Fix a touch drag of a legend or another component that the browser cancels, which kept its listeners and changed the result of the next drag [[#8221](https://github.com/plotly/plotly.js/pull/8221)], with thanks to @dominikvrbic for the contribution! - Fix a cartesian drag that stayed active after `Plotly.react` removed its subplot [[#8221](https://github.com/plotly/plotly.js/pull/8221)], with thanks to @dominikvrbic for the contribution! +- Fix a legend drag that kept its document listeners after `Plotly.purge` [[#8221](https://github.com/plotly/plotly.js/pull/8221)], with thanks to @dominikvrbic for the contribution! From 35ad3691f61ffe9c4067451f4209954bb13314e9 Mon Sep 17 00:00:00 2001 From: dominikvrbic <50887747+dominikvrbic@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:59:12 +0100 Subject: [PATCH 16/16] Start a new touch drag when a new contact reuses the identifier of the old one After a lost touchend, Chromium can give the next contact the same identifier. A touchstart that holds the owner identifier in changedTouches starts a new contact. --- src/components/dragelement/index.js | 9 ++++++--- test/jasmine/tests/dragelement_test.js | 12 ++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/components/dragelement/index.js b/src/components/dragelement/index.js index 3d10d80cee0..cd1775511c9 100644 --- a/src/components/dragelement/index.js +++ b/src/components/dragelement/index.js @@ -184,11 +184,14 @@ dragElement.init = function init(options) { return; } - // A new press of the same mouse button, or a touch list without the owning contact, - // shows that the browser did not deliver the end of this drag. + // A new press of the same mouse button, a touch list without the owning contact, + // or a new contact with the identifier of the owner shows that the browser did not + // deliver the end of this drag. A browser can reuse the identifier of an ended contact. function lostEnd(e) { if (touchId == null) return !e.changedTouches && e.button === button; - return !!e.touches && !Array.from(e.touches).some(contact => contact.identifier === touchId); + if (!e.touches) return false; + const hasOwner = contacts => Array.from(contacts).some(contact => contact.identifier === touchId); + return hasOwner(e.changedTouches) || !hasOwner(e.touches); } function getContact(e) { diff --git a/test/jasmine/tests/dragelement_test.js b/test/jasmine/tests/dragelement_test.js index 17defdfbd7d..ae9b8f7b17c 100644 --- a/test/jasmine/tests/dragelement_test.js +++ b/test/jasmine/tests/dragelement_test.js @@ -391,6 +391,18 @@ describe('dragElement', function() { expect(this.gd._dragging).toBe(false); }); + it('should replace a touch drag when a new contact reuses its identifier', function () { + const calls = recordDrag(this); + const event = (type, x, y) => touchEvent(type, this.x + x, this.y + y, {element: this.element, identifier: 0}); + event('touchstart', 0, 0); + event('touchmove', 20, 0); + event('touchstart', 40, 0); + event('touchmove', 70, 20); + event('touchend', 70, 20); + expect(calls).toEqual([['move', 20, 0], ['cancel', true, false], ['move', 30, 20], ['done']]); + expect(this.gd._dragging).toBe(false); + }); + it('should not count a cancelled touch as the first click of a double click', function () { const calls = []; dragElement.init({