|
| 1 | +import QtQml 2.0 |
| 2 | +import QOwnNotesTypes 1.0 |
| 3 | + |
| 4 | +Script { |
| 5 | + /** |
| 6 | + * Sarà eseguito quando il motore di scripting parte |
| 7 | + */ |
| 8 | + function init() { |
| 9 | + script.registerCustomAction("ascii-tree-factory", "Generate ASCII tree from path"); |
| 10 | + } |
| 11 | + |
| 12 | + function customActionInvoked(identifier) { |
| 13 | + switch (identifier) { |
| 14 | + case "ascii-tree-factory": { |
| 15 | + var selection = script.noteTextEditSelectedText(); |
| 16 | + // break selection strings at line ends |
| 17 | + var lines = selection.split("\n"); |
| 18 | + // initialize tree object |
| 19 | + var tree = {}; |
| 20 | + //for each line in selection |
| 21 | + lines.forEach(function(line){ |
| 22 | + // break line at slashes |
| 23 | + var path = line.split("/"); |
| 24 | + var current = tree; |
| 25 | + // for each segment |
| 26 | + path.forEach(function(subpath){ |
| 27 | + // if the key doesn't have descendants, attach an empty object. |
| 28 | + if (!current[subpath]){ |
| 29 | + current[subpath] = {}; |
| 30 | + } |
| 31 | + // else move to the next level |
| 32 | + current = current[subpath]; |
| 33 | + }); |
| 34 | + }); |
| 35 | + // uncomment for troubleshooting |
| 36 | + // script.log(JSON.stringify(tree)); |
| 37 | + |
| 38 | + // Start rendering the codeblock with the "graphical" tree |
| 39 | + var codeBlockTree = `\`\`\`\n`; |
| 40 | + // init an array to keep track if each level is the last one at that depth |
| 41 | + var lastLevel = []; |
| 42 | + // recursive function to print the tree |
| 43 | + function printTree(tree, level){ |
| 44 | + lastLevel.push(false); |
| 45 | + let keys = Object.keys(tree); |
| 46 | + for (var k=0; k < keys.length; k++){ |
| 47 | + if (k == keys.length - 1){ |
| 48 | + lastLevel[level]=true; |
| 49 | + } |
| 50 | + // preparing the string that will be printed before the current key |
| 51 | + let previousLevelsRendering = ""; |
| 52 | + for (var l=0; l<level; l++){ |
| 53 | + // for each previous level print a "│ " if it's not the last key at that level |
| 54 | + previousLevelsRendering += lastLevel[l] ? " " : "│ "; |
| 55 | + } |
| 56 | + // put together the string to be printed accounting for first level and last key at that level |
| 57 | + codeBlockTree += `${(level==0) ? keys[k] : previousLevelsRendering +(lastLevel[level]?"└─" :"├─" )+keys[k]}\n`; |
| 58 | + printTree(tree[keys[k]], level + 1); |
| 59 | + } |
| 60 | + } |
| 61 | + // calling the recursive function |
| 62 | + printTree(tree, 0); |
| 63 | + // closing the codeblock |
| 64 | + codeBlockTree += `\`\`\``; |
| 65 | + script.noteTextEditWrite(codeBlockTree); |
| 66 | + break; |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments