How to create a Data Table from forge viewer - datatable

I want to create a table that represents the data from a model that i have loaded in the forge viewer.
i want the table to be in a docking panel, and show the propertys for elements in the model ( level, name, comment,Area, type name--> for each element [if it has the property])
i have tried to use the API reference, and create a DataTable, but i did not find examples of how to actually impliment it.
where and when do i need to set the datatable? ( after or before creating the docking pannel?)
what is the content of the arrays that i should pass in the constructor? ( according to the documentation : array of arrays for the rows, and array for the columns. is the row array, is simply an array that contains the columns arrays?)
this is my current code for the extension that shows the amount to instances in the model for each property that i want to adjust:
'''
class testTest extends Autodesk.Viewing.Extension {
constructor(viewer, options) {
super(viewer, options);
this._group = null;
this._button = null;
}
load() {
console.log('testTest has been loaded');
return true;
}
unload() {
// Clean our UI elements if we added any
if (this._group) {
this._group.removeControl(this._button);
if (this._group.getNumberOfControls() === 0) {
this.viewer.toolbar.removeControl(this._group);
}
}
console.log('testTest has been unloaded');
return true;
}
// The Viewer contains all elements on the model, including categories (e.g. families or part definition),
//so we need to enumerate the leaf nodes, meaning actual instances on the model.
getAllLeafComponents(callback) {
this.viewer.getObjectTree(function (tree) {
let leaves = [];// an empty 'leaf' list that we want to fill wiith the objects that has no mo children
//dbId== object id
// for each child that we enumerate from a root, call a code , and finally a true /false flag parameter that run the function recursivly for all the children of a child.
tree.enumNodeChildren(tree.getRootId(), function (dbId) {
if (tree.getChildCount(dbId) === 0) {
leaves.push(dbId);// if the object has no children--> add it to the list.
}
}, true);// the last argument we past ("true") will make sure that the function in the seccond argument ("function (dbId)(...)" ")will run recursively not only for the children of the roots,
//but for all the children and childrtn's children.
callback(leaves);//return the leaves
});
}
onToolbarCreated() {
// Create a new toolbar group if it doesn't exist
this._group = this.viewer.toolbar.getControl('allMyAwesomeExtensionsToolbar');//if there is no controller named "allMyAwesomeExtensionsToolbar" create one
if (!this._group) {
this._group = new Autodesk.Viewing.UI.ControlGroup('allMyAwesomeExtensionsToolbar');
this.viewer.toolbar.addControl(this._group);// add the control to tool bar
}
// Add a new button to the toolbar group
this._button = new Autodesk.Viewing.UI.Button('testTest');
this._button.onClick = (ev) => {
// Check if the panel is created or not
if (this._panel == null) {//check if there is an instance of our pannel. if not- create one
this._panel = new ModelSummaryPanel(this.viewer, this.viewer.container, 'modelSummaryPanel', 'Model Summary');
}
// Show/hide docking panel
this._panel.setVisible(!this._panel.isVisible());//cal a method from the parent to show/ hide the panel -->use this to toggle from visible to invisible
this._panel.set
// If panel is NOT visible, exit the function
if (!this._panel.isVisible())
return;
// First, the viewer contains all elements on the model, including
// categories (e.g. families or part definition), so we need to enumerate
// the leaf nodes, meaning actual instances of the model. The following
// getAllLeafComponents function is defined at the bottom
this.getAllLeafComponents((dbIds) => {// now we have the list of the Id's of all the leaves
// Now for leaf components, let's get some properties and count occurrences of each value
debugger;
const filteredProps = ['Level','Name','Comments','Area','Type Name'];
// Get only the properties we need for the leaf dbIds
this.viewer.model.getBulkProperties(dbIds,filteredProps , (items) => {
// Iterate through the elements we found
items.forEach((item) => {
// and iterate through each property
item.properties.forEach(function (prop) {
// Use the filteredProps to store the count as a subarray
if (filteredProps[prop.displayName] === undefined)
filteredProps[prop.displayName] = {};
// Start counting: if first time finding it, set as 1, else +1
if (filteredProps[prop.displayName][prop.displayValue] === undefined)
filteredProps[prop.displayName][prop.displayValue] = 1;
else
filteredProps[prop.displayName][prop.displayValue] += 1;
});
});
// Now ready to show!
// The PropertyPanel has the .addProperty that receives the name, value
// and category, that simple! So just iterate through the list and add them
filteredProps.forEach((prop) => {
if (filteredProps[prop] === undefined) return;
Object.keys(filteredProps[prop]).forEach((val) => {
this._panel.addProperty(val, filteredProps[prop][val], prop);
this.dt = new DataTabe(this._panel);
this.dt.setData()
});
});
});
});
};
this._button.setToolTip('Or Levis extenssion');
this._button.addClass('testTest');
this._group.addControl(this._button);
}
}
Autodesk.Viewing.theExtensionManager.registerExtension('testTest', testTest);'''
'''

We have a tutorial with step-by-step on how to do it.
Please, refer to Dashboard tutorial, specifically in Data Grid section.
In this case, the tutorial uses an external library (Tabulator) to show the data.

Related

check if d3.select or d3.selectAll

I have a method on a reusable chart that can be passed a selection and return a value if it is passed a d3.select('#id') selection or an array of values if it is passed a d3.selectAll('.class') selection. I'm currently interrogating the passed argument with context._groups[0] instanceof NodeList, but it feels a little fragile using an undocumented property, as that may change in future versions. Is there a more built in way of determining if a selection comes from select or selectAll?
selection.size() will not help here, as it only tells us the result of the selection, not how it was called.
EDIT:
Here's the context of the use. I'm using Mike Bostock's reusable chart pattern and this instance includes a method for getting/setting a label for a donut.
To me, this API usage follows the principle of least astonishment, as it's how I would expect the result to be returned.
var donut = APP.rotatingDonut();
// set label for one element
d3.select('#donut1.donut')
.call(donut.label, 'Donut 1')
d3.select('#donut2.donut')
.call(donut.label, 'Donut 2')
// set label for multiple elements
d3.selectAll('.donut.group-1')
.call(donut.label, 'Group 1 Donuts')
// get label for one donut
var donutOneLabel = d3.select('#donut1').call(donut.label)
// donutOnelabel === 'Donut 1'
// get label for multiple donuts
var donutLables = d3.selectAll('.donut').call(donut.label)
// donutLabels === ['Donut 1', 'Donut 2', 'Group 1 Donuts', 'Group 1 Donuts']
and the internal method definition:
App.rotatingDonut = function() {
var label = d3.local();
function donut() {}
donut.label = function(context, value) {
var returnArray;
var isList = context._groups[0] instanceof NodeList;
if (typeof value === 'undefined' ) {
// getter
returnArray = context.nodes()
.map(function (node) {return label.get(node);});
return isList ? returnArray : returnArray[0];
}
// settter
context.each(function() {label.set(this, value);});
// allows method chaining
return donut;
};
return donut
}
Well, sometimes a question here at S.O. simply doesn't have an answer (it has happened before).
That seems to be the case of this question of yours: "Is there a more built in way of determining if a selection comes from select or selectAll?". Probably no.
To prove that, let's see the source code for d3.select and d3.selectAll (important: those are not selection.select and selection.selectAll, which are very different from each other).
First, d3.select:
export default function(selector) {
return typeof selector === "string"
? new Selection([[document.querySelector(selector)]], [document.documentElement])
: new Selection([[selector]], root);
}
Now, d3.selectAll:
export default function(selector) {
return typeof selector === "string"
? new Selection([document.querySelectorAll(selector)], [document.documentElement])
: new Selection([selector == null ? [] : selector], root);
}
As you can see, we have only two differences here:
d3.selectAll accepts null. That will not help you.
d3.selectAll uses querySelectorAll, while d3.select uses querySelector.
That second difference is the only one that suits you, as you know by now, since querySelectorAll:
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList. (emphasis mine)
And querySelector only...:
Returns the first Element within the document that matches the specified selector, or group of selectors.
Therefore, the undocumented (and hacky, since you are using _groups, which is not a good idea) selection._groups[0] instanceof NodeList you are using right now seems to be the only way to tell a selection created by d3.select from a selection created by d3.selectAll.

Why session.getSaveBatch() is undefined when child record was added - Ext 5.1.1

Well the title says it all, details following.
I have two related models, User & Role.
User has roles defined as:
Ext.define('App.model.security.User', {
extend: 'App.model.Base',
entityName: 'User',
fields: [
{ name: 'id' },
{ name: 'email'},
{ name: 'name'},
{ name: 'enabled', type: 'bool'}
],
manyToMany: 'Role'
});
Then I have a grid of users and a form to edit user's data including his roles.
The thing is, when I try to add or delete a role from the user a later call to session.getSaveBatch() returns undefined and then I cannot start the batch to send the modifications to the server.
How can I solve this?
Well after reading a lot I found that Ext won't save the changed relationships between two models at least on 5.1.1.
I've had to workaround this by placing an aditional field on the left model (I named it isDirty) with a default value of false and set it true to force the session to send the update to the server with getSaveBatch.
Later I'll dig into the code to write an override to BatchVisitor or a custom BatchVisitor class that allow to save just associations automatically.
Note that this only occurs when you want to save just the association between the two models and if you also modify one of the involved entities then the association will be sent on the save batch.
Well this was interesting, I've learned a lot about Ext by solving this simple problem.
The solution I came across is to override the BatchVisitor class to make use of an event handler for the event onCleanRecord raised from the private method visitData of the Session class.
So for each record I look for left side entities in the matrix and if there is a change then I call the handler for onDirtyRecord which is defined on the BatchVisitor original class.
The code:
Ext.define('Ext.overrides.data.session.BatchVisitor', {
override: 'Ext.data.session.BatchVisitor',
onCleanRecord: function (record) {
var matrices = record.session.matrices
bucket = null,
ops = [],
recordId = record.id,
className = record.$className;
// Before anything I check that the record does not exists in the bucket
// If it exists then any change on matrices will be considered (so leave)
try {
bucket = this.map[record.$className];
ops.concat(bucket.create || [], bucket.destroy || [], bucket.update || []);
var found = ops.findIndex(function (element, index, array) {
if (element.id === recordId) {
return true;
}
});
if (found != -1) {
return;
}
}
catch (e) {
// Do nothing
}
// Now I look for changes on matrices
for (name in matrices) {
matrix = matrices[name].left;
if (className === matrix.role.cls.$className) {
slices = matrix.slices;
for (id in slices) {
slice = slices[id];
members = slice.members;
for (id2 in members) {
id1 = members[id2][0]; // This is left side id, right side is index 1
state = members[id2][2];
if (id1 !== recordId) { // Not left side => leave
break;
}
if (state) { // Association changed
this.onDirtyRecord(record);
// Same case as above now it exists in the bucket (so leave)
return;
}
}
}
}
}
}
});
It works very well for my needs, probably it wont be the best solution for others but can be a starting point anyways.
Finally, if it's not clear yet, what this does is give the method getSaveBatch the ability to detect changes on relationships.

Kendo multiselect, trigger an event when an item is removed

I use the multiselect from the Kendo UI.
I want to know if there is any way to trigger a function, when the user deletes an item from the multiselect.
So far I know that the 'change' event is triggered, but it is too generic and I can't find any info on what the user removed. Or is there?
What about define change as:
change : function (e) {
var previous = this._savedOld;
var current = this.value();
var diff = [];
if (previous) {
diff = $(previous).not(current).get();
}
this._savedOld = current.slice(0);
// diff has the elements removed do whatever you want...
}
What I do is save previous values on _savedOld and then compute the difference with current using jQuery.not. It's important to note the use of slice for cloning previous list of values, if we save current then we are actually saving a reference to current list and since it is a reference next time we try to use we get again current value.
EDIT: In order to save the values set during the initialization, you can do:
dataBound : function (e) {
saveCurrent(this);
},
change : function (e) {
var previous = this._savedOld;
var current = this.value();
var diff = $(previous).not(current).get();
saveCurrent(this);
// diff has the elements removed do whatever you want...
}
where saveCurrent is a function defined as:
function saveCurrent(multi) {
multi._savedOld = multi.value().slice(0);
}

Ordering backbone views together with collection

I have a collection which contains several items that should be accessible in a list.
So every element in the collection gets it own view element which is then added to the DOM into one container.
My question is:
How do I apply the sort order I achieved in the collection with a comparator function to the DOM?
The first rendering is easy: you iterate through the collection and create all views which are then appended to the container element in the correct order.
But what if models get changed and are re-ordered by the collection? What if elements are added? I don't want to re-render ALL elements but rather update/move only the necessary DOM nodes.
model add
The path where elements are added is rather simple, as you get the index in the options when a model gets added to a collection. This index is the sorted index, based on that if you have a straightforward view, it should be easy to insert your view at a certain index.
sort attribute change
This one is a bit tricky, and I don't have an answer handy (and I've struggled with this at times as well) because the collection doesn't automatically reshuffle its order after you change an attribute the model got sorted on when you initially added it.
from the backbone docs:
Collections with comparator functions will not automatically re-sort
if you later change model attributes, so you may wish to call sort
after changing model attributes that would affect the order.
so if you call sort on a collection it will trigger a reset event which you can hook into to trigger a redraw of the whole list.
It's highly ineffective when dealing with lists that are fairly long and can seriously reduce user experience or even induce hangs
So the few things you get walking away from this is knowing you can:
always find the index of a model after sorting by calling collection.indexOf(model)
get the index of a model from an add event (3rd argument)
Edit:
After thinking about if for a bit I came up with something like this:
var Model = Backbone.Model.extend({
initialize: function () {
this.bind('change:name', this.onChangeName, this);
},
onChangeName: function ()
{
var index, newIndex;
index = this.collection.indexOf(this);
this.collection.sort({silent: true});
newIndex = this.collection.indexOf(this);
if (index !== newIndex)
{
this.trigger('reindex', newIndex);
// or
// this.collection.trigger('reindex', this, newIndex);
}
}
});
and then in your view you could listen to
var View = Backbone.View.extend({
initialize: function () {
this.model.bind('reindex', this.onReindex, this);
},
onReindex: function (newIndex)
{
// execute some code that puts the view in the right place ilke
$("ul li").eq(newIndex).after(this.$el);
}
});
Thanks Vincent for an awesome solution. There's however a problem with the moving of the element, depending on which direction the reindexed element is moving. If it's moving down, the index of the new location doesn't match the index of what's in the DOM. This fixes it:
var Model = Backbone.Model.extend({
initialize: function () {
this.bind('change:name', this.onChangeName, this);
},
onChangeName: function () {
var fromIndex, toIndex;
fromIndex = this.collection.indexOf(this);
this.collection.sort({silent: true});
toIndex = this.collection.indexOf(this);
if (fromIndex !== toIndex)
{
this.trigger('reindex', fromIndex, toIndex);
// or
// this.collection.trigger('reindex', this, fromIndex, toIndex);
}
}
});
And the example listening part:
var View = Backbone.View.extend({
initialize: function () {
this.model.bind('reindex', this.onReindex, this);
},
onReindex: function (fromIndex, toIndex) {
var $movingEl, $replacingEl;
$movingEl = this.$el;
$replacingEl = $("ul li").eq(newIndex);
if (fromIndex < toIndex) {
$replacingEl.after($movingEl);
} else {
$replacingEl.before($movingEl);
}
}
});

Cascading to a auto completing text box

I have a web page where the user will enter their address. They will select their country and region in cascading drop down lists. I would like to provide an auto completing textbox for their city, but I want to be context sensitive to the country and region selections. I would have just used another cascading drop down list, however the number of cities exceeds the maximum number of list items.
Any suggestions or cool code spinets out there that may help me out?
I just found the following blog post that looks at least close to what you want.
They manage it using the following javascript functions:
function initCascadingAutoComplete() {
var moviesAutoComplete = $find('autoCompleteBehavior1');
var actorsAutoComplete = $find('autoCompleteBehavior2');
actorsAutoComplete.set_contextKey(moviesAutoComplete.get_element().value);
moviesAutoComplete.add_itemSelected(cascade);
// setup initial state of second flyout
if (moviesAutoComplete.get_element().value) {
actorsAutoComplete.get_element().disabled = false;
} else {
actorsAutoComplete.get_element().disabled = true;
actorsAutoComplete.get_element().value = "";
}
}
function cascade(sender, ev) {
var actorsAutoComplete = $find('autoCompleteBehavior2');
actorsAutoComplete.set_contextKey(ev.get_text());
actorsAutoComplete.get_element().value = '';
if (actorsAutoComplete.get_element().disabled) {
actorsAutoComplete.get_element().disabled = false;
}
}
Sys.Application.add_load(initCascadingAutoComplete);
Calling the cascade function on the add_itemSelected method of the parent control for the cascading behaviour.
They cascade the contents of one auto complete extender into another, rather than taking a cascading drop down list, but hopefully you can reuse some of the ideas.

Resources