0.0.5 • Published 6 years ago

@wuweiweiwu/react-shopify-draggable v0.0.5

Weekly downloads
88
License
MIT
Repository
github
Last release
6 years ago

React Shopify Draggable

npm version

Port of @shopify/draggable to React

# adding to project
npm install @wuweiweiwu/react-shopify-draggable
# or
yarn add @wuweiweiwu/react-shopify-draggable

DEMO

import React, { Component } from 'react';
import {
  DraggableItem,
  DraggableContainer,
} from '@wuweiweiwu/react-shopify-draggable';

import '../shared/favicon/favicon.ico';
import './stylesheets/app.css';

const random255 = () => Math.floor(Math.random() * 256);
const randomColor = () => `rgb(${random255()}, ${random255()}, ${random255()})`;

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      blockCount: 14,
    };
    this.handleBlockCount = this.handleBlockCount.bind(this);
  }

  handleBlockCount(e) {
    if (e.target.value) {
      this.setState({
        blockCount: parseInt(e.target.value),
      });
    }
  }

  render() {
    return (
      <div className="App">
        <div className="App-body">
          <div className="App-body-count">
            <h1 className="App-body-count-text">Block count:</h1>
            <input
              type="number"
              className="App-body-count-input"
              value={this.state.blockCount}
              onChange={this.handleBlockCount}
            />
          </div>
          <DraggableContainer
            as="div"
            type="sortable"
            className="BlockGenerator"
          >
            {Array.from(Array(this.state.blockCount).keys()).map(number => (
              <DraggableItem
                as="div"
                className="Block"
                style={{ backgroundColor: randomColor() }}
              >
                {number}
              </DraggableItem>
            ))}
          </DraggableContainer>
        </div>
      </div>
    );
  }
}

export default App;

Options

<DraggableContainer/>

This is the base component that wraps <DraggableItem/>,<DraggableHandle/>, <DroppableZone/>

You specify the draggable, handle, droppable props in this component and they will automatically be passed (deeply) to the Draggable children via React Context

Props that will cause a re-rendering of self (and also child components if shouldComponentUpdate returns true):

  • as
  • children (Nodes passed/nested as children)

Props that will only force a re-rendering of child Draggable components using forceUpdate:

  • draggable
  • handle
  • droppable
PropsTypeDefaultDescription
asstring'div'what to render this component as
idstringid to add to this element
classNamestring or Array<string>class(es) to add to this element
styleobjectcss inline styling (React style)
type'draggable' or 'droppable' or 'swappable' or 'sortable''draggable'what type of Draggable instance is it? Draggable, Droppable, Swappable, Sortable.
draggablestring'draggable-source'the class added to draggable items
handlestringnullthe class added to draggable handles
droppablestringthe class added to the droppable zone
collidablestringthe class that specifies the collidable elements
sensorsArray<Sensor>[]additional sensors added to Draggable (MouseSensor & TouchSensor already included)
pluginsArray<BasePlugin>[]additional plugins added to Draggable
classes{ [string]: string }object keyed by events. Values are classnames added. ex: { 'drag:start': '.add-class' }
eleRefHTMLElement => voidexactly like how refs work in React. This ref will return the base element of the component
dragRefDraggable => voidsimilar to how refs work in React. This ref will return the Draggable instance
appendTostring or HTMLElement or(()=>HTMLElement)what to append the mirror element to
mirror{ xAxis: boolean, yAxis: boolean, constrainDimensions: boolean}{ xAxis: true, yAxis: true, constrainDimensions: false }mirror options (see @shopify/draggable docs)
swapAnimation{ duration: number, easingFunction: string }{ duration: 150, easingFunction: 'ease-in-out' }Sortable swap animation options (see @shopify/draggable docs)

Event Handlers

for more documentation on these see @shopify/draggable

ex: onDragStart is the same as 'drag:start' and onSwappableStart is the same as 'swappable:start'

// Draggable events
onDragStart?: BaseEvent => void,
onDragMove?: BaseEvent => void,
onDragOver?: BaseEvent => void,
onDragOverContainer?: BaseEvent => void,
onDragOut?: BaseEvent => void,
onDragOutContainer?: BaseEvent => void,
onDragStop?: BaseEvent => void,
onDragPressure?: BaseEvent => void,

// Mirror events
onMirrorCreated?: BaseEvent => void,
onMirrorAttached?: BaseEvent => void,
onMirrorMove?: BaseEvent => void,
onMirrorDestroy?: BaseEvent => void,

// Droppable events
onDroppableOver?: BaseEvent => void,
onDroppableOut?: BaseEvent => void,

// Sortable events
onSortableStart?: BaseEvent => void,
onSortableSorted?: BaseEvent => void,
onSortableStop?: BaseEvent => void,

// Swappable events
onSwappableStart?: BaseEvent => void,
onSwappableSwapped?: BaseEvent => void,
onSwappableStop?: BaseEvent => void,

// Collidable events
onCollidableIn?: BaseEvent => void,
onCollidableOut?: BaseEvent => void,

// Snappable events
onSnapIn?: BaseEvent => void,
onSnapOut?: BaseEvent => void,

<DraggableItem/>,<DraggableHandle/>, <DroppableZone/>

NOTE #1: DraggableHandle HAS to be nested inside a DraggableItem for it to work

NOTE #2: If you set the handle prop for DraggableContainer but don't have a DraggableHandle inside the container then it won't work.

Props that will cause a re-rendering of self (and child components where shouldComponentUpdate returns true):

  • as
  • children (Nodes passed/nested as children)
PropsTypeDefaultDescription
asstring'div'what to render this component as
idstringid to add to this element
classNamestringclass to add to this element (on top of what DraggableContainer will inject)
styleobjectcss inline styling (React style)
eleRefHTMLElement => voidexactly like how refs work in React. This ref will return the base element of the component

Implementation details

@wuweiweiwu/react-shopify-react was built to address @shopify/draggable issue #32 where users were having trouble integrating Draggable with React because re renders would cause the state of the Draggable elements to reset. Unless you wanted to implement the details of shouldComponentUpdate and componentWillReceiveProps it would be difficult to use Draggable with React.

This component provides a <DraggableContainer/> that represents the Draggable container that contains draggable elements. It also provides the classnames that child Draggable components will have. For example: instead of specifying the draggable option and also putting that class explicitly in your HTML it uses React Context to pass down the class names internally. Thus you should NOT nest <DraggableContainer/> inside each other.

Deciding when to rerender in React is a little finicky. If we don't want the internal Draggable state to change on renders then we need to implement our shouldComponentUpdate functions and decide how to update properties such as id and className without causing a rerender. <DraggableContainer/> and other components provided in this package should only rerender if you are changing as or children prop. Other prop changes should not cause a rerender, event options passed to @shopify/draggable. Thus we maintain an internal instance of Draggable that is updated in the React lifecycle function componentWillReceiveProps which is called when the component received new or updated props. Thus we can reset/update the instance without causing a rerender.

shouldComponentUpdate(nextProps: Props): boolean {
  console.log('shouldComponentUpdate');
  // only rerender if as or children is different
  if (propertiesChanged(this.props, nextProps, ['as', 'children'])) {
    return true;
  }
  return false;
}

By using context to pass the draggable, handle, droppable options to child components. It means that <DraggableItem/>,<DraggableHandle/>, <DroppableZone/> can be nested infinitely inside other components and it will always receive these update. This functionality is implemented following this concept in this article How to use React Context safely. Thus you can even use Redux with this component and there will be no problems.

Setting inline styles without rerendering involved stealing some code from Facebook React

Contributing

After cloning the repository and running npm install inside, you can use the following commands to develop and build the project.

# Starts a webpack dev server that hosts a demo page with the component.
# It uses react-hot-loader so changes are reflected on save.
npm start

# Start the storybook, which has several different examples to play with.
# Also hot-reloaded.
npm run storybook

# Runs the library tests
npm test

# Lints the code with eslint
npm run lint

# run flow type checking
npm run flow

# Lints and builds the code, placing the result in the dist directory.
# This build is necessary to reflect changes if you're
#  `npm link`-ed to this repository from another local project.
npm run build

Pull requests are welcome!

License

MIT