util.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { filter, isArray, isString } from '@antv/util';
  2. /** export 一些字段常量 */
  3. /** 在同层级,同一父节点下的节点索引顺序 */
  4. export var NODE_INDEX_FIELD = 'nodeIndex';
  5. /** child 节点数量 */
  6. export var CHILD_NODE_COUNT = 'childNodeCount';
  7. /** 节点的祖先节点 */
  8. export var NODE_ANCESTORS_FIELD = 'nodeAncestor';
  9. var INVALID_FIELD_ERR_MSG = 'Invalid field: it must be a string!';
  10. export function getField(options, defaultField) {
  11. var field = options.field, fields = options.fields;
  12. if (isString(field)) {
  13. return field;
  14. }
  15. if (isArray(field)) {
  16. console.warn(INVALID_FIELD_ERR_MSG);
  17. return field[0];
  18. }
  19. console.warn("".concat(INVALID_FIELD_ERR_MSG, " will try to get fields instead."));
  20. if (isString(fields)) {
  21. return fields;
  22. }
  23. if (isArray(fields) && fields.length) {
  24. return fields[0];
  25. }
  26. if (defaultField) {
  27. return defaultField;
  28. }
  29. throw new TypeError(INVALID_FIELD_ERR_MSG);
  30. }
  31. export function getAllNodes(root) {
  32. var nodes = [];
  33. if (root && root.each) {
  34. var parent_1;
  35. var index_1;
  36. // d3-hierarchy: Invokes the specified function for node and each descendant in **breadth-first order**
  37. root.each(function (node) {
  38. var _a, _b;
  39. if (node.parent !== parent_1) {
  40. parent_1 = node.parent;
  41. index_1 = 0;
  42. }
  43. else {
  44. index_1 += 1;
  45. }
  46. var ancestors = filter((((_a = node.ancestors) === null || _a === void 0 ? void 0 : _a.call(node)) || []).map(function (d) { return nodes.find(function (n) { return n.name === d.name; }) || d; }), function (_a) {
  47. var depth = _a.depth;
  48. return depth > 0 && depth < node.depth;
  49. });
  50. node[NODE_ANCESTORS_FIELD] = ancestors;
  51. node[CHILD_NODE_COUNT] = ((_b = node.children) === null || _b === void 0 ? void 0 : _b.length) || 0;
  52. node[NODE_INDEX_FIELD] = index_1;
  53. nodes.push(node);
  54. });
  55. }
  56. else if (root && root.eachNode) {
  57. // @antv/hierarchy
  58. root.eachNode(function (node) {
  59. nodes.push(node);
  60. });
  61. }
  62. return nodes;
  63. }
  64. //# sourceMappingURL=util.js.map