Wanted: Directions/ideas for a custom tree-to-tree drag'n'drop implementation in ExtJS - drag-and-drop

I need some combined functionality regarding drag'n'drop between two trees in ExtJS.
The first required feature is very simple and is just the builtin drag'n'drop features isolated to a single tree only.
The second required feature is that I wan't the user to be able to drag a node from the left tree and drop it at any node in the right tree.
The action should not remove the node from the left tree, thus creating the possibility of dragging the same node from the left tree to multiple places in the right tree.
My question is: Which approach should I take to combine these two functionalities, utilizing the existing possibilities in the TreePanel object without inventing the wheel again? I am not looking for a complete solution (it would be nice though ;-) ), but rather how to handle drag/drop-zones, events and so on.

Okay. I have been thinking about this some time now, and the following approach seems to work for me :)
I have configured the left tree as this:
listeners:
{
beforenodedrop: function (dropEvent) {
// Does this node come from the right tree?
if (dropEvent.source.tree.id !== dropEvent.tree.id) {
// The node should be discarded.
dropEvent.dropNode.parentNode.removeChild(dropEvent.dropNode, true);
// The node has been discarded, return drop succeeded.
dropEvent.dropStatus = true;
return false;
}
return true;
},
nodedragover: function (dragevent) {
// If the node comes from the right tree, it is allowed to be dropped here.
if (dragevent.source.tree.id !== dragevent.tree.id) {
return true;
}
// A node from this tree is not allowed to be dropped.
return false;
}
}
The right tree is configured like this:
listeners:
{
beforenodedrop: function (dropEvent) {
// Does this node come from the left tree?
if (dropEvent.source.tree.id !== dropEvent.tree.id) {
// The node should be cloned and inserted in the right tree.
// Copy the node.
var node = dropEvent.dropNode; // the node that was dropped
var nodeCopy = new Ext.tree.TreeNode( // copy it
Ext.apply({}, node.attributes)
);
// Match the id's.
nodeCopy.id = Ext.id(null,'newnode') + '_' + node.id;
// Find the right place to put it.
if (dropEvent.target.parentNode === dropEvent.tree.getRootNode()) {
// The node is placed on a folder, thus drop it there.
dropEvent.target.appendChild(nodeCopy);
} else {
// The node is placed inside a folder, thus place it in there.
dropEvent.target.parentNode.appendChild(nodeCopy);
}
// The node has been dropped, return okay and stop further process.
dropEvent.dropStatus = true;
return false;
}
// Just use the normal builtin drag and drop.
return true;
}
}
Both trees has been set to enable Drag'n'Drop:
enableDD: true
All leaf nodes have the following configuration:
allowDrop: true,
draggable: true
All folders are set to:
allowDrop: true,
draggable: false
The conclusion is, that I have chosen to override some of the builtin drag'n'drop methods in the treepanel while still maintaining the builtin functionality.

Related

Automatically load node children in fancytree

I have a fancytree implementation where each parent node has a child node that can be selected. After a user selects specific children, she is able to save her selections and settings so that she can come back to it later.
I'm able to do all of this, except for when I do an initial load of previously saved data. What I need to do is identify the nodes that need to be opened (and its children selected), and have Fancytree open those nodes and select the children.
I'm using lazy loading, and when the lazyloading event fires I'm able to check to see if the child needs to be selected and do so as needed. What I'd like to be able to do is programmatically do the same thing so that all the previously selected children are loaded and selected upon load. Currently, I'm attempting this in this way:
function getMultipleFieldsNoReset(element,selectedFieldsArray) {
var fieldCreator = element.value;
var tree = $("#multipleFields").fancytree("getTree");
var treeOptions = {
url: "urltogetdata",
type: "POST",
data: {
id: fieldCreator
},
dataType: "json"
};
tree.reload(treeOptions);
for (var i = 0, len = selectedFieldsArray.length; i < len; i++) {
var valueAry = selectedFieldsArray[i].split("-");
var growerNode = valueAry[0];
var farmNode = valueAry[1];
var fieldNode = valueAry[2];
var node = tree.getNodeByKey(growerNode);
console.log(node);
}
}
My problem is that tree.getNodeByKey(growerNode) never finds the node, even though I'm able to find the node in the console after this runs. It seems like the parent nodes aren't loaded yet, which can cause this issue, but I'm not certain where I can set a complete function. Where can I do this? Or even better, is there a cleaner way to handle this?
The OP / Fletchius has got solution on this issue and below is the answer of it. I achieved it in some different way but event loadChildren is the same. from which we both found solution. Just I'm loading those nodes which are selected nodes and lazy true meaning there are children down after this node. And only lazy=true can be useful for this.load(); explicit event.
loadChildren:function(event, data){
var node = data.node;
$(node.children).each(function(){
if(this.selected && this.lazy)
{
this.load();
}
});
},

Dragula Copy and removeOnSpill

I'm trying to use the Dragula Drag & Drop library to Clone elements into a target container AND allow the user to remove cloned elements from the Target Container by drag & dropping them outside of the target container (spilling).
Using the examples provided I have this:
dragula([$('left-copy-1tomany'), $('right-copy-1tomany')], {
copy: function (el, source) {
return source === $('left-copy-1tomany');
},
accepts: function (el, target) {
return target !== $('left-copy-1tomany');
}
});
dragula([$('right-copy-1tomany')], { removeOnSpill: true });
Which does not work - it seems that 'removeOnSpill' simply doesn't work if the container accepts a copy.
Does anybody know what I am not doing, doing wrong or if there is a work-around?
TIA!
I came here after looking for a while for a solution to a similar issue using the ng2-dragula for angular2.
dragulaService.setOptions('wallet-bag', {
removeOnSpill: (el: Element, source: Element): boolean => {
return source.id === 'wallet';
},
copySortSource: false,
copy: (el: Element, source: Element): boolean => {
return source.id !== 'wallet';
},
accepts: (el: Element, target: Element, source: Element, sibling: Element): boolean => {
return !el.contains(target) && target.id === 'wallet';
}
});
I've got 4 divs that can all drag into one which has the id of wallet
They are all part of the wallet-bag
using this code, they can all copy into the wallet, not copy between each other, and you can remove them from the wallet using the spill but not from the others.
I'm posting my solution as it may also help someone.
Ok, so the general answer I came trough is that:
you can have 'removeOnSpill' working - even with 'copy' option set to true - , only if you set the 'copy' option applying ONLY when the 'source' container IS NOT the one you are trying to remove elements from.
In my case I had 3 containers from which I can drag in another one called 'to_drop_to'.
Those container have all id starting with 'drag'.
So I set:
var containers = [document.querySelector('#drag1'),
document.querySelector('#drag2'),
document.querySelector('#drag3'),
document.querySelector('#to_drop_to')];
dragula(containers, {
accepts: function (el, target, source, sibling) {
return $(target).attr('id')=="gadget_drop"; // elements can be dropped only in 'to_drop_to' container
},
copy: function(el,source){
return $(source).attr('id').match('drag'); //elements are copied only if they are not already copied ones. That enables the 'removeOnSpill' to work
},
removeOnSpill: true
}
and this worked for me.
Hope it helps.
From the dragula documentation
options.removeOnSpill
By default, spilling an element outside of any containers will move
the element back to the drop position previewed by the feedback
shadow. Setting removeOnSpill to true will ensure elements dropped
outside of any approved containers are removed from the DOM. Note that
remove events won't fire if copy is set to true.

jsTree Node Expand/Collapse

I ran into the excellent jstree jQuery UI plug in this morning. In a word - great! It is easy to use, easy to style & does what it says on the box. The one thing I have not yet been able to figure out is this - in my app I want to ensure that only one node is expanded at any given time. i.e. when the user clicks on the + button and expands a node, any previously expanded node should silently be collapsed. I need to do this in part to prevent the container div for a rather lengthy tree view from creating an ugly scrollbar on overflow and also to avoid "choice overload" for the user.
I imagine that there is some way of doing this but the good but rather terse jstree documentation has not helped me to identify the right way to do this. I would much appreciate any help.
jsTree is great but its documentation is rather dense. I eventually figured it out so here is the solution for anyone running into this thread.
Firstly, you need to bind the open_node event to the tree in question. Something along the lines of
$("tree").jstree({"themes":objTheme,"plugins":arrPlugins,"core":objCore}).
bind("open_node.jstree",function(event,data){closeOld(data)});
i.e. you configure the treeview instance and then bind the open_node event. Here I am calling the closeOld function to do the job I require - close any other node that might be open. The function goes like so
function closeOld(data)
{
var nn = data.rslt.obj;
var thisLvl = nn;
var levels = new Array();
var iex = 0;
while (-1 != thisLvl)
{
levels.push(thisLvl);
thisLvl = data.inst._get_parent(thisLvl);
iex++;
}
if (0 < ignoreExp)
{
ignoreExp--;
return;
}
$("#divElements").jstree("close_all");
ignoreExp = iex;
var len = levels.length - 1;
for (var i=len;i >=0;i--) $('#divElements').jstree('open_node',levels[i]);
}
This will correctly handle the folding of all other nodes irrespective of the nesting level of the node that has just been expanded.
A brief explanation of the steps involved
First we step back up the treeview until we reach a top level node (-1 in jstree speak) making sure that we record every ancestor node encountered in the process in the array levels
Next we collapse all the nodes in the treeview
We are now going to re-expand all of the nodees in the levels array. Whilst doing so we do not want this code to execute again. To stop that from happening we set the global ignoreEx variable to the number of nodes in levels
Finally, we step through the nodes in levels and expand each one of them
The above answer will construct tree again and again.
The below code will open the node and collapse which are already opened and it does not construct tree again.
.bind("open_node.jstree",function(event,data){
closeOld(data);
});
and closeOld function contains:
function closeOld(data)
{
if($.inArray(data.node.id, myArray)==-1){
myArray.push(data.node.id);
if(myArray.length!=1){
var arr =data.node.id+","+data.node.parents;
var res = arr.split(",");
var parentArray = new Array();
var len = myArray.length-1;
for (i = 0; i < res.length; i++) {
parentArray.push(res[i]);
}
for (var i=len;i >=0;i--){
var index = $.inArray(myArray[i], parentArray);
if(index==-1){
if(data.node.id!=myArray[i]){
$('#jstree').jstree('close_node',myArray[i]);
delete myArray[i];
}
}
}
}
}
Yet another example for jstree 3.3.2.
It uses underscore lib, feel free to adapt solution to jquery or vanillla js.
$(function () {
var tree = $('#tree');
tree.on('before_open.jstree', function (e, data) {
var remained_ids = _.union(data.node.id, data.node.parents);
var $tree = $(this);
_.each(
$tree
.jstree()
.get_json($tree, {flat: true}),
function (n) {
if (
n.state.opened &&
_.indexOf(remained_ids, n.id) == -1
) {
grid.jstree('close_node', n.id);
}
}
);
});
tree.jstree();
});
I achieved that by just using the event "before_open" and close all nodes, my tree had just one level tho, not sure if thats what you need.
$('#dtree').on('before_open.jstree', function(e, data){
$("#dtree").jstree("close_all");
});

jstree move, drag and drop

I want to implement the move functionality for a node in jstree. Is it the move that needs to be implemented or the drag and drop? Also, it would be nice to have working code for binding the container to event and the event code.
You only need to use the dnd plugin if you don't need to enforce any move rules(don't allow certain nodes to be moved to other nodes etc)
If you need to enforce move rules, you can add the crrm plugin.
See the Reorder only demo of the dnd pluign documentation for an example of this. The documentation is very poor, so you will have to use the developer tool on your browser to see what the properties of the parameter for the check_move callback are. For the example in the documentation, m.o refers to your dragged node and m.r refers to your destination node.
You will also likely need to be notified when a node is moved, so bind to the move_node.jstree event when you initialize the tree:
$("#treeHost").jstree({
// ...
}).bind("move_node.jstree", function (e, data) {
// data.rslt.o is a list of objects that were moved
// Inspect data using your fav dev tools to see what the properties are
});
$("#demo1").jstree({
....
.bind("move_node.jstree", function (e, data) {
/*
requires crrm plugin
.o - the node being moved
.r - the reference node in the move
.ot - the origin tree instance
.rt - the reference tree instance
.p - the position to move to (may be a string - "last", "first", etc)
.cp - the calculated position to move to (always a number)
.np - the new parent
.oc - the original node (if there was a copy)
.cy - boolen indicating if the move was a copy
.cr - same as np, but if a root node is created this is -1
.op - the former parent
.or - the node that was previously in the position of the moved node */
var nodeType = $(data.rslt.o).attr("rel");
var parentType = $(data.rslt.np).attr("rel");
if (nodeType && parentType) {
// TODO!
}
})
});
The above approaches do not work with the latest versions of jstree (3.3.7 as of today).
The first line of Bojin's answer still holds true. To implement rules, you can use core.check_callback or possibly, the types plugin; the crrm plugin doesn't exist anymore. Bind to move_node.jstree to perform some action on completion of move (drop). By default, the dnd plugin allows re-ordering (dropping between two nodes) and copying (Ctrl + drag), in addition to moving a node. The code snippet below shows how to disable these additional behaviors.
$('#treeElement').jstree({
'core': {
'check_callback': CheckOperation,
...
},
'plugins': ['dnd']
})
.bind("move_node.jstree", function(e, data) {
//data.node was dragged and dropped on data.parent
});
function CheckOperation(operation, node, parent, position, more) {
if (operation == "move_node") {
if (more && more.dnd && more.pos !== "i") { // disallow re-ordering
return false;
}
... more rules if needed ...
else {
return true;
}
}
else if (operation == "copy_node") {
return false;
}
return true;
}

JsTree with dnd plugin, always copy

I have 2 trees using jsTree and dnd plugin.
I want that each drag operation to be a copy instead of a move.
There is a "copy_modifier" which works Ok when pressing a modifier key, but I want copy to be the default behavior without the modifier.
Any ideas?
Thanks,
Adrian
Found a solution on http://groups.google.com/group/jstree
I added the following section when configuring jsTree:
"crrm": {
"move": { "always_copy": "multitree" }
}
Hope this helps,
Adrian
another solution for the new version. it works, but not fully tested.
"core": {
"check_callback": function (operation, node, node_parent, node_position, more) {
if (more) {
if (more.is_multi) {
more.origin.settings.dnd.always_copy = true;
} else {
more.origin.settings.dnd.always_copy = false;
}
}
return true;
}
}
Adrian's solution won't work with the new versions.
There's that dnd plugins always copy flag
dnd.always_copy
Setting this flag will make all drag and drops copy operations instead of move. But if you are looking for a solution where you need internal tree elements to be moved on dnd but inter tree dnds to be copies than here's a hack:
Keep a global variable flag on your page
Handle copy_node.jstree events and update your global flag from
data.is_multi (data is the second arg of the event function)
Implement check_callback function and if operation is delete_node and your flag is set unset your flag and return false, preventing deletion from the dnd.