tree.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. interface TreeHelperConfig {
  2. id: string
  3. children: string
  4. pid: string
  5. }
  6. const DEFAULT_CONFIG: TreeHelperConfig = {
  7. id: 'id',
  8. children: 'children',
  9. pid: 'pid'
  10. }
  11. export const defaultProps = {
  12. children: 'children',
  13. label: 'name',
  14. value: 'id',
  15. isLeaf: 'leaf',
  16. multiple: true,
  17. emitPath: false // 用于 cascader 组件:在选中节点改变时,是否返回由该节点所在的各级菜单的值所组成的数组,若设置 false,则只返回该节点的值
  18. }
  19. const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config)
  20. // tree from list
  21. export const listToTree = <T = any>(list: any[], config: Partial<TreeHelperConfig> = {}): T[] => {
  22. const conf = getConfig(config) as TreeHelperConfig
  23. const nodeMap = new Map()
  24. const result: T[] = []
  25. const { id, children, pid } = conf
  26. for (const node of list) {
  27. node[children] = node[children] || []
  28. nodeMap.set(node[id], node)
  29. }
  30. for (const node of list) {
  31. const parent = nodeMap.get(node[pid])
  32. ;(parent ? parent.children : result).push(node)
  33. }
  34. return result
  35. }
  36. export const treeToList = <T = any>(tree: any, config: Partial<TreeHelperConfig> = {}): T => {
  37. config = getConfig(config)
  38. const { children } = config
  39. const result: any = [...tree]
  40. for (let i = 0; i < result.length; i++) {
  41. if (!result[i][children!]) continue
  42. result.splice(i + 1, 0, ...result[i][children!])
  43. }
  44. return result
  45. }
  46. export const findNode = <T = any>(
  47. tree: any,
  48. func: Fn,
  49. config: Partial<TreeHelperConfig> = {}
  50. ): T | null => {
  51. config = getConfig(config)
  52. const { children } = config
  53. const list = [...tree]
  54. for (const node of list) {
  55. if (func(node)) return node
  56. node[children!] && list.push(...node[children!])
  57. }
  58. return null
  59. }
  60. export const findNodeAll = <T = any>(
  61. tree: any,
  62. func: Fn,
  63. config: Partial<TreeHelperConfig> = {}
  64. ): T[] => {
  65. config = getConfig(config)
  66. const { children } = config
  67. const list = [...tree]
  68. const result: T[] = []
  69. for (const node of list) {
  70. func(node) && result.push(node)
  71. node[children!] && list.push(...node[children!])
  72. }
  73. return result
  74. }
  75. export const findPath = <T = any>(
  76. tree: any,
  77. func: Fn,
  78. config: Partial<TreeHelperConfig> = {}
  79. ): T | T[] | null => {
  80. config = getConfig(config)
  81. const path: T[] = []
  82. const list = [...tree]
  83. const visitedSet = new Set()
  84. const { children } = config
  85. while (list.length) {
  86. const node = list[0]
  87. if (visitedSet.has(node)) {
  88. path.pop()
  89. list.shift()
  90. } else {
  91. visitedSet.add(node)
  92. node[children!] && list.unshift(...node[children!])
  93. path.push(node)
  94. if (func(node)) {
  95. return path
  96. }
  97. }
  98. }
  99. return null
  100. }
  101. export const findPathAll = (tree: any, func: Fn, config: Partial<TreeHelperConfig> = {}) => {
  102. config = getConfig(config)
  103. const path: any[] = []
  104. const list = [...tree]
  105. const result: any[] = []
  106. const visitedSet = new Set(),
  107. { children } = config
  108. while (list.length) {
  109. const node = list[0]
  110. if (visitedSet.has(node)) {
  111. path.pop()
  112. list.shift()
  113. } else {
  114. visitedSet.add(node)
  115. node[children!] && list.unshift(...node[children!])
  116. path.push(node)
  117. func(node) && result.push([...path])
  118. }
  119. }
  120. return result
  121. }
  122. export const filter = <T = any>(
  123. tree: T[],
  124. func: (n: T) => boolean,
  125. config: Partial<TreeHelperConfig> = {}
  126. ): T[] => {
  127. config = getConfig(config)
  128. const children = config.children as string
  129. function listFilter(list: T[]) {
  130. return list
  131. .map((node: any) => ({ ...node }))
  132. .filter((node) => {
  133. node[children] = node[children] && listFilter(node[children])
  134. return func(node) || (node[children] && node[children].length)
  135. })
  136. }
  137. return listFilter(tree)
  138. }
  139. export const forEach = <T = any>(
  140. tree: T[],
  141. func: (n: T) => any,
  142. config: Partial<TreeHelperConfig> = {}
  143. ): void => {
  144. config = getConfig(config)
  145. const list: any[] = [...tree]
  146. const { children } = config
  147. for (let i = 0; i < list.length; i++) {
  148. // func 返回true就终止遍历,避免大量节点场景下无意义循环,引起浏览器卡顿
  149. if (func(list[i])) {
  150. return
  151. }
  152. children && list[i][children] && list.splice(i + 1, 0, ...list[i][children])
  153. }
  154. }
  155. /**
  156. * @description: Extract tree specified structure
  157. */
  158. export const treeMap = <T = any>(
  159. treeData: T[],
  160. opt: { children?: string; conversion: Fn }
  161. ): T[] => {
  162. return treeData.map((item) => treeMapEach(item, opt))
  163. }
  164. /**
  165. * @description: Extract tree specified structure
  166. */
  167. export const treeMapEach = (
  168. data: any,
  169. { children = 'children', conversion }: { children?: string; conversion: Fn }
  170. ) => {
  171. const haveChildren = Array.isArray(data[children]) && data[children].length > 0
  172. const conversionData = conversion(data) || {}
  173. if (haveChildren) {
  174. return {
  175. ...conversionData,
  176. [children]: data[children].map((i: number) =>
  177. treeMapEach(i, {
  178. children,
  179. conversion
  180. })
  181. )
  182. }
  183. } else {
  184. return {
  185. ...conversionData
  186. }
  187. }
  188. }
  189. /**
  190. * 递归遍历树结构
  191. * @param treeDatas 树
  192. * @param callBack 回调
  193. * @param parentNode 父节点
  194. */
  195. export const eachTree = (treeDatas: any[], callBack: Fn, parentNode = {}) => {
  196. treeDatas.forEach((element) => {
  197. const newNode = callBack(element, parentNode) || element
  198. if (element.children) {
  199. eachTree(element.children, callBack, newNode)
  200. }
  201. })
  202. }
  203. /**
  204. * 构造树型结构数据
  205. * @param {*} data 数据源
  206. * @param {*} id id字段 默认 'id'
  207. * @param {*} parentId 父节点字段 默认 'parentId'
  208. * @param {*} children 孩子节点字段 默认 'children'
  209. */
  210. export const handleTree = (data: any[], id?: string, parentId?: string, children?: string) => {
  211. if (!Array.isArray(data)) {
  212. console.warn('data must be an array')
  213. return []
  214. }
  215. const config = {
  216. id: id || 'id',
  217. parentId: parentId || 'parentId',
  218. childrenList: children || 'children'
  219. }
  220. const childrenListMap = {}
  221. const nodeIds = {}
  222. const tree: any[] = []
  223. for (const d of data) {
  224. const parentId = d[config.parentId]
  225. if (childrenListMap[parentId] == null) {
  226. childrenListMap[parentId] = []
  227. }
  228. nodeIds[d[config.id]] = d
  229. childrenListMap[parentId].push(d)
  230. }
  231. for (const d of data) {
  232. const parentId = d[config.parentId]
  233. if (nodeIds[parentId] == null) {
  234. tree.push(d)
  235. }
  236. }
  237. for (const t of tree) {
  238. adaptToChildrenList(t)
  239. }
  240. function adaptToChildrenList(o) {
  241. if (childrenListMap[o[config.id]] !== null) {
  242. o[config.childrenList] = childrenListMap[o[config.id]]
  243. }
  244. if (o[config.childrenList]) {
  245. for (const c of o[config.childrenList]) {
  246. adaptToChildrenList(c)
  247. }
  248. }
  249. }
  250. return tree
  251. }
  252. /**
  253. * 构造树型结构数据
  254. * @param {*} data 数据源
  255. * @param {*} id id字段 默认 'id'
  256. * @param {*} parentId 父节点字段 默认 'parentId'
  257. * @param {*} children 孩子节点字段 默认 'children'
  258. * @param {*} rootId 根Id 默认 0
  259. */
  260. // @ts-ignore
  261. export const handleTree2 = (data, id, parentId, children, rootId) => {
  262. id = id || 'id'
  263. parentId = parentId || 'parentId'
  264. // children = children || 'children'
  265. rootId =
  266. rootId ||
  267. Math.min(
  268. ...data.map((item) => {
  269. return item[parentId]
  270. })
  271. ) ||
  272. 0
  273. // 对源数据深度克隆
  274. const cloneData = JSON.parse(JSON.stringify(data))
  275. // 循环所有项
  276. const treeData = cloneData.filter((father) => {
  277. const branchArr = cloneData.filter((child) => {
  278. // 返回每一项的子级数组
  279. return father[id] === child[parentId]
  280. })
  281. branchArr.length > 0 ? (father.children = branchArr) : ''
  282. // 返回第一层
  283. return father[parentId] === rootId
  284. })
  285. return treeData !== '' ? treeData : data
  286. }
  287. /**
  288. * 校验选中的节点,是否为指定 level
  289. *
  290. * @param tree 要操作的树结构数据
  291. * @param nodeId 需要判断在什么层级的数据
  292. * @param level 检查的级别, 默认检查到二级
  293. * @return true 是;false 否
  294. */
  295. export const checkSelectedNode = (tree: any[], nodeId: any, level = 2): boolean => {
  296. if (typeof tree === 'undefined' || !Array.isArray(tree) || tree.length === 0) {
  297. console.warn('tree must be an array')
  298. return false
  299. }
  300. // 校验是否是一级节点
  301. if (tree.some((item) => item.id === nodeId)) {
  302. return false
  303. }
  304. // 递归计数
  305. let count = 1
  306. // 深层次校验
  307. function performAThoroughValidation(arr: any[]): boolean {
  308. count += 1
  309. for (const item of arr) {
  310. if (item.id === nodeId) {
  311. return true
  312. } else if (typeof item.children !== 'undefined' && item.children.length !== 0) {
  313. if (performAThoroughValidation(item.children)) {
  314. return true
  315. }
  316. }
  317. }
  318. return false
  319. }
  320. for (const item of tree) {
  321. count = 1
  322. if (performAThoroughValidation(item.children)) {
  323. // 找到后对比是否是期望的层级
  324. if (count >= level) {
  325. return true
  326. }
  327. }
  328. }
  329. return false
  330. }
  331. /**
  332. * 获取节点的完整结构
  333. * @param tree 树数据
  334. * @param nodeId 节点 id
  335. */
  336. export const treeToString = (tree: any[], nodeId) => {
  337. if (typeof tree === 'undefined' || !Array.isArray(tree) || tree.length === 0) {
  338. console.warn('tree must be an array')
  339. return ''
  340. }
  341. // 校验是否是一级节点
  342. const node = tree.find((item) => item.id === nodeId)
  343. if (typeof node !== 'undefined') {
  344. return node.name
  345. }
  346. let str = ''
  347. function performAThoroughValidation(arr) {
  348. for (const item of arr) {
  349. if (item.id === nodeId) {
  350. str += ` / ${item.name}`
  351. return true
  352. } else if (typeof item.children !== 'undefined' && item.children.length !== 0) {
  353. str += ` / ${item.name}`
  354. if (performAThoroughValidation(item.children)) {
  355. return true
  356. }
  357. }
  358. }
  359. return false
  360. }
  361. for (const item of tree) {
  362. str = `${item.name}`
  363. if (performAThoroughValidation(item.children)) {
  364. break
  365. }
  366. }
  367. return str
  368. }