leaflet.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * Allows dragging a Leaflet map by the given amounts. A factor of 1 means the map
  3. * will be dragged the whole width of the map canvas in X direction and the whole
  4. * height of the map canvas in Y direction.
  5. *
  6. * ex: cy.get('#map-canvas').dragMapFromCenter({ xMoveFactor: 0.25, yMoveFactor: -0.5 })
  7. */
  8. Cypress.Commands.add(
  9. 'dragMapFromCenter',
  10. { prevSubject: 'element' },
  11. (element, { xMoveFactor, yMoveFactor }) => {
  12. // Get the raw HTML element from jQuery wrapper
  13. const canvas = element.get(0)
  14. const rect = canvas.getBoundingClientRect()
  15. const center = {
  16. x: rect.left + rect.width / 2,
  17. y: rect.top + rect.height / 2
  18. }
  19. // Start dragging from the center of the map
  20. cy.log('mousedown', {
  21. clientX: center.x,
  22. clientY: center.y
  23. })
  24. canvas.dispatchEvent(
  25. new MouseEvent('mousedown', {
  26. clientX: center.x,
  27. clientY: center.y
  28. })
  29. )
  30. // Let Leaflet know the mouse has started to move. The diff between
  31. // mousedown and mousemove event needs to be large enough so that Leaflet
  32. // will really think the mouse is moving and not that it was a click where
  33. // the mouse moved just a tiny amount.
  34. cy.log('mousemove', {
  35. clientX: center.x,
  36. clientY: center.y + 5
  37. })
  38. canvas.dispatchEvent(
  39. new MouseEvent('mousemove', {
  40. clientX: center.x,
  41. clientY: center.y + 5,
  42. bubbles: true
  43. })
  44. )
  45. // After Leaflet knows mouse is moving, we move the mouse as depicted by the options.
  46. cy.log('mousemove', {
  47. clientX: center.x + rect.width * xMoveFactor,
  48. clientY: center.y + rect.height * yMoveFactor
  49. })
  50. canvas.dispatchEvent(
  51. new MouseEvent('mousemove', {
  52. clientX: center.x + rect.width * xMoveFactor,
  53. clientY: center.y + rect.height * yMoveFactor,
  54. bubbles: true
  55. })
  56. )
  57. // Now when we "release" the mouse, Leaflet will fire a "dragend" event and
  58. // the search should register that the drag has stopped and run callbacks.
  59. cy.log('mouseup', {
  60. clientX: center.x + rect.width * xMoveFactor,
  61. clientY: center.y + rect.height * yMoveFactor
  62. })
  63. requestAnimationFrame(() => {
  64. canvas.dispatchEvent(
  65. new MouseEvent('mouseup', {
  66. clientX: center.x + rect.width * xMoveFactor,
  67. clientY: center.y + rect.height * yMoveFactor,
  68. bubbles: true
  69. })
  70. )
  71. })
  72. }
  73. )