Skip to content

Instantly share code, notes, and snippets.

@dralletje
Created June 21, 2018 23:48
Show Gist options
  • Save dralletje/3efc6e12a22e47338c734c4456ef111f to your computer and use it in GitHub Desktop.
Save dralletje/3efc6e12a22e47338c734c4456ef111f to your computer and use it in GitHub Desktop.
Voor Timon
import React from 'react';
/*
Simple component that will not render anything.
On mount it will bind to a document event, and it will clean up on unmount
<DocumentEvent
name="scroll"
handler={updateScrollPosition}
/>
*/
type T_documentevent_props = {
handler: (e: any) => mixed,
name: string,
passive?: boolean,
};
export class DocumentEvent extends React.Component<T_documentevent_props> {
unbind: () => void;
componentDidMount() {
let fn = (e) => {
if (!this.props.passive) e.preventDefault();
this.props.handler(e);
};
document.addEventListener(this.props.name, fn);
this.unbind = () => {
document.removeEventListener(this.props.name, fn);
};
}
componentWillUnmount() {
this.unbind();
}
render() {
return null;
}
}
class Draggable extends React.Component {
state = {
dragging_state: null,
};
// screen_position = null;
render() {
let { dragging_state } = this.state;
let { onMove, onMoveEnd, children } = this.props;
return (
<React.Fragment>
{dragging_state != null && (
<DocumentEvent
name="mousemove"
handler={(e) => {
if (dragging_state != null) {
onMove({
y: e.pageY - dragging_state.start_mouse_y,
x: e.pageX - dragging_state.start_mouse_x,
});
}
}}
/>
)}
{dragging_state != null && (
<DocumentEvent
name="mouseup"
handler={(e) => {
this.setState({ dragging_state: null });
onMoveEnd({
y: e.pageY - dragging_state.start_mouse_y,
x: e.pageX - dragging_state.start_mouse_x,
});
}}
/>
)}
<div
onMouseDown={(e) => {
this.setState({
dragging_state: {
start_mouse_x: e.pageX,
start_mouse_y: e.pageY,
},
});
}}
>
{children}
</div>
</React.Fragment>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment