|
| 1 | +import Yace from "https://unpkg.com/yace?module"; |
| 2 | +let text = ` |
| 3 | +Root |
| 4 | +
|
| 5 | + - branch 1 |
| 6 | + +branch 1.1 |
| 7 | +
|
| 8 | + - branch 2 |
| 9 | + branch 2.1 |
| 10 | + * branch 2.2 |
| 11 | + branch 2.2.1 |
| 12 | +
|
| 13 | + -Branch 3 |
| 14 | + - alo |
| 15 | + - ola |
| 16 | + - ollala |
| 17 | +
|
| 18 | + -Branch 4 |
| 19 | + - Branch 4.1 |
| 20 | + - Branch 4.1.1 |
| 21 | + - Branch 4.2 |
| 22 | + - Branch 4.3`; |
| 23 | + |
| 24 | +const Parser = mindtree.Parsers.TextParser; |
| 25 | +const viewer = new mindtree.Viewer("#drawing", {}); |
| 26 | +const layout = mindtree.MindmapLayouts.Standard; |
| 27 | + |
| 28 | +function highlighter(value) { |
| 29 | + return hljs.highlight("markdown", value).value; |
| 30 | +} |
| 31 | + |
| 32 | +const editor = new Yace("#editor", { |
| 33 | + value: text, |
| 34 | + lineNumbers: true, |
| 35 | + highlighter: highlighter, |
| 36 | + plugins: [tabPlugin], |
| 37 | +}); |
| 38 | + |
| 39 | +function updateMindmap(text) { |
| 40 | + var data = Parser.parse(text); |
| 41 | + var mindMap = new mindtree.MindMap(data.root, layout, {}); |
| 42 | + mindMap.build(); |
| 43 | + viewer.render(mindMap); |
| 44 | +} |
| 45 | + |
| 46 | +updateMindmap(text); |
| 47 | +editor.update({ value: text }); |
| 48 | +editor.textarea.focus(); |
| 49 | + |
| 50 | +editor.onUpdate(function (code) { |
| 51 | + updateMindmap(code); |
| 52 | +}); |
| 53 | + |
| 54 | +function tabPlugin(textareaProps, event) { |
| 55 | + const { value, selectionStart, selectionEnd } = textareaProps; |
| 56 | + const tabCharacter = " "; |
| 57 | + |
| 58 | + if (event.type !== "keydown") { |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + // tab |
| 63 | + if (event.keyCode == 9) { |
| 64 | + event.preventDefault(); |
| 65 | + if (selectionStart === selectionEnd) { |
| 66 | + const updatedSelection = selectionStart + tabCharacter.length; |
| 67 | + const newValue = |
| 68 | + value.substring(0, selectionStart) + |
| 69 | + tabCharacter + |
| 70 | + value.substring(selectionEnd); |
| 71 | + |
| 72 | + return { |
| 73 | + value: newValue, |
| 74 | + selectionStart: updatedSelection, |
| 75 | + selectionEnd: updatedSelection, |
| 76 | + }; |
| 77 | + } |
| 78 | + |
| 79 | + const linesBeforeCaret = value.substring(0, selectionStart).split("\n"); |
| 80 | + const startLine = linesBeforeCaret.length - 1; |
| 81 | + const endLine = value.substring(0, selectionEnd).split("\n").length - 1; |
| 82 | + |
| 83 | + return { |
| 84 | + value: value |
| 85 | + .split("\n") |
| 86 | + .map((line, i) => { |
| 87 | + if (i >= startLine && i <= endLine) { |
| 88 | + return tabCharacter + line; |
| 89 | + } |
| 90 | + |
| 91 | + return line; |
| 92 | + }) |
| 93 | + .join("\n"), |
| 94 | + selectionStart: selectionStart + tabCharacter.length, |
| 95 | + selectionEnd: |
| 96 | + selectionEnd + tabCharacter.length * (endLine - startLine + 1), |
| 97 | + }; |
| 98 | + } |
| 99 | +} |
0 commit comments