gaoluyang
2026-11-03 2d8b1a28fa5c8b852f0d0078bac4894bfb4abed5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
/**
 * 部门树选择的核心逻辑(与 UI 解耦,便于单测)
 *
 * 全部对齐 web 端 `form-create/components/dept-select.vue` —— 那里用的是
 * antd `TreeSelect`,且**没有**设置 `treeCheckStrictly` / `showCheckedStrategy`,
 * 因此走的是 antd 默认语义:
 *  - 单选(未开启 tree-checkable):所有节点(含父级)都可作为值;
 *  - 多选:父子联动(勾父级连带全部后代,子级全选的祖先自动入集);
 *  - 多选回填按默认 `showCheckedStrategy = SHOW_CHILD`,即最终值只保留叶子节点。
 */
import type { TreeNodeLike } from "./shared";
 
export interface DeptNode extends TreeNodeLike {
  name?: string;
  children?: DeptNode[];
}
 
/** key -> 节点 / 父节点 / 直接子节点 三张索引表 */
export interface DeptTreeIndex {
  nodeMap: Map<string, DeptNode>;
  parentMap: Map<string, string>;
  childMap: Map<string, DeptNode[]>;
}
 
export const deptKey = (node: DeptNode) => String(node?.id);
 
export function indexDeptTree(nodes: DeptNode[]): DeptTreeIndex {
  const nodeMap = new Map<string, DeptNode>();
  const parentMap = new Map<string, string>();
  const childMap = new Map<string, DeptNode[]>();
  const walk = (list: DeptNode[], parentKey?: string) => {
    (Array.isArray(list) ? list : []).forEach(node => {
      const key = deptKey(node);
      nodeMap.set(key, node);
      if (parentKey !== undefined) parentMap.set(key, parentKey);
      const children = Array.isArray(node.children) ? node.children : [];
      childMap.set(key, children);
      if (children.length) walk(children, key);
    });
  };
  walk(nodes || []);
  return { nodeMap, parentMap, childMap };
}
 
/** 以 key 为根的整棵子树(含自身) */
export function deptSubtreeKeys(index: DeptTreeIndex, key: string): string[] {
  const result = [key];
  (index.childMap.get(key) || []).forEach(child => {
    result.push(...deptSubtreeKeys(index, deptKey(child)));
  });
  return result;
}
 
/**
 * 勾选 / 取消单个节点(父子联动,对齐 antd `treeCheckStrictly = false`)。
 * 向下:连带整棵子树;向上:子级全选的祖先自动入集,否则出集(半选态不入集)。
 * 返回值是新的选中集,不修改入参。
 */
export function toggleDeptCheck(
  index: DeptTreeIndex,
  picked: string[],
  key: string,
): string[] {
  const set = new Set(picked);
  const subtree = deptSubtreeKeys(index, key);
  if (set.has(key)) subtree.forEach(item => set.delete(item));
  else subtree.forEach(item => set.add(item));
 
  let cursor = index.parentMap.get(key);
  while (cursor) {
    const siblings = index.childMap.get(cursor) || [];
    if (!siblings.length) break;
    if (siblings.every(child => set.has(deptKey(child)))) set.add(cursor);
    else set.delete(cursor);
    cursor = index.parentMap.get(cursor);
  }
  return [...set];
}
 
/** all 全选 / half 半选 / none 未选 */
export function deptCheckState(
  index: DeptTreeIndex,
  picked: Set<string>,
  key: string,
): "all" | "half" | "none" {
  const keys = deptSubtreeKeys(index, key);
  const checked = keys.filter(item => picked.has(item)).length;
  if (checked === 0) return "none";
  if (checked === keys.length) return "all";
  return "half";
}
 
/**
 * 提交值。
 * 移植 antd `formatStrategyValues` 的 SHOW_CHILD 分支:
 * 某节点只要「有子级在选中集里」且「全部子级都在选中集里」,该父节点就被剔除。
 * 配合父子联动,效果即最终只保留叶子节点 —— 与 web 端 dept-select.vue 存的值一致。
 */
export function deptSubmitKeys(
  index: DeptTreeIndex,
  picked: string[],
): Array<number | string> {
  const pickedSet = new Set(picked);
  return picked
    .filter(key => {
      const children = index.childMap.get(key) || [];
      if (!children.length) return true;
      const states = children.map(child => pickedSet.has(deptKey(child)));
      return !(states.some(Boolean) && states.every(Boolean));
    })
    .map(key => index.nodeMap.get(key)?.id as number | string)
    .filter(value => value !== undefined && value !== null);
}
 
/**
 * 搜索过滤(对齐 antd `filterTreeNode` + rc-tree filterTree):
 * 节点自身命中时保留整棵子树(便于看清上下文),
 * 否则只要有后代命中就保留该节点作为路径。
 */
export function filterDeptTree(nodes: DeptNode[], keyword: string): DeptNode[] {
  const text = keyword.trim().toLowerCase();
  if (!text) return nodes || [];
  const result: DeptNode[] = [];
  (Array.isArray(nodes) ? nodes : []).forEach(node => {
    const children = Array.isArray(node.children) ? node.children : [];
    const selfMatch = String(node.name || "").toLowerCase().includes(text);
    if (selfMatch) {
      result.push(node);
      return;
    }
    const kept = filterDeptTree(children, text);
    if (kept.length) result.push({ ...node, children: kept });
  });
  return result;
}
 
/** 带层级的拍平结果,用于列表渲染 */
export interface DeptRow {
  key: string;
  node: DeptNode;
  depth: number;
  hasChildren: boolean;
  expanded: boolean;
  state: "all" | "half" | "none";
}
 
/**
 * 按展开状态把树拍平成可渲染的行。
 * children 取传入的「显示树」(搜索后是过滤过的),不会被整棵树覆盖。
 */
export function flattenDeptRows(
  index: DeptTreeIndex,
  displayNodes: DeptNode[],
  expandedKeys: Set<string>,
  pickedSet: Set<string>,
): DeptRow[] {
  const rows: DeptRow[] = [];
  const walk = (list: DeptNode[], depth: number) => {
    (Array.isArray(list) ? list : []).forEach(node => {
      const key = deptKey(node);
      const children = Array.isArray(node.children) ? node.children : [];
      const expanded = expandedKeys.has(key);
      rows.push({
        key,
        node,
        depth,
        hasChildren: children.length > 0,
        expanded,
        state: deptCheckState(index, pickedSet, key),
      });
      if (expanded && children.length) walk(children, depth + 1);
    });
  };
  walk(displayNodes, 0);
  return rows;
}
 
/** 树里有子节点的所有 key(用于「展开全部」) */
export function deptExpandableKeys(nodes: DeptNode[]): string[] {
  const keys: string[] = [];
  const walk = (list: DeptNode[]) => {
    (Array.isArray(list) ? list : []).forEach(node => {
      const children = Array.isArray(node.children) ? node.children : [];
      if (children.length) {
        keys.push(deptKey(node));
        walk(children);
      }
    });
  };
  walk(nodes || []);
  return keys;
}
 
/** 搜索时强制展开所有命中路径 */
export function deptVisibleKeys(nodes: DeptNode[]): Set<string> {
  const keys = new Set<string>();
  const walk = (list: DeptNode[]) => {
    (Array.isArray(list) ? list : []).forEach(node => {
      keys.add(deptKey(node));
      walk(Array.isArray(node.children) ? node.children : []);
    });
  };
  walk(nodes || []);
  return keys;
}