Compare commits

...
Author SHA1 Message Date
zsviczian 542fcec6ac 2.28.0-beta.4 2026-09-24 22:30:49 +02:00
zsviczian a8182899b7 2.28.0-beta.3 2026-09-20 18:06:08 +02:00
zsviczian 9d5057dba7 updated excalidraw manifest with correct link 2026-09-20 14:36:40 +02:00
zsviczian 718f671109 ExcaliBrain patch compatiblity 2026-09-20 12:27:17 +02:00
zsviczian 6294305dd8 script store optimization, legacy script store removal 2026-09-20 06:38:53 +02:00
zsviczian add50b79d4 updated ea-scripting.md 2026-09-19 17:51:19 +02:00
20 changed files with 439 additions and 397 deletions

No files matched your search

+31 -3
View File
@@ -40,8 +40,24 @@ The repository already contains:
7. Copy the generated `.md` script and its preview SVG from `build/` into the Script Engine folder configured in Excalidraw settings. Run the script from an Excalidraw drawing.
> **Important:** files under `src/scripts/{slug}/` are development source files. In particular, `src/scripts/{slug}/main.ts` is **not** a script you can copy into Obsidian and run directly. After creating or changing a script, ask your coding agent to run `npm run build`, or run it yourself. The ready-to-run Script Engine artifact is generated under `build/{slug}/`.
The generated `.md` file contains executable JavaScript for the Excalidraw Script Engine; it is not an Obsidian plugin. If `.md` and `.js` versions with the same script name are both present, Excalidraw prefers the `.md` version.
### Keep your script workspace up to date
The template can update its shared tooling, Excalidraw Automate types, agent guidance, and build infrastructure without replacing your scripts. A good update sequence is:
```bash
npm run update-template:check
npm run update-template
npm install
npm run check
npm run build
```
Run `npm install` after `npm run update-template` because a template update may change `package.json` or `package-lock.json`. Then run the checks and rebuild your scripts before testing them in Obsidian.
## Why AI agents work so well for scripting
The workflow demonstrated in **[AI Scripting Superpowers](https://youtu.be/6BjhUyfS4iM)** is still the core idea:
@@ -75,11 +91,12 @@ Browse the Community Script Store for examples and inspiration before starting f
The template's authoring guidance handles the details, but these principles matter:
- Work in `src/scripts/{slug}/`; treat `build/` as generated output. Do not hand-edit the built script as your source of truth.
- Excalidraw scene elements are immutable; edit them through the Excalidraw Automate workbench and commit the result back to the view.
- The Script Engine injects `ea` and `utils`. Runtime Obsidian APIs are available through `ea.obsidian`.
- Scripts with UI or long-lived behavior need deliberate cleanup and lifecycle handling.
- Test cancellation, empty selections, undo/save behavior, view changes, and any mobile-specific UI on a physical mobile device.
- Run `npm run check` and `npm run build` before distributing a script.
- Run `npm run check` and `npm run build` before testing or distributing a changed script.
## Scripts are code
@@ -87,9 +104,20 @@ A script can change your drawing and can also work with files in your vault. Tre
## Share a script with the community
Community scripts are maintained in the central [Obsidian Excalidraw repository](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts). If you build something broadly useful, open a focused pull request with the script, its icon/preview, and its Script Store catalog entry.
Community scripts are maintained in the central [Obsidian Excalidraw repository](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts). Publish the **built** `.md` artifact, not `src/scripts/{slug}/main.ts`, together with its matching SVG icon/preview when applicable and an entry in `ea-scripts/script-store.json`.
For repository-specific publishing steps, see [ea-scripts/README.md](../ea-scripts/README.md).
The current Script Store workflow is:
```bash
npm run script-store:check
npm run script-store:build
```
`script-store:build` validates the catalog and updates `directory-info.json` only for script or icon files that actually changed. Do not hand-edit unrelated `mtime` values: existing timestamps are part of backward-compatible update detection.
`ea-scripts/index-new.md` is the frozen legacy catalog for older Excalidraw versions. Routine Script Store publishing should not modify it. New scripts are published through `script-store.json` unless a maintainer deliberately updates the legacy catalog separately.
For the repository-specific publishing rules and current compatibility notes, see [ea-scripts/README.md](../ea-scripts/README.md).
## More resources
+2 -2
View File
@@ -1,11 +1,11 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.28.0-beta.2",
"version": "2.28.0-beta.4",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
"authorUrl": "https://excalidraw-obsidian.online",
"authorUrl": "https://community.sketch-your-mind.com/em",
"fundingUrl": "https://ko-fi.com/zsolt",
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
"isDesktopOnly": false
+1 -1
View File
@@ -5,7 +5,7 @@
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
"authorUrl": "https://excalidraw-obsidian.online",
"authorUrl": "https://community.sketch-your-mind.com/em",
"fundingUrl": "https://ko-fi.com/zsolt",
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
"isDesktopOnly": false
+4 -4
View File
@@ -13,7 +13,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.137",
"@zsviczian/excalidraw": "0.18.139",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -5255,9 +5255,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.137",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.137.tgz",
"integrity": "sha512-Qua9UpBVxU/jOG3vAj/9hO+ZGejvtjk6grvsdt6z1j7c5rphu5IHZtceTdC11wm2wP+iTuMYTxBAvjvDOE0NIw==",
"version": "0.18.139",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.139.tgz",
"integrity": "sha512-3d31zicckBIK4VMyldgCLuPON5xCWNTxn0vF1r3FdlVbfLXI+OFdeq6Qog8aYO4IXN2W5XKdIF5Byzk17U4Aqg==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
+1 -1
View File
@@ -34,7 +34,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.137",
"@zsviczian/excalidraw": "0.18.139",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
-1
View File
@@ -247,7 +247,6 @@ export const ROUNDNESS = {
export const THEME_FILTER = "invert(93%) hue-rotate(180deg) saturate(1.25)";
export const URLFETCHTIMEOUT = 3000;
export const PLUGIN_ID = "obsidian-excalidraw-plugin";
export const SCRIPT_INSTALL_CODEBLOCK = "excalidraw-script-install";
export const SCRIPT_INSTALL_FOLDER = "Downloaded";
export const fileid = customAlphabet("1234567890abcdef", 40);
export const REG_LINKINDEX_INVALIDCHARS = /[<>:"\\|?*#]/g;
-5
View File
@@ -329,11 +329,6 @@ export const URL_REGISTRY = {
"https://community.sketch-your-mind.com/vtw",
UrlPurpose.SUPPORT,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD:
defineUrl(
getPluginRepositoryRawUrl("ea-scripts/index-new.md"),
UrlPurpose.APP_LOGIC,
),
WWW_W3SCHOOLS_COM_COLORS_DEFAULT_ASP: defineUrl(
"https://www.w3schools.com/colors/default.asp",
UrlPurpose.DOCS,
-53
View File
@@ -25,7 +25,6 @@ import {
FRONTMATTER_KEYS,
FRONTMATTER,
JSON_parse,
SCRIPT_INSTALL_CODEBLOCK,
EXPORT_TYPES,
EXPORT_IMG_ICON_NAME,
EXPORT_IMG_ICON,
@@ -104,8 +103,6 @@ import { getHighlightColor } from "src/utils/dynamicStyling";
import { InlineLinkSuggester } from "src/shared/Suggesters/InlineLinkSuggester";
import { KeyBlocker } from "src/types/excalidrawAutomateTypes";
import { UIMode } from "src/shared/Dialogs/UIModeSettingComponent";
import { hideElement, setButtonBgColor } from "src/utils/styleUtils";
import { installButton } from "src/utils/scriptLibraryUtils";
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
import type { MarkdownImageData } from "src/types/markdownImageTypes";
import { StencilLibraryManager } from "./managers/StencilLibraryManager";
@@ -618,14 +615,6 @@ export default class ExcalidrawPlugin extends Plugin {
}
this.logStartupEvent("Editor handler initialized");
try {
this.registerInstallCodeblockProcessor();
} catch (e) {
new Notice("Error registering script install-codeblock processor", 6000);
console.error("Error registering script install-codeblock processor", e);
}
this.logStartupEvent("Script install-codeblock processor registered");
this.commandManager.initialize();
try {
@@ -732,48 +721,6 @@ export default class ExcalidrawPlugin extends Plugin {
return false;
}
private registerInstallCodeblockProcessor() {
const codeblockProcessor = async (source: string, el: HTMLElement) => {
// The mirrored update button is only available in the Script Library
// index layout. Other render contexts do not have the adjacent heading.
let button2: HTMLButtonElement = null;
const heading = el.previousElementSibling?.getAttribute("data-heading");
const link = heading
? Array.from(el.parentElement?.querySelectorAll("a") ?? []).find(
(anchor) => anchor.getAttribute("href") === `#${heading}`,
)
: null;
if (link?.parentElement) {
link.addClass("excalidraw-installCodeBlock-link");
button2 = link.parentElement.createEl("button", null, (b) => {
b.setText(t("UPDATE_SCRIPT"));
b.addClass("mod-muted");
setButtonBgColor(b, "success");
hideElement(b);
});
}
source = source.trim();
el.createEl("button", null, (button) => {
void installButton(this, button, button2, source);
});
};
this.registerMarkdownCodeBlockProcessor(
SCRIPT_INSTALL_CODEBLOCK,
async (source, el) => {
el.addEventListener(RERENDER_EVENT, (e) => {
void (async () => {
e.stopPropagation();
el.empty();
await codeblockProcessor(source, el);
})();
});
await codeblockProcessor(source, el);
},
);
}
/**
* Displays a transcluded .excalidraw image in markdown preview mode
*/
-5
View File
@@ -45,11 +45,6 @@ export default {
EMBEDDABLE_RELATIVE_ZOOM:
"Scale selected embeddable elements to 100% relative to the current canvas zoom",
OPEN_IMAGE_SOURCE: "Open Excalidraw drawing",
INSTALL_SCRIPT: "Install the script",
UPDATE_SCRIPT: "Update available - Click to install",
CHECKING_SCRIPT: "Checking for newer version - Click to reinstall",
UNABLETOCHECK_SCRIPT: "Update check failed - Click to reinstall",
UPTODATE_SCRIPT: "Script is up to date - Click to reinstall",
OPEN_AS_EXCALIDRAW: "Open as Excalidraw Drawing",
TOGGLE_MODE: "Toggle between Excalidraw and Markdown mode",
DUPLICATE_IMAGE: "Duplicate selected image with a different image ID",
-6
View File
@@ -44,12 +44,6 @@ export default {
EMBEDDABLE_RELATIVE_ZOOM:
"Escalar Elementos Incrustados seleccionados al 100% con respecto al zoom actual del lienzo",
OPEN_IMAGE_SOURCE: "Abrir bosquejo de Excalidraw",
INSTALL_SCRIPT: "Instalar script",
UPDATE_SCRIPT: "Actualización disponible - Click aquí para instalar",
CHECKING_SCRIPT: "Buscando versión más reciente - Click aquí para reinstalar",
UNABLETOCHECK_SCRIPT:
"Fallo en la verificación de actualización - Click aquí para reinstalar",
UPTODATE_SCRIPT: "Script actualizado - Click aquí para reinstalar",
OPEN_AS_EXCALIDRAW: "Abrir como bosquejo de Excalidraw",
TOGGLE_MODE: "Alternar entre modo Excalidraw y Markdown",
DUPLICATE_IMAGE: "Duplicar imagen seleccionada con un ID de imagen diferente",
-7
View File
@@ -38,13 +38,6 @@ export default {
EMBEDDABLE_RELATIVE_ZOOM:
"Масштабирование выбранных встраиваемых элементов до 100% относительно текущего масштаба холста",
OPEN_IMAGE_SOURCE: "Открыть чертеж Excalidraw",
INSTALL_SCRIPT: "Установите скрипт",
UPDATE_SCRIPT: "Доступно обновление - нажмите для установки",
CHECKING_SCRIPT:
"Проверка на наличие новой версии - Нажмите для переустановки",
UNABLETOCHECK_SCRIPT:
"Проверка обновления не удалась - Нажмите, чтобы переустановить",
UPTODATE_SCRIPT: "Скрипт обновлен - Нажмите для переустановки",
OPEN_AS_EXCALIDRAW: "Открыть как рисунок Excalidraw",
TOGGLE_MODE: "Переключение между режимами Excalidraw и Markdown",
CONVERT_NOTE_TO_EXCALIDRAW:
-5
View File
@@ -37,11 +37,6 @@ export default {
EMBEDDABLE_PROPERTIES: "Embeddable 元素设置",
EMBEDDABLE_RELATIVE_ZOOM: "使元素的缩放级别等于当前绘图的缩放级别",
OPEN_IMAGE_SOURCE: "打开 Excalidraw 绘图",
INSTALL_SCRIPT: "安装此脚本",
UPDATE_SCRIPT: "有可用更新 - 点击安装",
CHECKING_SCRIPT: "检查更新中 - 点击重新安装",
UNABLETOCHECK_SCRIPT: "检查更新失败 - 点击重新安装",
UPTODATE_SCRIPT: "脚本已是最新 - 点击重新安装",
OPEN_AS_EXCALIDRAW: "打开为 Excalidraw 绘图",
TOGGLE_MODE: "在 Excalidraw 和 Markdown 模式之间切换",
DUPLICATE_IMAGE: "复制所选图像,并分配一个不同的图像 ID",
-5
View File
@@ -37,11 +37,6 @@ export default {
EMBEDDABLE_PROPERTIES: "Embeddable 元素設定",
EMBEDDABLE_RELATIVE_ZOOM: "使元素的縮放級別等於當前繪圖的縮放級別",
OPEN_IMAGE_SOURCE: "開啟 Excalidraw 繪圖",
INSTALL_SCRIPT: "安裝此指令碼",
UPDATE_SCRIPT: "有可用更新 - 點選安裝",
CHECKING_SCRIPT: "檢查更新中 - 點選重新安裝",
UNABLETOCHECK_SCRIPT: "檢查更新失敗 - 點選重新安裝",
UPTODATE_SCRIPT: "指令碼已是最新 - 點選重新安裝",
OPEN_AS_EXCALIDRAW: "開啟為 Excalidraw 繪圖",
TOGGLE_MODE: "在 Excalidraw 和 Markdown 模式之間切換",
DUPLICATE_IMAGE: "複製所選影像,並分配一個不同的影像 ID",
+9
View File
@@ -36,6 +36,15 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
- Selection rectangles in popout windows are no longer positioned incorrectly when displays use different DPI settings. [#2940](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2940)
## New/Fixed in Excalidraw Automate
- Added three view-lifecycle helpers for integrations that use a view-local Excalidraw Automate instance or render generated/transient scene state:
\`\`\`ts
clearViewDirty(): void;
registerThisAsViewEA(): boolean;
deregisterThisAsViewEA(): boolean;
\`\`\`
- \`clearViewDirty()\` clears the target view's current dirty marker without saving it.
- \`registerThisAsViewEA()\` registers the EA instance as the hook server for its target view.
- \`deregisterThisAsViewEA()\` restores the default plugin-global EA hook server and is safe to use during view teardown.
- Scripts can create native sticky notes, including automatically fitted labels:
\`\`\`ts
addStickyNote(topX: number, topY: number, text: string, formatting?: {width?: number; height?: number; fontSize?: number; fontFamily?: number; textAlign?: "left" | "center" | "right"; textVerticalAlign?: "top" | "middle" | "bottom";}, id?: string): string;
+26 -77
View File
@@ -1,6 +1,4 @@
import {
Component,
MarkdownRenderer,
Modal,
Notice,
normalizePath,
@@ -23,18 +21,14 @@ import { sanitizedFragment, setSanitizedHtml } from "../../utils/htmlUtils";
import {
getInstalledScriptFiles,
getInstalledScriptGroups,
getScriptInstallState,
getScriptInstallStates,
installScript,
moveInstalledScriptToGroup,
uninstallScript,
type ScriptLibraryPluginContext,
} from "../../utils/scriptLibraryUtils";
import { errorlog } from "../../utils/utils";
import { log } from "../../utils/debugHelper";
import { ContentSearcher } from "../components/ContentSearcher";
const LEGACY_URL =
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD;
const CATALOG_URL =
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_SCRIPT_STORE_JSON;
const FEATURED_CATEGORY = "Editors Picks";
@@ -101,29 +95,11 @@ const getScriptIconUrl = (entry: ScriptStoreEntry): string =>
const getScriptSourceUrl = (entry: ScriptStoreEntry): string =>
getPluginRepositoryBlobUrl(`ea-scripts/${entry.file}`);
const rewriteLegacyInstallUrls = (source: string): string =>
source.replace(
/(```excalidraw-script-install\s*\r?\n)([^\r\n]+)(\r?\n```)/g,
(match, opening: string, installUrl: string, closing: string) => {
try {
const filename = decodeURIComponent(
new URL(installUrl.trim()).pathname.split("/").pop() ?? "",
);
if (!/\.(?:md|js)$/i.test(filename)) {
return match;
}
return `${opening}${getPluginRepositoryRawUrl(`ea-scripts/${filename}`)}${closing}`;
} catch {
return match;
}
},
);
export class ScriptInstallPrompt extends Modal {
private contentDiv: HTMLDivElement;
private renderComponent: Component;
private catalog: ScriptStoreCatalog | null = null;
private installStates = new Map<string, ScriptStoreInstallState>();
private descriptionText = new Map<string, string>();
private selectedCategory = "";
private searchQuery = "";
private storeView: StoreView = "all";
@@ -134,8 +110,6 @@ export class ScriptInstallPrompt extends Modal {
onOpen(): void {
this.titleEl.setText(t("SCRIPT_STORE_TITLE"));
this.renderComponent = new Component();
this.renderComponent.load();
this.contentEl.classList.add(
"excalidraw-scriptengine-install",
"excalidraw-script-store",
@@ -171,7 +145,8 @@ export class ScriptInstallPrompt extends Modal {
this.renderStore();
} catch (error: unknown) {
errorlog({ where: "ScriptInstallPrompt.loadStore", error });
await this.renderLegacyStore();
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
this.close();
}
}
@@ -179,15 +154,16 @@ export class ScriptInstallPrompt extends Modal {
if (!this.catalog) {
return;
}
const stateEntries = await Promise.all(
this.catalog.scripts.map(async (entry) =>
[
entry.name,
await getScriptInstallState(this.plugin, getScriptInstallUrl(entry)),
] as const,
),
const sources = this.catalog.scripts.map((entry) =>
getScriptInstallUrl(entry),
);
const states = await getScriptInstallStates(this.plugin, sources);
this.installStates = new Map(
this.catalog.scripts.map((entry, index) => [
entry.name,
states.get(sources[index]) ?? "error",
]),
);
this.installStates = new Map(stateEntries);
}
private renderStore(): void {
@@ -476,7 +452,7 @@ export class ScriptInstallPrompt extends Modal {
entry.name,
entry.author,
entry.categories.join(" "),
sanitizedFragment(entry.descriptionHtml).textContent ?? "",
this.getDescription(entry),
]
.join(" ")
.toLowerCase();
@@ -594,9 +570,17 @@ export class ScriptInstallPrompt extends Modal {
}
private getDescription(entry: ScriptStoreEntry): string {
return (sanitizedFragment(entry.descriptionHtml).textContent ?? "")
const cached = this.descriptionText.get(entry.file);
if (cached !== undefined) {
return cached;
}
const description = (
sanitizedFragment(entry.descriptionHtml).textContent ?? ""
)
.replace(/\s+/g, " ")
.trim();
this.descriptionText.set(entry.file, description);
return description;
}
private getActionLabel(state: ScriptStoreInstallState): string {
@@ -904,8 +888,9 @@ export class ScriptInstallPrompt extends Modal {
try {
const source = getScriptInstallUrl(entry);
await uninstallScript(this.plugin, source, localPath);
const state = await getScriptInstallState(this.plugin, source);
this.installStates.set(entry.name, state);
if (getInstalledScriptFiles(this.plugin, source).length === 0) {
this.installStates.set(entry.name, "install");
}
new Notice(`${t("SCRIPT_STORE_UNINSTALLED")}: ${entry.name}`);
this.renderDetail(entry);
} catch (error: unknown) {
@@ -934,8 +919,6 @@ export class ScriptInstallPrompt extends Modal {
targetGroup,
localPath,
);
const state = await getScriptInstallState(this.plugin, source);
this.installStates.set(entry.name, state);
new Notice(`${t("SCRIPT_STORE_MOVED_TO_GROUP")}: ${entry.name}`);
this.renderDetail(entry);
} catch (error: unknown) {
@@ -949,41 +932,7 @@ export class ScriptInstallPrompt extends Modal {
}
}
private async renderLegacyStore(): Promise<void> {
try {
const source = await request({ url: LEGACY_URL });
if (!source) {
new Notice(t("SCRIPT_INSTALL_PROMPT_FETCH_ERROR"), 5000);
log(LEGACY_URL);
this.close();
return;
}
this.contentDiv.replaceChildren();
new ContentSearcher(this.contentDiv);
await MarkdownRenderer.render(
this.plugin.app,
rewriteLegacyInstallUrls(source),
this.contentDiv,
"",
this.renderComponent,
);
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");
});
} catch (error: unknown) {
errorlog({ where: "ScriptInstallPrompt.renderLegacyStore", error });
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
this.close();
}
}
onClose(): void {
this.contentEl.replaceChildren();
this.renderComponent.unload();
}
}
+18
View File
@@ -661,6 +661,24 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: null,
after: "",
},
{
field: "clearViewDirty",
code: "clearViewDirty(): void;",
desc: "Clears the target view's current dirty marker without saving. Intended for generated/transient scene integrations that update a view with save=false. Calls racing view teardown are ignored.",
after: "",
},
{
field: "registerThisAsViewEA",
code: "registerThisAsViewEA(): boolean;",
desc: "Registers this EA instance as the hook server for its target view.",
after: "",
},
{
field: "deregisterThisAsViewEA",
code: "deregisterThisAsViewEA(): boolean;",
desc: "Restores the target view's default plugin-global EA hook server. Safe to call during view teardown.",
after: "",
},
{
field: "connectObjectWithViewSelectedElement",
code: "connectObjectWithViewSelectedElement(objectA: string, connectionA: ConnectionPoint, connectionB: ConnectionPoint, formatting?: {numberOfPoints?: number; startArrowHead?: string; endArrowHead?: string; padding?: number;},): boolean;",
+68 -27
View File
@@ -870,6 +870,24 @@ export class ExcalidrawAutomate {
this.targetView = view;
}
/**
* Returns the current target view when it is safe to perform a live-view
* operation. Calls that arrive after EA destruction or while the target view
* is unloading are expected teardown races and are ignored silently. Genuine
* calls without an active target view still report the usual EA API error.
*/
private getReadyTargetView(source: string): ExcalidrawView | null {
const view = this.targetView;
if (this.destroyed || view?.semaphores?.viewunload) {
return null;
}
if (view?._loaded) {
return view;
}
errorMessage("targetView not set", source);
return null;
}
/**
* Registers synchronous cleanup owned by this EA instance. Use this for
* external listeners, observers, timers, and subscriptions that EA cannot
@@ -3868,11 +3886,10 @@ export class ExcalidrawAutomate {
* @param {boolean} [forceViewMode=false] - Whether to force view mode.
*/
viewToggleFullScreen(forceViewMode: boolean = false): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
const view = this.getReadyTargetView("viewToggleFullScreen()");
if (!view) {
return;
}
const view = this.targetView;
const isFullscreen = view.isFullscreen();
if (forceViewMode) {
view.updateScene({
@@ -3882,9 +3899,7 @@ export class ExcalidrawAutomate {
},
captureUpdate: CaptureUpdateAction.NEVER,
});
this.targetView.toolsPanelRef?.current?.setExcalidrawViewMode(
!isFullscreen,
);
view.toolsPanelRef?.current?.setExcalidrawViewMode(!isFullscreen);
}
if (isFullscreen) {
@@ -3899,11 +3914,10 @@ export class ExcalidrawAutomate {
* @param {boolean} enabled - Whether to enable view mode.
*/
setViewModeEnabled(enabled: boolean): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
const view = this.getReadyTargetView("setViewModeEnabled()");
if (!view) {
return;
}
const view = this.targetView;
view.updateScene({
appState: { viewModeEnabled: enabled },
captureUpdate: CaptureUpdateAction.NEVER,
@@ -3933,15 +3947,15 @@ export class ExcalidrawAutomate {
},
restore: boolean = false,
): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
const view = this.getReadyTargetView("viewUpdateScene()");
if (!view) {
return;
}
if (!scene.storeAction) {
scene.storeAction = scene.commitToHistory ? "capture" : "update";
}
this.targetView.updateScene(
view.updateScene(
{
elements: scene.elements,
appState: scene.appState,
@@ -4016,11 +4030,26 @@ export class ExcalidrawAutomate {
elements: ExcalidrawElement[],
margin: number = 0.05,
): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
const view = this.getReadyTargetView("viewZoomToElements()");
if (!view) {
return;
}
this.targetView.zoomToElements(selectElements, elements, margin);
view.zoomToElements(selectElements, elements, margin);
}
/**
* Clears the target view's current dirty marker without saving.
*
* This is intended for integrations that deliberately render generated or
* transient scene state with `save=false`. It does not disable future dirty
* tracking or persistence. Calls racing view teardown are ignored.
*/
clearViewDirty(): void {
const view = this.getReadyTargetView("clearViewDirty()");
if (!view) {
return;
}
view.clearDirty();
}
/**
@@ -4038,15 +4067,15 @@ export class ExcalidrawAutomate {
shouldRestoreElements: boolean = false,
captureUpdate: CaptureUpdateActionType = CaptureUpdateAction.IMMEDIATELY,
): Promise<boolean> {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "addElementsToView()");
const view = this.getReadyTargetView("addElementsToView()");
if (!view) {
return false;
}
const elements = this.getElements();
if (elements.some((el) => el.type === "embeddable")) {
patchMobileView(this.targetView);
patchMobileView(view);
}
const result = await this.targetView.addElements({
const result = await view.addElements({
newElements: elements,
repositionToCursor,
save,
@@ -4065,24 +4094,28 @@ export class ExcalidrawAutomate {
* @returns {boolean} True if successful, false otherwise.
*/
registerThisAsViewEA(): boolean {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "addElementsToView()");
const view = this.getReadyTargetView("registerThisAsViewEA()");
if (!view) {
return false;
}
this.targetView.setHookServer(this);
view.setHookServer(this);
return true;
}
/**
* Sets the target view EA to window.ExcalidrawAutomate.
* @returns {boolean} True if successful, false otherwise.
* Restores the target view's default plugin-global EA hook server. This is a
* teardown operation, so it remains valid while the view itself is unloading.
* @returns {boolean} True if a target view was available, false otherwise.
*/
deregisterThisAsViewEA(): boolean {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "addElementsToView()");
const view = this.targetView;
if (!view) {
if (!this.destroyed) {
errorMessage("targetView not set", "deregisterThisAsViewEA()");
}
return false;
}
this.targetView.setHookServer(this);
view.setHookServer();
return true;
}
@@ -5381,6 +5414,14 @@ export class ExcalidrawAutomate {
}
});
this.sidepanelTab?.close();
const targetView = this.targetView;
try {
if (targetView?.getHookServer() === this) {
targetView.setHookServer();
}
} catch {
// The target view may already be past its unload lifecycle.
}
this.targetView = null;
this.plugin = null;
this.elementsDict = {};
+123 -6
View File
@@ -378,6 +378,23 @@ export class ScriptEngine {
);
}
/**
* Runs a coordinated script-file mutation without letting the vault event
* handlers trigger full registry reloads for each intermediate file change.
* The caller is responsible for refreshing the affected registry entries.
*/
public async withScriptFileEventsSuspended<T>(
operation: () => Promise<T>,
): Promise<T> {
const wasSuspended = this.scriptFileEventsSuspended;
this.scriptFileEventsSuspended = true;
try {
return await operation();
} finally {
this.scriptFileEventsSuspended = wasSuspended;
}
}
updateScriptPath() {
if (this.scriptPath === this.plugin.settings.scriptFolderPath) {
return;
@@ -429,6 +446,47 @@ export class ScriptEngine {
);
}
/** Refreshes one script after an in-place write without reloading all scripts. */
public async refreshManagedScriptFile(file: TFile): Promise<void> {
this.invalidateCompiledScript(file.path);
if (!this.isInScriptFolder(file.path) || !this.isScriptPath(file.path)) {
return;
}
if (!this.loadedScriptPaths.has(file.path)) {
await this.loadScript(file);
return;
}
await this.addScriptIconToMap(
file.path,
this.getScriptName(file),
this.scriptRegistryGeneration,
);
}
/** Removes one deleted script from the live registry without a full reload. */
public async removeManagedScriptFile(
scriptPath: string,
scriptName: string,
): Promise<void> {
this.invalidateCompiledScript(scriptPath);
this.clearAutostartAttachment(scriptPath);
if (
this.loadedScriptPaths.has(scriptPath) ||
Boolean(this.scriptIconMap?.[scriptPath])
) {
this.unloadScript(scriptName, scriptPath);
}
const hasAutostartState =
scriptName in this.plugin.settings.autostartScripts ||
scriptName in this.plugin.settings.autostartScriptFailures;
if (hasAutostartState && !this.getScriptFileByName(scriptName)) {
await this.purgeAutostartPermission(scriptName);
}
getExcalidrawViews(this.app, true).forEach((view) =>
view.updatePinnedScripts(),
);
}
/**
* Builds a non-destructive plan for moving scripts to the selected local
* extension. A configured startup script outside the Scripts folder is
@@ -589,14 +647,73 @@ export class ScriptEngine {
destinationPath: string,
): Promise<void> {
const sourcePath = file.path;
const startupScriptPath = resolveConfiguredStartupScriptPath(
this.plugin.settings.startupScriptPath,
if (sourcePath === destinationPath) {
return;
}
if (
this.app.vault.getFileByPath(destinationPath) ||
this.app.vault.getFolderByPath(destinationPath)
) {
throw new Error(`Script destination already exists: ${destinationPath}`);
}
const sourceScriptName = this.getScriptName(sourcePath);
const wasLoaded = this.loadedScriptPaths.has(sourcePath);
const originalPinnedScripts = [...this.plugin.settings.pinnedScripts];
const originalStartupScriptPath = this.plugin.settings.startupScriptPath;
const resolvedStartupPath = resolveConfiguredStartupScriptPath(
originalStartupScriptPath,
);
await this.migrateScriptFiles({
renames: [{ file, sourcePath, destinationPath }],
conflicts: [],
includesStartupScript: startupScriptPath === sourcePath,
const pinnedChanged = originalPinnedScripts.includes(sourcePath);
const startupChanged = resolvedStartupPath === sourcePath;
let renamed = false;
await this.withScriptFileEventsSuspended(async () => {
try {
await this.app.fileManager.renameFile(file, destinationPath);
renamed = true;
if (pinnedChanged) {
this.plugin.settings.pinnedScripts = originalPinnedScripts.map((path) =>
path === sourcePath ? destinationPath : path,
);
}
if (startupChanged) {
this.plugin.settings.startupScriptPath = destinationPath;
}
if (pinnedChanged || startupChanged) {
await this.plugin.saveSettings();
}
} catch (error: unknown) {
this.plugin.settings.pinnedScripts = originalPinnedScripts;
this.plugin.settings.startupScriptPath = originalStartupScriptPath;
if (renamed) {
try {
await this.app.fileManager.renameFile(file, sourcePath);
} catch (rollbackError: unknown) {
errorlog({
where: "ScriptEngine.renameManagedScriptFile.rollback",
sourcePath: destinationPath,
error: rollbackError,
});
}
}
throw error;
}
});
this.invalidateCompiledScript(sourcePath);
this.invalidateCompiledScript(file.path);
this.clearAutostartAttachment(sourcePath);
if (wasLoaded) {
this.unloadScript(sourceScriptName, sourcePath);
}
if (this.isInScriptFolder(file.path) && this.isScriptPath(file.path)) {
await this.loadScript(file);
}
getExcalidrawViews(this.app, true).forEach((view) =>
view.updatePinnedScripts(),
);
}
public getScriptName(f: TFile | string): string {
+156 -185
View File
@@ -20,7 +20,6 @@ import {
getScriptFileStem,
isScriptFilePath,
} from "./scriptFileUtils";
import { hideElement, setButtonBgColor, showElement } from "./styleUtils";
type ScriptLibrarySettings = {
scriptFolderPath: string;
@@ -29,10 +28,10 @@ type ScriptLibrarySettings = {
};
type ScriptLibraryScriptEngine = {
scriptIconMap: Record<string, unknown> | null;
getScriptName(file: TFile | string): string;
loadScripts(generation?: number): Promise<void>;
reloadScripts(): Promise<void>;
withScriptFileEventsSuspended<T>(operation: () => Promise<T>): Promise<T>;
refreshManagedScriptFile(file: TFile): Promise<void>;
removeManagedScriptFile(scriptPath: string, scriptName: string): Promise<void>;
renameManagedScriptFile(file: TFile, destinationPath: string): Promise<void>;
};
@@ -76,14 +75,6 @@ const decodeRemoteFilename = (source: string): string => {
}
};
const isInDownloadedScriptsFolder = (
plugin: ScriptLibraryPluginContext,
file: TFile,
): boolean => {
const root = getDownloadedScriptsFolder(plugin);
return Boolean(root) && file.path.startsWith(`${root}/`);
};
const sortManagedCopies = (
plugin: ScriptLibraryPluginContext,
files: TFile[],
@@ -98,22 +89,47 @@ const sortManagedCopies = (
});
};
const getManagedScriptFilesByStem = (
plugin: ScriptLibraryPluginContext,
): Map<string, TFile[]> => {
const root = plugin.app.vault.getFolderByPath(
getDownloadedScriptsFolder(plugin),
);
if (!root) {
return new Map();
}
const managedFiles: TFile[] = [];
const visit = (folder: TFolder): void => {
folder.children.forEach((child) => {
if (child instanceof TFolder) {
visit(child);
} else if (child instanceof TFile && isScriptFilePath(child.path)) {
managedFiles.push(child);
}
});
};
visit(root);
const filesByStem = new Map<string, TFile[]>();
getPreferredScriptFiles(managedFiles).forEach((file) => {
const stem = getScriptFileStem(file.name);
const files = filesByStem.get(stem) ?? [];
files.push(file);
filesByStem.set(stem, files);
});
filesByStem.forEach((files, stem) => {
filesByStem.set(stem, sortManagedCopies(plugin, files));
});
return filesByStem;
};
const getLocalScriptFiles = (
plugin: ScriptLibraryPluginContext,
remoteFilename: string,
): TFile[] => {
const stem = getScriptFileStem(remoteFilename);
const matches = getPreferredScriptFiles(
plugin.app.vault
.getFiles()
.filter(
(file) =>
isInDownloadedScriptsFolder(plugin, file) &&
isScriptFilePath(file.path) &&
getScriptFileStem(file.name) === stem,
),
);
return sortManagedCopies(plugin, matches);
return getManagedScriptFilesByStem(plugin).get(stem) ?? [];
};
const getLocalScriptFile = (
@@ -245,20 +261,24 @@ export const moveInstalledScriptToGroup = async (
let iconMoved = false;
try {
if (iconFile) {
await plugin.app.fileManager.renameFile(iconFile, destinationIconPath);
iconMoved = true;
}
await plugin.scriptEngine.renameManagedScriptFile(
scriptFile,
destinationPath,
);
await plugin.scriptEngine.withScriptFileEventsSuspended(async () => {
if (iconFile) {
await plugin.app.fileManager.renameFile(iconFile, destinationIconPath);
iconMoved = true;
}
await plugin.scriptEngine.renameManagedScriptFile(
scriptFile,
destinationPath,
);
});
} catch (error: unknown) {
if (iconMoved) {
const movedIcon = plugin.app.vault.getFileByPath(destinationIconPath);
if (movedIcon) {
try {
await plugin.app.fileManager.renameFile(movedIcon, sourceIconPath);
await plugin.scriptEngine.withScriptFileEventsSuspended(async () => {
await plugin.app.fileManager.renameFile(movedIcon, sourceIconPath);
});
} catch (rollbackError: unknown) {
errorlog({
where: "scriptLibraryUtils.moveInstalledScriptToGroup.rollback",
@@ -287,19 +307,23 @@ export const uninstallScript = async (
const iconFile = plugin.app.vault.getFileByPath(
getIMGFilename(scriptFile.path, "svg"),
);
await plugin.app.fileManager.trashFile(scriptFile);
if (iconFile) {
try {
await plugin.app.fileManager.trashFile(iconFile);
} catch (error: unknown) {
errorlog({
where: "scriptLibraryUtils.uninstallScript.icon",
source: iconFile.path,
error,
});
const scriptPath = scriptFile.path;
const scriptName = plugin.scriptEngine.getScriptName(scriptFile);
await plugin.scriptEngine.withScriptFileEventsSuspended(async () => {
await plugin.app.fileManager.trashFile(scriptFile);
if (iconFile) {
try {
await plugin.app.fileManager.trashFile(iconFile);
} catch (error: unknown) {
errorlog({
where: "scriptLibraryUtils.uninstallScript.icon",
source: iconFile.path,
error,
});
}
}
}
await plugin.scriptEngine.reloadScripts();
});
await plugin.scriptEngine.removeManagedScriptFile(scriptPath, scriptName);
};
const getDirectoryInfo = async (): Promise<Map<string, number> | null> => {
@@ -369,26 +393,53 @@ const getInstallStateFromDirectoryInfo = (
* Resolves one community script's install/update state using the legacy mtime
* contract. directory-info.json is the compatibility source of truth.
*/
export const getScriptInstallStates = async (
plugin: ScriptLibraryPluginContext,
sources: readonly string[],
): Promise<Map<string, ScriptStoreInstallState>> => {
const filesByStem = getManagedScriptFilesByStem(plugin);
const remoteFiles = sources.map((source) => ({
source,
remoteFilename: decodeRemoteFilename(source),
}));
const hasInstalledScripts = remoteFiles.some(({ remoteFilename }) =>
filesByStem.has(getScriptFileStem(remoteFilename)),
);
const states = new Map<string, ScriptStoreInstallState>();
if (!hasInstalledScripts) {
remoteFiles.forEach(({ source }) => states.set(source, "install"));
return states;
}
const files = await getDirectoryInfo();
remoteFiles.forEach(({ source, remoteFilename }) => {
const scriptFile =
filesByStem.get(getScriptFileStem(remoteFilename))?.[0] ?? null;
if (!scriptFile) {
states.set(source, "install");
return;
}
states.set(
source,
files
? getInstallStateFromDirectoryInfo(
plugin,
scriptFile,
remoteFilename,
files,
)
: "error",
);
});
return states;
};
/** Resolves one community script's install/update state. */
export const getScriptInstallState = async (
plugin: ScriptLibraryPluginContext,
source: string,
): Promise<ScriptStoreInstallState> => {
const remoteFilename = decodeRemoteFilename(source);
const scriptFile = getLocalScriptFile(plugin, remoteFilename);
if (!scriptFile) {
return "install";
}
const files = await getDirectoryInfo();
if (!files) {
return "error";
}
return getInstallStateFromDirectoryInfo(
plugin,
scriptFile,
remoteFilename,
files,
);
};
): Promise<ScriptStoreInstallState> =>
(await getScriptInstallStates(plugin, [source])).get(source) ?? "error";
const restartSidepanelTabIfActive = async (
plugin: ScriptLibraryPluginContext,
@@ -438,47 +489,59 @@ export const installScript = async (
getIMGFilename(scriptPath, "svg"),
);
const download = async (
url: string,
file: TFile | null,
localPath: string,
): Promise<TFile | null> => {
const fetchRemote = async (url: string): Promise<string | null> => {
const data = await request({ url });
if (!data || data.startsWith("404: Not Found")) {
return null;
}
return await createOrOverwriteFile(
plugin.app,
file?.path ?? localPath,
data,
);
return data;
};
try {
scriptPath = getLocalScriptPath();
if (scriptFile && scriptFile.path !== scriptPath) {
if (plugin.app.vault.getFileByPath(scriptPath)) {
scriptPath = scriptFile.path;
} else {
await plugin.scriptEngine.renameManagedScriptFile(scriptFile, scriptPath);
}
}
scriptFile = await download(source, scriptFile, scriptPath);
if (!scriptFile) {
const [scriptData, iconData] = await Promise.all([
fetchRemote(source),
fetchRemote(getIMGFilename(source, "svg")),
]);
if (!scriptData) {
throw new Error("Script file not found");
}
const iconPath = getIMGFilename(scriptFile.path, "svg");
iconFile = await download(
getIMGFilename(source, "svg"),
plugin.app.vault.getFileByPath(iconPath),
iconPath,
);
await plugin.scriptEngine.withScriptFileEventsSuspended(async () => {
scriptPath = getLocalScriptPath();
if (scriptFile && scriptFile.path !== scriptPath) {
if (plugin.app.vault.getFileByPath(scriptPath)) {
scriptPath = scriptFile.path;
} else {
await plugin.scriptEngine.renameManagedScriptFile(
scriptFile,
scriptPath,
);
}
}
if (Object.keys(plugin.scriptEngine.scriptIconMap ?? {}).length === 0) {
await plugin.scriptEngine.loadScripts();
scriptFile = await createOrOverwriteFile(
plugin.app,
scriptFile?.path ?? scriptPath,
scriptData,
);
const iconPath = getIMGFilename(scriptFile.path, "svg");
if (iconData) {
const existingIcon = plugin.app.vault.getFileByPath(iconPath);
iconFile = await createOrOverwriteFile(
plugin.app,
existingIcon?.path ?? iconPath,
iconData,
);
} else {
iconFile = null;
}
});
if (!scriptFile) {
throw new Error("Script file was not created");
}
await plugin.scriptEngine.refreshManagedScriptFile(scriptFile);
await restartSidepanelTabIfActive(plugin, scriptFile);
if (showNotice) {
new Notice(`${t("SCRIPT_INSTALLED_NOTICE")}: ${scriptFile.basename}`);
@@ -509,16 +572,8 @@ export const getInstalledScriptUpdates = async (
return [];
}
const managedFiles = getPreferredScriptFiles(
plugin.app.vault
.getFiles()
.filter(
(file) =>
isInDownloadedScriptsFolder(plugin, file) &&
isScriptFilePath(file.path),
),
);
if (managedFiles.length === 0) {
const copiesByStem = getManagedScriptFilesByStem(plugin);
if (copiesByStem.size === 0) {
return [];
}
@@ -527,17 +582,9 @@ export const getInstalledScriptUpdates = async (
return [];
}
const copiesByStem = new Map<string, TFile[]>();
managedFiles.forEach((file) => {
const stem = getScriptFileStem(file.name);
const copies = copiesByStem.get(stem) ?? [];
copies.push(file);
copiesByStem.set(stem, copies);
});
const updates: string[] = [];
copiesByStem.forEach((copies, stem) => {
const scriptFile = sortManagedCopies(plugin, copies)[0];
const scriptFile = copies[0];
if (!scriptFile) {
return;
}
@@ -563,79 +610,3 @@ export const getInstalledScriptUpdates = async (
return updates.sort((a, b) => a.localeCompare(b));
};
export const installButton = async (
plugin: ScriptLibraryPluginContext,
button: HTMLButtonElement,
button2: HTMLButtonElement | null,
source: string,
): Promise<void> => {
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");
setButtonText(
getLocalScriptFile(plugin, decodeRemoteFilename(source))
? "CHECKING"
: "INSTALL",
);
button.onclick = async () => {
setButtonText("CHECKING");
try {
await installScript(plugin, source);
setButtonText("UPTODATE");
} catch {
setButtonText("ERROR");
}
};
if (button2) {
button2.onclick = button.onclick;
}
const state = await getScriptInstallState(plugin, source);
switch (state) {
case "install":
setButtonText("INSTALL");
break;
case "update":
setButtonText("UPDATE");
break;
case "up-to-date":
setButtonText("UPTODATE");
break;
case "error":
setButtonText("ERROR");
break;
}
};
-4
View File
@@ -1014,10 +1014,6 @@ End Obsidian Sheets Plus support
margin-right: 0.5em;
}
.excalidraw-installCodeBlock-link {
padding-right: 10px;
}
.excalidraw-insertpdf-infolabel {
min-width: 2.3em;
text-align: right;