@smkit/ui
Version:
UI Kit of SberMarketing
81 lines (80 loc) • 2.81 kB
JavaScript
import { Types } from '../../types';
// TODO use from utils/number in future
// function round(number: number, roundness: number = 100) {
// return Math.round(number * roundness) / roundness;
// }
export function CSVExport($body, $header) {
const casted = [];
for (const row of $body) {
casted.push($header
.sort((a, b) => a.index - b.index)
.map((head) => {
const cell = row[head.name];
if (head.cast) {
return head.cast(cell);
}
if (typeof cell === 'object' && cell) {
return JSON.stringify(cell);
}
if (head.type === Types.Date) {
const date = new Date(cell).toLocaleString(navigator.language, {
day: '2-digit',
month: '2-digit',
year: 'numeric'
});
return date.replace(/\./g, '.').replace(/ /g, '.');
}
if (head.type === Types.Number)
return cell ? Number.parseFloat(cell) : null;
if (cell === null || cell === undefined)
return null;
return cell.toString();
}));
}
return { prepHeader: $header, prepBody: casted };
}
export function ExcelExport($body, $header) {
const casted = [];
for (const row of $body) {
casted.push($header
.sort((a, b) => a.index - b.index)
.map((head) => {
const cell = row[head.name];
if (head.cast) {
return head.cast(cell);
}
if (typeof cell === 'object' && cell) {
return JSON.stringify(cell);
}
if (head.type === Types.Date) {
return new Date(cell);
}
if (head.type === Types.Number)
return cell ? Number.parseFloat(cell) : null;
if (cell === null || cell === undefined)
return null;
return cell.toString();
}));
}
return { prepHeader: $header, prepBody: casted };
}
export function triggerDownload({ blob, name = '', extension = 'csv' }) {
const d = new Date();
name = name || `Выгрузка-${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
const filename = `${name}.${extension}`;
saveData(blob, filename);
}
const saveData = (function () {
if (typeof document === 'undefined')
return () => { };
const a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
return function (blob, fileName) {
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
})();