-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
53 lines (42 loc) · 1.41 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { Plugin } from 'obsidian';
export default class TreePlugin extends Plugin {
async onload() {
this.registerMarkdownCodeBlockProcessor('tree', this.treeProcessor);
}
private treeProcessor = (source: string, el: HTMLElement) => {
const lines = source.split('\n');
const nodes = lines.map(line => {
const level = (line.match(/=/g) || []).length;
const textPart = line.replace(/=+/g, '');
const leadingWhitespace = (textPart.match(/^[\t ]*/) || [''])[0];
const text = textPart.slice(leadingWhitespace.length);
return {
level,
leadingWhitespace,
text
};
});
const hierarchy: boolean[] = [];
const output = nodes.map((node, index) => {
let isLast = true;
for (let j = index + 1; j < nodes.length; j++) {
if (nodes[j].level < node.level) break;
if (nodes[j].level === node.level) {
isLast = false;
break;
}
}
hierarchy[node.level] = isLast;
hierarchy.length = node.level + 1;
let prefix = '';
for (let lvl = 1; lvl < node.level; lvl++) {
prefix += hierarchy[lvl] ? ' ' : '│ ';
}
if (node.level > 0) {
prefix += isLast ? '└── ' : '├── ';
}
return `${node.leadingWhitespace}${prefix}${node.text}`;
}).join('\n');
el.innerHTML = `<pre><code>${output}</code></pre>`;
};
}