Compare commits

...
Author SHA1 Message Date
zsviczian 2d39586865 implemented toggleViewMode 2026-09-28 19:50:45 +02:00
zsviczian 3f98be4500 Merge pull request #2960 from zsviczian/kplex-support
feat: add view-scoped integration APIs for K-Plex
2026-09-28 12:13:45 +02:00
zsviczian 038384ce2a linkclick hook, zoom to fit view 2026-09-28 12:12:22 +02:00
zsviczian 7f16448595 save fontTopPicks to file 2026-09-26 10:31:31 +02:00
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
zsviczian 6197ebe199 2.28.0-beta.2 2026-09-19 17:14:41 +02:00
zsviczian 5c51d057f3 updated skills 2026-09-19 16:47:42 +02:00
zsviczian 593b02cce3 Merge pull request #2944 from zsviczian/reimagine-scriptstore
feat: Reimagine the Community Script Store
2026-09-19 16:41:35 +02:00
34 changed files with 989 additions and 452 deletions

No files matched your search

@@ -2354,12 +2354,22 @@ export interface SelectableFontOption {
/* lib/types/githubTypes.d.ts */
/* ******************************** */
/**
* Metadata entry describing a file in the remote EA scripts directory listing.
* Metadata entry describing a file in the legacy remote EA scripts directory listing.
*/
export type RemoteDirectoryInfo = {
fname: string;
mtime: number;
};
/**
* File metadata returned by GitHub's repository contents endpoint.
*/
export type GitHubRepositoryContentFile = {
name: string;
path: string;
sha: string;
type: "file" | "dir" | "symlink" | "submodule";
download_url?: string | null;
};
/* ************************************** */
/* lib/types/markdownImageTypes.d.ts */
@@ -2591,6 +2601,32 @@ export interface InputPromptOptions {
draggable?: boolean;
}
/* ************************************* */
/* lib/types/scriptStoreTypes.d.ts */
/* ************************************* */
export type ScriptStoreCategory = {
name: string;
description: string;
};
export type ScriptStoreEntry = {
name: string;
file: string;
installUrl: string;
iconUrl: string;
author: string;
authorUrl: string;
sourceUrl: string;
descriptionHtml: string;
categories: string[];
featuredRank?: number;
};
export type ScriptStoreCatalog = {
version: number;
categories: ScriptStoreCategory[];
scripts: ScriptStoreEntry[];
};
export type ScriptStoreInstallState = "install" | "update" | "up-to-date" | "error";
/* ************************************** */
/* lib/types/sidepanelTabTypes.d.ts */
/* ************************************** */
@@ -12,7 +12,7 @@ Content structure:
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: 2026-09-19T09:34:28.553Z
Generated on: 2026-09-19T14:44:44.719Z
---
@@ -51943,6 +51943,26 @@ Open the script you are interested in and save it to your Obsidian Vault includi
|[Zoom to Fit Selected Elements](Zoom%20to%20Fit%20Selected%20Elements.md)|Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)||[@zsviczian](https://github.com/zsviczian)|
|[Hardware Eraser Suppoer](Hardware%20Eraser%20Support.md)|Allows the use of pen inversion/hardware erasers on supported pens.|[@threethan](https://github.com/threethan)|
|[Hardware Eraser Suppoer](Auto%20Draw%20for%20Pen.md)|Automatically switched from the Select tool to the Draw tool when a pen is hovered, and then back.|[@threethan](https://github.com/threethan)|
## Publishing a community script
The current Script Store reads metadata from `ea-scripts/script-store.json`. Add or update one catalog entry when publishing a script, plus the script file and its matching SVG icon/preview when applicable.
Run:
```bash
npm run script-store:check
npm run script-store:build
```
`script-store:build` validates `script-store.json` and updates `directory-info.json` only for script or icon files that are actually modified/new in the current Git working tree. It **does not recalculate historical timestamps**, and repeated builds preserve an already-updated value. When the repository was exported without `.git`, all existing mtimes are left untouched.
`index-new.md` is a frozen legacy catalog for older Excalidraw versions. Routine Script Store publishing must not generate or modify it. New scripts added only to `script-store.json` are intentionally unavailable in older plugin versions unless a maintainer explicitly updates the legacy catalog separately.
Do not hand-edit unrelated `mtime` values. The plugin still uses these timestamps for backward-compatible script update detection.
### Beta release compatibility
Released 2.27.x clients fetch `ea-scripts/index-new.md` and `ea-scripts/directory-info.json` directly from the repository `master` branch at runtime. Keep `index-new.md` unchanged during routine 2.28 Script Store work. `directory-info.json` may still advance for scripts/icons that are actually updated, preserving the established update behavior for scripts already present in the legacy catalog.
---
@@ -2635,12 +2635,22 @@ export interface SelectableFontOption {
/* lib/types/githubTypes.d.ts */
/* ******************************** */
/**
* Metadata entry describing a file in the remote EA scripts directory listing.
* Metadata entry describing a file in the legacy remote EA scripts directory listing.
*/
export type RemoteDirectoryInfo = {
fname: string;
mtime: number;
};
/**
* File metadata returned by GitHub's repository contents endpoint.
*/
export type GitHubRepositoryContentFile = {
name: string;
path: string;
sha: string;
type: "file" | "dir" | "symlink" | "submodule";
download_url?: string | null;
};
/* ************************************** */
/* lib/types/markdownImageTypes.d.ts */
@@ -2872,6 +2882,32 @@ export interface InputPromptOptions {
draggable?: boolean;
}
/* ************************************* */
/* lib/types/scriptStoreTypes.d.ts */
/* ************************************* */
export type ScriptStoreCategory = {
name: string;
description: string;
};
export type ScriptStoreEntry = {
name: string;
file: string;
installUrl: string;
iconUrl: string;
author: string;
authorUrl: string;
sourceUrl: string;
descriptionHtml: string;
categories: string[];
featuredRank?: number;
};
export type ScriptStoreCatalog = {
version: number;
categories: ScriptStoreCategory[];
scripts: ScriptStoreEntry[];
};
export type ScriptStoreInstallState = "install" | "update" | "up-to-date" | "error";
/* ************************************** */
/* lib/types/sidepanelTabTypes.d.ts */
/* ************************************** */
@@ -6959,7 +6995,7 @@ Content structure:
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: 2026-09-19T09:34:28.553Z
Generated on: 2026-09-19T14:44:44.719Z
---
@@ -58890,6 +58926,26 @@ Open the script you are interested in and save it to your Obsidian Vault includi
|[Zoom to Fit Selected Elements](Zoom%20to%20Fit%20Selected%20Elements.md)|Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)||[@zsviczian](https://github.com/zsviczian)|
|[Hardware Eraser Suppoer](Hardware%20Eraser%20Support.md)|Allows the use of pen inversion/hardware erasers on supported pens.|[@threethan](https://github.com/threethan)|
|[Hardware Eraser Suppoer](Auto%20Draw%20for%20Pen.md)|Automatically switched from the Select tool to the Draw tool when a pen is hovered, and then back.|[@threethan](https://github.com/threethan)|
## Publishing a community script
The current Script Store reads metadata from `ea-scripts/script-store.json`. Add or update one catalog entry when publishing a script, plus the script file and its matching SVG icon/preview when applicable.
Run:
```bash
npm run script-store:check
npm run script-store:build
```
`script-store:build` validates `script-store.json` and updates `directory-info.json` only for script or icon files that are actually modified/new in the current Git working tree. It **does not recalculate historical timestamps**, and repeated builds preserve an already-updated value. When the repository was exported without `.git`, all existing mtimes are left untouched.
`index-new.md` is a frozen legacy catalog for older Excalidraw versions. Routine Script Store publishing must not generate or modify it. New scripts added only to `script-store.json` are intentionally unavailable in older plugin versions unless a maintainer explicitly updates the legacy catalog separately.
Do not hand-edit unrelated `mtime` values. The plugin still uses these timestamps for backward-compatible script update detection.
### Beta release compatibility
Released 2.27.x clients fetch `ea-scripts/index-new.md` and `ea-scripts/directory-info.json` directly from the repository `master` branch at runtime. Keep `index-new.md` unchanged during routine 2.28 Script Store work. `directory-info.json` may still advance for scripts/icons that are actually updated, preserving the established update behavior for scripts already present in the legacy catalog.
---
@@ -83,4 +83,24 @@ Open the script you are interested in and save it to your Obsidian Vault includi
|[Transfer TextElements to Excalidraw markdown metadata](Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md)|The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Zoom to Fit Selected Elements](Zoom%20to%20Fit%20Selected%20Elements.md)|Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)||[@zsviczian](https://github.com/zsviczian)|
|[Hardware Eraser Suppoer](Hardware%20Eraser%20Support.md)|Allows the use of pen inversion/hardware erasers on supported pens.|[@threethan](https://github.com/threethan)|
|[Hardware Eraser Suppoer](Auto%20Draw%20for%20Pen.md)|Automatically switched from the Select tool to the Draw tool when a pen is hovered, and then back.|[@threethan](https://github.com/threethan)|
|[Hardware Eraser Suppoer](Auto%20Draw%20for%20Pen.md)|Automatically switched from the Select tool to the Draw tool when a pen is hovered, and then back.|[@threethan](https://github.com/threethan)|
## Publishing a community script
The current Script Store reads metadata from `ea-scripts/script-store.json`. Add or update one catalog entry when publishing a script, plus the script file and its matching SVG icon/preview when applicable.
Run:
```bash
npm run script-store:check
npm run script-store:build
```
`script-store:build` validates `script-store.json` and updates `directory-info.json` only for script or icon files that are actually modified/new in the current Git working tree. It **does not recalculate historical timestamps**, and repeated builds preserve an already-updated value. When the repository was exported without `.git`, all existing mtimes are left untouched.
`index-new.md` is a frozen legacy catalog for older Excalidraw versions. Routine Script Store publishing must not generate or modify it. New scripts added only to `script-store.json` are intentionally unavailable in older plugin versions unless a maintainer explicitly updates the legacy catalog separately.
Do not hand-edit unrelated `mtime` values. The plugin still uses these timestamps for backward-compatible script update detection.
### Beta release compatibility
Released 2.27.x clients fetch `ea-scripts/index-new.md` and `ea-scripts/directory-info.json` directly from the repository `master` branch at runtime. Keep `index-new.md` unchanged during routine 2.28 Script Store work. `directory-info.json` may still advance for scripts/icons that are actually updated, preserving the established update behavior for scripts already present in the legacy catalog.
@@ -2354,12 +2354,22 @@ export interface SelectableFontOption {
/* lib/types/githubTypes.d.ts */
/* ******************************** */
/**
* Metadata entry describing a file in the remote EA scripts directory listing.
* Metadata entry describing a file in the legacy remote EA scripts directory listing.
*/
export type RemoteDirectoryInfo = {
fname: string;
mtime: number;
};
/**
* File metadata returned by GitHub's repository contents endpoint.
*/
export type GitHubRepositoryContentFile = {
name: string;
path: string;
sha: string;
type: "file" | "dir" | "symlink" | "submodule";
download_url?: string | null;
};
/* ************************************** */
/* lib/types/markdownImageTypes.d.ts */
@@ -2591,6 +2601,32 @@ export interface InputPromptOptions {
draggable?: boolean;
}
/* ************************************* */
/* lib/types/scriptStoreTypes.d.ts */
/* ************************************* */
export type ScriptStoreCategory = {
name: string;
description: string;
};
export type ScriptStoreEntry = {
name: string;
file: string;
installUrl: string;
iconUrl: string;
author: string;
authorUrl: string;
sourceUrl: string;
descriptionHtml: string;
categories: string[];
featuredRank?: number;
};
export type ScriptStoreCatalog = {
version: number;
categories: ScriptStoreCategory[];
scripts: ScriptStoreEntry[];
};
export type ScriptStoreInstallState = "install" | "update" | "up-to-date" | "error";
/* ************************************** */
/* lib/types/sidepanelTabTypes.d.ts */
/* ************************************** */
+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.1",
"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
Binary file not shown.
+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,
+6
View File
@@ -2,6 +2,12 @@ import "obsidian";
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { errorlog } from "src/utils/coreUtils";
import type ExcalidrawView from "src/view/ExcalidrawView";
export type {
ExcalidrawAutomate,
ViewLinkClickContext,
ViewLinkClickHook,
} from "src/shared/ExcalidrawAutomate";
export type { ExcalidrawEphemeralState } from "src/types/excalidrawViewTypes";
//import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
//export ExcalidrawAutomate from "./ExcalidrawAutomate";
//export {ExcalidrawAutomate} from "./ExcaildrawAutomate";
+6 -54
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
*/
@@ -1227,7 +1174,11 @@ export default class ExcalidrawPlugin extends Plugin {
return file.path;
}
public async setMarkdownView(leaf: WorkspaceLeaf, eState?: ViewStateResult) {
public async setMarkdownView(
leaf: WorkspaceLeaf,
eState?: ViewStateResult,
active?: boolean,
) {
const state = leaf.view.getState();
//Note v2.0.19: I have absolutely no idea why I thought this is necessary. Removing this.
@@ -1242,6 +1193,7 @@ export default class ExcalidrawPlugin extends Plugin {
type: "markdown",
state,
popstate: true,
...(active === undefined ? {} : { active }),
} as ViewState,
eState ? eState : { focus: true },
);
+2 -9
View File
@@ -12,7 +12,6 @@ import {
View,
} from "obsidian";
import {
VIEW_TYPE_EXCALIDRAW,
ICON_NAME,
IMAGE_TYPES,
DEVICE,
@@ -2508,20 +2507,14 @@ export class CommandManager {
const excalidrawView =
this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (excalidrawView) {
void excalidrawView.openAsMarkdown();
void this.plugin.ea.toggleViewMode(excalidrawView);
return;
}
const markdownView =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView && fileIsExcalidraw) {
void (async () => {
await markdownView.save();
const activeLeaf = markdownView.leaf;
this.plugin.excalidrawFileModes[activeLeaf.id || activeFile.path] =
VIEW_TYPE_EXCALIDRAW;
await setExcalidrawView(activeLeaf);
})();
void this.plugin.ea.toggleViewMode(markdownView);
}
},
});
-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",
+25
View File
@@ -25,6 +25,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
## New from Excalidraw.com
- Create sticky notes with the new **Sticky note** tool or the **N** shortcut. Labels automatically fit and grow with their note, with dedicated colors and a creation-date footer. [#12064](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12064)
- Right click panning (without enabling a specific "Miro-style" setting) is now supported. [#12110](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12110)
- Customize font top picks by drag and drop. To set top picks as your default for all new drawings save the file with your toppick choices as a template. [#12160](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12160)
## Fixed / Refactored
- Lasso tool was not available in the More Tools menu in Tray Mode [#2937](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2937)
@@ -36,6 +37,30 @@ 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 a view-targeted representation toggle for integrations. It switches the supplied live Excalidraw-backed view directly between Excalidraw and Markdown without relying on the workspace active leaf or command routing:
\`\`\`ts
public async toggleViewMode(view: View): Promise<View | null>;
\`\`\`
- Integrations can now register a link handler on one target view and receive Excalidraw's resolved pane action without replacing the global hook or copying modifier settings. A new zoom helper fits the complete target scene:
\`\`\`ts
registerViewLinkClickHook(hook: ViewLinkClickHook): () => void;
viewZoomToFit(): void;
\`\`\`
- Excalidraw view state accepts one-shot \`mode: "view" | "edit"\` and \`zoomToFit: true\` options. This lets host integrations open a drawing in its intended mode without polling the React canvas.
- Link-open callbacks now receive a usable native event even when an upstream synthesized event omitted it.
- 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();
}
}
+38
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;",
@@ -969,6 +987,14 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Returns a new instance of ExcalidrawAutomate.",
after: "",
},
{
field: "toggleViewMode",
code: "public async toggleViewMode(view: View): Promise<View | null>",
desc:
"Toggles the supplied live Excalidraw-backed view between Excalidraw and Markdown without relying on the active workspace leaf. " +
"The input may be an ExcalidrawView or a MarkdownView whose file is an Excalidraw drawing. Returns the replacement view after a successful toggle, or null when the supplied view is not eligible.",
after: "(view);",
},
{
field: "getAttachmentFilepath",
code: "async getAttachmentFilepath(filename: string): Promise<string>",
@@ -1293,6 +1319,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Sets Excalidraw in the targetView to view-mode",
after: "",
},
{
field: "registerViewLinkClickHook",
code: "registerViewLinkClickHook(hook: ViewLinkClickHook): () => void;",
desc: "Registers a link-click hook only for the target view and returns a disposer. The callback receives the resolved pane action, so integrations do not need to inspect Excalidraw settings or reproduce platform modifier rules. Return false to prevent native navigation.",
after: "",
},
{
field: "splitFolderAndFilename",
code: "splitFolderAndFilename(filepath: string): { folderpath: string; filename: string; basename: string; extension: string; }",
@@ -1313,6 +1345,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Zoom tarteView to fit elements provided as input. elements === [] will zoom to fit the entire scene. SelectElements toggles whether the elements should be in a selected state at the end of the operation.",
after: "",
},
{
field: "viewZoomToFit",
code: "viewZoomToFit(): void",
desc: "Zooms the target view to fit its complete scene using Excalidraw's normal maximum zoom and safety checks.",
after: "",
},
{
field: "compressToBase64",
code: "compressToBase64(str: string):string",
+176 -27
View File
@@ -23,6 +23,7 @@ import {
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
import {
Editor,
MarkdownView,
Notice,
OpenViewState,
RequestUrlResponse,
@@ -50,6 +51,7 @@ import {
refreshTextDimensions,
getFontFamilyString,
convertToExcalidrawElements,
VIEW_TYPE_EXCALIDRAW,
} from "src/constants/constants";
import {
blobToBase64,
@@ -79,6 +81,7 @@ import {
isObsidianThemeDark,
mergeMarkdownFiles,
openLeaf,
setExcalidrawView,
} from "src/utils/obsidianUtils";
import { getAttachmentsFolderAndFilePath } from "src/utils/pathUtils";
import {
@@ -240,6 +243,19 @@ import { RELEASE_NOTES } from "./Dialogs/Messages";
type ExcalidrawAutomateHelpTarget = ((...args: unknown[]) => unknown) | string;
/** Details supplied to an integration when a link is activated in one Excalidraw view. */
export interface ViewLinkClickContext {
element: ExcalidrawElement;
linkText: string;
event: MouseEvent | null;
action: PaneTarget;
view: ExcalidrawView;
ea: ExcalidrawAutomate;
}
/** A view-scoped link hook. Return `false` to prevent Excalidraw's default navigation. */
export type ViewLinkClickHook = (context: ViewLinkClickContext) => boolean | void;
extendPlugins([
HarmonyPlugin,
MixPlugin,
@@ -870,6 +886,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 +3902,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 +3915,7 @@ export class ExcalidrawAutomate {
},
captureUpdate: CaptureUpdateAction.NEVER,
});
this.targetView.toolsPanelRef?.current?.setExcalidrawViewMode(
!isFullscreen,
);
view.toolsPanelRef?.current?.setExcalidrawViewMode(!isFullscreen);
}
if (isFullscreen) {
@@ -3899,11 +3930,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,
@@ -3911,6 +3941,25 @@ export class ExcalidrawAutomate {
view.toolsPanelRef?.current?.setExcalidrawViewMode(enabled);
}
/**
* Registers a link-click hook on the target view only.
*
* The callback receives Excalidraw's resolved pane action, so integrations do not need to read
* plugin settings or reproduce platform-specific modifier-key rules. The returned disposer must
* be called when the integration unmounts. Returning `false` from the callback prevents native
* link navigation.
*
* @param hook - Callback invoked for links activated in the current target view.
* @returns A disposer that unregisters this callback, or a no-op disposer if no view is ready.
*/
registerViewLinkClickHook(hook: ViewLinkClickHook): () => void {
const view = this.getReadyTargetView("registerViewLinkClickHook()");
if (!view) {
return () => undefined;
}
return view.registerViewLinkClickHook(hook, this);
}
/**
* Updates the scene in the target view.
* @param {Object} scene - The scene to load to Excalidraw.
@@ -3933,15 +3982,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 +4065,40 @@ 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);
}
/**
* Zooms the target view to fit its complete scene using Excalidraw's normal safety limits.
*
* This honors the plugin's maximum zoom setting and skips unsafe automatic zoom work while the
* view is closing, editing text, or displaying a modal.
*/
viewZoomToFit(): void {
const view = this.getReadyTargetView("viewZoomToFit()");
if (!view) {
return;
}
view.zoomToFit(false);
}
/**
* 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 +4116,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 +4143,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;
}
@@ -4934,6 +5016,65 @@ export class ExcalidrawAutomate {
return view instanceof ExcalidrawView;
}
/**
* Toggles an Excalidraw-backed view between the native Excalidraw and Markdown representations.
*
* The supplied view is the authority for the transition; this method does not depend on the
* workspace's currently active leaf or the command palette. Markdown views are accepted only
* when their file is an Excalidraw file. Excalidraw compatibility-mode views are left unchanged.
*
* @param {View} view - The ExcalidrawView or MarkdownView to toggle.
* @returns {Promise<View | null>} The replacement view after a successful toggle, or null when
* the supplied view is not a live Excalidraw-backed view that can be toggled.
*/
public async toggleViewMode(view: View): Promise<View | null> {
if (view instanceof ExcalidrawView) {
const file = view.file;
const leaf = view.leaf;
if (
!file ||
!leaf ||
leaf.view !== view ||
view.compatibilityMode ||
!this.isExcalidrawFile(file)
) {
return null;
}
const preserveInactive = this.plugin.app.workspace.getMostRecentLeaf() !== leaf;
await view.openAsMarkdown(
preserveInactive ? { focus: false } : undefined,
preserveInactive ? false : undefined,
);
return leaf.view instanceof MarkdownView ? leaf.view : null;
}
if (!(view instanceof MarkdownView)) {
return null;
}
const file = view.file;
const leaf = view.leaf;
if (
!file ||
!leaf ||
leaf.view !== view ||
!this.isExcalidrawFile(file)
) {
return null;
}
await view.save();
this.plugin.excalidrawFileModes[leaf.id || file.path] =
VIEW_TYPE_EXCALIDRAW;
const preserveInactive = this.plugin.app.workspace.getMostRecentLeaf() !== leaf;
await setExcalidrawView(
leaf,
preserveInactive ? { active: false, focus: false } : undefined,
);
return leaf.view instanceof ExcalidrawView ? leaf.view : null;
}
/**
* Sets the selection in the view.
* @param {ExcalidrawElement[] | string[]} elements - Array of elements or element IDs to select.
@@ -5381,6 +5522,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 {
+4
View File
@@ -80,6 +80,10 @@ export interface ExcalidrawEphemeralState {
rename?: string;
subpath?: string;
line?: number;
/** One-shot view/edit mode requested by an integration opening this drawing. */
mode?: "view" | "edit";
/** One-shot request to fit the scene after its first complete render. */
zoomToFit?: boolean;
match?: {
content?: string;
matches?: [number, number][];
+21 -6
View File
@@ -582,12 +582,27 @@ export const foldExcalidrawSection = (view: MarkdownView) => {
}
};
export async function setExcalidrawView(leaf: WorkspaceLeaf) {
await leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state: leaf.view.getState(),
popstate: true,
} as ViewState);
export interface ViewTransitionOptions {
active?: boolean;
focus?: boolean;
}
/** Replace a leaf with an Excalidraw view while honoring explicit activation and focus policy. */
export async function setExcalidrawView(
leaf: WorkspaceLeaf,
options?: ViewTransitionOptions,
) {
await leaf.setViewState(
{
type: VIEW_TYPE_EXCALIDRAW,
state: leaf.view.getState(),
popstate: true,
...(options?.active === undefined ? {} : { active: options.active }),
} as ViewState,
options?.focus === undefined
? undefined
: { focus: options.focus },
);
}
export async function closeLeafView(leaf: WorkspaceLeaf) {
+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;
}
};
+33 -3
View File
@@ -1,4 +1,4 @@
import { App, FileView, WorkspaceLeaf } from "obsidian";
import { App, FileView, WorkspaceLeaf, type ViewStateResult } from "obsidian";
import { DEVICE, VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
@@ -18,6 +18,11 @@ export async function switchToExcalidraw(app: App) {
}
export class ExcalidrawLoading extends FileView {
private integrationState: {
mode?: "view" | "edit";
zoomToFit?: true;
} = {};
constructor(
leaf: WorkspaceLeaf,
private plugin: ExcalidrawPlugin,
@@ -30,19 +35,44 @@ export class ExcalidrawLoading extends FileView {
this.displayLoadingText();
}
/** Retains one-shot integration options while the loading view owns the leaf. */
public async setState(
state: Record<string, unknown>,
result: ViewStateResult,
): Promise<void> {
this.integrationState = {
...(state.mode === "view" || state.mode === "edit"
? { mode: state.mode }
: {}),
...(state.zoomToFit === true ? { zoomToFit: true as const } : {}),
};
await super.setState(state, result);
}
/** Includes retained integration options in the handoff to the real Excalidraw view. */
public getState(): Record<string, unknown> {
return { ...super.getState(), ...this.integrationState };
}
public async switchToExcalidraw() {
const prevLeaf = this.app.workspace.getLeaf();
const state = this.leaf.view.getState();
const preserveInactive = this.app.workspace.getMostRecentLeaf() !== this.leaf;
const inactiveResult = preserveInactive
? ({ focus: false } as unknown as ViewStateResult)
: undefined;
// Force a fresh view instance: switching to the same type can be a no-op.
await this.leaf.setViewState({
type: "empty",
state: {},
});
...(preserveInactive ? { active: false } : {}),
}, inactiveResult);
await this.leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state,
});
...(preserveInactive ? { active: false } : {}),
}, inactiveResult);
if (DEVICE.isDesktop) {
return;
}
+80 -17
View File
@@ -56,7 +56,11 @@ import {
sceneCoordsToViewportCoords,
} from "../constants/constants";
import ExcalidrawPlugin from "../core/main";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import {
ExcalidrawAutomate,
type ViewLinkClickHook,
} from "../shared/ExcalidrawAutomate";
import type { PaneTarget } from "../types/utilTypes";
import { TextMode, getTextMode } from "../shared/TextMode";
import { ExcalidrawSidepanelView } from "./sidepanel/Sidepanel";
import {
@@ -578,6 +582,8 @@ export default class ExcalidrawView
private lastAppState: AppState | null = null;
private lastElementsVersion: number = -1;
private pendingMigrationHandoffToken: string | null = null;
private pendingOpenMode: "view" | "edit" | null = null;
private pendingOpenZoomToFit = false;
private pendingMigrationBinaryFiles: BinaryFiles | null = null;
private migrationBinaryFilePublication: Promise<void> | null = null;
private isSynchronizing = false;
@@ -1678,8 +1684,22 @@ export default class ExcalidrawView
element: ExcalidrawElement,
link: string,
event: MouseEvent | null,
action?: PaneTarget,
): boolean {
return this.linkNavigationManager.handleLinkHookCall(element, link, event);
return this.linkNavigationManager.handleLinkHookCall(
element,
link,
event,
action,
);
}
/** Registers an integration hook for link clicks originating from this view only. */
public registerViewLinkClickHook(
hook: ViewLinkClickHook,
ea: ExcalidrawAutomate,
): () => void {
return this.linkNavigationManager.registerViewLinkClickHook(hook, ea);
}
private getLinkTextForElement(
@@ -2983,6 +3003,9 @@ export default class ExcalidrawView
typeof state?.migrationHandoffToken === "string"
? state.migrationHandoffToken
: null;
this.pendingOpenMode =
state?.mode === "view" || state?.mode === "edit" ? state.mode : null;
this.pendingOpenZoomToFit = state?.zoomToFit === true;
await super.setState(state, result);
}
@@ -4008,16 +4031,21 @@ export default class ExcalidrawView
this.semaphores.justLoaded = justloaded;
this.clearDirty();
const om = this.excalidrawData.getOpenMode();
const requestedViewModeEnabled = this.pendingOpenMode === null
? null
: this.pendingOpenMode === "view";
this.clearOwnWriteReloadSuppression();
const penEnabled = this.plugin.isPenMode();
const api = this.excalidrawAPI;
if (api) {
//isLoaded flags that a new file is being loaded, isLoaded will be true after loadDrawing completes
const viewModeEnabled = !this.isLoaded
? excalidrawData.elements.length > 0
? om.viewModeEnabled
: false
: api.getAppState().viewModeEnabled;
const viewModeEnabled = requestedViewModeEnabled ?? (
!this.isLoaded
? excalidrawData.elements.length > 0
? om.viewModeEnabled
: false
: api.getAppState().viewModeEnabled
);
const zenModeEnabled = !this.isLoaded
? om.zenModeEnabled
: api.getAppState().zenModeEnabled;
@@ -4104,8 +4132,9 @@ export default class ExcalidrawView
}
: {}),
zenModeEnabled: om.zenModeEnabled,
viewModeEnabled:
excalidrawData.elements.length > 0 ? om.viewModeEnabled : false,
viewModeEnabled: requestedViewModeEnabled ?? (
excalidrawData.elements.length > 0 ? om.viewModeEnabled : false
),
linkOpacity: this.excalidrawData.getLinkOpacity(),
penMode: penEnabled,
penDetected: penEnabled,
@@ -4498,7 +4527,7 @@ export default class ExcalidrawView
return ICON_NAME;
}
async setMarkdownView(eState?: MarkdownViewOpenState) {
async setMarkdownView(eState?: MarkdownViewOpenState, active?: boolean) {
//save before switching to markdown view.
//this would also happen onClose, but it does not hurt to save it here
//this way isDirty() will return false in onClose, thus
@@ -4531,7 +4560,11 @@ export default class ExcalidrawView
}
plugin.excalidrawFileModes[this.id || file.path] = "markdown";
await plugin.setMarkdownView(leaf, eState as ViewStateResult | undefined);
await plugin.setMarkdownView(
leaf,
eState as ViewStateResult | undefined,
active,
);
} catch (e: unknown) {
errorlog({
where: "ExcalidrawView.setMarkdownView",
@@ -4541,7 +4574,7 @@ export default class ExcalidrawView
}
}
public async openAsMarkdown(eState?: MarkdownViewOpenState) {
public async openAsMarkdown(eState?: MarkdownViewOpenState, active?: boolean) {
if (
this.plugin.settings.compress &&
this.plugin.settings.decompressForMDView
@@ -4551,7 +4584,7 @@ export default class ExcalidrawView
} else if (this.isDirty()) {
await this.save(true, true, true);
}
void this.setMarkdownView(eState);
await this.setMarkdownView(eState, active);
}
public async convertExcalidrawToMD() {
@@ -5320,6 +5353,7 @@ export default class ExcalidrawView
gridColor: st.gridColor,
colorPalette: st.colorPalette,
colorTopPicks: st.colorTopPicks,
fontTopPicks: st.fontTopPicks,
currentStrokeOptions: st.currentStrokeOptions,
frameRendering: st.frameRendering,
objectsSnapModeEnabled: st.objectsSnapModeEnabled,
@@ -5943,11 +5977,24 @@ export default class ExcalidrawView
return;
}
this.semaphores.justLoaded = false;
const pendingOpenMode = this.pendingOpenMode;
const pendingOpenZoomToFit = this.pendingOpenZoomToFit;
this.pendingOpenMode = null;
this.pendingOpenZoomToFit = false;
if (pendingOpenMode) {
const viewModeEnabled = pendingOpenMode === "view";
this.updateScene({
appState: { viewModeEnabled },
captureUpdate: CaptureUpdateAction.NEVER,
});
this.toolsPanelRef?.current?.setExcalidrawViewMode(viewModeEnabled);
}
if (
!this.semaphores.preventAutozoom &&
this.plugin.settings.zoomToFitOnOpen
(pendingOpenZoomToFit || this.plugin.settings.zoomToFitOnOpen)
) {
if (
pendingOpenZoomToFit ||
getExcalidraAndMarkdowViewsForFile(this.app, this.file).length === 1
) {
this.zoomToFit(false, true);
@@ -6677,8 +6724,24 @@ export default class ExcalidrawView
}
window.setTimeout(() => this.removeLinkTooltip(), 500);
let event = e?.detail?.nativeEvent;
if (this.handleLinkHookCall(element, link, event as MouseEvent)) {
const nativeEvent = e?.detail?.nativeEvent;
const ownerMouseEvent = (
this.ownerWindow as (Window & { MouseEvent?: typeof MouseEvent }) | null
)?.MouseEvent;
const event = nativeEvent ?? new (ownerMouseEvent ?? MouseEvent)("click", {
...emulateKeysForLinkClick("new-tab"),
});
const hasModifier =
event.shiftKey || event.ctrlKey || event.metaKey || event.altKey;
const linkAction = hasModifier ? linkClickModifierType(event) : "new-tab";
if (
this.handleLinkHookCall(
element,
link,
event as MouseEvent,
linkAction,
)
) {
return;
}
//if(openExternalLink(element.link, this.app, !isSHIFT(event) && !isWinCTRLorMacCMD(event) && !isWinMETAorMacCTRL(event) && !isWinALTorMacOPT(event) ? element : undefined)) return;
@@ -6686,7 +6749,7 @@ export default class ExcalidrawView
return;
}
if (!event.shiftKey && !event.ctrlKey && !event.metaKey && !event.altKey) {
if (!hasModifier) {
void this.linkClick(
null,
null,
+21 -2
View File
@@ -8,7 +8,14 @@ node.render();
container.appendChild(node.contentEl)
*/
import { Editor, TFile, View, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
import {
type App,
Editor,
TFile,
View,
WorkspaceLeaf,
WorkspaceSplit,
} from "obsidian";
import type ExcalidrawView from "src/view/ExcalidrawView";
import {
getContainerForDocument,
@@ -29,6 +36,12 @@ interface ObsidianCanvas {
removeNode: (node: ObsidianCanvasNode) => void;
}
type DetachedWorkspaceSplit = WorkspaceSplit & {
insertChild(index: number, child: WorkspaceLeaf, resize?: boolean): void;
};
type WorkspaceLeafConstructor = new (app: App) => WorkspaceLeaf;
export interface ObsidianCanvasNodeChild extends View {
file?: TFile;
heading?: string;
@@ -83,7 +96,13 @@ export class CanvasNodeFactory {
rootSplit.getRoot = () =>
app.workspace[doc === mainDocument ? "rootSplit" : "floatingSplit"];
rootSplit.getContainer = () => getContainerForDocument(doc);
this.leaf = app.workspace.createLeafInParent(rootSplit, 0);
// `workspace.createLeafInParent()` activates its new leaf and schedules a workspace layout
// update. That is observable even though this split is detached: on mobile it navigates away
// from an open sidebar that hosts an embedded Excalidraw view. Construct and insert the
// internal Canvas leaf directly so initialization has no workspace activation side effect.
const LeafConstructor = WorkspaceLeaf as unknown as WorkspaceLeafConstructor;
this.leaf = new LeafConstructor(app);
(rootSplit as DetachedWorkspaceSplit).insertChild(0, this.leaf);
this.canvas = canvasPlugin.views.canvas(this.leaf).canvas as ObsidianCanvas;
this.initialized = true;
}
+45 -1
View File
@@ -16,6 +16,10 @@ import type {
SelectedImage,
} from "../../types/excalidrawViewTypes";
import type { ModifierKeys } from "../../utils/modifierkeyHelper";
import type {
ExcalidrawAutomate,
ViewLinkClickHook,
} from "../../shared/ExcalidrawAutomate";
import { getMermaidText, shouldRenderMermaid } from "../../utils/mermaidUtils";
import type ExcalidrawView from "../ExcalidrawView";
@@ -57,6 +61,11 @@ export interface ViewLinkNavigationDependencies {
* this module does not create a runtime import cycle.
*/
export class ViewLinkNavigationManager {
private readonly viewLinkClickHooks = new Set<{
hook: ViewLinkClickHook;
ea: ExcalidrawAutomate;
}>();
public constructor(
private readonly view: ExcalidrawView,
private readonly dependencies: ViewLinkNavigationDependencies,
@@ -80,6 +89,9 @@ export class ViewLinkNavigationManager {
element: ExcalidrawElement,
link: string,
event: MouseEvent | null,
action = this.dependencies.linkClickModifierType(
event ?? this.dependencies.emulateKeysForLinkClick("new-tab"),
),
): boolean {
if (this.view.getHookServer().onLinkClickHook) {
try {
@@ -102,9 +114,41 @@ export class ViewLinkNavigationManager {
});
}
}
for (const registration of this.viewLinkClickHooks) {
try {
if (
registration.hook({
element,
linkText: link,
event,
action,
view: this.view,
ea: registration.ea,
}) === false
) {
return true;
}
} catch (e: unknown) {
this.dependencies.errorlog({
where: "ViewLinkNavigationManager.handleLinkHookCall",
fn: "registerViewLinkClickHook callback",
error: e,
});
}
}
return false;
}
/** Registers a link-click hook whose lifetime and dispatch are scoped to this view. */
public registerViewLinkClickHook(
hook: ViewLinkClickHook,
ea: ExcalidrawAutomate,
): () => void {
const registration = { hook, ea };
this.viewLinkClickHooks.add(registration);
return () => this.viewLinkClickHooks.delete(registration);
}
/** Resolves the effective link and source element for a view selection. */
public getLinkTextForElement(
selectedText: SelectedElementWithLink,
@@ -550,7 +594,7 @@ export class ViewLinkNavigationManager {
const sceneElements = this.view.excalidrawAPI.getSceneElements() as readonly
ExcalidrawElement[];
const el = sceneElements.filter((element) => element.id === id)[0];
if (this.view.handleLinkHookCall(el, linkText, ev)) {
if (this.view.handleLinkHookCall(el, linkText, ev, linkClickType)) {
return;
}
+14 -14
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;
@@ -1098,7 +1094,7 @@ End Obsidian Sheets Plus support
/* Radix portals the canvas menu under the owning document's body. Keep it on
Obsidian's menu layer so body-level Obsidian tooltips remain above it. */
body > [data-radix-portal] .main-menu {
body>[data-radix-portal] .main-menu {
z-index: var(--layer-menu);
}
@@ -1727,7 +1723,7 @@ button.excalidraw-font-picker {
align-items: start;
}
.excalidraw-filename-information > :first-child {
.excalidraw-filename-information> :first-child {
min-width: 0;
}
@@ -1795,7 +1791,7 @@ button.excalidraw-font-picker {
text-decoration: none;
}
.excalidraw-script-store__support-item + .excalidraw-script-store__support-item {
.excalidraw-script-store__support-item+.excalidraw-script-store__support-item {
border-left: 1px solid var(--background-modifier-border);
}
@@ -1945,7 +1941,7 @@ button.excalidraw-font-picker {
min-width: 12rem;
}
.excalidraw-script-store__search > span {
.excalidraw-script-store__search>span {
position: absolute;
left: 0.65rem;
top: 50%;
@@ -2170,7 +2166,7 @@ button.excalidraw-font-picker {
background: var(--background-secondary);
}
.excalidraw-script-store__card-footer > span {
.excalidraw-script-store__card-footer>span {
min-width: 0;
color: var(--text-faint);
font-size: var(--font-ui-smaller);
@@ -2276,7 +2272,7 @@ button.excalidraw-font-picker {
font-size: var(--font-ui-medium);
}
.excalidraw-script-store__local-copy + .excalidraw-script-store__local-copy {
.excalidraw-script-store__local-copy+.excalidraw-script-store__local-copy {
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid var(--background-modifier-border);
@@ -2341,7 +2337,7 @@ button.excalidraw-font-picker {
border-top: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__group-row > label {
.excalidraw-script-store__group-row>label {
flex: 0 0 auto;
font-weight: var(--font-medium);
}
@@ -2380,7 +2376,7 @@ button.excalidraw-font-picker {
grid-template-columns: 1fr;
}
.excalidraw-script-store__support-item + .excalidraw-script-store__support-item {
.excalidraw-script-store__support-item+.excalidraw-script-store__support-item {
border-left: 0;
border-top: 1px solid var(--background-modifier-border);
}
@@ -2407,7 +2403,7 @@ button.excalidraw-font-picker {
flex: 1 1 12rem;
}
.excalidraw-script-store__controls > select,
.excalidraw-script-store__controls>select,
.excalidraw-script-store__view-toggle {
flex: 1 1 auto;
}
@@ -2432,8 +2428,12 @@ button.excalidraw-font-picker {
align-items: stretch;
}
.excalidraw-script-store__controls > select,
.excalidraw-script-store__controls>select,
.excalidraw-script-store__view-toggle {
width: 100%;
}
}
.excalidraw .excalidraw-tooltip-wrapper {
--no-tooltip: true;
}