Skip to content

Commit

Permalink
Edit view-manager.ts: add insertion functions
Browse files Browse the repository at this point in the history
  • Loading branch information
HyeonseoNam committed Mar 16, 2023
1 parent 4093284 commit 6d2aeb7
Showing 1 changed file with 45 additions and 7 deletions.
52 changes: 45 additions & 7 deletions src/view-manager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { App, MarkdownView } from "obsidian";
import { App, MarkdownView, Notice, Editor} from "obsidian";

export class ViewManager {
app: App;
Expand All @@ -7,25 +7,26 @@ export class ViewManager {
this.app = app;
}

getSelection(): string | null {
async getSelection(editor?: Editor): Promise<string | null> {
if (editor) {
return editor.getSelection();
}
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
const editor = activeView.editor;
const selectedText = editor.getSelection();
return selectedText;
return activeView.editor.getSelection();
}
return null;
}

getTitle(): string | null {
async getTitle(): Promise<string | null> {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
return activeView.file.basename;
}
return null;
}

getFrontMatter(): Record<string, unknown> | null {
async getFrontMatter(): Promise<Record<string, unknown> | null> {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
const file = activeView.file;
Expand All @@ -35,5 +36,42 @@ export class ViewManager {
return null;
}

async insertAtFrontMatter(key: string, value: string, overwrite = false): Promise<void> {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);

if (activeView) {
const file = activeView.file;
await this.app.fileManager.processFrontMatter(file, (frontmatter) => {
frontmatter = frontmatter || {};

if (frontmatter[key] && !overwrite) {
// add value as list element if exist
if (Array.isArray(frontmatter[key])) {
frontmatter[key].push(value);
} else {
frontmatter[key] = [frontmatter[key], value];
}
} else {
// overwrite
frontmatter[key] = value;
}
});
}
}

async insertAtCursor(value: string, overwrite = false): Promise<void> {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);

if (activeView) {
const editor = activeView.editor;
const selection = editor.getSelection();
if (selection && !overwrite) {
// replace selection
editor.setSelection(editor.getCursor('to'));
}
// overwrite
editor.replaceSelection(value);
}
}

}

0 comments on commit 6d2aeb7

Please sign in to comment.