obsidian-reference-architecture
Implement Obsidian reference architecture with best-practice project layout. Use when designing new plugins, reviewing project structure, or establishing architecture standards for Obsidian development. Trigger with phrases like "obsidian architecture", "obsidian project structure", "obsidian best practices", "organize obsidian plugin".
What this skill does
# Obsidian Reference Architecture
## Overview
Architecture patterns for complex Obsidian plugins: modular project structure with separate files for views, commands, settings, and services; state management; a service layer for vault operations; command registry; view manager; and CSS scoping.
## Prerequisites
- TypeScript and Obsidian API familiarity
- Working build pipeline (esbuild recommended)
- Plugin scaffolding complete (`manifest.json`, `package.json`, `tsconfig.json`)
## Instructions
### Step 1: Project Structure
```
my-plugin/
├── src/
│ ├── main.ts # Plugin entry — thin orchestrator
│ ├── types.ts # Shared interfaces and type definitions
│ ├── constants.ts # Plugin-wide constants
│ ├── commands/
│ │ ├── index.ts # Command registry
│ │ ├── insert-template.ts
│ │ └── toggle-sidebar.ts
│ ├── views/
│ │ ├── index.ts # View registry
│ │ ├── sidebar-view.ts
│ │ └── modal-view.ts
│ ├── settings/
│ │ ├── settings.ts # Settings interface and defaults
│ │ └── settings-tab.ts # Settings UI tab
│ └── services/
│ ├── vault-service.ts # File read/write/search operations
│ ├── metadata-service.ts # Frontmatter and cache operations
│ └── sync-service.ts # External sync or background tasks
├── styles.css
├── manifest.json
├── versions.json
├── package.json
├── tsconfig.json
└── esbuild.config.mjs
```
### Step 2: Thin Main Entry Point
```typescript
// src/main.ts — orchestrates, does not implement
import { Plugin } from 'obsidian';
import { MyPluginSettings, DEFAULT_SETTINGS } from './settings/settings';
import { MySettingTab } from './settings/settings-tab';
import { registerCommands } from './commands';
import { registerViews } from './views';
import { VaultService } from './services/vault-service';
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
vaultService: VaultService;
async onload() {
await this.loadSettings();
this.vaultService = new VaultService(this.app);
registerCommands(this);
registerViews(this);
this.addSettingTab(new MySettingTab(this.app, this));
}
onunload() {
// Services clean up their own resources
this.vaultService.destroy();
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
```
### Step 3: Command Registry Pattern
```typescript
// src/commands/index.ts
import type MyPlugin from '../main';
import { insertTemplate } from './insert-template';
import { toggleSidebar } from './toggle-sidebar';
export function registerCommands(plugin: MyPlugin) {
plugin.addCommand({
id: 'insert-template',
name: 'Insert Template',
editorCallback: (editor, view) => insertTemplate(plugin, editor, view),
});
plugin.addCommand({
id: 'toggle-sidebar',
name: 'Toggle Sidebar',
callback: () => toggleSidebar(plugin),
});
}
```
```typescript
// src/commands/insert-template.ts
import { Editor, MarkdownView } from 'obsidian';
import type MyPlugin from '../main';
export function insertTemplate(plugin: MyPlugin, editor: Editor, view: MarkdownView) {
const template = plugin.settings.defaultTemplate;
editor.replaceSelection(template);
}
```
### Step 4: View Manager
```typescript
// src/views/index.ts
import type MyPlugin from '../main';
import { SidebarView, VIEW_TYPE_SIDEBAR } from './sidebar-view';
export function registerViews(plugin: MyPlugin) {
plugin.registerView(VIEW_TYPE_SIDEBAR, (leaf) => new SidebarView(leaf, plugin));
// Add ribbon icon to activate view
plugin.addRibbonIcon('layout-sidebar-right', 'Open Sidebar', () => {
activateView(plugin);
});
}
async function activateView(plugin: MyPlugin) {
const { workspace } = plugin.app;
let leaf = workspace.getLeavesOfType(VIEW_TYPE_SIDEBAR)[0];
if (!leaf) {
const rightLeaf = workspace.getRightLeaf(false);
if (rightLeaf) {
await rightLeaf.setViewState({ type: VIEW_TYPE_SIDEBAR, active: true });
leaf = rightLeaf;
}
}
if (leaf) {
workspace.revealLeaf(leaf);
}
}
```
```typescript
// src/views/sidebar-view.ts
import { ItemView, WorkspaceLeaf } from 'obsidian';
import type MyPlugin from '../main';
export const VIEW_TYPE_SIDEBAR = 'my-plugin-sidebar';
export class SidebarView extends ItemView {
plugin: MyPlugin;
constructor(leaf: WorkspaceLeaf, plugin: MyPlugin) {
super(leaf);
this.plugin = plugin;
}
getViewType(): string {
return VIEW_TYPE_SIDEBAR;
}
getDisplayText(): string {
return 'My Plugin';
}
getIcon(): string {
return 'layout-sidebar-right';
}
async onOpen() {
const container = this.containerEl.children[1];
container.empty();
container.addClass('my-plugin-sidebar');
container.createEl('h3', { text: 'My Plugin' });
const list = container.createEl('ul');
// Populate from service layer
const files = await this.plugin.vaultService.getRecentFiles(10);
for (const file of files) {
list.createEl('li', { text: file.basename });
}
}
async onClose() {
// Clean up DOM references
this.containerEl.empty();
}
}
```
### Step 5: Service Layer for Vault Operations
```typescript
// src/services/vault-service.ts
import { App, TFile, TFolder, CachedMetadata } from 'obsidian';
export class VaultService {
constructor(private app: App) {}
// File operations
async readFile(path: string): Promise<string> {
const file = this.app.vault.getAbstractFileByPath(path);
if (!(file instanceof TFile)) throw new Error(`Not a file: ${path}`);
return this.app.vault.read(file);
}
async writeFile(path: string, content: string): Promise<void> {
const file = this.app.vault.getAbstractFileByPath(path);
if (file instanceof TFile) {
await this.app.vault.modify(file, content);
} else {
await this.app.vault.create(path, content);
}
}
// Search operations
getFilesInFolder(folderPath: string): TFile[] {
const folder = this.app.vault.getAbstractFileByPath(folderPath);
if (!(folder instanceof TFolder)) return [];
return folder.children.filter((f): f is TFile => f instanceof TFile);
}
getRecentFiles(limit: number): TFile[] {
return this.app.vault.getMarkdownFiles()
.sort((a, b) => b.stat.mtime - a.stat.mtime)
.slice(0, limit);
}
// Metadata operations
getMetadata(file: TFile): CachedMetadata | null {
return this.app.metadataCache.getFileCache(file);
}
getFrontmatter(file: TFile): Record<string, unknown> | undefined {
return this.getMetadata(file)?.frontmatter;
}
// Cleanup
destroy() {
// Release any held references
}
}
```
### Step 6: Settings Architecture
```typescript
// src/settings/settings.ts
export interface MyPluginSettings {
version: number;
defaultTemplate: string;
showStatusBar: boolean;
syncInterval: number;
}
export const DEFAULT_SETTINGS: MyPluginSettings = {
version: 1,
defaultTemplate: '## New Section\n\n',
showStatusBar: true,
syncInterval: 300,
};
```
```typescript
// src/settings/settings-tab.ts
import { App, PluginSettingTab, Setting } from 'obsidian';
import type MyPlugin from '../main';
export class MySettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName('Default template')
.setDesc('Content inserted by the Insert Template command')
.addTextArea(text => text
.setValue(this.plugin.settings.defaultTemplate)
.onChange(async (value) => {
this.plugin.settings.defaultTemplate = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Show status bar')
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.