helpers.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import { CanvasDirection, NodeData, EdgeData } from "reaflow";
  2. import { parser } from "src/utils/json-editor-parser";
  3. const toString = (value: string | object) => {
  4. const isObject = value instanceof Object;
  5. if (isObject) {
  6. const entries = Object.entries(value);
  7. const stringObj = entries.map((val) => [
  8. JSON.stringify(val[0]).replaceAll('"', ""),
  9. JSON.stringify(val[1]),
  10. ]);
  11. return Object.fromEntries(stringObj);
  12. }
  13. return String(value);
  14. };
  15. export function getEdgeNodes(
  16. graph: string,
  17. isExpanded: boolean = true
  18. ): {
  19. nodes: NodeData[];
  20. edges: EdgeData[];
  21. } {
  22. const elements = parser(JSON.parse(graph));
  23. let nodes: NodeData[] = [],
  24. edges: EdgeData[] = [];
  25. for (let i = 0; i < elements.length; i++) {
  26. const el = elements[i];
  27. if (isNode(el)) {
  28. const text = renderText(el.text);
  29. const lines = text.split("\n");
  30. const lineLengths = lines
  31. .map((line) => line.length)
  32. .sort((a, b) => a - b);
  33. const longestLine = lineLengths.reverse()[0];
  34. const height = lines.length * 17.8 < 30 ? 40 : lines.length * 17.8;
  35. nodes.push({
  36. id: el.id,
  37. text: toString(el.text),
  38. data: {
  39. isParent: el.parent,
  40. },
  41. width: isExpanded ? 35 + longestLine * (el.parent ? 9 : 8) : 180,
  42. height,
  43. });
  44. } else {
  45. edges.push(el);
  46. }
  47. }
  48. return {
  49. nodes,
  50. edges,
  51. };
  52. }
  53. export function getNextLayout(layout: CanvasDirection) {
  54. switch (layout) {
  55. case "RIGHT":
  56. return "DOWN";
  57. case "DOWN":
  58. return "LEFT";
  59. case "LEFT":
  60. return "UP";
  61. default:
  62. return "RIGHT";
  63. }
  64. }
  65. function renderText(value: string | object) {
  66. if (value instanceof Object) {
  67. let temp = "";
  68. const entries = Object.entries(value);
  69. if (Object.keys(value).every((val) => !isNaN(+val))) {
  70. return Object.values(value).join("");
  71. }
  72. entries.forEach((entry) => {
  73. temp += `${entry[0]}: ${String(entry[1])}\n`;
  74. });
  75. return temp;
  76. }
  77. return value;
  78. }
  79. function isNode(element: NodeData | EdgeData) {
  80. if ("text" in element) return true;
  81. return false;
  82. }