diff --git a/manifest-beta.json b/manifest-beta.json index 881453d7..96cfc50b 100644 --- a/manifest-beta.json +++ b/manifest-beta.json @@ -1,7 +1,7 @@ { "id": "obsidian-excalidraw-plugin", "name": "Excalidraw", - "version": "2.23.11", + "version": "2.23.12", "minAppVersion": "1.8.7", "description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.", "author": "Zsolt Viczian", diff --git a/manifest.json b/manifest.json index 42fa341b..95d23193 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "obsidian-excalidraw-plugin", "name": "Excalidraw", - "version": "2.23.11", + "version": "2.23.12", "minAppVersion": "1.8.7", "description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.", "author": "Zsolt Viczian", diff --git a/src/core/main.ts b/src/core/main.ts index 636ae9e4..485b3875 100644 --- a/src/core/main.ts +++ b/src/core/main.ts @@ -10,7 +10,6 @@ import { ViewState, ViewStateResult, Notice, - request, MetadataCache, Workspace, TAbstractFile, @@ -28,7 +27,6 @@ import { FRONTMATTER, JSON_parse, SCRIPT_INSTALL_CODEBLOCK, - SCRIPT_INSTALL_FOLDER, EXPORT_TYPES, EXPORT_IMG_ICON_NAME, EXPORT_IMG_ICON, @@ -61,7 +59,6 @@ import { createOrOverwriteFile, fileShouldDefaultAsExcalidraw, getDrawingFilename, - getIMGFilename, getNewUniqueFilepath, } from "../utils/fileUtils"; import { @@ -90,7 +87,6 @@ import { import { FieldSuggester } from "../shared/Suggesters/FieldSuggester"; import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes"; import { DeviceType, Packages } from "../types/types"; -import { RemoteDirectoryInfo } from "../types/githubTypes"; import { PaneTarget, PreviewImageType } from "../types/utilTypes"; import { emulateCTRLClickForLinks, @@ -132,11 +128,8 @@ import { encryptPersistedAPIKeys, } from "src/utils/settingsKeyObfuscation"; import { URLs } from "src/constants/safeUrls"; -import { - hideElement, - setButtonBgColor, - showElement, -} from "src/utils/styleUtils"; +import { hideElement, setButtonBgColor } from "src/utils/styleUtils"; +import { installButton } from "src/utils/scriptLibraryUtils"; declare const PLUGIN_VERSION: string; declare const INITIAL_TIMESTAMP: number; @@ -1285,189 +1278,20 @@ export default class ExcalidrawPlugin extends Plugin { } source = source.trim(); - el.createEl("button", null, async (button) => { - const setButtonText = ( - text: "CHECKING" | "INSTALL" | "UPTODATE" | "UPDATE" | "ERROR", - ) => { - if (button2) { - hideElement(button2); - } - switch (text) { - case "CHECKING": - button.setText(t("CHECKING_SCRIPT")); - setButtonBgColor(button, "normal"); - break; - case "INSTALL": - button.setText(t("INSTALL_SCRIPT")); - setButtonBgColor(button, "accent"); - break; - case "UPTODATE": - button.setText(t("UPTODATE_SCRIPT")); - setButtonBgColor(button, "normal"); - break; - case "UPDATE": - button.setText(t("UPDATE_SCRIPT")); - setButtonBgColor(button, "success"); - if (button2) { - showElement(button2); - } - break; - case "ERROR": - button.setText(t("UNABLETOCHECK_SCRIPT")); - setButtonBgColor(button, "normal"); - break; - } - }; - button.addClass("mod-muted"); - let decodedURI = source; - try { - decodedURI = decodeURI(source); - } catch (e) { - errorlog({ - where: - "ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick", - source, - error: e, - }); - } - const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1); - const folder = `${this.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`; - const downloaded = this.app.vault - .getFiles() - .filter((f) => f.path.startsWith(folder) && f.name === fname) - .sort((a, b) => (a.path > b.path ? 1 : -1)); - let scriptFile = downloaded[0]; - const scriptPath = scriptFile?.path ?? `${folder}/${fname}`; - const svgPath = getIMGFilename(scriptPath, "svg"); - let svgFile = this.app.vault.getFileByPath(svgPath); - setButtonText(scriptFile ? "CHECKING" : "INSTALL"); - button.onclick = async () => { - const download = async ( - url: string, - file: TFile, - localPath: string, - ): Promise => { - const data = await request({ url }); - if (!data || data.startsWith("404: Not Found")) { - return null; - } - return await createOrOverwriteFile( - this.app, - file?.path ?? localPath, - data, - ); - }; - - try { - scriptFile = await download(source, scriptFile, scriptPath); - if (!scriptFile) { - setButtonText("ERROR"); - throw "File not found"; - } - svgFile = await download( - getIMGFilename(source, "svg"), - svgFile, - svgPath, - ); - setButtonText("UPTODATE"); - if (Object.keys(this.scriptEngine.scriptIconMap).length === 0) { - this.scriptEngine.loadScripts(); - } - const restartSidepanelTabIfActive = async () => { - if (!this.scriptEngine || !(scriptFile instanceof TFile)) { - return; - } - const scriptName = this.scriptEngine.getScriptName(scriptFile); - const spView = ExcalidrawSidepanelView.getExisting(false); - if ( - !spView || - !scriptName || - !spView.getTabByScript(scriptName) - ) { - return; - } - try { - await spView.restartTabForScript(scriptName); - } catch (error) { - errorlog({ - where: - "ExcalidrawPlugin.registerInstallCodeblockProcessor.restartSidepanelTab", - error, - scriptName, - }); - } - }; - await restartSidepanelTabIfActive(); - new Notice(`Installed: ${scriptFile.basename}`); - } catch (e) { - new Notice(`Error installing script: ${fname}`); - errorlog({ - where: - "ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick", - error: e, - }); - } - }; - if (button2) { - button2.onclick = button.onclick; - } - - //check modified date on github - //https://superuser.com/questions/1406875/how-to-get-the-latest-commit-date-of-a-file-from-a-given-github-reposotiry - if (!scriptFile || !(scriptFile instanceof TFile)) { - return; - } - - const files = new Map(); - JSON.parse( - await request({ - url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON, - }), - ).forEach((f: RemoteDirectoryInfo) => files.set(f.fname, f.mtime)); - - const checkModifyDate = ( - gitFilename: string, - file: TFile, - ): "ERROR" | "UPDATE" | "UPTODATE" => { - if (files.size === 0 || !files.has(gitFilename)) { - //setButtonText("ERROR"); - return "ERROR"; - } - const mtime = files.get(gitFilename); - if (!file || mtime > file.stat.mtime) { - //setButtonText("UPDATE"); - return "UPDATE"; - } - return "UPTODATE"; - }; - - const scriptButtonText = checkModifyDate(fname, scriptFile); - const svgButtonText = checkModifyDate( - getIMGFilename(fname, "svg"), - !svgFile || !(svgFile instanceof TFile) ? null : svgFile, - ); - - setButtonText( - scriptButtonText === "UPTODATE" && svgButtonText === "UPTODATE" - ? "UPTODATE" - : scriptButtonText === "UPTODATE" && svgButtonText === "ERROR" - ? "UPTODATE" - : scriptButtonText === "ERROR" - ? "ERROR" - : scriptButtonText === "UPDATE" || svgButtonText === "UPDATE" - ? "UPDATE" - : "UPTODATE", - ); + el.createEl("button", null, (button) => { + void installButton(this, button, button2, source); }); }; this.registerMarkdownCodeBlockProcessor( SCRIPT_INSTALL_CODEBLOCK, async (source, el) => { - el.addEventListener(RERENDER_EVENT, async (e) => { - e.stopPropagation(); - el.empty(); - await codeblockProcessor(source, el); + el.addEventListener(RERENDER_EVENT, (e) => { + void (async () => { + e.stopPropagation(); + el.empty(); + await codeblockProcessor(source, el); + })(); }); await codeblockProcessor(source, el); }, @@ -1663,7 +1487,7 @@ export default class ExcalidrawPlugin extends Plugin { if (markdownViewLoaded) { const leaf = this; - window.setTimeout(async () => { + window.setTimeout(() => { if ( !leaf || !leaf.view || diff --git a/src/core/managers/CommandManager.ts b/src/core/managers/CommandManager.ts index 1cde3ca0..be386dc0 100644 --- a/src/core/managers/CommandManager.ts +++ b/src/core/managers/CommandManager.ts @@ -1064,8 +1064,9 @@ export class CommandManager { if (view) { this.insertLinkDialog.start( view.file.path, - (markdownlink: string, path: string, alias: string) => - view.addLink(markdownlink, path, alias), + (markdownlink: string, path: string, alias: string) => { + void view.addLink(markdownlink, path, alias); + }, ); return true; } @@ -1085,8 +1086,9 @@ export class CommandManager { const view = this.app.workspace.getActiveViewOfType(ExcalidrawView); if (view) { this.insertCommandDialog.start( - (text: string, fontFamily?: 1 | 2 | 3 | 4, save?: boolean) => - view.addText(text, fontFamily, save), + (text: string, fontFamily?: 1 | 2 | 3 | 4, save?: boolean) => { + void view.addText(text, fontFamily, save); + }, ); return true; } diff --git a/src/core/managers/FileManager.ts b/src/core/managers/FileManager.ts index af812c12..d1c037ae 100644 --- a/src/core/managers/FileManager.ts +++ b/src/core/managers/FileManager.ts @@ -390,20 +390,22 @@ export class PluginFileManager { "my-library", "filename, leave blank to cancel action", ); - void prompt.openAndGetValue(async (filename: string) => { - if (!filename) { - return; - } - filename = `${filename}.excalidrawlib`; - const folderpath = normalizePath(this.settings.folder); - await checkAndCreateFolder(folderpath); //create folder if it does not exist - const fname = getNewUniqueFilepath( - this.app.vault, - filename, - folderpath, - ); - await this.app.vault.create(fname, this.settings.library); - new Notice(`Exported library to ${fname}`, 6000); + void prompt.openAndGetValue((filename: string) => { + void (async () => { + if (!filename) { + return; + } + filename = `${filename}.excalidrawlib`; + const folderpath = normalizePath(this.settings.folder); + await checkAndCreateFolder(folderpath); //create folder if it does not exist + const fname = getNewUniqueFilepath( + this.app.vault, + filename, + folderpath, + ); + await this.app.vault.create(fname, this.settings.library); + new Notice(`Exported library to ${fname}`, 6000); + })(); }); return; } @@ -612,81 +614,83 @@ export class PluginFileManager { public async modifyEventHandler(file: TFile) { const excalidrawViews = getExcalidrawViews(this.app); - excalidrawViews.forEach(async (excalidrawView) => { - if (excalidrawView.semaphores?.viewunload) { - return; - } - if ( - excalidrawView.file && - (excalidrawView.file.path === file.path || - (file.extension === "excalidraw" && - `${file.path.substring( - 0, - file.path.lastIndexOf(".excalidraw"), - )}.md` === excalidrawView.file.path)) - ) { - if (excalidrawView.semaphores?.preventReload) { - excalidrawView.semaphores.preventReload = false; + excalidrawViews.forEach((excalidrawView) => { + void (async () => { + if (excalidrawView.semaphores?.viewunload) { return; } - - // Avoid synchronizing or reloading if the user hasn't interacted with the file for 5 minutes. - // This prevents complex sync issues when multiple remote changes occur outside an active collaboration session. - - // The following logic handles a rare edge case where: - // 1. The user opens an Excalidraw file. - // 2. Immediately splits the view without saving Excalidraw (since no changes were made). - // 3. Switches the new split view to Markdown, edits the file, and quickly returns to Excalidraw. - // 4. The "modify" event may fire while Excalidraw is active, triggering an unwanted reload and zoom reset. - - // To address this: - // - We check if the user is currently editing the Markdown version of the Excalidraw file in a split view. - // - As a heuristic, we also check for recent leaf switches. - // This is not perfectly accurate (e.g., rapid switching between views within a few seconds), - // but it is sufficient to avoid most edge cases without introducing complexity. - - // Edge case impact: - // - In extremely rare situations, an update arriving within the "recent switch" timeframe (e.g., from Obsidian Sync) - // might not trigger a reload. This is unlikely and an acceptable trade-off for better user experience. - const activeView = this.app.workspace.activeLeaf.view; - const isEditingMarkdownSideInSplitView = - (activeView !== excalidrawView && - activeView instanceof MarkdownView && - activeView.file === excalidrawView.file) || - (activeView === excalidrawView && - this.plugin.isRecentSplitViewSwitch()); - if ( - !isEditingMarkdownSideInSplitView && - excalidrawView.lastSaveTimestamp + 300000 < Date.now() + excalidrawView.file && + (excalidrawView.file.path === file.path || + (file.extension === "excalidraw" && + `${file.path.substring( + 0, + file.path.lastIndexOf(".excalidraw"), + )}.md` === excalidrawView.file.path)) ) { - await excalidrawView.reload(true, excalidrawView.file); - return; - } - if (file.extension === "md") { - if (excalidrawView.semaphores?.embeddableIsEditingSelf) { + if (excalidrawView.semaphores?.preventReload) { + excalidrawView.semaphores.preventReload = false; return; } - const inData = new ExcalidrawData(this.plugin); - const data = await this.app.vault.read(file); - await inData.loadData(data, file, getTextMode(data)); - await excalidrawView.synchronizeWithData(inData); - inData.destroy(); - if (excalidrawView?.isDirty()) { - if ( - excalidrawView.autosaveTimer && - excalidrawView.autosaveFunction - ) { - window.clearTimeout(excalidrawView.autosaveTimer); + + // Avoid synchronizing or reloading if the user hasn't interacted with the file for 5 minutes. + // This prevents complex sync issues when multiple remote changes occur outside an active collaboration session. + + // The following logic handles a rare edge case where: + // 1. The user opens an Excalidraw file. + // 2. Immediately splits the view without saving Excalidraw (since no changes were made). + // 3. Switches the new split view to Markdown, edits the file, and quickly returns to Excalidraw. + // 4. The "modify" event may fire while Excalidraw is active, triggering an unwanted reload and zoom reset. + + // To address this: + // - We check if the user is currently editing the Markdown version of the Excalidraw file in a split view. + // - As a heuristic, we also check for recent leaf switches. + // This is not perfectly accurate (e.g., rapid switching between views within a few seconds), + // but it is sufficient to avoid most edge cases without introducing complexity. + + // Edge case impact: + // - In extremely rare situations, an update arriving within the "recent switch" timeframe (e.g., from Obsidian Sync) + // might not trigger a reload. This is unlikely and an acceptable trade-off for better user experience. + const activeView = this.app.workspace.activeLeaf.view; + const isEditingMarkdownSideInSplitView = + (activeView !== excalidrawView && + activeView instanceof MarkdownView && + activeView.file === excalidrawView.file) || + (activeView === excalidrawView && + this.plugin.isRecentSplitViewSwitch()); + + if ( + !isEditingMarkdownSideInSplitView && + excalidrawView.lastSaveTimestamp + 300000 < Date.now() + ) { + await excalidrawView.reload(true, excalidrawView.file); + return; + } + if (file.extension === "md") { + if (excalidrawView.semaphores?.embeddableIsEditingSelf) { + return; } - if (excalidrawView.autosaveFunction) { - await excalidrawView.autosaveFunction(); + const inData = new ExcalidrawData(this.plugin); + const data = await this.app.vault.read(file); + await inData.loadData(data, file, getTextMode(data)); + await excalidrawView.synchronizeWithData(inData); + inData.destroy(); + if (excalidrawView?.isDirty()) { + if ( + excalidrawView.autosaveTimer && + excalidrawView.autosaveFunction + ) { + window.clearTimeout(excalidrawView.autosaveTimer); + } + if (excalidrawView.autosaveFunction) { + await excalidrawView.autosaveFunction(); + } } + } else { + await excalidrawView.reload(true, excalidrawView.file); } - } else { - await excalidrawView.reload(true, excalidrawView.file); } - } + })(); }); } diff --git a/src/core/managers/MarkdownPostProcessor.ts b/src/core/managers/MarkdownPostProcessor.ts index 913639bc..5f5a7bdd 100644 --- a/src/core/managers/MarkdownPostProcessor.ts +++ b/src/core/managers/MarkdownPostProcessor.ts @@ -672,34 +672,36 @@ const createImgElement = async ( timer = null; }); eventElement.addEventListener("dblclick", clickEvent); - eventElement.addEventListener(RERENDER_EVENT, async (e) => { + eventElement.addEventListener(RERENDER_EVENT, (e) => { e.stopPropagation(); - const parent = imgOrDiv.parentElement; - const imgMaxWidth = imgOrDiv.style.maxWidth; - const imgMaxHeigth = imgOrDiv.style.maxHeight; - const fileSource = imgOrDiv.getAttribute("fileSource"); - const onCanvas = imgOrDiv.getAttribute("onCanvas") === "true"; - const newImg = await createImgElement( - { - fname: fileSource, - fwidth: imgOrDiv.getAttribute("w"), - fheight: imgOrDiv.getAttribute("h"), - imgstyle: [...Array.from(imgOrDiv.classList)], - }, - onCanvas, - ); - if (!newImg) { - return; - } - parent.empty(); - if (!onCanvas) { - setStyle(newImg, { - maxHeight: imgMaxHeigth, - maxWidth: imgMaxWidth, - }); - } - newImg.setAttribute("fileSource", fileSource); - parent.append(newImg); + void (async () => { + const parent = imgOrDiv.parentElement; + const imgMaxWidth = imgOrDiv.style.maxWidth; + const imgMaxHeigth = imgOrDiv.style.maxHeight; + const fileSource = imgOrDiv.getAttribute("fileSource"); + const onCanvas = imgOrDiv.getAttribute("onCanvas") === "true"; + const newImg = await createImgElement( + { + fname: fileSource, + fwidth: imgOrDiv.getAttribute("w"), + fheight: imgOrDiv.getAttribute("h"), + imgstyle: [...Array.from(imgOrDiv.classList)], + }, + onCanvas, + ); + if (!newImg) { + return; + } + parent.empty(); + if (!onCanvas) { + setStyle(newImg, { + maxHeight: imgMaxHeigth, + maxWidth: imgMaxWidth, + }); + } + newImg.setAttribute("fileSource", fileSource); + parent.append(newImg); + })(); }); const cssClasses = getFileCSSClasses(attr.file); cssClasses.forEach((cssClass) => { @@ -1132,11 +1134,13 @@ const tmpObsidianWYSIWYG = async ( if (timer) { window.clearTimeout(timer); } - timer = window.setTimeout(async () => { + timer = window.setTimeout(() => { timer = null; internalEmbedDiv.empty(); - const imgDiv = await processInternalEmbed(internalEmbedDiv, file); - internalEmbedDiv.appendChild(imgDiv); + void (async () => { + const imgDiv = await processInternalEmbed(internalEmbedDiv, file); + internalEmbedDiv.appendChild(imgDiv); + })(); }, 500); }; const observer = DEBUGGING @@ -1322,7 +1326,7 @@ const legacyExcalidrawPopoverObserverFn: MutationCallback = async (m) => { fheight: null, imgstyle: ["excalidraw-svg"], }); - const div = createDiv("", async (el) => { + const div = createDiv("", (el) => { el.appendChild(img); el.setAttribute("src", file.path); el.onClickEvent((ev) => { diff --git a/src/core/settings.ts b/src/core/settings.ts index 9fd6e0aa..3975634b 100644 --- a/src/core/settings.ts +++ b/src/core/settings.ts @@ -2291,7 +2291,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { .setDesc(fragWithHTML(description)) .addDropdown((dropdown) => { optionValues.forEach((value) => dropdown.addOption(value, value)); - return dropdown.setValue(selectedValue).onChange(async (value) => { + return dropdown.setValue(selectedValue).onChange((value) => { if (kind === "text") { selectedTextModelConfig = value; this.plugin.settings.aiDefaultTextModel = value; @@ -2396,7 +2396,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab { text .setPlaceholder(placeholder) .setValue(getter().toString()) - .onChange(async (value) => { + .onChange((value) => { const intVal = parseInt(value, 10); if (isNaN(intVal) && value !== "") { text.setValue(getter().toString()); diff --git a/src/shared/Dialogs/ExportDialog.ts b/src/shared/Dialogs/ExportDialog.ts index 31484edb..17432941 100644 --- a/src/shared/Dialogs/ExportDialog.ts +++ b/src/shared/Dialogs/ExportDialog.ts @@ -427,16 +427,18 @@ export class ExportDialog extends Modal { bPNG.onclick = () => { if (isScreenshot) { //allow dialog to close before taking screenshot - window.setTimeout(async () => { - const png = await captureScreenshot(this.view, { - zoom: this.scale, - margin: this.padding, - selectedOnly: this.isSelectedOnly, - theme: this.theme, - }); - if (png) { - exportPNG(png, this.view.file.basename); - } + window.setTimeout(() => { + void (async () => { + const png = await captureScreenshot(this.view, { + zoom: this.scale, + margin: this.padding, + selectedOnly: this.isSelectedOnly, + theme: this.theme, + }); + if (png) { + exportPNG(png, this.view.file.basename); + } + })(); }); } else { void this.view.exportPNG(this.embedScene, this.isSelectedOnly); @@ -452,22 +454,24 @@ export class ExportDialog extends Modal { bPNGVault.onclick = () => { if (isScreenshot) { //allow dialog to close before taking screenshot - window.setTimeout(async () => { - const png = await captureScreenshot(this.view, { - zoom: this.scale, - margin: this.padding, - selectedOnly: this.isSelectedOnly, - theme: this.theme, - }); - if (png) { - void exportImageToFile( - this.view, - getIMGFilename(this.view.file.path, "png"), - png, - ".png", - ); - } - }); + window.setTimeout(() => { + void (async () => { + const png = await captureScreenshot(this.view, { + zoom: this.scale, + margin: this.padding, + selectedOnly: this.isSelectedOnly, + theme: this.theme, + }); + if (png) { + void exportImageToFile( + this.view, + getIMGFilename(this.view.file.path, "png"), + png, + ".png", + ); + } + })(); + }, 0); } else { void this.view.savePNG({ scene: this.view.getScene(this.isSelectedOnly), @@ -483,16 +487,18 @@ export class ExportDialog extends Modal { bPNGClipboard.onclick = async () => { if (isScreenshot) { //allow dialog to close before taking screenshot - window.setTimeout(async () => { - const png = await captureScreenshot(this.view, { - zoom: this.scale, - margin: this.padding, - selectedOnly: this.isSelectedOnly, - theme: this.theme, - }); - if (png) { - await exportPNGToClipboard(png); - } + window.setTimeout(() => { + void (async () => { + const png = await captureScreenshot(this.view, { + zoom: this.scale, + margin: this.padding, + selectedOnly: this.isSelectedOnly, + theme: this.theme, + }); + if (png) { + await exportPNGToClipboard(png); + } + })(); }); } else { await this.view.exportPNGToClipboard( diff --git a/src/shared/Dialogs/FloatingModal.ts b/src/shared/Dialogs/FloatingModal.ts index 0f812cad..04828740 100644 --- a/src/shared/Dialogs/FloatingModal.ts +++ b/src/shared/Dialogs/FloatingModal.ts @@ -246,7 +246,9 @@ export class FloatingModal extends Modal { try { // Release modal scope so focus and key handling can return to the workspace. this.app.keymap.popScope(this.scope); - } catch {} + } catch (error) { + console.log(error); + } // prevent automatic selection / focus restoration this.shouldRestoreSelection = false; } @@ -324,7 +326,9 @@ export class FloatingModal extends Modal { ) { try { this.previousActive.focus({ preventScroll: true }); - } catch {} + } catch (error) { + console.log(error); + } } const { modalEl } = this; // Clean up event listeners diff --git a/src/shared/Dialogs/Messages.ts b/src/shared/Dialogs/Messages.ts index 48ca60a1..7e2219f8 100644 --- a/src/shared/Dialogs/Messages.ts +++ b/src/shared/Dialogs/Messages.ts @@ -16,6 +16,10 @@ export const RELEASE_NOTES: { [k: string]: string } = { I build this plugin as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}). Want to master Excalidraw? Join [Excalidraw Mastery](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}). If you find it valuable, say "Thank you", and
Buy Me a Coffee at ko-fi.com
+`, + "2.23.12": ` + ## Fixed + - Code scanner error `, "2.23.11": ` ## Fixed diff --git a/src/shared/Dialogs/UIModeSettings.ts b/src/shared/Dialogs/UIModeSettings.ts index fab5e4e2..1bae3faa 100644 --- a/src/shared/Dialogs/UIModeSettings.ts +++ b/src/shared/Dialogs/UIModeSettings.ts @@ -27,7 +27,9 @@ export class UIModeSettings extends Modal { this.contentEl, this.plugin.settings, this.app, - () => this.applySettingsUpdate(), + () => { + void this.applySettingsUpdate(); + }, () => this.close(), ).render(); } diff --git a/src/shared/ExcalidrawData.ts b/src/shared/ExcalidrawData.ts index 35972aea..d2300b81 100644 --- a/src/shared/ExcalidrawData.ts +++ b/src/shared/ExcalidrawData.ts @@ -752,7 +752,9 @@ export class ExcalidrawData { .forEach((textEl: Mutable) => { textEl.containerId = null; }); // log({message:"cleanup",textEl})}); - } catch {} + } catch (error) { + console.log(error); + } } /** diff --git a/src/utils/customEmbeddableUtils.ts b/src/utils/customEmbeddableUtils.ts index 8c349b7c..305cd91b 100644 --- a/src/utils/customEmbeddableUtils.ts +++ b/src/utils/customEmbeddableUtils.ts @@ -155,7 +155,9 @@ export function predictViewType(app: App, file: TFile): string { if (typeof vt === "string" && vt) { return vt; } - } catch {} + } catch (error) { + console.log(error); + } } } // 2) Try extension mapping from registry @@ -169,7 +171,9 @@ export function predictViewType(app: App, file: TFile): string { if (typeof vt === "string" && vt) { return vt; } - } catch {} + } catch (error) { + console.log(error); + } } } diff --git a/src/utils/scriptLibraryUtils.ts b/src/utils/scriptLibraryUtils.ts new file mode 100644 index 00000000..a611281a --- /dev/null +++ b/src/utils/scriptLibraryUtils.ts @@ -0,0 +1,183 @@ +import { TFile, Notice, request } from "obsidian"; +import { SCRIPT_INSTALL_FOLDER } from "src/constants/constants"; +import { URLs } from "src/constants/safeUrls"; +import { t } from "src/lang/helpers"; +import { RemoteDirectoryInfo } from "src/types/githubTypes"; +import { ExcalidrawSidepanelView } from "src/view/sidepanel/Sidepanel"; +import { errorlog } from "./coreUtils"; +import { getIMGFilename, createOrOverwriteFile } from "./fileUtils"; +import { hideElement, setButtonBgColor, showElement } from "./styleUtils"; +import ExcalidrawPlugin from "src/core/main"; + +export const installButton = async ( + plugin: ExcalidrawPlugin, + button: HTMLButtonElement, + button2: HTMLButtonElement, + source: string, +) => { + const setButtonText = ( + text: "CHECKING" | "INSTALL" | "UPTODATE" | "UPDATE" | "ERROR", + ) => { + if (button2) { + hideElement(button2); + } + switch (text) { + case "CHECKING": + button.setText(t("CHECKING_SCRIPT")); + setButtonBgColor(button, "normal"); + break; + case "INSTALL": + button.setText(t("INSTALL_SCRIPT")); + setButtonBgColor(button, "accent"); + break; + case "UPTODATE": + button.setText(t("UPTODATE_SCRIPT")); + setButtonBgColor(button, "normal"); + break; + case "UPDATE": + button.setText(t("UPDATE_SCRIPT")); + setButtonBgColor(button, "success"); + if (button2) { + showElement(button2); + } + break; + case "ERROR": + button.setText(t("UNABLETOCHECK_SCRIPT")); + setButtonBgColor(button, "normal"); + break; + } + }; + + button.addClass("mod-muted"); + let decodedURI = source; + try { + decodedURI = decodeURI(source); + } catch (e) { + errorlog({ + where: + "ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick", + source, + error: e, + }); + } + const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1); + const folder = `${plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`; + const downloaded = plugin.app.vault + .getFiles() + .filter((f) => f.path.startsWith(folder) && f.name === fname) + .sort((a, b) => (a.path > b.path ? 1 : -1)); + let scriptFile = downloaded[0]; + const scriptPath = scriptFile?.path ?? `${folder}/${fname}`; + const svgPath = getIMGFilename(scriptPath, "svg"); + let svgFile = plugin.app.vault.getFileByPath(svgPath); + setButtonText(scriptFile ? "CHECKING" : "INSTALL"); + button.onclick = async () => { + const download = async ( + url: string, + file: TFile, + localPath: string, + ): Promise => { + const data = await request({ url }); + if (!data || data.startsWith("404: Not Found")) { + return null; + } + return await createOrOverwriteFile( + plugin.app, + file?.path ?? localPath, + data, + ); + }; + + try { + scriptFile = await download(source, scriptFile, scriptPath); + if (!scriptFile) { + setButtonText("ERROR"); + throw "File not found"; + } + svgFile = await download(getIMGFilename(source, "svg"), svgFile, svgPath); + setButtonText("UPTODATE"); + if (Object.keys(plugin.scriptEngine.scriptIconMap).length === 0) { + plugin.scriptEngine.loadScripts(); + } + const restartSidepanelTabIfActive = async () => { + if (!plugin.scriptEngine || !(scriptFile instanceof TFile)) { + return; + } + const scriptName = plugin.scriptEngine.getScriptName(scriptFile); + const spView = ExcalidrawSidepanelView.getExisting(false); + if (!spView || !scriptName || !spView.getTabByScript(scriptName)) { + return; + } + try { + await spView.restartTabForScript(scriptName); + } catch (error) { + errorlog({ + where: + "ExcalidrawPlugin.registerInstallCodeblockProcessor.restartSidepanelTab", + error, + scriptName, + }); + } + }; + await restartSidepanelTabIfActive(); + new Notice(`Installed: ${scriptFile.basename}`); + } catch (e) { + new Notice(`Error installing script: ${fname}`); + errorlog({ + where: + "ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick", + error: e, + }); + } + }; + if (button2) { + button2.onclick = button.onclick; + } + + //check modified date on github + //https://superuser.com/questions/1406875/how-to-get-the-latest-commit-date-of-a-file-from-a-given-github-reposotiry + if (!scriptFile || !(scriptFile instanceof TFile)) { + return; + } + + const files = new Map(); + JSON.parse( + await request({ + url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON, + }), + ).forEach((f: RemoteDirectoryInfo) => files.set(f.fname, f.mtime)); + + const checkModifyDate = ( + gitFilename: string, + file: TFile, + ): "ERROR" | "UPDATE" | "UPTODATE" => { + if (files.size === 0 || !files.has(gitFilename)) { + //setButtonText("ERROR"); + return "ERROR"; + } + const mtime = files.get(gitFilename); + if (!file || mtime > file.stat.mtime) { + //setButtonText("UPDATE"); + return "UPDATE"; + } + return "UPTODATE"; + }; + + const scriptButtonText = checkModifyDate(fname, scriptFile); + const svgButtonText = checkModifyDate( + getIMGFilename(fname, "svg"), + !svgFile || !(svgFile instanceof TFile) ? null : svgFile, + ); + + setButtonText( + scriptButtonText === "UPTODATE" && svgButtonText === "UPTODATE" + ? "UPTODATE" + : scriptButtonText === "UPTODATE" && svgButtonText === "ERROR" + ? "UPTODATE" + : scriptButtonText === "ERROR" + ? "ERROR" + : scriptButtonText === "UPDATE" || svgButtonText === "UPDATE" + ? "UPDATE" + : "UPTODATE", + ); +}; diff --git a/src/utils/styleUtils.ts b/src/utils/styleUtils.ts index 8622d569..9dcca919 100644 --- a/src/utils/styleUtils.ts +++ b/src/utils/styleUtils.ts @@ -63,7 +63,7 @@ export const removeStyle = ( } for (const prop of properties) { - const propStr = prop as string; + const propStr = prop; if (propStr.startsWith("--")) { element.style.removeProperty(propStr); diff --git a/src/view/ExcalidrawView.ts b/src/view/ExcalidrawView.ts index 6fc9ba10..5b9db8a6 100644 --- a/src/view/ExcalidrawView.ts +++ b/src/view/ExcalidrawView.ts @@ -717,8 +717,8 @@ export default class ExcalidrawView const collected: Record = {}; let resolved = false; - await new Promise(async (resolve) => { - await loader.loadSceneFiles({ + void (await new Promise(async (resolve) => { + void (await loader.loadSceneFiles({ excalidrawData: this.excalidrawData, addFiles: ( files: FileData[], @@ -737,8 +737,8 @@ export default class ExcalidrawView }, depth: 0, isThemeChange: true, - }); - }); + })); + })); return Object.keys(collected).length ? collected : null; } @@ -1181,10 +1181,9 @@ export default class ExcalidrawView const data = this.lastSavedData; //if the scene is empty, do not save to BAK (this could be due to a crash when the BAK should not be updated) if (scene && scene.elements && scene.elements.length > 0) { - window.setTimeout( - () => getImageCache().addBAKToCache(path, data), - 50, - ); + window.setTimeout(() => { + void getImageCache().addBAKToCache(path, data); + }, 50); } triggerReload = this.lastSaveTimestamp === this.file.stat.mtime && @@ -4256,81 +4255,87 @@ export default class ExcalidrawView "", "Leave blank to cancel this action", ); - void prompt.openAndGetValue(async (filename: string) => { - if (!filename) { - return; - } - filename = `${filename}.md`; - const folderpath = splitFolderAndFilename(this.file.path).folderpath; - await checkAndCreateFolder(folderpath); //create folder if it does not exist - const fname = getNewUniqueFilepath(this.app.vault, filename, folderpath); - const text: string[] = []; - if (containerElement && containerElement.link) { - text.push(containerElement.link); - } - text.push(textElement.rawText); - const f = await createOrOverwriteFile(this.app, fname, text.join("\n")); - if (f) { - const ea: ExcalidrawAutomate = getEA(this); - const elements = containerElement - ? [textElement, containerElement] - : [textElement]; - ea.copyViewElementsToEAforEditing(elements); - ea.getElements().forEach((el) => (el.isDeleted = true)); - const [x, y, w, h] = containerElement - ? [ - containerElement.x, - containerElement.y, - containerElement.width, - containerElement.height, - ] - : [textElement.x, textElement.y, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE]; - const id = ea.addEmbeddable(x, y, w, h, undefined, f); - if (containerElement) { - const props: (keyof ExcalidrawElement)[] = [ - "backgroundColor", - "fillStyle", - "roughness", - "roundness", - "strokeColor", - "strokeStyle", - "strokeWidth", - ]; - props.forEach((prop) => { - const element = ea.getElement(id); - if (prop in element) { - const mutableElement = element as Mutable; - switch (prop) { - case "backgroundColor": - mutableElement.backgroundColor = - containerElement.backgroundColor; - break; - case "fillStyle": - mutableElement.fillStyle = containerElement.fillStyle; - break; - case "roughness": - mutableElement.roughness = containerElement.roughness; - break; - case "roundness": - mutableElement.roundness = containerElement.roundness; - break; - case "strokeColor": - mutableElement.strokeColor = containerElement.strokeColor; - break; - case "strokeStyle": - mutableElement.strokeStyle = containerElement.strokeStyle; - break; - case "strokeWidth": - mutableElement.strokeWidth = containerElement.strokeWidth; - break; - } - } - }); + void prompt.openAndGetValue((filename: string) => { + void (async () => { + if (!filename) { + return; } - ea.getElement(id); - await ea.addElementsToView(); - ea.destroy(); - } + filename = `${filename}.md`; + const folderpath = splitFolderAndFilename(this.file.path).folderpath; + await checkAndCreateFolder(folderpath); //create folder if it does not exist + const fname = getNewUniqueFilepath( + this.app.vault, + filename, + folderpath, + ); + const text: string[] = []; + if (containerElement && containerElement.link) { + text.push(containerElement.link); + } + text.push(textElement.rawText); + const f = await createOrOverwriteFile(this.app, fname, text.join("\n")); + if (f) { + const ea: ExcalidrawAutomate = getEA(this); + const elements = containerElement + ? [textElement, containerElement] + : [textElement]; + ea.copyViewElementsToEAforEditing(elements); + ea.getElements().forEach((el) => (el.isDeleted = true)); + const [x, y, w, h] = containerElement + ? [ + containerElement.x, + containerElement.y, + containerElement.width, + containerElement.height, + ] + : [textElement.x, textElement.y, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE]; + const id = ea.addEmbeddable(x, y, w, h, undefined, f); + if (containerElement) { + const props: (keyof ExcalidrawElement)[] = [ + "backgroundColor", + "fillStyle", + "roughness", + "roundness", + "strokeColor", + "strokeStyle", + "strokeWidth", + ]; + props.forEach((prop) => { + const element = ea.getElement(id); + if (prop in element) { + const mutableElement = element as Mutable; + switch (prop) { + case "backgroundColor": + mutableElement.backgroundColor = + containerElement.backgroundColor; + break; + case "fillStyle": + mutableElement.fillStyle = containerElement.fillStyle; + break; + case "roughness": + mutableElement.roughness = containerElement.roughness; + break; + case "roundness": + mutableElement.roundness = containerElement.roundness; + break; + case "strokeColor": + mutableElement.strokeColor = containerElement.strokeColor; + break; + case "strokeStyle": + mutableElement.strokeStyle = containerElement.strokeStyle; + break; + case "strokeWidth": + mutableElement.strokeWidth = containerElement.strokeWidth; + break; + } + } + }); + } + ea.getElement(id); + await ea.addElementsToView(); + ea.destroy(); + } + })(); }); } diff --git a/src/view/components/CustomEmbeddable.tsx b/src/view/components/CustomEmbeddable.tsx index 24ce1a01..ff559b84 100644 --- a/src/view/components/CustomEmbeddable.tsx +++ b/src/view/components/CustomEmbeddable.tsx @@ -284,7 +284,9 @@ function setupPdfViewEnhancements( setStyle(view.contentEl, { cursor: "grabbing", }); - } catch {} + } catch (error) { + console.log(error); + } }; const onPointerMove = (e: PointerEvent) => { @@ -320,7 +322,9 @@ function setupPdfViewEnhancements( setStyle(view.contentEl, { cursor: "", }); - } catch {} + } catch (error) { + console.log(error); + } window.removeEventListener("pointermove", onPointerMove, true); window.removeEventListener("pointerup", onPointerUp, true); window.removeEventListener("pointercancel", onPointerUp, true); @@ -386,10 +390,14 @@ function setupPdfViewEnhancements( // Cleanup existing handlers/observers try { pdfObserverRef.currentCleanup?.(); - } catch {} + } catch (error) { + console.log(error); + } try { pdfObserverRef.current?.disconnect(); - } catch {} + } catch (error) { + console.log(error); + } // Re-setup on next tick to allow DOM to settle window.setTimeout(() => { @@ -412,13 +420,19 @@ function setupPdfViewEnhancements( pdfObserverRef.currentCleanup = () => { try { prevCleanup?.(); - } catch {} + } catch (error) { + console.log(error); + } try { pdfObserverRef.current?.disconnect(); - } catch {} + } catch (error) { + console.log(error); + } try { detachObserver?.disconnect(); - } catch {} + } catch (error) { + console.log(error); + } detachObserver = null; }; } @@ -769,7 +783,9 @@ function RenderObsidianView({ // cleanup persistent mobile patch if active try { mobilePatchCleanupRef.current?.(); - } catch {} + } catch (error) { + console.log(error); + } mobilePatchCleanupRef.current = null; view.updateEmbeddableLeafRef(element.id); @@ -1195,7 +1211,9 @@ function RenderObsidianView({ // stop persistent observer when deactivated try { mobilePatchCleanupRef.current?.(); - } catch {} + } catch (error) { + console.log(error); + } mobilePatchCleanupRef.current = null; } }