Last active
October 14, 2024 08:01
-
-
Save Quorafind/16202a6b07319a63846e7e534e64d8b2 to your computer and use it in GitHub Desktop.
Obsidian Jump to/Hover Specific Content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Interface defining the options for showing content | |
interface ShowContentOptions { | |
start: number; // Starting position of the content | |
end: number; // Ending position of the content | |
content: string; // The full content string | |
view: MyView; // The view object | |
file: TFile; // The file object | |
plugin: MyPlugin; // The plugin instance | |
} | |
// Debounced function to show content on hover | |
const showContent = debounce((event: MouseEvent, options: ShowContentOptions) => { | |
const { view, file, plugin, start, content } = options; | |
// Create a state object with the calculated scroll position | |
let state = { | |
scroll: calculateLineNumber(content, start), | |
}; | |
// Trigger the hover-link event with the necessary information | |
plugin.app.workspace.trigger('hover-link', { | |
event, | |
source: 'my-source', | |
hoverParent: view.containerEl, | |
targetEl: event.target as HTMLElement, | |
linktext: file.path, | |
sourcePath: file.path, | |
state, | |
}); | |
}, 100); // Debounce delay of 100ms | |
// Function to calculate the line number based on a position in the content | |
const calculateLineNumber = (content: string, position: number): number => { | |
let lineNumber = 0; | |
let index = 0; | |
// Iterate through the content, counting newlines until we reach the position | |
while (index < position && index !== -1) { | |
index = content.indexOf('\n', index); | |
if (index !== -1 && index < position) { | |
index++; | |
lineNumber++; | |
} | |
} | |
return lineNumber; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Plugin, WorkspaceLeaf } from 'obsidian'; | |
export default class MyPlugin extends Plugin { | |
async onload(): Promise<void> { | |
// You need to register hover link source first. | |
this.registerHoverLinkSource('my-plugin', { | |
display: 'My plugin', | |
defaultMod: true, | |
}); | |
} | |
onunload() { | |
super.onunload(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment