Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(client/ts): port services/frontend_script_api
Elian Doran650a116193ae
diff --git a/src/public/app/components/app_context.ts b/src/public/app/components/app_context.tsindex 6372d43ce3..783373023d 100644--- a/src/public/app/components/app_context.ts+++ b/src/public/app/components/app_context.ts@@ -14,6 +14,7 @@ import MainTreeExecutors from "./main_tree_executors.js";import toast from "../services/toast.js";import ShortcutComponent from "./shortcut_component.js";import { t, initLocale } from "../services/i18n.js";+import NoteDetailWidget from "../widgets/note_detail.js";interface Layout {getRootWidget: (appContext: AppContext) => RootWidget;@@ -27,11 +28,18 @@ interface BeforeUploadListener extends Component {beforeUnloadEvent(): boolean;}-interface TriggerData {+export type TriggerData = {noteId?: string;noteIds?: string[];- messages?: unknown[];+ messages?: unknown[];callback?: () => void;+} | {+ ntxId: string;+ notePath: string;+} | {+ text: string;+} | {+ callback: (value: NoteDetailWidget | PromiseLike<NoteDetailWidget>) => void}class AppContext extends Component {diff --git a/src/public/app/services/frontend_script_api.js b/src/public/app/services/frontend_script_api.tssimilarity index 65%rename from src/public/app/services/frontend_script_api.jsrename to src/public/app/services/frontend_script_api.tsindex 5af37876a5..b320518fee 100644--- a/src/public/app/services/frontend_script_api.js+++ b/src/public/app/services/frontend_script_api.ts@@ -9,12 +9,17 @@ import dateNotesService from './date_notes.js';import searchService from './search.js';import RightPanelWidget from '../widgets/right_panel_widget.js';import ws from "./ws.js";-import appContext from "../components/app_context.js";+import appContext, { TriggerData } from "../components/app_context.js";import NoteContextAwareWidget from "../widgets/note_context_aware_widget.js";import BasicWidget from "../widgets/basic_widget.js";import SpacedUpdate from "./spaced_update.js";import shortcutService from "./shortcuts.js";import dialogService from "./dialog.js";+import FNote from '../entities/fnote.js';+import { t } from './i18n.js';+import NoteContext from '../components/note_context.js';+import NoteDetailWidget from '../widgets/note_detail.js';+import Component from '../components/component.js';/**@@ -28,116 +33,94 @@ import dialogService from "./dialog.js";* @var {FrontendScriptApi} api*/-/**- * <p>This is the main frontend API interface for scripts. All the properties and methods are published in the "api" object- * available in the JS frontend notes. You can use e.g. <code>api.showMessage(api.startNote.title);</code></p>- *- * @constructor- */-function FrontendScriptApi(startNote, currentNote, originEntity = null, $container = null) {+interface AddToToolbarOpts {+ title: string;+ /** callback handling the click on the button */+ action: () => void;+ /** id of the button, used to identify the old instances of this button to be replaced+ * ID is optional because of BC, but not specifying it is deprecated. ID can be alphanumeric only. */+ id: string;+ /** name of the boxicon to be used (e.g. "time" for "bx-time" icon) */+ icon: string;+ /** keyboard shortcut for the button, e.g. "alt+t" */+ shortcut: string;+}++// TODO: Deduplicate me with the server.+interface ExecResult {+ success: boolean;+ executionResult: unknown;+ error?: string;+}++interface Entity {+ noteId: string;+}++type Func = ((...args: unknown[]) => unknown) | string;++interface Api {/*** Container of all the rendered script content- * @type {jQuery}* */- this.$container = $container;+ $container: JQuery<HTMLElement> | null;/*** Note where the script started executing, i.e., the (event) entrypoint of the current script execution.- * @type {FNote}*/- this.startNote = startNote;+ startNote: FNote;/*** Note where the script is currently executing, i.e. the note where the currently executing source code is written.- * @type {FNote}*/- this.currentNote = currentNote;+ currentNote: FNote;/*** Entity whose event triggered this execution.- * @type {object|null}*/- this.originEntity = originEntity;+ originEntity: unknown | null;/*** day.js library for date manipulation.* See {@link https://day.js.org} for documentation* @see https://day.js.org- * @type {dayjs}*/- this.dayjs = dayjs;-- /** @type {RightPanelWidget} */- this.RightPanelWidget = RightPanelWidget;+ dayjs: typeof window.dayjs;- /** @type {NoteContextAwareWidget} */- this.NoteContextAwareWidget = NoteContextAwareWidget;-- /** @type {BasicWidget} */- this.BasicWidget = BasicWidget;+ RightPanelWidget: typeof RightPanelWidget;+ NoteContextAwareWidget: typeof NoteContextAwareWidget;+ BasicWidget: typeof BasicWidget;/*** Activates note in the tree and in the note detail.*- * @method- * @param {string} notePath (or noteId)- * @returns {Promise<void>}+ * @param notePath (or noteId)*/- this.activateNote = async notePath => {- await appContext.tabManager.getActiveContext().setNote(notePath);- };+ activateNote(notePath: string): Promise<void>;/*** Activates newly created note. Compared to this.activateNote() also makes sure that frontend has been fully synced.*- * @param {string} notePath (or noteId)- * @returns {Promise<void>}+ * @param notePath (or noteId)*/- this.activateNewNote = async notePath => {- await ws.waitForMaxKnownEntityChangeId();-- await appContext.tabManager.getActiveContext().setNote(notePath);- await appContext.triggerEvent('focusAndSelectTitle');- };+ activateNewNote(notePath: string): Promise<void>;- /**+ /*** Open a note in a new tab.** @method- * @param {string} notePath (or noteId)- * @param {boolean} activate - set to true to activate the new tab, false to stay on the current tab- * @returns {Promise<void>}+ * @param notePath (or noteId)+ * @param activate - set to true to activate the new tab, false to stay on the current tab*/- this.openTabWithNote = async (notePath, activate) => {- await ws.waitForMaxKnownEntityChangeId();-- await appContext.tabManager.openTabWithNoteWithHoisting(notePath, { activate });-- if (activate) {- await appContext.triggerEvent('focusAndSelectTitle');- }- };+ openTabWithNote(notePath: string, activate: boolean): Promise<void>;/*** Open a note in a new split.*- * @method- * @param {string} notePath (or noteId)- * @param {boolean} activate - set to true to activate the new split, false to stay on the current split- * @returns {Promise<void>}+ * @param notePath (or noteId)+ * @param activate - set to true to activate the new split, false to stay on the current split*/- this.openSplitWithNote = async (notePath, activate) => {- await ws.waitForMaxKnownEntityChangeId();-- const subContexts = appContext.tabManager.getActiveContext().getSubContexts();- const {ntxId} = subContexts[subContexts.length - 1];-- await appContext.triggerCommand("openNewNoteSplit", {ntxId, notePath});-- if (activate) {- await appContext.triggerEvent('focusAndSelectTitle');- }- };+ openSplitWithNote(notePath: string, activate: boolean): Promise<void>;/*** Adds a new launcher to the launchbar. If the launcher (id) already exists, it will be updated.@@ -145,64 +128,13 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain* @method* @deprecated you can now create/modify launchers in the top-left Menu -> Configure Launchbar* for special needs there's also backend API's createOrUpdateLauncher()- * @param {object} opts- * @param {string} opts.title- * @param {function} opts.action - callback handling the click on the button- * @param {string} [opts.id] - id of the button, used to identify the old instances of this button to be replaced- * ID is optional because of BC, but not specifying it is deprecated. ID can be alphanumeric only.- * @param {string} [opts.icon] - name of the boxicon to be used (e.g. "time" for "bx-time" icon)- * @param {string} [opts.shortcut] - keyboard shortcut for the button, e.g. "alt+t"*/- this.addButtonToToolbar = async opts => {- console.warn("api.addButtonToToolbar() has been deprecated since v0.58 and may be removed in the future. Use Menu -> Configure Launchbar to create/update launchers instead.");+ addButtonToToolbar(opts: AddToToolbarOpts): void;- const {action, ...reqBody} = opts;- reqBody.action = action.toString();-- await server.put('special-notes/api-script-launcher', reqBody);- };-- function prepareParams(params) {- if (!params) {- return params;- }-- return params.map(p => {- if (typeof p === "function") {- return `!@#Function: ${p.toString()}`;- }- else {- return p;- }- });- }-- /**+ /*** @private*/- this.__runOnBackendInner = async (func, params, transactional) => {- if (typeof func === "function") {- func = func.toString();- }-- const ret = await server.post('script/exec', {- script: func,- params: prepareParams(params),- startNoteId: startNote.noteId,- currentNoteId: currentNote.noteId,- originEntityName: "notes", // currently there's no other entity on the frontend which can trigger event- originEntityId: originEntity ? originEntity.noteId : null,- transactional- }, "script");-- if (ret.success) {- await ws.waitForMaxKnownEntityChangeId();-- return ret.executionResult;- } else {- throw new Error(`server error: ${ret.error}`);- }- }+ __runOnBackendInner(func: unknown, params: unknown[], transactional: boolean): unknown;/*** Executes given anonymous function on the backend.@@ -211,17 +143,11 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain* with transaction management. If you really know what you're doing, you can call api.runAsyncOnBackendWithManualTransactionHandling()** @method- * @param {function|string} func - (synchronous) function to be executed on the backend- * @param {Array.<?>} params - list of parameters to the anonymous function to be sent to backend- * @returns {Promise<*>} return value of the executed function on the backend+ * @param func - (synchronous) function to be executed on the backend+ * @param params - list of parameters to the anonymous function to be sent to backend+ * @returns return value of the executed function on the backend*/- this.runOnBackend = async (func, params = []) => {- if (func?.constructor.name === "AsyncFunction" || func?.startsWith?.("async ")) {- toastService.showError(t("frontend_script_api.async_warning"));- }-- return await this.__runOnBackendInner(func, params, true);- };+ runOnBackend(func: Func, params: unknown[]): unknown;/*** Executes given anonymous function on the backend.@@ -233,52 +159,28 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain* If you have a synchronous function, please use api.runOnBackend().** @method- * @param {function|string} func - (synchronous) function to be executed on the backend- * @param {Array.<?>} params - list of parameters to the anonymous function to be sent to backend- * @returns {Promise<*>} return value of the executed function on the backend+ * @param func - (synchronous) function to be executed on the backend+ * @param params - list of parameters to the anonymous function to be sent to backend+ * @returns return value of the executed function on the backend*/- this.runAsyncOnBackendWithManualTransactionHandling = async (func, params = []) => {- if (func?.constructor.name === "Function" || func?.startsWith?.("function")) {- toastService.showError(t("frontend_script_api.sync_warning"));- }-- return await this.__runOnBackendInner(func, params, false);- };+ runAsyncOnBackendWithManualTransactionHandling(func: Func, params: unknown[]): unknown;/*** This is a powerful search method - you can search by attributes and their values, e.g.:* "#dateModified =* MONTH AND #log". See full documentation for all options at: https://triliumnext.github.io/Docs/Wiki/search.html- *- * @method- * @param {string} searchString- * @returns {Promise<FNote[]>}*/- this.searchForNotes = async searchString => {- return await searchService.searchForNotes(searchString);- };+ searchForNotes(searchString: string): Promise<FNote[]>;/*** This is a powerful search method - you can search by attributes and their values, e.g.:* "#dateModified =* MONTH AND #log". See full documentation for all options at: https://triliumnext.github.io/Docs/Wiki/search.html- *- * @method- * @param {string} searchString- * @returns {Promise<FNote|null>}*/- this.searchForNote = async searchString => {- const notes = await this.searchForNotes(searchString);-- return notes.length > 0 ? notes[0] : null;- };+ searchForNote(searchString: string): Promise<FNote | null>;/*** Returns note by given noteId. If note is missing from the cache, it's loaded.- **- * @method- * @param {string} noteId- * @returns {Promise<FNote>}*/- this.getNote = async noteId => await froca.getNote(noteId);+ getNote(noteId: string): Promise<FNote | null>;/*** Returns list of notes. If note is missing from the cache, it's loaded.@@ -286,265 +188,189 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain* This is often used to bulk-fill the cache with notes which would have to be picked one by one* otherwise (by e.g. createLink())*- * @method- * @param {string[]} noteIds- * @param {boolean} [silentNotFoundError] - don't report error if the note is not found- * @returns {Promise<FNote[]>}+ * @param [silentNotFoundError] - don't report error if the note is not found*/- this.getNotes = async (noteIds, silentNotFoundError = false) => await froca.getNotes(noteIds, silentNotFoundError);+ getNotes(noteIds: string[], silentNotFoundError: boolean): Promise<FNote[]>;/*** Update frontend tree (note) cache from the backend.- *- * @method- * @param {string[]} noteIds*/- this.reloadNotes = async noteIds => await froca.reloadNotes(noteIds);+ reloadNotes(noteIds: string[]): Promise<void>;/*** Instance name identifies particular Trilium instance. It can be useful for scripts* if some action needs to happen on only one specific instance.- *- * @method- * @returns {string}*/- this.getInstanceName = () => window.glob.instanceName;+ getInstanceName(): string;/**- * @method- * @param {Date} date- * @returns {string} date in YYYY-MM-DD format+ * @returns date in YYYY-MM-DD format*/- this.formatDateISO = utils.formatDateISO;+ formatDateISO: typeof utils.formatDateISO;- /**- * @method- * @param {string} str- * @returns {Date} parsed object- */- this.parseDate = utils.parseDate;+ parseDate: typeof utils.parseDate;/*** Show an info toast message to the user.- *- * @method- * @param {string} message*/- this.showMessage = toastService.showMessage;+ showMessage: typeof toastService.showMessage;/*** Show an error toast message to the user.- *- * @method- * @param {string} message*/- this.showError = toastService.showError;+ showError: typeof toastService.showError;/*** Show an info dialog to the user.- *- * @method- * @param {string} message- * @returns {Promise}*/- this.showInfoDialog = dialogService.info;+ showInfoDialog: typeof dialogService.info;/*** Show confirm dialog to the user.- *- * @method- * @param {string} message- * @returns {Promise<boolean>} promise resolving to true if the user confirmed+ * @returns promise resolving to true if the user confirmed*/- this.showConfirmDialog = dialogService.confirm;+ showConfirmDialog: typeof dialogService.confirm;/*** Show prompt dialog to the user.*- * @method- * @param {object} props- * @param {string} props.title- * @param {string} props.message- * @param {string} props.defaultValue- * @returns {Promise<string>} promise resolving to the answer provided by the user+ * @returns promise resolving to the answer provided by the user*/- this.showPromptDialog = dialogService.prompt;+ showPromptDialog: typeof dialogService.prompt;/*** Trigger command. This is a very low-level API which should be avoided if possible.- *- * @method- * @param {string} name- * @param {object} data*/- this.triggerCommand = (name, data) => appContext.triggerCommand(name, data);+ triggerCommand(name: string, data: TriggerData): void;/*** Trigger event. This is a very low-level API which should be avoided if possible.- *- * @method- * @param {string} name- * @param {object} data*/- this.triggerEvent = (name, data) => appContext.triggerEvent(name, data);+ triggerEvent(name: string, data: TriggerData): void;- /**+ /*** Create a note link (jQuery object) for given note.*- * @method* @param {string} notePath (or noteId)* @param {object} [params]- * @param {boolean} [params.showTooltip=true] - enable/disable tooltip on the link- * @param {boolean} [params.showNotePath=false] - show also whole note's path as part of the link- * @param {boolean} [params.showNoteIcon=false] - show also note icon before the title+ * @param {boolean} [params.showTooltip] - enable/disable tooltip on the link+ * @param {boolean} [params.showNotePath] - show also whole note's path as part of the link+ * @param {boolean} [params.showNoteIcon] - show also note icon before the title* @param {string} [params.title] - custom link tile with note's title as default* @param {string} [params.title=] - custom link tile with note's title as default* @returns {jQuery} - jQuery element with the link (wrapped in <span>)*/- this.createLink = linkService.createLink;+ createLink: typeof linkService.createLink;/** @deprecated - use api.createLink() instead */- this.createNoteLink = linkService.createLink;+ createNoteLink: typeof linkService.createLink;/*** Adds given text to the editor cursor*- * @method- * @param {string} text - this must be clear text, HTML is not supported.+ * @param text - this must be clear text, HTML is not supported.*/- this.addTextToActiveContextEditor = text => appContext.triggerCommand('addTextToActiveEditor', {text});+ addTextToActiveContextEditor(text: string): void;/**- * @method- * @returns {FNote} active note (loaded into center pane)+ * @returns active note (loaded into center pane)*/- this.getActiveContextNote = () => appContext.tabManager.getActiveContextNote();+ getActiveContextNote(): FNote;/**- * @method- * @returns {NoteContext} - returns active context (split)+ * @returns returns active context (split)*/- this.getActiveContext = () => appContext.tabManager.getActiveContext();+ getActiveContext(): NoteContext;/**- * @method- * @returns {NoteContext} - returns active main context (first split in a tab, represents the tab as a whole)+ * @returns returns active main context (first split in a tab, represents the tab as a whole)*/- this.getActiveMainContext = () => appContext.tabManager.getActiveMainContext();+ getActiveMainContext(): NoteContext;/**- * @method- * @returns {NoteContext[]} - returns all note contexts (splits) in all tabs+ * @returns returns all note contexts (splits) in all tabs*/- this.getNoteContexts = () => appContext.tabManager.getNoteContexts();+ getNoteContexts(): NoteContext[];/**- * @method- * @returns {NoteContext[]} - returns all main contexts representing tabs+ * @returns returns all main contexts representing tabs*/- this.getMainNoteContexts = () => appContext.tabManager.getMainNoteContexts();+ getMainNoteContexts(): NoteContext[];/*** See https://ckeditor.com/docs/ckeditor5/latest/api/module_core_editor_editor-Editor.html for documentation on the returned instance.*- * @method* @returns {Promise<BalloonEditor>} instance of CKEditor*/- this.getActiveContextTextEditor = () => appContext.tabManager.getActiveContext()?.getTextEditor();+ getActiveContextTextEditor(): Promise<unknown>;/*** See https://codemirror.net/doc/manual.html#api** @method- * @returns {Promise<CodeMirror>} instance of CodeMirror+ * @returns instance of CodeMirror*/- this.getActiveContextCodeEditor = () => appContext.tabManager.getActiveContext()?.getCodeEditor();+ getActiveContextCodeEditor(): Promise<unknown>;/*** Get access to the widget handling note detail. Methods like `getWidgetType()` and `getTypeWidget()` to get to the* implementation of actual widget type.- *- * @method- * @returns {Promise<NoteDetailWidget>}*/- this.getActiveNoteDetailWidget = () => new Promise(resolve => appContext.triggerCommand('executeInActiveNoteDetailWidget', {callback: resolve}));-+ getActiveNoteDetailWidget(): Promise<NoteDetailWidget>;/**- * @method- * @returns {Promise<string|null>} returns a note path of active note or null if there isn't active note+ * @returns returns a note path of active note or null if there isn't active note*/- this.getActiveContextNotePath = () => appContext.tabManager.getActiveContextNotePath();+ getActiveContextNotePath(): string | null;/*** Returns component which owns the given DOM element (the nearest parent component in DOM tree)** @method- * @param {Element} el - DOM element- * @returns {Component}+ * @param el DOM element*/- this.getComponentByEl = el => appContext.getComponentByEl(el);+ getComponentByEl(el: HTMLElement): Component;/**- * @method* @param {object} $el - jquery object on which to set up the tooltip- * @returns {Promise<void>}*/- this.setupElementTooltip = noteTooltipService.setupElementTooltip;+ setupElementTooltip: typeof noteTooltipService.setupElementTooltip;/**- * @method- * @param {string} noteId* @param {boolean} protect - true to protect note, false to unprotect- * @returns {Promise<void>}*/- this.protectNote = async (noteId, protect) => {- await protectedSessionService.protectNote(noteId, protect, false);- };+ protectNote: typeof protectedSessionService.protectNote;/**- * @method- * @param {string} noteId- * @param {boolean} protect - true to protect subtree, false to unprotect- * @returns {Promise<void>}+ * @param noteId+ * @param protect - true to protect subtree, false to unprotect*/- this.protectSubTree = async (noteId, protect) => {- await protectedSessionService.protectNote(noteId, protect, true);- };+ protectSubTree: typeof protectedSessionService.protectNote;/*** Returns date-note for today. If it doesn't exist, it is automatically created.- *- * @method- * @returns {Promise<FNote>}*/- this.getTodayNote = dateNotesService.getTodayNote;+ getTodayNote: typeof dateNotesService.getTodayNote;/*** Returns day note for a given date. If it doesn't exist, it is automatically created.*- * @method- * @param {string} date - e.g. "2019-04-29"- * @returns {Promise<FNote>}+ * @param date - e.g. "2019-04-29"*/- this.getDayNote = dateNotesService.getDayNote;+ getDayNote: typeof dateNotesService.getDayNote;/*** Returns day note for the first date of the week of the given date. If it doesn't exist, it is automatically created.*- * @method- * @param {string} date - e.g. "2019-04-29"- * @returns {Promise<FNote>}+ * @param date - e.g. "2019-04-29"*/- this.getWeekNote = dateNotesService.getWeekNote;+ getWeekNote: typeof dateNotesService.getWeekNote;/*** Returns month-note. If it doesn't exist, it is automatically created.*- * @method- * @param {string} month - e.g. "2019-04"- * @returns {Promise<FNote>}+ * @param month - e.g. "2019-04"*/- this.getMonthNote = dateNotesService.getMonthNote;+ getMonthNote: typeof dateNotesService.getMonthNote;/*** Returns year-note. If it doesn't exist, it is automatically created.@@ -553,32 +379,21 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain* @param {string} year - e.g. "2019"* @returns {Promise<FNote>}*/- this.getYearNote = dateNotesService.getYearNote;+ getYearNote: typeof dateNotesService.getYearNote;/*** Hoist note in the current tab. See https://triliumnext.github.io/Docs/Wiki/note-hoisting.html*- * @method* @param {string} noteId - set hoisted note. 'root' will effectively unhoist- * @returns {Promise<void>}*/- this.setHoistedNoteId = (noteId) => {- const activeNoteContext = appContext.tabManager.getActiveContext();+ setHoistedNoteId(noteId: string): void;- if (activeNoteContext) {- activeNoteContext.setHoistedNoteId(noteId);- }- };-- /**- * @method- * @param {string} keyboardShortcut - e.g. "ctrl+shift+a"- * @param {function} handler- * @param {string} [namespace] - specify namespace of the handler for the cases where call for bind may be repeated.+ /**+ * @param keyboardShortcut - e.g. "ctrl+shift+a"+ * @param [namespace] specify namespace of the handler for the cases where call for bind may be repeated.* If a handler with this ID exists, it's replaced by the new handler.- * @returns {Promise<void>}*/- this.bindGlobalShortcut = shortcutService.bindGlobalShortcut;+ bindGlobalShortcut: typeof shortcutService.bindGlobalShortcut;/*** Trilium runs in a backend and frontend process, when something is changed on the backend from a script,@@ -586,53 +401,256 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain** This method returns a promise which resolves once all the backend -> frontend synchronization is finished.* Typical use case is when a new note has been created, we should wait until it is synced into frontend and only then activate it.- *- * @method- * @returns {Promise<void>}*/- this.waitUntilSynced = ws.waitForMaxKnownEntityChangeId;+ waitUntilSynced: typeof ws.waitForMaxKnownEntityChangeId;/*** This will refresh all currently opened notes which have included note specified in the parameter** @param includedNoteId - noteId of the included note- * @returns {Promise<void>}*/- this.refreshIncludedNote = includedNoteId => appContext.triggerEvent('refreshIncludedNote', {noteId: includedNoteId});+ refreshIncludedNote(includedNoteId: string): void;/*** Return randomly generated string of given length. This random string generation is NOT cryptographically secure.** @method- * @param {int} length of the string- * @returns {string} random string+ * @param length of the string+ * @returns random string*/- this.randomString = utils.randomString;+ randomString: typeof utils.randomString;/**- * @method- * @param {int} size in bytes- * @return {string} formatted string+ * @param size in bytes+ * @return formatted string*/- this.formatSize = utils.formatSize;+ formatSize: typeof utils.formatSize;/**- * @method- * @param {int} size in bytes- * @return {string} formatted string+ * @param size in bytes+ * @return formatted string* @deprecated - use api.formatSize()*/- this.formatNoteSize = utils.formatSize;+ formatNoteSize: typeof utils.formatSize;- this.logMessages = {};- this.logSpacedUpdates = {};+ logMessages: Record<string, string[]>;+ logSpacedUpdates: Record<string, SpacedUpdate>;/*** Log given message to the log pane in UI- *- * @param message- * @returns {void}*/+ log(message: string): void;+}++/**+ * <p>This is the main frontend API interface for scripts. All the properties and methods are published in the "api" object+ * available in the JS frontend notes. You can use e.g. <code>api.showMessage(api.startNote.title);</code></p>+ *+ * @constructor+ */+function FrontendScriptApi (this: Api, startNote: FNote, currentNote: FNote, originEntity: Entity | null = null, $container = null) {++ this.$container = $container;+ this.startNote = startNote;+ this.currentNote = currentNote;+ this.originEntity = originEntity;+ this.dayjs = dayjs;+ this.RightPanelWidget = RightPanelWidget;+ this.NoteContextAwareWidget = NoteContextAwareWidget;+ this.BasicWidget = BasicWidget;++ this.activateNote = async notePath => {+ await appContext.tabManager.getActiveContext().setNote(notePath);+ };++ this.activateNewNote = async notePath => {+ await ws.waitForMaxKnownEntityChangeId();++ await appContext.tabManager.getActiveContext().setNote(notePath);+ await appContext.triggerEvent('focusAndSelectTitle');+ };+++ this.openTabWithNote = async (notePath, activate) => {+ await ws.waitForMaxKnownEntityChangeId();++ await appContext.tabManager.openTabWithNoteWithHoisting(notePath, { activate });++ if (activate) {+ await appContext.triggerEvent('focusAndSelectTitle');+ }+ };++ this.openSplitWithNote = async (notePath, activate) => {+ await ws.waitForMaxKnownEntityChangeId();++ const subContexts = appContext.tabManager.getActiveContext().getSubContexts();+ const {ntxId} = subContexts[subContexts.length - 1];++ await appContext.triggerCommand("openNewNoteSplit", {ntxId, notePath});++ if (activate) {+ await appContext.triggerEvent('focusAndSelectTitle');+ }+ };++ this.addButtonToToolbar = async opts => {+ console.warn("api.addButtonToToolbar() has been deprecated since v0.58 and may be removed in the future. Use Menu -> Configure Launchbar to create/update launchers instead.");++ const {action, ...reqBody} = opts;++ await server.put('special-notes/api-script-launcher', {+ action: action.toString(),+ ...reqBody+ });+ };++ function prepareParams(params: unknown[]) {+ if (!params) {+ return params;+ }++ return params.map(p => {+ if (typeof p === "function") {+ return `!@#Function: ${p.toString()}`;+ }+ else {+ return p;+ }+ });+ }+++ this.__runOnBackendInner = async (func, params, transactional) => {+ if (typeof func === "function") {+ func = func.toString();+ }++ const ret = await server.post<ExecResult>('script/exec', {+ script: func,+ params: prepareParams(params),+ startNoteId: startNote.noteId,+ currentNoteId: currentNote.noteId,+ originEntityName: "notes", // currently there's no other entity on the frontend which can trigger event+ originEntityId: originEntity ? originEntity.noteId : null,+ transactional+ }, "script");++ if (ret.success) {+ await ws.waitForMaxKnownEntityChangeId();++ return ret.executionResult;+ } else {+ throw new Error(`server error: ${ret.error}`);+ }+ }++ this.runOnBackend = async (func, params = []) => {+ if (func?.constructor.name === "AsyncFunction" || (typeof func === "string" && func?.startsWith?.("async "))) {+ toastService.showError(t("frontend_script_api.async_warning"));+ }++ return await this.__runOnBackendInner(func, params, true);+ };+++ this.runAsyncOnBackendWithManualTransactionHandling = async (func, params = []) => {+ if (func?.constructor.name === "Function" || (typeof func === "string" && func?.startsWith?.("function"))) {+ toastService.showError(t("frontend_script_api.sync_warning"));+ }++ return await this.__runOnBackendInner(func, params, false);+ };++ this.searchForNotes = async searchString => {+ return await searchService.searchForNotes(searchString);+ };+++ this.searchForNote = async searchString => {+ const notes = await this.searchForNotes(searchString);++ return notes.length > 0 ? notes[0] : null;+ };+++ this.getNote = async noteId => await froca.getNote(noteId);+ this.getNotes = async (noteIds, silentNotFoundError = false) => await froca.getNotes(noteIds, silentNotFoundError);+ this.reloadNotes = async noteIds => await froca.reloadNotes(noteIds);+ this.getInstanceName = () => window.glob.instanceName;+ this.formatDateISO = utils.formatDateISO;+ this.parseDate = utils.parseDate;++ this.showMessage = toastService.showMessage;+ this.showError = toastService.showError;+ this.showInfoDialog = dialogService.info;+ this.showConfirmDialog = dialogService.confirm;+++ this.showPromptDialog = dialogService.prompt;++ this.triggerCommand = (name, data) => appContext.triggerCommand(name, data);+ this.triggerEvent = (name, data) => appContext.triggerEvent(name, data);+++ this.createLink = linkService.createLink;+ this.createNoteLink = linkService.createLink;++ this.addTextToActiveContextEditor = text => appContext.triggerCommand('addTextToActiveEditor', {text});++ this.getActiveContextNote = () => appContext.tabManager.getActiveContextNote();+ this.getActiveContext = () => appContext.tabManager.getActiveContext();+ this.getActiveMainContext = () => appContext.tabManager.getActiveMainContext();++ this.getNoteContexts = () => appContext.tabManager.getNoteContexts();+ this.getMainNoteContexts = () => appContext.tabManager.getMainNoteContexts();+++ this.getActiveContextTextEditor = () => appContext.tabManager.getActiveContext()?.getTextEditor();+ this.getActiveContextCodeEditor = () => appContext.tabManager.getActiveContext()?.getCodeEditor();++ this.getActiveNoteDetailWidget = () => new Promise(resolve => appContext.triggerCommand('executeInActiveNoteDetailWidget', {callback: resolve}));+ this.getActiveContextNotePath = () => appContext.tabManager.getActiveContextNotePath();++ this.getComponentByEl = el => appContext.getComponentByEl(el);++ this.setupElementTooltip = noteTooltipService.setupElementTooltip;++ this.protectNote = async (noteId, protect) => {+ await protectedSessionService.protectNote(noteId, protect, false);+ };++ this.protectSubTree = async (noteId, protect) => {+ await protectedSessionService.protectNote(noteId, protect, true);+ };++ this.getTodayNote = dateNotesService.getTodayNote;+ this.getDayNote = dateNotesService.getDayNote;+ this.getWeekNote = dateNotesService.getWeekNote;+ this.getMonthNote = dateNotesService.getMonthNote;+ this.getYearNote = dateNotesService.getYearNote;++ this.setHoistedNoteId = (noteId) => {+ const activeNoteContext = appContext.tabManager.getActiveContext();++ if (activeNoteContext) {+ activeNoteContext.setHoistedNoteId(noteId);+ }+ };++ this.bindGlobalShortcut = shortcutService.bindGlobalShortcut;++ this.waitUntilSynced = ws.waitForMaxKnownEntityChangeId;++ this.refreshIncludedNote = includedNoteId => appContext.triggerEvent('refreshIncludedNote', {noteId: includedNoteId});+++ this.randomString = utils.randomString;+ this.formatSize = utils.formatSize;+ this.formatNoteSize = utils.formatSize;++ this.logMessages = {};+ this.logSpacedUpdates = {};this.log = message => {const {noteId} = this.startNote;diff --git a/src/public/app/services/spaced_update.ts b/src/public/app/services/spaced_update.tsindex 4ac0fdd236..9913204231 100644--- a/src/public/app/services/spaced_update.ts+++ b/src/public/app/services/spaced_update.ts@@ -1,4 +1,4 @@-type Callback = () => Promise<void>;+type Callback = () => Promise<void> | void;export default class SpacedUpdate {private updater: Callback;diff --git a/src/public/app/types.d.ts b/src/public/app/types.d.tsindex 4fb103b796..88f79b7eb8 100644--- a/src/public/app/types.d.ts+++ b/src/public/app/types.d.ts@@ -34,6 +34,7 @@ interface CustomGlobals {maxEntityChangeIdAtLoad: number;maxEntityChangeSyncIdAtLoad: number;assetPath: string;+ instanceName: string;}type RequireMethod = (moduleName: string) => any;@@ -64,7 +65,7 @@ declare global {};interface JQuery {- autocomplete: (action: "close" | "open" | "destroy" | AutoCompleteConfig, args?: AutoCompleteArg[]) => void;+ autocomplete: (action: "close" | "open" | "destroy" | AutoCompleteConfig, args?: AutoCompleteArg[]) => void;}var logError: (message: string) => void;@@ -83,4 +84,5 @@ declare global {language: string});};+ var dayjs: {};}