Added logging, changed some directory structure

This commit is contained in:
2018-01-13 21:33:40 -05:00
parent f079a5f067
commit 8e72ffb917
73656 changed files with 35284 additions and 53718 deletions

View File

@@ -0,0 +1,359 @@
// @flow
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import {createCSSTransform, createSVGTransform} from './utils/domFns';
import {canDragX, canDragY, createDraggableData, getBoundPosition} from './utils/positionFns';
import {dontSetMe} from './utils/shims';
import DraggableCore from './DraggableCore';
import type {ControlPosition, DraggableBounds, DraggableCoreProps} from './DraggableCore';
import log from './utils/log';
import type {DraggableEventHandler} from './utils/types';
import type {Element as ReactElement} from 'react';
type DraggableState = {
dragging: boolean,
dragged: boolean,
x: number, y: number,
slackX: number, slackY: number,
isElementSVG: boolean
};
export type DraggableProps = {
...$Exact<DraggableCoreProps>,
axis: 'both' | 'x' | 'y' | 'none',
bounds: DraggableBounds | string | false,
defaultClassName: string,
defaultClassNameDragging: string,
defaultClassNameDragged: string,
defaultPosition: ControlPosition,
position: ControlPosition,
};
//
// Define <Draggable>
//
export default class Draggable extends React.Component<DraggableProps, DraggableState> {
static displayName = 'Draggable';
static propTypes = {
// Accepts all props <DraggableCore> accepts.
...DraggableCore.propTypes,
/**
* `axis` determines which axis the draggable can move.
*
* Note that all callbacks will still return data as normal. This only
* controls flushing to the DOM.
*
* 'both' allows movement horizontally and vertically.
* 'x' limits movement to horizontal axis.
* 'y' limits movement to vertical axis.
* 'none' limits all movement.
*
* Defaults to 'both'.
*/
axis: PropTypes.oneOf(['both', 'x', 'y', 'none']),
/**
* `bounds` determines the range of movement available to the element.
* Available values are:
*
* 'parent' restricts movement within the Draggable's parent node.
*
* Alternatively, pass an object with the following properties, all of which are optional:
*
* {left: LEFT_BOUND, right: RIGHT_BOUND, bottom: BOTTOM_BOUND, top: TOP_BOUND}
*
* All values are in px.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable bounds={{right: 300, bottom: 300}}>
* <div>Content</div>
* </Draggable>
* );
* }
* });
* ```
*/
bounds: PropTypes.oneOfType([
PropTypes.shape({
left: PropTypes.number,
right: PropTypes.number,
top: PropTypes.number,
bottom: PropTypes.number
}),
PropTypes.string,
PropTypes.oneOf([false])
]),
defaultClassName: PropTypes.string,
defaultClassNameDragging: PropTypes.string,
defaultClassNameDragged: PropTypes.string,
/**
* `defaultPosition` specifies the x and y that the dragged item should start at
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable defaultPosition={{x: 25, y: 25}}>
* <div>I start with transformX: 25px and transformY: 25px;</div>
* </Draggable>
* );
* }
* });
* ```
*/
defaultPosition: PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number
}),
/**
* `position`, if present, defines the current position of the element.
*
* This is similar to how form elements in React work - if no `position` is supplied, the component
* is uncontrolled.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable position={{x: 25, y: 25}}>
* <div>I start with transformX: 25px and transformY: 25px;</div>
* </Draggable>
* );
* }
* });
* ```
*/
position: PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number
}),
/**
* These properties should be defined on the child, not here.
*/
className: dontSetMe,
style: dontSetMe,
transform: dontSetMe
};
static defaultProps = {
...DraggableCore.defaultProps,
axis: 'both',
bounds: false,
defaultClassName: 'react-draggable',
defaultClassNameDragging: 'react-draggable-dragging',
defaultClassNameDragged: 'react-draggable-dragged',
defaultPosition: {x: 0, y: 0},
position: null
};
constructor(props: DraggableProps) {
super(props);
this.state = {
// Whether or not we are currently dragging.
dragging: false,
// Whether or not we have been dragged before.
dragged: false,
// Current transform x and y.
x: props.position ? props.position.x : props.defaultPosition.x,
y: props.position ? props.position.y : props.defaultPosition.y,
// Used for compensating for out-of-bounds drags
slackX: 0, slackY: 0,
// Can only determine if SVG after mounting
isElementSVG: false
};
}
componentWillMount() {
if (this.props.position && !(this.props.onDrag || this.props.onStop)) {
// eslint-disable-next-line
console.warn('A `position` was applied to this <Draggable>, without drag handlers. This will make this ' +
'component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the ' +
'`position` of this element.');
}
}
componentDidMount() {
// Check to see if the element passed is an instanceof SVGElement
if(typeof window.SVGElement !== 'undefined' && ReactDOM.findDOMNode(this) instanceof window.SVGElement) {
this.setState({ isElementSVG: true });
}
}
componentWillReceiveProps(nextProps: Object) {
// Set x/y if position has changed
if (nextProps.position &&
(!this.props.position ||
nextProps.position.x !== this.props.position.x ||
nextProps.position.y !== this.props.position.y
)
) {
this.setState({ x: nextProps.position.x, y: nextProps.position.y });
}
}
componentWillUnmount() {
this.setState({dragging: false}); // prevents invariant if unmounted while dragging
}
onDragStart: DraggableEventHandler = (e, coreData) => {
log('Draggable: onDragStart: %j', coreData);
// Short-circuit if user's callback killed it.
const shouldStart = this.props.onStart(e, createDraggableData(this, coreData));
// Kills start event on core as well, so move handlers are never bound.
if (shouldStart === false) return false;
this.setState({dragging: true, dragged: true});
};
onDrag: DraggableEventHandler = (e, coreData) => {
if (!this.state.dragging) return false;
log('Draggable: onDrag: %j', coreData);
const uiData = createDraggableData(this, coreData);
const newState: $Shape<DraggableState> = {
x: uiData.x,
y: uiData.y
};
// Keep within bounds.
if (this.props.bounds) {
// Save original x and y.
const {x, y} = newState;
// Add slack to the values used to calculate bound position. This will ensure that if
// we start removing slack, the element won't react to it right away until it's been
// completely removed.
newState.x += this.state.slackX;
newState.y += this.state.slackY;
// Get bound position. This will ceil/floor the x and y within the boundaries.
// $FlowBug
[newState.x, newState.y] = getBoundPosition(this, newState.x, newState.y);
// Recalculate slack by noting how much was shaved by the boundPosition handler.
newState.slackX = this.state.slackX + (x - newState.x);
newState.slackY = this.state.slackY + (y - newState.y);
// Update the event we fire to reflect what really happened after bounds took effect.
uiData.x = newState.x;
uiData.y = newState.y;
uiData.deltaX = newState.x - this.state.x;
uiData.deltaY = newState.y - this.state.y;
}
// Short-circuit if user's callback killed it.
const shouldUpdate = this.props.onDrag(e, uiData);
if (shouldUpdate === false) return false;
this.setState(newState);
};
onDragStop: DraggableEventHandler = (e, coreData) => {
if (!this.state.dragging) return false;
// Short-circuit if user's callback killed it.
const shouldStop = this.props.onStop(e, createDraggableData(this, coreData));
if (shouldStop === false) return false;
log('Draggable: onDragStop: %j', coreData);
const newState: $Shape<DraggableState> = {
dragging: false,
slackX: 0,
slackY: 0
};
// If this is a controlled component, the result of this operation will be to
// revert back to the old position. We expect a handler on `onDragStop`, at the least.
const controlled = Boolean(this.props.position);
if (controlled) {
const {x, y} = this.props.position;
newState.x = x;
newState.y = y;
}
this.setState(newState);
};
render(): ReactElement<any> {
let style = {}, svgTransform = null;
// If this is controlled, we don't want to move it - unless it's dragging.
const controlled = Boolean(this.props.position);
const draggable = !controlled || this.state.dragging;
const position = this.props.position || this.props.defaultPosition;
const transformOpts = {
// Set left if horizontal drag is enabled
x: canDragX(this) && draggable ?
this.state.x :
position.x,
// Set top if vertical drag is enabled
y: canDragY(this) && draggable ?
this.state.y :
position.y
};
// If this element was SVG, we use the `transform` attribute.
if (this.state.isElementSVG) {
svgTransform = createSVGTransform(transformOpts);
} else {
// Add a CSS transform to move the element around. This allows us to move the element around
// without worrying about whether or not it is relatively or absolutely positioned.
// If the item you are dragging already has a transform set, wrap it in a <span> so <Draggable>
// has a clean slate.
style = createCSSTransform(transformOpts);
}
const {
defaultClassName,
defaultClassNameDragging,
defaultClassNameDragged
} = this.props;
// Mark with class while dragging
const className = classNames((this.props.children.props.className || ''), defaultClassName, {
[defaultClassNameDragging]: this.state.dragging,
[defaultClassNameDragged]: this.state.dragged
});
// Reuse the child provided
// This makes it flexible to use whatever element is wanted (div, ul, etc)
return (
<DraggableCore {...this.props} onStart={this.onDragStart} onDrag={this.onDrag} onStop={this.onDragStop}>
{React.cloneElement(React.Children.only(this.props.children), {
className: className,
style: {...this.props.children.props.style, ...style},
transform: svgTransform
})}
</DraggableCore>
);
}
}

View File

@@ -0,0 +1,415 @@
// @flow
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import {matchesSelectorAndParentsTo, addEvent, removeEvent, addUserSelectStyles, getTouchIdentifier,
removeUserSelectStyles, styleHacks} from './utils/domFns';
import {createCoreData, getControlPosition, snapToGrid} from './utils/positionFns';
import {dontSetMe} from './utils/shims';
import log from './utils/log';
import type {EventHandler, MouseTouchEvent} from './utils/types';
import type {Element as ReactElement} from 'react';
// Simple abstraction for dragging events names.
const eventsFor = {
touch: {
start: 'touchstart',
move: 'touchmove',
stop: 'touchend'
},
mouse: {
start: 'mousedown',
move: 'mousemove',
stop: 'mouseup'
}
};
// Default to mouse events.
let dragEventFor = eventsFor.mouse;
type DraggableCoreState = {
dragging: boolean,
lastX: number,
lastY: number,
touchIdentifier: ?number
};
export type DraggableBounds = {
left: number,
right: number,
top: number,
bottom: number,
};
export type DraggableData = {
node: HTMLElement,
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number,
};
export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void;
export type ControlPosition = {x: number, y: number};
export type DraggableCoreProps = {
allowAnyClick: boolean,
cancel: string,
children: ReactElement<any>,
disabled: boolean,
enableUserSelectHack: boolean,
offsetParent: HTMLElement,
grid: [number, number],
handle: string,
onStart: DraggableEventHandler,
onDrag: DraggableEventHandler,
onStop: DraggableEventHandler,
onMouseDown: (e: MouseEvent) => void,
};
//
// Define <DraggableCore>.
//
// <DraggableCore> is for advanced usage of <Draggable>. It maintains minimal internal state so it can
// work well with libraries that require more control over the element.
//
export default class DraggableCore extends React.Component<DraggableCoreProps, DraggableCoreState> {
static displayName = 'DraggableCore';
static propTypes = {
/**
* `allowAnyClick` allows dragging using any mouse button.
* By default, we only accept the left button.
*
* Defaults to `false`.
*/
allowAnyClick: PropTypes.bool,
/**
* `disabled`, if true, stops the <Draggable> from dragging. All handlers,
* with the exception of `onMouseDown`, will not fire.
*/
disabled: PropTypes.bool,
/**
* By default, we add 'user-select:none' attributes to the document body
* to prevent ugly text selection during drag. If this is causing problems
* for your app, set this to `false`.
*/
enableUserSelectHack: PropTypes.bool,
/**
* `offsetParent`, if set, uses the passed DOM node to compute drag offsets
* instead of using the parent node.
*/
offsetParent: function(props, propName) {
if (process.browser && props[propName] && props[propName].nodeType !== 1) {
throw new Error('Draggable\'s offsetParent must be a DOM Node.');
}
},
/**
* `grid` specifies the x and y that dragging should snap to.
*/
grid: PropTypes.arrayOf(PropTypes.number),
/**
* `handle` specifies a selector to be used as the handle that initiates drag.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return (
* <Draggable handle=".handle">
* <div>
* <div className="handle">Click me to drag</div>
* <div>This is some other content</div>
* </div>
* </Draggable>
* );
* }
* });
* ```
*/
handle: PropTypes.string,
/**
* `cancel` specifies a selector to be used to prevent drag initialization.
*
* Example:
*
* ```jsx
* let App = React.createClass({
* render: function () {
* return(
* <Draggable cancel=".cancel">
* <div>
* <div className="cancel">You can't drag from here</div>
* <div>Dragging here works fine</div>
* </div>
* </Draggable>
* );
* }
* });
* ```
*/
cancel: PropTypes.string,
/**
* Called when dragging starts.
* If this function returns the boolean false, dragging will be canceled.
*/
onStart: PropTypes.func,
/**
* Called while dragging.
* If this function returns the boolean false, dragging will be canceled.
*/
onDrag: PropTypes.func,
/**
* Called when dragging stops.
* If this function returns the boolean false, the drag will remain active.
*/
onStop: PropTypes.func,
/**
* A workaround option which can be passed if onMouseDown needs to be accessed,
* since it'll always be blocked (as there is internal use of onMouseDown)
*/
onMouseDown: PropTypes.func,
/**
* These properties should be defined on the child, not here.
*/
className: dontSetMe,
style: dontSetMe,
transform: dontSetMe
};
static defaultProps = {
allowAnyClick: false, // by default only accept left click
cancel: null,
disabled: false,
enableUserSelectHack: true,
offsetParent: null,
handle: null,
grid: null,
transform: null,
onStart: function(){},
onDrag: function(){},
onStop: function(){},
onMouseDown: function(){}
};
state = {
dragging: false,
// Used while dragging to determine deltas.
lastX: NaN, lastY: NaN,
touchIdentifier: null
};
componentWillUnmount() {
// Remove any leftover event handlers. Remove both touch and mouse handlers in case
// some browser quirk caused a touch event to fire during a mouse move, or vice versa.
const thisNode = ReactDOM.findDOMNode(this);
if (thisNode) {
const {ownerDocument} = thisNode;
removeEvent(ownerDocument, eventsFor.mouse.move, this.handleDrag);
removeEvent(ownerDocument, eventsFor.touch.move, this.handleDrag);
removeEvent(ownerDocument, eventsFor.mouse.stop, this.handleDragStop);
removeEvent(ownerDocument, eventsFor.touch.stop, this.handleDragStop);
if (this.props.enableUserSelectHack) removeUserSelectStyles(ownerDocument);
}
}
handleDragStart: EventHandler<MouseTouchEvent> = (e) => {
// Make it possible to attach event handlers on top of this one.
this.props.onMouseDown(e);
// Only accept left-clicks.
if (!this.props.allowAnyClick && typeof e.button === 'number' && e.button !== 0) return false;
// Get nodes. Be sure to grab relative document (could be iframed)
const thisNode = ReactDOM.findDOMNode(this);
if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {
throw new Error('<DraggableCore> not mounted on DragStart!');
}
const {ownerDocument} = thisNode;
// Short circuit if handle or cancel prop was provided and selector doesn't match.
if (this.props.disabled ||
(!(e.target instanceof ownerDocument.defaultView.Node)) ||
(this.props.handle && !matchesSelectorAndParentsTo(e.target, this.props.handle, thisNode)) ||
(this.props.cancel && matchesSelectorAndParentsTo(e.target, this.props.cancel, thisNode))) {
return;
}
// Set touch identifier in component state if this is a touch event. This allows us to
// distinguish between individual touches on multitouch screens by identifying which
// touchpoint was set to this element.
const touchIdentifier = getTouchIdentifier(e);
this.setState({touchIdentifier});
// Get the current drag point from the event. This is used as the offset.
const position = getControlPosition(e, touchIdentifier, this);
if (position == null) return; // not possible but satisfies flow
const {x, y} = position;
// Create an event object with all the data parents need to make a decision here.
const coreEvent = createCoreData(this, x, y);
log('DraggableCore: handleDragStart: %j', coreEvent);
// Call event handler. If it returns explicit false, cancel.
log('calling', this.props.onStart);
const shouldUpdate = this.props.onStart(e, coreEvent);
if (shouldUpdate === false) return;
// Add a style to the body to disable user-select. This prevents text from
// being selected all over the page.
if (this.props.enableUserSelectHack) addUserSelectStyles(ownerDocument);
// Initiate dragging. Set the current x and y as offsets
// so we know how much we've moved during the drag. This allows us
// to drag elements around even if they have been moved, without issue.
this.setState({
dragging: true,
lastX: x,
lastY: y
});
// Add events to the document directly so we catch when the user's mouse/touch moves outside of
// this element. We use different events depending on whether or not we have detected that this
// is a touch-capable device.
addEvent(ownerDocument, dragEventFor.move, this.handleDrag);
addEvent(ownerDocument, dragEventFor.stop, this.handleDragStop);
};
handleDrag: EventHandler<MouseTouchEvent> = (e) => {
// Prevent scrolling on mobile devices, like ipad/iphone.
if (e.type === 'touchmove') e.preventDefault();
// Get the current drag point from the event. This is used as the offset.
const position = getControlPosition(e, this.state.touchIdentifier, this);
if (position == null) return;
let {x, y} = position;
// Snap to grid if prop has been provided
if (Array.isArray(this.props.grid)) {
let deltaX = x - this.state.lastX, deltaY = y - this.state.lastY;
[deltaX, deltaY] = snapToGrid(this.props.grid, deltaX, deltaY);
if (!deltaX && !deltaY) return; // skip useless drag
x = this.state.lastX + deltaX, y = this.state.lastY + deltaY;
}
const coreEvent = createCoreData(this, x, y);
log('DraggableCore: handleDrag: %j', coreEvent);
// Call event handler. If it returns explicit false, trigger end.
const shouldUpdate = this.props.onDrag(e, coreEvent);
if (shouldUpdate === false) {
try {
// $FlowIgnore
this.handleDragStop(new MouseEvent('mouseup'));
} catch (err) {
// Old browsers
const event = ((document.createEvent('MouseEvents'): any): MouseTouchEvent);
// I see why this insanity was deprecated
// $FlowIgnore
event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
this.handleDragStop(event);
}
return;
}
this.setState({
lastX: x,
lastY: y
});
};
handleDragStop: EventHandler<MouseTouchEvent> = (e) => {
if (!this.state.dragging) return;
const position = getControlPosition(e, this.state.touchIdentifier, this);
if (position == null) return;
const {x, y} = position;
const coreEvent = createCoreData(this, x, y);
const thisNode = ReactDOM.findDOMNode(this);
if (thisNode) {
// Remove user-select hack
if (this.props.enableUserSelectHack) removeUserSelectStyles(thisNode.ownerDocument);
}
log('DraggableCore: handleDragStop: %j', coreEvent);
// Reset the el.
this.setState({
dragging: false,
lastX: NaN,
lastY: NaN
});
// Call event handler
this.props.onStop(e, coreEvent);
if (thisNode) {
// Remove event handlers
log('DraggableCore: Removing handlers');
removeEvent(thisNode.ownerDocument, dragEventFor.move, this.handleDrag);
removeEvent(thisNode.ownerDocument, dragEventFor.stop, this.handleDragStop);
}
};
onMouseDown: EventHandler<MouseTouchEvent> = (e) => {
dragEventFor = eventsFor.mouse; // on touchscreen laptops we could switch back to mouse
return this.handleDragStart(e);
};
onMouseUp: EventHandler<MouseTouchEvent> = (e) => {
dragEventFor = eventsFor.mouse;
return this.handleDragStop(e);
};
// Same as onMouseDown (start drag), but now consider this a touch device.
onTouchStart: EventHandler<MouseTouchEvent> = (e) => {
// We're on a touch device now, so change the event handlers
dragEventFor = eventsFor.touch;
return this.handleDragStart(e);
};
onTouchEnd: EventHandler<MouseTouchEvent> = (e) => {
// We're on a touch device now, so change the event handlers
dragEventFor = eventsFor.touch;
return this.handleDragStop(e);
};
render() {
// Reuse the child provided
// This makes it flexible to use whatever element is wanted (div, ul, etc)
return React.cloneElement(React.Children.only(this.props.children), {
style: styleHacks(this.props.children.props.style),
// Note: mouseMove handler is attached to document so it will still function
// when the user drags quickly and leaves the bounds of the element.
onMouseDown: this.onMouseDown,
onTouchStart: this.onTouchStart,
onMouseUp: this.onMouseUp,
onTouchEnd: this.onTouchEnd
});
}
}

View File

@@ -0,0 +1,175 @@
// @flow
import {findInArray, isFunction, int} from './shims';
import browserPrefix, {browserPrefixToKey} from './getPrefix';
import type {ControlPosition, MouseTouchEvent} from './types';
let matchesSelectorFunc = '';
export function matchesSelector(el: Node, selector: string): boolean {
if (!matchesSelectorFunc) {
matchesSelectorFunc = findInArray([
'matches',
'webkitMatchesSelector',
'mozMatchesSelector',
'msMatchesSelector',
'oMatchesSelector'
], function(method){
// $FlowIgnore: Doesn't think elements are indexable
return isFunction(el[method]);
});
}
// $FlowIgnore: Doesn't think elements are indexable
return el[matchesSelectorFunc].call(el, selector);
}
// Works up the tree to the draggable itself attempting to match selector.
export function matchesSelectorAndParentsTo(el: Node, selector: string, baseNode: Node): boolean {
let node = el;
do {
if (matchesSelector(node, selector)) return true;
if (node === baseNode) return false;
node = node.parentNode;
} while (node);
return false;
}
export function addEvent(el: ?Node, event: string, handler: Function): void {
if (!el) { return; }
if (el.attachEvent) {
el.attachEvent('on' + event, handler);
} else if (el.addEventListener) {
el.addEventListener(event, handler, true);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = handler;
}
}
export function removeEvent(el: ?Node, event: string, handler: Function): void {
if (!el) { return; }
if (el.detachEvent) {
el.detachEvent('on' + event, handler);
} else if (el.removeEventListener) {
el.removeEventListener(event, handler, true);
} else {
// $FlowIgnore: Doesn't think elements are indexable
el['on' + event] = null;
}
}
export function outerHeight(node: HTMLElement): number {
// This is deliberately excluding margin for our calculations, since we are using
// offsetTop which is including margin. See getBoundPosition
let height = node.clientHeight;
const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height += int(computedStyle.borderTopWidth);
height += int(computedStyle.borderBottomWidth);
return height;
}
export function outerWidth(node: HTMLElement): number {
// This is deliberately excluding margin for our calculations, since we are using
// offsetLeft which is including margin. See getBoundPosition
let width = node.clientWidth;
const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width += int(computedStyle.borderLeftWidth);
width += int(computedStyle.borderRightWidth);
return width;
}
export function innerHeight(node: HTMLElement): number {
let height = node.clientHeight;
const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
height -= int(computedStyle.paddingTop);
height -= int(computedStyle.paddingBottom);
return height;
}
export function innerWidth(node: HTMLElement): number {
let width = node.clientWidth;
const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);
width -= int(computedStyle.paddingLeft);
width -= int(computedStyle.paddingRight);
return width;
}
// Get from offsetParent
export function offsetXYFromParent(evt: {clientX: number, clientY: number}, offsetParent: HTMLElement): ControlPosition {
const isBody = offsetParent === offsetParent.ownerDocument.body;
const offsetParentRect = isBody ? {left: 0, top: 0} : offsetParent.getBoundingClientRect();
const x = evt.clientX + offsetParent.scrollLeft - offsetParentRect.left;
const y = evt.clientY + offsetParent.scrollTop - offsetParentRect.top;
return {x, y};
}
export function createCSSTransform({x, y}: {x: number, y: number}): Object {
// Replace unitless items with px
return {[browserPrefixToKey('transform', browserPrefix)]: 'translate(' + x + 'px,' + y + 'px)'};
}
export function createSVGTransform({x, y}: {x: number, y: number}): string {
return 'translate(' + x + ',' + y + ')';
}
export function getTouch(e: MouseTouchEvent, identifier: number): ?{clientX: number, clientY: number} {
return (e.targetTouches && findInArray(e.targetTouches, t => identifier === t.identifier)) ||
(e.changedTouches && findInArray(e.changedTouches, t => identifier === t.identifier));
}
export function getTouchIdentifier(e: MouseTouchEvent): ?number {
if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier;
if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier;
}
// User-select Hacks:
//
// Useful for preventing blue highlights all over everything when dragging.
// Note we're passing `document` b/c we could be iframed
export function addUserSelectStyles(doc: Document) {
let styleEl = doc.getElementById('react-draggable-style-el');
if (!styleEl) {
styleEl = doc.createElement('style');
styleEl.type = 'text/css';
styleEl.id = 'react-draggable-style-el';
styleEl.innerHTML = '.react-draggable-transparent-selection *::-moz-selection {background: transparent;}\n';
styleEl.innerHTML += '.react-draggable-transparent-selection *::selection {background: transparent;}\n';
doc.getElementsByTagName('head')[0].appendChild(styleEl);
}
if (doc.body) addClassName(doc.body, 'react-draggable-transparent-selection');
}
export function removeUserSelectStyles(doc: Document) {
if (doc.body) removeClassName(doc.body, 'react-draggable-transparent-selection');
window.getSelection().removeAllRanges(); // remove selection caused by scroll
}
export function styleHacks(childStyle: Object = {}): Object {
// Workaround IE pointer events; see #51
// https://github.com/mzabriskie/react-draggable/issues/51#issuecomment-103488278
return {
touchAction: 'none',
...childStyle
};
}
export function addClassName(el: HTMLElement, className: string) {
if (el.classList) {
el.classList.add(className);
} else {
if (!el.className.match(new RegExp(`(?:^|\\s)${className}(?!\\S)`))) {
el.className += ` ${className}`;
}
}
}
export function removeClassName(el: HTMLElement, className: string) {
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp(`(?:^|\\s)${className}(?!\\S)`, 'g'), '');
}
}

View File

@@ -0,0 +1,47 @@
// @flow
const prefixes = ['Moz', 'Webkit', 'O', 'ms'];
export function getPrefix(prop: string='transform'): string {
// Checking specifically for 'window.document' is for pseudo-browser server-side
// environments that define 'window' as the global context.
// E.g. React-rails (see https://github.com/reactjs/react-rails/pull/84)
if (typeof window === 'undefined' || typeof window.document === 'undefined') return '';
const style = window.document.documentElement.style;
if (prop in style) return '';
for (let i = 0; i < prefixes.length; i++) {
if (browserPrefixToKey(prop, prefixes[i]) in style) return prefixes[i];
}
return '';
}
export function browserPrefixToKey(prop: string, prefix: string): string {
return prefix ? `${prefix}${kebabToTitleCase(prop)}` : prop;
}
export function browserPrefixToStyle(prop: string, prefix: string): string {
return prefix ? `-${prefix.toLowerCase()}-${prop}` : prop;
}
function kebabToTitleCase(str: string): string {
let out = '';
let shouldCapitalize = true;
for (let i = 0; i < str.length; i++) {
if (shouldCapitalize) {
out += str[i].toUpperCase();
shouldCapitalize = false;
} else if (str[i] === '-') {
shouldCapitalize = true;
} else {
out += str[i];
}
}
return out;
}
// Default export is the prefix itself, like 'Moz', 'Webkit', etc
// Note that you may have to re-test for certain things; for instance, Chrome 50
// can handle unprefixed `transform`, but not unprefixed `user-select`
export default getPrefix();

View File

@@ -0,0 +1,5 @@
// @flow
/*eslint no-console:0*/
export default function log(...args: any) {
if (process.env.DRAGGABLE_DEBUG) console.log(...args);
}

View File

@@ -0,0 +1,134 @@
// @flow
import {isNum, int} from './shims';
import ReactDOM from 'react-dom';
import {getTouch, innerWidth, innerHeight, offsetXYFromParent, outerWidth, outerHeight} from './domFns';
import type Draggable from '../Draggable';
import type {Bounds, ControlPosition, DraggableData, MouseTouchEvent} from './types';
import type DraggableCore from '../DraggableCore';
export function getBoundPosition(draggable: Draggable, x: number, y: number): [number, number] {
// If no bounds, short-circuit and move on
if (!draggable.props.bounds) return [x, y];
// Clone new bounds
let {bounds} = draggable.props;
bounds = typeof bounds === 'string' ? bounds : cloneBounds(bounds);
const node = findDOMNode(draggable);
if (typeof bounds === 'string') {
const {ownerDocument} = node;
const ownerWindow = ownerDocument.defaultView;
let boundNode;
if (bounds === 'parent') {
boundNode = node.parentNode;
} else {
boundNode = ownerDocument.querySelector(bounds);
}
if (!(boundNode instanceof HTMLElement)) {
throw new Error('Bounds selector "' + bounds + '" could not find an element.');
}
const nodeStyle = ownerWindow.getComputedStyle(node);
const boundNodeStyle = ownerWindow.getComputedStyle(boundNode);
// Compute bounds. This is a pain with padding and offsets but this gets it exactly right.
bounds = {
left: -node.offsetLeft + int(boundNodeStyle.paddingLeft) + int(nodeStyle.marginLeft),
top: -node.offsetTop + int(boundNodeStyle.paddingTop) + int(nodeStyle.marginTop),
right: innerWidth(boundNode) - outerWidth(node) - node.offsetLeft +
int(boundNodeStyle.paddingRight) - int(nodeStyle.marginRight),
bottom: innerHeight(boundNode) - outerHeight(node) - node.offsetTop +
int(boundNodeStyle.paddingBottom) - int(nodeStyle.marginBottom)
};
}
// Keep x and y below right and bottom limits...
if (isNum(bounds.right)) x = Math.min(x, bounds.right);
if (isNum(bounds.bottom)) y = Math.min(y, bounds.bottom);
// But above left and top limits.
if (isNum(bounds.left)) x = Math.max(x, bounds.left);
if (isNum(bounds.top)) y = Math.max(y, bounds.top);
return [x, y];
}
export function snapToGrid(grid: [number, number], pendingX: number, pendingY: number): [number, number] {
const x = Math.round(pendingX / grid[0]) * grid[0];
const y = Math.round(pendingY / grid[1]) * grid[1];
return [x, y];
}
export function canDragX(draggable: Draggable): boolean {
return draggable.props.axis === 'both' || draggable.props.axis === 'x';
}
export function canDragY(draggable: Draggable): boolean {
return draggable.props.axis === 'both' || draggable.props.axis === 'y';
}
// Get {x, y} positions from event.
export function getControlPosition(e: MouseTouchEvent, touchIdentifier: ?number, draggableCore: DraggableCore): ?ControlPosition {
const touchObj = typeof touchIdentifier === 'number' ? getTouch(e, touchIdentifier) : null;
if (typeof touchIdentifier === 'number' && !touchObj) return null; // not the right touch
const node = findDOMNode(draggableCore);
// User can provide an offsetParent if desired.
const offsetParent = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;
return offsetXYFromParent(touchObj || e, offsetParent);
}
// Create an data object exposed by <DraggableCore>'s events
export function createCoreData(draggable: DraggableCore, x: number, y: number): DraggableData {
const state = draggable.state;
const isStart = !isNum(state.lastX);
const node = findDOMNode(draggable);
if (isStart) {
// If this is our first move, use the x and y as last coords.
return {
node,
deltaX: 0, deltaY: 0,
lastX: x, lastY: y,
x, y,
};
} else {
// Otherwise calculate proper values.
return {
node,
deltaX: x - state.lastX, deltaY: y - state.lastY,
lastX: state.lastX, lastY: state.lastY,
x, y,
};
}
}
// Create an data exposed by <Draggable>'s events
export function createDraggableData(draggable: Draggable, coreData: DraggableData): DraggableData {
return {
node: coreData.node,
x: draggable.state.x + coreData.deltaX,
y: draggable.state.y + coreData.deltaY,
deltaX: coreData.deltaX,
deltaY: coreData.deltaY,
lastX: draggable.state.x,
lastY: draggable.state.y
};
}
// A lot faster than stringify/parse
function cloneBounds(bounds: Bounds): Bounds {
return {
left: bounds.left,
top: bounds.top,
right: bounds.right,
bottom: bounds.bottom
};
}
function findDOMNode(draggable: Draggable | DraggableCore): HTMLElement {
const node = ReactDOM.findDOMNode(draggable);
if (!node) {
throw new Error('<DraggableCore>: Unmounted during event!');
}
// $FlowIgnore we can't assert on HTMLElement due to tests... FIXME
return node;
}

View File

@@ -0,0 +1,25 @@
// @flow
// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc
export function findInArray(array: Array<any> | TouchList, callback: Function): any {
for (let i = 0, length = array.length; i < length; i++) {
if (callback.apply(callback, [array[i], i, array])) return array[i];
}
}
export function isFunction(func: any): boolean {
return typeof func === 'function' || Object.prototype.toString.call(func) === '[object Function]';
}
export function isNum(num: any): boolean {
return typeof num === 'number' && !isNaN(num);
}
export function int(a: string): number {
return parseInt(a, 10);
}
export function dontSetMe(props: Object, propName: string, componentName: string) {
if (props[propName]) {
return new Error(`Invalid prop ${propName} passed to ${componentName} - do not set this, set it on the child.`);
}
}

View File

@@ -0,0 +1,29 @@
// @flow
// eslint-disable-next-line no-use-before-define
export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void | false;
export type DraggableData = {
node: HTMLElement,
x: number, y: number,
deltaX: number, deltaY: number,
lastX: number, lastY: number
};
export type Bounds = {
left: number, top: number, right: number, bottom: number
};
export type ControlPosition = {x: number, y: number};
export type EventHandler<T> = (e: T) => void | false;
// Missing in Flow
export class SVGElement extends HTMLElement {
}
// Missing targetTouches
export class TouchEvent2 extends TouchEvent {
changedTouches: TouchList;
targetTouches: TouchList;
}
export type MouseTouchEvent = MouseEvent & TouchEvent2;