feat: 🎸 Total Accumulator hook for totals row (#55)

* feat: 🎸 Accumulator event for totals row

* fix: 🐛 Changed values passed to accumulator function

and moved function to hooks.totalAccumulator

* fix: 🐛 Total row set null for column without any number

* fix: Refactor accumulator

- Rename to columnTotal

* fix: 🐛 Prevent showing 0 in total row for Data fieldtype

* fix: Remove hooks object from parent

* fix: Remove separate hooks initialization
This commit is contained in:
Saif 2019-02-12 19:21:13 +05:00 committed by Faris Ansari
parent 836b13bd88
commit 0f44a51da3
3 changed files with 44 additions and 11 deletions

View File

@ -216,7 +216,24 @@
return format($input.value); return format($input.value);
} }
} }
} },
hooks: {
columnTotal(columnValues, cell) {
if (cell.colIndex === 5) {
// calculated average for 5th column
const sum = columnValues.reduce((acc, value) => {
if (typeof value === 'number') {
return acc + value
}
return acc
}, 0);
return sum / columnValues.length
}
if (cell.colIndex === 2) {
return 'Total'
}
}
}
}); });
console.log(performance.now() - start); console.log(performance.now() - start);

View File

@ -71,7 +71,7 @@ export default class BodyRenderer {
getTotalRow() { getTotalRow() {
const columns = this.datamanager.getColumns(); const columns = this.datamanager.getColumns();
const totalRowTemplate = columns.map(col => { const totalRowTemplate = columns.map(col => {
let content = 0; let content = null;
if (['_rowIndex', '_checkbox'].includes(col.id)) { if (['_rowIndex', '_checkbox'].includes(col.id)) {
content = ''; content = '';
} }
@ -82,18 +82,31 @@ export default class BodyRenderer {
column: col column: col
}; };
}); });
const totalRow = this.visibleRows.reduce((acc, prevRow) => {
return acc.map((cell, i) => { const totalRow = totalRowTemplate.map((cell, i) => {
if (cell.content === '') return cell;
if (this.options.hooks.columnTotal) {
const columnValues = this.visibleRows.map(row => row[i].content);
const result = this.options.hooks.columnTotal.call(this.instance, columnValues, cell);
if (result != null) {
cell.content = result;
return cell;
}
}
cell.content = this.visibleRows.reduce((acc, prevRow) => {
const prevCell = prevRow[i]; const prevCell = prevRow[i];
if (typeof prevCell.content === 'number') { if (typeof prevCell.content === 'number') {
cell.content += prevRow[i].content; if (acc == null) acc = 0;
return acc + prevCell.content;
} }
if (!cell.format && prevCell.format) { return acc;
cell.format = prevCell.format; }, cell.content);
}
return Object.assign({}, cell); return cell;
}); });
}, totalRowTemplate);
return totalRow; return totalRow;
} }

View File

@ -38,6 +38,9 @@ export default {
onCheckRow(row) {}, onCheckRow(row) {},
onDestroy() {} onDestroy() {}
}, },
hooks: {
columnTotal: null
},
sortIndicator: { sortIndicator: {
asc: '↑', asc: '↑',
desc: '↓', desc: '↓',