### Notebook Navigator API - Core Methods Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference Provides essential methods to get the API version and check storage readiness. ```APIDOC ## Core API Methods ### Description Core methods to interact with the Notebook Navigator API, including retrieving the API version and checking storage status. ### Method `getVersion()` ### Description Gets the current version of the Notebook Navigator API. ### Returns - `string`: The API version string. --- ### Method `isStorageReady()` ### Description Checks if the internal storage is ready for metadata operations. ### Returns - `boolean`: `true` if storage is ready, `false` otherwise. ``` -------------------------------- ### Using Notebook Navigator API without Type Definitions (JavaScript/TypeScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference This example demonstrates how to use the Notebook Navigator API in JavaScript or TypeScript without explicitly importing type definitions. While it lacks compile-time type checking, the API remains functional. The code shows how to check for storage readiness and perform metadata operations. ```javascript // Works fine without types in JavaScript/TypeScript const nn = app.plugins.plugins['notebook-navigator']?.api; if (nn) { // Wait for storage if needed, then proceed if (!nn.isStorageReady()) { await new Promise(resolve => nn.once('storage-ready', resolve)); } // Storage is ready, safe to use metadata APIs await nn.metadata.setFolderMeta(folder, { color: '#FF5733' }); } ``` -------------------------------- ### Manage External Icons - ExternalIconProviderController (TypeScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fservice-architecture The ExternalIconProviderController manages the lifecycle of external icon packs, including installation, updates, and removal. It downloads assets, stores them, and syncs provider enablement with settings. ```typescript initialize(): Promise dispose(): void installProvider(id: ExternalIconProviderId, options?: InstallOptions): Promise removeProvider(id: ExternalIconProviderId, options?: RemoveOptions): Promise syncWithSettings(): Promise isProviderInstalled(id: ExternalIconProviderId): boolean isProviderDownloading(id: ExternalIconProviderId): boolean getProviderVersion(id: ExternalIconProviderId): string | null ``` -------------------------------- ### Complete Darcula Theme Example for Notebook Navigator (CSS) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Ftheming-guide This CSS code defines a complete theme for the Notebook Navigator application, inspired by the JetBrains Darcula color palette. It customizes various UI elements including pane overlays, navigation items (folders, tags), dividers, and list panes by setting specific CSS variables. No external dependencies are required, as it's a self-contained CSS style block. ```css /* ======================================== NOTEBOOK NAVIGATOR DARCULA THEME ======================================== */ body { /* ======================================== PANE OVERLAY STACKS ======================================== */ --nn-theme-pane-overlay-opacity: 85; /* Opacity for pane overlay stacks */ --nn-theme-pane-overlay-filter: blur(3px) saturate(160%); /* Backdrop filter for pane overlay stacks */ /* ======================================== NAVIGATION PANE (Folders & Tags) ======================================== */ /* Pane background */ --nn-theme-nav-bg: #3c3f41; /* Dark gray sidebar - navigation pane background */ --nn-theme-nav-separator-color: #6e6e6e; /* Muted gray - separator lines */ --nn-theme-nav-separator-background: var(--nn-theme-nav-separator-color); /* Solid separator fill */ --nn-theme-nav-separator-height: 1px; /* Keep separators at 1px */ --nn-theme-nav-separator-opacity: 0.35; /* Slightly stronger separator */ /* Folder & tag items */ --nn-theme-navitem-chevron-color: #6e6e6e; /* Muted gray - expand/collapse arrows */ --nn-theme-navitem-icon-color: #afb1b3; /* Light gray - folder/tag icons */ --nn-theme-navitem-name-color: #a9b7c6; /* Soft blue-gray - folder/tag names */ --nn-theme-navitem-file-name-color: #a9b7c6; /* Soft blue-gray - note shortcuts and recent files */ --nn-theme-navitem-count-color: #7f8b91; /* Muted gray - file count text */ --nn-theme-navitem-count-bg: transparent; /* No background for count badges */ --nn-theme-navitem-count-border-radius: 3px; /* Subtle rounded count badges */ --nn-theme-navitem-border-radius: 3px; /* Subtle rounded corners */ --nn-theme-navitem-hover-bg: #4b5059; /* Slightly lighter gray - hover background */ --nn-theme-navitem-selected-bg: #4a78c8; /* Muted blue - selected item background */ --nn-theme-navitem-selected-chevron-color: #c5c5c5; /* Light gray - selected item arrows */ --nn-theme-navitem-selected-icon-color: #e6e6e6; /* Near white - selected item icons */ --nn-theme-navitem-selected-name-color: #ffffff; /* White - selected item text */ --nn-theme-navitem-selected-count-color: #e6e6e6; /* Light gray - selected item count text */ --nn-theme-navitem-selected-count-bg: rgba(0, 0, 0, 0.2); /* Subtle dark overlay - selected count bg */ --nn-theme-navitem-selected-inactive-bg: #464c55; /* Dark gray - inactive selected background */ --nn-theme-navitem-selected-inactive-name-color: #cfd3da; /* Muted cool gray - inactive selected text */ --nn-theme-navitem-selected-inactive-chevron-color: #9da2ab; /* Dimmed arrow when pane is inactive */ --nn-theme-navitem-selected-inactive-icon-color: #b9bec6; /* Dimmed icon when pane is inactive */ --nn-theme-navitem-selected-inactive-count-color: #b9bec6; /* Dimmed count text when pane is inactive */ --nn-theme-navitem-selected-inactive-count-bg: rgba(0, 0, 0, 0.25); /* Slightly darker count bg when inactive */ /* Tag highlights and drop targets */ --nn-theme-tag-positive-bg: rgba(106, 135, 89, 0.2); /* Green tint - positive tag highlights */ --nn-theme-tag-negative-bg: rgba(219, 80, 80, 0.2); /* Red tint - negative tag highlights */ /* Pinned shortcuts */ --nn-theme-pinned-shortcut-shadow-color: rgba(0, 0, 0, 0.2); /* Shadow gradient below pinned shortcuts */ /* Text styling */ --nn-theme-navitem-name-font-weight: 400; /* Regular weight for normal items */ --nn-theme-navitem-file-name-font-weight: 400; /* Regular weight for file names */ --nn-theme-navitem-custom-color-name-font-weight: 500; /* Medium for custom colored items */ --nn-theme-navitem-custom-color-file-name-font-weight: 500; /* Medium for custom colored file names */ --nn-theme-navitem-folder-note-name-font-weight: 500; /* Medium for folder notes */ --nn-theme-navitem-folder-note-name-decoration: none; /* No decoration for cleaner look */ --nn-theme-navitem-count-font-weight: 400; /* Regular for count badges */ /* ======================================== PANE DIVIDER ======================================== */ --nn-theme-divider-border-color: #323232; /* Dark gray - vertical divider between panes */ --nn-theme-divider-resize-handle-hover-bg: #4a78c8; /* Blue accent - resize handle on hover */ /* ======================================== LIST PANE (Files) ======================================== */ /* Pane background */ --nn-theme-list-bg: #2b2b2b; /* Dark editor background - file list background */ --nn-theme-list-header-icon-color: #7f8b91; /* Muted gray - desktop breadcrumb icon */ --nn-theme-list-header-breadcrumb-color: #7f8b91; /* Muted gray - desktop breadcrumb text */ --nn-theme-list-header-breadcrumb-font-weight: 600; /* Bold weight - desktop breadcrumb */ } ``` -------------------------------- ### Navigate to a Specific Tag with Navigation API Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference This example shows how to use the `navigateToTag` method from the Navigation API to select a specific tag in the navigation pane. It includes a check to ensure the tag storage is ready and handles both plain tag names and prefixed tag names (e.g., 'work' or '#work'). The method supports hierarchical tags and preserves navigation focus. ```typescript // Wait for storage if needed, then navigate if (!nn.isStorageReady()) { await new Promise(resolve => nn.once('storage-ready', resolve)); } await nn.navigation.navigateToTag('#work'); ``` -------------------------------- ### IContentProvider Interface Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fservice-architecture Defines the interface for content providers, managing content generation and processing based on settings. It includes methods for getting content type, relevant settings, clearing content, queueing files, and processing updates. ```typescript interface IContentProvider { getContentType(): ContentProviderType; getRelevantSettings(): (keyof NotebookNavigatorSettings)[]; shouldRegenerate(oldSettings: NotebookNavigatorSettings, newSettings: NotebookNavigatorSettings): boolean; clearContent(context?: ContentProviderClearContext): Promise; queueFiles(files: TFile[]): void; startProcessing(settings: NotebookNavigatorSettings): void; stopProcessing(): void; waitForIdle(): Promise; onSettingsChanged(settings: NotebookNavigatorSettings): void; } ``` -------------------------------- ### Service Initialization in TypeScript Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fservice-architecture Demonstrates the initialization of various services within the Notebook Navigator plugin during startup. This includes services like RecentNotesService, WorkspaceCoordinator, TagTreeService, and ReleaseCheckService. ```typescript // Database and settings load happen before this block this.initializeRecentDataManager(); this.recentNotesService = new RecentNotesService(this); // Initialize workspace and homepage coordination this.workspaceCoordinator = new WorkspaceCoordinator(this); this.homepageController = new HomepageController(this, this.workspaceCoordinator); // Initialize services this.tagTreeService = new TagTreeService(); this.metadataService = new MetadataService(this.app, this, () => this.tagTreeService); this.tagOperations = new TagOperations( this.app, () => this.settings, () => this.tagTreeService, () => this.metadataService ); this.commandQueue = new CommandQueueService(this.app); this.fileSystemOps = new FileSystemOperations( this.app, () => this.tagTreeService, () => this.commandQueue, (): VisibilityPreferences => ({ includeDescendantNotes: this.uxPreferences.includeDescendantNotes, showHiddenItems: this.uxPreferences.showHiddenItems }), this ); this.omnisearchService = new OmnisearchService(this.app); this.api = new NotebookNavigatorAPI(this, this.app); this.releaseCheckService = new ReleaseCheckService(this); const iconService = getIconService(); this.externalIconController = new ExternalIconProviderController(this.app, iconService, this); const iconController = this.externalIconController; if (iconController) { runAsyncAction( async () => { await iconController.initialize(); await iconController.syncWithSettings(); }, { onError: (error: unknown) => { console.error('External icon controller init failed:', error); } } ); } ``` -------------------------------- ### Get API Version (JavaScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference Retrieves the current version string of the Notebook Navigator API. This is useful for compatibility checks or logging. ```javascript const apiVersion = nn.core.getVersion(); console.log(`Notebook Navigator API Version: ${apiVersion}`); ``` -------------------------------- ### React Context Providers for Dependency Injection Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fservice-architecture Illustrates the React component structure for providing dependencies to the Notebook Navigator UI. It uses nested context providers for settings, UX preferences, data, services, shortcuts, and storage. ```tsx {/* Navigator providers and UI */} ``` -------------------------------- ### Manage Folder and File Pins with Metadata API Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference This snippet demonstrates how to set metadata for folders (color, background color, icon) and how to pin/unpin files. It covers setting specific properties, clearing properties, pinning to default contexts, pinning to specific contexts, checking if a file is pinned, and retrieving all pinned files with their context information. Dependencies: 'app' object from Obsidian, 'nn' object from Notebook Navigator. ```typescript // Set folder appearance const folder = app.vault.getFolderByPath('Projects'); if (folder) { await nn.metadata.setFolderMeta(folder, { color: '#FF5733', // Hex, or 'red', 'rgb(255, 87, 51)', 'hsl(9, 100%, 60%)' backgroundColor: '#FFF3E0', // Light background color icon: 'lucide:folder-open' // Type-safe with IconString }); // Update only specific properties (other properties unchanged) await nn.metadata.setFolderMeta(folder, { color: 'blue' }); // Clear properties by passing null await nn.metadata.setFolderMeta(folder, { icon: null, backgroundColor: null }); } // Pin a file const file = app.workspace.getActiveFile(); if (file) { await nn.metadata.pin(file); // Pins in both folder and tag contexts by default // Or pin in specific context await nn.metadata.pin(file, 'folder'); } // Check if pinned if (nn.metadata.isPinned(file, 'folder')) { console.log('Pinned in folder context'); } // Get all pinned files with context info const pinned = nn.metadata.getPinned(); // Returns: Map // Example: Map { "Notes/todo.md" => { folder: true, tag: false }, ... } // Iterate over pinned files for (const [path, context] of pinned) { if (context.folder) { console.log(`${path} is pinned in folder view`); } } ``` -------------------------------- ### Get All Pinned Files (JavaScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference Retrieves a read-only collection of all files currently pinned in Notebook Navigator, including their associated context information (folder, tag, or both). ```javascript const pinnedFiles = nn.metadata.getPinned(); // pinnedFiles is an object mapping file paths to their context information ``` -------------------------------- ### Manage Homepage - HomepageController (TypeScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fservice-architecture HomepageController resolves configured homepage files, applies mobile overrides, and opens them at startup or via command. It collaborates with WorkspaceCoordinator and CommandQueueService for file operations. ```typescript resolveHomepageFile(): TFile | null handleWorkspaceReady(options: { shouldActivateOnStartup: boolean }): Promise open(trigger: 'startup' | 'command'): Promise ``` -------------------------------- ### Command Queue Service Key Methods Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fservice-architecture This TypeScript code snippet outlines the key methods available in the CommandQueueService. These methods facilitate managing active operations, executing file and folder-related commands, and subscribing to operation change events. ```typescript onOperationChange(listener: (type: OperationType, active: boolean) => void): () => void hasActiveOperation(type: OperationType): boolean getActiveOperations(): Operation[] clearAllOperations(): void isMovingFile(): boolean isDeletingFiles(): boolean isOpeningFolderNote(): boolean isOpeningHomepage(): boolean isOpeningVersionHistory(): boolean isOpeningInNewContext(): boolean executeMoveFiles( files: TFile[], targetFolder: TFolder ): Promise> executeDeleteFiles(files: TFile[], performDelete: () => Promise): Promise executeOpenFolderNote(folderPath: string, openFile: () => Promise): Promise executeOpenVersionHistory(file: TFile, openHistory: () => Promise): Promise executeOpenInNewContext(file: TFile, context: PaneType, openFile: () => Promise): Promise executeOpenActiveFile(file: TFile, openFile: () => Promise): Promise> executeHomepageOpen(file: TFile, openFile: () => Promise): Promise ``` -------------------------------- ### Get Tag Metadata (JavaScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference Fetches all metadata associated with a given tag from the Notebook Navigator API. Tags are normalized internally, so input can be without or with a '#' prefix and is case-insensitive. ```javascript const tagMeta = await nn.metadata.getTagMeta('work'); // or '#work' // tagMeta will be an object containing metadata or null ``` -------------------------------- ### Navigation Separator Management (TypeScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fservice-architecture APIs for managing navigation separators, allowing users to define separators for sections, folders, and tags. It supports adding, removing, and retrieving separators, as well as subscribing to changes and getting the current version. ```typescript getNavigationSeparators(): Record hasNavigationSeparator(target: NavigationSeparatorTarget): boolean addNavigationSeparator(target: NavigationSeparatorTarget): Promise removeNavigationSeparator(target: NavigationSeparatorTarget): Promise getNavigationSeparatorsVersion(): number subscribeToNavigationSeparatorChanges(listener: (version: number) => void): () => void ``` -------------------------------- ### Navigation Pane Virtualization Hooks (TypeScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Frendering-architecture This snippet demonstrates the usage of `useNavigationPaneData` and `useNavigationPaneScroll` hooks for managing data and scroll behavior in the navigation pane. It highlights how these hooks manage items, lookup maps, and virtualizer initialization for efficient rendering. ```typescript const { items, pathToIndex, shortcutIndex, shortcutItems } = useNavigationPaneData({ settings, activeProfile, isVisible: navigationVisible, shortcutsExpanded, recentNotesExpanded, pinShortcuts, sectionOrder }); const { rowVirtualizer, scrollContainerRefCallback, requestScroll } = useNavigationPaneScroll({ items, pathToIndex, isVisible: navigationVisible, activeShortcutKey, scrollMargin: navigationOverlayHeight }); ``` -------------------------------- ### Plugin Unload Sequence in main.ts Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fstartup-process Outlines the critical steps performed during the plugin's `onunload` event in `main.ts`. This includes setting flags, disposing managers, clearing listeners, releasing service instances, stopping content processing, and shutting down the database. ```javascript 1. Set the `isUnloading` flag to prevent new operations from starting. 2. Dispose runtime managers that watch local storage and external providers. * `RecentDataManager.dispose()` stops persistence sync. * `ExternalIconProviderController.dispose()` releases icon provider hooks. 3. Clear listener maps to avoid callbacks during teardown: * Settings update listeners * File rename listeners * Recent data listeners 4. Release service instances: * `MetadataService` and `TagOperations` references set to `null` * `CommandQueueService.clearAllOperations()` then set to `null` * `OmnisearchService` reference cleared * `RecentDataManager` reference cleared after disposal 5. Stop content processing in every navigator leaf: * Iterate leaves via `getLeavesOfType(NOTEBOOK_NAVIGATOR_VIEW)` * Call `stopContentProcessing()` on each view to halt the `ContentProviderRegistry` 6. Remove the ribbon icon element. 7. Call `shutdownDatabase()` to: * Close the IndexedDB connection * Clear the in-memory cache * Keep the operation idempotent for repeated unloads ``` -------------------------------- ### Get Folder Metadata (JavaScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference Retrieves all metadata associated with a given folder using the Notebook Navigator API. This method is useful for inspecting existing folder configurations like color, icon, or background color. ```javascript const folderMeta = await nn.metadata.getFolderMeta(folder); // folderMeta will be an object containing metadata or null if none exists ``` -------------------------------- ### Get Current Navigation Item with Selection API Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference This code snippet illustrates how to use the `getNavItem` method from the Selection API to determine which folder or tag is currently selected in the navigator. It checks if a folder or tag is selected and logs the respective path or name. If neither is selected, it indicates that nothing is selected. ```typescript // Check what's selected const navItem = nn.selection.getNavItem(); if (navItem.folder) { console.log('Folder selected:', navItem.folder.path); } else if (navItem.tag) { console.log('Tag selected:', navItem.tag); } else { console.log('Nothing selected in navigation pane'); } // Get selected files const { files, focused } = nn.selection.getCurrent(); ``` -------------------------------- ### Subscribe to Notebook Navigator Events (TypeScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference Demonstrates how to subscribe to various events emitted by the Notebook Navigator, such as file pinning changes, navigation item changes, and selection changes. It shows how to use `on` for persistent listeners, `once` for one-time subscriptions, and `off` to unsubscribe. Callbacks receive typed payloads. ```typescript // Subscribe to pin changes nn.on('pinned-files-changed', ({ files }) => { console.log(`Total pinned files: ${files.length}`); // Each file includes context information files.forEach(pf => { console.log(`${pf.file.name} - folder: ${pf.context.folder}, tag: ${pf.context.tag}`); }); }); // Use 'once' for one-time events (auto-unsubscribes) nn.once('storage-ready', () => { // Wait for storage to be ready before querying metadata or pinned files console.log('Storage is ready - safe to call read APIs'); // No need to unsubscribe, it's handled automatically }); // Use 'on' for persistent listeners const navRef = nn.on('nav-item-changed', ({ item }) => { if (item.folder) { console.log('Folder selected:', item.folder.path); } else if (item.tag) { console.log('Tag selected:', item.tag); } else { console.log('Navigation selection cleared'); } }); const selectionRef = nn.on('selection-changed', ({ state }) => { // TypeScript knows 'state' is SelectionState with files and focused properties console.log(`${state.files.length} files selected`); }); // Unsubscribe from persistent listeners nn.off(navRef); nn.off(selectionRef); ``` -------------------------------- ### CSS Theme Variables for Quick Actions Panel Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Ftheming-guide Sets the styling for the quick actions panel, including background transparency, border color, border radius, and icon colors for both default and hover states. Also defines separator styling. ```css /* Quick actions */ --nn-theme-quick-actions-bg: rgba(43, 43, 43, 0.95); /* Semi-transparent dark - quick actions panel */ --nn-theme-quick-actions-border: #555555; /* Subtle gray - quick actions border */ --nn-theme-quick-actions-border-radius: 4px; /* Subtle rounded toolbar */ --nn-theme-quick-actions-icon-color: #7f8b91; /* Muted gray - quick action icons */ --nn-theme-quick-actions-icon-hover-color: #a9b7c6; /* Light gray - quick action icons on hover */ --nn-theme-quick-actions-separator-color: #3c3c3c; /* Very subtle - separators between actions */ ``` -------------------------------- ### List Pane Virtualization Hooks (TypeScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Frendering-architecture This snippet showcases the `useListPaneData` and `useListPaneScroll` hooks for handling data and scroll virtualization in the list pane. It illustrates how these hooks compose list items, manage scroll behavior with a priority queue, and integrate with virtualizer components. ```typescript const { listItems, filePathToIndex, orderedFiles } = useListPaneData({ selectionType, selectedFolder, selectedTag, settings, activeProfile, searchProvider, searchQuery: isSearchActive ? debouncedSearchQuery : undefined, searchTokens: isSearchActive ? debouncedSearchTokens : undefined, visibility: { includeDescendantNotes, showHiddenItems } }); const { rowVirtualizer, scrollContainerRefCallback, handleScrollToTop } = useListPaneScroll({ listItems, filePathToIndex, selectedFile, selectedFolder, selectedTag, settings, folderSettings: appearanceSettings, isVisible, selectionState, selectionDispatch, searchQuery: isSearchActive ? debouncedSearchQuery : undefined, suppressSearchTopScrollRef, topSpacerHeight, includeDescendantNotes, scrollMargin: listOverlayHeight }); ``` -------------------------------- ### Content Provider File Detection Logic Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fstartup-process Demonstrates the conditions under which different content providers trigger file processing. These checks ensure that only necessary files are processed based on changes in tags, markdown pipeline status, feature images, or metadata. ```javascript * TagContentProvider: `tags === null` or `tagsMtime !== file.stat.mtime` * MarkdownPipelineContentProvider: `markdownPipelineMtime !== file.stat.mtime`, `previewStatus/featureImageStatus === 'unprocessed'`, or `customProperty === null` * FeatureImageContentProvider: `fileThumbnailsMtime !== file.stat.mtime` or missing/mismatched `featureImageKey` * MetadataContentProvider: `metadata === null` or `metadataMtime !== file.stat.mtime` ``` -------------------------------- ### Content Provider Registry for Batch Processing (TypeScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fmetadata-pipeline The ContentProviderRegistry manages different content providers, such as MarkdownPipelineContentProvider, TagContentProvider, and MetadataContentProvider. It runs provider batches and coordinates changes to provider settings. ```typescript interface ContentProvider { id: string; process(context: any): Promise; } class ContentProviderRegistry { private providers: Map = new Map(); registerProvider(provider: ContentProvider) { this.providers.set(provider.id, provider); } async runProviderBatch(providerIds: string[], context: any) { const batch = providerIds.map(id => this.providers.get(id)); await Promise.all(batch.map(provider => provider?.process(context))); } // ... methods for handling settings changes } // Example providers class MarkdownPipelineContentProvider implements ContentProvider { id = 'markdownPipeline'; async process(context: any) { /* ... */ } } class TagContentProvider implements ContentProvider { id = 'tags'; async process(context: any) { /* ... */ } } ``` -------------------------------- ### Core API Methods Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference Provides essential methods for interacting with the Notebook Navigator API, including retrieving the API version and managing event subscriptions. ```APIDOC ## Core API Methods | Method | Description | Returns | |---------------|----------------------------------------------------|------------| | `getVersion()`| Get API version | `string` | | `on(...)` | Subscribe to typed event | `EventRef` | | `once(...)` | Subscribe once (auto-unsubscribes after trigger) | `EventRef` | | `off(ref)` | Unsubscribe from event | `void` | ``` -------------------------------- ### Pin File in Notebook Navigator (JavaScript/Templater) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference This script uses the Notebook Navigator API to pin the current file. It checks if the API is available and then calls the `pin` method. The `pin` method takes the file object as an argument and optionally a context (defaults to 'all'). ```javascript <%* // Templater script to pin the current file in Notebook Navigator const nn = app.plugins.plugins['notebook-navigator']?.api; if (nn) { // Pin the current file in both folder and tag contexts const file = tp.config.target_file; await nn.metadata.pin(file); new Notice('File pinned in Notebook Navigator'); } %> ``` -------------------------------- ### Deferred Scheduling with setTimeout Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fstartup-process Illustrates the use of `setTimeout` for deferred scheduling to keep the UI responsive. This mechanism is employed for background processing and cleanup tasks across different platforms. ```javascript StorageContext defers non-blocking work with `setTimeout`, keeping the UI responsive: * Schedules background batches with zero-delay timeouts * Works across desktop, mobile, and Safari * Used for background processing and cleanup ``` -------------------------------- ### Pin a File (JavaScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference Adds a file to the pinned list within Notebook Navigator. Files can be pinned universally ('all') or within specific contexts like folders or tags. This is useful for prioritizing important notes. ```javascript await nn.metadata.pin(file, 'folder'); // Pin file in folder context await nn.metadata.pin(file, 'tag'); // Pin file in tag context await nn.metadata.pin(file); // Pin file in both contexts (default) ``` -------------------------------- ### Navigate to Active File with Navigation API Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference This code snippet demonstrates how to use the `reveal` method from the Navigation API to select and focus the currently active file within the file navigator. This action will switch to the file's parent folder, expand parent folders if necessary, select the file, and switch to the file list view in single-pane mode. The method returns silently if the file does not exist. ```typescript // Navigate to active file const activeFile = app.workspace.getActiveFile(); if (activeFile) { await nn.navigation.reveal(activeFile); // File is now selected in its parent folder } ``` -------------------------------- ### Folder Metadata Management (TypeScript) Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fservice-architecture Provides functions to manage metadata for folders, including setting and retrieving colors, background colors, icons, and sort overrides. It also handles folder renaming and deletion events. ```typescript setFolderColor(folderPath: string, color: string): Promise setFolderBackgroundColor(folderPath: string, color: string): Promise removeFolderColor(folderPath: string): Promise removeFolderBackgroundColor(folderPath: string): Promise getFolderColor(folderPath: string): string | undefined getFolderBackgroundColor(folderPath: string): string | undefined setFolderIcon(folderPath: string, iconId: string): Promise removeFolderIcon(folderPath: string): Promise getFolderIcon(folderPath: string): string | undefined setFolderSortOverride(folderPath: string, sortOption: SortOption): Promise removeFolderSortOverride(folderPath: string): Promise getFolderSortOverride(folderPath: string): SortOption | undefined handleFolderRename(oldPath: string, newPath: string): Promise handleFolderDelete(folderPath: string): Promise ``` -------------------------------- ### Notebook Navigator API - Navigation and Selection Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference Methods for navigating to files within the navigator and querying the current selection state. ```APIDOC ## Navigation and Selection APIs ### Description APIs for interacting with the navigation and selection features of Notebook Navigator. ### Navigation API *Methods for navigating to files within the navigator. Specific methods are not detailed in the provided text, but the namespace `navigation` is available. ### Selection API *Methods for querying the current selection state within the navigator. Specific methods are not detailed in the provided text, but the namespace `selection` is available. ``` -------------------------------- ### TypeScript Support - With Type Definitions Source: https://notebooknavigator.com/docs.html/index_doc=developer%2Fapi-reference This section explains how to leverage TypeScript definitions for enhanced type safety, IntelliSense, and compile-time checks when using the Notebook Navigator API. ```APIDOC ### Option 1: With Type Definitions (Recommended) Download the `notebook-navigator.d.ts` file for full type safety and IntelliSense. #### Usage Example (TypeScript) ```typescript import type { NotebookNavigatorAPI, NotebookNavigatorEvents, NavItem, IconString } from './notebook-navigator'; const nn = app.plugins.plugins['notebook-navigator']?.api as NotebookNavigatorAPI; if (nn) { // Wait for storage if needed if (!nn.isStorageReady()) { await new Promise(resolve => nn.once('storage-ready', resolve)); } // Use metadata APIs with type safety await nn.metadata.setFolderMeta(folder, { color: '#FF5733' }); // Icon strings are type-checked const icon: IconString = 'lucide:folder'; // Valid // Events have full type inference nn.on('selection-changed', ({ state }) => { // TypeScript knows 'state' is SelectionState }); } ``` #### Type Safety Features: * **`IconString`**: Template literal types for valid icon formats. * **Generic event subscriptions**: Full type inference for event payloads. * **Readonly arrays**: Prevents accidental mutation of returned data. * **Exported utility types**: `NavItem`, `IconString`, `PinContext`, etc. * **Complete API interface**: `NotebookNavigatorAPI`. * **Typed event system**: `NotebookNavigatorEvents` maps event names to payloads. * **Full JSDoc comments**: Documentation for methods and types. ```