Skip to content

Commit

Permalink
feat(dnd): add onDropFromOutside prop for Dnd Cal (#1290)
Browse files Browse the repository at this point in the history
This PR is meant to resolve issue #1090.

## Basic callback for outside drops
The change exposes the `onDropFromOutside` prop on the withDragAndDrop HOC, which takes a callback that fires when an outside draggable item is dropped onto the calendar. The callback receives as a parameter an object with start and end properties that are times based on the drop position and slot size. 

![a4be055597d294f257d59a6fa2982f27](https://user-images.githubusercontent.com/37093582/56405067-a6036e00-6227-11e9-9274-b1846b5b0be8.gif)

It is worth noting that it is entirely up to the user to handle actual event creation based on the callback. All that this API does is allow `draggable` DOM elements to trigger a callback that receives start and end times for the slot an item was dropped on, and a boolean as to whether it's an all-day event. If the user wants to know which event was dropped, they will have to handle that themselves outside of React-Big-Calendar. An example added to the example App demonstrates how this can be done.

## Optional selective dropping
By default, if `onDropFromOutside` prop is passed, all draggable events are droppable on calendar. If the user wishes to discriminate as to whether draggable events are droppable on the calendar, they can pass an additional `onDragOver` callback function. The `onDragOver` callback takes a DragEvent as its sole parameter. If it calls the DragEvent's `preventDefault` method, then the draggable item in question is droppable. If it does not call `preventDefault` during the function call, it will not be droppable.

![e374b60b55809f471b2f275d7f166278](https://user-images.githubusercontent.com/37093582/56405161-3b9efd80-6228-11e9-9b0b-2c925f371eb1.gif)

An example was also added to the examples App, this one labelled `Addon: Drag and Drop (from outside calendar). The GIFs show this example in action. 

I also added the following comments into the withDragAndDrop HOC by way of documentation.

```
 * Additionally, this HOC adds the callback props `onDropFromOutside` and `onDragOver`. 
 * By default, the calendar will not respond to outside draggable items being dropped
 * onto it. However, if `onDropFromOutside` callback is passed, then when draggable 
 * DOM elements are dropped on the calendar, the callback will fire, receiving an 
 * object with start and end times, and an allDay boolean.
 *
 * If `onDropFromOutside` is passed, but `onDragOver` is not, any draggable event will be
 * droppable  onto the calendar by default. On the other hand, if an `onDragOver` callback
 * *is* passed, then it can discriminate as to whether a draggable item is droppable on the
 * calendar. To designate a draggable item as droppable, call `event.preventDefault`
 * inside `onDragOver`. If `event.preventDefault` is not called in the `onDragOver`
 * callback, then the draggable item will not be droppable on the calendar.
```

Hopefully this gives users the flexibility they need, without getting react-big-calendar overly involved with managing outside drag and drop scenarios. Any feedback/discussion/harangues are welcome!
  • Loading branch information
kamry-bowman authored and jquense committed Apr 22, 2019
1 parent 0fa2c30 commit b9fdce4
Show file tree
Hide file tree
Showing 6 changed files with 289 additions and 4 deletions.
3 changes: 3 additions & 0 deletions examples/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import Resource from './demos/resource'
import DndResource from './demos/dndresource'
import Timeslots from './demos/timeslots'
import Dnd from './demos/dnd'
import DndOutsideSource from './demos/dndOutsideSource'
import Dropdown from 'react-bootstrap/lib/Dropdown'
import MenuItem from 'react-bootstrap/lib/MenuItem'

Expand All @@ -43,6 +44,7 @@ const EXAMPLES = {
customView: 'Custom Calendar Views',
resource: 'Resource Scheduling',
dnd: 'Addon: Drag and drop',
dndOutsideSource: 'Addon: Drag and drop (from outside calendar)',
}

const DEFAULT_EXAMPLE = 'basic'
Expand Down Expand Up @@ -78,6 +80,7 @@ class Example extends React.Component {
timeslots: Timeslots,
dnd: Dnd,
dndresource: DndResource,
dndOutsideSource: DndOutsideSource,
}[selected]

return (
Expand Down
174 changes: 174 additions & 0 deletions examples/demos/dndOutsideSource.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import React from 'react'
import events from '../events'
import BigCalendar from 'react-big-calendar'
import withDragAndDrop from 'react-big-calendar/lib/addons/dragAndDrop'
import Layout from 'react-tackle-box/Layout'
import Card from '../Card'

import 'react-big-calendar/lib/addons/dragAndDrop/styles.less'

const DragAndDropCalendar = withDragAndDrop(BigCalendar)

const formatName = (name, count) => `${name} ID ${count}`

class Dnd extends React.Component {
constructor(props) {
super(props)
this.state = {
events: events,
draggedEvent: null,
counters: {
item1: 0,
item2: 0,
},
}
}

handleDragStart = name => {
this.setState({ draggedEvent: name })
}

customOnDragOver = event => {
// check for undroppable is specific to this example
// and not part of API. This just demonstrates that
// onDragOver can optionally be passed to conditionally
// allow draggable items to be dropped on cal, based on
// whether event.preventDefault is called
if (this.state.draggedEvent !== 'undroppable') {
console.log('preventDefault')
event.preventDefault()
}
}

onDropFromOutside = ({ start, end, allDay }) => {
const { draggedEvent, counters } = this.state
const event = {
title: formatName(draggedEvent, counters[draggedEvent]),
start,
end,
isAllDay: allDay,
}
const updatedCounters = {
...counters,
[draggedEvent]: counters[draggedEvent] + 1,
}
this.setState({ draggedEvent: null, counters: updatedCounters })
this.newEvent(event)
}

moveEvent({ event, start, end, isAllDay: droppedOnAllDaySlot }) {
const { events } = this.state

const idx = events.indexOf(event)
let allDay = event.allDay

if (!event.allDay && droppedOnAllDaySlot) {
allDay = true
} else if (event.allDay && !droppedOnAllDaySlot) {
allDay = false
}

const updatedEvent = { ...event, start, end, allDay }

const nextEvents = [...events]
nextEvents.splice(idx, 1, updatedEvent)

this.setState({
events: nextEvents,
})

// alert(`${event.title} was dropped onto ${updatedEvent.start}`)
}

resizeEvent = ({ event, start, end }) => {
const { events } = this.state

const nextEvents = events.map(existingEvent => {
return existingEvent.id == event.id
? { ...existingEvent, start, end }
: existingEvent
})

this.setState({
events: nextEvents,
})

//alert(`${event.title} was resized to ${start}-${end}`)
}

newEvent(event) {
let idList = this.state.events.map(a => a.id)
let newId = Math.max(...idList) + 1
let hour = {
id: newId,
title: event.title,
allDay: event.isAllDay,
start: event.start,
end: event.end,
}
this.setState({
events: this.state.events.concat([hour]),
})
}

render() {
return (
<div>
<Card
className="examples--header"
style={{
display: 'flex',
justifyContent: 'center',
flexWrap: 'wrap',
}}
>
<h4 style={{ color: 'gray', width: '100%' }}>Outside Drag Sources</h4>
{Object.entries(this.state.counters).map(([name, count]) => (
<div
style={{
border: '2px solid gray',
borderRadius: '4px',
width: '100px',
margin: '10px',
}}
draggable="true"
key={name}
onDragStart={() => this.handleDragStart(name)}
>
{formatName(name, count)}
</div>
))}
<div
style={{
border: '2px solid gray',
borderRadius: '4px',
width: '100px',
margin: '10px',
}}
draggable="true"
key={name}
onDragStart={() => this.handleDragStart('undroppable')}
>
Draggable but not for calendar.
</div>
</Card>
<DragAndDropCalendar
selectable
localizer={this.props.localizer}
events={this.state.events}
onEventDrop={this.moveEvent}
onDropFromOutside={this.onDropFromOutside}
onDragOver={this.customOnDragOver}
resizable
onEventResize={this.resizeEvent}
onSelectSlot={this.newEvent}
onD
defaultView={BigCalendar.Views.MONTH}
defaultDate={new Date(2015, 3, 12)}
/>
</div>
)
}
}

export default Dnd
18 changes: 18 additions & 0 deletions src/Selection.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class Selection {
this._handleMoveEvent = this._handleMoveEvent.bind(this)
this._handleTerminatingEvent = this._handleTerminatingEvent.bind(this)
this._keyListener = this._keyListener.bind(this)
this._dropFromOutsideListener = this._dropFromOutsideListener.bind(this)

// Fixes an iOS 10 bug where scrolling could not be prevented on the window.
// https://github.com/metafizzy/flickity/issues/457#issuecomment-254501356
Expand All @@ -64,6 +65,10 @@ class Selection {
)
this._onKeyDownListener = addEventListener('keydown', this._keyListener)
this._onKeyUpListener = addEventListener('keyup', this._keyListener)
this._onDropFromOutsideListener = addEventListener(
'drop',
this._dropFromOutsideListener
)
this._addInitialEventListener()
}

Expand Down Expand Up @@ -187,6 +192,19 @@ class Selection {
}
}

_dropFromOutsideListener(e) {
const { pageX, pageY, clientX, clientY } = getEventCoordinates(e)

this.emit('dropFromOutside', {
x: pageX,
y: pageY,
clientX: clientX,
clientY: clientY,
})

e.preventDefault()
}

_handleInitialEvent(e) {
const { clientX, clientY, pageX, pageY } = getEventCoordinates(e)
let node = this.container(),
Expand Down
26 changes: 26 additions & 0 deletions src/addons/dragAndDrop/EventContainerWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class EventContainerWrapper extends React.Component {
draggable: PropTypes.shape({
onStart: PropTypes.func,
onEnd: PropTypes.func,
onDropFromOutside: PropTypes.func,
onBeginAction: PropTypes.func,
dragAndDropAction: PropTypes.object,
}),
Expand Down Expand Up @@ -113,6 +114,21 @@ class EventContainerWrapper extends React.Component {
this.update(event, slotMetrics.getRange(start, end))
}

handleDropFromOutside = (point, boundaryBox) => {
const { slotMetrics } = this.props

let start = slotMetrics.closestSlotFromPoint(
{ y: point.y, x: point.x },
boundaryBox
)

this.context.draggable.onDropFromOutside({
start,
end: slotMetrics.nextSlot(start),
allDay: false,
})
}

_selectable = () => {
let node = findDOMNode(this)
let selector = (this._selector = new Selection(() =>
Expand Down Expand Up @@ -141,6 +157,16 @@ class EventContainerWrapper extends React.Component {
if (dragAndDropAction.action === 'resize') this.handleResize(box, bounds)
})

selector.on('dropFromOutside', point => {
if (!this.context.draggable.onDropFromOutside) return

const bounds = getBoundsForNode(node)

if (!pointInColumn(bounds, point)) return

this.handleDropFromOutside(point, bounds)
})

selector.on('selectStart', () => this.context.draggable.onStart())

selector.on('select', point => {
Expand Down
27 changes: 27 additions & 0 deletions src/addons/dragAndDrop/WeekWrapper.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class WeekWrapper extends React.Component {
onStart: PropTypes.func,
onEnd: PropTypes.func,
dragAndDropAction: PropTypes.object,
onDropFromOutside: PropTypes.func,
onBeginAction: PropTypes.func,
}),
}
Expand Down Expand Up @@ -106,6 +107,21 @@ class WeekWrapper extends React.Component {
this.update(event, start, end)
}

handleDropFromOutside = (point, rowBox) => {
if (!this.context.draggable.onDropFromOutside) return
const { slotMetrics: metrics } = this.props

let start = metrics.getDateForSlot(
getSlotAtX(rowBox, point.x, false, metrics.slots)
)

this.context.draggable.onDropFromOutside({
start,
end: dates.add(start, 1, 'day'),
allDay: false,
})
}

handleResize(point, node) {
const { event, direction } = this.context.draggable.dragAndDropAction
const { accessors, slotMetrics: metrics } = this.props
Expand Down Expand Up @@ -193,6 +209,17 @@ class WeekWrapper extends React.Component {
if (!this.state.segment || !pointInBox(bounds, point)) return
this.handleInteractionEnd()
})

selector.on('dropFromOutside', point => {
if (!this.context.draggable.onDropFromOutside) return

const bounds = getBoundsForNode(node)

if (!pointInBox(bounds, point)) return

this.handleDropFromOutside(point, bounds)
})

selector.on('click', () => this.context.draggable.onEnd(null))
}

Expand Down
Loading

0 comments on commit b9fdce4

Please sign in to comment.