AG Data Grid table: generate a Vega-Lite chart that updates automatically - javascript

I would like to use Ag Data Grid filtered data to generate plots in Vega-Lite that update automatically whenever the filter(s) are changed. I would prefer to have the implementation in an observablehq notebook. Here is a section on how to access the table data in Ag Grid documentation. I created an observablehq notebook where the chart is updated using a button. There are two issues with this implementation:
The chart is generated only after the button is clicked.
I would prefer the chart update to be automatic without the need to click a button.

Thanks for linking to the notebook! It appears that the angular table does update, but it appends to the element and gets drawn behind the code cells. This is what it looks like in my browser when I move the slider:
The problem with components like this that manipulate the DOM is that they work against Observable's way of managing the DOM. Even if the component were to update correctly, it would probably still not resize the way you'd expect.
Observable is already reactive at its core, which is something angular (and other frameworks like React) was built to add to JavaScript. Using Observable's built-in reactivity will be much easier in the long run than trying to make two different reactivity models work with each other.

You can make the AG Grid table an Observable “view” so that you can both (1) see the table and (2) refer to its value in other cells, which will re-run when you filter the table. Once you do that, it'll work naturally with anything else you want to do in the notebook. Here's a working example with Observable Plot, and here's the same example with Vega-Lite.
Assuming you've loaded AgGrid and have gridOptions in a different cell, you can wrap AgGrid as an Observable view like this:
viewof table = {
const node = htl.html`<div style="height:320px;" class="ag-theme-alpine"></div>`;
new AgGrid.Grid(node, gridOptions);
gridOptions.api.addEventListener("modelUpdated", update) // set value after filter
gridOptions.api.sizeColumnsToFit();
update(); // set initial value
function update() { // for Observable dataflow
let value = [];
gridOptions.api.forEachNodeAfterFilter(d => value.push(d.data));
node.value = value;
node.dispatchEvent(new Event("input"));
}
return node;
}
A few notes on how this is different from your version (as of when I saw it):
I put the HTML and the AgGrid initialization in the same cell, so that AgGrid has an object reference to the node and if you re-run the cell it all gets cleaned up and recreated as a whole.
I listen for when the grid rows change with gridOptions.api.addEventListener("modelUpdated", update).
In that update function, I do the same iteration over the rows that you were doing to build an array, but then I set it as the value of the node, and dispatch an input event from that node. That's what Observable looks for to tell when a view has changed its value and other cells should re-run.
I name the cell viewof table. You might've seen this pattern with sliders and other inputs on Observable. The viewof keyword means that you get the DOM node rendered, but you can also refer to its value with just table in other cells.
Thanks for the question; I’ve been meaning to check out AG Grid for a while!

Related

React table pre select rows

I'm trying to preselect rows in my table but the table won't refresh unless there are changes to the actual data itself. Is there a method to reinit the table that doesn't involve changing the data?
It's also completely possible that my method for approaching this requirement is wrong and there may be a better way? I've created an example sandbox here:
https://codesandbox.io/s/mock-preselected-rows-data-t36nl?file=/src/App.js
In this you can see I have a mock response from my server for determining what rows should be selected. I'm then grabbing the data to compare to see if any of the items from the mock response exist in the data and if so push them to a new obj which is then fed into the intialState for selectedRowIds
Any guidance appreciated.
Seems your work is all working. The short answer to your question.
As long as you want the user see something, in a React way, it needs to be contained in a state, or state derivative. In your case, it's a cell data wrapped in row and in a table.
So you can't avoid selecting it without touching the data. Unless you don't want user see the change.
Although the checkbox doesn't seem to be part of the original data stream, when you develop on it, you have to make it part of the data. To be honest, it's easy you make it part of the data, because by the time you want to refresh the table, ex. selecting or de-selecting, or deleting a row, you want everything refreshed. Unfortunately it's very difficult to do local refresh with a table in React. It's possible, but very difficult, because most of the design is based on either prop or context.
You can also refactor your handleSelectedRows function.
// Find row ids and compare them with our 'preSelectedTheseItems' array.
const handleSelectedRows = () => {
const preIds = preSelectTheseItems.map(item => item.collectibleId)
return data?.filter((collectibleRow, index) => preIds.includes(collectibleRow.collectibleId));
};
Example : codesandbox

Tabulator.js table elements retrieve the index of the row and serve as a control element to other plots

I am using tabulator package 4.3.0 to work on a webpage. The table generated by the package is going to be the control element of a few other plots. In order to achieve this, I have been adding a dataFiltered function when defining the table variable. But instead of getting the order of the rows in my data object, I want to figure a way to get the index of the rows in the filtered table.
Currently, I searched the manual a little bit and have written the code analogue to this:
dataFiltered: function(filters,rows){
console.log(rows[0]._row.data)
console.log(rows[0].getPosition(true));
}
But the getPosition always returned -1, which refers to that the row is not found in the filtered table. I also generated a demo to show the real situ when running the function. with this link: https://jsfiddle.net/Binny92/3kbn8zet/53/.
I would really appreciate it if someone could help me explain a little bit of how could I get the real index of the row in the filtered data so that I could update the plot accordingly and why I am always getting -1 when running the code written in this way.
In addition, I wonder whether there is a way to retrieve the data also when the user is sorting the table. It's a pity that code using the following strategy is not working in the way I am expecting since it is not reacting to the sort action and will not show the information when loading the page for the first time.
$('#trialTable').on('change',function(x){console.log("Yes")})
Thank you for your help in advance.
The reason this is happening is because the dataFiltered callback is triggered after the rows are filtered but before they have been laid out on the table, so they wont necessarily be ready by the time you call the getPosition function on them.
You might do better to use the renderComplete callback, which will also handle the scenario when the table is sorted, which would change the row positions.
You could then use the getRows function passing in the value "active" as the first augment return only rows that have passed the filter:
renderComplete: function(){
var rows = table.getRows("active");
console.log(rows[0].getPosition(true));
}
On a side note i notice you are trying to access the _row property to access the row data. By convention underscore properties are considered private in JavaScript and should not be accessed as it can result in unstable system behaviour.
Tabulator has an extensive set of functions on the Row Component to allow you to access anything you need. In the case of accessing a rows data, there is the getData function
var data = row.getData();

Get Row Number with Handsontable

Super noob question here. I have an array of row indexes that I would like to use to change the color of my Handsontable rows. I figure HOT would provide a method to retrieve the tr element of a table with something like hot.getRow(5), but it doesn't seem to exist.
So in a nutshell I'm trying to do this
var rowIds = []
$.each(rowIds , function (i, element) {
var row = hot.getRow(i);
$(row).closest('tr').css('color','green');
});
I've found I can use getCell() method which accepts a row and column # along with a boolean, but using this would require extra code for something that should be as simple as passing a single argument. Is there a method I'm overlooking or is this the only way?
Here's the thing with how HOT works: it is a JS object which renders a stateless DOM table. This means you should never EVER try to manually modify the HTML of your table. Even if you did want to do that, as soon as you make a change to those green cells, they would get re-rendered, not green.
Instead, you want to use the readily accessible 'custom renderers' that are associated with each column or cell, depending on how you define them. These are applied just like the data attribute in the columns or cells definition. They are functions and here's an example:
function greenCellRenderer(instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
td.style.color = 'green';
}
You should read up on the full documentation to understand the full power of the renderer but it's pretty clear from the arguments it takes what you can do. One thing you would be able to do is apply the green color you're hoping for. Of course to selectively do this you would either apply the renderer to specific cells, or put a conditional inside this general renderer using the row and col arguments to your advantage.
Hope that helps!

Working with a huge state object

I have a problem with handling state in a React application. For some background: The application mostly renders a big table with lots of data that is then editable. The data comes from a single source as a big list of objects (actually it’s a more complicated hierachy but let’s keep it simple for this purpose), and should be kept as it is. Users can then partially change the data in the big table, and ultimately save their changes.
Since the data comes from a single source, I’m thinking in React and store the data as the table state and pass everything necessary down to the individual components. So a row gets only the row data as a prop, and the cell gets only the cell data as a prop. For the update process at cell level, I then use an inverse data flow to call an update method on the table that updates the state for the updated cell:
change (rowIndex, cellIndex, value) {
this.state.data[rowIndex][cellIndex] = value;
this.forceUpdate();
}
This works pretty fine in theory. However, I have a lot data; the table easily contains about 1000 rows with multiple columns. This is not a problem directly: it takes a bit time for the browser to render the table, but once it’s there, it can work with it pretty well. Also, React doesn’t have a problem with that data amount either.
But the problem is that changing a single cell essentially triggers a rerender of the whole table. Even if the DOM is only changed for a single cell as a result, all the render methods are executed with most of them not doing anything (because the change only happened in a single cell).
My current solution is to implement shouldComponentUpdate for the row component and perform a deep check on all mutable values to avoid a rerender at row and cell level. But this feels very messy as it’s not only very verbose but also very dependent on the data structure.
So I’m not really sure how to tackle this better. I’m currently thinking about moving the state into the rows, and as such also the mutation functionality, and have the table component query the rows for changes on demand. Alternatively I could also move the whole data out of the table, and only work with identifiers the rows then use to query the data from a central store that provides the data and also offers mutation functions. This would be possible because the whole data is loaded once on page load, and then only mutated by the user.
I’m really unsure on how to handle this situation. I’m even thinking of dropping React for this, and rendering everything as static HTML with a custom JavaScript module on top that fetches the data on-demand from the actual input elements when a save is requested. Is there a way to solve this in a good way?
In case you want to play around with this situation, I have a running example on CodePen. As you type into one of the many input fields, you will notice a lag that comes from React calling all the render functions without really changing anything in the DOM.
You should take a look at PureRenderingMixin and shouldComponentUpdate documentation
I made some changes to your code so you don't modify state directly so shouldComponentUpdate can properly compare the props to determine if a rerender is required. The code here is a bit messy and I hacked it together really fast but hopefully it gives a good idea of how it could be implemented.
http://codepen.io/anon/pen/yYXbaL?editors=001
Table
change (rowIndex, cellIndex, value) {
this.state.data[rowIndex][cellIndex] = value;
var newData = this.state.data.map((row, idx) => {
if(idx != rowIndex){
return this.state.data[idx]
} else {
var newRow = this.state.data[idx].map((colVal, idx) =>{
return idx == cellIndex ? value : colVal
})
return newRow
}
});
Row
shouldComponentUpdate(nextProps){
return this.props.cells != nextProps.cells;
}

Sorting a DataTable using custom function does not work

I am working with DataTables plug-in in JavaScript.
Usually, if I need to update a cell value, I use the cell().data(set) method followed by .draw().
However, I do not want to use this way because my table contains heavy DOM object. So, when I need to update a cell, I just call some jQuery like $("#cell").attr("myattr", 50) for example, and then I managed to never have to use draw(). This prevents the object to be rebuilt each time, but unfortunately it also means that the DataTable is not aware of these changes (cell().data() returns the unchanged object).
This is a problem when I want my table to be sorted. In fact, the sorting is performed on the data that the datatable known, data which is not changed.
So I thought I could use the columns.render option, implementing a function like this:
function(data, type, row, meta) {
if (type === "sort") {
return $("#cell").attr("myattr");
}
return data;
}
This does not work and I think this is because of the fact that DataTable caches the data. So, as I never update cells data, cache never need to be updated, and sorting is done using this cache, which does not correspond the cell myattr attribute.
I am looking for a workaround which can allow me to sort a DataTable even if cells values are not changed internally but from outside.
Play with this JSFiddle, clicking the "CHANGE VALUES" button and trying to sort the column, you can see that the values are not correctly ordered.
There are couple solutions:
SOLUTION #1
Use cell().invalidate() API method to invalidate data in cache as shown below:
$('#example').DataTable().cell($("#a").closest('td')).invalidate('dom').draw(false);
DEMO
See this jsFiddle for code and demonstration.
SOLUTION #2
You can use columns.orderDataType to specify name of custom ordering plug-in, see Custom data source sorting. These plug-ins can access live DOM content.
Please note that there are no plug-ins built into DataTables, they must be added separately.
You can use dom-text plug-in as a base and write your own function to access the data for sorting.
DEMO
See this jsFiddle for code and demonstration.

Categories