@adaptabletools/adaptable
Version:
Powerful data-agnostic HTML5 AG Grid extension which provides advanced, cutting-edge functionality to meet all DataGrid requirements
93 lines (92 loc) • 2.77 kB
JavaScript
/**
* There are two ways in which the datasource can be dropped in the wizard:
*
* 1. array of objects - eg: [{"lastName":"John","firstName":"Bobson"},{"lastName":"Mike","firstName":"Richardson"},...]
* 2. array of arrays - eg: [["lastName","firstName"],["John","Bobson"],["Mike","Richardson"],...]
*
* Although the second one is more compact, the first one is what we need for the datasource of the grid,
* so if we receive v2, we transform it to 1
* @param json
*/
export const prepareDataSource = (json, _file) => {
if (!Array.isArray(json) || !json.length) {
return {
primaryKey: undefined,
columns: [],
data: [],
};
}
let columns = [];
let data = [];
let primaryKey;
if (Array.isArray(json[0])) {
// we are in v2, as described above, so this is the list of columns
columns = json[0];
for (let i = 1, len = json.length; i < len; i++) {
const it = json[i];
const obj = {};
for (let j = 0; j < columns.length; j++) {
obj[columns[j]] = it[j];
}
data.push(obj);
}
}
else {
columns = Object.keys(json[0]);
data = json;
}
primaryKey = columns[0];
return {
primaryKey,
columns,
data,
};
};
const typeToColType = {
string: 'text',
number: 'number',
boolean: 'boolean',
date: 'date',
};
export const getColTypeFromValue = (value) => {
const dataType = typeof value;
let columnDataType = typeToColType[dataType] || typeToColType.string;
if (value instanceof Date) {
columnDataType = typeToColType.date;
}
if (Array.isArray(value) && value.length && typeof value[0] === 'number') {
columnDataType = 'numberArray';
}
return columnDataType;
};
export const prepareGridOptions = (dataSourceInfo, defaultGridOptions) => {
const firstItem = dataSourceInfo.data[0];
const columnDefs = dataSourceInfo.columns.map((columnName) => {
const firstItemValue = firstItem[columnName];
const columnType = getColTypeFromValue(firstItemValue);
return {
headerName: columnName,
field: columnName,
type: columnType,
filter: true,
sortable: true,
enableRowGroup: true,
resizable: true,
editable: true,
};
});
const gridOptions = {
...defaultGridOptions,
defaultColDef: {
floatingFilter: true,
},
rowData: dataSourceInfo.data,
columnDefs,
cellSelection: true,
rowSelection: {
mode: 'multiRow',
},
rowHeight: 30,
};
return gridOptions;
};