123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- import { TopicType } from "@/enum";
- import { MindMapProjectInfo, TopicItem, HierarchyResult } from "@/types";
- const DISTANCE = 20; // 子节点相对于父节点的偏差
- function firstWalk(node: TopicItem): HierarchyResult {
- const root: HierarchyResult = {
- x: 0,
- y: 0,
- totalHeight: 0,
- totalWidth: 0,
- width: node.width,
- height: node.height,
- id: node.id,
- data: node,
- children: [],
- };
- root.children = node.collapsed ? [] : node.children?.map((child) => firstWalk(child)) || [];
- return root;
- }
- // 设置宽高
- function secondWalk(
- node: HierarchyResult,
- pageSetting: MindMapProjectInfo["pageSetting"]
- ) {
- let totalHeight = node.height;
- let totalWidth = node.data.type === TopicType.main ? 0 : node.width;
- if (node.children?.length) {
- node.children.forEach((c: HierarchyResult, index) => {
- const childSize = secondWalk(c, pageSetting);
- // const offsetY = node.data.type === TopicType.main ? pageSetting.branchY : pageSetting.subTopicY;
- // 总的高度 = 自身高度 + 子节点的高度 + 节点之间的距离
- totalHeight += childSize.height + pageSetting.branchY;
-
- if (node.data.type === TopicType.main) {
- const offsetX = index < node.children.length - 1 ? pageSetting.branchX : 0;
- totalWidth += childSize.width + offsetX;
- } else {
- // 总的宽度 = 子节点的宽度与自身宽度取最大值
- totalWidth = Math.max(DISTANCE + childSize.width, totalWidth);
- }
- });
- }
- node.totalHeight = totalHeight;
- node.totalWidth = totalWidth;
- return {
- height: totalHeight,
- width: Math.max(totalWidth, node.width),
- };
- }
- function thirdWalk(node: HierarchyResult, pageSetting: MindMapProjectInfo['pageSetting']) {
- let startX = node.width / 2 - node.totalWidth / 2;
- node.children.forEach((child) => {
- child.y = node.y + node.height + pageSetting.branchY;
- child.x = startX;
- startX += child.totalWidth + pageSetting.branchX;
- fourthWalk(child, pageSetting);
- });
- }
- function fourthWalk(node: HierarchyResult, pageSetting: MindMapProjectInfo['pageSetting']) {
- let startY = node.y + node.height + pageSetting.branchY;
- node.children.forEach((child) => {
- child.y = startY;
- child.x = node.x + DISTANCE;
- startY += child.totalHeight + pageSetting.branchY;
- if(child.children.length) {
- fourthWalk(child, pageSetting);
- }
- });
- }
- export const getTreeDiagramHierarchy = <K>(
- topic: TopicItem,
- pageSetting: MindMapProjectInfo["pageSetting"]
- ): K => {
- const root = firstWalk(topic);
- secondWalk(root, pageSetting);
- thirdWalk(root, pageSetting);
- console.log(root);
- return root as K;
- };
|