jsTree Node Expand/Collapse - jstree

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");
});

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();
}
});
},

How can I select :last-child in d3.js?

I need to manipulate the text elements of the first and last tick of an axis to bring them more towards the center.
I am trying to select them, one at the time, with something like svg.select('.tick:last-child text') but it doesn't work. I'd then apply .transform('translate(4,0)')...
Am I doing something wrong? How can I achieve this?
One thing you could do is to create custom sub-selections by adding methods to d3.selection.prototype. You could create a selection.first() method that selects the first item in a selection, and a selection.last() method that selects the last item. For instance:
d3.selection.prototype.first = function() {
return d3.select(this[0][0]);
};
d3.selection.prototype.last = function() {
var last = this.size() - 1;
return d3.select(this[0][last]);
};
This would let you do the following:
var tickLabels = svg.selectAll('.tick text');
tickLabels.first()
.attr('transform','translate(4,0)');
tickLabels.last()
.attr('transform','translate(-4,0)');
Of course, you need to make sure that you only have one axis if you do it that way. Otherwise, specify the axis in your initial selection:
var tickLabels = svg.selectAll('.axis.x .tick text');
HERE is an example.
Here's the cleanest method I've found:
g.selectAll(".tick:first-of-type text").remove();
g.selectAll(".tick:last-of-type text").remove();
As google brought me here, I also want to add a cleaner method to what Adam Grey wrote.
Sometimes you just want to do it without taking a reference of selectAll .
svg.selectAll('.gridlines').filter(function(d, i,list) {
return i === list.length - 1;
}).attr('display', 'none');
the 3rd parameter of the filter function gives you the selected List of elements.
They don't exist in d3 specifically, but you can use the .firstChild and .lastChild methods on a node.
You can first select all of the parents of the node, and then operate within the scope of a .each() method, like so:
d3.selectAll('.myParentElements').each(function(d,i){
var firstChild = this.firstChild,
lastChild = this.lastChild;
//Do stuff with first and last child
});
Within the scope of .each(), this refers to the individual node, which is not wrapped by a d3 selection, so all of the standard methods on a node are available.
Using .filter() with a function also works selection.filter(filter) :
var gridlines;
gridlines = svg.selectAll('.gridlines');
gridlines.filter(function(d, i) {
return i === gridlines.size() - 1;
}).attr('display', 'none');
It's for D3.js v4
d3.selection.prototype.first = function() {
return d3.select(
this.nodes()[0]
);
};
d3.selection.prototype.last = function() {
return d3.select(
this.nodes()[this.size() - 1]
);
};
Example:
var lines = svg.selectAll('line');
lines.first()
.attr('transform','translate(4,0)');
lines.last()
.attr('transform','translate(-4,0)');
Here is another, even though I used Fered's solution for a problem I met.
d3.select(d3.selectAll('*').nodes().reverse()[0])

telerik kendo treeview - prevent dragging outside of parent

I'm trying to prevent the dragging and dropping of nodes outside of the parent node ("LLCA") with no luck.
Any suggestions?
Image of Treeview
I ended up getting it to work using your code below:
function onDrop(e) {
var dst = e.destinationNode;
var first = $('.k-item:first');
var pos = e.dropPosition;
if (dst && dst.uid === first.uid && pos !== "over") {
e.setValid(false);
}
}
Lets define the treeview:
var tree = $("#tree").kendoTreeView({
dataSource :content,
dragAndDrop:true
}).data("kendoTreeView");
What I'm going to do is add a drop callback where I will control that:
We are not dropping outside the tree
We are not dropping before or after the first node of the tree
The definition of the tree would be:
var tree = $("#tree").kendoTreeView({
dataSource :content,
dragAndDrop:true,
drop :function (ev) {
var dst = tree.dataItem(ev.destinationNode);
var first = tree.dataItem(".k-item:first");
var pos = ev.dropPosition;
if (dst && dst.uid === first.uid && pos !== "over") {
console.log("invalid");
ev.setValid(false);
}
}
}).data("kendoTreeView");
Check http://docs.kendoui.com/api/web/treeview#drop for information on drop event.
Because I cannot comment on an answer, I will write my own.
User Mithrilhall asked about MVC wrappers, also the top answer only prevents movement to the root node.
I will attempt to answer both Mithrilhall and provide an example where you can only move a child within the context of its parent. To put it another way, to only allow children of any parent to change their order within the parent.
Firstly, for MithrilHall, this is how you get to the events in MVC.
#(Html.Kendo().TreeView()
.Name("ourTreeView")
.Events(e => e.Drop("treeViewDrop"))
There are other events in treeview, you can take a gander for yourself. The argument is the name of a javascript function. Here is an example javascript function for this MVC wrapper to prevent children from moving outside of their parent, but allowing them to still move within the parent.
<script type="text/javascript">
function treeViewDrop(dropEvent) {
var treeView = $("#ourTreeView").data("kendoTreeView");
var destination = treeView.dataItem(dropEvent.destinationNode);
var source = treeView.dataItem(dropEvent.sourceNode);
if (!(destination && destination.parentID == source.parentID)) {
dropEvent.setValid(false);
}
}
</script>
I had a parentID field modeled in my datasource. You could accomplish this in many ways. The dataItem method returns a kendo treeview item, so it has all of your modeled fields in it.
Also understand, this solution does not change the widget to show an X when you are moving to a place you cannot drop to. This is another problem with another solution.
I hope this helps, good luck!

DOM manipulation with PhantomJS

I am using PhantomJS to create screenshots from arbitrary URLs. Before the screenshot is taken, I want to manipulate the page DOM to remove all drop-down menus, as PhantomJS renders them incorrectly in the top left-hand corner of the page (a known Phantom issue.)
I have a simple DOM script to do this with:
var selects = document.getElementsByTagName('select');
for (var i=0; i < selects.length; i++) {
document.getElementsByTagName('select')[i].style.visibility="hidden";
}
This has been tested and works fine as stand-alone Javascript. It doesn't however work inside the PhantomJS code I am using to collect the screenshots (last part shown):
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
window.setTimeout(function () {
var selects = document.getElementsByTagName('select');
for (var i=0; i < selects.length; i++) {
document.getElementsByTagName('select')[i].style.visibility="hidden";
}
page.render(output);
phantom.exit();
}, 200);
}
});
Some pages are still rendering with a select box in the wrong place. I'd appreciate help either solving the original PhantomJS rendering bug or hiding the drop-down menus in the DOM. Thanks.
Run it in the right context, i.e. inside the page with page.evaluate. There are many examples included with PhantomJS which demonstrate this, e.g. useragent.js.
This code doesn't work?
I used your cached selects variable in the for loop instead of re-selecting the elements from the DOM to improve performance.
var selects = document.getElementsByTagName('select');
for (var i=0; i < selects.length; i++) {
selects[i].style.visibility="hidden";
}

What is the proper way in OpenLayers (OSM) to trigger a popup for a feature?

I have the feature ID, I can grab the marker layer on GeoRSS loadend, but I'm still not sure how to cause the popup to appear programmatically.
I'll create the popup on demand if that's necessary, but it seems as though I should be able to get the id of the marker as drawn on the map and call some event on that. I've tried using jQuery and calling the $(marker-id).click() event on the map elements, but that doesn't seem to be working. What am I missing?
Since I was asked for code, and since I presumed it to be boilerplate, here's where I am so far:
map = new OpenLayers.Map('myMap');
map.addLayer(new OpenLayers.Layer.OSM());
map.addLayer(new OpenLayers.Layer.GeoRSS(name,url));
//I've done some stuff as well in re: projections and centering and
//setting extents, but those really don't pertain to this question.
Elsewhere I've done a bit of jQuery templating and built me a nice list of all the points that are being shown on the map. I know how to do a callback from the layer loadend and get the layer object, I know how to retrieve my layer out of the map manually, I know how to iter over the layers collection and find my layer. So I can grab any of those details about the popup, but I still don't know how to go about using the built-in methods of the DOM or of this API to make it as easy as element.click() which is what I would prefer to do.
You don't have to click the feature to open a popup.
First you need a reference to the feature from the feature id. I would do that in the loadend event of the GeoRSS layer, using the markers property on the layer.
Assuming you have a reference to your feature, I would write a method which handles the automatic popup:
var popups = {}; // to be able to handle them later
function addPopup(feature) {
var text = getHtmlContent(feature); // handle the content in a separate function.
var popupId = evt.xy.x + "," + evt.xy.y;
var popup = popups[popupId];
if (!popup || !popup.map) {
popup = new OpenLayers.Popup.Anchored(
popupId,
feature.lonlat,
null,
" ",
null,
true,
function(evt) {
delete popups[this.id];
this.hide();
OpenLayers.Event.stop(evt);
}
);
popup.autoSize = true;
popup.useInlineStyles = false;
popups[popupId] = popup;
feature.layer.map.addPopup(popup, true);
}
popup.setContentHTML(popup.contentHTML + text);
popup.show();
}
fwiw I finally came back to this and did something entirely different, but his answer was a good one.
//I have a list of boxes that contain the information on the map (think google maps)
$('.paginatedItem').live('mouseenter', onFeatureSelected).live('mouseleave',onFeatureUnselected);
function onFeatureSelected(event) {
// I stuff the lookup attribute (I'm lazy) into a global
// a global, because there can be only one
hoveredItem = $(this).attr('lookup');
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
}
function onFeatureUnselected(event) {
/* Do something here to indicate the onhover */
// find the layer pagination id
var feature = findFeatureById(hoveredItem);
if (feature) {
// use the pagination id to find the event, and then trigger the click for that event to show the popup
// also, pass a null event, since we don't necessarily have one.
feature.marker.events.listeners.click[0].func.call(feature, event)
}
/* Do something here to stop the indication of the onhover */
hoveredItem = null;
}
function findFeatureById(featureId) {
for (var key in map.layers) {
var layer = map.layers[key];
if (layer.hasOwnProperty('features')) {
for (var key1 in layer.features) {
var feature = layer.features[key1];
if (feature.hasOwnProperty('id') && feature.id == featureId) {
return feature;
}
}
}
}
return null;
}
also note that I keep map as a global so I don't have to reacquire it everytime I want to use it