Skip to content

[WIP] Implement drag and drop feature for widgets #2363

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
800 changes: 800 additions & 0 deletions docs/source/examples/Drag and Drop examples.ipynb

Large diffs are not rendered by default.

Binary file added docs/source/examples/dragable1.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 2 additions & 2 deletions ipywidgets/widgets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@
from .widget_core import CoreWidget
from .widget_bool import Checkbox, ToggleButton, Valid
from .widget_button import Button, ButtonStyle
from .widget_box import Box, HBox, VBox, GridBox
from .widget_box import Box, HBox, VBox, GridBox, DropBox, DraggableBox
from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider, FloatLogSlider
from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider, Play, SliderStyle
from .widget_color import ColorPicker
from .widget_date import DatePicker
from .widget_output import Output
from .widget_selection import RadioButtons, ToggleButtons, ToggleButtonsStyle, Dropdown, Select, SelectionSlider, SelectMultiple, SelectionRangeSlider
from .widget_selectioncontainer import Tab, Accordion
from .widget_string import HTML, HTMLMath, Label, Text, Textarea, Password
from .widget_string import HTML, HTMLMath, Label, Text, Textarea, Password, DraggableLabel
from .widget_controller import Controller
from .interaction import interact, interactive, fixed, interact_manual, interactive_output
from .widget_link import jslink, jsdlink
Expand Down
15 changes: 14 additions & 1 deletion ipywidgets/widgets/widget_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@
from .widget import register, widget_serialization, Widget
from .domwidget import DOMWidget
from .widget_core import CoreWidget
from .widget_drop import DropWidget
from .docutils import doc_subst
from .trait_types import TypedTuple
from traitlets import Unicode, CaselessStrEnum, Instance
from traitlets import Bool


_doc_snippets = {}
Expand Down Expand Up @@ -59,6 +61,8 @@ class Box(DOMWidget, CoreWidget):
values=['success', 'info', 'warning', 'danger', ''], default_value='',
help="""Use a predefined styling for the box.""").tag(sync=True)

dropzone = Bool(default=False).tag(sync=True)

def __init__(self, children=(), **kwargs):
kwargs['children'] = children
super(Box, self).__init__(**kwargs)
Expand Down Expand Up @@ -113,4 +117,13 @@ class HBox(Box):
class GridBox(Box):
_model_name = Unicode('GridBoxModel').tag(sync=True)
_view_name = Unicode('GridBoxView').tag(sync=True)


@register
class DropBox(DropWidget, Box):
_model_name = Unicode('DropBoxModel').tag(sync=True)
_view_name = Unicode('DropBoxView').tag(sync=True)

@register
class DraggableBox(DropWidget, Box):
_model_name = Unicode('DraggableBoxModel').tag(sync=True)
_view_name = Unicode('DraggableBoxView').tag(sync=True)
50 changes: 50 additions & 0 deletions ipywidgets/widgets/widget_drop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

"""Contains the DropWidget class"""
from .widget import Widget
from .widget import CallbackDispatcher
from traitlets import Bool, Dict

class DropWidget(Widget):
"""Widget that has the ondrop handler. Used as a mixin"""

draggable = Bool(default=False).tag(sync=True)
drag_data = Dict().tag(sync=True)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._click_handlers = CallbackDispatcher()
self.on_msg(self._handle_drop_msg)

def on_drop(self, callback, remove=False):
"""Register a callback to execute when an element is dropped.

The callback will be called with two arguments, the clicked button
widget instance, and the dropped element data.

Parameters
----------
remove: bool (optional)
Set to true to remove the callback from the list of callbacks.
"""
self._click_handlers.register_callback(callback, remove=remove)

def drop(self, data):
"""Programmatically trigger a drop event.

This will call the callbacks registered to the drop event.
"""

self._click_handlers(self, data)

def _handle_drop_msg(self, _, content, buffers):
"""Handle a msg from the front-end.

Parameters
----------
content: dict
Content of the msg.
"""
if content.get('event', '') == 'drop':
self.drop(content.get('data', {}))
27 changes: 26 additions & 1 deletion ipywidgets/widgets/widget_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@

from .widget_description import DescriptionWidget
from .valuewidget import ValueWidget
from .widget_drop import DropWidget
from .widget import CallbackDispatcher, register
from .widget_core import CoreWidget
from traitlets import Unicode, Bool, Int
from traitlets import Unicode, Bool, Int, Dict
from warnings import warn


Expand Down Expand Up @@ -56,6 +57,30 @@ class Label(_String):
_view_name = Unicode('LabelView').tag(sync=True)
_model_name = Unicode('LabelModel').tag(sync=True)

def __init__(self, *args, **kwargs):
super(Label, self).__init__(*args, **kwargs)

@register
class DraggableLabel(DropWidget, Label):
""" Draggable Label.

A label that can be dragged and responds to drop events.

Properties:

draggable : bool
activate or deactivate drag behaviour

Methods:

on_drop :
function that adds a drop event handler

"""
_view_name = Unicode('DraggableLabelView').tag(sync=True)
_model_name = Unicode('DraggableLabelModel').tag(sync=True)



@register
class Textarea(_String):
Expand Down
106 changes: 104 additions & 2 deletions packages/controls/src/widget_box.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ import {
Widget, Panel
} from '@phosphor/widgets';

import {
Droppable, Draggable, applyMixins
} from './widget_string';

import * as _ from 'underscore';
import * as $ from 'jquery';

Expand Down Expand Up @@ -75,7 +79,8 @@ class BoxModel extends CoreDOMWidgetModel {
_view_name: 'BoxView',
_model_name: 'BoxModel',
children: [],
box_style: ''
box_style: '',
dropzone: false
});
}

Expand Down Expand Up @@ -146,6 +151,32 @@ class BoxView extends DOMWidgetView {
this.set_box_style();
}

events(): {[e: string] : string; } {
return {'drop' : 'on_drop',
'dragover' : 'on_dragover'};
}

on_dragover(event) {
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = 'copy';
}

on_drop(event) {
event.preventDefault();
event.stopPropagation();
event.dataTransfer.dropEffect = 'copy';
if (this.model.get('dropzone')) {
let model_id = event.dataTransfer.getData('application/x-widget');
var promise = this.model.widget_manager.get_model(model_id);
promise.then((model) => {
let childs = this.model.get('children');
childs.push(model);
this.update_children();
});
}
}

update_children() {
this.children_views.update(this.model.get('children')).then((views: DOMWidgetView[]) => {
// Notify all children that their sizes may have changed.
Expand Down Expand Up @@ -223,7 +254,7 @@ class GridBoxView extends BoxView {
initialize(parameters) {
super.initialize(parameters);
this.pWidget.addClass('widget-gridbox');
// display needn't be set to flex and grid
// display needn't be set to flex and grid
this.pWidget.removeClass('widget-box');
}
}
Expand All @@ -237,3 +268,74 @@ class GridBoxModel extends BoxModel {
});
}
}

export
class DropBoxModel extends BoxModel {
defaults() {
return _.extend(super.defaults(), {
_view_name: 'DropBoxView',
_model_name: 'DropBoxModel',
});
}
}

export
class DropBoxView extends BoxView implements Droppable {
/**
* Public constructor
*/
initialize(parameters) {
super.initialize(parameters);
this.pWidget.addClass('widget-dropbox');
}

/**
* Dictionary of events and handlers
*/
events(): {[e: string] : string; } {
return {'drop': '_handle_drop',
'dragover' : 'on_dragover'};
}

_handle_drop : (event: Object) => void;
on_dragover : (event : Object) => void;
}

applyMixins(DropBoxView, [Droppable]);

export
class DraggableBoxModel extends BoxModel {
defaults() {
return _.extend(super.defaults(), {
_view_name: 'DraggableBoxView',
_model_name: 'DraggableBoxModel',
draggable : false,
drag_data: {}
});
}
}

export
class DraggableBoxView extends BoxView implements Draggable {
/**
* Public constructor
*/
initialize(parameters) {
super.initialize(parameters);
this.pWidget.addClass('widget-draggablebox');
this.dragSetup();
}

/**
* Dictionary of events and handlers
*/
events(): {[e: string] : string; } {
return {'dragstart' : 'on_dragstart'};
}

on_dragstart : (event : Object) => void;
on_change_draggable : () => void;
dragSetup : () => void;
}

applyMixins(DraggableBoxView, [Draggable]);
Loading