wix-style-react
Version:
66 lines (56 loc) • 2.11 kB
JavaScript
import { dataAttributes } from '../../DragAndDrop/Draggable/constants';
const getDraggableItemSelector = (dataHook, id) =>
dataHook
? `[data-hook="${dataHook}"]`
: `[${dataAttributes.id}="${id}"] [${dataAttributes.draggableSource}]`;
export const dragAndDropPuppeteerDriverFactory = ({ element }) => {
return {
beginDrag: async ({ dataHook, id }) => {
const selector = getDraggableItemSelector(dataHook, id);
await element.page.evaluate(
(baseElement, sourceSelector) => {
const sourceElement = baseElement.querySelector(sourceSelector);
const { x, y, height } = sourceElement.getBoundingClientRect();
sourceElement.dispatchEvent(
new MouseEvent('mousedown', {
bubbles: true,
clientX: x,
clientY: y + height / 2,
}),
);
},
element.element,
selector,
);
},
dragOver: async ({ dataHook, id, offset }) => {
const selector = getDraggableItemSelector(dataHook, id);
const moveMouseToNewPosition = () =>
element.page.evaluate(
(baseElement, destinationSelector, xAxisOffset) => {
const destinationElement =
baseElement.querySelector(destinationSelector);
const { x, y, height } = destinationElement.getBoundingClientRect();
const eventOptions = {
bubbles: true,
clientX: xAxisOffset ? x + xAxisOffset : x,
clientY: y + height / 2,
};
baseElement.dispatchEvent(
new MouseEvent('mousemove', eventOptions),
);
},
element.element,
selector,
offset?.x,
);
// We have to do it twice, because one mousemove event is not enough for item to occupy the new position
await moveMouseToNewPosition();
await moveMouseToNewPosition();
},
endDrag: () =>
element.page.evaluate(baseElement => {
baseElement.dispatchEvent(new MouseEvent('mouseup'));
}, element.element),
};
};