id_tree.js 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. /**
  2. * Created by Mai on 2017/3/17.
  3. */
  4. var idTree = {
  5. createNew: function (setting) {
  6. var _setting = {
  7. id: 'id',
  8. pid: 'pid',
  9. nid: 'nid',
  10. rootId: -1,
  11. autoUpdate: false
  12. };
  13. var _eventType = {
  14. editedData: 'editedData'
  15. };
  16. var tools = {
  17. findNode: function (nodes, check) {
  18. for (var i = 0; i < nodes.length; i++) {
  19. if (check(nodes[i])) {
  20. return nodes[i];
  21. }
  22. }
  23. return null;
  24. },
  25. reSortNodes: function (nodes, recursive) {
  26. var temp = [], first;
  27. var findFirstNode = function (nodes) {
  28. return tools.findNode(nodes, function (node) {
  29. return node.preSibling === null;
  30. });
  31. };
  32. var moveNode = function (node, orgArray, newArray, newIndex) {
  33. var current = node, currentIndex, next;
  34. // 不能递归:同级节点很多时,即使链正确也会超过浏览器调用栈。
  35. while (current) {
  36. currentIndex = orgArray.indexOf(current);
  37. if (currentIndex < 0) {
  38. break;
  39. }
  40. orgArray.splice(currentIndex, 1);
  41. newArray.splice(newIndex, 0, current);
  42. newIndex++;
  43. next = current.nextSibling;
  44. // next 不在当前同级数组中,说明它已处理、跨层、缺失、自指或成环。
  45. // 停止当前链,剩余节点交给外层 while 继续显示。
  46. if (!next || orgArray.indexOf(next) < 0) {
  47. break;
  48. }
  49. current = next;
  50. }
  51. };
  52. if (nodes.length === 0) {
  53. return nodes;
  54. }
  55. if (recursive) {
  56. nodes.forEach(function (node) {
  57. node.children = tools.reSortNodes(node.children, recursive);
  58. });
  59. }
  60. while (nodes.length > 0) {
  61. first = findFirstNode(nodes);
  62. first = first ? first : nodes[0];
  63. moveNode(first, nodes, temp, temp.length);
  64. }
  65. nodes = null;
  66. tools.reSiblingNodes(temp);
  67. return temp;
  68. },
  69. reSiblingNodes: function (nodes) {
  70. var i;
  71. for (i = 0; i < nodes.length; i++) {
  72. nodes[i].preSibling = (i === 0) ? null : nodes[i - 1];
  73. nodes[i].nextSibling = (i === nodes.length - 1) ? null : nodes[i + 1];
  74. }
  75. },
  76. // 在nodes中,从iIndex(包括)开始全部移除
  77. removeNodes: function (tree, parent, iIndex, count) {
  78. var children = parent ? parent.children : tree.roots;
  79. var pre = (iIndex < 0 || iIndex >= children.length) ? null : children[iIndex].preSibling;
  80. var next = (pre && iIndex + count - 1 < children.length) ? children[iIndex + count] : null;
  81. if (pre) {
  82. pre.setNextSibling(next);
  83. } else if (next) {
  84. next.preSibling = null;
  85. }
  86. if (arguments.length === 4) {
  87. children.splice(iIndex, count);
  88. } else {
  89. children.splice(iIndex, children.length - iIndex);
  90. }
  91. },
  92. // 在parent.children/tree.roots中增加nodes, 位置从index开始
  93. addNodes: function (tree, parent, nodes, iIndex) {
  94. var children = parent ? parent.children : tree.roots;
  95. var pre, next, i;
  96. if (nodes.length === 0) { return; }
  97. if (arguments.length === 4) {
  98. pre = (iIndex <= 0 || iIndex > children.length) ? null : children[iIndex - 1];
  99. next = pre ? pre.nextSibling : null;
  100. } else if (arguments.length === 3) {
  101. pre = children.length === 0 ? null : children[children.length - 1];
  102. next = null;
  103. }
  104. if (pre) {
  105. pre.setNextSibling(nodes[0]);
  106. } else {
  107. nodes[0].preSibling = null;
  108. }
  109. nodes[nodes.length - 1].setNextSibling(next);
  110. for (i = 0; i < nodes.length; i++) {
  111. if (arguments.length === 4) {
  112. children.splice(iIndex + i, 0, nodes[i]);
  113. } else if (arguments.length === 3) {
  114. children.push(nodes[i]);
  115. }
  116. nodes[i].setParent(parent ? parent : null);
  117. }
  118. },
  119. sortTreeItems: function (tree) {
  120. var addItems = function (items) {
  121. var i;
  122. for (i = 0; i < items.length; i++) {
  123. tree.items.push(items[i]);
  124. addItems(items[i].children);
  125. }
  126. };
  127. tree.items.splice(0, tree.items.length);
  128. addItems(tree.roots);
  129. },
  130. addUpdateDataForParent: function (datas, nodes, pid) {
  131. nodes.forEach(function (node) {
  132. datas.push({ type: 'update', data: node.tree.getDataTemplate(node.getID(), pid, node.getNextSiblingID()) });
  133. });
  134. },
  135. addUpdateDataForNextSibling: function (datas, node, nid) {
  136. if (node) {
  137. datas.push({ type: 'update', data: node.tree.getDataTemplate(node.getID(), node.getParentID(), nid) });
  138. }
  139. }
  140. };
  141. var Node = function (tree, data) {
  142. // 以下的属性,本单元外均不可直接修改
  143. this.tree = tree;
  144. this.data = data;
  145. this.children = [];
  146. this.parent = null;
  147. this.nextSibling = null;
  148. this.preSibling = null;
  149. this.expanded = true;
  150. this.visible = true;
  151. this.visible = true;
  152. };
  153. Node.prototype.getID = function () {
  154. return this.data[this.tree.setting.id];
  155. };
  156. Node.prototype.getParentID = function () {
  157. return this.parent ? this.parent.getID() : -1;
  158. };
  159. Node.prototype.getNextSiblingID = function () {
  160. return this.nextSibling ? this.nextSibling.getID() : -1;
  161. };
  162. Node.prototype.setParent = function (parent) {
  163. this.parent = parent;
  164. if (this.tree.setting.autoUpdate) {
  165. this.data[this.tree.setting.pid] = this.getParentID();
  166. }
  167. };
  168. Node.prototype.setNextSibling = function (nextSibling) {
  169. this.nextSibling = nextSibling;
  170. if (nextSibling) {
  171. nextSibling.preSibling = this;
  172. }
  173. if (this.tree.setting.autoUpdate) {
  174. this.data[this.tree.setting.nid] = this.getNextSiblingID();
  175. }
  176. }
  177. Node.prototype.firstChild = function () {
  178. return this.children.length === 0 ? null : this.children[0];
  179. };
  180. Node.prototype.lastChild = function () {
  181. return this.children.length === 0 ? null : this.children[this.children.length - 1];
  182. };
  183. Node.prototype.depth = function () {
  184. return this.parent ? this.parent.depth() + 1 : 0;
  185. };
  186. Node.prototype.isFirst = function () {
  187. if (this.parent) {
  188. return this.parent.children.indexOf(this) === 0 ? true : false;
  189. } else {
  190. return this.tree.roots.indexOf(this) === 0 ? true : false;
  191. }
  192. };
  193. Node.prototype.isLast = function () {
  194. if (this.parent) {
  195. return this.parent.children.indexOf(this) === this.parent.children.length - 1 ? true : false;
  196. } else {
  197. return this.tree.roots.indexOf(this) === this.tree.roots.length - 1 ? true : false;
  198. }
  199. };
  200. Node.prototype.siblingIndex = function () {
  201. return this.parent ? this.parent.children.indexOf(this) : this.tree.roots.indexOf(this);
  202. };
  203. Node.prototype.posterityCount = function () {
  204. var iCount = 0;
  205. if (this.children.length !== 0) {
  206. iCount += this.children.length;
  207. this.children.forEach(function (child) {
  208. iCount += child.posterityCount();
  209. });
  210. }
  211. return iCount;
  212. /*return (node.children.length === 0) ? 0 : node.children.reduce(function (x, y) {
  213. return x.posterityCount() + y.posterityCount();
  214. }) + node.children.count;*/
  215. };
  216. Node.prototype.posterityLeafCount = function () {
  217. return this.getPosterity().filter(item => !item.children.length).length;
  218. };
  219. // 获取节点所有后代节点
  220. Node.prototype.getPosterity = function () {
  221. let posterity = [];
  222. getNodes(this.children);
  223. return posterity;
  224. function getNodes(nodes) {
  225. for (let node of nodes) {
  226. posterity.push(node);
  227. if (node.children.length > 0) {
  228. getNodes(node.children);
  229. }
  230. }
  231. }
  232. };
  233. // 担心链有问题,preSibling不靠谱的话,按照显示顺序算preSibling
  234. Node.prototype.prevNode = function () {
  235. const parent = this.parent || this.tree.roots;
  236. if (!parent) {
  237. return null;
  238. }
  239. const children = parent === this.tree.roots ? this.tree.roots : parent.children;
  240. const index = children.indexOf(this);
  241. return children[index - 1] || null;
  242. }
  243. Node.prototype.setExpanded = function (expanded) {
  244. var setNodesVisible = function (nodes, visible) {
  245. nodes.forEach(function (node) {
  246. node.visible = visible;
  247. setNodesVisible(node.children, visible && node.expanded);
  248. })
  249. };
  250. this.expanded = expanded;
  251. setNodesVisible(this.children, expanded);
  252. };
  253. /*Node.prototype.vis = function () {
  254. return this.parent ? this.parent.vis() && this.parent.expanded() : true;
  255. };*/
  256. Node.prototype.serialNo = function () {
  257. return this.tree.items.indexOf(this);
  258. };
  259. Node.prototype.addChild = function (node) {
  260. var preSibling = this.children.length === 0 ? null : this.children[this.children.length - 1];
  261. node.parent = this;
  262. if (preSibling) {
  263. preSibling.nextSibling = node;
  264. }
  265. node.preSibling = preSibling;
  266. this.children.push(node);
  267. };
  268. Node.prototype.removeChild = function (node) {
  269. var preSibling = node.preSibling, nextSibling = node.nextSibling;
  270. if (preSibling) {
  271. preSibling.nextSibling = nextSibling;
  272. }
  273. if (nextSibling) {
  274. nextSibling.preSibling = preSibling;
  275. }
  276. this.children.splice(node.siblingIndex, 1);
  277. };
  278. Node.prototype.canUpLevel = function () {
  279. return this.parent ? true : false;
  280. };
  281. Node.prototype.getUpLevelData = function () {
  282. var data = [];
  283. if (this.canUpLevel()) {
  284. if (!this.isLast()) {
  285. tools.addUpdateDataForParent(data, this.parent.children.slice(this.siblingIndex() + 1), this.getID());
  286. }
  287. if (this.preSibling) {
  288. tools.addUpdateDataForNextSibling(data, this.preSibling, this.tree.setting.rootId);
  289. }
  290. tools.addUpdateDataForNextSibling(data, this.parent, this.getID());
  291. data.push({ type: 'update', data: this.tree.getDataTemplate(this.getID(), this.parent.getParentID(), this.parent.getNextSiblingID()) });
  292. }
  293. return data;
  294. };
  295. Node.prototype.upLevel = function () {
  296. var result = { success: false, updateDatas: [] };
  297. var iIndex = this.parent.children.indexOf(this), orgParent = this.parent, newNextSibling = this.parent.nextSibling;
  298. if (this.canUpLevel) {
  299. // NextSiblings become child
  300. tools.addNodes(this.tree, this, this.parent.children.slice(iIndex + 1));
  301. // Orginal Parent remove node and nextSiblings
  302. tools.removeNodes(this.tree, this.parent, iIndex);
  303. // New Parent add node
  304. tools.addNodes(this.tree, this.parent.parent, [this], this.parent.siblingIndex() + 1);
  305. if (!this.expanded) {
  306. this.setExpanded(true);
  307. }
  308. result.success = true;
  309. }
  310. return result;
  311. };
  312. Node.prototype.canDownLevel = function () {
  313. return !this.isFirst();
  314. };
  315. Node.prototype.getDownLevelData = function () {
  316. var data = [];
  317. if (this.canDownLevel()) {
  318. if (this.preSibling.children.length !== 0) {
  319. tools.addUpdateDataForNextSibling(data, this.preSibling.lastChild(), this.getID());
  320. }
  321. tools.addUpdateDataForNextSibling(data, this.preSibling, this.getNextSiblingID());
  322. data.push({ type: 'update', data: this.tree.getDataTemplate(this.getID(), this.preSibling.getID(), this.tree.setting.rootId) });
  323. }
  324. return data;
  325. };
  326. Node.prototype.downLevel = function () {
  327. var success = false, iIndex = this.parent ? this.parent.children.indexOf(this) : this.tree.roots.indexOf(this);
  328. var newParent = this.preSibling;
  329. if (this.canDownLevel()) {
  330. tools.removeNodes(this.tree, this.parent, this.siblingIndex(), 1);
  331. tools.addNodes(this.tree, this.preSibling, [this]);
  332. if (!newParent.expanded) {
  333. newParent.setExpanded(true);
  334. }
  335. success = true;
  336. }
  337. return success;
  338. };
  339. Node.prototype.canUpMove = function () {
  340. return !this.isFirst();
  341. };
  342. Node.prototype.getUpMoveData = function () {
  343. var data = [];
  344. if (this.canUpMove()) {
  345. if (this.preSibling.preSibling) {
  346. tools.addUpdateDataForNextSibling(data, this.preSibling.preSibling, this.getID());
  347. }
  348. tools.addUpdateDataForNextSibling(data, this.preSibling, this.getNextSiblingID());
  349. tools.addUpdateDataForNextSibling(data, this, this.preSibling.getID());
  350. }
  351. return data;
  352. };
  353. Node.prototype.upMove = function () {
  354. var success = false;
  355. var iIndex = this.siblingIndex(), belongArray = this.parent ? this.parent.children : this.tree.roots, orgPre = this.preSibling;
  356. if (this.canUpMove()) {
  357. if (orgPre.preSibling) {
  358. orgPre.preSibling.setNextSibling(this);
  359. } else {
  360. this.preSibling = null;
  361. }
  362. orgPre.setNextSibling(this.nextSibling);
  363. this.setNextSibling(orgPre);
  364. belongArray.splice(iIndex, 1);
  365. belongArray.splice(iIndex - 1, 0, this);
  366. tools.sortTreeItems(this.tree);
  367. success = true;
  368. }
  369. return success;
  370. };
  371. Node.prototype.canDownMove = function () {
  372. return !this.isLast();
  373. };
  374. Node.prototype.getDownMoveData = function () {
  375. var data = [];
  376. if (this.canDownMove()) {
  377. if (this.preSibling) {
  378. tools.addUpdateDataForNextSibling(data, this.preSibling, this.nextSibling.getID());
  379. }
  380. tools.addUpdateDataForNextSibling(data, this, this.nextSibling.getNextSiblingID());
  381. tools.addUpdateDataForNextSibling(data, this.nextSibling, this.getID());
  382. }
  383. return data;
  384. };
  385. Node.prototype.downMove = function () {
  386. var success = false;
  387. var iIndex = this.siblingIndex(), belongArray = this.parent ? this.parent.children : this.tree.roots, orgNext = this.nextSibling;
  388. if (this.canDownMove()) {
  389. if (this.preSibling) {
  390. this.preSibling.setNextSibling(orgNext);
  391. } else if (orgNext) {
  392. orgNext.preSibling = null;
  393. }
  394. this.setNextSibling(orgNext.nextSibling);
  395. orgNext.setNextSibling(this);
  396. belongArray.splice(iIndex, 1);
  397. belongArray.splice(iIndex + 1, 0, this);
  398. tools.sortTreeItems(this.tree);
  399. success = true;
  400. }
  401. return success;
  402. };
  403. var Tree = function (setting) {
  404. this.nodes = {};
  405. this.roots = [];
  406. this.items = [];
  407. this.setting = setting;
  408. this.prefix = 'id_';
  409. this.selected = null;
  410. this.event = {};
  411. this.eventType = _eventType;
  412. };
  413. Tree.prototype.getDataTemplate = function (id, pid, nid) {
  414. var data = {};
  415. data[this.setting.id] = id;
  416. data[this.setting.pid] = pid;
  417. data[this.setting.nid] = nid;
  418. return data;
  419. };
  420. Tree.prototype.maxNodeID = (function () {
  421. var maxID = 0;
  422. return function (ID) {
  423. if (arguments.length === 0) {
  424. return maxID;
  425. } else {
  426. maxID = Math.max(maxID, ID);
  427. }
  428. };
  429. })();
  430. Tree.prototype.rangeNodeID = (function () {
  431. var rangeID = -1;
  432. return function (ID) {
  433. if (arguments.length === 0) {
  434. return rangeID;
  435. } else {
  436. rangeID = Math.max(rangeID, ID);
  437. }
  438. }
  439. })();
  440. Tree.prototype.newNodeID = function () {
  441. if (this.rangeNodeID() == -1) {
  442. return this.maxNodeID() + 1;
  443. } else {
  444. if (this.maxNodeID() < this.rangeNodeID()) {
  445. return this.maxNodeID() + 1;
  446. } else {
  447. return -1;
  448. }
  449. }
  450. /*if (this.maxID >= this.rangeNodeID() || this.rangeNodeID === -1) {
  451. return -1;
  452. } else {
  453. return this.maxNodeID() + 1;
  454. }*/
  455. };
  456. Tree.prototype.clearNodes = function () {
  457. this.nodes = {};
  458. this.roots = [];
  459. this.items = [];
  460. };
  461. Tree.prototype.loadDatas = function (datas) {
  462. var prefix = this.prefix, i, node, parent, next, that = this;
  463. this.nodes = {};
  464. this.roots = [];
  465. this.items = [];
  466. // prepare index
  467. datas.forEach(function (data) {
  468. var node = new Node(that, data);
  469. that.nodes[prefix + data[that.setting.id]] = node;
  470. that.maxNodeID(data[that.setting.id]);
  471. });
  472. // set parent by pid, set nextSibling by nid
  473. datas.forEach(function (data) {
  474. node = that.nodes[prefix + data[that.setting.id]];
  475. if (data[that.setting.pid] == that.setting.rootId) {
  476. that.roots.push(node);
  477. } else {
  478. parent = that.nodes[prefix + data[that.setting.pid]];
  479. if (parent) {
  480. node.parent = parent;
  481. parent.children.push(node);
  482. }
  483. }
  484. if (data[that.setting.nid] !== that.setting.rootId) {
  485. next = that.nodes[prefix + data[that.setting.nid]];
  486. if (next) {
  487. node.nextSibling = next;
  488. next.preSibling = node;
  489. }
  490. }
  491. })
  492. // sort by nid
  493. this.roots = tools.reSortNodes(this.roots, true);
  494. tools.sortTreeItems(this);
  495. };
  496. Tree.prototype.firstNode = function () {
  497. return this.roots.length === 0 ? null : this.roots[0];
  498. };
  499. Tree.prototype.findNode = function (id) {
  500. return this.nodes[this.prefix + id];
  501. };
  502. Tree.prototype.count = function () {
  503. var iCount = 0;
  504. if (this.roots.length !== 0) {
  505. iCount += this.roots.length;
  506. this.roots.forEach(function (node) {
  507. iCount += node.posterityCount();
  508. });
  509. }
  510. return iCount;
  511. };
  512. Tree.prototype.insert = function (parentID, nextSiblingID) {
  513. var newID = this.newNodeID(), node = null, data = {};
  514. var parent = parentID == -1 ? null : this.nodes[this.prefix + parentID];
  515. var nextSibling = nextSiblingID == -1 ? null : this.nodes[this.prefix + nextSiblingID];
  516. if (newID !== -1) {
  517. data = {};
  518. data[this.setting.id] = newID;
  519. data[this.setting.pid] = parent ? parent.getID() : this.setting.rootId;
  520. data[this.setting.nid] = nextSibling ? nextSibling.getID() : this.setting.rootId;
  521. node = new Node(this, data);
  522. if (nextSibling) {
  523. tools.addNodes(this, parent, [node], nextSibling.siblingIndex());
  524. } else {
  525. tools.addNodes(this, parent, [node]);
  526. }
  527. this.nodes[this.prefix + newID] = node;
  528. tools.sortTreeItems(this);
  529. this.maxNodeID(newID);
  530. }
  531. return node;
  532. };
  533. Tree.prototype.m_insert = function (datas, parentID, nextSiblingID) {
  534. // var newID = this.newNodeID(), node = null, data = {};
  535. var parent = parentID == -1 ? null : this.nodes[this.prefix + parentID];
  536. var nextSibling = nextSiblingID == -1 ? null : this.nodes[this.prefix + nextSiblingID];
  537. let preInsertNode = null, nodes = [];
  538. for (let d of datas) {
  539. let node = new Node(this, d.data);
  540. if (preInsertNode == null) {
  541. if (nextSibling) {
  542. tools.addNodes(this, parent, [node], nextSibling.siblingIndex());
  543. } else {
  544. tools.addNodes(this, parent, [node]);
  545. }
  546. } else {
  547. tools.addNodes(this, parent, [node], preInsertNode.siblingIndex());
  548. }
  549. this.nodes[this.prefix + d.data.ID] = node;
  550. if (preInsertNode) node.setNextSibling(preInsertNode);
  551. preInsertNode = node;
  552. nodes.push(node);
  553. }
  554. tools.sortTreeItems(this);
  555. return nodes;
  556. };
  557. Tree.prototype.insertByID = function (newID, parentID, nextSiblingID) {
  558. var node = null, data = {};
  559. var parent = parentID == -1 ? null : this.nodes[this.prefix + parentID];
  560. var nextSibling = nextSiblingID == -1 ? null : this.nodes[this.prefix + nextSiblingID];
  561. if (newID) {
  562. data = {};
  563. data[this.setting.id] = newID;
  564. data[this.setting.pid] = parent ? parent.getID() : this.setting.rootId;
  565. data[this.setting.nid] = nextSibling ? nextSibling.getID() : this.setting.rootId;
  566. node = new Node(this, data);
  567. if (nextSibling) {
  568. tools.addNodes(this, parent, [node], nextSibling.siblingIndex());
  569. } else {
  570. tools.addNodes(this, parent, [node]);
  571. }
  572. this.nodes[this.prefix + newID] = node;
  573. tools.sortTreeItems(this);
  574. }
  575. return node;
  576. };
  577. Tree.prototype.getInsertData = function (parentID, nextSiblingID) {
  578. var data = [];
  579. var newID = this.newNodeID();
  580. var parent = parentID == -1 ? null : this.nodes[this.prefix + parentID];
  581. var nextSibling = nextSiblingID == -1 ? null : this.nodes[this.prefix + nextSiblingID];
  582. if (newID !== -1) {
  583. data.push({ type: 'new', data: this.getDataTemplate(newID, parent ? parent.getID() : this.setting.rootId, nextSibling ? nextSibling.getID() : this.setting.rootId) });
  584. if (nextSibling && nextSibling.preSibling) {
  585. tools.addUpdateDataForNextSibling(data, nextSibling.preSibling, newID);
  586. } else if (parent && parent.children.length !== 0) {
  587. tools.addUpdateDataForNextSibling(data, parent.lastChild(), newID);
  588. } else if (!parent && this.roots.length !== 0) {
  589. tools.addUpdateDataForNextSibling(data, this.roots[this.roots.length - 1], newID);
  590. }
  591. }
  592. return data;
  593. };
  594. //插入多行
  595. Tree.prototype.getInsertDatas = function (rowCount, parentID, nextSiblingID) {
  596. let data = [], preInsertID = null, lastID;
  597. let parent = parentID == -1 ? null : this.nodes[this.prefix + parentID];
  598. let nextSibling = nextSiblingID == -1 ? null : this.nodes[this.prefix + nextSiblingID];
  599. for (let i = 0; i < rowCount; i++) {//先插入的在最后,后插的在最前
  600. let newID = this.newNodeID();
  601. if (newID !== -1) {
  602. if (preInsertID == null) {//说明是第一个插入的
  603. data.push({ type: 'new', data: this.getDataTemplate(newID, parent ? parent.getID() : this.setting.rootId, nextSibling ? nextSibling.getID() : this.setting.rootId) });
  604. } else {//其它的下一节点ID取上一个插入的节点
  605. data.push({ type: 'new', data: this.getDataTemplate(newID, parent ? parent.getID() : this.setting.rootId, preInsertID) });
  606. }
  607. this.maxNodeID(newID);
  608. preInsertID = newID;
  609. }
  610. }
  611. if (nextSibling && nextSibling.preSibling) {
  612. tools.addUpdateDataForNextSibling(data, nextSibling.preSibling, preInsertID);
  613. } else if (parent && parent.children.length !== 0) {
  614. tools.addUpdateDataForNextSibling(data, parent.lastChild(), preInsertID);
  615. } else if (!parent && this.roots.length !== 0) {
  616. tools.addUpdateDataForNextSibling(data, this.roots[this.roots.length - 1], preInsertID);
  617. }
  618. return data;
  619. };
  620. Tree.prototype.insertByData = function (data, parentID, nextSiblingID) {
  621. var parent = parentID == -1 ? null : this.nodes[this.prefix + parentID];
  622. var nextSibling = nextSiblingID == -1 ? null : this.nodes[this.prefix + nextSiblingID];
  623. var node = this.nodes[this.prefix + data[this.setting.id]];
  624. if (node) {
  625. return node;
  626. } else {
  627. node = new Node(this, data);
  628. if (nextSibling) {
  629. tools.addNodes(this, parent, [node], nextSibling.siblingIndex());
  630. } else {
  631. tools.addNodes(this, parent, [node]);
  632. }
  633. this.nodes[this.prefix + data[this.setting.id]] = node;
  634. tools.sortTreeItems(this);
  635. this.maxNodeID(data[this.setting.id]);
  636. return node;
  637. }
  638. };
  639. // 插入离散节点
  640. Tree.prototype.insertByDatas = function (datas) {
  641. const nodes = [];
  642. datas.forEach(item => {
  643. const node = this.insertByData(item, item.ParentID, item.NextSiblingID);
  644. nodes.push(node);
  645. });
  646. return nodes;
  647. };
  648. //批量新增节点到节点后项,节点已有树结构数据
  649. Tree.prototype.insertDatasTo = function (preData, datas) {
  650. let rst = [];
  651. for (let data of datas) {
  652. this.nodes[this.prefix + data.ID] = new Node(this, data.ID);
  653. this.nodes[this.prefix + data.ID]['data'] = data;
  654. rst.push(this.nodes[this.prefix + data.ID]);
  655. }
  656. for (let data of datas) {
  657. let node = this.nodes[this.prefix + data.ID];
  658. let parent = data.ParentID == -1 ? null : this.nodes[this.prefix + data.ParentID];
  659. node.parent = parent;
  660. if (!parent) {
  661. this.roots.push(node);
  662. }
  663. else {
  664. parent.children.push(node);
  665. }
  666. let next = data.NextSiblingID == -1 ? null : this.nodes[this.prefix + data.NextSiblingID];
  667. node.nextSibling = next;
  668. if (next) {
  669. next.preSibling = node;
  670. }
  671. }
  672. let preNode = this.nodes[this.prefix + preData.ID];
  673. if (preNode) {
  674. preNode.nextSibling = this.nodes[this.prefix + preData.NextSiblingID] ? this.nodes[this.prefix + preData.NextSiblingID] : null;
  675. if (preNode.nextSibling) {
  676. preNode.nextSibling.preSibling = preNode;
  677. }
  678. }
  679. //resort
  680. this.roots = tools.reSortNodes(this.roots, true);
  681. tools.sortTreeItems(this);
  682. return rst;
  683. };
  684. Tree.prototype.delete = function (node) {
  685. var success = false, that = this;
  686. if (node) success = that.m_delete([node]);
  687. return success;
  688. };
  689. Tree.prototype.m_delete = function (nodes) {
  690. let success = false, that = this;
  691. let deleteIdIndex = function (nodes) {
  692. nodes.forEach(function (node) {
  693. delete that.nodes[that.prefix + node.getID()];
  694. deleteIdIndex(node.children);
  695. })
  696. };
  697. for (let n of nodes) {
  698. deleteIdIndex([n]);
  699. if (n.preSibling) {
  700. n.preSibling.setNextSibling(n.nextSibling);
  701. } else if (n.nextSibling) {
  702. n.nextSibling.preSibling = null;
  703. }
  704. if (n.parent) {
  705. n.parent.children.splice(n.siblingIndex(), 1);
  706. } else {
  707. this.roots.splice(n.siblingIndex(), 1);
  708. }
  709. }
  710. tools.sortTreeItems(this);
  711. success = true;
  712. return success;
  713. };
  714. Tree.prototype.m_upLevel = function (nodes) {//原先的父节点变成前一个节点,原先的兄弟节点变成子节点
  715. let o_parent = nodes[0].parent;//原来的父节点
  716. let o_next = o_parent.nextSibling;//父节点的下一节点
  717. let o_pre = nodes[0].preSibling;
  718. let o_children = o_parent.children;//旧的所有兄弟节点
  719. let children = o_parent.parent ? o_parent.parent.children : this.roots;//新的兄弟节点
  720. let last;
  721. let lastNext;//最后一个选中节点后面的所有兄弟节点变成最后一个节点的子节点
  722. for (let i = 0; i < nodes.length; i++) {
  723. let index = children.indexOf(o_parent) + 1;
  724. children.splice(index + i, 0, nodes[i]);//往新的父节点的子节点插入节点
  725. o_children.splice(nodes[i].siblingIndex(), 1);//旧的数组删除节点
  726. if (i == 0) {//第一个节点变成原来父节点的下一节点
  727. o_parent.setNextSibling(nodes[i]);
  728. if (o_pre) o_pre.setNextSibling(null); //第一个选中节点的前一节点的下一节点设置为空
  729. }
  730. nodes[i].setParent(o_parent.parent);
  731. last = nodes[i];
  732. lastNext = last.nextSibling;
  733. }
  734. last.setNextSibling(o_next);//最后一个选中的节点的下一个节点设置为原父节点的下一节点
  735. if (lastNext) {
  736. let t_index = o_children.indexOf(lastNext);
  737. for (let j = t_index; j < o_children.length; j++) {//剩下的添加为最后一个选中节点的子节点
  738. last.addChild(o_children[j]);
  739. }
  740. if (o_children.length > t_index) o_children.splice(t_index, o_children.length - t_index);//从原先的children中移除
  741. }
  742. if (o_parent.parent && !o_parent.parent.expanded) o_parent.parent.setExpanded(true);
  743. tools.sortTreeItems(this);
  744. return true;
  745. };
  746. Tree.prototype.getUpLevelDatas = function (nodes) {
  747. //getParentID
  748. let o_parentID = nodes[0].getParentID();
  749. let o_children = nodes[0].parent.children;//旧的所有兄弟节点
  750. let o_pre = nodes[0].preSibling;
  751. let new_parentID = nodes[0].parent.getParentID();
  752. let o_nextID = nodes[0].parent.getNextSiblingID();
  753. let dataMap = {}, updateDatas = [], lastID, lastNext;
  754. for (let i = 0; i < nodes.length; i++) {
  755. if (i == 0) {
  756. dataMap[o_parentID] = { "ID": o_parentID, "NextSiblingID": nodes[i].getID() };
  757. if (o_pre) dataMap[o_pre.getID()] = { "ID": o_pre.getID(), "NextSiblingID": -1 }; //nodes[i].preSibling.setNextSibling(null);
  758. }
  759. dataMap[nodes[i].getID()] = { "ID": nodes[i].getID(), "ParentID": new_parentID };
  760. lastID = nodes[i].getID();
  761. lastNext = nodes[i].nextSibling;
  762. }
  763. if (dataMap[lastID] !== undefined) {
  764. dataMap[lastID].NextSiblingID = o_nextID;
  765. }
  766. if (lastNext) {
  767. let t_index = o_children.indexOf(lastNext);
  768. for (let j = t_index; j < o_children.length; j++) {//剩下的添加为最后一个选中节点的子节点
  769. dataMap[o_children[j].getID()] = { "ID": o_children[j].getID(), "ParentID": lastID };
  770. }
  771. }
  772. for (let key in dataMap) {
  773. updateDatas.push({ type: 'update', data: dataMap[key] });
  774. }
  775. return updateDatas;
  776. };
  777. Tree.prototype.m_downLevel = function (nodes) {
  778. let pre = nodes[0].preSibling; //第一个节点的前一节点,即会成为新的父节点
  779. let next;//最后一个节点的后一节点,会成为pre 的下一个节点
  780. let last;//选中的最后一个节点,nextSibling要设置为0
  781. for (let n of nodes) {
  782. next = n.nextSibling;
  783. last = n;
  784. let children = n.parent ? n.parent.children : this.roots;
  785. children.splice(n.siblingIndex(), 1);
  786. pre.addChild(n);
  787. }
  788. if (!pre.expanded) pre.setExpanded(true);
  789. pre.setNextSibling(next);
  790. last.nextSibling = null;
  791. tools.sortTreeItems(this);
  792. return true;
  793. };
  794. Tree.prototype.getDownLevelDatas = function (nodes) {
  795. let dataMap = {}, updateDatas = [], nextID, last;//注释同m_downLevel 方法
  796. let newParent = nodes[0].preSibling;//{"type":"update","data":{"ID":3,"ParentID":-1,"NextSiblingID":5}}
  797. let newPre = newParent.children && newParent.children.length > 0 ? newParent.children[newParent.children.length - 1] : null;
  798. if (newPre) { //如果新的父节点有子节点,则把新的父节点的最后一个子节点的下一节点的值改成第一个选中节点的ID
  799. dataMap[newPre.getID()] = { "ID": newPre.getID(), "NextSiblingID": nodes[0].getID() }
  800. }
  801. for (let n of nodes) {
  802. nextID = n.getNextSiblingID();
  803. last = n;
  804. dataMap[n.getID()] = { "ID": n.getID(), "ParentID": newParent.getID() }//修改父ID;
  805. }
  806. dataMap[newParent.getID()] = { "ID": newParent.getID(), "NextSiblingID": nextID }//设置新的父节点的下一个节点ID;
  807. if (dataMap[last.getID()] !== undefined) {//把最后一个节点的下一个节点ID变成-1
  808. dataMap[last.getID()].NextSiblingID = -1
  809. } else {
  810. dataMap[last.getID()] = { "ID": last.getID(), "NextSiblingID": -1 };
  811. }
  812. for (let key in dataMap) {
  813. updateDatas.push({ type: 'update', data: dataMap[key] });
  814. }
  815. return updateDatas;
  816. };
  817. Tree.prototype.getDeleteData = function (node) {
  818. var data = [];
  819. var addUpdateDataForDelete = function (datas, nodes) {
  820. nodes.forEach(function (node) {
  821. var delData = {};
  822. delData[node.tree.setting.id] = node.getID();
  823. datas.push({ type: 'delete', data: delData });
  824. addUpdateDataForDelete(datas, node.children);
  825. })
  826. };
  827. if (node) {
  828. addUpdateDataForDelete(data, [node]);
  829. if (node.preSibling) {
  830. tools.addUpdateDataForNextSibling(data, node.preSibling, node.getNextSiblingID());
  831. }
  832. }
  833. return data;
  834. };
  835. Tree.prototype.getDeleteDatas = function (deleteMap, deleteNodes) {//批量删除
  836. let datas = [];
  837. addDeleteDatas(datas, deleteNodes);
  838. for (let d of deleteNodes) {
  839. addPreUpdateData(datas, deleteMap, d.preSibling, d.nextSibling);
  840. }
  841. function addPreUpdateData(updateDatas, map, preSibling, nextSibling) {
  842. if (preSibling && (map[preSibling.getID()] == undefined || map[preSibling.getID()] == null)) {
  843. if (nextSibling) {
  844. if (map[nextSibling.getID()]) {//如果下一个节点也是要删除的,则再往下顺延
  845. addPreUpdateData(updateDatas, map, preSibling, nextSibling.nextSibling);
  846. } else {
  847. updateDatas.push({ type: 'update', data: preSibling.tree.getDataTemplate(preSibling.getID(), preSibling.getParentID(), nextSibling.getID()) });
  848. }
  849. } else {
  850. updateDatas.push({ type: 'update', data: preSibling.tree.getDataTemplate(preSibling.getID(), preSibling.getParentID(), -1) });
  851. }
  852. }
  853. }
  854. function addDeleteDatas(dataArray, nodes) {
  855. for (let n of nodes) {
  856. let delData = {};
  857. delData[n.tree.setting.id] = n.getID();
  858. dataArray.push({ type: 'delete', data: delData });
  859. addDeleteDatas(dataArray, n.children);
  860. }
  861. }
  862. return datas;
  863. };
  864. /*Tree.prototype.editedData = function (field, id, newText) {
  865. var node = this.findNode(id), result = {allow: false, nodes: []};
  866. if (this.event[this.eventType.editedData]) {
  867. return this.event[this.eventType.editedData](field, node.data);
  868. } else {
  869. node.data[field] = newText;
  870. result.allow = true;
  871. return result;
  872. }
  873. };*/
  874. Tree.prototype.bind = function (eventName, eventFun) {
  875. this.event[eventName] = eventFun;
  876. };
  877. Tree.prototype.resetID = function (items, IDFunc) {
  878. const IDMap = {};
  879. items.forEach(item => {
  880. IDMap[item.ID] = IDFunc();
  881. });
  882. items.forEach(item => {
  883. if (IDMap[item.ID]) {
  884. item.ID = IDMap[item.ID];
  885. }
  886. if (IDMap[item.ParentID]) {
  887. item.ParentID = IDMap[item.ParentID];
  888. }
  889. if (IDMap[item.NextSiblingID]) {
  890. item.NextSiblingID = IDMap[item.NextSiblingID];
  891. }
  892. });
  893. };
  894. /**
  895. * 检查原始树数据,并给出可用于修复数据的 updateDatas。
  896. * 最好在 loadDatas 前调用 newCheck(datas),避免错误的关系影响树的构建。
  897. * 不传 datas 时检查当前树中保存的原始 data;本方法不会修改原数据。
  898. */
  899. Tree.prototype.newCheck = function (datas) {
  900. var that = this;
  901. var idField = this.setting.id;
  902. var pidField = this.setting.pid;
  903. var nidField = this.setting.nid;
  904. var rootId = this.setting.rootId;
  905. var source = Array.isArray(datas) ? datas : Object.keys(this.nodes).map(function (key) {
  906. return that.nodes[key].data;
  907. });
  908. var problems = [];
  909. var updateMap = Object.create(null);
  910. var nodeMap = Object.create(null);
  911. var duplicateMap = Object.create(null);
  912. var duplicates = [];
  913. var stackRisks = [];
  914. var records = [];
  915. var valueKey = function (value) {
  916. return String(value);
  917. };
  918. var sameValue = function (left, right) {
  919. return left == right;
  920. };
  921. var addProblem = function (type, record, field, currentValue, suggestedValue, message) {
  922. problems.push({
  923. type: type,
  924. id: record ? record.id : undefined,
  925. dataIndex: record ? record.index : undefined,
  926. rowNumber: record ? record.index + 1 : undefined,
  927. // 保留对象引用供控制台展开,不能 JSON.stringify:Node 包含 tree 循环引用。
  928. nodeData: record ? record.data : null,
  929. field: field || '',
  930. currentValue: currentValue,
  931. suggestedValue: suggestedValue,
  932. message: message
  933. });
  934. };
  935. var suggestUpdate = function (record, field, value) {
  936. var key = valueKey(record.id);
  937. if (!updateMap[key]) {
  938. updateMap[key] = {};
  939. updateMap[key][idField] = record.id;
  940. }
  941. updateMap[key][field] = value;
  942. };
  943. source.forEach(function (data, index) {
  944. // 兼容 newCheck(rawDatas) 和 newCheck(tree.items) 两种调用方式。
  945. // Tree Node 中包含 node.tree.nodes -> node 的循环关系,只检查其原始 data。
  946. var rawData = data && typeof data.getID === 'function' && data.data ? data.data : data;
  947. var record = {
  948. data: rawData,
  949. id: rawData[idField],
  950. pid: rawData[pidField],
  951. nid: rawData[nidField],
  952. index: index
  953. };
  954. var key = valueKey(record.id);
  955. if (nodeMap[key]) {
  956. var firstRecord = nodeMap[key];
  957. duplicateMap[key] = true;
  958. duplicates.push({
  959. id: record.id,
  960. first: {
  961. dataIndex: firstRecord.index,
  962. rowNumber: firstRecord.index + 1,
  963. data: firstRecord.data
  964. },
  965. duplicate: {
  966. dataIndex: record.index,
  967. rowNumber: record.index + 1,
  968. data: record.data
  969. }
  970. });
  971. addProblem('duplicate-id', record, idField, record.id, undefined,
  972. 'ID ' + record.id + ' 重复:datas[' + firstRecord.index + '](第 ' +
  973. (firstRecord.index + 1) + ' 条)和 datas[' + record.index + '](第 ' +
  974. (record.index + 1) + ' 条)是两个不同节点,请修改其中一个节点的 ID');
  975. return;
  976. }
  977. nodeMap[key] = record;
  978. records.push(record);
  979. });
  980. // 先修正无效父节点,再检查父子关系是否成环。
  981. records.forEach(function (record) {
  982. var parent = nodeMap[valueKey(record.pid)];
  983. record.fixedPid = record.pid;
  984. if (sameValue(record.pid, rootId)) {
  985. return;
  986. }
  987. if (sameValue(record.pid, record.id) || !parent) {
  988. record.fixedPid = rootId;
  989. suggestUpdate(record, pidField, rootId);
  990. addProblem(sameValue(record.pid, record.id) ? 'parent-self' : 'parent-missing',
  991. record, pidField, record.pid, rootId,
  992. sameValue(record.pid, record.id) ? '父节点指向自身,应改为根节点' : '父节点不存在,应改为根节点');
  993. }
  994. });
  995. records.forEach(function (record) {
  996. var current = record;
  997. var path = [];
  998. var pathIndex = Object.create(null);
  999. while (current && !sameValue(current.fixedPid, rootId)) {
  1000. var currentKey = valueKey(current.id);
  1001. if (pathIndex[currentKey] !== undefined) {
  1002. var breaker = path[path.length - 1];
  1003. var cycle = path.slice(pathIndex[currentKey]).map(function (item) {
  1004. return item.id;
  1005. });
  1006. breaker.fixedPid = rootId;
  1007. suggestUpdate(breaker, pidField, rootId);
  1008. addProblem('parent-cycle', breaker, pidField, breaker.pid, rootId,
  1009. '父节点形成环:' + cycle.join(' -> ') + ',建议断开此节点并改为根节点');
  1010. break;
  1011. }
  1012. pathIndex[currentKey] = path.length;
  1013. path.push(current);
  1014. current = nodeMap[valueKey(current.fixedPid)];
  1015. }
  1016. });
  1017. // 按修正后的父节点分组,在每组内恢复为一条完整、无环、无分叉的兄弟链。
  1018. var groups = Object.create(null);
  1019. records.forEach(function (record) {
  1020. var groupKey = valueKey(record.fixedPid);
  1021. if (!groups[groupKey]) {
  1022. groups[groupKey] = [];
  1023. }
  1024. groups[groupKey].push(record);
  1025. });
  1026. Object.keys(groups).forEach(function (groupKey) {
  1027. var siblings = groups[groupKey];
  1028. var siblingMap = Object.create(null);
  1029. var nextMap = Object.create(null);
  1030. var incoming = Object.create(null);
  1031. var visited = Object.create(null);
  1032. var ordered = [];
  1033. var stackRiskLimit = 1000;
  1034. siblings.forEach(function (record) {
  1035. siblingMap[valueKey(record.id)] = record;
  1036. incoming[valueKey(record.id)] = 0;
  1037. });
  1038. siblings.forEach(function (record) {
  1039. var next = sameValue(record.nid, rootId) ? null : nodeMap[valueKey(record.nid)];
  1040. if (next && siblingMap[valueKey(next.id)] && !sameValue(next.id, record.id)) {
  1041. nextMap[valueKey(record.id)] = next;
  1042. incoming[valueKey(next.id)]++;
  1043. } else {
  1044. nextMap[valueKey(record.id)] = null;
  1045. if (!sameValue(record.nid, rootId)) {
  1046. addProblem(next && sameValue(next.id, record.id) ? 'next-self' : 'next-invalid',
  1047. record, nidField, record.nid, undefined,
  1048. next ? 'NextSiblingID 指向不同父节点下的节点或自身' : 'NextSiblingID 指向不存在的节点');
  1049. }
  1050. }
  1051. });
  1052. Object.keys(incoming).forEach(function (key) {
  1053. if (incoming[key] > 1) {
  1054. var target = siblingMap[key];
  1055. addProblem('next-branch', target, nidField, target.id, undefined,
  1056. '有 ' + incoming[key] + ' 个节点同时指向该节点,兄弟链产生分叉');
  1057. }
  1058. });
  1059. var appendChain = function (start) {
  1060. var current = start;
  1061. var chain = [];
  1062. var chainIndex = Object.create(null);
  1063. while (current && !visited[valueKey(current.id)]) {
  1064. chainIndex[valueKey(current.id)] = chain.length;
  1065. chain.push(current);
  1066. visited[valueKey(current.id)] = true;
  1067. ordered.push(current);
  1068. current = nextMap[valueKey(current.id)];
  1069. }
  1070. if (current && chainIndex[valueKey(current.id)] !== undefined) {
  1071. var cycleStart = chainIndex[valueKey(current.id)];
  1072. var cycleRecords = chain.slice(cycleStart);
  1073. var cycleEnd = cycleRecords[cycleRecords.length - 1];
  1074. addProblem('next-cycle', cycleEnd, nidField, cycleEnd.nid, undefined,
  1075. '兄弟节点的 NextSiblingID 形成环:' + cycleRecords.map(function (item) {
  1076. return item.id;
  1077. }).concat([current.id]).join(' -> ') + ',请按 updateDatas 修复');
  1078. }
  1079. if (chain.length > stackRiskLimit) {
  1080. stackRisks.push({
  1081. parentId: start.fixedPid,
  1082. chainLength: chain.length,
  1083. firstNodeId: chain[0].id,
  1084. lastNodeId: chain[chain.length - 1].id,
  1085. message: '同一父节点下连续兄弟链有 ' + chain.length +
  1086. ' 个节点,旧版 moveNode 逐节点递归会导致 Maximum call stack size exceeded;请使用迭代版 moveNode'
  1087. });
  1088. }
  1089. };
  1090. siblings.forEach(function (record) {
  1091. if (incoming[valueKey(record.id)] === 0) {
  1092. appendChain(record);
  1093. }
  1094. });
  1095. // 剩余节点属于环,或处于已合并链的未访问部分;按原数据顺序接到末尾。
  1096. siblings.forEach(function (record) {
  1097. appendChain(record);
  1098. });
  1099. ordered.forEach(function (record, index) {
  1100. var expectedNid = index === ordered.length - 1 ? rootId : ordered[index + 1].id;
  1101. if (!sameValue(record.nid, expectedNid)) {
  1102. suggestUpdate(record, nidField, expectedNid);
  1103. addProblem('next-order', record, nidField, record.nid, expectedNid,
  1104. '兄弟链不连续,按可恢复顺序修改 NextSiblingID');
  1105. }
  1106. });
  1107. });
  1108. var updateDatas = Object.keys(updateMap).map(function (key) {
  1109. return { type: 'update', data: updateMap[key] };
  1110. });
  1111. var result = {
  1112. valid: problems.length === 0,
  1113. canAutoFix: Object.keys(duplicateMap).length === 0,
  1114. problems: problems,
  1115. duplicates: duplicates,
  1116. stackRisks: stackRisks,
  1117. updateDatas: updateDatas
  1118. };
  1119. if (typeof console !== 'undefined') {
  1120. if (result.valid) {
  1121. console.log('树结构检查通过,共 ' + records.length + ' 个节点');
  1122. } else {
  1123. console.group('树结构检查:发现 ' + problems.length + ' 个问题');
  1124. console.table(problems);
  1125. duplicates.forEach(function (item, index) {
  1126. console.group('重复 ID 问题 ' + (index + 1) + ':ID = ' + item.id);
  1127. console.error('以下两个节点的 ID 相同,必须修改其中一个:');
  1128. console.log('节点 A:datas[' + item.first.dataIndex + '],第 ' +
  1129. item.first.rowNumber + ' 条原始数据', item.first.data);
  1130. console.log('节点 B:datas[' + item.duplicate.dataIndex + '],第 ' +
  1131. item.duplicate.rowNumber + ' 条原始数据', item.duplicate.data);
  1132. console.groupEnd();
  1133. });
  1134. console.log('建议修改数据(newCheck 只生成建议,不会自动修改):');
  1135. console.table(updateDatas.map(function (item) { return item.data; }));
  1136. if (!result.canAutoFix) {
  1137. console.warn('存在重复 ID,必须先人工分配新 ID,其他修改建议才可安全应用');
  1138. }
  1139. console.groupEnd();
  1140. }
  1141. if (stackRisks.length) {
  1142. console.group('树排序递归栈风险:发现 ' + stackRisks.length + ' 条过长兄弟链');
  1143. console.table(stackRisks);
  1144. console.warn('这不一定是数据错误;旧版递归 moveNode 会因此堆栈溢出,改为迭代实现即可正常显示');
  1145. console.groupEnd();
  1146. }
  1147. }
  1148. return result;
  1149. };
  1150. //检查树结构数据有没问题
  1151. Tree.prototype.check = function (roots) {
  1152. return isValid(roots);
  1153. function isValid(nodes) {
  1154. for (let node of nodes) {
  1155. if (node.data.ParentID != -1 &&
  1156. (!node.parent || node.parent.data.ID !== node.data.ParentID)) {
  1157. console.log(`${node.serialNo() + 1}:${node.data.name} parent对应错误`);
  1158. return false;
  1159. }
  1160. if (node.data.ParentID == -1 && node.parent) {
  1161. console.log(`${node.serialNo() + 1}:${node.data.name} 不应有parent`);
  1162. return false;
  1163. }
  1164. if (node.data.NextSiblingID != -1 &&
  1165. (!node.nextSibling || node.nextSibling.data.ID !== node.data.NextSiblingID)) {
  1166. console.log(`${node.serialNo() + 1}:${node.data.name} next对应错误`);
  1167. return false;
  1168. }
  1169. if (node.data.NextSiblingID == -1 && node.nextSibling) {
  1170. console.log(`${node.serialNo() + 1}:${node.data.name} 不应有next`);
  1171. return false;
  1172. }
  1173. let sameDepthNodes = node.parent ? node.parent.children : roots,
  1174. nodeIdx = sameDepthNodes.indexOf(node),
  1175. nextIdx = sameDepthNodes.indexOf(node.nextSibling);
  1176. if (nodeIdx != -1 && nextIdx != -1 && nodeIdx > nextIdx) {
  1177. console.log(`${node.serialNo() + 1}:${node.data.name} node索引大于next索引`);
  1178. return false;
  1179. }
  1180. // nextSibling跟parent children的下一节点对应不上
  1181. if (nodeIdx != -1 &&
  1182. (nodeIdx === sameDepthNodes.length - 1 && nextIdx != -1) ||
  1183. (nodeIdx !== sameDepthNodes.length - 1 && nodeIdx + 1 !== nextIdx)) {
  1184. console.log(`${node.serialNo() + 1}:${node.data.name} nextSibling与树显示的下一节点对应不上`);
  1185. return false;
  1186. }
  1187. if (node.children.length) {
  1188. let v = isValid(node.children);
  1189. if (!v) {
  1190. return false;
  1191. }
  1192. }
  1193. }
  1194. return true;
  1195. }
  1196. };
  1197. return new Tree(setting);
  1198. },
  1199. updateType: { update: 'update', new: 'new', delete: 'delete' }
  1200. };