From 49bef1ce3775ac38cd6bb4597746c1bc55e64d85 Mon Sep 17 00:00:00 2001 From: Dian Date: Fri, 31 Jan 2025 21:37:06 +0800 Subject: [PATCH] make ribbon create a right sidebar view --- CustomView.ts | 30 ++++++++++++++++++++++++++++++ main.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 CustomView.ts diff --git a/CustomView.ts b/CustomView.ts new file mode 100644 index 0000000..97bf201 --- /dev/null +++ b/CustomView.ts @@ -0,0 +1,30 @@ +import { ItemView, WorkspaceLeaf } from "obsidian"; +// Each view is uniquely identified by a text string +// and several operations require that you specify the view you'd like to use. +// Extracting it to a constant, VIEW_TYPE_EXAMPLE, is a good idea—as you will see later in this guide. + +export const VIEW_TYPE_EXAMPLE = "example-view"; + +export class ExampleView extends ItemView { + constructor(leaf: WorkspaceLeaf) { + super(leaf); + } + + getViewType() { + return VIEW_TYPE_EXAMPLE; + } + + getDisplayText() { + return "Example view"; + } + + async onOpen() { + const container = this.containerEl.children[1]; + container.empty(); + container.createEl("h4", { text: "Example view" }); + } + + async onClose() { + // Nothing to clean up. + } +} diff --git a/main.ts b/main.ts index 79138fe..c15bef9 100644 --- a/main.ts +++ b/main.ts @@ -1,3 +1,4 @@ +import { ExampleView, VIEW_TYPE_EXAMPLE } from "CustomView"; import { addIcon, App, @@ -8,9 +9,13 @@ import { Plugin, PluginSettingTab, Setting, + WorkspaceLeaf, } from "obsidian"; // Remember to rename these classes and interfaces! +// +// Custom views need to be registered when the plugin is enabled, +// and cleaned up when the plugin is disabled: interface MyPluginSettings { mySetting: string; @@ -25,6 +30,25 @@ const DEFAULT_SETTINGS: MyPluginSettings = { export default class NemesisPlugin extends Plugin { settings: MyPluginSettings; + async activateView() { + const { workspace } = this.app; + let leaf: WorkspaceLeaf | null = null; + const leaves = workspace.getLeavesOfType(VIEW_TYPE_EXAMPLE); + if (leaves.length > 0) { + // A leaf with our view already exists, use that + leaf = leaves[0]; + } else { + // Create a new leaf in the right sidebar + leaf = workspace.getRightLeaf(false); + if (leaf) { + await leaf.setViewState({ + type: VIEW_TYPE_EXAMPLE, + active: true, + }); + } + } + } + async onload() { await this.loadSettings(); @@ -42,10 +66,13 @@ export default class NemesisPlugin extends Plugin { // Called when the user clicks the icon. new Notice("This is a notice!"); console.log("click"); + this.activateView(); // console.log(`My openai key: ${this.settings.openAiKey}`); } ); // todo create and open new view to display the open ai nemesis result + // it currently does not pop open the view + this.registerView(VIEW_TYPE_EXAMPLE, (leaf) => new ExampleView(leaf)); // use this class to perform additional things with the ribbon // ribbonIconEl.addClass("my-plugin-ribbon-class");