|
| 1 | +import convTypesToArray from "./convTypesToArray" |
| 2 | +import JSONEqual from "lib/JSON/JSONEqual" |
| 3 | +import toArray from "lib/x/toArray" |
| 4 | + |
| 5 | +// Compares whether props (rendered and non-rendered) are |
| 6 | +// deeply equal. |
| 7 | +function propsAreEqual(rendered, nonRendered) { |
| 8 | + const { children: _, ...props } = rendered // Obscures rendered.children |
| 9 | + return JSONEqual(props, nonRendered) |
| 10 | +} |
| 11 | + |
| 12 | +// Queries the next parent element and non-nested types. |
| 13 | +function queryNext(tree, { types }) { |
| 14 | + const typeArr = convTypesToArray(types) |
| 15 | + |
| 16 | + if (!tree.length || !typeArr.length) { |
| 17 | + return [tree, typeArr] |
| 18 | + } |
| 19 | + let lastRef = toArray(tree).slice(-1)[0] |
| 20 | + let ref = lastRef |
| 21 | + let x = 0 |
| 22 | + for (; x < typeArr.length; x++) { |
| 23 | + const type = typeArr[x] |
| 24 | + |
| 25 | + ref = toArray(ref).slice(-1)[0] |
| 26 | + if (typeof ref === "string" || ref.type !== type.type || !propsAreEqual(ref.props, type.props)) { |
| 27 | + // No-op |
| 28 | + break |
| 29 | + } |
| 30 | + lastRef = ref |
| 31 | + ref = ref.props.children |
| 32 | + } |
| 33 | + if (lastRef === ref) { |
| 34 | + return [tree, typeArr] |
| 35 | + } |
| 36 | + lastRef.props.children = toArray(lastRef.props.children) |
| 37 | + return [lastRef.props.children, typeArr.slice(x)] |
| 38 | +} |
| 39 | + |
| 40 | +// Creates a tree-shaped React element. |
| 41 | +function createElement(child, types) { |
| 42 | + if (!types.length) { |
| 43 | + return child.props.children |
| 44 | + } |
| 45 | + const element = {} |
| 46 | + let ref = element |
| 47 | + for (const [x, { type, props }] of types.entries()) { |
| 48 | + Object.assign(ref, { |
| 49 | + type, |
| 50 | + props: { |
| 51 | + ...props, |
| 52 | + children: x + 1 < types.length ? {} |
| 53 | + : child.props.children, |
| 54 | + }, |
| 55 | + }) |
| 56 | + ref = ref.props.children |
| 57 | + } |
| 58 | + return element |
| 59 | +} |
| 60 | + |
| 61 | +// Converts children to tree-shaped children. |
| 62 | +function toTree(children) { |
| 63 | + const tree = [] |
| 64 | + for (const each of children) { |
| 65 | + const [parentElement, types] = queryNext(tree, each) |
| 66 | + parentElement.push(createElement(each, types)) |
| 67 | + } |
| 68 | + return tree |
| 69 | +} |
| 70 | + |
| 71 | +export default toTree |
0 commit comments