You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

advanced-dragndrop.asciidoc 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. ---
  2. title: Drag and Drop
  3. order: 12
  4. layout: page
  5. ---
  6. [[advanced.dragndrop]]
  7. = Drag and Drop
  8. ((("Drag and Drop", id="term.advanced.dragndrop", range="startofrange")))
  9. IMPORTANT: This feature is currently being developed and only available in the Framework 8.1 prerelease versions, starting from 8.1.0.alpha1.
  10. Dragging an object from one location to another by grabbing it with mouse,
  11. holding the mouse button pressed, and then releasing the button to "drop" it to
  12. the other location is a common way to move, copy, or associate objects. For
  13. example, most operating systems allow dragging and dropping files between
  14. folders or dragging a document on a program to open it. Framework version 8.1 adds support for https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API[HTML5 drag and drop] features. This makes it possible to set components as drag sources that user can drag and drop, or to set them as drop targets to drop things on.
  15. == Drag Source
  16. Any component can be made a drag source that has textual data that is transferred when it is dragged and dropped.
  17. To make a component a drag source, you apply the [classname]#DragSourceExtension# to it. Then you can define the text to transfer, and the allowed drag effect.
  18. [source, java]
  19. ----
  20. Label draggableLabel = new Label("You can grab and drag me");
  21. DragSourceExtension<Label> dragSource = new DragSourceExtension<>(draggableLabel);
  22. // set the allowed effect
  23. dragSource.setEffectAllowed(EffectAllowed.MOVE);
  24. // set the text to transfer
  25. dragSource.setDataTransferText("hello receiver");
  26. // set other data to transfer (in this case HTML)
  27. dragSource.setDataTransferData("text/html", "<label>hello receiver</label>");
  28. ----
  29. The __effect allowed__ specifies the allowed effects that must match the __drop effect__ of the drop target. If these don't match, the drop event is never fired on the target. If multiple effects are allowed, the user can use the modifier keys to switch between the desired effects. The default effect and the modifier keys are system and browser dependent.
  30. The __data transfer text__ is textual data, that the drop target will receive in the __drop event__.
  31. The __data transfer data__ is any data of the given type, that the drop target will also receive in the __drop event__. The order, in which the data is set for the drag source, is preserved, which helps the drop target finding the most preferred and supported data.
  32. [NOTE]
  33. ====
  34. Note that `"text"` is the only cross browser supported data type. If your application supports IE11, pleas only use the `setDataTransferText()` method.
  35. ====
  36. The [classname]#DragStartEvent# is fired when the drag has started, and the [classname]#DragEndEvent# event when the drag has ended, either in a drop or a cancel.
  37. [source, java]
  38. ----
  39. dragSource.addDragStartListener(event ->
  40. Notification.show("Drag event started");
  41. );
  42. dragSource.addDragEndListener(event -> {
  43. if (event.isCanceled()) {
  44. Notification.show("Drag event was canceled");
  45. } else {
  46. Notification.show("Drag event finished");
  47. }
  48. });
  49. ----
  50. You can check whether the drag was canceled using the `isCanceled()` method.
  51. It is possible to transfer any Object as server side data to the drop target if both the drag source and drop target are placed in the same UI. This data is available in the drop event via the `DropEvent.getDragData()` method.
  52. [source, java]
  53. ----
  54. dragSource.addDragStartListener(event ->
  55. dragSource.setDragData(myObject);
  56. );
  57. dragSource.addDragEndListener(event ->
  58. dragSource.setDragData(null);
  59. };
  60. ----
  61. === CSS Style Rules
  62. The drag source element, additional to it's primary style name, have a style name with the `-dragsource` suffix. For example, a Label component would have the style name `v-label-dragsource` when the drag source extension is applied to it.
  63. Additionally, the elements also have the `v-draggable` style name that is independent of the component's primary style.
  64. While being dragged, the element also gets the style name with suffix `-dragged`.
  65. An example for this is `v-label-dragged` in case of a Label component.
  66. This style name is added during the drag start and removed during the drag end event.
  67. The browsers allow the user to select and drag and drop text, which could cause issues with components that have text. The Framework tries to prevent this by automatically adding the following style to all `v-draggable` elements. It is included by the sass mixin `valo-drag-element`.
  68. [source, css]
  69. ----
  70. .v-draggable {
  71. -moz-user-select: none !important;
  72. -ms-user-select: none !important;
  73. -webkit-user-select: none !important;
  74. user-select: none !important;
  75. }
  76. ----
  77. [[advanced.dragndrop.drophandler]]
  78. == Drop Target
  79. The drag operations end when the mouse button is released on a valid drop target. It is then up to the target to react to the drop event and the data associated with the drag, set by the drag source.
  80. To make a component be a drop target, you apply the [classname]#DropTargetExtension# to it. The extension allows you to control when the drop is acceptable and then react to the drop event.
  81. [source, java]
  82. ----
  83. VerticalLayout dropTargetLayout = new VerticalLayout();
  84. dropTargetLayout.setCaption("Drop things inside me");
  85. dropTargetLayout.addStyleName(ValoTheme.LAYOUT_CARD);
  86. // make the layout accept drops
  87. DropTargetExtension<VerticalLayout> dropTarget = new DropTargetExtension<>(dropTargetLayout);
  88. // the drop effect must match the allowed effect in the drag source for a successful drop
  89. dropTarget.setDropEffect(DropEffect.MOVE);
  90. // catch the drops
  91. dropTarget.addDropListener(event -> {
  92. // if the drag source is in the same UI as the target
  93. Optional<AbstractComponent> dragSource = event.getDragSourceComponent();
  94. if (dragSource.isPresent() && dragSource.get() instanceof Label) {
  95. // move the label to the layout
  96. dropTargetLayout.addComponent(dragSource.get());
  97. // get possible transfer data
  98. String message = event.getDataTransferData("text/html");
  99. if (message != null) {
  100. Notification.show("DropEvent with data transfer html: " + message);
  101. } else {
  102. // get transfer text
  103. message = event.getDataTransferText();
  104. Notification.show("DropEvent with data transfer text: " + message);
  105. }
  106. // handle possible server side drag data, if the drag source was in the same UI
  107. event.getDragData().ifPresent(data -> handleMyDragData((MyObject) data));
  108. }
  109. });
  110. ----
  111. When data is dragged over a drop target, the __v-drag-over__ class name is applied to the root element of the drop target component automatically.
  112. === Controlling When The Drop is Acceptable
  113. The __drop effect__ allows you to specify the desired drop effect, and for a succesful drop it must match the allowed effect that has been set for the drag source. Note that you can allow multiple effects, and that you should not rely on the default effect since it may vary between browsers.
  114. The __drop criteria__ allows you to determine whether the current drag data can be dropped on the drop target. It is executed on `dragenter`, `dragover` and `drop` events. The script gets the current event as a parameter named `event`. Returning `false` will prevent the drop and no drop event is fired on the server side.
  115. ////
  116. TODO Add an example of drop criteria
  117. ////
  118. === CSS Style Rules
  119. Each drop target element have an applied style name, the primary style name with `-droptarget` suffix, e.g. `v-label-droptarget`, to indicate that it is a potential target for data to be dropped onto it.
  120. When dragging data over a drop target and the drag over criteria passes, a style name is applied to indicate that the element accepts the drop. This style name is the primary style name with `-drag-center` suffix, e.g. `v-label-drag-center`.
  121. ////
  122. TODO add back when supported with new API ?
  123. [[advanced.dragndrop.external]]
  124. == Dragging Files from Outside the Browser
  125. The [classname]#DropTargetExtension# allows dragging files from outside the
  126. browser and dropping them on a target component.
  127. Dropped files are automatically uploaded to the application and can be acquired from the
  128. wrapper with [methodname]#getFiles()#. The files are represented as
  129. [classname]#Html5File# objects as defined in the inner class. You can define an
  130. upload [classname]#Receiver# to receive the content of a file to an
  131. [classname]#OutputStream#.
  132. Dragging and dropping files to browser is supported in HTML 5 and requires a
  133. compatible browser, such as Mozilla Firefox 3.6 or newer.
  134. ////
  135. [[advanced.dragndrop.mobile]]
  136. == Mobile Drag And Drop Support
  137. The HTML 5 Drag and Drop API is not yet supported by mobile browsers. To enable HTML5 DnD support on mobile devices, we have included
  138. an link:https://github.com/timruffles/ios-html5-drag-drop-shim/tree/rewrite:[external Polyfill]. Please note that this Polyfill is under the BSD 2 License.
  139. By default, the mobile DnD support is disabled, but you can enable it any time for a [classname]#UI#. Starting from the request where the support was enabled, all the added [classname]#DragSourceExtension#, [classname]#DropTargetExtension# and their subclasses will also work on mobile devices for that UI. The Polyfill is only loaded when the user is using a touch device.
  140. Drag and Drop is mutually exclusive with context click on mobile devices.
  141. [source, java]
  142. ----
  143. public class MyUI extends UI {
  144. protected void init(VaadinRequest request) {
  145. setMobileHtml5DndEnabled(true);
  146. }
  147. }
  148. ----
  149. [NOTE]
  150. ====
  151. When disabling the support, you need to also remove all the [classname]#DragSourceExtension#, [classname]#DropTargetExtension# and their subclasses that were added when the mobile DnD support was enabled.
  152. ====
  153. === CSS Style Rules
  154. The Polyfill allows you to apply custom styling to enhance the user experience on touch devices. It is important to remember that these customizations are only used when the polyfill is loaded, and not possible for desktop DnD operations.
  155. The drag image can be customized using the `dnd-poly-drag-image` class name. You must NOT wrap the class rule with e.g. `.valo`, since that is not applied to the drag image element. The following styling can be used to make the drag image opaque and "snap back" when the user did not drop to a valid dropzone:
  156. [source, css]
  157. ====
  158. .dnd-poly-drag-image {
  159. opacity: .5 !important;
  160. }
  161. .dnd-poly-drag-image.dnd-poly-snapback {
  162. transition-property: transform, -webkit-transform !important;
  163. transition-duration: 200ms !important;
  164. transition-timing-function: ease-out !important;
  165. }
  166. ====
  167. More details can be found from the link:https://github.com/timruffles/ios-html5-drag-drop-shim/tree/rewrite:[Polyfill] website.
  168. [[advanced.dragndrop.grid]]
  169. == Drag and Drop Rows in Grid
  170. It is possible to drag and drop the rows of a Grid component. This allows reordering of rows, dragging rows between different Grids, dragging rows outside of a Grid or dropping data onto rows.
  171. === Grid as a Drag Source
  172. A Grid component's rows can be made draggable by applying [classname]#GridDragSource# extension to the component. The extended Grid's rows become draggable, meaning that each row can be grabbed and moved by the mouse individually.
  173. When the Grid's selection mode is `SelectionMode.MULTI` and multiple rows are selected, it is possible to drag all the visible selected rows by grabbing one of them. However, when the grabbed row is not selected, only that one row will be dragged.
  174. [NOTE]
  175. ====
  176. It is important to note that when dragging multiple rows, only the visible selected rows will be set as dragged data.
  177. ====
  178. By default, the drag data of type `"text"` will contain the content of each column separated by a tabulator character (`"\t"`).
  179. When multiple rows are dragged, the generated data is combined into one String separated by new line characters (`"\n"`).
  180. You can override the default behaviour and provide a custom drag data for each item by setting a custom _drag data generator_ for the `"text"` type.
  181. The generator is executed for each item and returns a `String` containing the data to be transferred for that item.
  182. The following example shows how you can define the allowed drag effect and customize the drag data by setting a drag data generator.
  183. [source,java]
  184. ----
  185. Grid<Person> grid = new Grid<>();
  186. // ...
  187. GridDragSource<Person> dragSource = new GridDragSource<>(grid);
  188. // set allowed effects
  189. dragSource.setEffectAllowed(EffectAllowed.MOVE);
  190. // add a drag data generator
  191. dragSource.setDragDataGenerator("text", person -> {
  192. return person.getFirstName() + " " + person.getLastName() +
  193. "\t" + // tabulator character
  194. person.getAddress().getCity();
  195. });
  196. ----
  197. It is possible to set multiple generators with the `setDragDataGenerator(type, generator)` method.
  198. The generated data will be set as data transfer data with the given type and can then be accessed during drop from the drop event's `getDataTransferData(type)` method.
  199. The [classname]#GridDragStartEvent# is fired when dragging a row has started, and the [classname]#GridDragEndEvent# when the drag has ended, either in a drop or a cancel.
  200. [source,java]
  201. ----
  202. dragSource.addGridDragStartListener(event ->
  203. // Keep reference to the dragged items
  204. draggedItems = event.getDraggedItems()
  205. );
  206. // Add drag end listener
  207. dragSource.addGridDragEndListener(event -> {
  208. // If drop was successful, remove dragged items from source Grid
  209. if (event.getDropEffect() == DropEffect.MOVE) {
  210. ((ListDataProvider<Person>) grid.getDataProvider()).getItems()
  211. .removeAll(draggedItems);
  212. grid.getDataProvider().refreshAll();
  213. // Remove reference to dragged items
  214. draggedItems = null;
  215. }
  216. });
  217. ----
  218. The dragged rows can be accessed from both events using the `getDraggedItems()` method.
  219. ==== CSS Style Rules
  220. A drag source Grid's rows have the `v-grid-row-dragsource` and the `v-draggable` style names applied to indicate that the rows are draggable.
  221. Additionally, the style name `v-grid-row-dragged` is applied to all the dragged rows during the drag start event and removed during the drag end event.
  222. === Grid as a Drop Target
  223. To make a Grid component's rows accept a drop event, apply the [classname]#GridDropTarget# extension to the component. When creating the extension, you need to specify where the transferred data can be dropped on.
  224. [source,java]
  225. ----
  226. Grid<Person> grid = new Grid<>();
  227. // ...
  228. GridDropTarget<Person> dropTarget = new GridDropTarget<>(grid, DropMode.BETWEEN);
  229. dropTarget.setDropEffect(DropEffect.MOVE);
  230. ----
  231. The _drop mode_ specifies the behaviour of the row when an element is dragged over or dropped onto it. Use `DropMode.ON_TOP` when you want to drop elements on top of a row and `DropMode.BETWEEN` when you want to drop elements between rows. `DropMode_ON_TOP_OR_BETWEEN` allows to drop on between or top rows.
  232. The [classname]#GridDropEvent# is fired when data is dropped onto one of the Grid's rows. The following example shows how you can insert items into the Grid at the drop position. If the drag source is another Grid, you can access the generated drag data with the event's [methodname]#getDataTransferText()# method.
  233. If the drag source Grid uses a custom generator for a different type than `"text"`, you can access it's generated data using the [methodname]#getDataTransferData(type)# method. You can also check all the received data transfer data by fetching the type-to-data map with the [methodname]#getDataTransferData()# method.
  234. [source,java]
  235. ----
  236. dropTarget.addGridDropListener(event -> {
  237. // Accepting dragged items from another Grid in the same UI
  238. event.getDragSourceExtension().ifPresent(source -> {
  239. if (source instanceof GridDragSource) {
  240. // Get the target Grid's items
  241. ListDataProvider<Person> dataProvider = (ListDataProvider<Person>)
  242. event.getComponent().getDataProvider();
  243. List<Person> items = (List<Person>) dataProvider.getItems();
  244. // Calculate the target row's index
  245. int index = items.size();
  246. if (event.getDropTargetRow().isPresent()) {
  247. index = items.indexOf(event.getDropTargetRow().get()) + (
  248. event.getDropLocation() == DropLocation.BELOW ? 1 : 0);
  249. }
  250. // Add dragged items to the target Grid
  251. items.addAll(index, draggedItems);
  252. dataProvider.refreshAll();
  253. // Show the dropped data
  254. Notification.show("Dropped row data: " + event.getDataTransferText());
  255. }
  256. });
  257. });
  258. ----
  259. The _drop location_ property in the [classname]#GridDropEvent# specifies the dropped location in relative to grid row the drop happened on and depends on the used [classname]#DropMode#. When the drop happened on top of a row, the possible options for the location are `ON_TOP`, `ABOVE` and `BELOW`.
  260. If the grid is empty or if the drop was on empty space after the last row in grid, and the [classname]#DropMode.ON_TOP# was used, then the drop location `EMPTY` will be used. If the drop modes [classname]#DropMode.BETWEEN# or [classname]#DropMode.ON_TOP_OR_BETWEEN# are used, then the location can be `EMPTY` only when the grid was empty; otherwise the drop happened `BELOW` the last visible row. When the drop location is `EMPTY`, the [methodname]#getDropTargetRow# method will also return an empty optional.
  261. When dropping on top of the grid's header or footer, the drop location will be `EMPTY` if there are no rows in the grid or if [classname]#DropMode.ON_TOP# was used. If there are rows in the grid, dropping on top of the header will set the drop location to `ABOVE` and the dropped row will be the first currently visible row in grid. Similarly, if dropping on top of the footer, the drop location will be `BELOW` and the dropped row will be the last visible row in the grid.
  262. ==== CSS Style Rules
  263. A drop target Grid's body has the style name `v-grid-body-droptarget` to indicate that it is a potential target for data to be dropped.
  264. When dragging data over a drop target Grid's row, depending on the drop mode and the mouse position relative to the row, a style name is applied to the row or to the grid body to indicate the drop location.
  265. When dragging on top of a row, `v-grid-row-drag-center` indicates ON_TOP, `v-grid-row-drag-top` indicates ABOVE and `v-grid-row-drag-bottom` indicates BELOW locations. When dragging on top of an empty grid, or when the drop location is ON_TOP and dragged below the last row in grid (and there is empty space visible), the `v-grid-body-body-drag-top` style is applied to the `v-grid-tablewrapper` element which surrounds the grid header, body and footer.
  266. (((range="endofrange", startref="term.advanced.dragndrop")))
  267. == Drag and Drop Files
  268. Files can be uploaded to the server by dropping them onto a file drop target. To make a component a file drop target, apply the [classname]#FileDropTarget# extension to it by creating a new instance and passing the component as first constructor parameter to it.
  269. You can handle the dropped files with the `FileDropHandler` that you add as the second constructor parameter. The [classname]#FileDropEvent#, received by the handler, contains information about the dropped files such as file name, file size and mime type.
  270. In the handler you can decide if you would like to upload each of the dropped files.
  271. To start uploading a file, set a `StreamVariable` to it. The stream variable provides an output stream where the file will be written and has callback methods for all the stages of the upload process.
  272. [source,java]
  273. ----
  274. Label dropArea = new Label("Drop files here");
  275. FileDropTarget<Label> dropTarget = new FileDropTarget<>(dropArea, event -> {
  276. List<Html5File> files = event.getFiles();
  277. files.forEach(file -> {
  278. // Max 1 MB files are uploaded
  279. if (file.getFileSize() <= 1024 * 1024) {
  280. file.setStreamVariable(new StreamVariable() {
  281. // Output stream to write the file to
  282. @Override
  283. public OutputStream getOutputStream() {
  284. return new FileOutputStream("/path/to/files/"
  285. + file.getFileName());
  286. }
  287. // Returns whether onProgress() is called during upload
  288. @Override
  289. public boolean listenProgress() {
  290. return true;
  291. }
  292. // Called periodically during upload
  293. @Override
  294. public void onProgress(StreamingProgressEvent event) {
  295. Notification.show("Progress, bytesReceived="
  296. + event.getBytesReceived());
  297. }
  298. // Called when upload started
  299. @Override
  300. public void streamingStarted(StreamingStartEvent event) {
  301. Notification.show("Stream started, fileName="
  302. + event.getFileName());
  303. }
  304. // Called when upload finished
  305. @Override
  306. public void streamingFinished(StreamingEndEvent event) {
  307. Notification.show("Stream finished, fileName="
  308. + event.getFileName());
  309. }
  310. // Called when upload failed
  311. @Override
  312. public void streamingFailed(StreamingErrorEvent event) {
  313. Notification.show("Stream failed, fileName="
  314. + event.getFileName());
  315. }
  316. });
  317. }
  318. }
  319. });
  320. ----