|
| 1 | +const obsidian = require('obsidian'); |
| 2 | + |
| 3 | +class TitleAppenderPlugin extends obsidian.Plugin { |
| 4 | + async onload() { |
| 5 | + console.log('Loading TitleAppender plugin'); |
| 6 | + |
| 7 | + // Create stylesheet element only once during initialization |
| 8 | + try { |
| 9 | + this.styleEl = document.head.createEl('style'); |
| 10 | + this.styleEl.id = 'title-appender-styles'; |
| 11 | + } catch (error) { |
| 12 | + console.error('Error creating style element:', error); |
| 13 | + return; |
| 14 | + } |
| 15 | + |
| 16 | + // Wait for layout to be ready |
| 17 | + this.app.workspace.onLayoutReady(() => { |
| 18 | + this.registerEvents(); |
| 19 | + this.updateAllTitles(); |
| 20 | + }); |
| 21 | + } |
| 22 | + |
| 23 | + registerEvents() { |
| 24 | + // Update styles when files change |
| 25 | + this.registerEvent( |
| 26 | + this.app.metadataCache.on('changed', () => { |
| 27 | + this.updateAllTitles(); |
| 28 | + }) |
| 29 | + ); |
| 30 | + |
| 31 | + // Update on file explorer changes |
| 32 | + this.registerEvent( |
| 33 | + this.app.workspace.on('file-menu', () => { |
| 34 | + this.updateAllTitles(); |
| 35 | + }) |
| 36 | + ); |
| 37 | + |
| 38 | + // Update when layout changes |
| 39 | + this.registerEvent( |
| 40 | + this.app.workspace.on('layout-change', () => { |
| 41 | + this.updateAllTitles(); |
| 42 | + }) |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + updateAllTitles() { |
| 47 | + try { |
| 48 | + // Get all markdown files |
| 49 | + const files = this.app.vault.getMarkdownFiles(); |
| 50 | + let cssRules = []; |
| 51 | + |
| 52 | + // Create CSS rules for each file with a frontmatter title |
| 53 | + files.forEach(file => { |
| 54 | + try { |
| 55 | + const metadata = this.app.metadataCache.getFileCache(file); |
| 56 | + const title = metadata?.frontmatter?.title; |
| 57 | + |
| 58 | + if (title) { |
| 59 | + const escapedPath = CSS.escape(file.path); |
| 60 | + const escapedTitle = title.replace(/"/g, '\\"'); |
| 61 | + |
| 62 | + cssRules.push(` |
| 63 | + .nav-file-title[data-path="${escapedPath}"] .nav-file-title-content::after { |
| 64 | + content: " (${escapedTitle})"; |
| 65 | + color: var(--color-orange); |
| 66 | + font-size: 0.85em; |
| 67 | + opacity: 0.8; |
| 68 | + } |
| 69 | + `); |
| 70 | + } |
| 71 | + } catch (e) { |
| 72 | + console.error('Error processing file:', file?.path, e); |
| 73 | + } |
| 74 | + }); |
| 75 | + |
| 76 | + // Update stylesheet content |
| 77 | + if (this.styleEl) { |
| 78 | + this.styleEl.textContent = cssRules.join("\n"); |
| 79 | + } |
| 80 | + } catch (error) { |
| 81 | + console.error('Error updating titles:', error); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + onunload() { |
| 86 | + console.log('Unloading TitleAppender plugin'); |
| 87 | + if (this.styleEl) { |
| 88 | + this.styleEl.remove(); |
| 89 | + } |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +module.exports = TitleAppenderPlugin; |
0 commit comments