This provides an example of using the HTML Drag and Drop API to sort a list in a Rails application. The solution uses two Stimulus controllers to invoke the API and update the sort order.
This solution is not packaged. Implementation requires the copy-and-paste skills of the developer.
The two controllers are in app/javascript/controllers
and namespaced as dnd
:
In this implementation, the two controllers are added to the TODO List form view and the Task Fields partial.
The main container element specifies (1) the container controller, (2) the outlet for the item controller, and (3) the mouseup listener:
<div id="container"
data-controller="dnd--container"
data-dnd--container-dnd--item-outlet=".nested-fields"
data-action="mouseup->dnd--container#disableDrag" >
The main item element specifies (1) the item controller, (2) listeners (dragstart, dragend, dragenter, dragover, dragleave, and drop), and (3) the outlet for the container controller:
<div
data-controller="dnd--item"
data-dnd--item-dnd--container-outlet="#container"
data-action="dragstart->dnd--item#dragStart
dragend->dnd--item#dragEnd
dragenter->dnd--item#addDropIndicator
dragover->dnd--item#allowDrop
dragleave->dnd--item#removeDropIndicator
drop->dnd--item#drop" >
The handle for the item includes the handle target as well as a mousedown listener:
<a href="#" class="btn btn-primary"
data-dnd--item-target="handle"
data-action="mousedown->dnd--item#enableDrag" >
<i class="fa fa-bars"></i>
</a>
There are three additional targets for the item controller:
- id: the form element with the unique item Id
- order: the form element with the order; this value gets updated
- description: only used by the debugger to help identify the row in the logs
The following styles support the feature. The can be customized as needed, though the pointer-events: none
is required.
Selector | Notes |
---|---|
.dragged | Reduces opacity to highlight which item is being dragged |
.drop-above | When items are dragged upwards, this draws a line where the item would be dropped |
.drop-below | When items are dragged dwonwards, this draws a line where the item would be dropped |
.dropzone .nested-fields * | Prevents events from firing while the drag is occurring (required) |
The versions in the repo are a bit dated. I found I had to use node 13 to get yarn to install.
There is a seed file with a sample TODO list.
The code is available as open source under the terms of the MIT License.
The underlying TODO app comes from the talented folks at Drifting Ruby, from an episode about nested forms and Stimulus.
Thanks to Doug Pace for his help in testing the feature.