Advertisement
dhniceday

Untitled

Nov 21st, 2022
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 2.26 KB | Software | 0 0
  1. <%*
  2. const IDX = Object.freeze({"depth":0, "text":1, "parent":2, "size":3, "children": 4, "objectId":5});
  3.  
  4. //check if an editor is the active view
  5. const editor = this.app.workspace.activeLeaf?.view?.editor;
  6. if(!editor) return;
  7.  
  8. //initialize the tree with the title of the document as the first element
  9. let tree = [[0,this.app.workspace.activeLeaf?.view?.getDisplayText(),-1,0,[],0]];
  10. const linecount = editor.lineCount();
  11.  
  12. //helper function, use regex to calculate indentation depth, and to get line text
  13. function getLineProps (i) {
  14.   props = editor.getLine(i).match(/^(\t*)-\s+(.*)/);
  15.   return [props[1].length+1, props[2]];
  16. }
  17.  
  18. //a vector that will hold last valid parent for each depth
  19. let parents = [0];
  20.  
  21. //load outline into tree
  22. for(i=0;i<linecount;i++) {
  23.   [depth,text] = getLineProps(i);
  24.   if(depth>parents.length) parents.push(i+1);
  25.   else parents[depth] = i+1;
  26.   tree.push([depth,text,parents[depth-1],1,[]]);
  27.   tree[parents[depth-1]][IDX.children].push(i+1);
  28. }
  29.  
  30. //recursive function to crawl the tree and identify height aka. size of each node
  31. function crawlTree(i) {
  32.   if(i>linecount) return 0;
  33.   size = 0;
  34.   if((i+1<=linecount && tree[i+1][IDX.depth] <= tree[i][IDX.depth])|| i == linecount) { //I am a leaf
  35.     tree[i][IDX.size] = 1;
  36.     return 1;
  37.   }
  38.   tree[i][IDX.children].forEach((node)=>{
  39.     size += crawlTree(node);
  40.   });
  41.   tree[i][IDX.size] = size;
  42.   return size;  
  43. }
  44.  
  45. crawlTree(0);
  46.  
  47. //Build the mindmap in Excalidraw
  48. const width = 300;
  49. const height = 100;
  50. const color = "#FFFFFF"
  51. const ea = ExcalidrawAutomate;
  52. ea.reset();
  53.  
  54. //stores position offset of branch/leaf in height units
  55. offsets = [0];
  56.  
  57. for(i=0;i<=linecount;i++) {
  58.   depth = tree[i][IDX.depth];
  59.   if (depth == 1) ea.style.strokeColor = color;
  60.   tree[i][IDX.objectId] = ea.addText(depth*width,((tree[i][IDX.size]/2)+offsets[depth])*height,tree[i][IDX.text],{box:true});
  61.   //set child offset equal to parent offset
  62.   if((depth+1)>offsets.length) offsets.push(offsets[depth]);
  63.   else offsets[depth+1] = offsets[depth];
  64.   offsets[depth] += tree[i][IDX.size];
  65.   if(tree[i][IDX.parent]!=-1) {
  66.     ea.connectObjects(tree[tree[i][IDX.parent]][IDX.objectId],"right",tree[i][IDX.objectId],"left",{startArrowHead: 'dot'});
  67.   }
  68. }
  69.  
  70. await ea.create({onNewPane: true});
  71. %>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement