UNPKG

react-mosaic-component2

Version:
118 lines (117 loc) 3.08 kB
// src/util/mosaicUtilities.ts import { clone, get } from "lodash-es"; function alternateDirection(node, direction = "row") { if (isParent(node)) { const nextDirection = getOtherDirection(direction); return { direction, first: alternateDirection(node.first, nextDirection), second: alternateDirection(node.second, nextDirection) }; } else { return node; } } var Corner = /* @__PURE__ */ ((Corner2) => { Corner2[Corner2["TOP_LEFT"] = 1] = "TOP_LEFT"; Corner2[Corner2["TOP_RIGHT"] = 2] = "TOP_RIGHT"; Corner2[Corner2["BOTTOM_LEFT"] = 3] = "BOTTOM_LEFT"; Corner2[Corner2["BOTTOM_RIGHT"] = 4] = "BOTTOM_RIGHT"; return Corner2; })(Corner || {}); function isParent(node) { return node.direction != null; } function createBalancedTreeFromLeaves(leaves, startDirection = "row") { if (leaves.length === 0) { return null; } let current = clone(leaves); let next = []; while (current.length > 1) { while (current.length > 0) { if (current.length > 1) { next.push({ direction: "row", first: current.shift(), second: current.shift() }); } else { next.unshift(current.shift()); } } current = next; next = []; } return alternateDirection(current[0], startDirection); } function getOtherBranch(branch) { if (branch === "first") { return "second"; } else if (branch === "second") { return "first"; } else { throw new Error(`Branch '${branch}' not a valid branch`); } } function getOtherDirection(direction) { if (direction === "row") { return "column"; } else { return "row"; } } function getPathToCorner(tree, corner) { let currentNode = tree; const currentPath = []; while (isParent(currentNode)) { if (currentNode.direction === "row" && (corner === 1 /* TOP_LEFT */ || corner === 3 /* BOTTOM_LEFT */)) { currentPath.push("first"); currentNode = currentNode.first; } else if (currentNode.direction === "column" && (corner === 1 /* TOP_LEFT */ || corner === 2 /* TOP_RIGHT */)) { currentPath.push("first"); currentNode = currentNode.first; } else { currentPath.push("second"); currentNode = currentNode.second; } } return currentPath; } function getLeaves(tree) { if (tree == null) { return []; } else if (isParent(tree)) { return getLeaves(tree.first).concat(getLeaves(tree.second)); } else { return [tree]; } } function getNodeAtPath(tree, path) { if (path.length > 0) { return get(tree, path, null); } else { return tree; } } function getAndAssertNodeAtPathExists(tree, path) { if (tree == null) { throw new Error("Root is empty, cannot fetch path"); } const node = getNodeAtPath(tree, path); if (node == null) { throw new Error(`Path [${path.join(", ")}] did not resolve to a node`); } return node; } export { Corner, createBalancedTreeFromLeaves, getAndAssertNodeAtPathExists, getLeaves, getNodeAtPath, getOtherBranch, getOtherDirection, getPathToCorner, isParent };