Last active
February 13, 2021 16:26
-
-
Save prevwong/6bfd41dcd22a6701f15a4d5f8d095970 to your computer and use it in GitHub Desktop.
Craft-Cypress Commands
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DummyDataTransfer { | |
data = {}; | |
dropEffect = 'move'; | |
effectAllowed = 'all'; | |
files = []; | |
items = []; | |
types = []; | |
clearData(format) { | |
if (format) { | |
delete this.data[format]; | |
const index = this.types.indexOf(format); | |
delete this.types[index]; | |
delete this.data[index]; | |
} else { | |
this.data = {}; | |
} | |
} | |
setData(format, data) { | |
this.data[format] = data; | |
this.items.push(data); | |
this.types.push(format); | |
} | |
getData(format) { | |
if (format in this.data) { | |
return this.data[format]; | |
} | |
return ''; | |
} | |
setDragImage(img, xOffset, yOffset) {} | |
} | |
export const getCoordinatesFromPos = (dom, position) => { | |
const rect = dom.getBoundingClientRect(); | |
switch (position) { | |
case 'right': { | |
return { | |
x: rect.left + rect.width, | |
y: rect.top + rect.height / 2, | |
}; | |
} | |
case 'left': { | |
return { | |
x: rect.left, | |
y: rect.top + rect.height / 2, | |
}; | |
} | |
case 'top': { | |
return { | |
x: rect.left + rect.width / 2, | |
y: rect.top, | |
}; | |
} | |
case 'bottom': { | |
return { | |
x: rect.left + rect.width / 2, | |
y: rect.top + rect.height, | |
}; | |
} | |
case 'inside': { | |
return { | |
x: rect.left + 10, | |
y: rect.top + 10, | |
}; | |
} | |
default: { | |
return { | |
x: 0, | |
y: 0, | |
}; | |
} | |
} | |
}; | |
/** | |
Usage: cy.get('dragTarget').drop('dropTarget') | |
**/ | |
Cypress.Commands.add( | |
'drop', | |
{ | |
prevSubject: true, | |
}, | |
(subject, target, opts = {}) => { | |
const { position } = { | |
position: 'right', // 'left' | 'right' | 'top' | 'bottom' | 'inside' | |
...opts, | |
}; | |
cy.get(target).as('target'); | |
cy.get('@target').then(($target) => { | |
const [dom] = $target; | |
const { x, y } = getCoordinatesFromPos(dom, position); | |
const dataTransfer = new DummyDataTransfer(); | |
cy.get('@target').parent().as('parent'); | |
cy.get(subject).trigger('mousedown', { force: true }).trigger('dragstart', { | |
force: true, | |
dataTransfer, | |
}); | |
if (position === 'inside') { | |
cy.get('@target').trigger('dragenter', { | |
clientX: Math.floor(x), | |
clientY: Math.floor(y), | |
dataTransfer, | |
force: true, | |
}); | |
} else { | |
cy.get('@parent').trigger('dragenter', { | |
clientX: Math.floor(x), | |
clientY: Math.floor(y), | |
dataTransfer, | |
force: true, | |
}); | |
} | |
cy.get(subject).trigger('dragend', { force: true }); | |
}); | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment