Show only checked nodes and parents of it in jstree - jstree

I have to show only selected nodes and parents, and hide rest nodes.
There is no get_unchecked in current documentation. My json format is huge so taking it in string and formatting and reloading tree will be inefficient.
Is there a way to get all unchecked nodes and hide it?
if there is i can check all parent node of current checked node and then just hide all unchecked nodes, but i cannot find any method to retrive all unchecked nodes.

You can do it by:
getting all selected nodes along with the parents
going over all nodes and seeing if a node is not selected, then hiding it
Check code below and demo - codepen.
var $tree = $("#myTree").jstree(),
nodesSelected = $('#myTree').jstree('get_checked', true),
nodeIdsToStay = [];
nodesSelected.forEach(function(node) {
var path = $tree.get_path(node, false, true);
path.forEach(function(n) {
if (nodeIdsToStay.indexOf(n) === -1) {
nodeIdsToStay.push(n);
}
})
})
$('#myTree').find('li').each(function() {
if (nodeIdsToStay.indexOf(this.id) === -1) {
$(this).hide();
}
})

Work around for the question i made.
$('#jstree_demo_div').on('loaded.jstree', function(e, data) {
console.log("loaded");
checked_ids = $('#jstree_demo_div').jstree('get_selected', true);
$("#jstree_demo_div").jstree('select_all');
$.each(checked_ids, function(index, value) {
$("#jstree_demo_div").jstree('deselect_node', value);
uiParentsShow(value);
});
checked_ids = $('#jstree_demo_div').jstree('get_selected', true);
$.each(checked_ids, function(index, value) {
$("#jstree_demo_div").jstree('hide_node', value);
});
});
function uiParentsShow(node) {
try {
var parent = $("#jstree_demo_div").jstree('get_parent', node);
$("#jstree_demo_div").jstree('deselect_node', parent);
if (parent != '#') {
uiParentsShow1(parent);
}
} catch (err) {
console.log('Error in uiGetParents' + err);
}
}
Steps:
Step 1: Selecting All the elements
Step 2: Deselecting the checked node and the parent of checked node
Step 3: Hide Selected Nodes

From the response above I was able to create this function that filters the Treeview based on a node attribute value. (Replace '
$('#jstree').find('li').each(function () {
if ($("#" + this.id).attr("tag") == "<MYTAG>") {
$(this).hide();
}
else {
$(this).show();
}
})

I wrote another code maybe help someone.
var value = $(this).val();
if (value == "all") {
$('#permissions').jstree("show_all")
return;
}
checkedNodes = $('#permissions').jstree("get_checked", true);
if (value == "granted") {
$('#permissions').jstree("hide_all")
checkedNodes.forEach(function (node) {
$('#permissions').jstree("show_node", node.parent);
$('#permissions').jstree("show_node", node);
});
}
else if ("notgranted") {
$('#permissions').jstree("show_all")
checkedNodes.forEach(function (node) {
$('#permissions').jstree("hide_node", node);
});
}

Related

Amchart annotations . Returning back to normal mode from annotations mode

I am using external buttons for am charts export. when i enter into annotations mode and do export, the chart gets exported with annotations. But when the chart gets reloaded , the annotations mode does not revert back.
Could somebody let me know how to go back from annotations to normal mode.
if (chart.export.drawing.buffer.enabled === true) {
// Exporting the annotated chart with out "
//chart.export.capture"
chart.export.toPNG({}, function (data) {
chartimage.postImageData(data, chart_image_name)
});
} else {
chart.export.capture({
// action: "draw"
}, function () {
this.toPNG({
}, function (data) {
images.push({
"image": data,
"fit": [523.28, 769.89]
});
pending--;
if (pending === 0) {
chart.export.toPNG({
content: images
}, function (data) {
chartimage.postImageData(data, chart_image_name)
});
}
});
});
}
}
To exit from Annotation mode, simply use Export plugin's internal API method done():
chart["export"].drawing.handler.done();
BTW, export keyword is reserved and will result in errors on some browsers. It's better to access Export instance via named key: chart["export"].toPNG() versus chart.export.toPNG().
Please find the workaround below..
First capture the events for set and cancel annotations using menu reviewer
menuReviver: function (item, li) {
if (item.format === "XLSX" || item.format === "JSON") {
li.style.display = "none";
}
$(li).click(function () {
if (item.action == "draw") {
$("#chart_annotations").val(1);
}
if (item.action == "cancel") {
$("#chart_annotations").val(0);
}
});
return li;
}
Now while exporting the chart image use $("#chart_annotations").val() value as a
flag whether to export annotated chart or a normal chart. Please find the code below...
if (window.fabric) {
if ($("#chart_annotations").val() == 1) {
chart.export.toPNG({}, function (data) {
chartimage.postImageData(data, chart_image_name)
});
} else {
chart.export.capture({
//action: "change"
}, function () {
this.toPNG({
}, function (data) {
images.push({
"image": data,
"fit": [523.28, 769.89]
});
pending--;
if (pending === 0) {
chart.export.toPNG({
content: images
}, function (data) {
//post the image data using ajax
chartimage.postImageData(data, chart_image_name)
});
}
});
});
}

Handling tab for lists in Draft.js

I have a wrapper around the Editor provided by Draft.js, and I would like to get the tab/shift-tab keys working like they should for the UL and OL. I have the following methods defined:
_onChange(editorState) {
this.setState({editorState});
if (this.props.onChange) {
this.props.onChange(
new CustomEvent('chimpeditor_update',
{
detail: stateToHTML(editorState.getCurrentContent())
})
);
}
}
_onTab(event) {
console.log('onTab');
this._onChange(RichUtils.onTab(event, this.state.editorState, 6));
}
Here I have a method, _onTab, which is connected to the Editor.onTab, where I call RichUtil.onTab(), which I assume returns the updated EditorState, which I then pass to a generic method that updates the EditorState and calls some callbacks. But, when I hit tab or shift-tab, nothing happens at all.
So this came up while implementing with React Hooks, and a google search had this answer as the #2 result.
I believe the code OP has is correct, and I was seeing "nothing happening" as well. The problem turned out to be not including the Draft.css styles.
import 'draft-js/dist/Draft.css'
import { Editor, RichUtils, getDefaultKeyBinding } from 'draft-js'
handleEditorChange = editorState => this.setState({ editorState })
handleKeyBindings = e => {
const { editorState } = this.state
if (e.keyCode === 9) {
const newEditorState = RichUtils.onTab(e, editorState, 6 /* maxDepth */)
if (newEditorState !== editorState) {
this.handleEditorChange(newEditorState)
}
return
}
return getDefaultKeyBinding(e)
}
render() {
return <Editor onTab={this.handleKeyBindings} />
}
The following example will inject \t into the current location, and update the state accordingly.
function custKeyBindingFn(event) {
if (event.keyCode === 9) {
let newContentState = Modifier.replaceText(
editorState.getCurrentContent(),
editorState.getSelection(),
'\t'
);
setEditorState(EditorState.push(editorState, newContentState, 'insert-characters'));
event.preventDefault(); // For good measure. (?)
return null;
}
return getDefaultKeyBinding(event);
}

With Chrome FileSystem, let the user choose a Directory, load files inside. And save files in that directory without prompting again

I could not found any examples with this scenario so here we go:
I want the user choose a directory, load all files inside it, change them, and save this file overriding it or saving a new file in that same directory without asking where he want to save.
I don't know how to list the files of the directory
I don't know how to save a file in a directory without prompting the filechooser window
I believe it is possible because I see something similar here (last paragraph):
http://www.developer.com/lang/using-the-file-api-outside-the-sandbox-in-chrome-packaged-apps.html
Any answer will be appreciated, Thank you
EDIT: Thanks to Chris Johnsen for giving me this great answer:
var fileHandler = function() {
var _entry = null;
this.open = function(cb) {
chrome.fileSystem.chooseEntry({
type: 'openDirectory'
}, function(dirEntry) {
if (!dirEntry || !dirEntry.isDirectory) {
cb && cb(null);
return;
}
_entry = dirEntry;
listDir(_entry, cb);
});
};
this.save = function(filename, source) {
chrome.fileSystem.getWritableEntry(_entry, function(entry) {
entry.getFile(filename, {
create: true
}, function(entry) {
entry.createWriter(function(writer) {
writer.onwrite = function() {
writer.onwrite = null;
writer.truncate(writer.position);
};
writer.write(new Blob([source], {
type: 'text/javascript'
}));
});
});
});
};
this.saveAs = function(filename, source) {
chrome.fileSystem.chooseEntry({
type: 'openDirectory'
}, function(entry) {
chrome.fileSystem.getWritableEntry(entry, function(entry) {
entry.getFile(filename, {
create: true
}, function(entry) {
entry.createWriter(function(writer) {
writer.onwrite = function() {
writer.onwrite = null;
writer.truncate(writer.position);
};
writer.write(new Blob([source], {
type: 'text/javascript'
}));
});
});
});
});
};
var listDir = function(dirent, cb, listing) {
if (listing === undefined) {
listing = [];
}
var reader = dirent.createReader();
var read_some = reader.readEntries.bind(reader, function(ents) {
if (ents.length === 0) {
return cb && cb(listing);
}
var process_some = function(ents, i) {
for (; i < ents.length; i++) {
listing.push(ents[i]);
if (ents[i].isDirectory) {
return listDir(ents[i], process_some.bind(null, ents, i + 1), listing);
}
}
read_some();
};
process_some(ents, 0);
}, function() {
console.error('error reading directory');
});
read_some();
};
};
Your save method should work fine (mostly, see below) for your second requirement (write to a code-chosen filename without another user prompt), but there are a couple of bugs in open (at least as presented in the question):
Inside the chooseEntry callback, this !== fileHandler because the callback is invoked with a different this (probably the background page’s window object).
You can work around this in several ways:
Use fileHandler instead of this (if you are not using it as any kind of prototype).
Use .bind(this) to bind each of your callback functions to the same context.
Use var self = this; at the top of open and use self.entry (et cetera) in the callbacks.
You may want to call cb for the success case. Maybe you have another way of postponing calls to (e.g.) fileHandler.save (clicking on some element to trigger the save?), but adding something like
⋮
cb && cb(self.entry);
⋮
after self.entry = dirEntry makes it easy to (e.g.) chain open and save:
fileHandler.open(function(ent) {
fileHandler.save('newfile','This is the text\nto save in the (possibly) new file.');
});
There is a latent bug in save: if you ever overwrite an existing file, then you will want to call writer.truncate() (unless you always write more bytes than the file originally held).
⋮
writer.onwrite = function() {
writer.onwrite = null;
writer.truncate(writer.position);
};
writer.write(…);
⋮
It looks like you have a good start on the file listing part. If you want to reference the list of files later, then you might want to save them in your object instead of just logging them; this can get a bit hairy if you want to recurse into subdirectories (and also not assume that readEntries returns everything for its first call).
function list_dir(dirent, cb, listing) {
if (listing === undefined) listing = [];
var reader = dirent.createReader();
var read_some = reader.readEntries.bind(reader, function(ents) {
if (ents.length === 0)
return cb && cb(listing);
process_some(ents, 0);
function process_some(ents, i) {
for(; i < ents.length; i++) {
listing.push(ents[i]);
if (ents[i].isDirectory)
return list_dir(ents[i], process_some.bind(null, ents, i + 1), listing);
}
read_some();
}
}, function() {
console.error('error reading directory');
});
read_some();
}
You could use it in the open callback (assuming you add its success callback) like this:
fileHandler.open(function(ent) {
ent && list_dir(ent, function(listing) {
fileHandler.listing = listing;
console.log('listing', fileHandler.listing.map(function(ent){return ent.fullPath}).join('\n'));
fileHandler.save('a_dir/somefile','This is some data.');
});
});

Add new data from restful api to angularjs scope

I'm trying to create a list with endless scroll in angularjs. For this I need to fetch new data from an api and then append it to the existing results of a scope in angularjs. I have tried several methods, but none of them worked so far.
Currently this is my controller:
userControllers.controller('userListCtrl', ['$scope', 'User',
function($scope, User) {
$scope.users = User.query();
$scope.$watch('users');
$scope.orderProp = 'name';
window.addEventListener('scroll', function(event) {
if (document.body.offsetHeight < window.scrollY +
document.documentElement.clientHeight + 300) {
var promise = user.query();
$scope.users = $scope.users.concat(promise);
}
}, false);
}
]);
And this is my service:
userServices.factory('User', ['$resource',
function($resource) {
return $resource('api/users', {}, {
query: {
method: 'GET',
isArray: true
}
});
}
]);
How do I append new results to the scope instead of replacing the old ones?
I think you may need to use $scope.apply()
When the promise returns, because it isnt
Part of the angular execution loop.
Try something like:
User.query().then(function(){
$scope.apply(function(result){
// concat new users
});
});
The following code did the trick:
$scope.fetch = function() {
// Use User.query().$promise.then(...) to parse the results
User.query().$promise.then(function(result) {
for(var i in result) {
// There is more data in the result than just the users, so check types.
if(result[i] instanceof User) {
// Never concat and set the results, just append them.
$scope.users.push(result[i]);
}
}
});
};
window.addEventListener('scroll', function(event) {
if (document.body.offsetHeight < window.scrollY +
document.documentElement.clientHeight + 300) {
$scope.fetch();
}
}, false);

Creating new Meteor collections on the fly

Is it possible to create new Meteor collections on-the-fly? I'd like to create foo_bar or bar_bar depending on some pathname which should be a global variable I suppose (so I can access it throughout my whole application).
Something like:
var prefix = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');
var Bar = new Meteor.Collection(prefix+'_bar');
The thing here is that I should get my prefix variable from URL, so if i declare it outside of if (Meteor.isClient) I get an error: ReferenceError: window is not defined. Is it possible to do something like that at all?
Edit : Using the first iteration of Akshats answer my project js : http://pastie.org/6411287
I'm not entirely certain this will work:
You need it in two pieces, the first to load collections you've set up before (on both the client and server)
var collections = {};
var mysettings = new Meteor.Collection('settings') //use your settings
//Startup
Collectionlist = mysettings.find({type:'collection'});
Collectionlist.forEach(function(doc) {
collections[doc.name] = new Meteor.Collection(doc.name);
})'
And you need a bit to add the collections on the server:
Meteor.methods({
'create_server_col' : function(collectionname) {
mysettings.insert({type:'collection', name: collectionname});
newcollections[collectionname] = new Collection(collectionname);
return true;
}
});
And you need to create them on the client:
//Create the collection:
Meteor.call('create_server_col', 'My New Collection Name', function(err,result) {
if(result) {
alert("Collection made");
}
else
{
console.log(err);
}
}
Again, this is all untested so I'm just giving it a shot hopefully it works.
EDIT
Perhaps the below should work, I've added a couple of checks to see if the collection exists first. Please could you run meteor reset before you use it to sort bugs from the code above:
var collections = {};
var mysettings = new Meteor.Collection('settings')
if (Meteor.isClient) {
Meteor.startup(function() {
Collectionlist = mysettings.find({type:'collection'});
Collectionlist.forEach(function(doc) {
eval("var "+doc.name+" = new Meteor.Collection("+doc.name+"));
});
});
Template.hello.greeting = function () {
return "Welcome to testColl.";
};
var collectionname=prompt("Enter a collection name to create:","collection name")
create_collection(collectionname);
function create_collection(name) {
Meteor.call('create_server_col', 'tempcoll', function(err,result) {
if(!err) {
if(result) {
//make sure name is safe
eval("var "+name+" = new Meteor.Collection('"+name+"'));
alert("Collection made");
console.log(result);
console.log(collections);
} else {
alert("This collection already exists");
}
}
else
{
alert("Error see console");
console.log(err);
}
});
}
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
Collectionlist = mysettings.find({type:'collection'});
Collectionlist.forEach(function(doc) {
collections[doc.name] = new Meteor.Collection(doc.name);
});
});
Meteor.methods({
'create_server_col' : function(collectionname) {
if(!mysettings.findOne({type:'collection', name: collectionname})) {
mysettings.insert({type:'collection', name: collectionname});
collections[collectionname] = new Meteor.Collection(collectionname);
return true;
}
else
{
return false; //Collection already exists
}
}
});
}
Also make sure your names are javascript escaped.
Things got much easier:
var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
db.createCollection("COLLECTION_NAME", (err, res) => {
console.log(res);
});
Run this in your server method.