generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
71 lines (58 loc) · 2.16 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { Plugin, TFile } from 'obsidian';
import { Root, createRoot } from 'react-dom/client';
import React from 'react';
import {MapViewContainer} from './MapViewContainer';
interface WardleyMapsPluginSettings {
mySetting: string;
}
const DEFAULT_SETTINGS: WardleyMapsPluginSettings = {
mySetting: 'default'
}
export default class WardleyMapsPlugin extends Plugin {
settings: WardleyMapsPluginSettings;
async onload() {
await this.loadSettings();
this.registerMarkdownCodeBlockProcessor('wardleymap', async (source, el, ctx) => {
el.appendChild(document.createTextNode(source));
let root: Root;
if (el instanceof Element) {
const reactComponent = React.createElement(MapViewContainer, {
markdownText: source,
mutateMapText: async (newText: string) => {
// Get the active file from the context
const activeFile = ctx.sourcePath ? this.app.vault.getAbstractFileByPath(ctx.sourcePath) : null;
// Proceed if activeFile is found and is a TFile
if (activeFile instanceof TFile) {
// Read the current content of the file
const fileContent = await this.app.vault.read(activeFile);
// Split file content by lines for easier manipulation
const lines = fileContent.trim().split('\n');
// Replace the lines for the `wardleymap` block
// Locate the block by line numbers provided in ctx
const startLine = ctx.getSectionInfo(el)?.lineStart ?? 0;
const endLine = ctx.getSectionInfo(el)?.lineEnd ?? 0;
// Update the block content in-place
lines.splice(startLine + 1, endLine - startLine - 1, newText.trim());
// Join lines back and save the file
const updatedContent = lines.join('\n');
await this.app.vault.modify(activeFile, updatedContent);
} else {
console.error('Unable to locate the active file or file is not a TFile');
}
}
});
el.classList.add('wardley-map-root');
root = createRoot(el);
root.render(reactComponent);
}
});
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}