From 44bb246572da94ff37d7dd792e427ad499f5d338 Mon Sep 17 00:00:00 2001 From: zsviczian Date: Sat, 13 Jun 2026 13:34:14 +0200 Subject: [PATCH] mostly type fixes --- src/constants/constants.ts | 5 +- src/core/main.ts | 19 +- src/core/managers/CommandManager.ts | 17 +- src/core/managers/EventManager.ts | 29 +- src/core/settings.ts | 98 +- src/lang/locale/en.ts | 29 + src/shared/Dialogs/EmbeddableSettings.ts | 8 +- src/shared/Dialogs/ExportDialog.ts | 6 +- src/shared/Dialogs/ImportSVGDialog.ts | 22 +- src/shared/Dialogs/InsertPDFModal.ts | 4 +- src/shared/Dialogs/PenSettingsModal.ts | 4 +- src/shared/Dialogs/Prompt.ts | 24 +- src/shared/Dialogs/PublishOutOfDateFiles.ts | 2 +- src/shared/Dialogs/RankMessage.ts | 2 +- src/shared/Dialogs/ReleaseNotes.ts | 14 +- src/shared/Dialogs/ScriptInstallPrompt.ts | 66 +- src/shared/Dialogs/UIModeSettings.ts | 4 +- src/shared/ExcalidrawAutomate.ts | 9 +- src/shared/ExcalidrawData.ts | 34 +- src/shared/Suggesters/InlineLinkSuggester.ts | 66 +- src/utils/debugHelper.ts | 7 +- src/utils/excalidrawAutomateUtils.ts | 51 - src/utils/excalidrawViewHelpers.ts | 25 +- src/utils/sceneDataUtils.ts | 4 +- src/utils/utils.ts | 3 +- src/view/ExcalidrawView.ts | 1278 +++++++++--------- 26 files changed, 960 insertions(+), 870 deletions(-) diff --git a/src/constants/constants.ts b/src/constants/constants.ts index 586ebc31..652d4a35 100644 --- a/src/constants/constants.ts +++ b/src/constants/constants.ts @@ -9,6 +9,7 @@ import { setStyle } from "src/utils/styleUtils"; //This is only for backward compatibility because an early version of obsidian included an encoding to avoid fantom links from littering Obsidian graph view declare const PLUGIN_VERSION: string; export let EXCALIDRAW_PLUGIN: ExcalidrawPlugin = null; +// eslint-disable-next-line obsidianmd/prefer-active-doc export const mainDocument = document; //signals deliberate use of main document instead of activeDocument export const setExcalidrawPlugin = (plugin: ExcalidrawPlugin) => { EXCALIDRAW_PLUGIN = plugin; @@ -175,7 +176,9 @@ export function updateExcalidrawLib() { getDefaultColorPalette, } = excalidrawLib); } catch (error) { - errorHandler.handleError(error, "updateExcalidrawLib", true); + if (error instanceof Error || typeof error === "string") { + errorHandler.handleError(error, "updateExcalidrawLib", true); + } // Don't throw here - we'll try to continue with potentially stale functions // but at least we won't crash } diff --git a/src/core/main.ts b/src/core/main.ts index b683ec14..c3265864 100644 --- a/src/core/main.ts +++ b/src/core/main.ts @@ -52,7 +52,6 @@ import { import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate"; import { initExcalidrawAutomate, - insertLaTeXToView, } from "src/utils/excalidrawAutomateUtils"; import { around, dedupe } from "monkey-around"; import { t } from "../lang/helpers"; @@ -132,6 +131,7 @@ import { URLs } from "src/constants/safeUrls"; import { hideElement, setButtonBgColor } from "src/utils/styleUtils"; import { installButton } from "src/utils/scriptLibraryUtils"; import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks"; +import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers"; declare const PLUGIN_VERSION: string; declare const INITIAL_TIMESTAMP: number; @@ -809,12 +809,13 @@ export default class ExcalidrawPlugin extends Plugin { this.addRibbonIcon( ICON_NAME, t("CREATE_NEW"), - this.actionRibbonClick.bind(this), + (e) => this.actionRibbonClick(e), ); try { - void this.loadSettings({ reEnableAutosave: true }).then( - this.onloadCheckForOnceOffSettingsUpdates.bind(this), + void this.loadSettings({ reEnableAutosave: true }).then(() => + this.onloadCheckForOnceOffSettingsUpdates(), + ); } catch (e) { new Notice("Error loading plugin settings", 6000); @@ -835,12 +836,12 @@ export default class ExcalidrawPlugin extends Plugin { //Licat: Are you registering your post processors in onLayoutReady? You should register them in onload instead this.addMarkdownPostProcessor(); } catch (e) { - new Notice("Error adding markdown post processor", 6000); - console.error("Error adding markdown post processor", e); + new Notice("Error adding Markdown post processor", 6000); + console.error("Error adding Markdown post processor", e); } this.logStartupEvent("Markdown post processor added"); - this.app.workspace.onLayoutReady(this.onloadOnLayoutReady.bind(this)); + this.app.workspace.onLayoutReady(() => this.onloadOnLayoutReady()); this.logStartupEvent("Workspace ready event handler added"); } @@ -1793,6 +1794,10 @@ export default class ExcalidrawPlugin extends Plugin { await this.saveData(encryptPersistedAPIKeys(persistedSettings)); } + async onExternalSettingsChange() { + await this.loadSettings(); + } + public async openSidepanel( reveal: boolean = true, ): Promise { diff --git a/src/core/managers/CommandManager.ts b/src/core/managers/CommandManager.ts index 4d8aa191..9b32a13c 100644 --- a/src/core/managers/CommandManager.ts +++ b/src/core/managers/CommandManager.ts @@ -34,7 +34,7 @@ import { InsertImageDialog } from "../../shared/Dialogs/InsertImageDialog"; import { ImportSVGDialog } from "../../shared/Dialogs/ImportSVGDialog"; import { InsertMDDialog } from "../../shared/Dialogs/InsertMDDialog"; import { ExcalidrawAutomate } from "../../shared/ExcalidrawAutomate"; -import { insertLaTeXToView, search } from "src/utils/excalidrawAutomateUtils"; +import { search } from "src/utils/excalidrawAutomateUtils"; import { templatePromt } from "../../shared/Dialogs/Prompt"; import { t } from "../../lang/helpers"; import { @@ -91,6 +91,7 @@ import ExcalidrawPlugin from "src/core/main"; import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings"; import { PaneTarget } from "src/types/utilTypes"; import { decompress } from "src/utils/sceneDataUtils"; +import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers"; declare const PLUGIN_VERSION: string; @@ -189,7 +190,7 @@ export class CommandManager { let folderpath = file.path; if (file instanceof TFile) { folderpath = normalizePath( - file.path.substr(0, file.path.lastIndexOf(file.name)), + file.path.substring(0, file.path.lastIndexOf(file.name)), ); } void this.plugin.createAndOpenDrawing( @@ -720,7 +721,7 @@ export class CommandManager { if (view) { if (!this.settings.taskboneEnabled) { new Notice( - "Taskbone OCR is not enabled. Please go to plugins settings to enable it.", + t("TASKBONE_NOT_ENABLED"), 4000, ); return true; @@ -743,7 +744,7 @@ export class CommandManager { if (view) { if (!this.settings.taskboneEnabled) { new Notice( - "Taskbone OCR is not enabled. Please go to plugins settings to enable it.", + t("TASKBONE_NOT_ENABLED"), 4000, ); return true; @@ -766,7 +767,7 @@ export class CommandManager { if (view) { if (!this.settings.taskboneEnabled) { new Notice( - "Taskbone OCR is not enabled. Please go to plugins settings to enable it.", + t("TASKBONE_NOT_ENABLED"), 4000, ); return true; @@ -935,6 +936,7 @@ export class CommandManager { this.forceSaveCommand = this.addCommand({ id: "save", + //eslint-disable-next-line obsidianmd/commands/no-default-hotkeys hotkeys: [{ modifiers: ["Ctrl"], key: "s" }], //See also Poposcope name: t("FORCE_SAVE"), checkCallback: (checking: boolean) => @@ -1048,7 +1050,6 @@ export class CommandManager { this.addCommand({ id: "insert-link", - hotkeys: [{ modifiers: ["Mod", "Shift"], key: "k" }], name: t("INSERT_LINK"), checkCallback: (checking: boolean) => { if (checking) { @@ -2059,9 +2060,7 @@ export class CommandManager { } //console.log({counter, file}); if (!newFile || !(newFile instanceof TFile)) { - new Notice( - "File not found. NewExcalidraw Drawing is taking too long to create. Please try again.", - ); + new Notice(t("ANNOTATE_IMAGE_ERROR")); return; } diff --git a/src/core/managers/EventManager.ts b/src/core/managers/EventManager.ts index 572eb4e2..6dfbe91b 100644 --- a/src/core/managers/EventManager.ts +++ b/src/core/managers/EventManager.ts @@ -126,21 +126,20 @@ export class EventManager { this.registerEvent( this.plugin.app.workspace.on( "active-leaf-change", - this.onActiveLeafChangeHandler.bind(this), + (leaf) => this.onActiveLeafChangeHandler(leaf), ), ); this.registerEvent( this.app.workspace.on( "layout-change", - this.onLayoutChangeHandler.bind(this), + () => this.onLayoutChangeHandler(), ), ); //File Save Trigger Handlers //Save the drawing if the user clicks outside the Excalidraw Canvas - const onClickEventSaveActiveDrawing = - this.onClickSaveActiveDrawing.bind(this); + const onClickEventSaveActiveDrawing = (e: PointerEvent) => this.onClickSaveActiveDrawing(e); this.app.workspace.containerEl.addEventListener( "click", onClickEventSaveActiveDrawing, @@ -154,7 +153,7 @@ export class EventManager { this.registerEvent( this.app.workspace.on( "file-menu", - this.onFileMenuSaveActiveDrawing.bind(this), + () => this.onFileMenuSaveActiveDrawing(), ), ); @@ -166,12 +165,22 @@ export class EventManager { ); this.registerEvent( - this.app.workspace.on("file-menu", this.onFileMenuHandler.bind(this)), + this.app.workspace.on("file-menu", (menu, file, source, leaf) => { + if (!(file instanceof TFile)) { + return; + } + this.onFileMenuHandler(menu, file, source, leaf); + }), ); this.plugin.registerEvent( this.plugin.app.workspace.on( "editor-menu", - this.onEditorMenuHandler.bind(this), + (menu, editor, view) =>{ + if (!(view instanceof MarkdownView)) { + return; + } + this.onEditorMenuHandler(menu, editor, view); + }, ), ); } @@ -209,7 +218,11 @@ export class EventManager { if (data.startsWith(`{"type":"excalidraw/clipboard"`)) { evt.preventDefault(); try { - const drawing = JSON.parse(data); + const drawing = JSON.parse(data) as { + type: string; + elements: ExcalidrawElement[]; + }; + const hasOneTextElement = drawing.elements.filter((el: ExcalidrawElement) => el.type === "text") .length === 1; diff --git a/src/core/settings.ts b/src/core/settings.ts index 3975634b..afc155b5 100644 --- a/src/core/settings.ts +++ b/src/core/settings.ts @@ -1233,7 +1233,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { } } - async hide() { + hide() { this.detachSettingsFocusoutHandler(); if (this.plugin.settings.overrideObsidianFontSize) { setStyle(mainDocument.documentElement, { fontSize: "" }); @@ -1247,22 +1247,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab { setRootElementSize(); } - await this.persistDirtySettings(); - await this.applyPendingActions(); - this.hotkeyEditor.unload(); - if (this.hotkeyEditor.isDirty) { - this.plugin.registerHotkeyOverrides(); - } - this.plugin.scriptEngine.updateScriptPath(); + void (async () => { + void await this.persistDirtySettings(); + void await this.applyPendingActions(); + this.hotkeyEditor.unload(); + if (this.hotkeyEditor.isDirty) { + this.plugin.registerHotkeyOverrides(); + } + this.plugin.scriptEngine.updateScriptPath(); + })(); /* if(this.reloadMathJax) { this.plugin.loadMathJax(); }*/ } - async display() { + display() { let detailsEl: HTMLElement; - await this.plugin.loadSettings(); //in case sync loaded changed settings in the background + //await this.plugin.loadSettings(); //in case sync loaded changed settings in the background this.settingsDirty = false; this.requestEmbedUpdate = false; this.requestReloadDrawings = false; @@ -1317,7 +1319,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { "span", { cls: "excalidraw-mastery-promo__summary-title", - text: "Excalidraw Mastery", + text: t("EXCALIDRAW_MASTERY"), }, ); const excalidrawMasterySummaryState = excalidrawMasterySummary.createEl( @@ -1509,7 +1511,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("FOLDER_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: Excalidraw") + .setPlaceholder(t("FOLDER_PLACEHOLDER")) .setValue(this.plugin.settings.folder) .onChange(async (value) => { this.plugin.settings.folder = value; @@ -1534,7 +1536,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("CROP_FOLDER_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: Excalidraw/Cropped") + .setPlaceholder(t("CROP_FOLDER_PLACEHOLDER")) .setValue(this.plugin.settings.cropFolder) .onChange(async (value) => { this.plugin.settings.cropFolder = value; @@ -1547,7 +1549,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("ANNOTATE_FOLDER_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: Excalidraw/Annotations") + .setPlaceholder(t("ANNOTATE_FOLDER_PLACEHOLDER")) .setValue(this.plugin.settings.annotateFolder) .onChange(async (value) => { this.plugin.settings.annotateFolder = value; @@ -1560,7 +1562,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("TEMPLATE_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: Excalidraw/Template") + .setPlaceholder(t("TEMPLATE_PLACEHOLDER")) .setValue(this.plugin.settings.templateFilePath) .onChange(async (value) => { this.plugin.settings.templateFilePath = value; @@ -1574,7 +1576,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("SCRIPT_FOLDER_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: Excalidraw/Scripts") + .setPlaceholder(t("SCRIPT_FOLDER_PLACEHOLDER")) .setValue(this.plugin.settings.scriptFolderPath) .onChange(async (value) => { this.plugin.settings.scriptFolderPath = value; @@ -1686,7 +1688,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("FILENAME_PREFIX_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: Drawing ") + .setPlaceholder(t("FILENAME_PREFIX_PLACEHOLDER")) .setValue(this.plugin.settings.drawingFilenamePrefix) .onChange(async (value) => { this.plugin.settings.drawingFilenamePrefix = value.replaceAll( @@ -1766,7 +1768,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("CROP_PREFIX_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: cropped_") + .setPlaceholder(t("CROP_PREFIX_PLACEHOLDER")) .setValue(this.plugin.settings.cropPrefix) .onChange(async (value) => { this.plugin.settings.cropPrefix = value.replaceAll( @@ -1783,7 +1785,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("CROP_SUFFIX_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: _cropped") + .setPlaceholder(t("CROP_SUFFIX_PLACEHOLDER")) .setValue(this.plugin.settings.cropSuffix) .onChange(async (value) => { this.plugin.settings.cropSuffix = value.replaceAll( @@ -1800,7 +1802,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("ANNOTATE_PREFIX_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: annotated_") + .setPlaceholder(t("ANNOTATE_PREFIX_PLACEHOLDER")) .setValue(this.plugin.settings.annotatePrefix) .onChange(async (value) => { this.plugin.settings.annotatePrefix = value.replaceAll( @@ -1817,7 +1819,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("ANNOTATE_SUFFIX_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: _annotated") + .setPlaceholder(t("ANNOTATE_SUFFIX_PLACEHOLDER")) .setValue(this.plugin.settings.annotateSuffix) .onChange(async (value) => { this.plugin.settings.annotateSuffix = value.replaceAll( @@ -2290,7 +2292,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab { ) .setDesc(fragWithHTML(description)) .addDropdown((dropdown) => { - optionValues.forEach((value) => dropdown.addOption(value, value)); + optionValues.forEach((value) => { + void dropdown.addOption(value, value); + }); return dropdown.setValue(selectedValue).onChange((value) => { if (kind === "text") { selectedTextModelConfig = value; @@ -2574,9 +2578,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("DYNAMICSTYLE_DESC"))) .addDropdown((dropdown) => dropdown - .addOption("none", "Dynamic Styling OFF") - .addOption("colorful", "Match color") - .addOption("gray", "Gray, match tone") + .addOption("none", t("DYNAMICSTYLE_OPTION_NONE")) + .addOption("colorful", t("DYNAMICSTYLE_OPTION_COLORFUL")) + .addOption("gray", t("DYNAMICSTYLE_OPTION_GRAY")) .setValue(this.plugin.settings.dynamicStyling) .onChange(async (value) => { this.requestUpdateDynamicStyling = true; @@ -2645,10 +2649,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("DEFAULT_OPEN_MODE_DESC"))) .addDropdown((dropdown) => dropdown - .addOption("normal", "Always in normal-mode") - .addOption("zen", "Always in zen-mode") - .addOption("view", "Always in view-mode") - .addOption("view-mobile", "Usually normal, but view-mode on Phone") + .addOption("normal", t("DEFAULT_OPEN_MODE_OPTION_NORMAL")) + .addOption("zen", t("DEFAULT_OPEN_MODE_OPTION_ZEN")) + .addOption("view", t("DEFAULT_OPEN_MODE_OPTION_VIEW")) + .addOption("view-mobile", t("DEFAULT_OPEN_MODE_OPTION_VIEW_MOBILE")) .setValue(this.plugin.settings.defaultMode) .onChange(async (value) => { this.plugin.settings.defaultMode = value; @@ -2809,9 +2813,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("DEFAULT_PEN_MODE_DESC"))) .addDropdown((dropdown) => dropdown - .addOption("never", "Never") - .addOption("mobile", "On Obsidian Mobile") - .addOption("always", "Always") + .addOption("never", t("DEFAULT_PEN_MODE_OPTION_NEVER")) + .addOption("mobile", t("DEFAULT_PEN_MODE_OPTION_MOBILE")) + .addOption("always", t("DEFAULT_PEN_MODE_OPTION_ALWAYS")) .setValue(this.plugin.settings.defaultPenMode) .onChange(async (value: "never" | "always" | "mobile") => { this.plugin.settings.defaultPenMode = value; @@ -3070,7 +3074,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { new ModifierKeySettingsComponent( detailsEl, this.plugin.settings.modifierKeyConfig, - this.applySettingsUpdate.bind(this), + () => this.applySettingsUpdate(), ).render(); // ------------------------------------------------ @@ -3389,9 +3393,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("EMBED_PREVIEW_IMAGETYPE_DESC"))) .addDropdown((dropdown) => dropdown - .addOption(PreviewImageType.PNG, "PNG Image") - .addOption(PreviewImageType.SVG, "Native SVG") - .addOption(PreviewImageType.SVGIMG, "SVG Image") + .addOption(PreviewImageType.PNG, t("EMBED_PREVIEW_IMAGETYPE_OPTION_PNG")) + .addOption(PreviewImageType.SVG, t("EMBED_PREVIEW_IMAGETYPE_OPTION_SVG")) + .addOption(PreviewImageType.SVGIMG, t("EMBED_PREVIEW_IMAGETYPE_OPTION_SVGIMG")) .setValue(this.plugin.settings.previewImageType) .onChange((value) => { this.plugin.settings.previewImageType = value as PreviewImageType; @@ -3408,7 +3412,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("EMBED_TYPE_DESC"))) .addDropdown(async (d: DropdownComponent) => { dropdown = d; - dropdown.addOption("excalidraw", "excalidraw"); + dropdown.addOption("excalidraw", "Excalidraw"); if (this.plugin.settings.autoexportPNG) { dropdown.addOption("PNG", "PNG"); } else if (this.plugin.settings.embedType === "PNG") { @@ -3628,7 +3632,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("EMBED_WIDTH_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: 400") + .setPlaceholder("400") .setValue(this.plugin.settings.width) .onChange(async (value) => { this.plugin.settings.width = value; @@ -3642,7 +3646,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("EMBED_HEIGHT_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: 400") + .setPlaceholder("400") .setValue(this.plugin.settings.height) .onChange(async (value) => { this.plugin.settings.height = value; @@ -3978,7 +3982,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("MD_DEFAULT_COLOR_DESC"))) .addText((text) => text - .setPlaceholder("CSS Color-name|RGB-HEX") + .setPlaceholder(t("DEFAULT_COLOR_MD_DESC")) .setValue(this.plugin.settings.mdFontColor) .onChange((value) => { this.requestReloadDrawings = true; @@ -3992,7 +3996,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("MD_DEFAULT_BORDER_COLOR_DESC"))) .addText((text) => text - .setPlaceholder("CSS Color-name|RGB-HEX") + .setPlaceholder(t("DEFAULT_COLOR_MD_DESC")) .setValue(this.plugin.settings.mdBorderColor) .onChange((value) => { this.requestReloadDrawings = true; @@ -4006,7 +4010,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("MD_CSS_DESC"))) .addText((text) => text - .setPlaceholder("filename of css file in vault") + .setPlaceholder(t("MD_CSS_PLACEHOLDER")) .setValue(this.plugin.settings.mdCSS) .onChange((value) => { this.requestReloadDrawings = true; @@ -4156,7 +4160,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(t("CJK_ASSETS_FOLDER_DESC"))) .addText((text) => text - .setPlaceholder("e.g.: Excalidraw/FontAssets") + .setPlaceholder(t("CJK_ASSETS_FOLDER_PLACEHOLDER")) .setValue(this.plugin.settings.fontAssetsPath) .onChange(async (value) => { this.plugin.settings.fontAssetsPath = value; @@ -4464,7 +4468,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { } startupScriptButton.setButtonText(t("STARTUP_SCRIPT_BUTTON_OPEN")); await this.app.workspace.openLinkText(f.path, "", true); - await this.hide(); + this.hide(); }); }); @@ -4648,9 +4652,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setName(variableName) .setDesc(fragWithHTML(description ?? "")) .addDropdown((dropdown) => { - valueset.forEach((val: string) => - dropdown.addOption(val.toString(), val.toString()), - ); + valueset.forEach((val: string) => { + void dropdown.addOption(val.toString(), val.toString()) + }); dropdown .setValue(getValue(scriptName, variableName) as string) .onChange(async (value) => { diff --git a/src/lang/locale/en.ts b/src/lang/locale/en.ts index 233cf3c0..4e39fc3b 100644 --- a/src/lang/locale/en.ts +++ b/src/lang/locale/en.ts @@ -117,6 +117,7 @@ export default { ABOUT_EXCALIDRAW: "About Excalidraw", RUN_OCR: "OCR full drawing: Grab text from freedraw + images to clipboard and doc.props", + TASKBONE_NOT_ENABLED: "Taskbone OCR is not enabled. Please go to plugins settings to enable it.", RERUN_OCR: "OCR full drawing re-run: Grab text from freedraw + images to clipboard and doc.props", RUN_OCR_ELEMENTS: @@ -126,6 +127,7 @@ export default { CROP_PAGE: "Crop and mask selected page", CROP_IMAGE: "Crop and mask image", ANNOTATE_IMAGE: "Annotate image in Excalidraw", + ANNOTATE_IMAGE_ERROR: "File not found. New Excalidraw drawing is taking too long to create. Please try again.", INSERT_ACTIVE_PDF_PAGE_AS_IMAGE: "Insert active PDF page as image", RESET_IMG_TO_100: "Set selected image element size to 100% of original", RESET_IMG_ASPECT_RATIO: "Reset selected image element aspect ratio", @@ -253,6 +255,32 @@ export default { SEARCH_PREVIOUS: "Previous", //settings.ts + FOLDER_PLACEHOLDER: "e.g.: Excalidraw", + CROP_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Cropped", + ANNOTATE_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Annotations", + TEMPLATE_PLACEHOLDER: "e.g.: Excalidraw/Template", + SCRIPT_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Scripts", + FILENAME_PREFIX_PLACEHOLDER: "e.g.: Drawing ", + CROP_PREFIX_PLACEHOLDER: "e.g.: cropped_", + CROP_SUFFIX_PLACEHOLDER: "e.g.: _cropped", + ANNOTATE_PREFIX_PLACEHOLDER: "e.g.: annotated_", + ANNOTATE_SUFFIX_PLACEHOLDER: "e.g.: _annotated", + DYNAMICSTYLE_OPTION_NONE: "Dynamic Styling OFF", + DYNAMICSTYLE_OPTION_COLORFUL: "Match color", + DYNAMICSTYLE_OPTION_GRAY: "Gray, match tone", + DEFAULT_OPEN_MODE_OPTION_NORMAL: "Always in normal-mode", + DEFAULT_OPEN_MODE_OPTION_ZEN: "Always in zen-mode", + DEFAULT_OPEN_MODE_OPTION_VIEW: "Always in view-mode", + DEFAULT_OPEN_MODE_OPTION_VIEW_MOBILE: "Usually normal, but view-mode on Phone", + DEFAULT_PEN_MODE_OPTION_NEVER: "Never", + DEFAULT_PEN_MODE_OPTION_MOBILE: "On Obsidian Mobile", + DEFAULT_PEN_MODE_OPTION_ALWAYS: "Always", + EMBED_PREVIEW_IMAGETYPE_OPTION_PNG: "PNG Image", + EMBED_PREVIEW_IMAGETYPE_OPTION_SVG: "Native SVG", + EMBED_PREVIEW_IMAGETYPE_OPTION_SVGIMG: "SVG Image", + DEFAULT_COLOR_MD_DESC: "CSS Color-name|RGB-HEX", + MD_CSS_PLACEHOLDER: "Filename of CSS file in Vault", + CJK_ASSETS_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/FontAssets", DISABLE_CONTEXT_MENU_NAME: "Disable Excalidraw context menu", DISABLE_CONTEXT_MENU_DESC: "Disables the Excalidraw context menu. This can be useful on Mobile devices where the context menu pops up in unwanted moments.", @@ -260,6 +288,7 @@ export default { "Ask NotebookLM for help about the plugin. This model is pre-loaded with all my video transcripts, release notes and other helpful content. Chat with NotebookLM to explore my 250+ videos and the Excalidraw documentation.", NOTEBOOKLM_LINK_TEXT: "Learn the Plugin. Access the NotebookLM knowledgebase.", + EXCALIDRAW_MASTERY: "Excalidraw Mastery", EXCALIDRAW_MASTERY_PROMO_ARIA: "Open Excalidraw Mastery", EXCALIDRAW_MASTERY_PROMO_HTML: `

Feeling lost in the toggles and menus?

Excalidraw is a Visual PKM powerhouse built for heavy-duty workflows like Visual-First Daily Notes, deep PDF research, automation, AI integration, and Visual Zettelkasten. But all this power comes with complexity.

Skip the trial and error. 👉 Join Excalidraw Mastery to learn these exact setups step-by-step. Overcome tool friction and master your knowledge alongside a supportive community of visual thinkers!

`, EXCALIDRAW_MASTERY_PROMO_SHOW: "Show", diff --git a/src/shared/Dialogs/EmbeddableSettings.ts b/src/shared/Dialogs/EmbeddableSettings.ts index 7d366342..e749c49e 100644 --- a/src/shared/Dialogs/EmbeddableSettings.ts +++ b/src/shared/Dialogs/EmbeddableSettings.ts @@ -19,7 +19,7 @@ import { updateYouTubeStartTime, } from "src/utils/YoutTubeUtils"; import { EmbeddalbeMDFileCustomDataSettingsComponent } from "./EmbeddableMDFileCustomDataSettingsComponent"; -import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper"; +import { isWinCTRLorMacCMD, labelCTRL } from "src/utils/modifierkeyHelper"; import { CaptureUpdateAction } from "src/constants/constants"; export type EmbeddableMDCustomProps = { @@ -164,14 +164,14 @@ export class EmbeddableSettings extends Modal { button .setButtonText(t("PROMPT_BUTTON_CANCEL")) .setTooltip("ESC") - .onClick(this.close.bind(this)), + .onClick(() => this.close()), ) .addButton((button) => button .setButtonText(t("PROMPT_BUTTON_OK")) - .setTooltip("CTRL/Opt+Enter") + .setTooltip(labelCTRL()+"Enter") .setCta() - .onClick(this.applySettings.bind(this)), + .onClick(() => this.applySettings()), ); const onKeyDown = (ev: KeyboardEvent) => { diff --git a/src/shared/Dialogs/ExportDialog.ts b/src/shared/Dialogs/ExportDialog.ts index 17432941..de395eb4 100644 --- a/src/shared/Dialogs/ExportDialog.ts +++ b/src/shared/Dialogs/ExportDialog.ts @@ -81,7 +81,7 @@ export class ExportDialog extends Modal { this.theme = getExportTheme( this.plugin, this.file, - this.api.getAppState().theme, + this.api.getAppState().theme as string, ); this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements()); this.embedScene = shouldEmbedScene(this.plugin, this.file); @@ -127,7 +127,7 @@ export class ExportDialog extends Modal { } else { this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements()); } - if (this.scaleSetting) { + if (this.scaleSetting !== null) { this.scaleSetting.setDesc(this.size()); } } @@ -140,7 +140,7 @@ export class ExportDialog extends Modal { this.updateBoundingBox(); } - async onClose() { + onClose() { this.dirty = this.saveSettings; } diff --git a/src/shared/Dialogs/ImportSVGDialog.ts b/src/shared/Dialogs/ImportSVGDialog.ts index 787b0c3a..03a6fed4 100644 --- a/src/shared/Dialogs/ImportSVGDialog.ts +++ b/src/shared/Dialogs/ImportSVGDialog.ts @@ -43,19 +43,21 @@ export class ImportSVGDialog extends FuzzySuggestModal { return item.path; } - async onChooseItem(item: TFile, _: KeyboardEvent): Promise { + onChooseItem(item: TFile, _: KeyboardEvent): void { if (!item) { return; } - const ea = getEA(this.view); - const svg = await this.app.vault.read(item); - if (!svg || svg === "") { - return; - } - ea.importSVG(svg); - ea.addToGroup(ea.getElements().map((el) => el.id)); - await ea.addElementsToView(true, true, true, true); - ea.destroy(); + void (async () => { + const ea = getEA(this.view); + const svg = await this.app.vault.read(item); + if (!svg || svg === "") { + return; + } + ea.importSVG(svg); + ea.addToGroup(ea.getElements().map((el) => el.id)); + await ea.addElementsToView(true, true, true, true); + ea.destroy(); + })(); } onClose(): void { diff --git a/src/shared/Dialogs/InsertPDFModal.ts b/src/shared/Dialogs/InsertPDFModal.ts index 3e175fa0..3e3eaf72 100644 --- a/src/shared/Dialogs/InsertPDFModal.ts +++ b/src/shared/Dialogs/InsertPDFModal.ts @@ -54,7 +54,7 @@ export class InsertPDFModal extends Modal { void this.createForm(); } - async onClose() { + onClose() { if (this.dirty) { this.plugin.settings.pdfImportScale = this.importScale; this.plugin.settings.pdfBorderBox = this.borderBox; @@ -65,7 +65,7 @@ export class InsertPDFModal extends Modal { this.plugin.settings.pdfNumRows = this.numRows; this.plugin.settings.pdfDirection = this.direction; this.plugin.settings.pdfLockAfterImport = this.lockAfterImport; - await this.plugin.saveSettings(); + void this.plugin.saveSettings(); } if (this.pdfDoc) { this.pdfDoc.destroy(); diff --git a/src/shared/Dialogs/PenSettingsModal.ts b/src/shared/Dialogs/PenSettingsModal.ts index c3dd4e35..f732a0c9 100644 --- a/src/shared/Dialogs/PenSettingsModal.ts +++ b/src/shared/Dialogs/PenSettingsModal.ts @@ -72,9 +72,9 @@ export class PenSettingsModal extends Modal { void this.createForm(); } - async onClose() { + onClose() { if (this.dirty) { - await this.plugin.saveSettings(); + void this.plugin.saveSettings(); getExcalidrawViews(this.app, true).forEach((excalidrawView) => excalidrawView.updatePinnedCustomPens(), ); diff --git a/src/shared/Dialogs/Prompt.ts b/src/shared/Dialogs/Prompt.ts index ab4cf766..40f1d1ad 100644 --- a/src/shared/Dialogs/Prompt.ts +++ b/src/shared/Dialogs/Prompt.ts @@ -107,7 +107,6 @@ export class Prompt extends Modal { export class LaTexPrompt extends FloatingModal { public waitForClose: Promise; - private promptEl: HTMLInputElement; private resolvePromise: (input: string) => void; private rejectPromise: (reason?: string) => void; private editorView: EditorView; @@ -144,11 +143,18 @@ export class LaTexPrompt extends FloatingModal { ); } - public static Prompt( + public static async Prompt( + plugin: ExcalidrawPlugin, app: App, prompt_text?: string, default_value?: string, ): Promise { + const mathjaxAPI = await plugin.extrasGateway.getMathJax(); + + if (!mathjaxAPI) { + return Promise.reject((new Error("MathJax is not available or activation was cancelled"))); + } + const latexprompt = new this(app, prompt_text, default_value); return latexprompt.waitForClose; @@ -210,7 +216,7 @@ export class LaTexPrompt extends FloatingModal { this.createButton( actionButtonContainer, "", - this.submitCallback.bind(this), + () => this.submitCallback(), t("PROMPT_BUTTON_OK") ?? "", undefined, "check", @@ -220,7 +226,7 @@ export class LaTexPrompt extends FloatingModal { this.createButton( actionButtonContainer, "", - this.cancelCallback.bind(this), + () => this.cancelCallback(), t("PROMPT_BUTTON_CANCEL"), undefined, "x", @@ -268,8 +274,8 @@ export class LaTexPrompt extends FloatingModal { this.close(); } - async onOpen(): Promise { - await super.onOpen(); + onOpen(): void { + super.onOpen(); this.editorView.focus(); } @@ -831,7 +837,7 @@ export class GenericInputPrompt extends Modal { }, 10); }; - async onOpen() { + onOpen() { super.onOpen(); this.modalEl.classList.add("excalidraw-modal"); this.containerEl.classList.add("excalidraw-modal"); @@ -1342,8 +1348,8 @@ export class MultiOptionConfirmationPrompt extends Modal { return button; } - async onOpen() { - await super.onOpen(); + onOpen() { + super.onOpen(); const defaultButton = this.ctaButtonEl ?? this.contentEl.querySelector("button"); // Obsidian modal open may apply its own autofocus after onOpen; defer to enforce default keyboard action. diff --git a/src/shared/Dialogs/PublishOutOfDateFiles.ts b/src/shared/Dialogs/PublishOutOfDateFiles.ts index 64900de0..8fd07701 100644 --- a/src/shared/Dialogs/PublishOutOfDateFiles.ts +++ b/src/shared/Dialogs/PublishOutOfDateFiles.ts @@ -105,7 +105,7 @@ export class PublishOutOfDateFilesDialog extends Modal { super(plugin.app); } - async onClose() {} + onClose() {} onOpen() { this.containerEl.classList.add("excalidraw-release"); diff --git a/src/shared/Dialogs/RankMessage.ts b/src/shared/Dialogs/RankMessage.ts index 2b1bba32..b974c65f 100644 --- a/src/shared/Dialogs/RankMessage.ts +++ b/src/shared/Dialogs/RankMessage.ts @@ -25,7 +25,7 @@ export class RankMessage extends Modal { void this.createForm(); } - async onClose() { + onClose() { this.contentEl.empty(); this.plugin = null; } diff --git a/src/shared/Dialogs/ReleaseNotes.ts b/src/shared/Dialogs/ReleaseNotes.ts index 43c521fd..6269a4a8 100644 --- a/src/shared/Dialogs/ReleaseNotes.ts +++ b/src/shared/Dialogs/ReleaseNotes.ts @@ -44,16 +44,18 @@ export class ReleaseNotes extends Modal { } // Disable pointer events on header to allow clicks through } - async onClose() { + onClose() { this.contentEl.empty(); if (this.options.persistVersion === false) { return; } - await this.plugin.loadSettings(); - if (this.plugin.settings.previousRelease !== PLUGIN_VERSION) { - this.plugin.settings.previousRelease = PLUGIN_VERSION; - await this.plugin.saveSettings(); - } + void (async () => { + await this.plugin.loadSettings(); + if (this.plugin.settings.previousRelease !== PLUGIN_VERSION) { + this.plugin.settings.previousRelease = PLUGIN_VERSION; + await this.plugin.saveSettings(); + } + })(); } async createForm() { diff --git a/src/shared/Dialogs/ScriptInstallPrompt.ts b/src/shared/Dialogs/ScriptInstallPrompt.ts index 8a28d70a..45f55570 100644 --- a/src/shared/Dialogs/ScriptInstallPrompt.ts +++ b/src/shared/Dialogs/ScriptInstallPrompt.ts @@ -17,7 +17,7 @@ export class ScriptInstallPrompt extends Modal { // this.titleEl.setText(t("INSTAL_MODAL_TITLE")); } - async onOpen(): Promise { + onOpen(): void { this.contentEl.classList.add("excalidraw-scriptengine-install"); this.contentDiv = mainDocument.createElement("div"); this.contentEl.appendChild(this.contentDiv); @@ -25,39 +25,41 @@ export class ScriptInstallPrompt extends Modal { new ContentSearcher(this.contentDiv); this.containerEl.classList.add("excalidraw-scriptengine-install"); - try { - const source = await request({ url: URL }); - if (!source) { - new Notice( - "Error opening the Excalidraw Script Store page. " + - "Please double check that you can access the website. " + - "I've logged the link in developer console (press CTRL+SHIFT+i)", - 5000, + void (async () => { + try { + const source = await request({ url: URL }); + if (!source) { + new Notice( + "Error opening the Excalidraw Script Store page. " + + "Please double check that you can access the website. " + + "I've logged the link in developer console (press CTRL+SHIFT+i)", + 5000, + ); + log(URL); + this.close(); + return; + } + await MarkdownRenderer.render( + this.plugin.app, + source, + this.contentDiv, + "", + this.plugin, ); - log(URL); - this.close(); - return; - } - await MarkdownRenderer.render( - this.plugin.app, - source, - this.contentDiv, - "", - this.plugin, - ); - this.contentDiv - .querySelectorAll("h1[data-heading],h2[data-heading],h3[data-heading]") - .forEach((el) => { - el.setAttribute("id", el.getAttribute("data-heading")); + this.contentDiv + .querySelectorAll("h1[data-heading],h2[data-heading],h3[data-heading]") + .forEach((el) => { + el.setAttribute("id", el.getAttribute("data-heading")); + }); + this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => { + el.removeAttribute("target"); }); - this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => { - el.removeAttribute("target"); - }); - } catch (e) { - errorlog({ where: "ScriptInstallPrompt.onOpen", error: e }); - new Notice("Could not open ScriptEngine repository"); - this.close(); - } + } catch (e) { + errorlog({ where: "ScriptInstallPrompt.onOpen", error: e }); + new Notice("Could not open ScriptEngine repository"); + this.close(); + } + })(); } onClose(): void { diff --git a/src/shared/Dialogs/UIModeSettings.ts b/src/shared/Dialogs/UIModeSettings.ts index 1bae3faa..1cdbf205 100644 --- a/src/shared/Dialogs/UIModeSettings.ts +++ b/src/shared/Dialogs/UIModeSettings.ts @@ -14,9 +14,9 @@ export class UIModeSettings extends Modal { void this.createForm(); } - async onClose() { + onClose() { if (this.isDirty) { - await this.plugin.saveSettings(); + void this.plugin.saveSettings(); } this.plugin = null; } diff --git a/src/shared/ExcalidrawAutomate.ts b/src/shared/ExcalidrawAutomate.ts index 7cb0fb37..3a37cb0b 100644 --- a/src/shared/ExcalidrawAutomate.ts +++ b/src/shared/ExcalidrawAutomate.ts @@ -15,6 +15,7 @@ import { RoundnessType, ExcalidrawFrameElement, ExcalidrawTextContainer, + ElementsMap, } from "@zsviczian/excalidraw/types/element/src/types"; import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes"; import { @@ -2444,7 +2445,7 @@ export class ExcalidrawAutomate { const dimensions = refreshTextDimensions( textElement, container, - arrayToMap(this.getElements()), + arrayToMap(this.getElements()) as ElementsMap, originalText, ); @@ -3663,8 +3664,8 @@ export class ExcalidrawAutomate { * @param {ExcalidrawElement[]} [scene.elements] - Array of elements in the scene. * @param {AppState} [scene.appState] - The app state of the scene. * @param {BinaryFiles} [scene.files] - The files in the scene. - * @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history. @deprecated Use scene.storageOption instead - * @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene. @deprecated Use scene.storageOption instead + * @param {boolean} [scene.commitToHistory] - Deprecated: Use scene.storageOption instead. + * @param {"capture" | "none" | "update"} [scene.storeAction] - Deprecated: Use scene.storageOption instead * @param {"IMMEDIATELY" | "NEVER" | "EVENTUALLY"} [scene.captureUpdate] - The capture update action for the scene. * @param {boolean} [restore=false] - Whether to restore legacy elements in the scene. */ @@ -4159,7 +4160,7 @@ export class ExcalidrawAutomate { * @returns {ExcalidrawElement[][]} Array of arrays of grouped elements. */ getMaximumGroups(elements: ExcalidrawElement[]): ExcalidrawElement[][] { - return getMaximumGroups(elements, arrayToMap(elements)); + return getMaximumGroups(elements, arrayToMap(elements) as ElementsMap); } /** diff --git a/src/shared/ExcalidrawData.ts b/src/shared/ExcalidrawData.ts index c0a7b8e9..83430d38 100644 --- a/src/shared/ExcalidrawData.ts +++ b/src/shared/ExcalidrawData.ts @@ -40,6 +40,7 @@ import { import { isObsidianThemeDark } from "../utils/obsidianUtils"; import { cleanBlockRef, cleanSectionHeading } from "../utils/pathUtils"; import { + ElementsMap, ExcalidrawElement, ExcalidrawImageElement, ExcalidrawTextElement, @@ -65,6 +66,7 @@ import { t } from "../lang/helpers"; import { displayFontMessage } from "../utils/excalidrawViewUtils"; import { getPDFRect } from "../utils/PDFUtils"; import { URLs } from "src/constants/safeUrls"; +import { errorlog } from "src/utils/coreUtils"; type SceneDataWithFiles = SceneData & { files: BinaryFiles }; @@ -268,7 +270,7 @@ export function getJSON(data: string): { scene: string; pos: number } { if (parts.value && parts.value.length > 1) { const result = parts.value[2]; return { - scene: result.substr(0, result.lastIndexOf("}") + 1), + scene: result.substring(0, result.lastIndexOf("}") + 1), pos: parts.value.index, }; //this is a workaround in case sync merges two files together and one version is still an old version without the ```codeblock } @@ -568,16 +570,20 @@ export class ExcalidrawData { URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG, )[1] ?? "1.8.16"; - const elements = this.scene.elements as Mutable[]; + const elements = this.scene.elements as Mutable[]; for (const el of elements) { if (el.type === "iframe" && !el.customData) { + //@ts-ignore -- retyping in ExcalidrawData is possible, this is not the live inmutable object el.type = "embeddable"; } if (el.boundElements) { - const map = new Map(); + const map = new Map(); let alreadyHasText: boolean = false; el.boundElements.forEach((item: { id: string; type: string }) => { + if (item.type !== "text" && item.type !== "arrow") { + return; + } if (item.type === "text") { if (!alreadyHasText) { map.set(item.id, item.type); @@ -633,15 +639,17 @@ export class ExcalidrawData { if (el.y === null) { el.y = 0; } + /* FixedPointBinding type no longer has focus property. restoreElemenets should take care of this if (el.startBinding?.focus === null) { el.startBinding.focus = 0; } if (el.endBinding?.focus === null) { el.endBinding.focus = 0; } + */ //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/497 - if (el.fontSize === null) { + if (el.type === "text" && el.fontSize === null) { el.fontSize = 20; } @@ -688,7 +696,7 @@ export class ExcalidrawData { container.id === textEl.containerId, )[0]; const boundEl = container.boundElements.filter( - (boundEl: { id: string; type: string }) => + (boundEl: { id: string; type: "text" | "arrow" }) => !( boundEl.type === "text" && !elements.some( @@ -696,15 +704,15 @@ export class ExcalidrawData { ) ), ); - container.boundElements = [{ id: textEl.id, type: "text" }].concat( + container.boundElements = [{ id: textEl.id, type: "text" as "text" | "arrow" }].concat( boundEl, ); - } catch (error) { - console.log( - "unexpected error in initializeNonInitializedFields", - this.initializeNonInitializedFields.bind(this), - error, - ); + } catch (e) { + errorlog( { + message: "unexpected error in initializeNonInitializedFields", + context: this.initializeNonInitializedFields.bind(this) as unknown, + error: e as unknown, + }); } }, ); @@ -1175,7 +1183,7 @@ export class ExcalidrawData { private async updateSceneTextElements() { //update text in scene based on textElements Map //first get scene text elements - const elementsMap = arrayToMap(this.scene.elements); + const elementsMap = arrayToMap(this.scene.elements) as ElementsMap; const texts = this.scene.elements?.filter( (el: ExcalidrawElement) => el.type === "text" && !el.isDeleted, ) as Mutable[]; diff --git a/src/shared/Suggesters/InlineLinkSuggester.ts b/src/shared/Suggesters/InlineLinkSuggester.ts index 4a11acd9..90f4f907 100644 --- a/src/shared/Suggesters/InlineLinkSuggester.ts +++ b/src/shared/Suggesters/InlineLinkSuggester.ts @@ -213,7 +213,7 @@ export class InlineLinkSuggester return input; } - async onInputChanged(): Promise { + onInputChanged(): void { const inputStr = this.modifyInput(this.inputEl.value); this.caretPos = this.inputEl.selectionStart ?? inputStr.length; @@ -249,21 +249,23 @@ export class InlineLinkSuggester return; } - if (this.mode === "heading") { - await this.loadHeadings(this.activeFile); - } else if (this.mode === "block") { - await this.loadParagraphs(this.activeFile); - } else if (this.mode === "frame" || this.mode === "clippedframe") { - await this.loadFrames(this.activeFile, this.mode); - } else { - this.headingItems = []; - this.paragraphItems = []; - this.frameItems = []; - } + void (async () => { + if (this.mode === "heading") { + await this.loadHeadings(this.activeFile); + } else if (this.mode === "block") { + await this.loadParagraphs(this.activeFile); + } else if (this.mode === "frame" || this.mode === "clippedframe") { + await this.loadFrames(this.activeFile, this.mode); + } else { + this.headingItems = []; + this.paragraphItems = []; + this.frameItems = []; + } - this.tagItems = []; - this.block = true; - super.onInputChanged(); + this.tagItems = []; + this.block = true; + super.onInputChanged(); + })(); return; } @@ -287,7 +289,7 @@ export class InlineLinkSuggester this.tagItems = this.getTagSuggestions(); this.block = true; - await super.onInputChanged(); + super.onInputChanged(); } private getTagSuggestions(): TagSuggestion[] { @@ -386,7 +388,7 @@ export class InlineLinkSuggester return item.path + (item.alias ? `|${item.alias}` : ""); } - async onChooseItem(item: InlineSuggestion | undefined): Promise { + onChooseItem(item: InlineSuggestion | undefined): void { if (!item) { return; } @@ -409,18 +411,20 @@ export class InlineLinkSuggester } if (this.isParagraph(item)) { - const id = await this.ensureParagraphHasId(item); - if (!id) { - return; - } - const linktext = this.app.metadataCache.fileToLinktext( - item.file, - this.getSourcePath() ?? "", - true, - ); - const aliasSuffix = - this.activeAlias !== null ? `|${this.activeAlias}` : ""; - this.insertLink(`[[${linktext}#^${id}${aliasSuffix}]]`); + void (async () => { + const id = await this.ensureParagraphHasId(item); + if (!id) { + return; + } + const linktext = this.app.metadataCache.fileToLinktext( + item.file, + this.getSourcePath() ?? "", + true, + ); + const aliasSuffix = + this.activeAlias !== null ? `|${this.activeAlias}` : ""; + this.insertLink(`[[${linktext}#^${id}${aliasSuffix}]]`); + })(); return; } @@ -442,13 +446,13 @@ export class InlineLinkSuggester this.insertLink(linkString); } - async selectSuggestion( + selectSuggestion( value: FuzzyMatch, evt: MouseEvent | KeyboardEvent, ) { evt?.preventDefault?.(); evt?.stopPropagation?.(); - await this.onChooseItem(value?.item); + void this.onChooseItem(value?.item); } open(): void { diff --git a/src/utils/debugHelper.ts b/src/utils/debugHelper.ts index c207d932..4fabb104 100644 --- a/src/utils/debugHelper.ts +++ b/src/utils/debugHelper.ts @@ -1,15 +1,14 @@ export const durationTreshold = 0; //0.05; //ms export const DEBUGGING = false; - -export const log = console.log.bind(window.console); +//eslint-disable-next-line obsidianmd/rule-custom-message +export const log = (...args: unknown[]) => console.log(...args); export const debug = ( fn: (...args: unknown[]) => unknown, fnName: string, ...messages: unknown[] ) => { - //console.log(fnName,fn,...messages); - console.log(fnName, ...messages); + log(fnName, ...messages); }; let timestamp: number[] = []; diff --git a/src/utils/excalidrawAutomateUtils.ts b/src/utils/excalidrawAutomateUtils.ts index 87f484af..7f5e90e9 100644 --- a/src/utils/excalidrawAutomateUtils.ts +++ b/src/utils/excalidrawAutomateUtils.ts @@ -828,57 +828,6 @@ export function repositionElementsToCursor( }); } -export const insertLaTeXToView = ( - view: ExcalidrawView, - center: boolean = false, -) => { - const app = view.plugin.app; - const ea = getEA(view); - LaTexPrompt.Prompt( - app, - t("ENTER_LATEX"), - view.plugin.settings.latexBoilerplate, - ).then( - async (formula: string) => { - const lastLatexEl = ea - .getViewElements() - .filter( - (el) => - el.type === "image" && view.excalidrawData.hasEquation(el.fileId), - ) - .reduce( - (maxel, curr) => - !maxel || curr.updated > maxel.updated ? curr : maxel, - undefined, - ) as ExcalidrawImageElement; - let scaleX = 1; - let scaleY = 1; - if (lastLatexEl) { - const equation = view.excalidrawData.getEquation(lastLatexEl.fileId); - const dataurl = await ea.tex2dataURL(equation.latex); - if (dataurl.size.width > 0 && dataurl.size.height > 0) { - scaleX = lastLatexEl.width / dataurl.size.width; - scaleY = lastLatexEl.height / dataurl.size.height; - } - } - if (formula) { - const id = await ea.addLaTex(0, 0, formula, scaleX, scaleY); - if (center) { - const el = ea.getElement(id); - const { width, height } = el; - const { x, y } = ea.getViewCenterPosition(); - el.x = x - width / 2; - el.y = y - height / 2; - } - await ea.addElementsToView(!center, false, true); - ea.selectElementsInView([id]); - } - ea.destroy(); - }, - () => {}, - ); -}; - export const search = async (view: ExcalidrawView) => { const ea = view.plugin.ea; ea.reset(); diff --git a/src/utils/excalidrawViewHelpers.ts b/src/utils/excalidrawViewHelpers.ts index 9d59450d..aa684e0a 100644 --- a/src/utils/excalidrawViewHelpers.ts +++ b/src/utils/excalidrawViewHelpers.ts @@ -7,6 +7,7 @@ import { getCommonBoundingBox, restoreElements } from "src/constants/constants"; import { getEA } from "src/core"; import { t } from "src/lang/helpers"; import type ExcalidrawView from "src/view/ExcalidrawView"; +import { errorlog } from "./utils"; function estimateBounds( elements: ExcalidrawElement[], @@ -64,8 +65,10 @@ export const insertLaTeXToView = ( ) => { const app = view.plugin.app; const ea = getEA(view); + void import("src/shared/Dialogs/Prompt").then(({ LaTexPrompt }) => { LaTexPrompt.Prompt( + view.plugin, app, t("ENTER_LATEX"), view.plugin.settings.latexBoilerplate, @@ -82,31 +85,41 @@ export const insertLaTeXToView = ( !maxel || curr.updated > maxel.updated ? curr : maxel, undefined, ) as ExcalidrawImageElement; + let scaleX = 1; let scaleY = 1; + if (lastLatexEl) { const equation = view.excalidrawData.getEquation(lastLatexEl.fileId); const dataurl = await ea.tex2dataURL(equation.latex); - if (dataurl.size.width > 0 && dataurl.size.height > 0) { + if (dataurl && dataurl.size.width > 0 && dataurl.size.height > 0) { scaleX = lastLatexEl.width / dataurl.size.width; scaleY = lastLatexEl.height / dataurl.size.height; } } + if (formula) { const id = await ea.addLaTex(0, 0, formula, scaleX, scaleY); if (center) { const el = ea.getElement(id); - const { width, height } = el; - const { x, y } = ea.getViewCenterPosition(); - el.x = x - width / 2; - el.y = y - height / 2; + if (el) { + const { width, height } = el; + const { x, y } = ea.getViewCenterPosition(); + el.x = x - width / 2; + el.y = y - height / 2; + } } await ea.addElementsToView(!center, false, true); ea.selectElementsInView([id]); } ea.destroy(); }, - () => {}, + (e) => { + // Promise rejection handler (e.g. user cancelled prompt or Extras plugin is missing) + if (e && e instanceof Error) { + errorlog({message: "LaTeX Insertion aborted", error: e}); + } + }, ); }); }; diff --git a/src/utils/sceneDataUtils.ts b/src/utils/sceneDataUtils.ts index 6fdc8a8f..58d6e902 100644 --- a/src/utils/sceneDataUtils.ts +++ b/src/utils/sceneDataUtils.ts @@ -1,4 +1,4 @@ -import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types"; +import type { ElementsMap, ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types"; import type { AppState } from "@zsviczian/excalidraw/types/excalidraw/types"; import type { TFile } from "obsidian"; import { FRONTMATTER_KEYS, getContainerElement } from "src/constants/constants"; @@ -248,7 +248,7 @@ export function _getContainerElement( return null; } if (element.containerId) { - return getContainerElement(element, arrayToMap(scene.elements)); + return getContainerElement(element, arrayToMap(scene.elements) as ElementsMap); } return null; } diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 1ba8898b..f028714a 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -20,6 +20,7 @@ import { } from "../constants/constants"; import ExcalidrawPlugin from "../core/main"; import { + ElementsMap, ExcalidrawElement, ExcalidrawImageElement, ImageCrop, @@ -1058,7 +1059,7 @@ export function _getContainerElement( return null; } if (element.containerId) { - return getContainerElement(element, arrayToMap(scene.elements)); + return getContainerElement(element, arrayToMap(scene.elements) as ElementsMap) ?? null; //return scene.elements.find((el:ExcalidrawElement)=>el.id === element.containerId) ?? null; } return null; diff --git a/src/view/ExcalidrawView.ts b/src/view/ExcalidrawView.ts index 877bb34e..02c8c3f8 100644 --- a/src/view/ExcalidrawView.ts +++ b/src/view/ExcalidrawView.ts @@ -24,6 +24,7 @@ import { FileId, NonDeletedExcalidrawElement, BoundElement, + ElementsMap, } from "@zsviczian/excalidraw/types/element/src/types"; import { AppState, @@ -587,21 +588,23 @@ export default class ExcalidrawView this.file.basename, t("EXPORT_FILENAME_PROMPT_PLACEHOLDER"), ); - void prompt.openAndGetValue(async (filename: string) => { + void prompt.openAndGetValue((filename: string) => { if (!filename) { return; } - filename = `${filename}.excalidraw`; - const folderpath = splitFolderAndFilename(this.file?.path).folderpath; - await checkAndCreateFolder(folderpath); //create folder if it does not exist - const path = getNewUniqueFilepath(this.app.vault, filename, folderpath); - const file = await exportImageToFile( - this, - path, - JSON.stringify(this.getScene(), null, "\t"), - ".excalidraw", - ); - new Notice(`Exported to ${file?.name}`, 6000); + void (async () => { + filename = `${filename}.excalidraw`; + const folderpath = splitFolderAndFilename(this.file?.path).folderpath; + await checkAndCreateFolder(folderpath); //create folder if it does not exist + const path = getNewUniqueFilepath(this.app.vault, filename, folderpath); + const file = await exportImageToFile( + this, + path, + JSON.stringify(this.getScene(), null, "\t"), + ".excalidraw", + ); + new Notice(`Exported to ${file?.name}`, 6000); + })(); }); return; } @@ -718,8 +721,8 @@ export default class ExcalidrawView const collected: Record = {}; let resolved = false; - void (await new Promise(async (resolve) => { - void (await loader.loadSceneFiles({ + void await new Promise((resolve) => { + void loader.loadSceneFiles({ excalidrawData: this.excalidrawData, addFiles: ( files: FileData[], @@ -738,8 +741,8 @@ export default class ExcalidrawView }, depth: 0, isThemeChange: true, - })); - })); + }); + }); return Object.keys(collected).length ? collected : null; } @@ -1163,13 +1166,15 @@ export default class ExcalidrawView const d = this.getViewData(); const plugin = this.plugin; const file = this.file; - window.setTimeout(async () => { - if (!d) { - return; - } - await plugin.app.vault.modify(file, d); - //this is a shady edge case, don't scrifice the BAK file in case the drawing is empty - //await getImageCache().addBAKToCache(file.path,d); + window.setTimeout(() => { + void (async () => { + if (!d) { + return; + } + await plugin.app.vault.modify(file, d); + //this is a shady edge case, don't scrifice the BAK file in case the drawing is empty + //await getImageCache().addBAKToCache(file.path,d); + })(); }, 200); this.semaphores.saving = false; return; @@ -1412,31 +1417,35 @@ export default class ExcalidrawView } } - LaTexPrompt.Prompt(this.app, t("ENTER_LATEX"), equation).then( - async (formula: string) => { - if (!formula || formula === equation) { - return; - } - this.excalidrawData.setEquation(fileId, { - latex: formula, - isLoaded: false, - }); - const ea = getEA(this); - ea.copyViewElementsToEAforEditing([el]); - ea.addAppendUpdateCustomData(el.id, { latex: formula }); - const dataurl = await ea.tex2dataURL(equation); - if (dataurl && dataurl.size.height > 0 && dataurl.size.width > 0) { - ea.addAppendUpdateCustomData(el.id, { - latexscale: { - scaleX: el.width / dataurl.size.width, - scaleY: el.height / dataurl.size.height, - }, + LaTexPrompt.Prompt(this.plugin,this.app, t("ENTER_LATEX"), equation).then( + (formula: string) => { + void (async () => { + if (!formula || formula === equation) { + return; + } + this.excalidrawData.setEquation(fileId, { + latex: formula, + isLoaded: false, }); - } - await ea.addElementsToView(false, false, false, false); - await this.save(false); - await updateEquation(formula, fileId, this, addFiles); - this.setDirty(); + const ea = getEA(this); + ea.copyViewElementsToEAforEditing([el]); + ea.addAppendUpdateCustomData(el.id, { latex: formula }); + const dataurl = await ea.tex2dataURL(equation); + if (dataurl && dataurl.size.height > 0 && dataurl.size.width > 0) { + ea.addAppendUpdateCustomData(el.id, { + latexscale: { + scaleX: el.width / dataurl.size.width, + scaleY: el.height / dataurl.size.height, + }, + }); + } + await ea.addElementsToView(false, false, false, false); + await this.save(false); + await updateEquation(formula, fileId, this, (files, view) => { + void addFiles(files, view); + }); + this.setDirty(); + })(); }, () => {}, ); @@ -1731,7 +1740,7 @@ export default class ExcalidrawView let selectedTextElement: ExcalidrawTextElement = selectedText.id ? this.excalidrawAPI .getSceneElements() - .find((el: ExcalidrawElement) => el.id === selectedText.id) + .find((el: ExcalidrawElement) => el.id === selectedText.id) as ExcalidrawTextElement : null; let selectedElement = selectedElementWithLink.id @@ -1739,7 +1748,7 @@ export default class ExcalidrawView .getSceneElements() .find( (el: ExcalidrawElement) => el.id === selectedElementWithLink.id, - ) + ) as ExcalidrawElement : null; //if the user clicked on the label of an arrow then the label will be captured in selectedElement, because @@ -1750,7 +1759,7 @@ export default class ExcalidrawView if (!selectedTextElement && selectedElement?.type === "text") { const container = getContainerElement( selectedElement, - arrayToMap(this.excalidrawAPI.getSceneElements()), + arrayToMap(this.excalidrawAPI.getSceneElements()) as ElementsMap, ); if (container?.type === "arrow") { const x = getTextElementAtPointer(this.currentPosition, this); @@ -1778,15 +1787,15 @@ export default class ExcalidrawView //CTRL click on a linear element with a link will navigate instead of line editor const container = getContainerElement( selectedElement, - arrayToMap(this.excalidrawAPI.getSceneElements()), + arrayToMap(this.excalidrawAPI.getSceneElements()) as ElementsMap, ); if (container?.type !== "arrow") { - selectedTextElement = selectedElement as ExcalidrawTextElement; + selectedTextElement = selectedElement; selectedElement = null; } else { const x = this.processLinkText( selectedElement.rawText, - selectedElement as ExcalidrawTextElement, + selectedElement, container, false, ); @@ -1797,7 +1806,7 @@ export default class ExcalidrawView }; } } else { - selectedTextElement = selectedElement as ExcalidrawTextElement; + selectedTextElement = selectedElement; selectedElement = null; } } @@ -2466,7 +2475,7 @@ export default class ExcalidrawView this.offsetTop = parent.offsetTop; //triggers when the leaf is moved in the workspace - const observerFn = async (m: MutationRecord[]) => { + const observerFn = (m: MutationRecord[]) => { const target = m[0].target; if (!isInstanceOfHTMLElement(target)) { return; @@ -2554,7 +2563,7 @@ export default class ExcalidrawView this.blockTextModeChange = false; } - public autosaveFunction: (() => Promise) | null; + public autosaveFunction: (() => void) | null; get autosaveInterval() { return DEVICE.isMobile ? this.plugin.settings.autosaveIntervalMobile @@ -2562,54 +2571,56 @@ export default class ExcalidrawView } public setupAutosaveTimer() { - const timer = async () => { - if (!this.isLoaded) { - this.autosaveTimer = window.setTimeout(timer, this.autosaveInterval); - return; - } - - const api = this.excalidrawAPI; - if (!api) { - warningUnknowSeriousError(); - return; - } - const st = api.getAppState() as AppState; - const isFreedrawActive = - st.activeTool?.type === "freedraw" && - this.freedrawLastActiveTimestamp > Date.now() - 2000; - const isEditingText = st.editingTextElement !== null; - const isEditingNewElement = st.newElement !== null; - //this will reset positioning of the cursor in case due to the popup keyboard, - //or the command palette, or some other unexpected reason the onResize would not fire... - this.refreshCanvasOffset(); - if ( - this.isDirty() && - this.plugin.settings.autosave && - !this.semaphores.forceSaving && - !this.semaphores.autosaving && - !this.semaphores.embeddableIsEditingSelf && - !isFreedrawActive && - !isEditingText && - !isEditingNewElement //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/630 - ) { - //console.log("autosave"); - this.autosaveTimer = null; - if (this.excalidrawAPI) { - this.semaphores.autosaving = true; - //changed from await to then to avoid lag during saving of large file - void this.save().then(() => (this.semaphores.autosaving = false)); + const timer = () => { + void (async () => { + if (!this.isLoaded) { + this.autosaveTimer = window.setTimeout(timer, this.autosaveInterval); + return; } - this.autosaveTimer = window.setTimeout(timer, this.autosaveInterval); - } else { - this.autosaveTimer = window.setTimeout( - timer, - this.plugin.activeExcalidrawView === this && - this.semaphores.dirty && - this.plugin.settings.autosave - ? 1000 //try again in 1 second - : this.autosaveInterval, - ); - } + + const api = this.excalidrawAPI; + if (!api) { + warningUnknowSeriousError(); + return; + } + const st = api.getAppState() as AppState; + const isFreedrawActive = + st.activeTool?.type === "freedraw" && + this.freedrawLastActiveTimestamp > Date.now() - 2000; + const isEditingText = st.editingTextElement !== null; + const isEditingNewElement = st.newElement !== null; + //this will reset positioning of the cursor in case due to the popup keyboard, + //or the command palette, or some other unexpected reason the onResize would not fire... + this.refreshCanvasOffset(); + if ( + this.isDirty() && + this.plugin.settings.autosave && + !this.semaphores.forceSaving && + !this.semaphores.autosaving && + !this.semaphores.embeddableIsEditingSelf && + !isFreedrawActive && + !isEditingText && + !isEditingNewElement //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/630 + ) { + //console.log("autosave"); + this.autosaveTimer = null; + if (this.excalidrawAPI) { + this.semaphores.autosaving = true; + //changed from await to then to avoid lag during saving of large file + void this.save().then(() => (this.semaphores.autosaving = false)); + } + this.autosaveTimer = window.setTimeout(timer, this.autosaveInterval); + } else { + this.autosaveTimer = window.setTimeout( + timer, + this.plugin.activeExcalidrawView === this && + this.semaphores.dirty && + this.plugin.settings.autosave + ? 1000 //try again in 1 second + : this.autosaveInterval, + ); + } + })(); }; this.autosaveFunction = timer; @@ -3061,30 +3072,32 @@ export default class ExcalidrawView : state.subpath, ); if (filenameParts.hasBlockref) { - window.setTimeout(async () => { - await waitForExcalidraw(); - if (filenameParts.blockref && !filenameParts.hasGroupref) { - if ( - !this.getScene()?.elements.find( - (el: ExcalidrawElement) => el.id === filenameParts.blockref, - ) - ) { - const cleanQuery = cleanSectionHeading( - filenameParts.blockref, - ).replaceAll(" ", ""); - const blocks = await this.getBackOfTheNoteBlocks(); - if (blocks.includes(cleanQuery)) { - void this.setMarkdownView(state); - return; + window.setTimeout(() => { + void (async () => { + await waitForExcalidraw(); + if (filenameParts.blockref && !filenameParts.hasGroupref) { + if ( + !this.getScene()?.elements.find( + (el: ExcalidrawElement) => el.id === filenameParts.blockref, + ) + ) { + const cleanQuery = cleanSectionHeading( + filenameParts.blockref, + ).replaceAll(" ", ""); + const blocks = await this.getBackOfTheNoteBlocks(); + if (blocks.includes(cleanQuery)) { + void this.setMarkdownView(state); + return; + } } } - } - window.setTimeout(() => - this.zoomToElementId( - filenameParts.blockref, - filenameParts.hasGroupref, - ), - ); + window.setTimeout(() => { + void this.zoomToElementId( + filenameParts.blockref, + filenameParts.hasGroupref, + ); + }); + })(); }); } @@ -3099,8 +3112,9 @@ export default class ExcalidrawView query.length > 0 && !(query.length === 1 && query[0].length === 0) ) { - window.setTimeout(async () => { - await waitForExcalidraw(); + window.setTimeout(() => { + void (async () => { + await waitForExcalidraw(); const api = this.excalidrawAPI; if (!api) { @@ -3163,21 +3177,25 @@ export default class ExcalidrawView } } - if ( - !this.selectElementsMatchingQuery( - elements, - query, - !api.getAppState().viewModeEnabled, - filenameParts.hasSectionref, - filenameParts.hasGroupref, - ) - ) { - const cleanQuery = cleanSectionHeading(query[0]); - const sections = await this.getBackOfTheNoteSections(); - if (sections.includes(cleanQuery) || this.data.includes(query[0])) { - void this.setMarkdownView(state); + if ( + !this.selectElementsMatchingQuery( + elements, + query, + !api.getAppState().viewModeEnabled, + filenameParts.hasSectionref, + filenameParts.hasGroupref, + ) + ) { + const cleanQuery = cleanSectionHeading(query[0]); + const sections = await this.getBackOfTheNoteSections(); + if ( + sections.includes(cleanQuery) || + this.data.includes(query[0]) + ) { + void this.setMarkdownView(state); + } } - } + })(); }); } @@ -3209,270 +3227,276 @@ export default class ExcalidrawView } public isLoaded: boolean = false; - async setViewData(data: string, clear: boolean = false) { + setViewData(data: string, clear: boolean = false) { //I am using last loaded file to control when the view reloads. //It seems text file view gets the modified file event after sync before the modifyEventHandler in main.ts //reload can only be triggered via reload() - await this.plugin.awaitInit(); - if (this.lastLoadedFile === this.file) { - return; - } - this.isLoaded = false; - if (!this.file) { - return; - } - if (this.plugin.settings.compareManifestToPluginVersion) { - void checkVersionMismatch(this.plugin); - } - if (this.plugin.settings.showNewVersionNotification) { - void checkExcalidrawVersion(); - } - if (isMaskFile(this.plugin, this.file)) { - const notice = new Notice(t("MASK_FILE_NOTICE"), 5000); - //add click and hold event listner to the notice - let noticeTimeout: number; - this.registerDomEvent(notice.messageEl, "pointerdown", () => { - noticeTimeout = window.setTimeout(() => { - window.open(getYouTubeUrl("uHFd0XoHRxE")); - }, 1000); - }); - this.registerDomEvent(notice.messageEl, "pointerup", () => { - window.clearTimeout(noticeTimeout); - }); - } - if (clear) { - this.clear(); - } - this.lastSaveTimestamp = this.file.stat.mtime; - this.lastLoadedFile = this.file; - data = this.data = data.replaceAll("\r\n", "\n").replaceAll("\r", "\n"); - this.app.workspace.onLayoutReady(async () => { - //the leaf moved to a window and ExcalidrawView was destructed - //Happens during Obsidian startup if View opens in new window. - if (!this?.app) { + void (async () => { + await this.plugin.awaitInit(); + if (this.lastLoadedFile === this.file) { return; } - await this.plugin.awaitInit(); - let counter = 0; - while ( - (!this.semaphores.viewloaded || - !this.file || - !this.plugin.fourthFontLoaded) && - counter++ < 50 - ) { - await sleep(50); - } + this.isLoaded = false; if (!this.file) { return; } - this.compatibilityMode = this.file.extension === "excalidraw"; - await this.plugin.loadSettings(); - if (this.compatibilityMode) { - this.plugin.enableLegacyFilePopoverObserver(); - this.actionButtons?.isRaw?.hide(); - // this.actionButtons.isParsed.hide(); - this.actionButtons?.link?.hide(); - this.textMode = TextMode.raw; - await this.excalidrawData.loadLegacyData(data, this.file); - if (!this.plugin.settings.compatibilityMode) { - new Notice(t("COMPATIBILITY_MODE"), 4000); - } - this.excalidrawData.disableCompression = true; - } else { - this.actionButtons?.link?.show(); - this.excalidrawData.disableCompression = false; - const textMode = getTextMode(data); - await this.changeTextMode(textMode, false); - try { - if ( - !(await this.excalidrawData.loadData( - data, - this.file, - this.textMode, - )) - ) { - return; - } - } catch (e) { - errorlog({ where: "ExcalidrawView.setViewData", error: e }); - if (e.message === ERROR_IFRAME_CONVERSION_CANCELED) { - await this.setMarkdownView(); - return; - } - const file = this.file; - const plugin = this.plugin; - const leaf = this.leaf; - void (async () => { - let confirmation: boolean | null = true; - let counter = 0; - const timestamp = Date.now(); - while (!getImageCache().isReady() && confirmation) { - const message = `You've been now waiting for ${Math.round((Date.now() - timestamp) / 1000)} seconds. `; - getImageCache().initializationNotice = true; - const confirmationPrompt = new MultiOptionConfirmationPrompt( - plugin, - `${ - counter > 0 - ? counter % 4 === 0 - ? `${message}The CACHE is still loading.

` - : counter % 4 === 1 - ? `${ - message - }Watch the top right corner for the notification.

` - : counter % 4 === 2 - ? `${ - message - }I really, really hope the backup will work for you!

` - : `${ - message - }I am sorry, it is taking a while, there is not much I can do...

` - : "" - }${t("CACHE_NOT_READY")}`, - ); - confirmation = await confirmationPrompt.waitForClose; - counter++; - } - - const drawingBAK = await getImageCache().getBAKFromCache(file.path); - if (!drawingBAK) { - new Notice( - `Error loading drawing:\n${e.message}${ - e.message === "Cannot read property 'index' of undefined" - ? "\n'# Drawing' section is likely missing" - : "" - }\n\nTry manually fixing the file or restoring an earlier version from sync history.`, - 10000, - ); - return; - } - const confirmationPrompt = new MultiOptionConfirmationPrompt( - plugin, - t("BACKUP_AVAILABLE"), - ); - void confirmationPrompt.waitForClose.then(async (confirmed) => { - if (confirmed) { - await this.app.vault.modify(file, drawingBAK); - plugin.excalidrawFileModes[leaf.id || file.path] = - VIEW_TYPE_EXCALIDRAW; - void setExcalidrawView(leaf); - } - }); - })(); - void this.setMarkdownView(); + if (this.plugin.settings.compareManifestToPluginVersion) { + void checkVersionMismatch(this.plugin); + } + if (this.plugin.settings.showNewVersionNotification) { + void checkExcalidrawVersion(); + } + if (isMaskFile(this.plugin, this.file)) { + const notice = new Notice(t("MASK_FILE_NOTICE"), 5000); + //add click and hold event listner to the notice + let noticeTimeout: number; + this.registerDomEvent(notice.messageEl, "pointerdown", () => { + noticeTimeout = window.setTimeout(() => { + window.open(getYouTubeUrl("uHFd0XoHRxE")); + }, 1000); + }); + this.registerDomEvent(notice.messageEl, "pointerup", () => { + window.clearTimeout(noticeTimeout); + }); + } + if (clear) { + this.clear(); + } + this.lastSaveTimestamp = this.file.stat.mtime; + this.lastLoadedFile = this.file; + data = this.data = data.replaceAll("\r\n", "\n").replaceAll("\r", "\n"); + this.app.workspace.onLayoutReady(async () => { + //the leaf moved to a window and ExcalidrawView was destructed + //Happens during Obsidian startup if View opens in new window. + if (!this?.app) { return; } - } - - if ( - getImageCache().isReady() && - this.excalidrawData.scene && - this.excalidrawData.scene.elements && - this.excalidrawData.scene.elements.length === 0 - ) { - const backup = await getImageCache().getBAKFromCache(this.file.path); - if (backup && backup.length > data.length) { - window.setTimeout(async () => { - const confirmationPrompt = new MultiOptionConfirmationPrompt( - this.plugin, - t("BACKUP_SAVE_AS_FILE"), - new Map([ - [t("BACKUP_CANCEL"), 0], - [t("BACKUP_DELETE"), 2], - [t("BACKUP_SAVE"), 1], - ]), - t("BACKUP_SAVE"), - ); - const result = await confirmationPrompt.waitForClose; - if (result === 1) { - const path = getNewUniqueFilepath( - this.app.vault, - `${this.file.basename}.restored.${this.file.extension}`, - this.file.parent.path, - ); - const backupFile = await createFileAndAwaitMetacacheUpdate( - this.app, - path, - backup, - ); - await getImageCache().removeBAKFromCache(this.file.path); - this.plugin.openDrawing(backupFile, "new-tab"); - } else if (result === 2) { - await getImageCache().removeBAKFromCache(this.file.path); + await this.plugin.awaitInit(); + let counter = 0; + while ( + (!this.semaphores.viewloaded || + !this.file || + !this.plugin.fourthFontLoaded) && + counter++ < 50 + ) { + await sleep(50); + } + if (!this.file) { + return; + } + this.compatibilityMode = this.file.extension === "excalidraw"; + await this.plugin.loadSettings(); + if (this.compatibilityMode) { + this.plugin.enableLegacyFilePopoverObserver(); + this.actionButtons?.isRaw?.hide(); + // this.actionButtons.isParsed.hide(); + this.actionButtons?.link?.hide(); + this.textMode = TextMode.raw; + await this.excalidrawData.loadLegacyData(data, this.file); + if (!this.plugin.settings.compatibilityMode) { + new Notice(t("COMPATIBILITY_MODE"), 4000); + } + this.excalidrawData.disableCompression = true; + } else { + this.actionButtons?.link?.show(); + this.excalidrawData.disableCompression = false; + const textMode = getTextMode(data); + await this.changeTextMode(textMode, false); + try { + if ( + !(await this.excalidrawData.loadData( + data, + this.file, + this.textMode, + )) + ) { + return; } - }); - } - } - await this.loadDrawing(true); + } catch (e) { + errorlog({ where: "ExcalidrawView.setViewData", error: e as unknown}); + if (e instanceof Error && e.message === ERROR_IFRAME_CONVERSION_CANCELED) { + await this.setMarkdownView(); + return; + } + const file = this.file; + const plugin = this.plugin; + const leaf = this.leaf; + void (async () => { + let confirmation: boolean | null = true; + let counter = 0; + const timestamp = Date.now(); + while (!getImageCache().isReady() && confirmation) { + const message = `You've been now waiting for ${Math.round((Date.now() - timestamp) / 1000)} seconds. `; + getImageCache().initializationNotice = true; + const confirmationPrompt = new MultiOptionConfirmationPrompt( + plugin, + `${ + counter > 0 + ? counter % 4 === 0 + ? `${message}The CACHE is still loading.

` + : counter % 4 === 1 + ? `${ + message + }Watch the top right corner for the notification.

` + : counter % 4 === 2 + ? `${ + message + }I really, really hope the backup will work for you!

` + : `${ + message + }I am sorry, it is taking a while, there is not much I can do...

` + : "" + }${t("CACHE_NOT_READY")}`, + ); + confirmation = await confirmationPrompt.waitForClose; + counter++; + } - onLoadMessages( - this.excalidrawData.scene as { - elements: ExcalidrawElement[]; - appState: AppState; - }, - ); - - if (this.plugin.ea.onFileOpenHook) { - const tempEA = getEA(this); - try { - await this.plugin.ea.onFileOpenHook({ - ea: tempEA, - excalidrawFile: this.file, - view: this, - }); - } catch (e) { - errorlog({ - where: "ExcalidrawView.setViewData.onFileOpenHook", - error: e, - }); - } finally { - tempEA.destroy(); - } - } - - const script = this.excalidrawData.getOnLoadScript(); - if (script) { - const scriptname = `${this.file.basename}-onlaod-script`; - const runScript = async () => { - if (!this.excalidrawAPI) { - //need to wait for Excalidraw to initialize - window.setTimeout((): void => { - void runScript(); - }, 200); + const drawingBAK = await getImageCache().getBAKFromCache(file.path); + if (!drawingBAK) { + new Notice( + `Error loading drawing:\n${e.message}${ + e.message === "Cannot read property 'index' of undefined" + ? "\n'# Drawing' section is likely missing" + : "" + }\n\nTry manually fixing the file or restoring an earlier version from sync history.`, + 10000, + ); + return; + } + const confirmationPrompt = new MultiOptionConfirmationPrompt( + plugin, + t("BACKUP_AVAILABLE"), + ); + void confirmationPrompt.waitForClose.then((confirmed) => { + void (async () => { + if (confirmed) { + await this.app.vault.modify(file, drawingBAK); + plugin.excalidrawFileModes[leaf.id || file.path] = + VIEW_TYPE_EXCALIDRAW; + void setExcalidrawView(leaf); + } + })(); + }); + })(); + void this.setMarkdownView(); return; } - void this.plugin.scriptEngine.executeScript( - this, - script, - scriptname, - this.file, - ); - }; - let allowOnloadScript: boolean | null = - this.plugin.settings.enableOnloadScripts; - if (!allowOnloadScript) { - const onloadScriptPromptButtons = new Map([ - [t("ENABLE_ONLOAD_SCRIPTS_CONFIRM_DENY"), null], - [t("ENABLE_ONLOAD_SCRIPTS_CONFIRM_ENABLE"), true], - ]); - const confirmationPrompt = new MultiOptionConfirmationPrompt( - this.plugin, - `${t("ENABLE_ONLOAD_SCRIPTS_NAME")}
${t("ENABLE_ONLOAD_SCRIPTS_CONFIRMATION")}` + - `

${t("ENABLE_ONLOAD_SCRIPTS_DESC")}`, - onloadScriptPromptButtons, - t("ENABLE_ONLOAD_SCRIPTS_CONFIRM_DENY"), - ); - allowOnloadScript = await confirmationPrompt.waitForClose; - if (allowOnloadScript) { - this.plugin.settings.enableOnloadScripts = true; - await this.plugin.saveSettings(); + } + + if ( + getImageCache().isReady() && + this.excalidrawData.scene && + this.excalidrawData.scene.elements && + this.excalidrawData.scene.elements.length === 0 + ) { + const backup = await getImageCache().getBAKFromCache(this.file.path); + if (backup && backup.length > data.length) { + window.setTimeout(() => { + void (async () => { + const confirmationPrompt = new MultiOptionConfirmationPrompt( + this.plugin, + t("BACKUP_SAVE_AS_FILE"), + new Map([ + [t("BACKUP_CANCEL"), 0], + [t("BACKUP_DELETE"), 2], + [t("BACKUP_SAVE"), 1], + ]), + t("BACKUP_SAVE"), + ); + const result = await confirmationPrompt.waitForClose; + if (result === 1) { + const path = getNewUniqueFilepath( + this.app.vault, + `${this.file.basename}.restored.${this.file.extension}`, + this.file.parent.path, + ); + const backupFile = await createFileAndAwaitMetacacheUpdate( + this.app, + path, + backup, + ); + await getImageCache().removeBAKFromCache(this.file.path); + this.plugin.openDrawing(backupFile, "new-tab"); + } else if (result === 2) { + await getImageCache().removeBAKFromCache(this.file.path); + } + })(); + }); } } - if (allowOnloadScript) { - await runScript(); + await this.loadDrawing(true); + + onLoadMessages( + this.excalidrawData.scene as { + elements: ExcalidrawElement[]; + appState: AppState; + }, + ); + + if (this.plugin.ea.onFileOpenHook) { + const tempEA = getEA(this); + try { + await this.plugin.ea.onFileOpenHook({ + ea: tempEA, + excalidrawFile: this.file, + view: this, + }); + } catch (e) { + errorlog({ + where: "ExcalidrawView.setViewData.onFileOpenHook", + error: e as unknown, + }); + } finally { + tempEA.destroy(); + } } - } - this.isLoaded = true; - }); + + const script = this.excalidrawData.getOnLoadScript(); + if (script) { + const scriptname = `${this.file.basename}-onlaod-script`; + const runScript = async () => { + if (!this.excalidrawAPI) { + //need to wait for Excalidraw to initialize + window.setTimeout((): void => { + void runScript(); + }, 200); + return; + } + void this.plugin.scriptEngine.executeScript( + this, + script, + scriptname, + this.file, + ); + }; + let allowOnloadScript: boolean | null = + this.plugin.settings.enableOnloadScripts; + if (!allowOnloadScript) { + const onloadScriptPromptButtons = new Map([ + [t("ENABLE_ONLOAD_SCRIPTS_CONFIRM_DENY"), null], + [t("ENABLE_ONLOAD_SCRIPTS_CONFIRM_ENABLE"), true], + ]); + const confirmationPrompt = new MultiOptionConfirmationPrompt( + this.plugin, + `${t("ENABLE_ONLOAD_SCRIPTS_NAME")}
${t("ENABLE_ONLOAD_SCRIPTS_CONFIRMATION")}` + + `

${t("ENABLE_ONLOAD_SCRIPTS_DESC")}`, + onloadScriptPromptButtons, + t("ENABLE_ONLOAD_SCRIPTS_CONFIRM_DENY"), + ); + allowOnloadScript = await confirmationPrompt.waitForClose; + if (allowOnloadScript) { + this.plugin.settings.enableOnloadScripts = true; + await this.plugin.saveSettings(); + } + } + if (allowOnloadScript) { + await runScript(); + } + } + this.isLoaded = true; + }); + })(); } private getGridColor(bgColor: string): { Bold: string; Regular: string } { @@ -3735,7 +3759,7 @@ export default class ExcalidrawView } void this.loadSceneFiles(); }; - window.setTimeout(async () => { + window.setTimeout(() => { retryLoadSceneFiles(); }, 2000); return true; @@ -4771,7 +4795,7 @@ export default class ExcalidrawView return false; } const sceneElements = api.getSceneElements() as ExcalidrawElement[]; - const elementsMap = arrayToMap(sceneElements); + const elementsMap = arrayToMap(sceneElements) as ElementsMap; const textElements = newElements.filter((el) => el.type == "text"); let shouldRefreshArrows = false; for (let i = 0; i < textElements.length; i++) { @@ -5753,60 +5777,66 @@ export default class ExcalidrawView ); if (isCodeblock) { const clipboardText = data.text; - window.setTimeout(() => this.pasteCodeBlock(clipboardText)); + window.setTimeout(() => { + void this.pasteCodeBlock(clipboardText); + }); return false; } if ( - isTextImageTransclusion(data.text, this, async (link, file) => { - const ea = getEA(this); - if (IMAGE_TYPES.contains(file.extension)) { - ea.selectElementsInView([ - await insertImageToView(ea, this.currentPosition, file), - ]); - ea.destroy(); - } else if (file.extension !== "pdf") { - ea.selectElementsInView([ - await insertEmbeddableToView( - ea, - this.currentPosition, - file, - link, - ), - ]); - ea.destroy(); - } else if ( - link.match(/^[^#]*#page=\d*(&\w*=[^&]+){0,}&rect=\d*,\d*,\d*,\d*/g) - ) { + isTextImageTransclusion(data.text, this, (link, file) => { + void (async () => { const ea = getEA(this); - const imgID = await ea.addImage( - this.currentPosition.x, - this.currentPosition.y, - link.split("&rect=")[0], - ); - const el = ea.getElement(imgID) as Mutable; - const fd = ea.imagesDict[el.fileId] as FileData; - el.crop = getPDFCropRect({ - scale: this.plugin.settings.pdfScale, - link, - naturalHeight: fd.size.height, - naturalWidth: fd.size.width, - pdfPageViewProps: fd.pdfPageViewProps, - }); - addAppendUpdateCustomData(el, { - pdfPageViewProps: fd.pdfPageViewProps, - }); - if (el.crop) { - el.width = el.crop.width / this.plugin.settings.pdfScale; - el.height = el.crop.height / this.plugin.settings.pdfScale; + if (IMAGE_TYPES.contains(file.extension)) { + ea.selectElementsInView([ + await insertImageToView(ea, this.currentPosition, file), + ]); + ea.destroy(); + } else if (file.extension !== "pdf") { + ea.selectElementsInView([ + await insertEmbeddableToView( + ea, + this.currentPosition, + file, + link, + ), + ]); + ea.destroy(); + } else if ( + link.match( + /^[^#]*#page=\d*(&\w*=[^&]+){0,}&rect=\d*,\d*,\d*,\d*/g, + ) + ) { + const ea = getEA(this); + const imgID = await ea.addImage( + this.currentPosition.x, + this.currentPosition.y, + link.split("&rect=")[0], + ); + const el = ea.getElement(imgID) as Mutable; + const fd = ea.imagesDict[el.fileId] as FileData; + el.crop = getPDFCropRect({ + scale: this.plugin.settings.pdfScale, + link, + naturalHeight: fd.size.height, + naturalWidth: fd.size.width, + pdfPageViewProps: fd.pdfPageViewProps, + }); + addAppendUpdateCustomData(el, { + pdfPageViewProps: fd.pdfPageViewProps, + }); + if (el.crop) { + el.width = el.crop.width / this.plugin.settings.pdfScale; + el.height = el.crop.height / this.plugin.settings.pdfScale; + } + el.link = `[[${link}]]`; + await ea.addElementsToView(false, false).then(() => ea.destroy()); + } else { + const modal = new UniversalInsertFileModal(this.plugin, this); + modal.open(file, this.currentPosition); } - el.link = `[[${link}]]`; - await ea.addElementsToView(false, false).then(() => ea.destroy()); - } else { - const modal = new UniversalInsertFileModal(this.plugin, this); - modal.open(file, this.currentPosition); - } - this.setDirty(); + this.setDirty(); + })(); }) ) { return false; @@ -5860,7 +5890,9 @@ export default class ExcalidrawView nanoid(), ), ); - window.setTimeout(() => this.save(false), 30); //removed prevent reload = false, as reload was triggered when pasted containers were processed and there was a conflict with the new elements + window.setTimeout(() => { + void this.save(false); + }, 30); //removed prevent reload = false, as reload was triggered when pasted containers were processed and there was a conflict with the new elements } //process pasted text after it was processed into elements by Excalidraw @@ -5876,15 +5908,16 @@ export default class ExcalidrawView .filter((el) => el.type === "text") .map((el) => el.id); - window.setTimeout(async () => { - const sceneElements = - api.getSceneElementsIncludingDeleted() as Mutable[]; - const newElements = sceneElements.filter( - (el) => - el.type === "text" && - !el.isDeleted && - !prevElements.includes(el.id), - ) as ExcalidrawTextElement[]; + window.setTimeout(() => { + void (async () => { + const sceneElements = + api.getSceneElementsIncludingDeleted() as Mutable[]; + const newElements = sceneElements.filter( + (el) => + el.type === "text" && + !el.isDeleted && + !prevElements.includes(el.id), + ) as ExcalidrawTextElement[]; //collect would-be image elements and their corresponding files and links const imageElementsMap = new Map< @@ -5900,66 +5933,67 @@ export default class ExcalidrawView isTextImageTransclusion(el.originalText, this, callback); }); - //if there are no image elements, save and return - //Save will ensure links and embeds are parsed - if (imageElementsMap.size === 0) { - await this.save(false); //saving because there still may be text transclusions - return; - } - - //if there are image elements - //first delete corresponding "old" text elements - for (const [el] of imageElementsMap) { - const clone = cloneElement(el); - clone.isDeleted = true; - this.excalidrawData.deleteTextElement(clone.id); - sceneElements[sceneElements.indexOf(el)] = clone; - } - this.updateScene({ - elements: sceneElements, - captureUpdate: CaptureUpdateAction.NEVER, - }); - - //then insert images and embeds - //shift text elements down to make space for images and embeds - const ea: ExcalidrawAutomate = getEA(this); - let offset = 0; - for (const el of newElements) { - const topleft = { x: el.x, y: el.y + offset }; - if (imageElementsMap.has(el)) { - const [link, file] = imageElementsMap.get(el); - if (IMAGE_TYPES.contains(file.extension)) { - const id = await insertImageToView( - ea, - topleft, - file, - undefined, - false, - ); - offset += ea.getElement(id).height - el.height; - } else if (file.extension !== "pdf") { - //isTextImageTransclusion will not return text only markdowns, this is here - //for the future when we may want to support other embeddables - const id = await insertEmbeddableToView( - ea, - topleft, - file, - link, - false, - ); - offset += ea.getElement(id).height - el.height; - } else { - const modal = new UniversalInsertFileModal(this.plugin, this); - modal.open(file, topleft); - } - } else if (offset !== 0) { - ea.copyViewElementsToEAforEditing([el]); - ea.getElement(el.id).y = topleft.y; + //if there are no image elements, save and return + //Save will ensure links and embeds are parsed + if (imageElementsMap.size === 0) { + await this.save(false); //saving because there still may be text transclusions + return; } - } - await ea.addElementsToView(false, true); - ea.selectElementsInView(newElements.map((el) => el.id)); - ea.destroy(); + + //if there are image elements + //first delete corresponding "old" text elements + for (const [el] of imageElementsMap) { + const clone = cloneElement(el); + clone.isDeleted = true; + this.excalidrawData.deleteTextElement(clone.id); + sceneElements[sceneElements.indexOf(el)] = clone; + } + this.updateScene({ + elements: sceneElements, + captureUpdate: CaptureUpdateAction.NEVER, + }); + + //then insert images and embeds + //shift text elements down to make space for images and embeds + const ea: ExcalidrawAutomate = getEA(this); + let offset = 0; + for (const el of newElements) { + const topleft = { x: el.x, y: el.y + offset }; + if (imageElementsMap.has(el)) { + const [link, file] = imageElementsMap.get(el); + if (IMAGE_TYPES.contains(file.extension)) { + const id = await insertImageToView( + ea, + topleft, + file, + undefined, + false, + ); + offset += ea.getElement(id).height - el.height; + } else if (file.extension !== "pdf") { + //isTextImageTransclusion will not return text only markdowns, this is here + //for the future when we may want to support other embeddables + const id = await insertEmbeddableToView( + ea, + topleft, + file, + link, + false, + ); + offset += ea.getElement(id).height - el.height; + } else { + const modal = new UniversalInsertFileModal(this.plugin, this); + modal.open(file, topleft); + } + } else if (offset !== 0) { + ea.copyViewElementsToEAforEditing([el]); + ea.getElement(el.id).y = topleft.y; + } + } + await ea.addElementsToView(false, true); + ea.selectElementsInView(newElements.map((el) => el.id)); + ea.destroy(); + })(); }, 200); //parse transclusion and links after paste } return true; @@ -6083,47 +6117,49 @@ export default class ExcalidrawView // 1 2 if ( isTextImageTransclusion(nextOriginalText, this, (link, file) => { - window.setTimeout(async () => { - const elements = - this.excalidrawAPI.getSceneElements() as Mutable[]; - const el = elements.filter( - (el: ExcalidrawElement) => el.id === textElement.id, - ) as ExcalidrawTextElement[]; - if (el.length === 1) { - const center = { x: el[0].x, y: el[0].y }; - const clone = cloneElement(el[0]); - clone.isDeleted = true; - this.excalidrawData.deleteTextElement(clone.id); - elements[elements.indexOf(el[0])] = clone; - this.updateScene({ - elements, - captureUpdate: CaptureUpdateAction.NEVER, - }); - const ea: ExcalidrawAutomate = getEA(this); - if (IMAGE_TYPES.contains(file.extension)) { - ea.selectElementsInView([ - await insertImageToView(ea, center, file), - ]); - ea.destroy(); - } else if (file.extension !== "pdf") { - ea.selectElementsInView([ - await insertEmbeddableToView(ea, center, file, link), - ]); - ea.destroy(); - } else { - const linkParts = getLinkParts(link); - if (linkParts.page) { - const path = `${file.path}#${link.split("#")[1]}`; + window.setTimeout(() => { + void (async () => { + const elements = + this.excalidrawAPI.getSceneElements() as Mutable[]; + const el = elements.filter( + (el: ExcalidrawElement) => el.id === textElement.id, + ) as ExcalidrawTextElement[]; + if (el.length === 1) { + const center = { x: el[0].x, y: el[0].y }; + const clone = cloneElement(el[0]); + clone.isDeleted = true; + this.excalidrawData.deleteTextElement(clone.id); + elements[elements.indexOf(el[0])] = clone; + this.updateScene({ + elements, + captureUpdate: CaptureUpdateAction.NEVER, + }); + const ea: ExcalidrawAutomate = getEA(this); + if (IMAGE_TYPES.contains(file.extension)) { ea.selectElementsInView([ - await insertImageToView(ea, center, path), + await insertImageToView(ea, center, file), ]); + ea.destroy(); + } else if (file.extension !== "pdf") { + ea.selectElementsInView([ + await insertEmbeddableToView(ea, center, file, link), + ]); + ea.destroy(); } else { - const modal = new UniversalInsertFileModal(this.plugin, this); - modal.open(file, center); + const linkParts = getLinkParts(link); + if (linkParts.page) { + const path = `${file.path}#${link.split("#")[1]}`; + ea.selectElementsInView([ + await insertImageToView(ea, center, path), + ]); + } else { + const modal = new UniversalInsertFileModal(this.plugin, this); + modal.open(file, center); + } } + this.setDirty(); } - this.setDirty(); - } + })(); }); }) ) { @@ -6142,7 +6178,7 @@ export default class ExcalidrawView // setTextElement will invoke this callback function in case quick parse was not possible, the parsed text contains transclusions // in this case I need to update the scene asynchronously when parsing is complete - const callback = async (parsedText: string) => { + const callback = (parsedText: string) => { //this callback function will only be invoked if quick parse fails, i.e. there is a transclusion in the raw text if (this.textMode === TextMode.raw) { return; @@ -6150,7 +6186,7 @@ export default class ExcalidrawView const elements = this.excalidrawAPI.getSceneElements() as Mutable[]; - const elementsMap = arrayToMap(elements); + const elementsMap = arrayToMap(elements) as ElementsMap; const el = elements.filter( (el: ExcalidrawElement) => el.id === textElement.id, ); @@ -6578,8 +6614,9 @@ export default class ExcalidrawView } this.plugin.insertLinkDialog.start( this.file.path, - (markdownlink: string, path: string, alias: string) => - this.addLink(markdownlink, path, alias, linkVal), + (markdownlink: string, path: string, alias: string) => { + void this.addLink(markdownlink, path, alias, linkVal); + }, link, ); } @@ -6636,15 +6673,17 @@ export default class ExcalidrawView renderContextMenuAction( React, t("REMOVE_LINK"), - async () => { - const ea = getEA(this); - ea.copyViewElementsToEAforEditing([selectedTextElement]); - const el = ea.getElement( - selectedTextElement.id, - ) as Mutable; - el.link = null; - await ea.addElementsToView(false); - ea.destroy(); + () => { + void (async () => { + const ea = getEA(this); + ea.copyViewElementsToEAforEditing([selectedTextElement]); + const el = ea.getElement( + selectedTextElement.id, + ) as Mutable; + el.link = null; + await ea.addElementsToView(false); + ea.destroy(); + })(); }, onClose, "removeLink", @@ -6695,11 +6734,11 @@ export default class ExcalidrawView renderContextMenuAction( React, t("CONVERT_URL_TO_FILE"), - () => { - window.setTimeout(() => - this.convertImageElWithURLToLocalFile(img), - ); - }, + () => { + window.setTimeout(() => { + void this.convertImageElWithURLToLocalFile(img); + }); + }, onClose, "convertImgUrlToFile", ), @@ -6716,21 +6755,23 @@ export default class ExcalidrawView renderContextMenuAction( React, t("IMPORT_SVG_CONTEXTMENU"), - async () => { - const base64Content = img.embeddedFile - .getImage(false) - .split(",")[1]; - // Decoding the base64 content - const svg = atob(base64Content); - if (!svg || svg === "") { - return; - } - const ea = getEA(this); - ea.importSVG(svg); - ea.addToGroup(ea.getElements().map((el) => el.id)); - await ea.addElementsToView(true, true, true, true); - ea.destroy(); - }, + () => { + void (async () => { + const base64Content = img.embeddedFile + .getImage(false) + .split(",")[1]; + // Decoding the base64 content + const svg = atob(base64Content); + if (!svg || svg === "") { + return; + } + const ea = getEA(this); + ea.importSVG(svg); + ea.addToGroup(ea.getElements().map((el) => el.id)); + await ea.addElementsToView(true, true, true, true); + ea.destroy(); + })(); + }, onClose, "convertSvgToStrokes", ), @@ -6832,35 +6873,37 @@ export default class ExcalidrawView renderContextMenuAction( React, t("INVERT_IMAGES_IN_DARK_MODE"), - async () => { - const ea = getEA(this); - ea.copyViewElementsToEAforEditing( - imagesWithStatus.map((img) => img.el), - ); - imagesWithStatus.forEach((img) => { - const editableEl = ea.getElement( - img.el.id, - ) as Mutable; - const embeddedFile = this.excalidrawData.getFile( - editableEl.fileId, + () => { + void (async () => { + const ea = getEA(this); + ea.copyViewElementsToEAforEditing( + imagesWithStatus.map((img) => img.el), ); - const imageType = getImageType(embeddedFile) ?? img.imageType; - if (imageType === "svg" || imageType === "excalidraw") { - addAppendUpdateCustomData(editableEl, { - doNotInvertSVGInDarkMode: newInvertState - ? undefined - : true, - invertBitmapInDarkmode: undefined, - }); - } else { - addAppendUpdateCustomData(editableEl, { - invertBitmapInDarkmode: newInvertState, - doNotInvertSVGInDarkMode: undefined, - }); - } - }); - await ea.addElementsToView(false); - ea.destroy(); + imagesWithStatus.forEach((img) => { + const editableEl = ea.getElement( + img.el.id, + ) as Mutable; + const embeddedFile = this.excalidrawData.getFile( + editableEl.fileId, + ); + const imageType = getImageType(embeddedFile) ?? img.imageType; + if (imageType === "svg" || imageType === "excalidraw") { + addAppendUpdateCustomData(editableEl, { + doNotInvertSVGInDarkMode: newInvertState + ? undefined + : true, + invertBitmapInDarkmode: undefined, + }); + } else { + addAppendUpdateCustomData(editableEl, { + invertBitmapInDarkmode: newInvertState, + doNotInvertSVGInDarkMode: undefined, + }); + } + }); + await ea.addElementsToView(false); + ea.destroy(); + })(); }, onClose, "invertImageInDarkmode", @@ -6910,7 +6953,9 @@ export default class ExcalidrawView renderContextMenuAction( React, t("CONVERT_CARD_TO_FILE"), - () => this.moveBackOfTheNoteCardToFile(), + () => { + void this.moveBackOfTheNoteCardToFile(); + }, onClose, "convertCardToFile", ), @@ -6922,7 +6967,9 @@ export default class ExcalidrawView renderContextMenuAction( React, t("INSERT_CARD"), - () => this.insertBackOfTheNoteCard(), + () => { + void this.insertBackOfTheNoteCard(); + }, onClose, "insertCard", ), @@ -6950,8 +6997,9 @@ export default class ExcalidrawView () => { this.plugin.insertLinkDialog.start( this.file.path, - (markdownlink: string, path: string, alias: string) => - this.addLink(markdownlink, path, alias), + (markdownlink: string, path: string, alias: string) => { + void this.addLink(markdownlink, path, alias); + }, ); }, onClose, @@ -6964,12 +7012,14 @@ export default class ExcalidrawView renderContextMenuAction( React, t("PASTE_CODEBLOCK"), - async () => { - const data = await navigator.clipboard?.readText(); - if (!data || data.trim() === "") { - return; - } - void this.pasteCodeBlock(data); + () => { + void (async () => { + const data = await navigator.clipboard?.readText(); + if (!data || data.trim() === "") { + return; + } + void this.pasteCodeBlock(data); + })(); }, onClose, "pasteCodeblock",