diff --git a/draftlogs/8221_fix.md b/draftlogs/8221_fix.md new file mode 100644 index 00000000000..e45f4867809 --- /dev/null +++ b/draftlogs/8221_fix.md @@ -0,0 +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! diff --git a/src/components/dragelement/index.js b/src/components/dragelement/index.js index 16a75982f0c..cd1775511c9 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, 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; @@ -109,7 +113,18 @@ dragElement.init = function init(options) { var clampFn = options.clampFn || _clampFn; + let moveEvent; + let endEvent; + let touchId; + let button; + function onStart(e) { + const active = gd._activeDragElement; + if (active) { + 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 gd._dragged = false; @@ -149,22 +164,50 @@ dragElement.init = function init(options) { document.documentElement.style.cursor = window.getComputedStyle(element).cursor; } - document.addEventListener('mouseup', onDone); - document.addEventListener('touchend', onDone); + gd._activeDragElement = element; + 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); + 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; } + // 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; + 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) { + 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]; @@ -187,24 +230,41 @@ dragElement.init = function init(options) { return; } - function onDone(e) { - delete gd._dragdata; + function onCancel(e) { + if (getContact(e)) cancelDrag(false); + } - if(options.dragmode !== false) { - e.preventDefault(); - document.removeEventListener('mousemove', onMove); - document.removeEventListener('touchmove', onMove); - } + function cancelDrag(removed) { + const dragged = gd._dragged; + endDrag(); + gd._dragging = false; + gd._dragged = false; + gd._mouseDownTime = 0; + if (options.cancelFn) options.cancelFn(dragged, removed); + } - document.removeEventListener('mouseup', onDone); - document.removeEventListener('touchend', onDone); + function endDrag() { + delete element._cancelDrag; + delete element._lostEnd; + delete gd._activeDragElement; + delete gd._dragdata; + + 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; diff --git a/src/plots/cartesian/dragbox.js b/src/plots/cartesian/dragbox.js index 6f7c87a4576..58a5c7bc4df 100644 --- a/src/plots/cartesian/dragbox.js +++ b/src/plots/cartesian/dragbox.js @@ -83,6 +83,10 @@ 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; + // keys of the ranges that a preview reported + let previewKeys; + const previewSubplots = new Set(); // scaling factors from css transform var scaleX; var scaleY; @@ -183,6 +187,9 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { if(freeMode(dragModeNow)) dragOptions.minDrag = 1; else dragOptions.minDrag = undefined; + dragOptions.cancelFn = undefined; + panStart = undefined; + previewKeys = undefined; if(selectingOrDrawing(dragModeNow)) { dragOptions.xaxes = xaxes; dragOptions.yaxes = yaxes; @@ -204,10 +211,20 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { clearAndResetSelect(); } - if(!allFixedRanges) { + if (allFixedRanges || dragModeNow === false) { + dragOptions.moveFn = undefined; + dragOptions.doneFn = undefined; + } else { + previewKeys = new Set(); if(dragModeNow === 'zoom') { dragOptions.moveFn = zoomMove; dragOptions.doneFn = zoomDone; + dragOptions.cancelFn = (_, removed) => { + removeZoombox(gd); + const keys = previewKeys; + previewKeys = undefined; + if (!removed && keys?.size) afterTransition(() => emitFinalPreview(keys)); + }; // zoomMove takes care of the threshold, but we need to // minimize this so that constrained zoom boxes will flip @@ -218,6 +235,8 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { } else if(dragModeNow === 'pan') { dragOptions.moveFn = plotDrag; dragOptions.doneFn = dragTail; + dragOptions.cancelFn = cancelPan; + snapshotPan(); } } } @@ -225,18 +244,56 @@ 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 (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; @@ -245,6 +302,8 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { } function clickFn(numClicks, evt) { + panStart = undefined; + previewKeys = undefined; var gd = dragOptions.gd; if(gd._fullLayout._activeShapeIndex >= 0) { gd._fullLayout._deactivateShape(gd); @@ -426,7 +485,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; } @@ -558,7 +617,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; } @@ -591,9 +650,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; } @@ -616,7 +675,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]); @@ -655,7 +717,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; @@ -663,7 +725,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; @@ -687,9 +749,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) { @@ -855,10 +917,12 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { // dragTail - finish a drag event with a redraw function dragTail() { + panStart = 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` - 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. @@ -871,11 +935,43 @@ function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { ], gd); } + function cancelPan(_, removed) { + const snapshot = panStart; + const keys = previewKeys; + panStart = undefined; + previewKeys = undefined; + if (!removed && snapshot && keys?.size) afterTransition(() => restorePan(snapshot, keys)); + } + + 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(); + updateSubplots(); + 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, () => emitFinalPreview(keys)], 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; @@ -909,21 +1005,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]) { @@ -936,7 +1037,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 && ( @@ -947,7 +1048,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]) { @@ -960,7 +1064,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 && ( @@ -980,6 +1084,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; @@ -1011,6 +1117,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 @@ -1028,10 +1135,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/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/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/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/cartesian_interact_test.js b/test/jasmine/tests/cartesian_interact_test.js index c3817896b41..240e1b2ebc0 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,8 +65,81 @@ describe('zoom box element', function() { 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(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; @@ -216,6 +290,435 @@ describe('main plot pan', function() { .then(done, done.fail); }); + 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 [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}]; + 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'}], { + ...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 + }); + + 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); + 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); + }); + } + + 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]]); + }); + + 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, {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(); + const events = watchDragEvents(gd); + touchEvent('touchstart', 250, 250); + const transitioning = new Promise(resolve => gd.once('plotly_transitioning', resolve)); + const animation = animate(); + await transitioning; + touchEvent('touchmove', 315, 275); + touchEvent('touchcancel', 315, 275); + expect(gd._dragging).toBe(false); + + await animation; + expect(events.filter(([name]) => name === 'plotly_relayouting')).toEqual([]); + 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); + }); + + 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; + 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.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 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(view().point.x).toBeCloseTo(initial.point.x + 100); + await Plotly.relayout(gd, {'xaxis.fixedrange': true, 'yaxis.fixedrange': true}); + touchEvent(endEvent, 350, 250); + 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); + }); + } + + 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) { 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..ae9b8f7b17c 100644 --- a/test/jasmine/tests/dragelement_test.js +++ b/test/jasmine/tests/dragelement_test.js @@ -276,6 +276,149 @@ 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 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}); + 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); + 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); + 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(); + }); + + 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 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({ + 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() {