UNPKG

svelte-ux

Version:

- Increment version in `package.json` and commit as `Version bump to x.y.z` - `npm run publish`

98 lines (97 loc) 3.3 kB
import { isFunction, get } from 'lodash-es'; import { parseISO } from 'date-fns'; import { PeriodType } from '../utils/date'; import { format } from '../utils/format'; export function getHeaders(columns) { const maxDepth = getDepth(columns); const result = Array.from({ length: maxDepth, }).map(() => []); function addItems(columns, depth) { columns.forEach((column) => { const columnDef = { ...column, }; delete columnDef.columns; if (column.columns) { const colSpan = getWidth(column); if (colSpan > 1) { columnDef.colSpan = colSpan; } addItems(column.columns, depth + 1); } else { const rowSpan = maxDepth - depth; if (rowSpan > 1) { columnDef.rowSpan = maxDepth - depth; } } result[depth].push(columnDef); }); } addItems(columns, 0); return result; } export function getRowColumns(columns) { const result = []; function setColumns(column) { if (column.columns == null) { result.push(column); return; } column.columns.forEach((child) => setColumns(child)); } columns.forEach((column) => setColumns(column)); return result; } export function getDepth(columns) { if (columns == null) { return 0; } let depth = 0; columns.forEach((item) => { depth = Math.max(depth, getDepth(item.columns)); }); return depth + 1; } export function getWidth(column) { if (column.columns == null) { return 1; } let width = 0; column.columns.forEach((child) => { width += getWidth(child); }); return width; } export function getCellHeader(column) { if (column.header != null) { return column.header; } let header = column.name.split('.')[0]; // Use first section before dot (`Organization.Identifier` => `Organization`) header = header.replace(/([a-z])([A-Z])/g, '$1 $2'); // Add space before capital letters - https://stackoverflow.com/questions/5582228/insert-space-before-capital-letters return header; } export function getCellValue(column, rowData, rowIndex) { var _a; let value = undefined; if (isFunction(column.value)) { value = (_a = column.value) === null || _a === void 0 ? void 0 : _a.call(column, rowData, rowIndex); } if (value === undefined) { value = get(rowData, typeof column.value === 'string' ? column.value : column.name); } if (typeof value === 'string' && !isFunction(column.format) && column.format in PeriodType) { // Convert date string to Date instance // TODO: Shoud dateFns.parseISO() be used? // TODO: Should we handle date-only strings different? // value = new Date(value); // console.log({ column: column.name, value }); value = parseISO(value); } return value; } export function getCellContent(column, rowData, rowIndex) { const value = getCellValue(column, rowData, rowIndex); return format(value, column === null || column === void 0 ? void 0 : column.format, rowData, rowIndex); }