|
| 1 | +export const CELL = 'cell'; |
| 2 | +export const COLUMN = 'column'; |
| 3 | +export const ROW = 'row'; |
| 4 | +export const TABLE = 'table'; |
| 5 | + |
| 6 | +function create(type, props) { |
| 7 | + const node = { ...props, type }; |
| 8 | + const { data, position } = props; |
| 9 | + if (data instanceof Object) { |
| 10 | + node.data = data; |
| 11 | + } |
| 12 | + |
| 13 | + if (position instanceof Object) { |
| 14 | + node.position = position; |
| 15 | + } |
| 16 | + |
| 17 | + return node; |
| 18 | +} |
| 19 | + |
| 20 | +export function cell(value, props = {}) { |
| 21 | + const { data, position } = props; |
| 22 | + return create(CELL, { data, position, value }); |
| 23 | +} |
| 24 | + |
| 25 | +export function column(value, props = {}) { |
| 26 | + const { data, dataType, index, label, position } = props; |
| 27 | + return create(COLUMN, { data, dataType, index, label, position, value }); |
| 28 | +} |
| 29 | + |
| 30 | +export function row(props = {}, children = []) { |
| 31 | + const { data, index, position } = props; |
| 32 | + let firstChildType; |
| 33 | + const updatedChildren = children |
| 34 | + .map((child) => { |
| 35 | + const isNode = child?.type; |
| 36 | + if (!firstChildType) { |
| 37 | + if (isNode) { |
| 38 | + if ([CELL, COLUMN].includes(child.type)) { |
| 39 | + firstChildType = child.type; |
| 40 | + } |
| 41 | + } else { |
| 42 | + firstChildType = CELL; |
| 43 | + } |
| 44 | + } |
| 45 | + if (!isNode) { |
| 46 | + return cell(child); |
| 47 | + } |
| 48 | + if (isNode && firstChildType === child.type) { |
| 49 | + return child; |
| 50 | + } |
| 51 | + return null; |
| 52 | + }) |
| 53 | + .filter((child) => child) |
| 54 | + .map((child, index) => { |
| 55 | + return child.type === COLUMN ? { ...child, index } : child; |
| 56 | + }); |
| 57 | + return create(ROW, { children: updatedChildren, data, index, position }); |
| 58 | +} |
| 59 | + |
| 60 | +export function table(props = {}, children = []) { |
| 61 | + const { data, position } = props; |
| 62 | + const updatedChildren = children |
| 63 | + .map((child) => { |
| 64 | + const isRowNode = child?.type === ROW; |
| 65 | + if (isRowNode) { |
| 66 | + return row(child, child.children); |
| 67 | + } |
| 68 | + return null; |
| 69 | + }) |
| 70 | + .filter((child) => child) |
| 71 | + .map((child, index) => ({ ...child, index })); |
| 72 | + return create(TABLE, { children: updatedChildren, data, position }); |
| 73 | +} |
0 commit comments