-
-
Notifications
You must be signed in to change notification settings - Fork 20
Note Toolbar API
The Note Toolbar API can be executed from Note Toolbar items to get toolbar access, and to show UI (suggesters, prompts, menus, and modals). The latter enables Dataview JS, JS Engine, or Templater scripts to ask for information, or to show helpful text.
I would appreciate your feedback, which you can leave in the discussions.
Even if you're not a developer, getting started with the API is easy:
- Create a new toolbar item with a JavaScript type.
- Select function... → Evaluate JavaScript.
- Copy/Paste one of the examples provided into the JavaScript expression field.
Warning
You can also directly access Note Toolbar's settings or toolbar items via app.plugins.getPlugin("note-toolbar").settings, but be aware that these are subject to change and may break your scripts. The API will be the official way to access and change information about toolbars.
Functions for reading and manipulating notes in the vault.
getProperty: (
property) =>string|undefined
Gets the value of the given property in the active note.
| Parameter | Type | Description |
|---|---|---|
property |
string |
The property to get the frontmatter for. |
string | undefined
The frontmatter value for the given property, or undefined if it does not exist.
const createdDate = ntb.getProperty('created');getSelection: () =>
string
Gets the currently selected text, or the word at the current cursor position, if nothing's selected. Only works in markdown editing or reading modes.
string
The selected text, or the word at the current cursor position. Otherwise returns an empty string.
1.26
setProperty: (
property,value) =>Promise<void>
Sets the given property's value in the active note.
| Parameter | Type | Description |
|---|---|---|
property |
string |
Propety to set in the frontmatter. |
value |
any |
Value to set for the property. |
Promise<void>
await ntb.setProperty('Created', moment().format('YYYY-MM-DD'));
await ntb.setProperty('cssclasses', 'myclass');
await ntb.setProperty('A Link', '[[Some Note]]');
await ntb.setProperty('A Number', 1234);
await ntb.setProperty('A List', ['asdf', 'asdf2']);setSelection: (
replacement) =>void
Replaces the selected text, or the word at the cursor position, with the provided string.
| Parameter | Type | Description |
|---|---|---|
replacement |
string |
The text to replace the selection with. |
void
This does not do anything in Reading mode.
// makes the selected text or the current word red
ntb.setSelection(`<span style="color: var(--color-red)">${ntb.getSelection()}</span>`);1.26
Methods for creating and updating toolbars.
export: (
toolbar) =>Promise<string|null>
Exports the given toolbar as a Note Toolbar callout.
| Parameter | Type |
|---|---|
toolbar |
IToolbar |
Promise<string | null>
Toolbar as a callout or null if the toolbar is undefined.
const toolbars = ntb.getToolbars();
for (let toolbar of toolbars) {
console.log(`\n## ${toolbar.getName()}\n\n`);
console.log(await ntb.export(toolbar));
}NtbExport.js in the examples/Scripts folder.
1.29
getActiveItem: () =>
IItem|undefined
Gets the active (last activated) toolbar item.
IItem | undefined
The active (last activated) item.
This does not work with Note Toolbar Callouts.
getItem: (
id) =>IItem|undefined
Gets an item by its ID, if it exists.
| Parameter | Type | Description |
|---|---|---|
id |
string |
The ID of the item. |
IItem | undefined
The item, or undefined.
// to get the ID, edit an item's settings and use _Copy developer ID_
const item = ntb.getItem('112c7ed3-d5c2-4750-b95d-75bc84e23513');getToolbars: () =>
IToolbar[]
Gets all toolbars.
IToolbar[]
All toolbars.
Functions for showing various UI components, such as menus, modals, toolbars, and suggesters.
fileSuggester: (
options?) =>Promise<TAbstractFile|null>
Shows a file suggester modal and waits for the user's selection.
| Parameter | Type | Description |
|---|---|---|
options? |
{ allowCustomInput?: boolean; class?: string; collapse?: boolean; default?: string; exact?: boolean; filesonly?: boolean; folder?: string; foldersonly?: boolean; icon?: string; keymap?: object[]; label?: string; limit?: number; placeholder?: string; prefixes?: Record<string, unknown[] | (() => unknown[] | Promise<unknown>)>; rendermd?: boolean; } |
Optional display options. |
options.allowCustomInput? |
boolean |
If set to true, the user can input a custom value that is not in the list of suggestions. Default is false. |
options.class? |
string |
Optional CSS class(es) to add to the component. |
options.collapse? |
boolean |
If set to true, the results and suggester instructions are hidden until input is provided. Default is false. Since 1.29.14 |
options.default? |
string |
Optionally pre-set the suggester's input with this value. Matching results will be shown, as if you typed in that string yourself (assuming the string appears in the list of options provided). If not provided, no default is set. |
options.exact? |
boolean |
Set to true to use substring matching instead of fuzzy matching, prioritizing results that start with the input string. Default is false. Since 1.30.10 |
options.filesonly? |
boolean |
If set to true, only files are shown. If not provided, defaults to false. |
options.folder? |
string |
Limit results to this folder. Since 1.30.14 |
options.foldersonly? |
boolean |
If set to true, only folders are shown. If not provided, defaults to false. |
options.icon? |
string |
Optional icon to place before the input field. Since 1.29.14 |
options.keymap? |
object[] |
Optionally replace key bindings. See NtbKeyBinding for available actions and modifier options. Since 1.30.06 |
options.label? |
string |
Optional text shown above the input field, with markdown formatting supported. Default is no label. |
options.limit? |
number |
Optional limit of the number of items rendered at once (useful to improve performance when displaying large lists). |
options.placeholder? |
string |
Optional placeholder text for input field; defaults to preset message. |
options.prefixes? |
Record<string, unknown[] | (() => unknown[] | Promise<unknown>)> |
Maps input prefixes to arrays or functions that return suggestions, or a Promise (e.g. another suggester) that resolves to a value which is injected into the input. Examples { '#': ['tag1', 'tag2'], '[[': () => getFiles() } { '#': async () => await ntb.suggester(lorem, ipsum) } Since 1.30.0 |
options.rendermd? |
boolean |
Set to false to disable rendering of suggestions as markdown. Default is true. |
Promise<TAbstractFile | null>
The selected TAbstractFile.
const fileOrFolder = await ntb.fileSuggester();
new Notice(fileOrFolder.name);// show only folders
const folder = await ntb.fileSuggester({
foldersonly: true
});
new Notice(folder.name);menu: (
toolbarOrItems,options?) =>Promise<void>
Shows a menu with the provided items.
| Parameter | Type | Description |
|---|---|---|
toolbarOrItems |
string | NtbMenuItem[] |
Toolbar name or ID; or an array of items to display. See NtbMenuItem. |
options? |
{ class?: string; focusInMenu?: boolean; id?: string; position: "cursor" | "pointer" | "toolbar"; } |
Optional display options. |
options.class? |
string |
Optional CSS class(es) to add to the component. |
options.focusInMenu? |
boolean |
If true, the menu item will be focused when the menu opens; defaults to false. |
options.id? |
string |
Optional ID to add to the menu when it's rendered. Since 1.27 |
options.position? |
"cursor" | "pointer" | "toolbar"
|
Sets the position in which the menu will appear; defaults to toolbar. cursor: editor cursor or selected text position (falls back to pointer position, e.g., if editor is not in focus); pointer: mouse/pointer position; toolbar: last clicked toolbar element position (falls back to pointer position) Since 1.27 |
Promise<void>
Nothing. Displays the menu.
// show the "Daily Notes" toolbar as a menu
await ntb.menu('Daily Notes');// create a menu from scratch
await ntb.menu([
{ type: 'command', value: 'editor:toggle-bold', label: 'Toggle Bold', icon: 'bold' },
{ type: 'file', value: 'Home.md', label: 'Open File' },
{ type: 'uri', value: 'https://example.com', label: 'Visit Site' }
]);// shows bookmarks in a menu
const b = ntb.app.internalPlugins.plugins['bookmarks'];
if (!b?.enabled) return;
const i = b.instance?.getBookmarks();
const b = ntb.app.internalPlugins.plugins['bookmarks'];
const mi = i
.filter(b => b.type === 'file' || b.type === 'folder')
.map(b => ({
type: 'file',
value: b.path,
label: b.title ? b.title : b.path,
icon: b.type === 'folder' ? 'folder' : 'file'
}));
ntb.menu(mi);modal: (
content,options?) =>Promise<Modal>
Shows a modal with the provided content.
| Parameter | Type | Description |
|---|---|---|
content |
string | TFile
|
Content to display in the modal, either as a string or a file within the vault. |
options? |
{ class?: string; title?: string; webpage?: boolean; } |
Optional display options. |
options.class? |
string |
Optional CSS class(es) to add to the component. |
options.title? |
string |
Optional title for the modal, with markdown formatting supported. |
options.webpage? |
boolean |
If true, the modal will show the web page URL in content using the Web Viewer core plugin (if enabled); defaults to false. |
Promise<Modal>
A Modal, in case you want to manipulate it further; can be ignored otherwise.
// shows a modal with the provided string
await ntb.modal("_Hello_ world!");// shows a modal with the rendered contents of a file
const filename = "Welcome.md";
const file = ntb.app.vault.getAbstractFileByPath(filename);
if (file) {
await ntb.modal(file, {
title: `**${file.basename}**`
});
}
else {
new Notice(`File not found: ${filename}`);
}NtbModal.js in the examples/Scripts folder.
prompt: (
options?) =>Promise<string|null>
Shows the prompt modal and waits for the user's input.
| Parameter | Type | Description |
|---|---|---|
options? |
{ class?: string; default?: string; label?: string; large?: boolean; placeholder?: string; } |
Optional display options. |
options.class? |
string |
Optional CSS class(es) to add to the component. |
options.default? |
string |
Optional default value for text field. If not provided, no default value is set. |
options.label? |
string |
Optional text shown above the text field, with markdown formatting supported. Default is no label. |
options.large? |
boolean |
If set to true, the input field will be multi line. If not provided, defaults to false. |
options.placeholder? |
string |
Optional text inside text field. Defaults to a preset message. |
Promise<string | null>
The user's input.
// default (one-line) prompt with default placeholder message
const result = await ntb.prompt();
new Notice(result);// large prompt with message, overridden placeholder, and default value
const result = await ntb.prompt({
label: "Enter some text",
large: true,
placeholder: "Placeholder",
default: "Default"
});
new Notice(result);NtbPrompt.js in the examples/Scripts folder.
suggester: (
values?,keys?,options?) =>Promise<T|null>
Shows a suggester modal and waits for the user's selection.
| Parameter | Type | Description |
|---|---|---|
values? |
string[] | ((value) => string) |
Array of strings representing the text that will be displayed for each item in the suggester prompt. This can also be a function that maps an item to its text representation. Markdown formatting is supported: optionally mix in Obsidian and plugin markdown (e.g., Iconize) to have it rendered |
keys? |
T[] |
Optional array containing the keys of each item in the correct order. If not provided or null, values are returned on selection. |
options? |
{ allowCustomInput?: boolean; class?: string; collapse?: boolean; default?: string; exact?: boolean; icon?: string; keymap?: object[]; label?: string; limit?: number; placeholder?: string; prefixes?: Record<string, unknown[] | (() => unknown[] | Promise<unknown>)>; rendermd?: boolean; } |
Optional display options. |
options.allowCustomInput? |
boolean |
If set to true, the user can input a custom value that is not in the list of suggestions. Default is false. |
options.class? |
string |
Optional CSS class(es) to add to the component. |
options.collapse? |
boolean |
If set to true, the results and suggester instructions are hidden until input is provided. Default is false. Since 1.29.14 |
options.default? |
string |
Optionally pre-set the suggester's input with this value. Matching results will be shown, as if you typed in that string yourself (assuming the string appears in the list of options provided). If not provided, no default is set. |
options.exact? |
boolean |
Set to true to use substring matching instead of fuzzy matching, prioritizing results that start with the input string. Default is false. Since 1.30.10 |
options.icon? |
string |
Optional icon to place before the input field. Since 1.29.14 |
options.keymap? |
object[] |
Optionally replace key bindings. See NtbKeyBinding for available actions and modifier options. Since 1.30.06 |
options.label? |
string |
Optional text shown above the input field, with markdown formatting supported. Default is no label. |
options.limit? |
number |
Optional limit of the number of items rendered at once (useful to improve performance when displaying large lists). |
options.placeholder? |
string |
Optional placeholder text for input field; defaults to preset message. |
options.prefixes? |
Record<string, unknown[] | (() => unknown[] | Promise<unknown>)> |
Maps input prefixes to arrays or functions that return suggestions, or a Promise (e.g. another suggester) that resolves to a value which is injected into the input. Examples { '#': ['tag1', 'tag2'], '[[': () => getFiles() } { '#': async () => await ntb.suggester(lorem, ipsum) } Since 1.30.0 |
options.rendermd? |
boolean |
Set to false to disable rendering of suggestions as markdown. Default is true. |
Promise<T | null>
The selected value, or corresponding key if keys are provided.
// shows a suggester that returns the selected value
const values = ["value `1`", "value `2`"];
const selectedValue = await ntb.suggester(values);
new Notice(selectedValue);// shows a suggester that returns a key corresponding to the selected value, and overrides placeholder text
const values = ["value `1`", "value `2`"];
const keys = ["key1", "key2"];
const selectedKey = await ntb.suggester(values, keys, {
placeholder: "Pick something"
});
new Notice(selectedKey);// shows a suggester with no existing values that can be typed in; displays tag and file suggestions when those prefixes are entered
const selected = await ntb.suggester(null, null, {
prefixes: {
"#": () => Object.keys(this.ntb.app.metadataCache.getTags()),
"[[": () => this.ntb.app.vault.getAllLoadedFiles().map(f => `[[${f.extension === 'md' ? f.basename : f.name}]]`)
}
});
new Notice(selected);// displays a suggester with the key mappings overridden
const values = ['cat', 'dog'];
const selected = await ntb.suggester(values, null, {
keymap: [
{ key: 'Tab', action: 'navigateNext' },
{ modifiers: ['Ctrl'], key: 'Tab', action: 'select' },
{ key: 'ArrowRight', action: 'autofill' },
],
});
new Notice(selected);NtbSuggester.js in the examples/Scripts folder.
toolbar: (
toolbarNameOrId,options?) =>Promise<void>
Shows a (floating) toolbar. Defaults to the 'toolbar' position.
| Parameter | Type | Description |
|---|---|---|
toolbarNameOrId |
string |
Toolbar name or ID. |
options? |
{ class?: string; position: "cursor" | "pointer" | "toolbar"; } |
Optional display options. |
options.class? |
string |
Optional CSS class(es) to add to the component. |
options.position? |
"cursor" | "pointer" | "toolbar"
|
Sets the position in which the toolbar will appear; defaults to toolbar. cursor: editor cursor or selected text position (falls back to pointer position, e.g., if editor is not in focus); pointer: mouse/pointer position; toolbar: last clicked toolbar element position (falls back to pointer position) |
Promise<void>
Nothing. Displays the toolbar.
// show the "Daily Notes" toolbar at the toolbar button (default)
ntb.toolbar('Daily Notes');// show the "Daily Notes" toolbar at the cursor position (or above the text selection)
ntb.toolbar('Daily Notes', { position: 'cursor' });1.27
app:
App
The Obsidian app instance. Use this instead of the global app when writing JavaScript.
const currentFile = ntb.app.workspace.getActiveFile();
new Notice(currentFile.name);1.26
clipboard: () =>
Promise<string|null>
Gets the clipboard value.
Promise<string | null>
The clipboard value or null.
// gets the clipboard value
const value = await ntb.clipboard();
new Notice(value);o:
__module
Reference to the Obsidian API module for accessing Obsidian classes and utilities from scripts.
// get the current markdown view
const view = ntb.app.workspace.getActiveViewOfType(ntb.o.MarkdownView);1.26
t:
string
This is the i18next translation function, scoped to Note Toolbar's localized strings.
The string translation corresponding with the provided key, if it exists, with a fallback to English. If the key does not exist, the key is returned.
// shows "Copied to clipboard" if the language is English, or in another langauge if the translation exists
new Notice(ntb.t('api.msg.clipboard-copied'));- For usage, see the i18next documentation.
-
en.jsonand other translations in the src/I18n folder.
User Guide • Gallery • Note Toolbar API • Support • Discussions ↗ • Release Notes ↗ • Roadmap
Note Toolbar by Chris Gurney • Buy me a coffee ☕️