Skip to content

Instantly share code, notes, and snippets.

@MelleB
Last active September 8, 2016 08:46
Show Gist options
  • Save MelleB/f473cc24cd78d42d71433eb630e2f841 to your computer and use it in GitHub Desktop.
Save MelleB/f473cc24cd78d42d71433eb630e2f841 to your computer and use it in GitHub Desktop.
Choo drag behavior
const initialState = () => ({
dragging: false,
moveAction: null,
moveData: null,
releaseAction: null,
releaseData: null,
offsetX: 0,
offsetY: 0,
parentOffsetX: 0,
parentOffsetY: 0
})
const getLocalCoords = (data, state) => ({
x: Math.round(data.x - state.offsetX - state.parentOffsetX),
y: Math.round(data.y - state.offsetY - state.parentOffsetY)
})
export default {
namespace: 'drag',
state: initialState(),
reducers: {
start: (data, state) => ({ ...initialState(), ...data, dragging:true }),
stop: (data, state) => ({ ...state, ...data, dragging:false }),
},
effects: {
move: (data, state, send, done) => {
if ( ! state.dragging || ! state.moveAction) return state
send(state.moveAction, { ...state.moveData, ...getLocalCoords(data, state) }, done)
},
drop: (data, state, send, done) => {
if ( ! state.dragging) return state
send('drag:stop', data, done)
if (state.releaseAction) {
send(state.releaseAction, { ...state.releaseData, ...getLocalCoords(data, state) }, done)
}
}
},
subscriptions: [
(send, done) => {
document.addEventListener('mousemove', ev => {
send('drag:move', {x:ev.clientX, y:ev.clientY}, done)
})
document.addEventListener('mouseup', ev => {
ev.preventDefault(); ev.stopPropagation();
send('drag:drop', {x:ev.clientX, y:ev.clientY}, done)
})
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment