Compare commits

..
Author SHA1 Message Date
zsviczian 45684d633c instrumentation 2026-09-15 21:31:00 +02:00
74 changed files with 3427 additions and 65944 deletions

No files matched your search

-14
View File
@@ -27,20 +27,6 @@ Before spending your valuable time writing code for a new feature or significant
The shipped plugin is `dist/main.js`, `dist/styles.css`, and `dist/manifest.json`. Keep `main.js` below the release size limit and report its byte size after dependency or packaging changes.
## Updating the EA script template
`npm run doc` and `npm run skill` both build the public library declarations, then
run full documentation generation. When `../ea-script-template` exists, they also
refresh its local agent references, generated EA declaration graph and provenance,
type dependencies, and template update manifest. The template consumes declarations
only; personal script workspaces no longer need this plugin as a Git dependency.
After generation, run `npm install`, `npm run check`, `npm run build`, and
`npm run test:template` in the template. Review both repositories separately and
publish the template's updated `master` so users can receive the snapshot with
`npm run update-template`. See the template's `.template/README.md` for ownership,
conflict handling, and the one-time adoption procedure for older workspaces.
## 🧪 Testing
At this time, the project **has no comprehensive automated test suite**. As a contributor, you are responsible for testing your changes thoroughly.
-1
View File
@@ -219,7 +219,6 @@ final upstream work is merged into the fork and installed in the plugin.
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-09-16 | Fixed mixed-DPI popout selection alignment (#2940) | `InteractiveCanvas` now uses the `scale` supplied by its mounted `App`, which is derived from that editor's `ownerWindow.devicePixelRatio`, instead of reading the shared runtime's global `window.devicePixelRatio`. This preserves correct backing-store scaling for selection rectangles and other interactive-canvas overlays when a Windows popout uses a different display DPI. | Fork `yarn build:obsidian`, root `yarn test:typecheck`, and the plugin `npm run build` against the locally generated fork artifacts passed. The user confirmed the original #2940 reproduction is fixed. The focused selection suite remains blocked before test execution by the existing `createTestHook` test-harness error. |
| 2026-09-13 | Revised checkpoint 8 after Markdown-image force-save overtook a pending shape | Reacquiring Markdown-image ownership kept view B's shape pending in view A. **Render now** then deliberately bypassed the same-file save guard and wrote A's stale scene, deleting the shape. Save initiators now reconcile pending disk state through only their own gate record, preserve the actively edited Markdown-image source, resolve the current merged image element, and then persist. Render, close, handoff, post-flush, and Canvas-entry force-save paths share this boundary; accepted sync also advances the raw Markdown envelope | Owner-specific bypass was added to the deterministic gate check. All persistence/classifier/snapshot/routing scripts, focused and unused-symbol lint, production build, bundle syntax, and diff checks pass with established baselines. Revised bundle: 4,917,773 bytes, SHA-256 `55fb6a7a981e17b2445631f00d72438a441ed9c039a0c25d570141d893fbfbab`. First retest the exact Markdown-image A → shape B → reopen/render A sequence and verify both changes in both views and after reopen |
| 2026-09-13 | Revised checkpoint 8 after same-file edit → migration overwrite | Moving a large drawing immediately after exiting a back-of-note editor allowed migration to invalidate the pending synchronization and serialize the captured scene against stale view `data`, later deleting the newer paragraph from disk. The source unmount remains before the first await; affected Markdown migrations now wait only the established same-file grace and reread the Vault envelope before serialization. No claim is made about whether the exposed interleaving predates checkpoint 8 | Focused view lint retains 18 established findings with none in the migration change; unused-symbol lint, gate check, production build, bundle syntax, and diff checks pass with 33 established circular warnings. Revised bundle: 4,915,716 bytes, SHA-256 `a504f2bf5a822f5a361b944b101baaad5f89ba9589321a710cfcfd285be31667`. First retest the exact paragraph-edit, exit, immediate **Move to new window** sequence and require both durable text and no serious-error Notice |
| 2026-09-13 | Implemented checkpoint 8 view-local same-file edit gate | Replaced the shared same-file Boolean/timer with idempotent owner identities and independent grace records. Canvas elements and Markdown-image controllers cannot clear each other; timer callbacks are realm-owned and stale-safe. Canvas entry is request-fenced across its pre-edit save so exit/removal cannot leave a delayed editor or leaked owner. Blocked modifies retain the existing pending latest-state synchronization until final release, and Markdown-image reload no longer needs explicit clear/re-arm gaps | Gate, classifier, snapshot, routing, persistence-queue, and backup-queue checks pass. Focused and unused-symbol lint, production build, bundle syntax, and diff checks pass with established lint/circular-warning baselines. Candidate bundle: 4,915,501 bytes, SHA-256 `6dad62e31c17e2d30ad38e52d59013941415ce3d3249e126aa984e6b176017cc`. Runtime gate: overlapping owners, final modify during grace, Markdown-image switching/close, navigation, both popout workflows, large-scene alternating edits, and physical mobile |
+10 -10
View File
@@ -8,7 +8,7 @@ Scope summary:
- Keep [docs/AITrainingData](docs/AITrainingData) as the canonical output location.
- Keep [docs/AITrainingData/ExcalidrawAutomate full library for LLM training.md](docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md) as a stable entrypoint, but curate it as a router to skill-first references.
- Use one unified generator behind `npm run doc`.
- Keep [ea-scripts/script-store.json](ea-scripts/script-store.json) as the contributor-facing catalog; keep [ea-scripts/index-new.md](ea-scripts/index-new.md) frozen for legacy clients and generate only targeted update metadata in `directory-info.json`.
- Keep [ea-scripts/index-new.md](ea-scripts/index-new.md) manually curated.
- Keep skill generation manually triggered by maintainer workflows (no automatic watcher/CI updates in this phase).
- Add strict naming rules for script preview images under [images](images).
@@ -23,10 +23,10 @@ Scope summary:
- It must warn AI tools that generated code quality may fail if linked skill/reference URLs are inaccessible (for example: URL access disabled in some chat tools).
3. Script library publishing guidance
- [ea-scripts/script-store.json](ea-scripts/script-store.json) is the contributor-facing metadata source.
- `index-new.md` remains manual.
- Agents should be guided to open a proper PR for publishing scripts in this repository instead of trying to bypass the normal contribution workflow.
- `npm run script-store:build` validates the current catalog and advances `directory-info.json` only for script/icon files that actually changed; it never rewrites `index-new.md`.
- Historical `mtime` values must remain untouched; they are part of the plugin's backward-compatible update-detection contract.
- Every publishing PR (new script or script update) must update [ea-scripts/directory-info.json](ea-scripts/directory-info.json).
- For updates, the `mtime` value for the updated script file must be refreshed so the plugin can detect local update availability.
4. Template repository direction
- A separate repository will be created first.
@@ -56,7 +56,7 @@ Target branch: `improved-scripting-skills`.
| Unify generator implementation behind `npm run doc` | Complete | Added shared generator core at [scripts/excalidraw-docs-generator-core.mjs](scripts/excalidraw-docs-generator-core.mjs); both [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs) and [scripts/skill-builder.mjs](scripts/skill-builder.mjs) are thin wrappers over one code path |
| Ensure canonical pen type completeness in generated docs | Complete | Generated references now include canonical Obsidian pen stroke type definitions plus the full public `src/types` and `lib/types` declaration surface |
| Curate legacy training entrypoint warning and routing | Complete | Legacy training entrypoint now warns about inaccessible references, names the master repository, and routes agents to the curated skill/reference set with absolute GitHub URLs |
| Add PR publishing workflow guidance for scripting agents | Complete | Generated skill guidance now directs script publishing through PRs, uses `script-store.json` as catalog metadata, and generates only targeted legacy mtime updates |
| Add PR publishing workflow guidance for scripting agents | Complete | Generated skill guidance now directs script publishing through PRs, keeps `index-new.md` manual, and requires `directory-info.json` mtime updates |
| Add strict image naming and validation | Complete | Generator now warns on non-conforming preview filenames and documents the `scripts-{slug}.{ext}` rule in generated publishing guidance |
| Optional template-repo sync from `npm run doc` | Complete | `npm run doc` now refreshes a co-located `ea-script-template` bootstrap under `.ai/excalidraw-automate/` when the sibling repo is present |
@@ -123,12 +123,12 @@ Planned changes:
- Add concise maintainer-approved workflow guidance in skill docs:
- add script to [ea-scripts](ea-scripts)
- add image to [images](images)
- add or update the entry in [ea-scripts/script-store.json](ea-scripts/script-store.json)
- run `npm run script-store:check` and `npm run script-store:build`
- allow the generator to advance only the changed script/icon `mtime` entry in [ea-scripts/directory-info.json](ea-scripts/directory-info.json)
- update [ea-scripts/index-new.md](ea-scripts/index-new.md) manually
- update [ea-scripts/directory-info.json](ea-scripts/directory-info.json) in the same PR
- for script updates, refresh the target script `mtime` entry in [ea-scripts/directory-info.json](ea-scripts/directory-info.json)
- keep AI training material updates out of script publishing PRs
- open PR with focused diff and validation notes
- Treat `index-new.md` as a frozen backward-compatibility catalog. Routine publishing must not modify it; new scripts are intentionally unavailable to older clients unless a maintainer explicitly updates the legacy catalog separately.
- Explicitly avoid automating `index-new.md`.
Acceptance:
- Publishing workflow appears in generated skill material.
@@ -136,7 +136,7 @@ Acceptance:
Status:
- Complete.
- The generated skill file now includes a dedicated publishing workflow section with absolute repository links, PR-only guidance, a frozen legacy catalog, and targeted `directory-info.json` updates.
- The generated skill file now includes a dedicated publishing workflow section with absolute repository links, PR-only guidance, manual `index-new.md` curation, and `directory-info.json` update requirements.
### Checkpoint 5: Strict image naming convention and validator
Objective:
@@ -770,30 +770,6 @@ export declare class ExcalidrawAutomate {
* @returns {string} The ID of the added rectangle element.
*/
addRect(topX: number, topY: number, width: number, height: number, id?: string): string;
/**
* Adds a sticky note and its optional fitted label to the ExcalidrawAutomate
* instance. Width and height default to Excalidraw's sticky-note size.
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
* @param {string} text - The sticky-note text. An empty string creates an unlabeled note.
* @param {Object} [formatting] - Sticky-note size and label formatting.
* @param {number} [formatting.width] - The initial width of the note.
* @param {number} [formatting.height] - The initial height of the note.
* @param {number} [formatting.fontSize] - The label's maximum font size.
* @param {number} [formatting.fontFamily] - The label font family.
* @param {"left" | "center" | "right"} [formatting.textAlign] - The label's horizontal alignment.
* @param {"top" | "middle" | "bottom"} [formatting.textVerticalAlign] - The label's vertical alignment.
* @param {string} [id] - The ID of the sticky-note element.
* @returns {string} The ID of the added sticky note.
*/
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;
/**
* Adds a diamond element to the ExcalidrawAutomate instance.
* @param {number} topX - The x-coordinate of the top-left corner.
@@ -871,8 +847,8 @@ export declare class ExcalidrawAutomate {
* @param {Object} [formatting] - Formatting options for the arrow element.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.startArrowHead] - The start arrowhead type.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.endArrowHead] - The end arrowhead type.
* @param {string} [formatting.startObjectId] - The ID of the start object. When omitted, the arrow start is unbound.
* @param {string} [formatting.endObjectId] - The ID of the end object. When omitted, the arrow end is unbound.
* @param {string} [formatting.startObjectId] - The ID of the start object.
* @param {string} [formatting.endObjectId] - The ID of the end object.
* BindMode Determines whether the arrow remains outside the shape or is allowed to
* go all the way inside the shape up to the exact fixed point.
* @param {"inside" | "orbit"} [formatting.startBindMode] - The binding mode for the start object.
@@ -1540,13 +1516,6 @@ export declare class ExcalidrawAutomate {
* @returns {string | null} The groupId or null if not found.
*/
getCommonGroupForElements(elements: ExcalidrawElement[]): string;
/**
* This is a convenience method to get the release notes for the plugin.
* @returns {Object} The release notes object.
*/
getReleaseNotes(): {
[k: string]: string;
};
/**
* Gets all the elements from elements[] that share one or more groupIds with the specified element.
* @param {ExcalidrawElement} element - The element to check.
@@ -2170,6 +2139,7 @@ export type MarkdownBlockCacheEntry = {
};
export interface ViewSemaphores {
warnAboutLinearElementLinkClick: boolean;
embeddableIsEditingSelf: boolean;
popoutUnload: boolean;
windowMigrating: boolean;
viewloaded: boolean;
@@ -2177,7 +2147,12 @@ export interface ViewSemaphores {
scriptsReady: boolean;
justLoaded: boolean;
preventAutozoom: boolean;
autosaving: boolean;
forceSaving: boolean;
dirty: string | null;
preventReload: boolean;
isEditingText: boolean;
saving: boolean;
hoverSleep: boolean;
wheelTimeout: number | null;
shouldSaveImportedImage: boolean;
@@ -2354,22 +2329,12 @@ export interface SelectableFontOption {
/* lib/types/githubTypes.d.ts */
/* ******************************** */
/**
* Metadata entry describing a file in the legacy remote EA scripts directory listing.
* Metadata entry describing a file in the 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 */
@@ -2601,32 +2566,6 @@ 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 */
/* ************************************** */
@@ -2753,6 +2692,26 @@ export interface FrameRenderingOptions {
clip: boolean;
}
export type PaneTarget = "active-pane" | "new-pane" | "popout-window" | "new-tab" | "md-properties";
export interface NestedFileNode {
file: TFile;
/**
* All distinct dependency paths from the root file down to this embedded file.
* Each path is an ordered array of TFile objects starting with the `rootFile` at index 0.
*
* @example
* If Root -> A -> B2.2 and Root -> B -> B2 -> B2.2
* The paths for B2.2 will be:
* [
* [Root, A, B2.2],
* [Root, B, B2, B2.2]
* ]
*
* Usage: To find which top-level embeds to reload if this file changes,
* you can map over `paths` and collect `path[1]`.
*/
paths: TFile[][];
}
export type NestedFileMap = Map<TFile, NestedFileNode>;
/* ************************************** */
/* node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts */
@@ -2917,11 +2876,6 @@ type _ExcalidrawElementBase = Readonly<{
boundElements: readonly BoundElement[] | null;
/** epoch (ms) timestamp of last element update */
updated: number;
/** Client wall-clock creation time in epoch milliseconds; null if unknown.
Preserved for this element's lifetime, including edits and undo/redo,
and excluded from `ElementUpdate` (mutateElement / newElementWith).
Duplicating an element starts a new lifetime. Not an ordering clock. */
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -2933,14 +2887,6 @@ export type ExcalidrawSelectionElement = _ExcalidrawElementBase & {
export type ExcalidrawRectangleElement = _ExcalidrawElementBase & {
type: "rectangle";
};
export type ExcalidrawStickyNoteElement = _ExcalidrawElementBase & Readonly<{
type: "stickynote";
/**
* The height the user set, from which the layout derives `height`: the
* note grows above it to fit its label and never shrinks below it
*/
baseHeight: number;
}>;
export type ExcalidrawDiamondElement = _ExcalidrawElementBase & {
type: "diamond";
};
@@ -3038,14 +2984,14 @@ export type ExcalidrawFrameLikeElement = ExcalidrawFrameElement | ExcalidrawMagi
* These are elements that don't have any additional properties.
*/
export type ExcalidrawGenericElement = ExcalidrawSelectionElement | ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawFlowchartNodeElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawRectanguloidElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawImageElement | ExcalidrawTextElement | ExcalidrawFreeDrawElement | ExcalidrawIframeLikeElement | ExcalidrawFrameLikeElement | ExcalidrawEmbeddableElement | ExcalidrawSelectionElement;
export type ExcalidrawFlowchartNodeElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawRectanguloidElement = ExcalidrawRectangleElement | ExcalidrawImageElement | ExcalidrawTextElement | ExcalidrawFreeDrawElement | ExcalidrawIframeLikeElement | ExcalidrawFrameLikeElement | ExcalidrawEmbeddableElement | ExcalidrawSelectionElement;
/**
* ExcalidrawElement should be JSON serializable and (eventually) contain
* no computed data. The list of all ExcalidrawElements should be shareable
* between peers and contain no state local to the peer.
*/
export type ExcalidrawElement = ExcalidrawGenericElement | ExcalidrawStickyNoteElement | ExcalidrawTextElement | ExcalidrawLinearElement | ExcalidrawArrowElement | ExcalidrawFreeDrawElement | ExcalidrawImageElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement;
export type ExcalidrawElement = ExcalidrawGenericElement | ExcalidrawTextElement | ExcalidrawLinearElement | ExcalidrawArrowElement | ExcalidrawFreeDrawElement | ExcalidrawImageElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement;
export type ExcalidrawNonSelectionElement = Exclude<ExcalidrawElement, ExcalidrawSelectionElement>;
export type Ordered<TElement extends ExcalidrawElement> = TElement & {
index: FractionalIndex;
@@ -3059,20 +3005,11 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
type: "text";
fontSize: number;
fontFamily: FontFamilyValues;
/**
* The font size the user picked, from which the layout derives `fontSize`.
* Today only sticky note labels have one: the auto-fit shrinks below it
* and never above it (compare `baseHeight`, which the note grows above).
* `null` for every other text. Read it through `getBaseFontSize` —
* generic binding repair can detach a label without clearing this, so
* the container decides its meaning.
*/
baseFontSize: number | null;
text: string;
rawText: string;
textAlign: TextAlign;
verticalAlign: VerticalAlign;
containerId: ExcalidrawTextContainer["id"] | null;
containerId: ExcalidrawGenericElement["id"] | null;
originalText: string;
/**
* If `true` the width will fit the text. If `false`, the text will
@@ -3096,8 +3033,8 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
* */
labelPosition?: number | null;
}>;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
export type ExcalidrawTextElementWithContainer = {
containerId: ExcalidrawTextContainer["id"];
} & ExcalidrawTextElement;
@@ -3276,7 +3213,7 @@ declare class App extends React.Component<AppProps, AppState> {
library: AppClassProperties["library"];
libraryItemsFromStorage: LibraryItems | undefined;
id: string;
store: Store;
private store;
private history;
private shouldRenderAllEmbeddables;
excalidrawContainerValue: {
@@ -3303,24 +3240,14 @@ declare class App extends React.Component<AppProps, AppState> {
private appStateObserver;
onStateChange: OnStateChange;
bucketFill: AppBucketFill;
toolDrag: AppToolDrag;
flowchart: AppFlowchart;
cursor: AppCursor;
arrowText: AppArrowText;
pan: AppPan;
viewport: AppViewport;
wheel: AppWheel;
bindModeHandler: ReturnType<typeof setTimeout> | null;
private textWysiwygSubmitHandler;
hitLinkElement?: NonDeletedExcalidrawElement;
lastPointerDownEvent: React.PointerEvent<HTMLElement> | null;
/**
* the handle of the resize in progress while `state.isResizing` — for UI
* that words itself by handle (a sticky note's corners resize
* proportionally, its edges freely); not app state, so it costs no
* re-render of its own
*/
activeResizeHandle: TransformHandleDirection | null;
lastPointerUpEvent: React.PointerEvent<HTMLElement> | PointerEvent | null;
lastPointerUpIsDoubleClick: boolean;
lastPointerMoveEvent: PointerEvent | null;
@@ -3475,12 +3402,6 @@ declare class App extends React.Component<AppProps, AppState> {
missingPointerEventCleanupEmitter: Emitter<[event: PointerEvent | null]>;
onRemoveEventListenersEmitter: Emitter<[]>;
api: ExcalidrawImperativeAPI;
private elementRenderOverrides;
/** offsets of `elementRenderOverrides`; keeps its identity while they don't change */
private elementRenderOffsets;
private renderOverridesUpdatePending;
private getRenderOverrideConfig;
private getElementRenderState;
private createExcalidrawAPI;
constructor(props: AppProps);
/**
@@ -3611,6 +3532,7 @@ declare class App extends React.Component<AppProps, AppState> {
private onBlur;
private onUnload;
private disableEvent;
private preventBrowserZoomWheel;
private handleNavigationModeKeyDown;
/**
* PageUp/PageDown scroll the canvas by a page — vertically, or
@@ -3748,10 +3670,6 @@ declare class App extends React.Component<AppProps, AppState> {
captureUpdate?: SceneData["captureUpdate"];
forceFlushSync?: boolean;
}) => void;
/**
* see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details
*/
setElementRenderOverrides: (overrides: ElementRenderOverrides | null) => void;
applyDeltas: (deltas: StoreDelta[], options?: ApplyToOptions) => [SceneElementsMap, AppState, boolean];
mutateElement: <TElement extends Mutable<ExcalidrawElement>>(element: TElement, updates: ElementUpdate<TElement>, informMutation?: boolean) => TElement;
triggerRender: (
@@ -3847,7 +3765,6 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3883,44 +3800,6 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
customData?: Record<string, any>;
}> & Readonly<{
type: "stickynote";
baseHeight: number;
}> & {
isDeleted: false;
}) | (Readonly<{
id: string;
x: number;
y: number;
strokeColor: string;
backgroundColor: string;
fillStyle: import("@excalidraw/element/types").FillStyle;
strokeWidth: number;
strokeStyle: import("@excalidraw/element/types").StrokeStyle;
roundness: null | {
type: import("@excalidraw/element/types").RoundnessType;
value?: number;
};
roughness: number;
opacity: number;
width: number;
height: number;
angle: Radians;
seed: number;
version: number;
versionNonce: number;
index: import("@excalidraw/element/types").FractionalIndex | null;
isDeleted: boolean;
groupIds: readonly import("@excalidraw/element/types").GroupId[];
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3956,7 +3835,6 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3992,7 +3870,6 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -4022,25 +3899,7 @@ declare class App extends React.Component<AppProps, AppState> {
* so the whole create-and-type lands in a single entry.
*/
private isEditingTextContent;
startTextEditing: ({ sceneX, sceneY, insertAtParentCenter, container, autoEdit, initialCaretSceneCoords, arrowEndpoint, }: {
/** X position to insert text at */
sceneX: number;
/** Y position to insert text at */
sceneY: number;
/** whether to attempt to insert at element center if applicable */
insertAtParentCenter?: boolean;
container?: ExcalidrawTextContainer | null;
autoEdit?: boolean;
initialCaretSceneCoords?: {
x: number;
y: number;
};
/**
* creates the text as a label for this arrow endpoint: the binding then
* dictates the text's position and alignment, overriding (sceneX, sceneY)
*/
arrowEndpoint?: ArrowEndpoint | null;
}) => void;
private startTextEditing;
private debounceDoubleClickTimestamp;
private startImageCropping;
private finishImageCropping;
@@ -4109,6 +3968,8 @@ declare class App extends React.Component<AppProps, AppState> {
* pointerup handlers manually
*/
private maybeCleanupAfterMissingPointerUp;
handleCanvasPanUsingWheelOrSpaceDrag: (event: React.PointerEvent<HTMLElement> | MouseEvent) => boolean;
private startRightClickPanning;
private updateGestureOnPointerDown;
/**
* Tracks the pointer within the ongoing multi-touch gesture and applies
@@ -4139,10 +4000,8 @@ declare class App extends React.Component<AppProps, AppState> {
}) => NonDeleted<ExcalidrawEmbeddableElement> | undefined;
private newImagePlaceholder;
private handleLinearElementOnPointerDown;
getCurrentItemRoundness(elementType: "selection" | "rectangle" | "stickynote" | "diamond" | "ellipse" | "iframe" | "embeddable"): {
type: 2 | 3;
} | null;
getCurrentItemStrokeWidth(elementType: ExcalidrawElement["type"]): number;
private getCurrentItemRoundness;
private getCurrentItemStrokeWidth;
private createGenericElementOnPointerDown;
private createFrameElementOnPointerDown;
private maybeCacheReferenceSnapPoints;
@@ -4178,29 +4037,19 @@ declare class App extends React.Component<AppProps, AppState> {
private handleAppOnDrop;
loadFileToCanvas: (file: File, fileHandle: FileSystemFileHandle | null) => Promise<void>;
private handleCanvasContextMenu;
/** opens the context menu for the element under the pointer, or the canvas */
openContextMenu: (pointer: {
clientX: number;
clientY: number;
button?: number;
pointerType?: string;
}) => void;
private maybeDragNewGenericElement;
private maybeHandleCrop;
private maybeHandleResize;
private getContextMenuItems;
private handleWheel;
getTextWysiwygSnappedToCenterPosition(x: number, y: number, appState: AppState, container?: ExcalidrawTextContainer | null): {
viewportX: number;
viewportY: number;
elementCenterX: number;
elementCenterY: number;
} | undefined;
savePointer: (x: number, y: number, button: "up" | "down") => void;
resetShouldCacheIgnoreZoomDebounced: {
(): void;
flush(): void;
cancel(): void;
};
private savePointer;
private resetShouldCacheIgnoreZoomDebounced;
private updateDOMRect;
refresh: () => void;
private getCanvasOffsets;
@@ -4352,7 +4201,7 @@ export type BinaryFileData = {
};
export type BinaryFileMetadata = Omit<BinaryFileData, "dataURL">;
export type BinaryFiles = Record<ExcalidrawElement["id"], BinaryFileData>;
export type ToolType = "selection" | "lasso" | "rectangle" | "diamond" | "ellipse" | "arrow" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "magicframe" | "stickynote" | "embeddable" | "laser" | "mermaid" | "autoshape" | "bucketfill";
export type ToolType = "selection" | "lasso" | "rectangle" | "diamond" | "ellipse" | "arrow" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "magicframe" | "embeddable" | "laser" | "mermaid" | "autoshape" | "bucketfill";
export type ElementOrToolType = ExcalidrawElementType | ToolType | "custom";
export type ActiveTool = {
type: ToolType;
@@ -4452,11 +4301,6 @@ export type ObservedElementsAppState = {
activeLockedId: AppState["activeLockedId"];
};
export type BoxSelectionMode = "contain" | "overlap";
/**
* The pointing device the wheel mappings are tuned for. `auto` is reserved
* for detecting it from the wheel events; see `resolveInputDevice`.
*/
export type InputDevice = "auto" | "mouse" | "trackpad";
/**
* A box, in scene coordinates, that pan & zoom are constrained to.
*
@@ -4536,14 +4380,6 @@ export interface AppState {
bindingPreference: "enabled" | "disabled";
/** user preference whether arrow snap to midpoints while binding */
isMidpointSnappingEnabled: boolean;
/**
* user preference for what the wheel does: with a `trackpad` a plain wheel
* pans; with a `mouse` a plain wheel zooms. Ctrl/cmd+wheel (how a pinch is
* delivered) zooms with either device. Shift+wheel pans horizontally;
* ctrl/cmd+shift+wheel pans vertically. `auto` resolves to `trackpad` until
* device detection exists — see `resolveInputDevice`
*/
inputDevice: InputDevice;
/**
* The bindable element the UI highlights for the user when an arrow is
* dragged or otherwise its endpoint being close to said element.
@@ -4599,8 +4435,6 @@ export interface AppState {
exportWithDarkMode: boolean;
exportScale: number;
currentItemStrokeColor: string;
currentItemStickynoteStrokeColor: string;
currentItemStickynoteBackgroundColor: string;
currentItemBackgroundColor: string;
currentItemFillStyle: ExcalidrawElement["fillStyle"];
currentItemStrokeWidth: number | undefined;
@@ -4775,9 +4609,6 @@ export interface AppState {
* even though both drive `currentItemBackgroundColor` (its defaults and
* use case differ — no transparent) */
bucketFill: readonly string[] | null;
/** sticky notes are their own color domain (own defaults, own picks) */
stickyNoteStroke: readonly string[] | null;
stickyNoteBackground: readonly string[] | null;
};
}
export type SearchMatch = {
@@ -4970,20 +4801,6 @@ export type UIConfig = {
scrollBackToContent?: boolean;
};
};
/** Supported visual changes. Geometry, content, bindings and styles are not overridable. */
export type ElementRenderOverride = Readonly<{
/** Absolute render opacity (0–100, clamped). Omitted: use element.opacity. */
opacity?: number;
/** Translation in scene units. Bound labels inherit their container's offset and ignore this field. */
offset?: Readonly<{
x: number;
y: number;
}>;
}>;
/** see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details */
export type ElementRenderOverrides = ReadonlyMap<ExcalidrawElement["id"], ElementRenderOverride>;
/** The translation part of a snapshot: only the entries that carry an offset. */
export type ElementRenderOffsets = ReadonlyMap<ExcalidrawElement["id"], NonNullable<ElementRenderOverride["offset"]>>;
export interface ExcalidrawProps {
className?: string;
/**
@@ -5200,8 +5017,7 @@ export interface ExcalidrawProps {
}) => MaybePromise<void> | AsyncGenerator<OnExportProgress, void>;
}
export type SceneData = {
/** Expects normalized elements; restore imported data before updating the scene. */
elements?: readonly ExcalidrawElement[] | null;
elements?: ImportedDataState["elements"];
appState?: ImportedDataState["appState"];
collaborators?: Map<SocketId, Collaborator>;
captureUpdate?: CaptureUpdateActionType;
@@ -5300,8 +5116,6 @@ export type AppClassProperties = {
arrowText: App["arrowText"];
cursor: App["cursor"];
bucketFill: App["bucketFill"];
toolDrag: App["toolDrag"];
activeResizeHandle: App["activeResizeHandle"];
isToolLocked: App["isToolLocked"];
getEffectiveGridSize: App["getEffectiveGridSize"];
setPlugins: App["setPlugins"];
@@ -5422,22 +5236,6 @@ export interface ExcalidrawImperativeAPI {
getName: InstanceType<typeof App>["getName"];
setViewport: InstanceType<typeof App>["viewport"]["setViewport"];
getViewportOffsets: InstanceType<typeof App>["viewport"]["getOffsets"];
/**
* Atomically replaces all transient visual overrides. Values are copied;
* omitted IDs/fields use document values, except for inherited label offsets.
* null clears the snapshot.
* Repaints without document changes, history entries or onChange events;
* an equivalent snapshot may still repaint (clearing an already clear
* snapshot does not), so submit only when something changed.
* Finite opacity is clamped to 0–100; non-finite values reject the snapshot.
* Unknown/deleted IDs are ignored when rendering. Reset/unmount clears it.
* Bound labels inherit their container's offset; offsets targeting them are
* ignored. Label opacity remains independent. Target frame children explicitly.
* Frame opacity still multiplies child opacity. Decorations follow their owner.
* Exports and interactive geometry (hit tests, selection, editing) use document
* values, including while authoring an animation preview in edit mode.
*/
setElementRenderOverrides: InstanceType<typeof App>["setElementRenderOverrides"];
registerAction: (action: Action) => void;
refresh: InstanceType<typeof App>["refresh"];
setToast: InstanceType<typeof App>["setToast"];
@@ -5703,7 +5501,7 @@ type EmbeddedLink =
))
| null;
export declare namespace ExcalidrawLib {
declare namespace ExcalidrawLib {
type ObsidianCommonHostUIMode = "full" | "compact" | "tray" | "mobile";
type ObsidianCommonHostAdapter = Readonly<{
@@ -5736,6 +5534,7 @@ export declare namespace ExcalidrawLib {
type ObsidianExcalidrawHostAdapter = Readonly<{
protocolVersion: 2;
isDoubleTapEraserEnabled: () => boolean;
isRightClickPanEnabled: () => boolean;
getZoomToFitMaxLevel: () => number;
isPenModeCrosshairVisible: () => boolean;
isSingleFingerPanningEnabled: () => boolean;
@@ -5924,7 +5723,6 @@ export declare namespace ExcalidrawLib {
} | undefined>;*/
let hashElementsVersion: typeof import("@zsviczian/excalidraw/types/excalidraw").hashElementsVersion;
let convertToExcalidrawElements: typeof import("@zsviczian/excalidraw").convertToExcalidrawElements;
let Excalidraw: typeof import("@zsviczian/excalidraw").Excalidraw;
let MainMenu: typeof import("@zsviczian/excalidraw").MainMenu;
let WelcomeScreen: typeof import("@zsviczian/excalidraw").WelcomeScreen;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -33,8 +33,7 @@ For a reference, follow the implementation pattern used in the "Printable Layout
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on `ea.obsidian`.
- In a template-based script workspace, `src/types/ea.d.ts` is an upstream-managed projection of the Script Engine API. Never edit it or generated declarations under `.template/types/`. Put repository-specific ambient declarations and type augmentations in `src/types/local.d.ts` instead, so template updates can replace the generated API safely.
- Version checks are distinct: use `ea.verifyMinimumPluginVersion()` for the Excalidraw plugin and `ea.obsidian.requireApiVersion()` only for the Obsidian application version.
- Version checks are distinct: use `ea.verifyMinimumPluginVersion()` for the Excalidraw plugin and `ea.verifyMinAppVersion()` only for the Obsidian application version.
- `utils.executionSource` describes why the current top-level invocation happened. Supported values are `"manual"`, `"plugin-startup"`, `"view-autostart"`, `"sidepanel-restore"`, `"sidepanel-reload"`, and `"drawing-onload"`. It does not indicate whether code came from the compilation cache or whether the script has run before.
- `ea.registerAutostart(message?)` requests view-autostart permission. The script is automatically attached once to each ExcalidrawView, while manual toolbar/command/hotkey invocation remains independently repeatable. The optional explanation appears as the second paragraph of the permission prompt; do not imply that the script's main interactive action starts automatically when only its tools/providers do.
- `ea.registerCleanup(cleanup)` registers synchronous cleanup owned by the current EA instance. Use it for external listeners, timers, observers, and subscriptions; the cleanup runs when that EA is destroyed.
@@ -297,9 +296,9 @@ The AI training material is maintained independently from publishing PRs; do not
- Add or update the script under [ea-scripts](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts).
- Add or update the preview image under [images](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images).
- Add or update the script's catalog entry in [ea-scripts/script-store.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/script-store.json).
- Run `npm run script-store:check`, then `npm run script-store:build`. The build validates the catalog and advances `directory-info.json` only for script/icon files that actually changed; it does not modify the frozen legacy `index-new.md` catalog.
- Do not hand-edit unrelated `mtime` values in [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json). Historical mtimes are part of the plugin's update-detection contract.
- Keep [ea-scripts/index-new.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index-new.md) manually curated; do not automate it.
- Update [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) in the same PR.
- For script updates, refresh the matching entry's `mtime` in [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) so the plugin can detect the newer local version.
- Keep the PR focused on the script and its generated references.
### How to use the Script Examples
@@ -56,7 +56,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **getCM**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Text Aura.md](scripts/Text%20Aura.md)
- **getCM6**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **getElement**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md)
- **getElements**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
- **getElements**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
- **getElementsInArea**: [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
- **getElementsIntersectionArea**: [Slideshow.md](scripts/Slideshow.md)
- **getElementsInTheSameGroupWithElement**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap format.md](scripts/Mindmap%20format.md)
@@ -95,7 +95,6 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **onLinkClickHook**: [Slideshow.md](scripts/Slideshow.md)
- **onSceneChangeHook**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Shade Master.md](scripts/Shade%20Master.md)
- **openFileInNewOrAdjacentLeaf**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **ownerDocument**: [Slideshow.md](scripts/Slideshow.md)
- **parseText**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **placeholder**: [Slideshow.md](scripts/Slideshow.md)
- **plugin**: [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Rename Image.md](scripts/Rename%20Image.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Path.md](scripts/Text%20to%20Path.md)
@@ -115,7 +114,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **setViewModeEnabled**: [Slideshow.md](scripts/Slideshow.md)
- **showAIUsageModal**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **showColorPicker**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md)
- **sidepanelTab**: [Icon Library.md](scripts/Icon%20Library.md), [LayerManager.md](scripts/LayerManager.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
- **sidepanelTab**: [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
- **skipSidepanelScriptRestore**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **style**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **targetView**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Folder Note Core - Make Current Drawing a Folder.md](scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md)
@@ -135,12 +134,11 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **features**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **getAppState**: [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Copy Selected Element Styles to Global.md](scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md), [Custom Zoom.md](scripts/Custom%20Zoom.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Invert colors.md](scripts/Invert%20colors.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **getSceneElements**: [Mindmap format.md](scripts/Mindmap%20format.md), [Slideshow.md](scripts/Slideshow.md)
- **onChange**: [LayerManager.md](scripts/LayerManager.md)
- **setActiveTool**: [Slideshow.md](scripts/Slideshow.md)
- **setToast**: [Slideshow.md](scripts/Slideshow.md)
- **startLineEditor**: [Slideshow.md](scripts/Slideshow.md)
- **updateContainerSize**: [Capture Note.md](scripts/Capture%20Note.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
- **updateScene**: [Custom Zoom.md](scripts/Custom%20Zoom.md), [LayerManager.md](scripts/LayerManager.md), [Palette loader.md](scripts/Palette%20loader.md), [Set Grid.md](scripts/Set%20Grid.md), [Slideshow.md](scripts/Slideshow.md)
- **updateScene**: [Custom Zoom.md](scripts/Custom%20Zoom.md), [Palette loader.md](scripts/Palette%20loader.md), [Set Grid.md](scripts/Set%20Grid.md), [Slideshow.md](scripts/Slideshow.md)
- **zoomToFit**: [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
## ExcalidrawLib
@@ -267,6 +267,7 @@ export interface ObsidianKeyBlocker {
export interface ObsidianExcalidrawHostAdapter {
readonly protocolVersion: typeof OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION;
isDoubleTapEraserEnabled(): boolean;
isRightClickPanEnabled(): boolean;
getZoomToFitMaxLevel(): number;
isPenModeCrosshairVisible(): boolean;
isSingleFingerPanningEnabled(): boolean;
File diff suppressed because it is too large. Load diff
@@ -83,24 +83,4 @@ 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)|
## 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.
|[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)|
File diff suppressed because it is too large. Load diff
@@ -770,30 +770,6 @@ export declare class ExcalidrawAutomate {
* @returns {string} The ID of the added rectangle element.
*/
addRect(topX: number, topY: number, width: number, height: number, id?: string): string;
/**
* Adds a sticky note and its optional fitted label to the ExcalidrawAutomate
* instance. Width and height default to Excalidraw's sticky-note size.
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
* @param {string} text - The sticky-note text. An empty string creates an unlabeled note.
* @param {Object} [formatting] - Sticky-note size and label formatting.
* @param {number} [formatting.width] - The initial width of the note.
* @param {number} [formatting.height] - The initial height of the note.
* @param {number} [formatting.fontSize] - The label's maximum font size.
* @param {number} [formatting.fontFamily] - The label font family.
* @param {"left" | "center" | "right"} [formatting.textAlign] - The label's horizontal alignment.
* @param {"top" | "middle" | "bottom"} [formatting.textVerticalAlign] - The label's vertical alignment.
* @param {string} [id] - The ID of the sticky-note element.
* @returns {string} The ID of the added sticky note.
*/
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;
/**
* Adds a diamond element to the ExcalidrawAutomate instance.
* @param {number} topX - The x-coordinate of the top-left corner.
@@ -871,8 +847,8 @@ export declare class ExcalidrawAutomate {
* @param {Object} [formatting] - Formatting options for the arrow element.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.startArrowHead] - The start arrowhead type.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.endArrowHead] - The end arrowhead type.
* @param {string} [formatting.startObjectId] - The ID of the start object. When omitted, the arrow start is unbound.
* @param {string} [formatting.endObjectId] - The ID of the end object. When omitted, the arrow end is unbound.
* @param {string} [formatting.startObjectId] - The ID of the start object.
* @param {string} [formatting.endObjectId] - The ID of the end object.
* BindMode Determines whether the arrow remains outside the shape or is allowed to
* go all the way inside the shape up to the exact fixed point.
* @param {"inside" | "orbit"} [formatting.startBindMode] - The binding mode for the start object.
@@ -1540,13 +1516,6 @@ export declare class ExcalidrawAutomate {
* @returns {string | null} The groupId or null if not found.
*/
getCommonGroupForElements(elements: ExcalidrawElement[]): string;
/**
* This is a convenience method to get the release notes for the plugin.
* @returns {Object} The release notes object.
*/
getReleaseNotes(): {
[k: string]: string;
};
/**
* Gets all the elements from elements[] that share one or more groupIds with the specified element.
* @param {ExcalidrawElement} element - The element to check.
@@ -2170,6 +2139,7 @@ export type MarkdownBlockCacheEntry = {
};
export interface ViewSemaphores {
warnAboutLinearElementLinkClick: boolean;
embeddableIsEditingSelf: boolean;
popoutUnload: boolean;
windowMigrating: boolean;
viewloaded: boolean;
@@ -2177,7 +2147,12 @@ export interface ViewSemaphores {
scriptsReady: boolean;
justLoaded: boolean;
preventAutozoom: boolean;
autosaving: boolean;
forceSaving: boolean;
dirty: string | null;
preventReload: boolean;
isEditingText: boolean;
saving: boolean;
hoverSleep: boolean;
wheelTimeout: number | null;
shouldSaveImportedImage: boolean;
@@ -2354,22 +2329,12 @@ export interface SelectableFontOption {
/* lib/types/githubTypes.d.ts */
/* ******************************** */
/**
* Metadata entry describing a file in the legacy remote EA scripts directory listing.
* Metadata entry describing a file in the 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 */
@@ -2601,32 +2566,6 @@ 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 */
/* ************************************** */
@@ -2753,6 +2692,26 @@ export interface FrameRenderingOptions {
clip: boolean;
}
export type PaneTarget = "active-pane" | "new-pane" | "popout-window" | "new-tab" | "md-properties";
export interface NestedFileNode {
file: TFile;
/**
* All distinct dependency paths from the root file down to this embedded file.
* Each path is an ordered array of TFile objects starting with the `rootFile` at index 0.
*
* @example
* If Root -> A -> B2.2 and Root -> B -> B2 -> B2.2
* The paths for B2.2 will be:
* [
* [Root, A, B2.2],
* [Root, B, B2, B2.2]
* ]
*
* Usage: To find which top-level embeds to reload if this file changes,
* you can map over `paths` and collect `path[1]`.
*/
paths: TFile[][];
}
export type NestedFileMap = Map<TFile, NestedFileNode>;
/* ************************************** */
/* node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts */
@@ -2917,11 +2876,6 @@ type _ExcalidrawElementBase = Readonly<{
boundElements: readonly BoundElement[] | null;
/** epoch (ms) timestamp of last element update */
updated: number;
/** Client wall-clock creation time in epoch milliseconds; null if unknown.
Preserved for this element's lifetime, including edits and undo/redo,
and excluded from `ElementUpdate` (mutateElement / newElementWith).
Duplicating an element starts a new lifetime. Not an ordering clock. */
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -2933,14 +2887,6 @@ export type ExcalidrawSelectionElement = _ExcalidrawElementBase & {
export type ExcalidrawRectangleElement = _ExcalidrawElementBase & {
type: "rectangle";
};
export type ExcalidrawStickyNoteElement = _ExcalidrawElementBase & Readonly<{
type: "stickynote";
/**
* The height the user set, from which the layout derives `height`: the
* note grows above it to fit its label and never shrinks below it
*/
baseHeight: number;
}>;
export type ExcalidrawDiamondElement = _ExcalidrawElementBase & {
type: "diamond";
};
@@ -3038,14 +2984,14 @@ export type ExcalidrawFrameLikeElement = ExcalidrawFrameElement | ExcalidrawMagi
* These are elements that don't have any additional properties.
*/
export type ExcalidrawGenericElement = ExcalidrawSelectionElement | ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawFlowchartNodeElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawRectanguloidElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawImageElement | ExcalidrawTextElement | ExcalidrawFreeDrawElement | ExcalidrawIframeLikeElement | ExcalidrawFrameLikeElement | ExcalidrawEmbeddableElement | ExcalidrawSelectionElement;
export type ExcalidrawFlowchartNodeElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawRectanguloidElement = ExcalidrawRectangleElement | ExcalidrawImageElement | ExcalidrawTextElement | ExcalidrawFreeDrawElement | ExcalidrawIframeLikeElement | ExcalidrawFrameLikeElement | ExcalidrawEmbeddableElement | ExcalidrawSelectionElement;
/**
* ExcalidrawElement should be JSON serializable and (eventually) contain
* no computed data. The list of all ExcalidrawElements should be shareable
* between peers and contain no state local to the peer.
*/
export type ExcalidrawElement = ExcalidrawGenericElement | ExcalidrawStickyNoteElement | ExcalidrawTextElement | ExcalidrawLinearElement | ExcalidrawArrowElement | ExcalidrawFreeDrawElement | ExcalidrawImageElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement;
export type ExcalidrawElement = ExcalidrawGenericElement | ExcalidrawTextElement | ExcalidrawLinearElement | ExcalidrawArrowElement | ExcalidrawFreeDrawElement | ExcalidrawImageElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement;
export type ExcalidrawNonSelectionElement = Exclude<ExcalidrawElement, ExcalidrawSelectionElement>;
export type Ordered<TElement extends ExcalidrawElement> = TElement & {
index: FractionalIndex;
@@ -3059,20 +3005,11 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
type: "text";
fontSize: number;
fontFamily: FontFamilyValues;
/**
* The font size the user picked, from which the layout derives `fontSize`.
* Today only sticky note labels have one: the auto-fit shrinks below it
* and never above it (compare `baseHeight`, which the note grows above).
* `null` for every other text. Read it through `getBaseFontSize` —
* generic binding repair can detach a label without clearing this, so
* the container decides its meaning.
*/
baseFontSize: number | null;
text: string;
rawText: string;
textAlign: TextAlign;
verticalAlign: VerticalAlign;
containerId: ExcalidrawTextContainer["id"] | null;
containerId: ExcalidrawGenericElement["id"] | null;
originalText: string;
/**
* If `true` the width will fit the text. If `false`, the text will
@@ -3096,8 +3033,8 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
* */
labelPosition?: number | null;
}>;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
export type ExcalidrawTextElementWithContainer = {
containerId: ExcalidrawTextContainer["id"];
} & ExcalidrawTextElement;
@@ -3276,7 +3213,7 @@ declare class App extends React.Component<AppProps, AppState> {
library: AppClassProperties["library"];
libraryItemsFromStorage: LibraryItems | undefined;
id: string;
store: Store;
private store;
private history;
private shouldRenderAllEmbeddables;
excalidrawContainerValue: {
@@ -3303,24 +3240,14 @@ declare class App extends React.Component<AppProps, AppState> {
private appStateObserver;
onStateChange: OnStateChange;
bucketFill: AppBucketFill;
toolDrag: AppToolDrag;
flowchart: AppFlowchart;
cursor: AppCursor;
arrowText: AppArrowText;
pan: AppPan;
viewport: AppViewport;
wheel: AppWheel;
bindModeHandler: ReturnType<typeof setTimeout> | null;
private textWysiwygSubmitHandler;
hitLinkElement?: NonDeletedExcalidrawElement;
lastPointerDownEvent: React.PointerEvent<HTMLElement> | null;
/**
* the handle of the resize in progress while `state.isResizing` — for UI
* that words itself by handle (a sticky note's corners resize
* proportionally, its edges freely); not app state, so it costs no
* re-render of its own
*/
activeResizeHandle: TransformHandleDirection | null;
lastPointerUpEvent: React.PointerEvent<HTMLElement> | PointerEvent | null;
lastPointerUpIsDoubleClick: boolean;
lastPointerMoveEvent: PointerEvent | null;
@@ -3475,12 +3402,6 @@ declare class App extends React.Component<AppProps, AppState> {
missingPointerEventCleanupEmitter: Emitter<[event: PointerEvent | null]>;
onRemoveEventListenersEmitter: Emitter<[]>;
api: ExcalidrawImperativeAPI;
private elementRenderOverrides;
/** offsets of `elementRenderOverrides`; keeps its identity while they don't change */
private elementRenderOffsets;
private renderOverridesUpdatePending;
private getRenderOverrideConfig;
private getElementRenderState;
private createExcalidrawAPI;
constructor(props: AppProps);
/**
@@ -3611,6 +3532,7 @@ declare class App extends React.Component<AppProps, AppState> {
private onBlur;
private onUnload;
private disableEvent;
private preventBrowserZoomWheel;
private handleNavigationModeKeyDown;
/**
* PageUp/PageDown scroll the canvas by a page — vertically, or
@@ -3748,10 +3670,6 @@ declare class App extends React.Component<AppProps, AppState> {
captureUpdate?: SceneData["captureUpdate"];
forceFlushSync?: boolean;
}) => void;
/**
* see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details
*/
setElementRenderOverrides: (overrides: ElementRenderOverrides | null) => void;
applyDeltas: (deltas: StoreDelta[], options?: ApplyToOptions) => [SceneElementsMap, AppState, boolean];
mutateElement: <TElement extends Mutable<ExcalidrawElement>>(element: TElement, updates: ElementUpdate<TElement>, informMutation?: boolean) => TElement;
triggerRender: (
@@ -3847,7 +3765,6 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3883,44 +3800,6 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
customData?: Record<string, any>;
}> & Readonly<{
type: "stickynote";
baseHeight: number;
}> & {
isDeleted: false;
}) | (Readonly<{
id: string;
x: number;
y: number;
strokeColor: string;
backgroundColor: string;
fillStyle: import("@excalidraw/element/types").FillStyle;
strokeWidth: number;
strokeStyle: import("@excalidraw/element/types").StrokeStyle;
roundness: null | {
type: import("@excalidraw/element/types").RoundnessType;
value?: number;
};
roughness: number;
opacity: number;
width: number;
height: number;
angle: Radians;
seed: number;
version: number;
versionNonce: number;
index: import("@excalidraw/element/types").FractionalIndex | null;
isDeleted: boolean;
groupIds: readonly import("@excalidraw/element/types").GroupId[];
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3956,7 +3835,6 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3992,7 +3870,6 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -4022,25 +3899,7 @@ declare class App extends React.Component<AppProps, AppState> {
* so the whole create-and-type lands in a single entry.
*/
private isEditingTextContent;
startTextEditing: ({ sceneX, sceneY, insertAtParentCenter, container, autoEdit, initialCaretSceneCoords, arrowEndpoint, }: {
/** X position to insert text at */
sceneX: number;
/** Y position to insert text at */
sceneY: number;
/** whether to attempt to insert at element center if applicable */
insertAtParentCenter?: boolean;
container?: ExcalidrawTextContainer | null;
autoEdit?: boolean;
initialCaretSceneCoords?: {
x: number;
y: number;
};
/**
* creates the text as a label for this arrow endpoint: the binding then
* dictates the text's position and alignment, overriding (sceneX, sceneY)
*/
arrowEndpoint?: ArrowEndpoint | null;
}) => void;
private startTextEditing;
private debounceDoubleClickTimestamp;
private startImageCropping;
private finishImageCropping;
@@ -4109,6 +3968,8 @@ declare class App extends React.Component<AppProps, AppState> {
* pointerup handlers manually
*/
private maybeCleanupAfterMissingPointerUp;
handleCanvasPanUsingWheelOrSpaceDrag: (event: React.PointerEvent<HTMLElement> | MouseEvent) => boolean;
private startRightClickPanning;
private updateGestureOnPointerDown;
/**
* Tracks the pointer within the ongoing multi-touch gesture and applies
@@ -4139,10 +4000,8 @@ declare class App extends React.Component<AppProps, AppState> {
}) => NonDeleted<ExcalidrawEmbeddableElement> | undefined;
private newImagePlaceholder;
private handleLinearElementOnPointerDown;
getCurrentItemRoundness(elementType: "selection" | "rectangle" | "stickynote" | "diamond" | "ellipse" | "iframe" | "embeddable"): {
type: 2 | 3;
} | null;
getCurrentItemStrokeWidth(elementType: ExcalidrawElement["type"]): number;
private getCurrentItemRoundness;
private getCurrentItemStrokeWidth;
private createGenericElementOnPointerDown;
private createFrameElementOnPointerDown;
private maybeCacheReferenceSnapPoints;
@@ -4178,29 +4037,19 @@ declare class App extends React.Component<AppProps, AppState> {
private handleAppOnDrop;
loadFileToCanvas: (file: File, fileHandle: FileSystemFileHandle | null) => Promise<void>;
private handleCanvasContextMenu;
/** opens the context menu for the element under the pointer, or the canvas */
openContextMenu: (pointer: {
clientX: number;
clientY: number;
button?: number;
pointerType?: string;
}) => void;
private maybeDragNewGenericElement;
private maybeHandleCrop;
private maybeHandleResize;
private getContextMenuItems;
private handleWheel;
getTextWysiwygSnappedToCenterPosition(x: number, y: number, appState: AppState, container?: ExcalidrawTextContainer | null): {
viewportX: number;
viewportY: number;
elementCenterX: number;
elementCenterY: number;
} | undefined;
savePointer: (x: number, y: number, button: "up" | "down") => void;
resetShouldCacheIgnoreZoomDebounced: {
(): void;
flush(): void;
cancel(): void;
};
private savePointer;
private resetShouldCacheIgnoreZoomDebounced;
private updateDOMRect;
refresh: () => void;
private getCanvasOffsets;
@@ -4352,7 +4201,7 @@ export type BinaryFileData = {
};
export type BinaryFileMetadata = Omit<BinaryFileData, "dataURL">;
export type BinaryFiles = Record<ExcalidrawElement["id"], BinaryFileData>;
export type ToolType = "selection" | "lasso" | "rectangle" | "diamond" | "ellipse" | "arrow" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "magicframe" | "stickynote" | "embeddable" | "laser" | "mermaid" | "autoshape" | "bucketfill";
export type ToolType = "selection" | "lasso" | "rectangle" | "diamond" | "ellipse" | "arrow" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "magicframe" | "embeddable" | "laser" | "mermaid" | "autoshape" | "bucketfill";
export type ElementOrToolType = ExcalidrawElementType | ToolType | "custom";
export type ActiveTool = {
type: ToolType;
@@ -4452,11 +4301,6 @@ export type ObservedElementsAppState = {
activeLockedId: AppState["activeLockedId"];
};
export type BoxSelectionMode = "contain" | "overlap";
/**
* The pointing device the wheel mappings are tuned for. `auto` is reserved
* for detecting it from the wheel events; see `resolveInputDevice`.
*/
export type InputDevice = "auto" | "mouse" | "trackpad";
/**
* A box, in scene coordinates, that pan & zoom are constrained to.
*
@@ -4536,14 +4380,6 @@ export interface AppState {
bindingPreference: "enabled" | "disabled";
/** user preference whether arrow snap to midpoints while binding */
isMidpointSnappingEnabled: boolean;
/**
* user preference for what the wheel does: with a `trackpad` a plain wheel
* pans; with a `mouse` a plain wheel zooms. Ctrl/cmd+wheel (how a pinch is
* delivered) zooms with either device. Shift+wheel pans horizontally;
* ctrl/cmd+shift+wheel pans vertically. `auto` resolves to `trackpad` until
* device detection exists — see `resolveInputDevice`
*/
inputDevice: InputDevice;
/**
* The bindable element the UI highlights for the user when an arrow is
* dragged or otherwise its endpoint being close to said element.
@@ -4599,8 +4435,6 @@ export interface AppState {
exportWithDarkMode: boolean;
exportScale: number;
currentItemStrokeColor: string;
currentItemStickynoteStrokeColor: string;
currentItemStickynoteBackgroundColor: string;
currentItemBackgroundColor: string;
currentItemFillStyle: ExcalidrawElement["fillStyle"];
currentItemStrokeWidth: number | undefined;
@@ -4775,9 +4609,6 @@ export interface AppState {
* even though both drive `currentItemBackgroundColor` (its defaults and
* use case differ — no transparent) */
bucketFill: readonly string[] | null;
/** sticky notes are their own color domain (own defaults, own picks) */
stickyNoteStroke: readonly string[] | null;
stickyNoteBackground: readonly string[] | null;
};
}
export type SearchMatch = {
@@ -4970,20 +4801,6 @@ export type UIConfig = {
scrollBackToContent?: boolean;
};
};
/** Supported visual changes. Geometry, content, bindings and styles are not overridable. */
export type ElementRenderOverride = Readonly<{
/** Absolute render opacity (0–100, clamped). Omitted: use element.opacity. */
opacity?: number;
/** Translation in scene units. Bound labels inherit their container's offset and ignore this field. */
offset?: Readonly<{
x: number;
y: number;
}>;
}>;
/** see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details */
export type ElementRenderOverrides = ReadonlyMap<ExcalidrawElement["id"], ElementRenderOverride>;
/** The translation part of a snapshot: only the entries that carry an offset. */
export type ElementRenderOffsets = ReadonlyMap<ExcalidrawElement["id"], NonNullable<ElementRenderOverride["offset"]>>;
export interface ExcalidrawProps {
className?: string;
/**
@@ -5200,8 +5017,7 @@ export interface ExcalidrawProps {
}) => MaybePromise<void> | AsyncGenerator<OnExportProgress, void>;
}
export type SceneData = {
/** Expects normalized elements; restore imported data before updating the scene. */
elements?: readonly ExcalidrawElement[] | null;
elements?: ImportedDataState["elements"];
appState?: ImportedDataState["appState"];
collaborators?: Map<SocketId, Collaborator>;
captureUpdate?: CaptureUpdateActionType;
@@ -5300,8 +5116,6 @@ export type AppClassProperties = {
arrowText: App["arrowText"];
cursor: App["cursor"];
bucketFill: App["bucketFill"];
toolDrag: App["toolDrag"];
activeResizeHandle: App["activeResizeHandle"];
isToolLocked: App["isToolLocked"];
getEffectiveGridSize: App["getEffectiveGridSize"];
setPlugins: App["setPlugins"];
@@ -5422,22 +5236,6 @@ export interface ExcalidrawImperativeAPI {
getName: InstanceType<typeof App>["getName"];
setViewport: InstanceType<typeof App>["viewport"]["setViewport"];
getViewportOffsets: InstanceType<typeof App>["viewport"]["getOffsets"];
/**
* Atomically replaces all transient visual overrides. Values are copied;
* omitted IDs/fields use document values, except for inherited label offsets.
* null clears the snapshot.
* Repaints without document changes, history entries or onChange events;
* an equivalent snapshot may still repaint (clearing an already clear
* snapshot does not), so submit only when something changed.
* Finite opacity is clamped to 0–100; non-finite values reject the snapshot.
* Unknown/deleted IDs are ignored when rendering. Reset/unmount clears it.
* Bound labels inherit their container's offset; offsets targeting them are
* ignored. Label opacity remains independent. Target frame children explicitly.
* Frame opacity still multiplies child opacity. Decorations follow their owner.
* Exports and interactive geometry (hit tests, selection, editing) use document
* values, including while authoring an animation preview in edit mode.
*/
setElementRenderOverrides: InstanceType<typeof App>["setElementRenderOverrides"];
registerAction: (action: Action) => void;
refresh: InstanceType<typeof App>["refresh"];
setToast: InstanceType<typeof App>["setToast"];
@@ -5703,7 +5501,7 @@ type EmbeddedLink =
))
| null;
export declare namespace ExcalidrawLib {
declare namespace ExcalidrawLib {
type ObsidianCommonHostUIMode = "full" | "compact" | "tray" | "mobile";
type ObsidianCommonHostAdapter = Readonly<{
@@ -5736,6 +5534,7 @@ export declare namespace ExcalidrawLib {
type ObsidianExcalidrawHostAdapter = Readonly<{
protocolVersion: 2;
isDoubleTapEraserEnabled: () => boolean;
isRightClickPanEnabled: () => boolean;
getZoomToFitMaxLevel: () => number;
isPenModeCrosshairVisible: () => boolean;
isSingleFingerPanningEnabled: () => boolean;
@@ -5924,7 +5723,6 @@ export declare namespace ExcalidrawLib {
} | undefined>;*/
let hashElementsVersion: typeof import("@zsviczian/excalidraw/types/excalidraw").hashElementsVersion;
let convertToExcalidrawElements: typeof import("@zsviczian/excalidraw").convertToExcalidrawElements;
let Excalidraw: typeof import("@zsviczian/excalidraw").Excalidraw;
let MainMenu: typeof import("@zsviczian/excalidraw").MainMenu;
let WelcomeScreen: typeof import("@zsviczian/excalidraw").WelcomeScreen;
-127
View File
@@ -1,127 +0,0 @@
# Automate anything with Excalidraw
![Automate anything](../images/banner-automate-anything.png)
Excalidraw Automate scripts are small programs that run inside the Obsidian Excalidraw plugin. They can automate repetitive drawing work, build custom tools and interfaces, work with files in your Obsidian vault, and combine several steps of a workflow into a single command.
The useful question is no longer _“does a community script already exist for this?”_ but _“what would I like Excalidraw to do for me?”_
## The easiest way to create your own script
Use the **[ExcalidrawAutomate script workspace](https://github.com/zsviczian/ea-script-template)**. It is a GitHub template designed for developing one or many Excalidraw Automate scripts with modern tooling and AI coding agents.
The repository already contains:
- Excalidraw Automate API types and reference material for AI agents.
- Agent instructions and practical API-usage examples.
- Script scaffolding, linting, type checking, bundling, and preview support.
- A clean source layout for keeping reusable helpers separate from individual scripts.
- An update workflow so your script repository can receive improvements from the template without replacing your own scripts and guidance.
### Quick start
1. Open [zsviczian/ea-script-template](https://github.com/zsviczian/ea-script-template) and choose **Use this template → Create a new repository**.
2. Clone your new repository and install its dependencies with Node 22.13 or newer.
3. Create a script:
```bash
npm install
npm run new-script -- --name "My Script"
```
4. Tell your AI coding agent what you want the script to accomplish. Describe the workflow, the user interaction, and what should happen on the Excalidraw canvas or in the Obsidian vault.
5. Ask the agent to read the repository instructions and the bundled Excalidraw Automate references before implementing the script.
6. Validate and build:
```bash
npm run check
npm run build
```
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:
1. Give the AI accurate Excalidraw Automate API context.
2. Describe a concrete problem and the behavior you want.
3. Let the AI build a first version.
4. Run it in Obsidian and report the exact error or behavior that needs improvement.
5. Iterate until the workflow feels natural.
The video builds a Layer Manager as an example: a purpose-built tool that did not already exist in the script library. The current script workspace takes this workflow further. Instead of manually feeding a large training document to an AI chat, the repository carries agent instructions, API references, types, examples, and validation tools alongside your source code.
You do not need to start by knowing the Excalidraw Automate API. Start by knowing what you want to automate.
## What can a script automate?
Practically anything that Excalidraw Automate and Obsidian expose, for example:
- Batch-format or rearrange selected elements.
- Build specialized drawing, layout, connector, annotation, or image tools.
- Create custom modals, controls, and persistent sidepanels.
- Create, rename, link, embed, or update files in your vault.
- Generate dashboards or drawings from vault data.
- Add startup, drawing-load, or long-lived automation where appropriate.
- Export drawings, images, or structured information.
- Combine several repetitive actions into a single command tailored to your workflow.
Browse the Community Script Store for examples and inspiration before starting from scratch.
## A few authoring rules worth knowing
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 testing or distributing a changed script.
## Scripts are code
A script can change your drawing and can also work with files in your vault. Treat scripts like any other code you install: use sources you trust, review unfamiliar scripts, keep backups, and test destructive workflows on disposable data first.
## 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). 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`.
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
- [ExcalidrawAutomate script workspace](https://github.com/zsviczian/ea-script-template)
- [AI Scripting Superpowers](https://youtu.be/6BjhUyfS4iM)
- [Excalidraw Script Engine documentation](https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html)
- [Excalidraw Automate API declaration](API/ExcalidrawAutomate.d.ts)
+86 -106
View File
@@ -1,106 +1,86 @@
# Excalidraw Script Engine scripts library
【English | [简体中文](../docs/zh-cn/ea-scripts/README.md)】
Click to watch the intro video:
[![Script Engine](https://user-images.githubusercontent.com/14358394/145684531-8d9c2992-59ac-4ebc-804a-4cce1777ded2.jpg)](https://youtu.be/hePJcObHIso)
> **Warning**
> There is an easier way to install/manage scripts than what is shown in this video
See the [Excalidraw Script Engine](https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html) documentation for more details.
## How to install scripts into your Obsidian Vault
To install one of the built-in scripts:
- Open up an excalidraw drawing in Obsidian
- In the pane dropdown menu select "Install or update Excalidraw Scripts"
- Click on one of the available scripts
- Click on "Install this script" (note if the script is already installed you will instead see an option to update it)
- Restart Obsidian so the script will be picked up
Note: By default this will install the script into your vault in the `Excalidraw/Scripts/Downloaded` folder
<details><summary>Manual installation of scripts</summary>
Open the script you are interested in and save it to your Obsidian Vault including the first line `/*`, or open it in "Raw" and copy the entire contents to Obsidian.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-download-raw.jpg)
</details>
## List of available scripts
|Title|Description|Icon|Contributor|
|----|----|----|----|
|[Add Connector Point](Add%20Connector%20Point.md)|This script will add a small circle to the top left of each text element in the selection and add the text and the "bullet point" into a group.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-bullet-point.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Link to Existing File and Open](Add%20Link%20to%20Existing%20File%20and%20Open.md)|Prompts for a file from the vault. Adds a link to the selected element pointing to the selected file. You can control in settings to open the file in the current active pane or an adjacent pane.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-and-open.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Link to New Page and Open](Add%20Link%20and%20Open%20Page.md)|Prompts for filename. Offers option to create and open a new Markdown or Excalidraw document. Adds link pointing to the new file, to the selected objects in the drawing. You can control in settings to open the file in the current active pane or an adjacent pane.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-to-new-page-and-pen.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Next Step in Process](Add%20Link%20to%20New%20Page%20and%20Open.md)|This script will prompt you for the title of the process step, then will create a stick note with the text. If an element is selected then the script will connect this new step with an arrow to the previous step (the selected element). If no element is selected, then the script assumes this is the first step in the process and will only output the sticky note with the text that was entered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-process-step.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split Ellipse](Boolean%20Operations.md)|With This Script it is possible to make boolean Operations on Shapes.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-boolean-operations-showcase.png)|[@GColoy](https://github.com/GColoy)|
|[Box Each Selected Groups](Box%20Each%20Selected%20Groups.md)|This script will add encapsulating boxes around each of the currently selected groups in Excalidraw.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-each-selected-groups.png)|[@1-2-3](https://github.com/1-2-3)|
|[Box Selected Elements](Box%20Selected%20Elements.md)|This script will add an encapsulating box around the currently selected elements in Excalidraw.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-elements.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Change shape of selected elements](Change%20shape%20of%20selected%20elements.md)|The script allows you to change the shape of selected Rectangles, Diamonds and Ellipses|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-change-shape.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Connect elements](Connect%20elements.md)|This script will connect two objects with an arrow. If either of the objects are a set of grouped elements (e.g. a text element grouped with an encapsulating rectangle), the script will identify these groups, and connect the arrow to the largest object in the group (assuming you want to connect the arrow to the box around the text element).|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-connect-elements.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Convert freedraw to line](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20freedraw%20to%20line.md)|Convert selected freedraw objects into editable lines. This will allow you to adjust your drawings by dragging line points and will also allow you to select shape fill in case of enclosed lines. You can adjust conversion point density in settings|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-convert-freedraw-to-line.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Convert selected text elements to sticky notes](Convert%20selected%20text%20elements%20to%20sticky%20notes.md)|Converts selected plain text elements to sticky notes with transparent background and transparent stroke color. Essentially converts text element into a wrappable format.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-textelement-to-transparent-stickynote.png)|[@zsviczian](https://github.com/zsviczian)|
|[Convert text to link with folder and alias](Convert%20text%20to%20link%20with%20folder%20and%20alias.md)|Converts text elements to links pointing to a file in a selected folder and with the alias set as the original text. The script will prompt the user to select an existing folder from the vault.|`original text` => `[[selected folder/original text\|original text]]`|[@zsviczian](https://github.com/zsviczian)|
|[Copy Selected Element Styles to Global](Copy%20Selected%20Element%20Styles%20to%20Global)|This script will copy styles of any selected element into Excalidraw's global styles.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png)|[@1-2-3](https://github.com/1-2-3)|
|[Create new markdown file and embed into active drawing](Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md)|The script will prompt you for a filename, then create a new markdown document with the file name provided, open the new markdown document in an adjacent pane, and embed the markdown document into the active Excalidraw drawing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-create-and-embed-new-markdown-file.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Darken background color](Darken%20background%20color.md)|This script darkens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect. In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png)|[@1-2-3](https://github.com/1-2-3)|
|[Elbow connectors](Elbow%20connectors.md)|This script converts the selected connectors to elbows.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/elbow-connectors.png)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles horizontally keep text centered](Expand%20rectangles%20horizontally%20keep%20text20%centered.md)|This script expands the width of the selected rectangles until they are all the same width and keep the text centered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles horizontally](Expand%20rectangles%20horizontally.md)|This script expands the width of the selected rectangles until they are all the same width.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles vertically keep text centered](Expand%20rectangles%20vertically%20keep%20text%20centered.md)|This script expands the height of the selected rectangles until they are all the same height and keep the text centered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles vertically](Expand%20rectangles%20vertically.md)|This script expands the height of the selected rectangles until they are all the same height.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed horizontal distance between centers](Fixed%20horizontal%20distance%20between%20centers.md)|This script arranges the selected elements horizontally with a fixed center spacing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-horizontal-distance-between-centers.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed inner distance](Fixed%20inner%20distance.md)|This script arranges selected elements and groups with a fixed inner distance.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-inner-distance.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed spacing](Fixed%20spacing.md)|The script arranges the selected elements horizontally with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fix-space-demo.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed vertical distance between centers](Fixed%20vertical%20distance%20between%20centers.md)|This script arranges the selected elements vertically with a fixed center spacing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance-between-centers.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed vertical distance](Fixed%20vertical%20distance.md)|The script arranges the selected elements vertically with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance.png)|[@1-2-3](https://github.com/1-2-3)|
|[Lighten background color](Lighten%20background%20color.md)|This script lightens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect.In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png)|[@1-2-3](https://github.com/1-2-3)|
|[Mindmap connector](Mindmap%20connector.md)|This script creates mindmap like lines (only right side and down available currently) for selected elements. The line will start according to the creation time of the elements. So you should create the header element first.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/mindmap%20connector.png)|[@xllowl](https://github.com/xllowl)|
|[Modify background color opacity](Modify%20background%20color%20opacity.md)|This script changes the opacity of the background color of the selected boxes. The default background color in Excalidraw is so dark that the text is hard to read. You can lighten the color a bit by setting transparency. And you can tweak the transparency over and over again until you're happy with it. Although excalidraw has the opacity option in its native property Settings, it also changes the transparency of the border. Use this script to change only the opacity of the background color without affecting the border.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-modify-background-color-opacity.png)|[@1-2-3](https://github.com/1-2-3)|
|[Normalize Selected Arrows](Normalize%20Selected%20Arrows.md)|This script will reset the start and end positions of the selected arrows. The arrow will point to the center of the connected box and will have a gap of 8px from the box.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-normalize-selected-arrows.png)|[@1-2-3](https://github.com/1-2-3)|
|[OCR - Optical Character Recognition](OCR%20-%20Optical%20Character%20Recognition.md)|The script will 1) send the selected image file to [taskbone.com](https://taskbone.com) to extract the text from the image, and 2) will add the text to your drawing as a text element.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Organic Line](Organic%20Line.md)|Converts selected freedraw lines such that pencil pressure will decrease from maximum to minimum from the beginning of the line to its end. The resulting line is placed at the back of the layers, under all other items. Helpful when drawing organic mindmaps.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-organic-line.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Repeat Elements](Repeat%20Elements.md)|This script will detect the difference between 2 selected elements, including position, size, angle, stroke and background color, and create several elements that repeat these differences based on the number of repetitions entered by the user.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-repeat-elements.png)|[@1-2-3](https://github.com/1-2-3)|
|[Reset LaTeX Size](Reset%20LaTeX%20Size.md)|Reset the sizes of embedded LaTeX equations to the default sizes or a multiple of the default sizes.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reset-latex.jpg)|[@firai](https://github.com/firai)|
|[Reverse arrows](Reverse%20arrows.md)|Reverse the direction of **arrows** within the scope of selected elements.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reverse-arrow.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Scribble Helper](Scribble%20Helper.md)|iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the creates a text element at pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then opens the input prompt where you can modify this text with scribble.|![]('https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-scribble-helper.jpg')|[@zsviczian](https://github.com/zsviczian)|
|[Select Elements of Type](Select%20Elements%20of%20Type.md)|Prompts you with a list of the different element types in the active image. Only elements of the selected type will be selected on the canvas. If nothing is selected when running the script, then the script will process all the elements on the canvas. If some elements are selected when the script is executed, then the script will only process the selected elements.<br>The script is useful when, for example, you want to bring to front all the arrows, or want to change the color of all the text elements, etc.|![]('https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-select-element-of-type.jpg')|[@zsviczian](https://github.com/zsviczian)|
|[Set background color of unclosed line object by adding a shadow clone](Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md)|Use this script to set the background color of unclosed (i.e. open) line objects by creating a clone of the object. The script will set the stroke color of the clone to transparent and will add a straight line to close the object. Use settings to define the default background color, the fill style, and the strokeWidth of the clone. By default the clone will be grouped with the original object, you can disable this also in settings.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Dimensions](Set%20Dimensions.md)|Currently there is no way to specify the exact location and size of objects in Excalidraw. You can bridge this gap with the following simple script.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Font Family](Set%20Font%20Family.md)|Sets font family of the text block (Virgil, Helvetica, Cascadia). Useful if you want to set a keyboard shortcut for selecting font family.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-font-family.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Grid](Set%20Grid.md)|The default grid size in Excalidraw is 20. Currently there is no way to change the grid size via the user interface. This script offers a way to bridge this gap.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-grid.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Link Alias](Set20%Link20%Alias.md)|Iterates all of the links in the selected TextElements and prompts the user to set or modify the alias for each link found.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-set-link-alias.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set stroke width of selected elements](Set%20Stroke%20Width%20of%20Selected%20Elements.md)|This script will set the stroke width of selected elements. This is helpful, for example, when you scale freedraw sketches and want to reduce or increase their line width.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-stroke-width.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split text by lines](Split%20text%20by%20lines.md)|Split lines of text into separate text elements for easier reorganization|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-split-lines.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Text Alignment](Set%20Text%20Alignment.md)|Sets text alignment of text block (cetner, right, left). Useful if you want to set a keyboard shortcut for selecting text alignment.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-align.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split Ellipse](Split%20Ellipse.md)|This script splits an ellipse at any point where a line intersects it.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-splitEllipse-demo1.png)|[@GColoy](https://github.com/GColoy)|
|[TheBrain-navigation](TheBrain-navigation.md)|An Excalidraw based graph user interface for your Vault. Requires the [Dataview plugin](https://github.com/blacksmithgu/obsidian-dataview). Generates a graph view similar to that of [TheBrain](https://TheBrain.com) plex. Watch introduction to this script on [YouTube](https://youtu.be/plYobK-VufM).|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/TheBrain.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Toggle Fullscreen on Mobile](Toggle%20Fullscreen%20on%20Mobile.md)|Hides Obsidian workspace leaf padding and header (based on option in settings, default is "hide header" = false) which will take Excalidraw to full screen. ⚠ Note that if the header is not visible, it will be very difficult to invoke the command palette to end full screen. Only hide the header if you have a keyboard or you've practiced opening command palette!|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/ea-toggle-fullscreen.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Toggle Grid](Toggle%20Grid.md)|Toggles the grid.||[@GColoy](https://github.com/GColoy)|
|[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)|
## 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.
# Excalidraw Script Engine scripts library
【English | [简体中文](../docs/zh-cn/ea-scripts/README.md)】
Click to watch the intro video:
[![Script Engine](https://user-images.githubusercontent.com/14358394/145684531-8d9c2992-59ac-4ebc-804a-4cce1777ded2.jpg)](https://youtu.be/hePJcObHIso)
> **Warning**
> There is an easier way to install/manage scripts than what is shown in this video
See the [Excalidraw Script Engine](https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html) documentation for more details.
## How to install scripts into your Obsidian Vault
To install one of the built-in scripts:
- Open up an excalidraw drawing in Obsidian
- In the pane dropdown menu select "Install or update Excalidraw Scripts"
- Click on one of the available scripts
- Click on "Install this script" (note if the script is already installed you will instead see an option to update it)
- Restart Obsidian so the script will be picked up
Note: By default this will install the script into your vault in the `Excalidraw/Scripts/Downloaded` folder
<details><summary>Manual installation of scripts</summary>
Open the script you are interested in and save it to your Obsidian Vault including the first line `/*`, or open it in "Raw" and copy the entire contents to Obsidian.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-download-raw.jpg)
</details>
## List of available scripts
|Title|Description|Icon|Contributor|
|----|----|----|----|
|[Add Connector Point](Add%20Connector%20Point.md)|This script will add a small circle to the top left of each text element in the selection and add the text and the "bullet point" into a group.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-bullet-point.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Link to Existing File and Open](Add%20Link%20to%20Existing%20File%20and%20Open.md)|Prompts for a file from the vault. Adds a link to the selected element pointing to the selected file. You can control in settings to open the file in the current active pane or an adjacent pane.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-and-open.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Link to New Page and Open](Add%20Link%20and%20Open%20Page.md)|Prompts for filename. Offers option to create and open a new Markdown or Excalidraw document. Adds link pointing to the new file, to the selected objects in the drawing. You can control in settings to open the file in the current active pane or an adjacent pane.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-to-new-page-and-pen.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Next Step in Process](Add%20Link%20to%20New%20Page%20and%20Open.md)|This script will prompt you for the title of the process step, then will create a stick note with the text. If an element is selected then the script will connect this new step with an arrow to the previous step (the selected element). If no element is selected, then the script assumes this is the first step in the process and will only output the sticky note with the text that was entered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-process-step.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split Ellipse](Boolean%20Operations.md)|With This Script it is possible to make boolean Operations on Shapes.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-boolean-operations-showcase.png)|[@GColoy](https://github.com/GColoy)|
|[Box Each Selected Groups](Box%20Each%20Selected%20Groups.md)|This script will add encapsulating boxes around each of the currently selected groups in Excalidraw.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-each-selected-groups.png)|[@1-2-3](https://github.com/1-2-3)|
|[Box Selected Elements](Box%20Selected%20Elements.md)|This script will add an encapsulating box around the currently selected elements in Excalidraw.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-elements.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Change shape of selected elements](Change%20shape%20of%20selected%20elements.md)|The script allows you to change the shape of selected Rectangles, Diamonds and Ellipses|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-change-shape.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Connect elements](Connect%20elements.md)|This script will connect two objects with an arrow. If either of the objects are a set of grouped elements (e.g. a text element grouped with an encapsulating rectangle), the script will identify these groups, and connect the arrow to the largest object in the group (assuming you want to connect the arrow to the box around the text element).|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-connect-elements.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Convert freedraw to line](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20freedraw%20to%20line.md)|Convert selected freedraw objects into editable lines. This will allow you to adjust your drawings by dragging line points and will also allow you to select shape fill in case of enclosed lines. You can adjust conversion point density in settings|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-convert-freedraw-to-line.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Convert selected text elements to sticky notes](Convert%20selected%20text%20elements%20to%20sticky%20notes.md)|Converts selected plain text elements to sticky notes with transparent background and transparent stroke color. Essentially converts text element into a wrappable format.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-textelement-to-transparent-stickynote.png)|[@zsviczian](https://github.com/zsviczian)|
|[Convert text to link with folder and alias](Convert%20text%20to%20link%20with%20folder%20and%20alias.md)|Converts text elements to links pointing to a file in a selected folder and with the alias set as the original text. The script will prompt the user to select an existing folder from the vault.|`original text` => `[[selected folder/original text\|original text]]`|[@zsviczian](https://github.com/zsviczian)|
|[Copy Selected Element Styles to Global](Copy%20Selected%20Element%20Styles%20to%20Global)|This script will copy styles of any selected element into Excalidraw's global styles.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png)|[@1-2-3](https://github.com/1-2-3)|
|[Create new markdown file and embed into active drawing](Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md)|The script will prompt you for a filename, then create a new markdown document with the file name provided, open the new markdown document in an adjacent pane, and embed the markdown document into the active Excalidraw drawing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-create-and-embed-new-markdown-file.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Darken background color](Darken%20background%20color.md)|This script darkens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect. In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png)|[@1-2-3](https://github.com/1-2-3)|
|[Elbow connectors](Elbow%20connectors.md)|This script converts the selected connectors to elbows.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/elbow-connectors.png)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles horizontally keep text centered](Expand%20rectangles%20horizontally%20keep%20text20%centered.md)|This script expands the width of the selected rectangles until they are all the same width and keep the text centered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles horizontally](Expand%20rectangles%20horizontally.md)|This script expands the width of the selected rectangles until they are all the same width.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles vertically keep text centered](Expand%20rectangles%20vertically%20keep%20text%20centered.md)|This script expands the height of the selected rectangles until they are all the same height and keep the text centered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles vertically](Expand%20rectangles%20vertically.md)|This script expands the height of the selected rectangles until they are all the same height.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed horizontal distance between centers](Fixed%20horizontal%20distance%20between%20centers.md)|This script arranges the selected elements horizontally with a fixed center spacing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-horizontal-distance-between-centers.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed inner distance](Fixed%20inner%20distance.md)|This script arranges selected elements and groups with a fixed inner distance.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-inner-distance.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed spacing](Fixed%20spacing.md)|The script arranges the selected elements horizontally with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fix-space-demo.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed vertical distance between centers](Fixed%20vertical%20distance%20between%20centers.md)|This script arranges the selected elements vertically with a fixed center spacing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance-between-centers.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed vertical distance](Fixed%20vertical%20distance.md)|The script arranges the selected elements vertically with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance.png)|[@1-2-3](https://github.com/1-2-3)|
|[Lighten background color](Lighten%20background%20color.md)|This script lightens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect.In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png)|[@1-2-3](https://github.com/1-2-3)|
|[Mindmap connector](Mindmap%20connector.md)|This script creates mindmap like lines (only right side and down available currently) for selected elements. The line will start according to the creation time of the elements. So you should create the header element first.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/mindmap%20connector.png)|[@xllowl](https://github.com/xllowl)|
|[Modify background color opacity](Modify%20background%20color%20opacity.md)|This script changes the opacity of the background color of the selected boxes. The default background color in Excalidraw is so dark that the text is hard to read. You can lighten the color a bit by setting transparency. And you can tweak the transparency over and over again until you're happy with it. Although excalidraw has the opacity option in its native property Settings, it also changes the transparency of the border. Use this script to change only the opacity of the background color without affecting the border.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-modify-background-color-opacity.png)|[@1-2-3](https://github.com/1-2-3)|
|[Normalize Selected Arrows](Normalize%20Selected%20Arrows.md)|This script will reset the start and end positions of the selected arrows. The arrow will point to the center of the connected box and will have a gap of 8px from the box.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-normalize-selected-arrows.png)|[@1-2-3](https://github.com/1-2-3)|
|[OCR - Optical Character Recognition](OCR%20-%20Optical%20Character%20Recognition.md)|The script will 1) send the selected image file to [taskbone.com](https://taskbone.com) to extract the text from the image, and 2) will add the text to your drawing as a text element.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Organic Line](Organic%20Line.md)|Converts selected freedraw lines such that pencil pressure will decrease from maximum to minimum from the beginning of the line to its end. The resulting line is placed at the back of the layers, under all other items. Helpful when drawing organic mindmaps.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-organic-line.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Repeat Elements](Repeat%20Elements.md)|This script will detect the difference between 2 selected elements, including position, size, angle, stroke and background color, and create several elements that repeat these differences based on the number of repetitions entered by the user.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-repeat-elements.png)|[@1-2-3](https://github.com/1-2-3)|
|[Reset LaTeX Size](Reset%20LaTeX%20Size.md)|Reset the sizes of embedded LaTeX equations to the default sizes or a multiple of the default sizes.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reset-latex.jpg)|[@firai](https://github.com/firai)|
|[Reverse arrows](Reverse%20arrows.md)|Reverse the direction of **arrows** within the scope of selected elements.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reverse-arrow.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Scribble Helper](Scribble%20Helper.md)|iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the creates a text element at pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then opens the input prompt where you can modify this text with scribble.|![]('https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-scribble-helper.jpg')|[@zsviczian](https://github.com/zsviczian)|
|[Select Elements of Type](Select%20Elements%20of%20Type.md)|Prompts you with a list of the different element types in the active image. Only elements of the selected type will be selected on the canvas. If nothing is selected when running the script, then the script will process all the elements on the canvas. If some elements are selected when the script is executed, then the script will only process the selected elements.<br>The script is useful when, for example, you want to bring to front all the arrows, or want to change the color of all the text elements, etc.|![]('https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-select-element-of-type.jpg')|[@zsviczian](https://github.com/zsviczian)|
|[Set background color of unclosed line object by adding a shadow clone](Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md)|Use this script to set the background color of unclosed (i.e. open) line objects by creating a clone of the object. The script will set the stroke color of the clone to transparent and will add a straight line to close the object. Use settings to define the default background color, the fill style, and the strokeWidth of the clone. By default the clone will be grouped with the original object, you can disable this also in settings.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Dimensions](Set%20Dimensions.md)|Currently there is no way to specify the exact location and size of objects in Excalidraw. You can bridge this gap with the following simple script.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Font Family](Set%20Font%20Family.md)|Sets font family of the text block (Virgil, Helvetica, Cascadia). Useful if you want to set a keyboard shortcut for selecting font family.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-font-family.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Grid](Set%20Grid.md)|The default grid size in Excalidraw is 20. Currently there is no way to change the grid size via the user interface. This script offers a way to bridge this gap.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-grid.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Link Alias](Set20%Link20%Alias.md)|Iterates all of the links in the selected TextElements and prompts the user to set or modify the alias for each link found.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-set-link-alias.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set stroke width of selected elements](Set%20Stroke%20Width%20of%20Selected%20Elements.md)|This script will set the stroke width of selected elements. This is helpful, for example, when you scale freedraw sketches and want to reduce or increase their line width.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-stroke-width.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split text by lines](Split%20text%20by%20lines.md)|Split lines of text into separate text elements for easier reorganization|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-split-lines.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Text Alignment](Set%20Text%20Alignment.md)|Sets text alignment of text block (cetner, right, left). Useful if you want to set a keyboard shortcut for selecting text alignment.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-align.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split Ellipse](Split%20Ellipse.md)|This script splits an ellipse at any point where a line intersects it.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-splitEllipse-demo1.png)|[@GColoy](https://github.com/GColoy)|
|[TheBrain-navigation](TheBrain-navigation.md)|An Excalidraw based graph user interface for your Vault. Requires the [Dataview plugin](https://github.com/blacksmithgu/obsidian-dataview). Generates a graph view similar to that of [TheBrain](https://TheBrain.com) plex. Watch introduction to this script on [YouTube](https://youtu.be/plYobK-VufM).|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/TheBrain.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Toggle Fullscreen on Mobile](Toggle%20Fullscreen%20on%20Mobile.md)|Hides Obsidian workspace leaf padding and header (based on option in settings, default is "hide header" = false) which will take Excalidraw to full screen. ⚠ Note that if the header is not visible, it will be very difficult to invoke the command palette to end full screen. Only hide the header if you have a keyboard or you've practiced opening command palette!|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/ea-toggle-fullscreen.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Toggle Grid](Toggle%20Grid.md)|Toggles the grid.||[@GColoy](https://github.com/GColoy)|
|[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)|
+256 -1174
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -401,7 +401,7 @@
},
{
"fname": "Slideshow.md",
"mtime": 1789502464420
"mtime": 1789297989767
},
{
"fname": "Slideshow.svg",
File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 KiB

+2 -2
View File
@@ -1,11 +1,11 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.28.0-beta.4",
"version": "2.28.0-beta.0",
"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://community.sketch-your-mind.com/em",
"authorUrl": "https://excalidraw-obsidian.online",
"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://community.sketch-your-mind.com/em",
"authorUrl": "https://excalidraw-obsidian.online",
"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.139",
"@zsviczian/excalidraw": "0.18.136",
"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.139",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.139.tgz",
"integrity": "sha512-3d31zicckBIK4VMyldgCLuPON5xCWNTxn0vF1r3FdlVbfLXI+OFdeq6Qog8aYO4IXN2W5XKdIF5Byzk17U4Aqg==",
"version": "0.18.136",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.136.tgz",
"integrity": "sha512-n43qggEICjK3NbpvOA4lKxtbFSXJp50WpD9iQOVS32PTXGm/eJtWzu1Ui3LYl30BVlPs/gjhCS7qO4tbqmlpBw==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
+3 -5
View File
@@ -21,10 +21,8 @@
"mindmap": "node scripts/deploy-mindmap-builder.mjs",
"lint": "eslint .",
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx}\" && eslint --max-warnings=0 --ext .ts,.tsx ./src --fix",
"repo:export": "node scripts/generate-repository-zip.mjs",
"repo:update": "node scripts/update-repository.mjs",
"script-store:build": "node scripts/build-script-store.mjs",
"script-store:check": "node scripts/build-script-store.mjs --check"
"repo:export": "bash scripts/generate-repository-zip.sh",
"repo:update": "rsync -av --progress ~/Downloads/update/ ./"
},
"keywords": [],
"author": "",
@@ -34,7 +32,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.139",
"@zsviczian/excalidraw": "0.18.136",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
+1 -57
View File
@@ -1,5 +1,4 @@
import { nodeResolve } from '@rollup/plugin-node-resolve';
import { execFileSync } from 'node:child_process';
import zlib from 'node:zlib';
import visualizer from 'rollup-plugin-visualizer';
import commonjs from '@rollup/plugin-commonjs';
@@ -33,59 +32,7 @@ const absolutePath = path.resolve(DIST_FOLDER);
fs.mkdirSync(absolutePath, { recursive: true });
const isProd = (process.env.NODE_ENV === "production");
const isLib = (process.env.NODE_ENV === "lib");
const DEFAULT_PLUGIN_REPOSITORY = {
owner: "zsviczian",
name: "obsidian-excalidraw-plugin",
ref: "master",
};
const resolvePluginRepositoryContext = () => {
const repository = { ...DEFAULT_PLUGIN_REPOSITORY };
try {
const remoteUrl = execFileSync("git", ["remote", "get-url", "origin"], {
cwd: process.cwd(),
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
const match = remoteUrl.match(
/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/i,
);
if (match) {
repository.owner = match[1];
repository.name = match[2];
}
const branch = execFileSync("git", ["branch", "--show-current"], {
cwd: process.cwd(),
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
if (branch) {
repository.ref = branch;
return repository;
}
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: process.cwd(),
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
if (commit) {
repository.ref = commit;
}
} catch {
// Source archives do not include .git. Keep canonical release defaults.
}
return repository;
};
const pluginRepository = resolvePluginRepositoryContext();
console.log(
`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}; repository: ${pluginRepository.owner}/${pluginRepository.name}@${pluginRepository.ref}`,
);
console.log(`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}`);
// Add non-English locales here to embed them as compressed payloads in main.js.
@@ -354,9 +301,6 @@ const getRollupPlugins = (tsconfig, ...plugins) => [
replace({
preventAssignment: true,
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
__PLUGIN_REPOSITORY_OWNER__: JSON.stringify(pluginRepository.owner),
__PLUGIN_REPOSITORY_NAME__: JSON.stringify(pluginRepository.name),
__PLUGIN_REPOSITORY_REF__: JSON.stringify(pluginRepository.ref),
}),
commonjs(),
nodeResolve({ browser: true, preferBuiltins: false }),
-195
View File
@@ -1,195 +0,0 @@
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const scriptsDir = path.join(root, "ea-scripts");
const catalogPath = path.join(scriptsDir, "script-store.json");
const directoryInfoPath = path.join(scriptsDir, "directory-info.json");
const checkOnly = process.argv.includes("--check");
const FEATURED_CATEGORY = "Editors Picks";
const fail = (message) => {
throw new Error(`[script-store] ${message}`);
};
const catalog = JSON.parse(fs.readFileSync(catalogPath, "utf8"));
const validateCatalog = () => {
if (catalog.version !== 1) {
fail(`Unsupported catalog version: ${catalog.version}`);
}
if (!Array.isArray(catalog.categories) || !Array.isArray(catalog.scripts)) {
fail("Catalog must contain categories[] and scripts[].");
}
const categories = new Set();
for (const category of catalog.categories) {
if (!category?.name || categories.has(category.name)) {
fail(`Invalid or duplicate category: ${category?.name ?? "<missing>"}`);
}
categories.add(category.name);
}
const names = new Set();
const files = new Set();
for (const script of catalog.scripts) {
if (!script?.name || !script?.file || !script?.installUrl) {
fail(`Script entry is missing name, file, or installUrl: ${JSON.stringify(script)}`);
}
if (names.has(script.name)) {
fail(`Duplicate script name: ${script.name}`);
}
if (files.has(script.file)) {
fail(`Duplicate script file: ${script.file}`);
}
names.add(script.name);
files.add(script.file);
if (!fs.existsSync(path.join(scriptsDir, script.file))) {
fail(`Missing script file: ea-scripts/${script.file}`);
}
for (const category of script.categories ?? []) {
if (!categories.has(category)) {
fail(`Unknown category "${category}" on ${script.name}`);
}
}
if (
script.featuredRank !== undefined &&
!script.categories?.includes(FEATURED_CATEGORY)
) {
fail(`${script.name} has featuredRank but is not in ${FEATURED_CATEGORY}.`);
}
}
};
const getGitOutput = (args) => {
try {
return execFileSync("git", args, {
cwd: root,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
});
} catch {
return null;
}
};
const getHeadDirectoryInfo = () => {
const source = getGitOutput(["show", "HEAD:ea-scripts/directory-info.json"]);
if (!source) {
return null;
}
try {
return JSON.parse(source);
} catch {
return null;
}
};
const getChangedManagedFiles = () => {
const status = getGitOutput([
"status",
"--porcelain=v1",
"--untracked-files=all",
"--",
"ea-scripts",
]);
if (status === null) {
return null;
}
const managed = new Set();
for (const script of catalog.scripts) {
managed.add(script.file);
managed.add(script.file.replace(/\.(?:md|js)$/i, ".svg"));
}
const changed = new Set();
for (const line of status.split(/\r?\n/)) {
if (line.length < 4) {
continue;
}
let filePath = line.slice(3).trim();
const renameSeparator = filePath.lastIndexOf(" -> ");
if (renameSeparator >= 0) {
filePath = filePath.slice(renameSeparator + 4);
}
if (filePath.startsWith('"') && filePath.endsWith('"')) {
filePath = filePath.slice(1, -1);
}
const prefix = "ea-scripts/";
if (!filePath.startsWith(prefix)) {
continue;
}
const filename = filePath.slice(prefix.length);
if (managed.has(filename)) {
changed.add(filename);
}
}
return changed;
};
const updateDirectoryInfoForChangedScripts = () => {
const existing = JSON.parse(fs.readFileSync(directoryInfoPath, "utf8"));
const changed = getChangedManagedFiles();
const headEntries = getHeadDirectoryInfo();
// Exported repository ZIPs do not contain .git. In that environment the
// historical mtimes are intentionally left completely untouched.
if (changed === null || headEntries === null || changed.size === 0) {
return null;
}
const headByName = new Map(headEntries.map((entry) => [entry.fname, entry.mtime]));
const currentByName = new Map(existing.map((entry) => [entry.fname, entry]));
let nextMtime = Date.now();
for (const filename of changed) {
const localPath = path.join(scriptsDir, filename);
if (!fs.existsSync(localPath)) {
continue;
}
const current = currentByName.get(filename);
const headMtime = headByName.get(filename);
// If this PR already changed the mtime, keep it. This makes repeated
// script-store:build runs idempotent and prevents timestamp churn.
if (current && headMtime !== undefined && current.mtime !== headMtime) {
continue;
}
const mtime = Math.max(nextMtime++, (current?.mtime ?? headMtime ?? 0) + 1);
if (current) {
current.mtime = mtime;
} else {
const entry = { fname: filename, mtime };
existing.push(entry);
currentByName.set(filename, entry);
}
}
return existing;
};
validateCatalog();
if (checkOnly) {
console.log(
`[script-store] Catalog OK: ${catalog.scripts.length} scripts in ${catalog.categories.length} categories.`,
);
process.exit(0);
}
const directoryInfo = updateDirectoryInfoForChangedScripts();
if (directoryInfo) {
const directoryInfoSource = `${JSON.stringify(directoryInfo, null, 2)}\n`;
if (directoryInfoSource !== fs.readFileSync(directoryInfoPath, "utf8")) {
fs.writeFileSync(directoryInfoPath, directoryInfoSource);
}
}
console.log(
`[script-store] Validated ${catalog.scripts.length} scripts and updated directory-info.json for changed script/icon files.`,
);
@@ -1,111 +0,0 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const log = (message) => process.stdout.write(`${message}\n`);
const jiti = createJiti(import.meta.url);
const {
collectReachableDependencyValues,
getMatchingTopLevelDependencyKeys,
hasReachableDependency,
} = await jiti.import("../src/utils/nestedDependencyTraversal.ts");
const graph = (entries) => ({
nodes: new Map(
Object.entries(entries).map(([key, childKeys]) => [
key,
{ value: key, childKeys },
]),
),
});
const diamond = graph({
root: ["left", "right"],
left: ["shared"],
right: ["shared"],
shared: ["leaf"],
leaf: [],
});
assert.deepEqual(
collectReachableDependencyValues(diamond, "root"),
["left", "right", "shared", "leaf"],
"direct dependencies retain metadata order and shared dependencies are returned once",
);
assert.deepEqual(
getMatchingTopLevelDependencyKeys(
diamond,
"root",
new Set(["left", "right"]),
(value) => value === "leaf",
),
new Set(["left", "right"]),
"a changed shared descendant must invalidate every containing top-level dependency",
);
const cyclic = graph({
root: ["a"],
a: ["b"],
b: ["root", "a", "changed"],
changed: [],
});
let cycleVisits = 0;
assert.equal(
hasReachableDependency(cyclic, "root", (value) => {
cycleVisits++;
return value === "changed";
}),
true,
"cycles must terminate and still find reachable changes",
);
assert.ok(cycleVisits <= 3, "a cycle must not cause repeated visits");
assert.deepEqual(
getMatchingTopLevelDependencyKeys(
cyclic,
"root",
new Set(["a"]),
(value) => value === "root",
),
new Set(),
"a back-link to the root must not invalidate a top-level dependency",
);
const layeredEntries = { root: ["top"] };
const layerCount = 22;
for (let layer = 0; layer < layerCount; layer++) {
const left = `left-${layer}`;
const right = `right-${layer}`;
const nextLeft = `left-${layer + 1}`;
const nextRight = `right-${layer + 1}`;
layeredEntries[left] = [nextLeft, nextRight];
layeredEntries[right] = [nextLeft, nextRight];
}
layeredEntries.top = ["left-0", "right-0"];
layeredEntries[`left-${layerCount}`] = [];
layeredEntries[`right-${layerCount}`] = [];
const layered = graph(layeredEntries);
let layeredVisits = 0;
assert.equal(
hasReachableDependency(layered, "root", () => {
layeredVisits++;
return false;
}),
false,
"an unchanged dependency graph must report no change",
);
assert.equal(
layeredVisits,
layered.nodes.size - 1,
"a graph with exponentially many conceptual paths must visit each node once",
);
assert.deepEqual(
getMatchingTopLevelDependencyKeys(
diamond,
"root",
new Set(["left"]),
(value) => value === "right",
),
new Set(),
"only requested direct dependencies may be returned",
);
log("nested dependency traversal checks passed");
+5 -15
View File
@@ -1,11 +1,8 @@
/* eslint-disable no-console */
import fs from 'fs';
import path from 'path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { syncScriptTemplateTypes } from './sync-script-template-types.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..');
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
const INDEX_NEW = path.join(EA_SCRIPTS_DIR, 'index-new.md');
const OUT_DIR = path.join(path.join(ROOT, 'docs'), 'AITrainingData');
@@ -54,8 +51,7 @@ For a reference, follow the implementation pattern used in the "Printable Layout
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on \`ea.obsidian\`.
- In a template-based script workspace, \`src/types/ea.d.ts\` is an upstream-managed projection of the Script Engine API. Never edit it or generated declarations under \`.template/types/\`. Put repository-specific ambient declarations and type augmentations in \`src/types/local.d.ts\` instead, so template updates can replace the generated API safely.
- Version checks are distinct: use \`ea.verifyMinimumPluginVersion()\` for the Excalidraw plugin and \`ea.obsidian.requireApiVersion()\` only for the Obsidian application version.
- Version checks are distinct: use \`ea.verifyMinimumPluginVersion()\` for the Excalidraw plugin and \`ea.verifyMinAppVersion()\` only for the Obsidian application version.
- \`utils.executionSource\` describes why the current top-level invocation happened. Supported values are \`"manual"\`, \`"plugin-startup"\`, \`"view-autostart"\`, \`"sidepanel-restore"\`, \`"sidepanel-reload"\`, and \`"drawing-onload"\`. It does not indicate whether code came from the compilation cache or whether the script has run before.
- \`ea.registerAutostart(message?)\` requests view-autostart permission. The script is automatically attached once to each ExcalidrawView, while manual toolbar/command/hotkey invocation remains independently repeatable. The optional explanation appears as the second paragraph of the permission prompt; do not imply that the script's main interactive action starts automatically when only its tools/providers do.
- \`ea.registerCleanup(cleanup)\` registers synchronous cleanup owned by the current EA instance. Use it for external listeners, timers, observers, and subscriptions; the cleanup runs when that EA is destroyed.
@@ -617,7 +613,6 @@ function syncTemplateRepository(mode = 'full') {
fs.rmSync(TEMPLATE_BOOTSTRAP_DIR, { recursive: true, force: true });
copyDirectoryRecursive(SKILL_DIR, TEMPLATE_BOOTSTRAP_DIR);
normalizeTemplateScriptReferences();
syncScriptTemplateTypes(TEMPLATE_REPO_ROOT);
writeTemplateBootstrapFile('README.md', `# ExcalidrawAutomate skill snapshot
This directory is synchronized from the plugin repository:
@@ -625,11 +620,6 @@ https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/docs/AITrain
Update source content by running npm run doc in the plugin repository.
`);
const manifestScript = path.join(TEMPLATE_REPO_ROOT, 'scripts/template-manifest.mjs');
if (fs.existsSync(manifestScript)) {
console.log('[template] Refreshing managed-file manifest...');
execFileSync(process.execPath, [manifestScript], { cwd: TEMPLATE_REPO_ROOT, stdio: 'inherit' });
}
return;
}
@@ -934,9 +924,9 @@ The AI training material is maintained independently from publishing PRs; do not
- Add or update the script under [ea-scripts](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts).
- Add or update the preview image under [images](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images).
- Add or update the script's catalog entry in [ea-scripts/script-store.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/script-store.json).
- Run \`npm run script-store:check\`, then \`npm run script-store:build\`. The build validates the catalog and advances \`directory-info.json\` only for script/icon files that actually changed; it does not modify the frozen legacy \`index-new.md\` catalog.
- Do not hand-edit unrelated \`mtime\` values in [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json). Historical mtimes are part of the plugin's update-detection contract.
- Keep [ea-scripts/index-new.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index-new.md) manually curated; do not automate it.
- Update [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) in the same PR.
- For script updates, refresh the matching entry's \`mtime\` in [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) so the plugin can detect the newer local version.
- Keep the PR focused on the script and its generated references.
### How to use the Script Examples
-330
View File
@@ -1,330 +0,0 @@
import {
chmodSync,
copyFileSync,
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
statSync,
utimesSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { basename, join, relative, resolve, sep } from "node:path";
import { spawnSync } from "node:child_process";
const OUTPUT = "repository.zip";
const IGNORE_DIRS = new Set([
".git",
".svn",
".hg",
"node_modules",
"dist",
".next",
".nuxt",
".cache",
".parcel-cache",
".turbo",
".idea",
".vscode",
".tools",
"coverage",
"build",
"out",
"output",
"secrets",
".claude",
"__MACOSX",
]);
const IGNORE_FILENAMES = new Set([
".DS_Store",
"Thumbs.db",
"REPOSITORY_STRUCTURE.md",
"REPOSITORY_CONTENTS.md",
OUTPUT,
]);
const IGNORE_EXTENSIONS = [
// Images
".png",
".jpg",
".jpeg",
".gif",
".webp",
".bmp",
".tif",
".tiff",
".ico",
".icns",
".avif",
".heic",
".heif",
".svgz",
// PDF / ebook / office containers
".pdf",
".epub",
".doc",
".docx",
".xls",
".xlsx",
".ppt",
".pptx",
// Audio
".mp3",
".wav",
".flac",
".aac",
".m4a",
".ogg",
".opus",
".wma",
// Video
".mp4",
".mov",
".mkv",
".avi",
".webm",
".m4v",
".mpeg",
".mpg",
// Fonts
".ttf",
".otf",
".woff",
".woff2",
".eot",
// Archives / compressed files
".zip",
".tar",
".gz",
".tgz",
".bz2",
".xz",
".7z",
".rar",
// Native binaries / executables / compiled objects
".exe",
".dll",
".so",
".dylib",
".bin",
".com",
".app",
".msi",
".o",
".obj",
".a",
".lib",
".class",
".jar",
".war",
".wasm",
".node",
// Binary databases / data formats
".db",
".sqlite",
".sqlite3",
".parquet",
".arrow",
".feather",
];
function isIgnoredExtension(filename) {
const lower = filename.toLowerCase();
return IGNORE_EXTENSIONS.some((extension) => lower.endsWith(extension));
}
function looksBinary(filePath) {
const buffer = readFileSync(filePath);
if (buffer.length === 0) return false;
if (buffer.includes(0)) return true;
try {
new TextDecoder("utf-8", { fatal: true }).decode(buffer);
} catch {
return true;
}
let suspiciousControls = 0;
for (const byte of buffer) {
const allowedControl = byte === 8 || byte === 9 || byte === 10 || byte === 12 || byte === 13;
if ((byte < 32 && !allowedControl) || byte === 127) {
suspiciousControls += 1;
}
}
return suspiciousControls / buffer.length > 0.01;
}
function copyPreservingMetadata(source, destination) {
mkdirSync(resolve(destination, ".."), { recursive: true });
copyFileSync(source, destination);
const stat = statSync(source);
chmodSync(destination, stat.mode);
utimesSync(destination, stat.atime, stat.mtime);
}
function collectFiles(root) {
const files = [];
const stats = {
included: 0,
skippedBinary: 0,
skippedType: 0,
skippedName: 0,
skippedDir: 0,
skippedOther: 0,
};
function walk(directory) {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const fullPath = join(directory, entry.name);
if (entry.isDirectory()) {
if (IGNORE_DIRS.has(entry.name)) {
stats.skippedDir += 1;
continue;
}
walk(fullPath);
continue;
}
// Match the old `find . -type f` behavior: do not include symlinks,
// sockets, devices, or other non-regular filesystem entries.
if (!entry.isFile()) {
stats.skippedOther += 1;
continue;
}
if (IGNORE_FILENAMES.has(entry.name)) {
stats.skippedName += 1;
continue;
}
if (isIgnoredExtension(entry.name)) {
stats.skippedType += 1;
continue;
}
if (looksBinary(fullPath)) {
stats.skippedBinary += 1;
continue;
}
files.push(fullPath);
stats.included += 1;
}
}
walk(root);
return { files, stats };
}
function createZipWithZipCommand(stageDir, outputPath) {
const result = spawnSync("zip", ["-q", "-r", outputPath, "."], {
cwd: stageDir,
stdio: "inherit",
});
if (result.error?.code === "ENOENT") {
throw new Error("'zip' is required on macOS/Linux but was not found in PATH.");
}
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`zip exited with status ${result.status ?? "unknown"}.`);
}
}
function createZipWithPowerShell(stageDir, outputPath) {
const command = [
"Add-Type -AssemblyName System.IO.Compression.FileSystem;",
"[System.IO.Compression.ZipFile]::CreateFromDirectory(",
"$env:REPO_EXPORT_STAGE,",
"$env:REPO_EXPORT_OUTPUT,",
"[System.IO.Compression.CompressionLevel]::Optimal,",
"$false",
")",
].join(" ");
const env = {
...process.env,
REPO_EXPORT_STAGE: stageDir,
REPO_EXPORT_OUTPUT: outputPath,
};
let lastError;
for (const executable of ["powershell.exe", "pwsh.exe"]) {
const result = spawnSync(
executable,
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command],
{ env, stdio: "inherit" },
);
if (result.error?.code === "ENOENT") {
lastError = result.error;
continue;
}
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`${executable} exited with status ${result.status ?? "unknown"}.`);
}
return;
}
throw new Error(
`PowerShell is required on Windows but was not found.${lastError ? ` ${lastError.message}` : ""}`,
);
}
const root = process.cwd();
const outputPath = join(root, OUTPUT);
const stageDir = mkdtempSync(join(tmpdir(), "ea-repo-export-"));
try {
const { files, stats } = collectFiles(root);
if (files.length === 0) {
console.log("No files matched the inclusion rules; no ZIP created.");
process.exitCode = 0;
} else {
for (const source of files) {
const relativePath = relative(root, source);
const destination = join(stageDir, ...relativePath.split(sep));
copyPreservingMetadata(source, destination);
}
rmSync(outputPath, { force: true });
if (process.platform === "win32") {
createZipWithPowerShell(stageDir, outputPath);
} else {
createZipWithZipCommand(stageDir, outputPath);
}
console.log(`Created ${basename(outputPath)}`);
console.log(`Included files: ${stats.included}`);
console.log(`Skipped ignored folders: ${stats.skippedDir}`);
console.log(`Skipped because of ignored filenames: ${stats.skippedName}`);
console.log(`Skipped because of ignored file types: ${stats.skippedType}`);
console.log(`Skipped because binary content was detected: ${stats.skippedBinary}`);
if (stats.skippedOther > 0) {
console.log(`Skipped non-regular filesystem entries: ${stats.skippedOther}`);
}
}
} finally {
if (existsSync(stageDir)) {
rmSync(stageDir, { recursive: true, force: true });
}
}
+304
View File
@@ -0,0 +1,304 @@
#!/usr/bin/env bash
# generate-repository-zip.sh
#
# Run from the root of a repository:
#
# bash generate-repository-zip.sh
#
# Generates:
# ./repository.zip
#
# The ZIP preserves the repository-relative directory structure while excluding:
# - node_modules, dist, and other ignored folders
# - __MACOSX folders
# - .DS_Store and other ignored filenames
# - common binary/media/archive/executable file types
# - files detected as binary even if their extension is unknown
#
# Requirements:
# - bash
# - find
# - file
# - zip
#
# Edit IGNORE_DIRS, IGNORE_FILENAMES, and IGNORE_EXTENSIONS below to customize.
set -euo pipefail
OUTPUT="repository.zip"
# ---------------------------------------------------------------------------
# Folder exclusions
# ---------------------------------------------------------------------------
# Folder names are matched at any depth.
IGNORE_DIRS=(
".git"
".svn"
".hg"
"node_modules"
"dist"
".next"
".nuxt"
".cache"
".parcel-cache"
".turbo"
".idea"
".vscode"
".tools"
"coverage"
"build"
"out"
"output"
"secrets"
".claude"
"__MACOSX"
)
# ---------------------------------------------------------------------------
# Filename exclusions
# ---------------------------------------------------------------------------
# Exact filenames are matched at any depth.
IGNORE_FILENAMES=(
".DS_Store"
"Thumbs.db"
"REPOSITORY_STRUCTURE.md"
"REPOSITORY_CONTENTS.md"
# Never package a previously generated repository archive.
"repository.zip"
)
# ---------------------------------------------------------------------------
# File-type exclusions
# ---------------------------------------------------------------------------
# Extensions are lowercase and include the leading dot.
IGNORE_EXTENSIONS=(
# Images
".png"
".jpg"
".jpeg"
".gif"
".webp"
".bmp"
".tif"
".tiff"
".ico"
".icns"
".avif"
".heic"
".heif"
".svg"
".svgz"
# PDF / ebook / office containers
".pdf"
".epub"
".doc"
".docx"
".xls"
".xlsx"
".ppt"
".pptx"
# Audio
".mp3"
".wav"
".flac"
".aac"
".m4a"
".ogg"
".opus"
".wma"
# Video
".mp4"
".mov"
".mkv"
".avi"
".webm"
".m4v"
".mpeg"
".mpg"
# Fonts
".ttf"
".otf"
".woff"
".woff2"
".eot"
# Archives / compressed files
".zip"
".tar"
".gz"
".tgz"
".bz2"
".xz"
".7z"
".rar"
# Native binaries / executables / compiled objects
".exe"
".dll"
".so"
".dylib"
".bin"
".com"
".app"
".msi"
".o"
".obj"
".a"
".lib"
".class"
".jar"
".war"
".wasm"
".node"
# Binary databases / data formats
".db"
".sqlite"
".sqlite3"
".parquet"
".arrow"
".feather"
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
contains_exact() {
local needle="$1"
shift
local item
for item in "$@"; do
[[ "$needle" == "$item" ]] && return 0
done
return 1
}
path_has_ignored_dir() {
local relative_path="$1"
local dir
for dir in "${IGNORE_DIRS[@]}"; do
if [[ "$relative_path" == "$dir/"* || "$relative_path" == *"/$dir/"* ]]; then
return 0
fi
done
return 1
}
is_ignored_filename() {
local filename="$1"
contains_exact "$filename" "${IGNORE_FILENAMES[@]}"
}
is_ignored_extension() {
local filename="$1"
local lower
lower="$(printf '%s' "$filename" | tr '[:upper:]' '[:lower:]')"
local ext
for ext in "${IGNORE_EXTENSIONS[@]}"; do
[[ "$lower" == *"$ext" ]] && return 0
done
return 1
}
looks_binary() {
local file_path="$1"
# Empty files are harmless text-like repository artifacts.
[[ ! -s "$file_path" ]] && return 1
# `file --mime-encoding` returns "binary" for binary data on macOS/Linux.
local encoding
encoding="$(file -b --mime-encoding "$file_path" 2>/dev/null || true)"
[[ "$encoding" == "binary" ]]
}
# ---------------------------------------------------------------------------
# Build file list
# ---------------------------------------------------------------------------
command -v zip >/dev/null 2>&1 || {
echo "Error: 'zip' is required but was not found." >&2
exit 1
}
command -v file >/dev/null 2>&1 || {
echo "Error: 'file' is required but was not found." >&2
exit 1
}
TMP_LIST="$(mktemp)"
trap 'rm -f "$TMP_LIST"' EXIT
included=0
skipped_binary=0
skipped_type=0
skipped_name=0
skipped_dir=0
while IFS= read -r -d '' full_path; do
relative_path="${full_path#./}"
filename="${relative_path##*/}"
if path_has_ignored_dir "$relative_path"; then
((skipped_dir += 1))
continue
fi
if is_ignored_filename "$filename"; then
((skipped_name += 1))
continue
fi
if is_ignored_extension "$filename"; then
((skipped_type += 1))
continue
fi
if looks_binary "$full_path"; then
((skipped_binary += 1))
continue
fi
printf '%s\n' "$relative_path" >> "$TMP_LIST"
((included += 1))
done < <(find . -type f -print0)
# Remove any previous archive before creating the new one.
rm -f "$OUTPUT"
if [[ ! -s "$TMP_LIST" ]]; then
echo "No files matched the inclusion rules; no ZIP created."
exit 0
fi
# -q quiet
# -@ read file paths from stdin
#
# Repository-relative paths are stored in the archive, not absolute paths.
zip -q "$OUTPUT" -@ < "$TMP_LIST"
echo "Created $OUTPUT"
echo "Included files: $included"
echo "Skipped because of ignored folders: $skipped_dir"
echo "Skipped because of ignored filenames: $skipped_name"
echo "Skipped because of ignored file types: $skipped_type"
echo "Skipped because binary content was detected: $skipped_binary"
-196
View File
@@ -1,196 +0,0 @@
// Project only declarations reachable from the supported script surface.
import fs from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
const hidden = (node) => node.modifiers?.some((m) =>
[ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword].includes(m.kind));
const names = (statement) => ts.isVariableStatement(statement)
? statement.declarationList.declarations.map((item) => item.name.text)
: statement.name ? [statement.name.text] : [];
export function projectScriptApi(root) {
const modules = new Map();
const selected = new Map();
const pending = [];
const external = new Set();
const overrides = new Map([
['core/main', `import type { App } from "obsidian";
/** Compatibility access to the official Obsidian app; plugin internals are not a scripting API. */
export default interface ExcalidrawPlugin { readonly app: App; }`],
['view/ExcalidrawView', `import type { TFile, WorkspaceLeaf } from "obsidian";
/** View identity and UI ownership for EA hooks. Use EA for drawing operations. */
export default interface ExcalidrawView {
readonly file: TFile | null;
readonly leaf: WorkspaceLeaf;
readonly contentEl: HTMLDivElement;
readonly ownerDocument: Document;
readonly ownerWindow: Window;
}`],
['shared/EmbeddedFileLoader', `declare const embeddedFilesLoader: unique symbol;
/** Opaque EA-owned handle. Obtain through ea.getEmbeddedFilesLoader(), then pass back to EA. */
export interface EmbeddedFilesLoader { readonly [embeddedFilesLoader]: never; }`],
['view/managers/CanvasNodeFactory', `declare const canvasNode: unique symbol;
/** Opaque embedded-canvas identity; Obsidian Canvas internals are not a scripting API. */
export interface ObsidianCanvasNode { readonly [canvasNode]: never; }`],
['view/sidepanel/SidepanelTab', `export type { SidepanelTab as ExcalidrawSidepanelTab } from "src/types/sidepanelTabTypes";`],
]);
const outputNames = {
'core/main': 'scriptPlugin', 'view/ExcalidrawView': 'scriptView',
'shared/ExcalidrawAutomate': 'excalidrawAutomate',
'shared/EmbeddedFileLoader': 'embeddedFilesLoader',
'view/managers/CanvasNodeFactory': 'embeddedCanvasNode',
'view/sidepanel/SidepanelTab': 'sidepanelTab',
'shared/Dialogs/FloatingModal': 'floatingModal',
'types/excalidrawLib': 'excalidrawLib',
'scriptUtils': 'scriptUtils',
};
const outputName = (name) => outputNames[name] ?? `support/${name}`;
function input(name) {
const lib = path.join(root, 'lib', `${name}.d.ts`);
return fs.readFileSync(fs.existsSync(lib) ? lib : path.join(root, 'src', `${name}.d.ts`), 'utf8');
}
// Utils are invocation helpers, not the ScriptEngine implementation class.
const scriptFile = ts.createSourceFile('Scripts.d.ts', input('shared/Scripts'), ts.ScriptTarget.Latest, true);
const engine = scriptFile.statements.find((node) => ts.isClassDeclaration(node));
function utility(name, skip) {
const method = engine.members.find((member) => member.name?.text === name);
const typeParameters = method.typeParameters?.length
? `<${method.typeParameters.map((p) => p.getText(scriptFile)).join(', ')}>` : '';
const result = name === 'inputPrompt' ? 'Promise<string | undefined>' : method.type.getText(scriptFile);
return `${name}${typeParameters}(${method.parameters.slice(skip).map((p) => p.getText(scriptFile)).join(', ')}): ${result};`;
}
const executionSource = scriptFile.statements.find((node) => node.name?.text === 'ScriptExecutionSource');
overrides.set('scriptUtils', `import type { TFile, Instruction } from "obsidian";
import type { ButtonDefinition, InputPromptOptions } from "src/types/promptTypes";
${executionSource.getText(scriptFile)}
export interface ScriptUtils {
${utility('inputPrompt', 3)}
inputPrompt(options: InputPromptOptions): Promise<string | undefined>;
${utility('suggester', 1)}
readonly scriptFile: TFile;
readonly executionSource: ScriptExecutionSource;
}`);
function module(name) {
if (modules.has(name)) return modules.get(name);
const file = ts.createSourceFile(`${name}.d.ts`, overrides.get(name) ?? input(name), ts.ScriptTarget.Latest, true);
const imports = new Map();
const declarations = new Map();
const reexports = new Map();
for (const statement of file.statements) {
if (ts.isImportDeclaration(statement)) {
const clause = statement.importClause;
if (clause?.name) imports.set(clause.name.text, { specifier: statement.moduleSpecifier.text, imported: 'default' });
const bindings = clause?.namedBindings;
if (bindings && ts.isNamedImports(bindings)) for (const item of bindings.elements) {
imports.set(item.name.text, { specifier: statement.moduleSpecifier.text, imported: item.propertyName?.text ?? item.name.text });
}
if (bindings && ts.isNamespaceImport(bindings)) imports.set(bindings.name.text, { specifier: statement.moduleSpecifier.text, imported: '*' });
} else if (ts.isExportDeclaration(statement) && statement.moduleSpecifier && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
for (const item of statement.exportClause.elements) reexports.set(item.name.text, { specifier: statement.moduleSpecifier.text, imported: item.propertyName?.text ?? item.name.text });
} else {
for (const key of names(statement)) declarations.set(key, statement);
if (statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) declarations.set('default', statement);
}
}
const result = { file, imports, declarations, reexports, usedImports: new Map(), usedExports: new Map(), emitted: new Set() };
modules.set(name, result);
return result;
}
function resolve(from, specifier) {
if (!specifier.startsWith('.') && !specifier.startsWith('src/')) {
external.add(specifier.startsWith('@') ? specifier.split('/').slice(0, 2).join('/') : specifier.split('/')[0]);
return { specifier, local: false };
}
let target = specifier.startsWith('src/') ? specifier.slice(4) : path.posix.normalize(path.posix.join(path.posix.dirname(from), specifier));
if (target.startsWith('../')) throw new Error(`Type import escapes source: ${specifier}`);
if (fs.existsSync(path.join(root, 'lib', target, 'index.d.ts'))) target += '/index';
let relative = path.posix.relative(path.posix.dirname(outputName(from)), outputName(target));
if (!relative.startsWith('.')) relative = `./${relative}`;
return { specifier: relative, local: true, target };
}
function request(name, symbol) {
if (!selected.has(name)) selected.set(name, new Set());
if (selected.get(name).has(symbol)) return;
selected.get(name).add(symbol);
pending.push([name, symbol]);
}
function follow(from, ref) {
const result = resolve(from, ref.specifier);
if (result.local) {
if (ref.imported === '*') throw new Error(`Unreviewed local namespace import in ${from}`);
request(result.target, ref.imported);
}
return result.specifier;
}
// Strip implementation-only members before traversing dependencies.
function project(name, declaration) {
if (ts.isClassDeclaration(declaration)) {
const members = declaration.members.filter((member) => !hidden(member) &&
!(name === 'shared/ExcalidrawAutomate' && ts.isConstructorDeclaration(member)));
return ts.factory.updateClassDeclaration(declaration, declaration.modifiers, declaration.name,
declaration.typeParameters, declaration.heritageClauses, members);
}
if (name === 'types/excalidrawLib' && ts.isModuleDeclaration(declaration)) {
const internal = /^(Obsidian.*Host.*|configureObsidian.*Host.*|OBSIDIAN_.*_HOST_PROTOCOL_VERSION)$/;
const body = ts.factory.updateModuleBlock(declaration.body, declaration.body.statements.filter((node) =>
!names(node).some((key) => internal.test(key))));
return ts.factory.updateModuleDeclaration(declaration, declaration.modifiers, declaration.name, body);
}
return declaration;
}
for (const [name, symbol] of [['shared/ExcalidrawAutomate', 'ExcalidrawAutomate'], ['types/excalidrawLib', 'ExcalidrawLib'], ['scriptUtils', 'ScriptUtils'], ['scriptUtils', 'ScriptExecutionSource']]) request(name, symbol);
while (pending.length) {
const [name, symbol] = pending.pop();
const current = module(name);
const reexport = current.reexports.get(symbol);
if (reexport) { current.usedExports.set(symbol, { ...reexport, specifier: follow(name, reexport) }); continue; }
const declaration = current.declarations.get(symbol);
if (!declaration) throw new Error(`Unresolved public type ${name}#${symbol}`);
const projected = project(name, declaration);
current.emitted.add(projected);
function visit(node) {
if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
const specifier = node.argument.literal.text;
const result = resolve(name, specifier);
if (result.local) {
if (!node.qualifier || !ts.isIdentifier(node.qualifier)) throw new Error(`Unsupported import type: ${node.getText(current.file)}`);
request(result.target, node.qualifier.text);
}
} else if (ts.isIdentifier(node)) {
const ref = current.imports.get(node.text);
if (ref) current.usedImports.set(node.text, { ...ref, specifier: follow(name, ref) });
else if (current.declarations.has(node.text)) request(name, node.text);
}
ts.forEachChild(node, visit);
}
visit(projected);
}
const files = new Map();
for (const [name, current] of modules) {
const imports = [...current.usedImports].map(([local, ref]) => {
const binding = ref.imported === 'default' ? local : ref.imported === '*' ? `* as ${local}` : `{ ${ref.imported === local ? local : `${ref.imported} as ${local}`} }`;
return `import type ${binding} from ${JSON.stringify(ref.specifier)};`;
});
const exports = [...current.usedExports].map(([local, ref]) => `export type { ${ref.imported === local ? local : `${ref.imported} as ${local}`} } from ${JSON.stringify(ref.specifier)};`);
const declarations = [...current.emitted].map((node) => {
const transformed = ts.transform(node, [(context) => {
const visit = (child) => {
if (ts.isImportTypeNode(child) && ts.isLiteralTypeNode(child.argument)) {
const specifier = resolve(name, child.argument.literal.text).specifier;
return ts.factory.updateImportTypeNode(child, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(specifier)), child.attributes, child.qualifier, child.typeArguments, child.isTypeOf);
}
return ts.visitEachChild(child, visit, context);
};
return (rootNode) => ts.visitNode(rootNode, visit);
}]);
const content = printer.printNode(ts.EmitHint.Unspecified, transformed.transformed[0], current.file);
transformed.dispose();
return content;
});
files.set(`${outputName(name)}.d.ts`, '// Generated scripting API. No plugin implementation declarations.\n' + [...imports, ...exports, ...declarations, 'export {};'].join('\n') + '\n');
}
return { files, external };
}
-69
View File
@@ -1,69 +0,0 @@
// Publishes a restricted scripting API projection, never the plugin implementation graph.
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
import { projectScriptApi } from './script-api-projection.mjs';
const log = (...args) => console.log(...args);
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
export function syncScriptTemplateTypes(templateRoot = path.resolve(root, '../ea-script-template')) {
if (!fs.existsSync(templateRoot)) return;
const output = path.join(templateRoot, '.template/types');
const { files: projectedFiles, external } = projectScriptApi(root);
const declarations = new Map();
function forkPath(specifier) {
return specifier
.replace(/^@zsviczian\/excalidraw\/types\/excalidraw$/, '@zsviczian/excalidraw')
.replace(/^@zsviczian\/excalidraw\/types\/excalidraw\//, '@zsviczian/excalidraw/')
.replace(/^@zsviczian\/excalidraw\/types\/(common|element|math|utils)\/src(?:\/index)?$/, '@zsviczian/excalidraw/$1/index')
.replace(/^@zsviczian\/excalidraw\/types\/(common|element|math|utils)\/src\//, '@zsviczian/excalidraw/$1/')
.replace(/^@excalidraw\/excalidraw\//, '@zsviczian/excalidraw/')
.replace(/^@excalidraw\/(common|element|math|utils)$/, '@zsviczian/excalidraw/$1/index')
.replace(/^@excalidraw\/(common|element|math|utils)\//, '@zsviczian/excalidraw/$1/');
}
for (const [name, source] of projectedFiles) {
let content = source;
for (const item of ts.preProcessFile(content).importedFiles.toReversed()) {
content = content.slice(0, item.pos + 1) + forkPath(item.fileName) + content.slice(item.end + 1);
}
declarations.set(name, content);
}
const pluginPackage = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const pkgPath = path.join(templateRoot, 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const forkPackage = JSON.parse(fs.readFileSync(path.join(root, 'node_modules/@zsviczian/excalidraw/package.json'), 'utf8'));
const dependencies = { ...forkPackage.devDependencies, ...pluginPackage.dependencies, ...pluginPackage.devDependencies };
external.add('@excalidraw/mermaid-to-excalidraw');
// Retire dependencies added by the old implementation-graph snapshot.
for (const name of ['react-dom', '@zsviczian/excalidraw-extras-api']) delete pkg.devDependencies[name];
for (const name of external) {
if (name === 'react') { pkg.devDependencies['@types/react'] = dependencies['@types/react']; continue; }
if (name === 'polybooljs') continue; // Included ambient declaration, no runtime dependency.
if (!dependencies[name]) throw new Error(`No declared version for type dependency ${name}`);
// Use the template's supported Obsidian baseline; never downgrade it during generation.
if (name === 'obsidian') continue;
pkg.devDependencies[name] = dependencies[name];
}
fs.rmSync(output, { recursive: true, force: true });
for (const [name, content] of declarations) {
const target = path.join(output, name);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content);
}
fs.copyFileSync(path.join(root, 'src/types/polybooljs.d.ts'), path.join(output, 'polybooljs.d.ts'));
const revision = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim();
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));
fs.writeFileSync(path.join(templateRoot, '.template/api-source.json'), JSON.stringify({
repository: 'https://github.com/zsviczian/obsidian-excalidraw-plugin', revision,
sourceDirty: Boolean(execFileSync('git', ['status', '--porcelain', '--', 'src', 'package.json', 'manifest.json'], { cwd: root, encoding: 'utf8' }).trim()),
pluginVersion: manifest.version, excalidrawVersion: dependencies['@zsviczian/excalidraw'],
}, null, 2) + '\n');
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
log(`[template-types] Synced ${declarations.size} declaration files from ${revision}`);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) syncScriptTemplateTypes(process.argv[2]);
-49
View File
@@ -1,49 +0,0 @@
import { cpSync, existsSync, lstatSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { join, relative, resolve } from "node:path";
const sourceRoot = resolve(
process.env.REPO_UPDATE_DIR || join(homedir(), "Downloads", "update"),
);
const destinationRoot = process.cwd();
if (!existsSync(sourceRoot) || !lstatSync(sourceRoot).isDirectory()) {
console.error(`Update folder not found: ${sourceRoot}`);
process.exit(1);
}
let copiedFiles = 0;
function countFiles(path) {
const stat = lstatSync(path);
if (stat.isSymbolicLink() || stat.isFile()) return 1;
if (!stat.isDirectory()) return 0;
let count = 0;
for (const entry of readdirSync(path)) {
count += countFiles(join(path, entry));
}
return count;
}
console.log(`Updating repository from: ${sourceRoot}`);
for (const entry of readdirSync(sourceRoot, { withFileTypes: true })) {
const source = join(sourceRoot, entry.name);
const destination = join(destinationRoot, entry.name);
const entryFileCount = countFiles(source);
cpSync(source, destination, {
recursive: true,
force: true,
errorOnExist: false,
dereference: false,
preserveTimestamps: true,
verbatimSymlinks: true,
});
copiedFiles += entryFileCount;
console.log(`Copied ${relative(sourceRoot, source)}`);
}
console.log(`Repository update complete. Copied ${copiedFiles} file${copiedFiles === 1 ? "" : "s"}.`);
+1
View File
@@ -247,6 +247,7 @@ 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;
+6 -57
View File
@@ -42,47 +42,6 @@ export function buildSafeUrl(
return `https://${domain}${path}`;
}
// Replaced by Rollup from the checked-out Git repository and branch.
declare const __PLUGIN_REPOSITORY_OWNER__: string;
declare const __PLUGIN_REPOSITORY_NAME__: string;
declare const __PLUGIN_REPOSITORY_REF__: string;
export const PLUGIN_REPOSITORY_OWNER = __PLUGIN_REPOSITORY_OWNER__;
export const PLUGIN_REPOSITORY_NAME = __PLUGIN_REPOSITORY_NAME__;
export const PLUGIN_REPOSITORY_REF = __PLUGIN_REPOSITORY_REF__;
const PLUGIN_REPOSITORY_PATH = [
PLUGIN_REPOSITORY_OWNER,
PLUGIN_REPOSITORY_NAME,
] as const;
const pathParts = (value: string): string[] =>
value
.split("/")
.filter(Boolean)
.map((part) => encodeURIComponent(part));
export const getPluginRepositoryRawUrl = (repositoryPath: string): string =>
buildSafeUrl(
["raw", "githubusercontent", "com"],
[
...PLUGIN_REPOSITORY_PATH,
...pathParts(PLUGIN_REPOSITORY_REF),
...pathParts(repositoryPath),
],
);
export const getPluginRepositoryBlobUrl = (repositoryPath: string): string =>
buildSafeUrl(
["github", "com"],
[
...PLUGIN_REPOSITORY_PATH,
"blob",
...pathParts(PLUGIN_REPOSITORY_REF),
...pathParts(repositoryPath),
],
);
// Helper to enforce type structure in the registry
const defineUrl = (url: string, purpose: string) => ({ url, purpose });
@@ -92,22 +51,7 @@ const defineUrl = (url: string, purpose: string) => ({ url, purpose });
export const URL_REGISTRY = {
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON:
defineUrl(
getPluginRepositoryRawUrl("ea-scripts/directory-info.json"),
UrlPurpose.APP_LOGIC,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_SCRIPT_STORE_JSON:
defineUrl(
getPluginRepositoryRawUrl("ea-scripts/script-store.json"),
UrlPurpose.APP_LOGIC,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPTING_MD:
defineUrl(
getPluginRepositoryBlobUrl("docs/ea-scripting.md"),
UrlPurpose.DOCS,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_IMAGE_BANNER_AUTOMATE_ANYTHING_PNG:
defineUrl(
getPluginRepositoryRawUrl("images/banner-automate-anything.png"),
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/directory-info.json",
UrlPurpose.APP_LOGIC,
),
API_GITHUB_COM_REPOS_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES: defineUrl(
@@ -329,6 +273,11 @@ 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(
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/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,12 +2,6 @@ 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";
+57 -9
View File
@@ -25,6 +25,7 @@ import {
FRONTMATTER_KEYS,
FRONTMATTER,
JSON_parse,
SCRIPT_INSTALL_CODEBLOCK,
EXPORT_TYPES,
EXPORT_IMG_ICON_NAME,
EXPORT_IMG_ICON,
@@ -103,6 +104,8 @@ 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";
@@ -615,6 +618,14 @@ 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 {
@@ -721,6 +732,48 @@ 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
*/
@@ -1174,11 +1227,7 @@ export default class ExcalidrawPlugin extends Plugin {
return file.path;
}
public async setMarkdownView(
leaf: WorkspaceLeaf,
eState?: ViewStateResult,
active?: boolean,
) {
public async setMarkdownView(leaf: WorkspaceLeaf, eState?: ViewStateResult) {
const state = leaf.view.getState();
//Note v2.0.19: I have absolutely no idea why I thought this is necessary. Removing this.
@@ -1193,7 +1242,6 @@ export default class ExcalidrawPlugin extends Plugin {
type: "markdown",
state,
popstate: true,
...(active === undefined ? {} : { active }),
} as ViewState,
eState ? eState : { focus: true },
);
@@ -1452,14 +1500,14 @@ export default class ExcalidrawPlugin extends Plugin {
* @param inputEl The text input element to attach the suggester to.
* @param widthWrapper Optional HTML element to wrap the width of suggester element.
* @param containerEl Optional container element used as collision boundary.
* @param suppressPlaceholder Whether to suppress the placeholder text. Defaults to true.
* @param surpessPlaceholder Whether to suppress the placeholder text. Defaults to true.
* @returns A KeyBlocker instance for managing keyboard input.
*/
public attachInlineLinkSuggester(
inputEl: HTMLInputElement | HTMLTextAreaElement,
widthWrapper?: HTMLElement,
containerEl?: HTMLDivElement,
suppressPlaceholder: boolean = true,
surpessPlaceholder: boolean = true,
): KeyBlocker {
const getSourcePath = () => {
this.ea.setView();
@@ -1471,7 +1519,7 @@ export default class ExcalidrawPlugin extends Plugin {
inputEl,
getSourcePath,
widthWrapper,
suppressPlaceholder,
surpessPlaceholder,
containerEl,
);
}
+9 -2
View File
@@ -12,6 +12,7 @@ import {
View,
} from "obsidian";
import {
VIEW_TYPE_EXCALIDRAW,
ICON_NAME,
IMAGE_TYPES,
DEVICE,
@@ -2507,14 +2508,20 @@ export class CommandManager {
const excalidrawView =
this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (excalidrawView) {
void this.plugin.ea.toggleViewMode(excalidrawView);
void excalidrawView.openAsMarkdown();
return;
}
const markdownView =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView && fileIsExcalidraw) {
void this.plugin.ea.toggleViewMode(markdownView);
void (async () => {
await markdownView.save();
const activeLeaf = markdownView.leaf;
this.plugin.excalidrawFileModes[activeLeaf.id || activeFile.path] =
VIEW_TYPE_EXCALIDRAW;
await setExcalidrawView(activeLeaf);
})();
}
},
});
+3 -36
View File
@@ -1252,24 +1252,6 @@ const tmpObsidianWYSIWYG = async (
return;
}
//This internal-embed's src may point to a completely different file than the
//Excalidraw file we are currently rendering (e.g. a plain image embedded in the
//markdown side of a hybrid note). Resolve the actual link target and only take
//over rendering when it is genuinely an Excalidraw drawing; otherwise leave the
//embed alone so Obsidian's native renderer can display it.
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2292
const embedSrc = internalEmbedDiv.getAttribute("src")?.split("#")[0];
const embedTargetFile = embedSrc
? metadataCache.getFirstLinkpathDest(embedSrc, ctx.sourcePath)
: null;
if (
!embedTargetFile ||
!(embedTargetFile instanceof TFile) ||
!plugin.isExcalidrawFile(embedTargetFile)
) {
return;
}
el.empty();
if (internalEmbedDiv.hasAttribute("ready")) {
@@ -1284,7 +1266,7 @@ const tmpObsidianWYSIWYG = async (
return;
}
const imgDiv = await processInternalEmbed(internalEmbedDiv, embedTargetFile);
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
if (!imgDiv) {
return;
}
@@ -1357,13 +1339,8 @@ export const markdownPostProcessor = async (
return;
}
await plugin.awaitSettings();
//Obsidian's Export to PDF renders the document in its own window (main window or a
//popout), not necessarily mainDocument, so the print marker must be looked up on the
//document this section actually belongs to rather than always on the main window.
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2292
const printOwnerDocument = el.ownerDocument ?? mainDocument;
const isPrinting = Boolean(
printOwnerDocument.body.querySelectorAll("body > .print").length > 0,
mainDocument.body.querySelectorAll("body > .print").length > 0,
);
//firstElementChild: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1956
const isFrontmatter =
@@ -1396,17 +1373,7 @@ export const markdownPostProcessor = async (
!plugin.settings.renderImageInHoverPreviewForMDNotes;
const embeddedItems = el.querySelectorAll(".internal-embed");
//tmpObsidianWYSIWYG only knows how to handle the frontmatter/area-ref section that
//renders this drawing's own preview. When this section contains real embeds of its
//own (e.g. a plain image embedded in the markdown side of a hybrid note), it must be
//routed to processReadingMode below instead, exactly like the non-print case - otherwise
//tmpObsidianWYSIWYG empties and discards the section without rendering anything back.
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2292
if (
isPrinting &&
plugin.settings.renderImageInMarkdownToPDF &&
embeddedItems.length === 0
) {
if (isPrinting && plugin.settings.renderImageInMarkdownToPDF) {
await tmpObsidianWYSIWYG(
el,
ctx,
@@ -16,6 +16,7 @@ export const createObsidianExcalidrawHostAdapter = (
): ExcalidrawLib.ObsidianExcalidrawHostAdapter => ({
protocolVersion,
isDoubleTapEraserEnabled: () => plugin.settings.penModeDoubleTapEraser,
isRightClickPanEnabled: () => plugin.settings.panWithRightMouseButton,
getZoomToFitMaxLevel: () => plugin.settings.zoomToFitMaxLevel,
isPenModeCrosshairVisible: () => plugin.settings.penModeCrosshairVisible,
isSingleFingerPanningEnabled: () =>
+10
View File
@@ -3001,6 +3001,16 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
private getZoomAndPanSpecs(): SettingSpec[] {
return [
{
name: t("PAN_WITH_RIGHT_MOUSE_BUTTON_NAME"),
desc: fragWithHTML(t("PAN_WITH_RIGHT_MOUSE_BUTTON_DESC")),
aliases: ["right click pan", "mouse pan"],
control: {
type: "toggle",
key: "panWithRightMouseButton",
reload: true,
},
},
{
name: t("DEFAULT_PINCHZOOM_NAME"),
desc: fragWithHTML(t("DEFAULT_PINCHZOOM_DESC")),
+2
View File
@@ -105,6 +105,7 @@ export interface ExcalidrawSettings {
penModeDoubleTapEraser: boolean;
penModeSingleFingerPanning: boolean;
penModeCrosshairVisible: boolean;
panWithRightMouseButton: boolean; //mfuria #329
renderImageInMarkdownReadingMode: boolean;
renderImageInHoverPreviewForMDNotes: boolean;
renderImageInMarkdownToPDF: boolean;
@@ -552,6 +553,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
penModeDoubleTapEraser: true,
penModeSingleFingerPanning: true,
penModeCrosshairVisible: true,
panWithRightMouseButton: false, //mfuria #329
renderImageInMarkdownReadingMode: false,
renderImageInHoverPreviewForMDNotes: false,
renderImageInMarkdownToPDF: false,
+11 -63
View File
@@ -45,6 +45,11 @@ 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",
@@ -868,14 +873,16 @@ export default {
ZOOM_AND_PAN_HEAD: "Zoom and Pan",
ZOOM_AND_PAN_DESC:
"Configure mouse, touch, opening, resizing, and zoom-range behavior.",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Right-click drag to pan",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"Right-click and drag to pan the canvas (Miro-style). Press 'm' to open the context menu.",
DEFAULT_PINCHZOOM_NAME: "Allow pinch zoom in pen mode",
DEFAULT_PINCHZOOM_DESC:
"Pinch zoom in pen mode when using the freedraw tool is disabled by default to prevent unwanted accidental zooming with your palm.<br>" +
"<b><u>Toggle ON:</u></b> Enable pinch zoom in pen mode<br><b><u>Toggle OFF:</u></b>Disable pinch zoom in pen mode",
DEFAULT_WHEELZOOM_NAME: "Invert the drawing's wheel zoom preference",
DEFAULT_WHEELZOOM_DESC:
"Applies to all drawings and inverts the drawing's <b>Input device</b> preference (whether the mouse wheel zooms or scrolls). The drawing preference applies only to the current drawing and can be saved in a template.",
DEFAULT_WHEELZOOM_NAME: "Mouse wheel to zoom by default",
DEFAULT_WHEELZOOM_DESC: `<b><u>Toggle ON:</u></b> Mouse wheel to zoom; ${labelCTRL()} + mouse wheel to scroll</br><b><u>Toggle OFF:</u></b>${labelCTRL()} + mouse wheel to zoom; Mouse wheel to scroll`,
ZOOM_TO_FIT_NAME: "Zoom to fit on view resize",
ZOOM_TO_FIT_DESC:
@@ -1515,65 +1522,6 @@ export default {
"Script execution error. Please find error message on the developer console.",
//ScriptInstallPrompt.ts
SCRIPT_INSTALLED_NOTICE: "Installed",
SCRIPT_INSTALL_ERROR_NOTICE: "Error installing script",
SCRIPT_STORE_TITLE: "Community scripts",
SCRIPT_STORE_LOADING: "Loading community scripts...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "Master Excalidraw and Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "Buy me a coffee",
SCRIPT_STORE_COFFEE_DESC: "Support continued Excalidraw development",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "Automate anything with Excalidraw scripts",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION:
"Create your own Excalidraw scripts. Click here to learn more.",
SCRIPT_STORE_UPDATES_TITLE: "Updates available",
SCRIPT_STORE_UPDATES_DESC:
"Update installed community scripts without hunting through the catalog.",
SCRIPT_STORE_UPDATE_ALL: "Update all",
SCRIPT_STORE_UPDATING: "Updating...",
SCRIPT_STORE_UPDATE_ALL_DONE: "All community scripts are up to date.",
SCRIPT_STORE_UPDATE_ALL_PARTIAL:
"Some scripts could not be updated. Failed:",
SCRIPT_STORE_BROWSE_TITLE: "Browse scripts",
SCRIPT_STORE_BROWSE_DESC: "Search by name, author, description, or category.",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "Search community scripts",
SCRIPT_STORE_CATEGORY_LABEL: "Script category",
SCRIPT_STORE_ALL_CATEGORIES: "All categories",
SCRIPT_STORE_ALL_SCRIPTS: "All",
SCRIPT_STORE_INSTALLED_SCRIPTS: "Installed",
SCRIPT_STORE_RESULTS: "scripts",
SCRIPT_STORE_NO_RESULTS: "No scripts found",
SCRIPT_STORE_NO_RESULTS_DESC: "Try a different search or category.",
SCRIPT_STORE_DETAILS: "Script details",
SCRIPT_STORE_FEATURED: "Featured",
SCRIPT_STORE_BY: "By",
SCRIPT_STORE_UPDATE_BADGE: "Update",
SCRIPT_STORE_INSTALLED_BADGE: "Installed",
SCRIPT_STORE_CHECK_FAILED: "Check failed",
SCRIPT_STORE_INSTALL: "Install",
SCRIPT_STORE_UPDATE: "Update",
SCRIPT_STORE_REINSTALL: "Reinstall",
SCRIPT_STORE_BACK: "Back to scripts",
SCRIPT_STORE_VIEW_SOURCE: "View source",
SCRIPT_STORE_LOCAL_TITLE: "Installed script",
SCRIPT_STORE_MULTIPLE_COPIES:
"Multiple managed copies found. Update checks use the first copy below. You can open, move, or uninstall each copy separately.",
SCRIPT_STORE_PRIMARY_COPY: "Used for update checks",
SCRIPT_STORE_ADDITIONAL_COPY: "Additional copy",
SCRIPT_STORE_LOCAL_FILE: "Local file",
SCRIPT_STORE_OPEN_LOCAL: "Open local file",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "Could not open the local script file.",
SCRIPT_STORE_JS_OPEN_NOTE:
"JavaScript files are not editable in Obsidian by default. If no plugin provides a .js editor, opening this file may hand it off to an external app.",
SCRIPT_STORE_UNINSTALL: "Uninstall",
SCRIPT_STORE_UNINSTALLED: "Uninstalled",
SCRIPT_STORE_UNINSTALL_FAILED: "Could not uninstall",
SCRIPT_STORE_GROUP_LABEL: "Script group",
SCRIPT_STORE_GROUP_ROOT: "No group (Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "New group name",
SCRIPT_STORE_MOVE_TO_GROUP: "Move",
SCRIPT_STORE_MOVED_TO_GROUP: "Moved script",
SCRIPT_STORE_MOVE_FAILED: "Could not move script",
SCRIPT_INSTALL_PROMPT_FETCH_ERROR:
"Error opening the Excalidraw Script Store page. " +
"Please double check that you can access the website. " +
@@ -1740,7 +1688,7 @@ export default {
//Utils.ts
UPDATE_AVAILABLE: `A newer version of Excalidraw is available in Community Plugins.\n\nYou are using ${PLUGIN_VERSION}.\nThe latest is`,
SCRIPT_UPDATES_AVAILABLE: `Script updates available - check the script store.\n\n${DEVICE.isDesktop ? `This message is available in console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}Only community scripts stored under the Downloaded folder are checked for updates. Copies elsewhere in your script folder are ignored.`,
SCRIPT_UPDATES_AVAILABLE: `Script updates available - check the script store.\n\n${DEVICE.isDesktop ? `This message is available in console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}If you have organized scripts into subfolders under the script store folder and have multiple copies of the same script, you may need to clean up unused versions to clear this alert. For private copies of scripts that should not be updated, store them outside the script store folder.`,
ERROR_PNG_TOO_LARGE:
"Error exporting PNG - PNG too large, try a smaller resolution",
+13 -60
View File
@@ -44,6 +44,12 @@ 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",
@@ -828,14 +834,17 @@ export default {
ZOOM_AND_PAN_HEAD: "Zoom y panorámica",
ZOOM_AND_PAN_DESC:
"Configura el comportamiento del ratón, el tacto, la apertura, el cambio de tamaño y el intervalo de zoom.",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME:
"Desplazar el lienzo con el botón derecho del mouse (abrir menú con 'm')",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"Cuando está habilitado, puedes desplazar el lienzo haciendo clic derecho y arrastrando. El menú contextual se abrirá con la tecla 'm', a menos que estés editando texto.",
DEFAULT_PINCHZOOM_NAME: "Permitir zoom con pellizco en modo lápiz",
DEFAULT_PINCHZOOM_DESC:
"El zoom con pellizco en modo lápiz, al usar la herramienta de dibujo a mano alzada, está deshabilitado por defecto para evitar zooms accidentales no deseados con la palma de la mano.<br>" +
"<b><u>Activado:</u></b> Habilita el zoom con pellizco en modo lápiz <br><b><u>Desactivado:</u></b>Deshabilita el zoom con pellizco en modo lápiz",
DEFAULT_WHEELZOOM_NAME: "Invertir la preferencia de zoom con la rueda",
DEFAULT_WHEELZOOM_DESC:
"Se aplica a todos los dibujos e invierte la preferencia de <b>Dispositivo de entrada</b> del dibujo (si la rueda del ratón hace zoom o desplaza). La preferencia del dibujo solo se aplica al dibujo actual y se puede guardar en una plantilla.",
DEFAULT_WHEELZOOM_NAME: "Rueda del mouse para zoom por defecto",
DEFAULT_WHEELZOOM_DESC: `<b><u>Activado:</u></b> Rueda del mouse para zoom; ${labelCTRL()} + rueda del mouse para desplazarse</br><b><u>Desactivado:</u></b>${labelCTRL()} + rueda del mouse para zoom; Rueda del mouse para desplazarse`,
ZOOM_TO_FIT_NAME: "Zoom para ajustar al redimensionar la vista",
ZOOM_TO_FIT_DESC:
@@ -1644,7 +1653,7 @@ export default {
//Utils.ts
UPDATE_AVAILABLE: `Hay una versión más nueva de Excalidraw disponible en los Complementos de la Comunidad.\n\nEstás usando la versión ${PLUGIN_VERSION}.\nLa última versión es `,
SCRIPT_UPDATES_AVAILABLE: `Hay actualizaciones de scripts disponibles; revisa la tienda de scripts.\n\n${DEVICE.isDesktop ? `Este mensaje está disponible en console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}Solo se comprueban las actualizaciones de los scripts de la comunidad guardados bajo la carpeta Downloaded. Las copias situadas en otros lugares de la carpeta de scripts se ignoran.`,
SCRIPT_UPDATES_AVAILABLE: `Hay actualizaciones de scripts disponibles; revisa la tienda de scripts.\n\n${DEVICE.isDesktop ? `Este mensaje está disponible en console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}Si has organizado los scripts en subcarpetas dentro de la carpeta de la tienda de scripts y tienes varias copias del mismo script, es posible que necesites limpiar las versiones no utilizadas para borrar esta alerta. Para copias privadas de scripts que no deben actualizarse, guárdalas fuera de la carpeta de la tienda de scripts.`,
ERROR_PNG_TOO_LARGE:
"Error al exportar PNG: El archivo PNG es demasiado grande, intenta una resolución más pequeña.",
@@ -1861,60 +1870,4 @@ Si quieres ver lo que ya es posible hoy, aquí tienes una presentación de las f
//carveout.ts
NEW_DRAWING_TIMEOUT:
"Archivo no encontrado. El nuevo dibujo de Excalidraw está tardando demasiado en crearse. Inténtelo de nuevo.",
SCRIPT_INSTALLED_NOTICE: "Instalado",
SCRIPT_INSTALL_ERROR_NOTICE: "Error al instalar el script",
SCRIPT_STORE_TITLE: "Scripts de la comunidad",
SCRIPT_STORE_LOADING: "Cargando scripts de la comunidad...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "Domina Excalidraw y Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "Invítame a un café",
SCRIPT_STORE_COFFEE_DESC: "Apoya el desarrollo continuo de Excalidraw",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "Automatiza cualquier cosa con scripts de Excalidraw",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION: "Crea tus propios scripts de Excalidraw. Haz clic aquí para saber más.",
SCRIPT_STORE_UPDATES_TITLE: "Actualizaciones disponibles",
SCRIPT_STORE_UPDATES_DESC: "Actualiza los scripts instalados sin buscarlos por todo el catálogo.",
SCRIPT_STORE_UPDATE_ALL: "Actualizar todo",
SCRIPT_STORE_UPDATING: "Actualizando...",
SCRIPT_STORE_UPDATE_ALL_DONE: "Todos los scripts de la comunidad están actualizados.",
SCRIPT_STORE_UPDATE_ALL_PARTIAL: "No se pudieron actualizar algunos scripts. Fallidos:",
SCRIPT_STORE_BROWSE_TITLE: "Explorar scripts",
SCRIPT_STORE_BROWSE_DESC: "Busca por nombre, autor, descripción o categoría.",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "Buscar scripts de la comunidad",
SCRIPT_STORE_CATEGORY_LABEL: "Categoría del script",
SCRIPT_STORE_ALL_CATEGORIES: "Todas las categorías",
SCRIPT_STORE_ALL_SCRIPTS: "Todos",
SCRIPT_STORE_INSTALLED_SCRIPTS: "Instalados",
SCRIPT_STORE_RESULTS: "scripts",
SCRIPT_STORE_NO_RESULTS: "No se encontraron scripts",
SCRIPT_STORE_NO_RESULTS_DESC: "Prueba otra búsqueda o categoría.",
SCRIPT_STORE_DETAILS: "Detalles del script",
SCRIPT_STORE_FEATURED: "Destacado",
SCRIPT_STORE_BY: "Por",
SCRIPT_STORE_UPDATE_BADGE: "Actualizar",
SCRIPT_STORE_INSTALLED_BADGE: "Instalado",
SCRIPT_STORE_CHECK_FAILED: "Falló la comprobación",
SCRIPT_STORE_INSTALL: "Instalar",
SCRIPT_STORE_UPDATE: "Actualizar",
SCRIPT_STORE_REINSTALL: "Reinstalar",
SCRIPT_STORE_BACK: "Volver a scripts",
SCRIPT_STORE_VIEW_SOURCE: "Ver código fuente",
SCRIPT_STORE_LOCAL_TITLE: "Script instalado",
SCRIPT_STORE_MULTIPLE_COPIES:
"Se encontraron varias copias administradas. Las comprobaciones de actualización usan la primera copia. Puedes abrir, mover o desinstalar cada copia por separado.",
SCRIPT_STORE_PRIMARY_COPY: "Usada para comprobar actualizaciones",
SCRIPT_STORE_ADDITIONAL_COPY: "Copia adicional",
SCRIPT_STORE_LOCAL_FILE: "Archivo local",
SCRIPT_STORE_OPEN_LOCAL: "Abrir archivo local",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "No se pudo abrir el archivo local del script.",
SCRIPT_STORE_JS_OPEN_NOTE:
"Obsidian no permite editar archivos JavaScript de forma predeterminada. Si ningún plugin proporciona un editor .js, el archivo puede abrirse en una aplicación externa.",
SCRIPT_STORE_UNINSTALL: "Desinstalar",
SCRIPT_STORE_UNINSTALLED: "Desinstalado",
SCRIPT_STORE_UNINSTALL_FAILED: "No se pudo desinstalar",
SCRIPT_STORE_GROUP_LABEL: "Grupo de scripts",
SCRIPT_STORE_GROUP_ROOT: "Sin grupo (Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "Nombre del nuevo grupo",
SCRIPT_STORE_MOVE_TO_GROUP: "Mover",
SCRIPT_STORE_MOVED_TO_GROUP: "Script movido",
SCRIPT_STORE_MOVE_FAILED: "No se pudo mover el script",
};
+13 -60
View File
@@ -38,6 +38,13 @@ 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:
@@ -754,14 +761,17 @@ export default {
ZOOM_AND_PAN_HEAD: "Масштаб и панорамирование",
ZOOM_AND_PAN_DESC:
"Настройте поведение мыши, сенсорного ввода, открытия, изменения размера и диапазона масштаба.",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME:
"Перемещение холста правой кнопкой мыши (открыть меню с 'm')",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"Когда этот параметр включен, вы можете перемещать холст, нажимая правую кнопку мыши и перетаскивая. Контекстное меню откроется с помощью клавиши 'm', если только вы не редактируете текст.",
DEFAULT_PINCHZOOM_NAME: "Разрешить масштабирование в режиме пера",
DEFAULT_PINCHZOOM_DESC:
"По умолчанию зуммирование в режиме пера при использовании инструмента «Свободное рисование» отключено, чтобы предотвратить нежелательное случайное масштабирование с помощью ладони.<br>" +
"<b><u>Переключатель ВКЛ:</u></b>Включение щипкового масштабирования в режиме пера<br><b><u>Переключатель ВЫКЛ:</u></b>Выключение щипкового масштабирования в режиме пера",
DEFAULT_WHEELZOOM_NAME: "Инвертировать настройку масштабирования колёсиком",
DEFAULT_WHEELZOOM_DESC:
"Применяется ко всем рисункам и инвертирует настройку <b>Устройство ввода</b> в рисунке (масштабирование или прокрутка колёсиком мыши). Настройка рисунка действует только для текущего рисунка и может быть сохранена в шаблоне.",
DEFAULT_WHEELZOOM_NAME: "Колесо мыши для масштабирования по умолчанию",
DEFAULT_WHEELZOOM_DESC: `<b><u>Переключатель ВКЛ:</u></b> Колесо мыши для масштабирования; ${labelCTRL()} + Колесо мыши для прокрутки</br><b><u>Переключатель ВЫКЛ:</u></b>${labelCTRL()} + Колесико мыши для масштабирования; Колесико мыши для прокрутки`,
ZOOM_TO_FIT_NAME: "Изменение масштаба при изменении размера просмотра",
ZOOM_TO_FIT_DESC:
@@ -1502,61 +1512,4 @@ export default {
//carveout.ts
NEW_DRAWING_TIMEOUT:
"Файл не найден. Создание нового рисунка Excalidraw занимает слишком много времени. Пожалуйста, попробуйте снова.",
SCRIPT_INSTALLED_NOTICE: "Установлено",
SCRIPT_INSTALL_ERROR_NOTICE: "Ошибка установки скрипта",
SCRIPT_STORE_TITLE: "Скрипты сообщества",
SCRIPT_STORE_LOADING: "Загрузка скриптов сообщества...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "Освойте Excalidraw и Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "Купить мне кофе",
SCRIPT_STORE_COFFEE_DESC: "Поддержать дальнейшую разработку Excalidraw",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "Автоматизируйте что угодно с помощью скриптов Excalidraw",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION: "Создавайте собственные скрипты Excalidraw. Нажмите, чтобы узнать больше.",
SCRIPT_STORE_UPDATES_TITLE: "Доступны обновления",
SCRIPT_STORE_UPDATES_DESC: "Обновляйте установленные скрипты без поиска по каталогу.",
SCRIPT_STORE_UPDATE_ALL: "Обновить все",
SCRIPT_STORE_UPDATING: "Обновление...",
SCRIPT_STORE_UPDATE_ALL_DONE: "Все скрипты сообщества обновлены.",
SCRIPT_STORE_UPDATE_ALL_PARTIAL: "Некоторые скрипты не удалось обновить. Ошибок:",
SCRIPT_STORE_BROWSE_TITLE: "Обзор скриптов",
SCRIPT_STORE_BROWSE_DESC: "Ищите по названию, автору, описанию или категории.",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "Поиск скриптов сообщества",
SCRIPT_STORE_CATEGORY_LABEL: "Категория скрипта",
SCRIPT_STORE_ALL_CATEGORIES: "Все категории",
SCRIPT_STORE_ALL_SCRIPTS: "Все",
SCRIPT_STORE_INSTALLED_SCRIPTS: "Установленные",
SCRIPT_STORE_RESULTS: "скриптов",
SCRIPT_STORE_NO_RESULTS: "Скрипты не найдены",
SCRIPT_STORE_NO_RESULTS_DESC: "Попробуйте другой запрос или категорию.",
SCRIPT_STORE_DETAILS: "Сведения о скрипте",
SCRIPT_STORE_FEATURED: "Избранное",
SCRIPT_STORE_BY: "Автор",
SCRIPT_STORE_UPDATE_BADGE: "Обновление",
SCRIPT_STORE_INSTALLED_BADGE: "Установлен",
SCRIPT_STORE_CHECK_FAILED: "Проверка не удалась",
SCRIPT_STORE_INSTALL: "Установить",
SCRIPT_STORE_UPDATE: "Обновить",
SCRIPT_STORE_REINSTALL: "Переустановить",
SCRIPT_STORE_BACK: "Назад к скриптам",
SCRIPT_STORE_VIEW_SOURCE: "Открыть исходник",
SCRIPT_STORE_LOCAL_TITLE: "Установленный скрипт",
SCRIPT_STORE_MULTIPLE_COPIES:
"Найдено несколько управляемых копий. Для проверки обновлений используется первая копия. Каждую копию можно открыть, переместить или удалить отдельно.",
SCRIPT_STORE_PRIMARY_COPY: "Используется для проверки обновлений",
SCRIPT_STORE_ADDITIONAL_COPY: "Дополнительная копия",
SCRIPT_STORE_LOCAL_FILE: "Локальный файл",
SCRIPT_STORE_OPEN_LOCAL: "Открыть локальный файл",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "Не удалось открыть локальный файл скрипта.",
SCRIPT_STORE_JS_OPEN_NOTE:
"По умолчанию Obsidian не редактирует JavaScript-файлы. Если ни один плагин не предоставляет редактор .js, файл может открыться во внешнем приложении.",
SCRIPT_STORE_UNINSTALL: "Удалить",
SCRIPT_STORE_UNINSTALLED: "Удалено",
SCRIPT_STORE_UNINSTALL_FAILED: "Не удалось удалить",
SCRIPT_STORE_GROUP_LABEL: "Группа скриптов",
SCRIPT_STORE_GROUP_ROOT: "Без группы (Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "Имя новой группы",
SCRIPT_STORE_MOVE_TO_GROUP: "Переместить",
SCRIPT_STORE_MOVED_TO_GROUP: "Скрипт перемещён",
SCRIPT_STORE_MOVE_FAILED: "Не удалось переместить скрипт",
SCRIPT_UPDATES_AVAILABLE: `Доступны обновления скриптов — проверьте магазин скриптов.\n\n${DEVICE.isDesktop ? `Это сообщение доступно в console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}Проверяются только скрипты сообщества, находящиеся в папке Downloaded. Копии в других местах папки скриптов игнорируются.`,
};
+11 -60
View File
@@ -37,6 +37,11 @@ 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",
@@ -790,14 +795,16 @@ export default {
ZOOM_AND_PAN_HEAD: "缩放和平移",
ZOOM_AND_PAN_DESC:
"配置鼠标、触控、打开、调整大小和缩放范围行为。",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右键拖动平移",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"右键点击并拖动来平移绘图(和在线白板工具 Miro 类似)。按 'm' 键打开上下文菜单。",
DEFAULT_PINCHZOOM_NAME: "允许在触控笔模式下进行双指缩放",
DEFAULT_PINCHZOOM_DESC:
"在触控笔模式下使用自由画笔工具时,双指缩放可能造成干扰。<br>" +
"<b>开启:</b>允许双指缩放。<b>关闭: </b>禁止双指缩放。",
DEFAULT_WHEELZOOM_NAME: "反转绘图的滚轮缩放设置",
DEFAULT_WHEELZOOM_DESC:
"应用于所有绘图,并反转绘图中的<b>输入设备</b>设置(鼠标滚轮用于缩放还是滚动)。绘图中的设置仅适用于当前绘图,也可以保存到模板中。",
DEFAULT_WHEELZOOM_NAME: "鼠标滚轮缩放",
DEFAULT_WHEELZOOM_DESC: `<b>开启:</b>鼠标滚轮为缩放绘图,${labelCTRL()}+鼠标滚轮为滚动绘图。<br><b>关闭:</b>鼠标滚轮为滚动绘图,${labelCTRL()}+鼠标滚轮为缩放绘图。`,
ZOOM_TO_FIT_NAME: "调整面板尺寸后自动缩放",
ZOOM_TO_FIT_DESC:
@@ -1572,7 +1579,7 @@ export default {
//Utils.ts
UPDATE_AVAILABLE: `Excalidraw 的新版本已在社区插件中可用。\n\n您正在使用 ${PLUGIN_VERSION}。\n最新版本是`,
SCRIPT_UPDATES_AVAILABLE: `脚本更新可用 - 请检查脚本存储。\n\n${DEVICE.isDesktop ? `此消息可在控制台日志中查看 (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}只检查 Downloaded 文件夹下的社区脚本更新。脚本文件夹中其他位置的副本会被忽略。`,
SCRIPT_UPDATES_AVAILABLE: `脚本更新可用 - 请检查脚本存储。\n\n${DEVICE.isDesktop ? `此消息可在控制台日志中查看 (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}如果您已将脚本组织到脚本存储文件夹下的子文件夹中,并且存在同一脚本的多个副本,可能需要清理未使用的版本以消除此警报。对于无需更新的私人脚本副本,请将它们存储在脚本存储文件夹之外。`,
ERROR_PNG_TOO_LARGE: "导出 PNG 时出错 - PNG 文件过大,请尝试较小的分辨率",
//modifierkeyHelper.ts
@@ -1815,60 +1822,4 @@ Obsidian 的 Excalidraw 插件远不只是画图工具。由于它与 Obsidian
//carveout.ts
NEW_DRAWING_TIMEOUT: "未找到文件。新建 Excalidraw 绘图耗时过长。请重试。",
SCRIPT_INSTALLED_NOTICE: "已安装",
SCRIPT_INSTALL_ERROR_NOTICE: "脚本安装失败",
SCRIPT_STORE_TITLE: "社区脚本",
SCRIPT_STORE_LOADING: "正在加载社区脚本...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "掌握 Excalidraw 与 Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "请我喝杯咖啡",
SCRIPT_STORE_COFFEE_DESC: "支持 Excalidraw 持续开发",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "用 Excalidraw 脚本自动化任何事情",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION: "创建你自己的 Excalidraw 脚本。点击这里了解更多。",
SCRIPT_STORE_UPDATES_TITLE: "有可用更新",
SCRIPT_STORE_UPDATES_DESC: "无需在目录中逐个查找,即可更新已安装的社区脚本。",
SCRIPT_STORE_UPDATE_ALL: "全部更新",
SCRIPT_STORE_UPDATING: "正在更新...",
SCRIPT_STORE_UPDATE_ALL_DONE: "所有社区脚本均已是最新版本。",
SCRIPT_STORE_UPDATE_ALL_PARTIAL: "部分脚本无法更新。失败数量:",
SCRIPT_STORE_BROWSE_TITLE: "浏览脚本",
SCRIPT_STORE_BROWSE_DESC: "可按名称、作者、描述或分类搜索。",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "搜索社区脚本",
SCRIPT_STORE_CATEGORY_LABEL: "脚本分类",
SCRIPT_STORE_ALL_CATEGORIES: "全部分类",
SCRIPT_STORE_ALL_SCRIPTS: "全部",
SCRIPT_STORE_INSTALLED_SCRIPTS: "已安装",
SCRIPT_STORE_RESULTS: "个脚本",
SCRIPT_STORE_NO_RESULTS: "未找到脚本",
SCRIPT_STORE_NO_RESULTS_DESC: "请尝试其他搜索词或分类。",
SCRIPT_STORE_DETAILS: "脚本详情",
SCRIPT_STORE_FEATURED: "精选",
SCRIPT_STORE_BY: "作者",
SCRIPT_STORE_UPDATE_BADGE: "更新",
SCRIPT_STORE_INSTALLED_BADGE: "已安装",
SCRIPT_STORE_CHECK_FAILED: "检查失败",
SCRIPT_STORE_INSTALL: "安装",
SCRIPT_STORE_UPDATE: "更新",
SCRIPT_STORE_REINSTALL: "重新安装",
SCRIPT_STORE_BACK: "返回脚本列表",
SCRIPT_STORE_VIEW_SOURCE: "查看源代码",
SCRIPT_STORE_LOCAL_TITLE: "已安装脚本",
SCRIPT_STORE_MULTIPLE_COPIES:
"发现多个受管理的副本。更新检查使用下面的第一个副本。你可以分别打开、移动或卸载每个副本。",
SCRIPT_STORE_PRIMARY_COPY: "用于更新检查",
SCRIPT_STORE_ADDITIONAL_COPY: "其他副本",
SCRIPT_STORE_LOCAL_FILE: "本地文件",
SCRIPT_STORE_OPEN_LOCAL: "打开本地文件",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "无法打开本地脚本文件。",
SCRIPT_STORE_JS_OPEN_NOTE:
"Obsidian 默认不支持编辑 JavaScript 文件。如果没有插件提供 .js 编辑器,打开文件时可能会交给外部应用。",
SCRIPT_STORE_UNINSTALL: "卸载",
SCRIPT_STORE_UNINSTALLED: "已卸载",
SCRIPT_STORE_UNINSTALL_FAILED: "无法卸载",
SCRIPT_STORE_GROUP_LABEL: "脚本分组",
SCRIPT_STORE_GROUP_ROOT: "不分组(Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "新分组名称",
SCRIPT_STORE_MOVE_TO_GROUP: "移动",
SCRIPT_STORE_MOVED_TO_GROUP: "脚本已移动",
SCRIPT_STORE_MOVE_FAILED: "无法移动脚本",
};
+11 -60
View File
@@ -37,6 +37,11 @@ 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",
@@ -790,14 +795,16 @@ export default {
ZOOM_AND_PAN_HEAD: "縮放和平移",
ZOOM_AND_PAN_DESC:
"設定滑鼠、觸控、開啟、調整大小和縮放範圍行為。",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右鍵拖動平移",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"右鍵點選並拖動來平移繪圖(和線上白板工具 Miro 類似)。按 'm' 鍵開啟上下文選單。",
DEFAULT_PINCHZOOM_NAME: "允許在觸控筆模式下進行雙指縮放",
DEFAULT_PINCHZOOM_DESC:
"在觸控筆模式下使用自由畫筆工具時,雙指縮放可能造成干擾。<br>" +
"<b>開啟:</b>允許雙指縮放。<b>關閉: </b>禁止雙指縮放。",
DEFAULT_WHEELZOOM_NAME: "反轉繪圖的滾輪縮放設定",
DEFAULT_WHEELZOOM_DESC:
"套用於所有繪圖,並反轉繪圖中的<b>輸入裝置</b>設定(滑鼠滾輪用於縮放還是捲動)。繪圖中的設定僅適用於目前繪圖,也可以儲存到範本中。",
DEFAULT_WHEELZOOM_NAME: "滑鼠滾輪縮放",
DEFAULT_WHEELZOOM_DESC: `<b>開啟:</b>滑鼠滾輪為縮放繪圖,${labelCTRL()}+滑鼠滾輪為滾動繪圖。<br><b>關閉:</b>滑鼠滾輪為滾動繪圖,${labelCTRL()}+滑鼠滾輪為縮放繪圖。`,
ZOOM_TO_FIT_NAME: "調整面板尺寸後自動縮放",
ZOOM_TO_FIT_DESC:
@@ -1572,7 +1579,7 @@ export default {
//Utils.ts
UPDATE_AVAILABLE: `Excalidraw 的新版本已在社群外掛中可用。\n\n您正在使用 ${PLUGIN_VERSION}。\n最新版本是`,
SCRIPT_UPDATES_AVAILABLE: `指令碼更新可用 - 請檢查指令碼儲存。\n\n${DEVICE.isDesktop ? `此訊息可在控制台日誌中檢視 (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}只檢查 Downloaded 資料夾下的社群指令碼更新。指令碼資料夾中其他位置的副本會被忽略。`,
SCRIPT_UPDATES_AVAILABLE: `指令碼更新可用 - 請檢查指令碼儲存。\n\n${DEVICE.isDesktop ? `此訊息可在控制台日誌中檢視 (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}如果您已將指令碼組織到指令碼儲存資料夾下的子資料夾中,並且存在同一指令碼的多個副本,可能需要清理未使用的版本以消除此警報。對於無需更新的私人指令碼副本,請將它們儲存在指令碼儲存資料夾之外。`,
ERROR_PNG_TOO_LARGE: "匯出 PNG 時出錯 - PNG 檔案過大,請嘗試較小的解析度",
//modifierkeyHelper.ts
@@ -1815,60 +1822,4 @@ Obsidian 的 Excalidraw 外掛遠不只是畫圖工具。由於它與 Obsidian
//carveout.ts
NEW_DRAWING_TIMEOUT: "找不到檔案。建立新的 Excalidraw 繪圖耗時過長。請重試。",
SCRIPT_INSTALLED_NOTICE: "已安裝",
SCRIPT_INSTALL_ERROR_NOTICE: "指令碼安裝失敗",
SCRIPT_STORE_TITLE: "社群指令碼",
SCRIPT_STORE_LOADING: "正在載入社群指令碼...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "掌握 Excalidraw 與 Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "請我喝杯咖啡",
SCRIPT_STORE_COFFEE_DESC: "支持 Excalidraw 持續開發",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "用 Excalidraw 指令碼自動化任何事情",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION: "建立你自己的 Excalidraw 指令碼。點擊這裡了解更多。",
SCRIPT_STORE_UPDATES_TITLE: "有可用更新",
SCRIPT_STORE_UPDATES_DESC: "不必逐一翻找目錄,就能更新已安裝的社群指令碼。",
SCRIPT_STORE_UPDATE_ALL: "全部更新",
SCRIPT_STORE_UPDATING: "正在更新...",
SCRIPT_STORE_UPDATE_ALL_DONE: "所有社群指令碼都已是最新版本。",
SCRIPT_STORE_UPDATE_ALL_PARTIAL: "部分指令碼無法更新。失敗數量:",
SCRIPT_STORE_BROWSE_TITLE: "瀏覽指令碼",
SCRIPT_STORE_BROWSE_DESC: "可依名稱、作者、描述或分類搜尋。",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "搜尋社群指令碼",
SCRIPT_STORE_CATEGORY_LABEL: "指令碼分類",
SCRIPT_STORE_ALL_CATEGORIES: "全部分類",
SCRIPT_STORE_ALL_SCRIPTS: "全部",
SCRIPT_STORE_INSTALLED_SCRIPTS: "已安裝",
SCRIPT_STORE_RESULTS: "個指令碼",
SCRIPT_STORE_NO_RESULTS: "找不到指令碼",
SCRIPT_STORE_NO_RESULTS_DESC: "請嘗試其他搜尋詞或分類。",
SCRIPT_STORE_DETAILS: "指令碼詳細資料",
SCRIPT_STORE_FEATURED: "精選",
SCRIPT_STORE_BY: "作者",
SCRIPT_STORE_UPDATE_BADGE: "更新",
SCRIPT_STORE_INSTALLED_BADGE: "已安裝",
SCRIPT_STORE_CHECK_FAILED: "檢查失敗",
SCRIPT_STORE_INSTALL: "安裝",
SCRIPT_STORE_UPDATE: "更新",
SCRIPT_STORE_REINSTALL: "重新安裝",
SCRIPT_STORE_BACK: "返回指令碼列表",
SCRIPT_STORE_VIEW_SOURCE: "檢視原始碼",
SCRIPT_STORE_LOCAL_TITLE: "已安裝指令碼",
SCRIPT_STORE_MULTIPLE_COPIES:
"找到多個受管理的副本。更新檢查使用下方第一個副本。你可以分別開啟、移動或解除安裝每個副本。",
SCRIPT_STORE_PRIMARY_COPY: "用於更新檢查",
SCRIPT_STORE_ADDITIONAL_COPY: "其他副本",
SCRIPT_STORE_LOCAL_FILE: "本機檔案",
SCRIPT_STORE_OPEN_LOCAL: "開啟本機檔案",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "無法開啟本機指令碼檔案。",
SCRIPT_STORE_JS_OPEN_NOTE:
"Obsidian 預設不支援編輯 JavaScript 檔案。如果沒有外掛提供 .js 編輯器,開啟檔案時可能會交給外部應用程式。",
SCRIPT_STORE_UNINSTALL: "解除安裝",
SCRIPT_STORE_UNINSTALLED: "已解除安裝",
SCRIPT_STORE_UNINSTALL_FAILED: "無法解除安裝",
SCRIPT_STORE_GROUP_LABEL: "指令碼群組",
SCRIPT_STORE_GROUP_ROOT: "不分組(Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "新群組名稱",
SCRIPT_STORE_MOVE_TO_GROUP: "移動",
SCRIPT_STORE_MOVED_TO_GROUP: "指令碼已移動",
SCRIPT_STORE_MOVE_FAILED: "無法移動指令碼",
};
+5 -40
View File
@@ -19,55 +19,21 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
`,
"2.28.0": `
## New
- The Community Script Store now has a searchable card-based library, a focused update section with **Update all**, and a compact top area for Excalidraw Mastery, support, and creating your own scripts. Script details now support reinstalling, opening local files in a new tab, uninstalling, and moving managed scripts between groups under the **Downloaded** folder. Update detection keeps the existing \`directory-info.json\` modified-time contract, ignores private copies outside **Downloaded**, and handles duplicate managed copies consistently. [#2944](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2944)
- Copied Markdown image SVGs now replace embedded base64 images and fonts with short placeholders, making them smaller and easier to share with AI agents when developing custom CSS.
## 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)
- \`.excalidraw\` drawings with embedded binary images now render those images when opened into an already-used Excalidraw tab. [#2929](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2929)
- Descriptions in settings no longer disappear when you revisit a settings page from search results. [#2935](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2935)
- Drawing persistence is now more reliable during rapid edits across multiple tabs, popout moves, and immediate closing. Backups and automatic exports now track the exact successfully saved revision. [#2933](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2933)
- Rapidly changing Markdown image appearance, selection, or image/embeddable conversion no longer leaves a rejected image-render promise in the console or lets a superseded render overwrite the newer element state.
- Fixed a bug where, with *"Render Excalidraw as Image in Obsidian PDF Export"* enabled, exporting a Hybrid Note (an Excalidraw drawing with your own Markdown content alongside it) to PDF could render blank sections wherever a regular image (or other non-Excalidraw) embed appeared on the Markdown side. [#2292](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2292), 🙏[bluechallenge](${URLs.GITHUB_COM}/bluechallenge) [#2936](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2936)
- 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.
## New in Excalidraw Automate
- 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;
\`\`\`
- Unbound arrows created with Excalidraw Automate's \`addArrow()\` no longer contain incomplete binding data that could cause an error when selected.
- Updated the [ea-script-template](${URLs.GITHUB_COM}/zsviczian/ea-script-template). Read [EA Script prompting with AI is magical](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}/t/10977)
## Fixed / Refactored
- Rich descriptions in searchable settings now remain visible when you revisit a settings page from search results. [#2935](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2935)
- Drawing persistence is now more reliable during rapid edits across multiple tabs, popout moves, and immediate closing. Backups and automatic exports now track the exact successfully saved revision. [#2933](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2933)
- Rapidly changing Markdown image appearance, selection, or image/embeddable conversion no longer leaves a rejected image-render promise in the console or lets a superseded render overwrite the newer element state.
`,
"2.27.3": `
## Fixed and updated
@@ -249,7 +215,6 @@ ${getYouTubeDiv("aqt5NJE2sJ8")}
- Fixed the "Customize the Embedded File Link" action. If you change the dimensions of the markdown image or the pdf page reference number, the image immediately updates in the scene. You can also use this feature to swap out images e.g. a png icon to an SVG icon. Default shortcut is CTRL+WIN+Click or CMD+Control+Click on the image element.
- LaTeX and Mermaid did not work on iOS. Released updated Excalidraw Extras and bumped the minimum required version to 0.0.15. [#2825](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2825)
- Malformed "Source" URL in ExcalidrawLib and Excalidraw Data json. [#2826]${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2826)
- Markdown-image editor did not function if Obsidian default for new tabs was set to preview mode.
## New in ExcalidrawAutomate
- Added \`onSceneChangeHook\` to allow scripts and sidepanel tabs to react to scene changes. The hook supports filtering by \`appStateKeys\` and checking for tab visibility to optimize performance.
+47 -917
View File
@@ -1,938 +1,68 @@
import {
Modal,
Notice,
normalizePath,
request,
setIcon,
} from "obsidian";
import { SCRIPT_INSTALL_FOLDER } from "../../constants/constants";
import {
getPluginRepositoryBlobUrl,
getPluginRepositoryRawUrl,
URLs,
} from "../../constants/safeUrls";
import { t } from "../../lang/helpers";
import type {
ScriptStoreCatalog,
ScriptStoreEntry,
ScriptStoreInstallState,
} from "../../types/scriptStoreTypes";
import { sanitizedFragment, setSanitizedHtml } from "../../utils/htmlUtils";
import {
getInstalledScriptFiles,
getInstalledScriptGroups,
getScriptInstallStates,
installScript,
moveInstalledScriptToGroup,
uninstallScript,
type ScriptLibraryPluginContext,
} from "../../utils/scriptLibraryUtils";
import { Component, MarkdownRenderer, Modal, Notice, request } from "obsidian";
import ExcalidrawPlugin from "../../core/main";
import { errorlog } from "../../utils/utils";
import { log } from "src/utils/debugHelper";
import { ContentSearcher } from "../components/ContentSearcher";
import { URLs } from "src/constants/safeUrls";
import { t } from "src/lang/helpers";
const CATALOG_URL =
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_SCRIPT_STORE_JSON;
const FEATURED_CATEGORY = "Editors Picks";
type StoreView = "all" | "installed";
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null;
const isUnknownArray = (value: unknown): value is unknown[] =>
Array.isArray(value);
const isStringArray = (value: unknown): value is string[] =>
isUnknownArray(value) &&
value.every((item: unknown) => typeof item === "string");
const isScriptStoreEntry = (value: unknown): value is ScriptStoreEntry =>
isRecord(value) &&
typeof value.name === "string" &&
typeof value.file === "string" &&
typeof value.installUrl === "string" &&
typeof value.iconUrl === "string" &&
typeof value.author === "string" &&
typeof value.authorUrl === "string" &&
typeof value.sourceUrl === "string" &&
typeof value.descriptionHtml === "string" &&
isStringArray(value.categories) &&
(value.featuredRank === undefined || typeof value.featuredRank === "number");
const isScriptStoreCategory = (
value: unknown,
): value is ScriptStoreCatalog["categories"][number] =>
isRecord(value) &&
typeof value.name === "string" &&
typeof value.description === "string";
const parseScriptStoreCatalog = (source: string): ScriptStoreCatalog => {
const parsed: unknown = JSON.parse(source) as unknown;
if (
!isRecord(parsed) ||
parsed.version !== 1 ||
!isUnknownArray(parsed.scripts) ||
!parsed.scripts.every(isScriptStoreEntry) ||
!isUnknownArray(parsed.categories) ||
!parsed.categories.every(isScriptStoreCategory)
) {
throw new Error("Unsupported script store catalog");
}
return {
version: parsed.version,
scripts: parsed.scripts,
categories: parsed.categories,
};
};
const getScriptInstallUrl = (entry: ScriptStoreEntry): string =>
getPluginRepositoryRawUrl(`ea-scripts/${entry.file}`);
const getScriptIconUrl = (entry: ScriptStoreEntry): string =>
getPluginRepositoryRawUrl(
`ea-scripts/${entry.file.replace(/\.(?:md|js)$/i, ".svg")}`,
);
const getScriptSourceUrl = (entry: ScriptStoreEntry): string =>
getPluginRepositoryBlobUrl(`ea-scripts/${entry.file}`);
const URL =
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD;
export class ScriptInstallPrompt extends Modal {
private contentDiv: HTMLDivElement;
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";
private renderComponent: Component;
constructor(private plugin: ScriptLibraryPluginContext) {
constructor(private plugin: ExcalidrawPlugin) {
super(plugin.app);
// this.titleEl.setText(t("INSTAL_MODAL_TITLE"));
}
onOpen(): void {
this.titleEl.setText(t("SCRIPT_STORE_TITLE"));
this.contentEl.classList.add(
"excalidraw-scriptengine-install",
"excalidraw-script-store",
);
this.containerEl.classList.add(
"excalidraw-scriptengine-install",
"excalidraw-script-store",
);
this.contentDiv = this.contentEl.createDiv({
cls: "excalidraw-script-store__content",
});
this.renderLoading();
void this.loadStore();
}
this.renderComponent = new Component();
this.renderComponent.load();
this.contentEl.classList.add("excalidraw-scriptengine-install");
this.contentDiv = this.contentEl.createDiv();
private renderLoading(): void {
this.contentDiv.replaceChildren();
const loading = this.contentDiv.createDiv({
cls: "excalidraw-script-store__loading",
});
const icon = loading.createSpan({
cls: "excalidraw-script-store__loading-icon",
});
setIcon(icon, "loader-circle");
loading.createSpan({ text: t("SCRIPT_STORE_LOADING") });
}
new ContentSearcher(this.contentDiv);
private async loadStore(): Promise<void> {
try {
const source = await request({ url: CATALOG_URL });
this.catalog = parseScriptStoreCatalog(source);
await this.refreshInstallStates();
this.renderStore();
} catch (error: unknown) {
errorlog({ where: "ScriptInstallPrompt.loadStore", error });
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
this.close();
}
}
private async refreshInstallStates(): Promise<void> {
if (!this.catalog) {
return;
}
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",
]),
);
}
private renderStore(): void {
if (!this.catalog) {
return;
}
this.contentDiv.replaceChildren();
this.renderSupportBar();
this.renderScriptingBanner();
this.renderUpdates();
this.renderBrowseControls();
this.renderScriptGrid();
}
private renderSupportBar(): void {
const support = this.contentDiv.createDiv({
cls: "excalidraw-script-store__support-bar",
});
const mastery = support.createEl("a", {
href: URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM,
cls: "excalidraw-script-store__support-item",
attr: { target: "_blank", rel: "noopener noreferrer" },
});
mastery.createEl("img", {
cls: "excalidraw-script-store__support-logo",
attr: {
src: URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EM_PNG,
alt: t("SCRIPT_STORE_MASTERY_TITLE"),
loading: "lazy",
},
});
const masteryText = mastery.createDiv({
cls: "excalidraw-script-store__support-text",
});
masteryText.createEl("strong", { text: t("SCRIPT_STORE_MASTERY_TITLE") });
masteryText.createSpan({ text: t("SCRIPT_STORE_MASTERY_DESC") });
const coffee = support.createEl("a", {
href: URLs.KO_FI_COM_ZSOLT,
cls: "excalidraw-script-store__support-item",
attr: { target: "_blank", rel: "noopener noreferrer" },
});
const coffeeIcon = coffee.createSpan({
cls: "excalidraw-script-store__support-icon",
});
setIcon(coffeeIcon, "coffee");
const coffeeText = coffee.createDiv({
cls: "excalidraw-script-store__support-text",
});
coffeeText.createEl("strong", { text: t("SCRIPT_STORE_COFFEE_TITLE") });
coffeeText.createSpan({ text: t("SCRIPT_STORE_COFFEE_DESC") });
}
private renderScriptingBanner(): void {
const section = this.contentDiv.createDiv({
cls: "excalidraw-script-store__scripting-promo",
});
const link = section.createEl("a", {
href: URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPTING_MD,
cls: "excalidraw-script-store__scripting-link",
attr: { target: "_blank", rel: "noopener noreferrer" },
});
link.createEl("img", {
cls: "excalidraw-script-store__scripting-banner",
attr: {
src: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_IMAGE_BANNER_AUTOMATE_ANYTHING_PNG,
alt: t("SCRIPT_STORE_SCRIPTING_BANNER_ALT"),
loading: "lazy",
},
});
link.createDiv({
cls: "excalidraw-script-store__scripting-caption",
text: t("SCRIPT_STORE_SCRIPTING_BANNER_CAPTION"),
});
}
private getUpdates(): ScriptStoreEntry[] {
return (
this.catalog?.scripts.filter(
(entry) => this.installStates.get(entry.name) === "update",
) ?? []
);
}
private renderUpdates(): void {
const updates = this.getUpdates();
if (updates.length === 0) {
return;
}
const section = this.contentDiv.createDiv({
cls: "excalidraw-script-store__updates",
});
const header = section.createDiv({
cls: "excalidraw-script-store__updates-header",
});
const titleWrap = header.createDiv();
const title = titleWrap.createEl("h2", {
text: `${t("SCRIPT_STORE_UPDATES_TITLE")} (${updates.length})`,
});
const icon = title.createSpan({
cls: "excalidraw-script-store__inline-icon",
});
setIcon(icon, "circle-arrow-up");
titleWrap.createEl("p", { text: t("SCRIPT_STORE_UPDATES_DESC") });
const updateAll = header.createEl("button", {
text: t("SCRIPT_STORE_UPDATE_ALL"),
cls: "mod-cta",
type: "button",
});
updateAll.addEventListener("click", () => {
void this.updateAll(updateAll);
});
const list = section.createDiv({
cls: "excalidraw-script-store__update-list",
});
updates.forEach((entry) => {
const button = list.createEl("button", {
text: entry.name,
cls: "excalidraw-script-store__update-chip",
type: "button",
});
button.addEventListener("click", () => this.renderDetail(entry));
});
}
private async updateAll(button: HTMLButtonElement): Promise<void> {
const updates = this.getUpdates();
if (updates.length === 0) {
return;
}
button.disabled = true;
button.setText(t("SCRIPT_STORE_UPDATING"));
let failures = 0;
for (const entry of updates) {
this.containerEl.classList.add("excalidraw-scriptengine-install");
void (async () => {
try {
await installScript(this.plugin, getScriptInstallUrl(entry), false);
this.installStates.set(entry.name, "up-to-date");
} catch {
failures += 1;
this.installStates.set(entry.name, "error");
}
}
new Notice(
failures === 0
? t("SCRIPT_STORE_UPDATE_ALL_DONE")
: `${t("SCRIPT_STORE_UPDATE_ALL_PARTIAL")} ${failures}`,
);
this.renderStore();
}
private renderBrowseControls(): void {
if (!this.catalog) {
return;
}
const browse = this.contentDiv.createDiv({
cls: "excalidraw-script-store__browse-header",
});
const heading = browse.createDiv();
heading.createEl("h2", { text: t("SCRIPT_STORE_BROWSE_TITLE") });
heading.createEl("p", { text: t("SCRIPT_STORE_BROWSE_DESC") });
const controls = browse.createDiv({
cls: "excalidraw-script-store__controls",
});
const searchWrap = controls.createDiv({
cls: "excalidraw-script-store__search",
});
const searchIcon = searchWrap.createSpan();
setIcon(searchIcon, "search");
const search = searchWrap.createEl("input", {
type: "search",
placeholder: t("SCRIPT_STORE_SEARCH_PLACEHOLDER"),
attr: { "aria-label": t("SCRIPT_STORE_SEARCH_PLACEHOLDER") },
});
search.value = this.searchQuery;
search.addEventListener("input", () => {
this.searchQuery = search.value.trim().toLowerCase();
this.renderScriptGrid();
});
const category = controls.createEl("select", {
attr: { "aria-label": t("SCRIPT_STORE_CATEGORY_LABEL") },
});
category.createEl("option", {
text: t("SCRIPT_STORE_ALL_CATEGORIES"),
value: "",
});
this.catalog.categories.forEach((item) => {
category.createEl("option", { text: item.name, value: item.name });
});
category.value = this.selectedCategory;
category.addEventListener("change", () => {
this.selectedCategory = category.value;
this.renderScriptGrid();
});
const viewToggle = controls.createDiv({
cls: "excalidraw-script-store__view-toggle",
});
this.renderViewButton(viewToggle, "all", t("SCRIPT_STORE_ALL_SCRIPTS"));
this.renderViewButton(
viewToggle,
"installed",
t("SCRIPT_STORE_INSTALLED_SCRIPTS"),
);
}
private renderViewButton(
parent: HTMLElement,
view: StoreView,
label: string,
): void {
const button = parent.createEl("button", {
text: label,
cls: this.storeView === view ? "is-active" : undefined,
type: "button",
});
button.addEventListener("click", () => {
this.storeView = view;
parent.querySelectorAll("button").forEach((item) => {
item.classList.toggle("is-active", item === button);
});
this.renderScriptGrid();
});
}
private renderScriptGrid(): void {
if (!this.catalog) {
return;
}
this.contentDiv.querySelector(".excalidraw-script-store__results")?.remove();
const results = this.contentDiv.createDiv({
cls: "excalidraw-script-store__results",
});
const entries = this.getFilteredEntries();
results.createDiv({
cls: "excalidraw-script-store__result-summary",
text: `${entries.length} ${t("SCRIPT_STORE_RESULTS")}`,
});
if (entries.length === 0) {
const empty = results.createDiv({
cls: "excalidraw-script-store__empty",
});
const icon = empty.createSpan();
setIcon(icon, "search-x");
empty.createEl("h3", { text: t("SCRIPT_STORE_NO_RESULTS") });
empty.createEl("p", { text: t("SCRIPT_STORE_NO_RESULTS_DESC") });
return;
}
const grid = results.createDiv({ cls: "excalidraw-script-store__grid" });
entries.forEach((entry) => this.renderScriptCard(grid, entry));
}
private getFilteredEntries(): ScriptStoreEntry[] {
if (!this.catalog) {
return [];
}
const featuredRank = new Map(
this.catalog.scripts
.filter((entry) => entry.categories.includes(FEATURED_CATEGORY))
.map((entry) => [
entry.name,
entry.featuredRank ?? Number.MAX_SAFE_INTEGER,
]),
);
return this.catalog.scripts
.filter((entry) => {
const state = this.installStates.get(entry.name) ?? "error";
if (this.storeView === "installed" && state === "install") {
return false;
const source = await request({ url: URL });
if (!source) {
new Notice(t("SCRIPT_INSTALL_PROMPT_FETCH_ERROR"), 5000);
log(URL);
this.close();
return;
}
if (
this.selectedCategory &&
!entry.categories.includes(this.selectedCategory)
) {
return false;
}
if (!this.searchQuery) {
return true;
}
const searchable = [
entry.name,
entry.author,
entry.categories.join(" "),
this.getDescription(entry),
]
.join(" ")
.toLowerCase();
return searchable.includes(this.searchQuery);
})
.sort((a, b) => {
const aRank = featuredRank.get(a.name);
const bRank = featuredRank.get(b.name);
if (aRank !== undefined && bRank !== undefined) {
return aRank - bRank;
}
if (aRank !== undefined) {
return -1;
}
if (bRank !== undefined) {
return 1;
}
return a.name.localeCompare(b.name);
});
}
private renderScriptCard(parent: HTMLElement, entry: ScriptStoreEntry): void {
const state = this.installStates.get(entry.name) ?? "error";
const card = parent.createDiv({ cls: "excalidraw-script-store__card" });
if (state === "update") {
card.classList.add("has-update");
}
const main = card.createEl("button", {
cls: "excalidraw-script-store__card-main",
type: "button",
attr: { "aria-label": `${t("SCRIPT_STORE_DETAILS")}: ${entry.name}` },
});
main.addEventListener("click", () => this.renderDetail(entry));
const iconWrap = main.createDiv({ cls: "excalidraw-script-store__icon" });
const fallback = iconWrap.createSpan({
cls: "excalidraw-script-store__icon-fallback",
});
setIcon(fallback, "scroll-text");
const image = iconWrap.createEl("img", {
attr: { src: getScriptIconUrl(entry), alt: "", loading: "lazy" },
});
image.addEventListener(
"error",
() => {
image.classList.add("is-hidden");
fallback.classList.add("is-visible");
},
{ once: true },
);
const text = main.createDiv({ cls: "excalidraw-script-store__card-text" });
const titleRow = text.createDiv({
cls: "excalidraw-script-store__title-row",
});
titleRow.createEl("h3", { text: entry.name });
this.renderStateBadge(titleRow, state);
if (entry.categories.includes(FEATURED_CATEGORY)) {
const featured = titleRow.createSpan({
cls: "excalidraw-script-store__badge is-featured",
text: t("SCRIPT_STORE_FEATURED"),
});
const icon = featured.createSpan();
setIcon(icon, "sparkles");
}
if (entry.author) {
text.createDiv({
cls: "excalidraw-script-store__author",
text: `${t("SCRIPT_STORE_BY")} ${entry.author}`,
});
}
text.createEl("p", { text: this.getDescription(entry) });
const footer = card.createDiv({
cls: "excalidraw-script-store__card-footer",
});
const categoryText = entry.categories
.filter((name) => name !== FEATURED_CATEGORY)
.slice(0, 2)
.join(" · ");
footer.createSpan({ text: categoryText });
const action = footer.createEl("button", {
text: this.getActionLabel(state),
type: "button",
cls: state === "update" ? "mod-cta" : undefined,
});
action.disabled = state === "up-to-date";
action.addEventListener("click", (event) => {
event.stopPropagation();
void this.installEntry(entry, action);
});
}
private renderStateBadge(
parent: HTMLElement,
state: ScriptStoreInstallState,
): void {
if (state === "install") {
return;
}
const badge = parent.createSpan({
cls: [
"excalidraw-script-store__badge",
state === "update" ? "has-update" : "is-installed",
],
text:
state === "update"
? t("SCRIPT_STORE_UPDATE_BADGE")
: state === "error"
? t("SCRIPT_STORE_CHECK_FAILED")
: t("SCRIPT_STORE_INSTALLED_BADGE"),
});
const icon = badge.createSpan();
setIcon(icon, state === "update" ? "circle-arrow-up" : "check");
}
private getDescription(entry: ScriptStoreEntry): string {
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 {
switch (state) {
case "install":
return t("SCRIPT_STORE_INSTALL");
case "update":
return t("SCRIPT_STORE_UPDATE");
case "up-to-date":
return t("SCRIPT_STORE_INSTALLED_BADGE");
case "error":
return t("SCRIPT_STORE_REINSTALL");
}
}
private getDetailActionLabel(state: ScriptStoreInstallState): string {
return state === "up-to-date"
? t("SCRIPT_STORE_REINSTALL")
: this.getActionLabel(state);
}
private async installEntry(
entry: ScriptStoreEntry,
button: HTMLButtonElement,
stayOnDetail = false,
): Promise<void> {
button.disabled = true;
button.setText(t("SCRIPT_STORE_UPDATING"));
try {
await installScript(this.plugin, getScriptInstallUrl(entry), false);
this.installStates.set(entry.name, "up-to-date");
new Notice(`${t("SCRIPT_INSTALLED_NOTICE")}: ${entry.name}`);
if (stayOnDetail) {
this.renderDetail(entry);
} else {
this.renderStore();
}
} catch {
this.installStates.set(entry.name, "error");
new Notice(`${t("SCRIPT_INSTALL_ERROR_NOTICE")}: ${entry.name}`);
button.disabled = false;
button.setText(t("SCRIPT_STORE_REINSTALL"));
}
}
private renderDetail(entry: ScriptStoreEntry): void {
const state = this.installStates.get(entry.name) ?? "error";
this.contentDiv.replaceChildren();
const back = this.contentDiv.createEl("button", {
text: t("SCRIPT_STORE_BACK"),
cls: "excalidraw-script-store__back",
type: "button",
});
const backIcon = back.createSpan();
setIcon(backIcon, "arrow-left");
back.addEventListener("click", () => this.renderStore());
const detail = this.contentDiv.createDiv({
cls: "excalidraw-script-store__detail",
});
const hero = detail.createDiv({
cls: "excalidraw-script-store__detail-hero",
});
const iconWrap = hero.createDiv({
cls: "excalidraw-script-store__detail-icon",
});
const fallback = iconWrap.createSpan({
cls: "excalidraw-script-store__detail-icon-fallback",
});
setIcon(fallback, "scroll-text");
const image = iconWrap.createEl("img", {
attr: { src: getScriptIconUrl(entry), alt: "", loading: "lazy" },
});
image.addEventListener(
"error",
() => {
image.classList.add("is-hidden");
fallback.classList.add("is-visible");
},
{ once: true },
);
const title = hero.createDiv({
cls: "excalidraw-script-store__detail-title",
});
title.createEl("h1", { text: entry.name });
if (entry.author) {
const byline = title.createDiv({
cls: "excalidraw-script-store__detail-byline",
});
byline.append(`${t("SCRIPT_STORE_BY")} `);
if (entry.authorUrl) {
byline.createEl("a", {
text: entry.author,
href: entry.authorUrl,
attr: { target: "_blank", rel: "noopener noreferrer" },
});
} else {
byline.append(entry.author);
}
}
const tags = title.createDiv({
cls: "excalidraw-script-store__detail-tags",
});
entry.categories.forEach((category) =>
tags.createSpan({ text: category, cls: "excalidraw-script-store__tag" }),
);
const actions = title.createDiv({
cls: "excalidraw-script-store__detail-actions",
});
const install = actions.createEl("button", {
text: this.getDetailActionLabel(state),
type: "button",
cls: state === "update" || state === "install" ? "mod-cta" : undefined,
});
install.addEventListener("click", () => {
void this.installEntry(entry, install, true);
});
actions.createEl("a", {
text: t("SCRIPT_STORE_VIEW_SOURCE"),
href: getScriptSourceUrl(entry),
cls: "excalidraw-script-store__source-link",
attr: { target: "_blank", rel: "noopener noreferrer" },
});
if (state !== "install") {
this.renderInstalledScriptManagement(detail, entry);
}
const description = detail.createDiv({
cls: "excalidraw-script-store__detail-description",
});
setSanitizedHtml(description, entry.descriptionHtml);
description.querySelectorAll("a").forEach((link) => {
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener noreferrer");
});
}
private renderInstalledScriptManagement(
parent: HTMLElement,
entry: ScriptStoreEntry,
): void {
const source = getScriptInstallUrl(entry);
const localFiles = getInstalledScriptFiles(this.plugin, source);
if (localFiles.length === 0) {
return;
}
const section = parent.createDiv({
cls: "excalidraw-script-store__local-management",
});
section.createEl("h2", { text: t("SCRIPT_STORE_LOCAL_TITLE") });
if (localFiles.length > 1) {
section.createDiv({
cls: "excalidraw-script-store__local-note",
text: t("SCRIPT_STORE_MULTIPLE_COPIES"),
});
}
if (this.plugin.settings.storeScriptFilesAsJavaScript) {
section.createDiv({
cls: "excalidraw-script-store__local-note",
text: t("SCRIPT_STORE_JS_OPEN_NOTE"),
});
}
const groups = getInstalledScriptGroups(this.plugin);
localFiles.forEach((localFile, index) => {
const copy = section.createDiv({
cls: "excalidraw-script-store__local-copy",
});
if (localFiles.length > 1) {
copy.createDiv({
cls: "excalidraw-script-store__local-copy-label",
text:
index === 0
? t("SCRIPT_STORE_PRIMARY_COPY")
: t("SCRIPT_STORE_ADDITIONAL_COPY"),
});
}
const fileRow = copy.createDiv({
cls: "excalidraw-script-store__local-row",
});
const fileInfo = fileRow.createDiv({
cls: "excalidraw-script-store__local-info",
});
fileInfo.createEl("strong", { text: t("SCRIPT_STORE_LOCAL_FILE") });
fileInfo.createEl("code", { text: localFile.path });
const fileActions = fileRow.createDiv({
cls: "excalidraw-script-store__local-actions",
});
const openButton = fileActions.createEl("button", {
text: t("SCRIPT_STORE_OPEN_LOCAL"),
type: "button",
});
openButton.onClickEvent(() => {
void this.openLocalScript(localFile.path);
});
const uninstallButton = fileActions.createEl("button", {
text: t("SCRIPT_STORE_UNINSTALL"),
type: "button",
cls: "mod-warning",
});
uninstallButton.onClickEvent(() => {
void this.uninstallEntry(entry, uninstallButton, localFile.path);
});
const downloadedRoot = normalizePath(
`${this.plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`,
);
const currentGroup =
localFile.parent?.path === downloadedRoot
? ""
: localFile.parent?.path.slice(downloadedRoot.length + 1) ?? "";
const groupRow = copy.createDiv({
cls: "excalidraw-script-store__group-row",
});
const groupLabel = groupRow.createEl("label", {
text: t("SCRIPT_STORE_GROUP_LABEL"),
});
const groupControls = groupRow.createDiv({
cls: "excalidraw-script-store__group-controls",
});
const groupSelect = groupControls.createEl("select", {
attr: {
id: `excalidraw-script-store-group-${index}`,
"aria-label": t("SCRIPT_STORE_GROUP_LABEL"),
},
});
groupSelect.createEl("option", {
text: t("SCRIPT_STORE_GROUP_ROOT"),
value: "",
});
groups.forEach((group) => {
groupSelect.createEl("option", { text: group, value: group });
});
if (
currentGroup &&
!Array.from(groupSelect.options).some(
(option) => option.value === currentGroup,
)
) {
groupSelect.createEl("option", {
text: currentGroup,
value: currentGroup,
});
}
groupSelect.value = currentGroup;
groupLabel.htmlFor = groupSelect.id;
const newGroup = groupControls.createEl("input", {
type: "text",
placeholder: t("SCRIPT_STORE_NEW_GROUP_PLACEHOLDER"),
attr: { "aria-label": t("SCRIPT_STORE_NEW_GROUP_PLACEHOLDER") },
});
const moveButton = groupControls.createEl("button", {
text: t("SCRIPT_STORE_MOVE_TO_GROUP"),
type: "button",
});
moveButton.onClickEvent(() => {
const targetGroup = newGroup.value.trim() || groupSelect.value;
void this.moveEntryToGroup(
entry,
localFile.path,
targetGroup,
moveButton,
await MarkdownRenderer.render(
this.plugin.app,
source,
this.contentDiv,
"",
this.renderComponent,
);
});
});
}
private async openLocalScript(localPath: string): Promise<void> {
const localFile = this.plugin.app.vault.getFileByPath(
normalizePath(localPath),
);
if (!localFile) {
return;
}
try {
this.close();
await this.plugin.app.workspace.getLeaf(true).openFile(localFile, {
active: true,
});
} catch (error: unknown) {
errorlog({
where: "ScriptInstallPrompt.openLocalScript",
source: localFile.path,
error,
});
new Notice(t("SCRIPT_STORE_OPEN_LOCAL_FAILED"));
}
}
private async uninstallEntry(
entry: ScriptStoreEntry,
button: HTMLButtonElement,
localPath: string,
): Promise<void> {
button.disabled = true;
try {
const source = getScriptInstallUrl(entry);
await uninstallScript(this.plugin, source, localPath);
if (getInstalledScriptFiles(this.plugin, source).length === 0) {
this.installStates.set(entry.name, "install");
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 (e: unknown) {
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e });
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
this.close();
}
new Notice(`${t("SCRIPT_STORE_UNINSTALLED")}: ${entry.name}`);
this.renderDetail(entry);
} catch (error: unknown) {
errorlog({
where: "ScriptInstallPrompt.uninstallEntry",
source: localPath,
error,
});
new Notice(`${t("SCRIPT_STORE_UNINSTALL_FAILED")}: ${entry.name}`);
button.disabled = false;
}
}
private async moveEntryToGroup(
entry: ScriptStoreEntry,
localPath: string,
targetGroup: string,
button: HTMLButtonElement,
): Promise<void> {
button.disabled = true;
try {
const source = getScriptInstallUrl(entry);
await moveInstalledScriptToGroup(
this.plugin,
source,
targetGroup,
localPath,
);
new Notice(`${t("SCRIPT_STORE_MOVED_TO_GROUP")}: ${entry.name}`);
this.renderDetail(entry);
} catch (error: unknown) {
errorlog({
where: "ScriptInstallPrompt.moveEntryToGroup",
source: localPath,
error,
});
new Notice(`${t("SCRIPT_STORE_MOVE_FAILED")}: ${entry.name}`);
button.disabled = false;
}
})();
}
onClose(): void {
this.contentEl.replaceChildren();
this.contentEl.empty();
this.renderComponent.unload();
}
}
+1 -39
View File
@@ -440,7 +440,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc:
"Adds an arrow element.\n" +
'Arrowheads: "arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null.\n' +
'Set startObjectId/endObjectId to bind the corresponding arrow end to a shape; omit an object ID to leave that end unbound. Bind mode: "orbit" (default) or "inside".\n' +
'Bindings: "inside" | "outside" Sets startObjectId/endObjectId to bind the arrow ends to shapes. Bind mode: "orbit" (default) or "inside".\n' +
"Fixed point: [xRatio,yRatio] in 0..1 (percentage of bound element width/height) to bind to a specific point on the element. In case of orbit mode, the orbit will happen around this immaginary point.\n" +
"Elbowed: true will create an elbowed arrow.",
after: "",
@@ -661,24 +661,6 @@ 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;",
@@ -987,14 +969,6 @@ 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>",
@@ -1319,12 +1293,6 @@ 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; }",
@@ -1345,12 +1313,6 @@ 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",
+1 -7
View File
@@ -32,7 +32,6 @@ import {
getPDFDoc,
getURLImageExtension,
hasExcalidrawEmbeddedImagesTreeChanged,
createNestedFileDependencyGraphContext,
readLocalFileBinary,
} from "../utils/fileUtils";
import { blobToDataURL, errorlog, getDataURL } from "../utils/coreUtils";
@@ -1499,11 +1498,6 @@ export class EmbeddedFilesLoader {
FileId,
DeferredCacheValidation
>();
// Deferred candidates frequently share most of the same nested graph.
// Scope this cache to one load so metadata is parsed once without retaining
// dependency state across synchronization operations.
const deferredDependencyGraphContext =
createNestedFileDependencyGraphContext(true);
const deferredGenerationEntries: typeof entries = [];
const renderedMarkdownImageCacheEntries = new Map<
FileId,
@@ -1582,7 +1576,7 @@ export class EmbeddedFilesLoader {
file,
deferredValidation.cacheMtime,
loader.plugin,
deferredDependencyGraphContext,
"deferred-scene-validation",
),
);
if (cacheIsValid) {
+47 -208
View File
@@ -23,7 +23,6 @@ import {
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
import {
Editor,
MarkdownView,
Notice,
OpenViewState,
RequestUrlResponse,
@@ -51,7 +50,6 @@ import {
refreshTextDimensions,
getFontFamilyString,
convertToExcalidrawElements,
VIEW_TYPE_EXCALIDRAW,
} from "src/constants/constants";
import {
blobToBase64,
@@ -81,7 +79,6 @@ import {
isObsidianThemeDark,
mergeMarkdownFiles,
openLeaf,
setExcalidrawView,
} from "src/utils/obsidianUtils";
import { getAttachmentsFolderAndFilePath } from "src/utils/pathUtils";
import {
@@ -239,23 +236,9 @@ import {
normalizeSceneArea,
} from "src/utils/excalidrawElementUtils";
import { cropPNGBlob } from "src/utils/imageExportUtils";
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,
@@ -886,24 +869,6 @@ 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
@@ -2763,8 +2728,8 @@ export class ExcalidrawAutomate {
* @param {Object} [formatting] - Formatting options for the arrow element.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.startArrowHead] - The start arrowhead type.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.endArrowHead] - The end arrowhead type.
* @param {string} [formatting.startObjectId] - The ID of the start object. When omitted, the arrow start is unbound.
* @param {string} [formatting.endObjectId] - The ID of the end object. When omitted, the arrow end is unbound.
* @param {string} [formatting.startObjectId] - The ID of the start object.
* @param {string} [formatting.endObjectId] - The ID of the end object.
* BindMode Determines whether the arrow remains outside the shape or is allowed to
* go all the way inside the shape up to the exact fixed point.
* @param {"inside" | "orbit"} [formatting.startBindMode] - The binding mode for the start object.
@@ -2812,32 +2777,20 @@ export class ExcalidrawAutomate {
},
id?: string,
): string {
const startFixedPoint = normalizeFixedPoint(formatting?.startFixedPoint);
const endFixedPoint = normalizeFixedPoint(formatting?.endFixedPoint);
const startMode = normalizeBindMode(formatting?.startBindMode);
const endMode = normalizeBindMode(formatting?.endBindMode);
const box = getLineBox(points);
const elbowed = formatting?.elbowed ?? false;
const startObjectId = formatting?.startObjectId;
const endObjectId = formatting?.endObjectId;
const startBinding: FixedPointBinding | null = startObjectId
? {
elementId: startObjectId,
mode: normalizeBindMode(formatting?.startBindMode),
fixedPoint: normalizeFixedPoint(formatting?.startFixedPoint),
}
: null;
const endBinding: FixedPointBinding | null = endObjectId
? {
elementId: endObjectId,
mode: normalizeBindMode(formatting?.endBindMode),
fixedPoint: normalizeFixedPoint(formatting?.endFixedPoint),
}
: null;
const startElement = startBinding
const startElement = formatting?.startObjectId
? (this.getElement(
startBinding.elementId,
formatting.startObjectId,
) as Mutable<ExcalidrawBindableElement>)
: null;
const endElement = endBinding
const endElement = formatting?.endObjectId
? (this.getElement(
endBinding.elementId,
formatting.endObjectId,
) as Mutable<ExcalidrawBindableElement>)
: null;
id = id ?? nanoid();
@@ -2845,8 +2798,16 @@ export class ExcalidrawAutomate {
points: normalizeLinePoints(points),
elbowed,
lastCommittedPoint: null,
startBinding,
endBinding,
startBinding: {
elementId: formatting?.startObjectId,
mode: startMode,
fixedPoint: startFixedPoint,
},
endBinding: {
elementId: formatting?.endObjectId,
mode: endMode,
fixedPoint: endFixedPoint,
},
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/388
startArrowhead:
typeof formatting?.startArrowHead !== "undefined"
@@ -3902,10 +3863,11 @@ export class ExcalidrawAutomate {
* @param {boolean} [forceViewMode=false] - Whether to force view mode.
*/
viewToggleFullScreen(forceViewMode: boolean = false): void {
const view = this.getReadyTargetView("viewToggleFullScreen()");
if (!view) {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
const view = this.targetView;
const isFullscreen = view.isFullscreen();
if (forceViewMode) {
view.updateScene({
@@ -3915,7 +3877,9 @@ export class ExcalidrawAutomate {
},
captureUpdate: CaptureUpdateAction.NEVER,
});
view.toolsPanelRef?.current?.setExcalidrawViewMode(!isFullscreen);
this.targetView.toolsPanelRef?.current?.setExcalidrawViewMode(
!isFullscreen,
);
}
if (isFullscreen) {
@@ -3930,10 +3894,11 @@ export class ExcalidrawAutomate {
* @param {boolean} enabled - Whether to enable view mode.
*/
setViewModeEnabled(enabled: boolean): void {
const view = this.getReadyTargetView("setViewModeEnabled()");
if (!view) {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
const view = this.targetView;
view.updateScene({
appState: { viewModeEnabled: enabled },
captureUpdate: CaptureUpdateAction.NEVER,
@@ -3941,25 +3906,6 @@ 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.
@@ -3982,15 +3928,15 @@ export class ExcalidrawAutomate {
},
restore: boolean = false,
): void {
const view = this.getReadyTargetView("viewUpdateScene()");
if (!view) {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
if (!scene.storeAction) {
scene.storeAction = scene.commitToHistory ? "capture" : "update";
}
view.updateScene(
this.targetView.updateScene(
{
elements: scene.elements,
appState: scene.appState,
@@ -4065,40 +4011,11 @@ export class ExcalidrawAutomate {
elements: ExcalidrawElement[],
margin: number = 0.05,
): void {
const view = this.getReadyTargetView("viewZoomToElements()");
if (!view) {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
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();
this.targetView.zoomToElements(selectElements, elements, margin);
}
/**
@@ -4116,15 +4033,15 @@ export class ExcalidrawAutomate {
shouldRestoreElements: boolean = false,
captureUpdate: CaptureUpdateActionType = CaptureUpdateAction.IMMEDIATELY,
): Promise<boolean> {
const view = this.getReadyTargetView("addElementsToView()");
if (!view) {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "addElementsToView()");
return false;
}
const elements = this.getElements();
if (elements.some((el) => el.type === "embeddable")) {
patchMobileView(view);
patchMobileView(this.targetView);
}
const result = await view.addElements({
const result = await this.targetView.addElements({
newElements: elements,
repositionToCursor,
save,
@@ -4143,28 +4060,24 @@ export class ExcalidrawAutomate {
* @returns {boolean} True if successful, false otherwise.
*/
registerThisAsViewEA(): boolean {
const view = this.getReadyTargetView("registerThisAsViewEA()");
if (!view) {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "addElementsToView()");
return false;
}
view.setHookServer(this);
this.targetView.setHookServer(this);
return true;
}
/**
* 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.
* Sets the target view EA to window.ExcalidrawAutomate.
* @returns {boolean} True if successful, false otherwise.
*/
deregisterThisAsViewEA(): boolean {
const view = this.targetView;
if (!view) {
if (!this.destroyed) {
errorMessage("targetView not set", "deregisterThisAsViewEA()");
}
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "addElementsToView()");
return false;
}
view.setHookServer();
this.targetView.setHookServer(this);
return true;
}
@@ -4719,13 +4632,6 @@ export class ExcalidrawAutomate {
return groupId.length > 0 ? groupId[0] : null;
}
/**
* This is a convenience method to get the release notes for the plugin.
* @returns {Object} The release notes object.
*/
getReleaseNotes(): { [k: string]: string } {
return RELEASE_NOTES;
}
/**
* Gets all the elements from elements[] that share one or more groupIds with the specified element.
* @param {ExcalidrawElement} element - The element to check.
@@ -5016,65 +4922,6 @@ 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.
@@ -5522,14 +5369,6 @@ 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 = {};
+1
View File
@@ -560,6 +560,7 @@ class ImageCache {
file,
cachedData.mtime,
this.plugin,
"indexeddb-cache-validation",
);
if (dependencyChanged) {
return undefined;
+6 -123
View File
@@ -378,23 +378,6 @@ 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;
@@ -446,47 +429,6 @@ 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
@@ -647,73 +589,14 @@ export class ScriptEngine {
destinationPath: string,
): Promise<void> {
const sourcePath = file.path;
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,
const startupScriptPath = resolveConfiguredStartupScriptPath(
this.plugin.settings.startupScriptPath,
);
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;
}
await this.migrateScriptFiles({
renames: [{ file, sourcePath, destinationPath }],
conflicts: [],
includesStartupScript: startupScriptPath === sourcePath,
});
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 {
+2 -2
View File
@@ -96,7 +96,7 @@ export class InlineLinkSuggester
inputEl: HTMLInputElement | HTMLTextAreaElement,
getSourcePath: () => string | undefined,
widthWrapper?: HTMLElement,
suppressPlaceholder: boolean = false,
surpessPlaceholder: boolean = false,
collisionBoundary?: HTMLElement,
) {
super(app, inputEl, [], collisionBoundary);
@@ -107,7 +107,7 @@ export class InlineLinkSuggester
this.handleBracketKeyDown = (event: KeyboardEvent) =>
this.onBracketKeyDown(event);
this.limit = 20;
if (!suppressPlaceholder) {
if (!surpessPlaceholder) {
this.setPlaceholder(t("INLINE_HINT"));
}
this.emptyStateText = "No match";
+2 -1
View File
@@ -81,7 +81,7 @@ type EmbeddedLink =
))
| null;
export declare namespace ExcalidrawLib {
declare namespace ExcalidrawLib {
type ObsidianCommonHostUIMode = "full" | "compact" | "tray" | "mobile";
type ObsidianCommonHostAdapter = Readonly<{
@@ -114,6 +114,7 @@ export declare namespace ExcalidrawLib {
type ObsidianExcalidrawHostAdapter = Readonly<{
protocolVersion: 2;
isDoubleTapEraserEnabled: () => boolean;
isRightClickPanEnabled: () => boolean;
getZoomToFitMaxLevel: () => number;
isPenModeCrosshairVisible: () => boolean;
isSingleFingerPanningEnabled: () => boolean;
-4
View File
@@ -80,10 +80,6 @@ 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][];
+1 -12
View File
@@ -1,18 +1,7 @@
/**
* Metadata entry describing a file in the legacy remote EA scripts directory listing.
* Metadata entry describing a file in the 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;
};
-29
View File
@@ -1,29 +0,0 @@
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";
+24
View File
@@ -1,3 +1,5 @@
import { TFile } from "obsidian";
export type FILENAMEPARTS = {
filepath: string;
hasBlockref: boolean;
@@ -34,3 +36,25 @@ export type PaneTarget =
| "popout-window"
| "new-tab"
| "md-properties";
export interface NestedFileNode {
file: TFile;
/**
* All distinct dependency paths from the root file down to this embedded file.
* Each path is an ordered array of TFile objects starting with the `rootFile` at index 0.
*
* @example
* If Root -> A -> B2.2 and Root -> B -> B2 -> B2.2
* The paths for B2.2 will be:
* [
* [Root, A, B2.2],
* [Root, B, B2, B2.2]
* ]
*
* Usage: To find which top-level embeds to reload if this file changes,
* you can map over `paths` and collect `path[1]`.
*/
paths: TFile[][];
}
export type NestedFileMap = Map<TFile, NestedFileNode>;
+19 -14
View File
@@ -31,8 +31,7 @@ import {
FileId,
NonDeletedExcalidrawElement,
} from "@zsviczian/excalidraw/types/element/src/types";
import { getNestedFileDependencyGraph } from "./fileUtils";
import { getMatchingTopLevelDependencyKeys } from "./nestedDependencyTraversal";
import { getAllNestedExcalidrawFiles } from "./fileUtils";
import {
getEmbeddedFilenameParts,
getLinkParts,
@@ -200,24 +199,30 @@ export function getChangedTopLevelDependencyFileIDs(
return changedFileIDs;
}
const dependencyGraph = getNestedFileDependencyGraph(
// Walk the full nested visual-dependency tree of the root drawing.
// If any nested file changed since lastLoadTime, mark all top-level embeds
// that include it (identified via path[1]) as needing a rebuild.
const nestedTree = getAllNestedExcalidrawFiles(
plugin,
view.file,
true,
"leaf-switch",
);
const changedTopLevelPaths = getMatchingTopLevelDependencyKeys(
dependencyGraph,
view.file.path,
new Set(excalidrawFileIdsByPath.keys()),
(file) => file.stat.mtime > lastLoadTime,
);
for (const path of changedTopLevelPaths) {
const fileIds = excalidrawFileIdsByPath.get(path);
if (!fileIds) {
for (const [file, node] of nestedTree.entries()) {
if (file.stat.mtime <= lastLoadTime) {
continue;
}
for (const fileId of fileIds) {
changedFileIDs.add(fileId);
for (const path of node.paths) {
const topLevelDep = path[1];
if (!topLevelDep) {
continue;
}
const fileIds = excalidrawFileIdsByPath.get(topLevelDep.path);
if (fileIds) {
for (const fileId of fileIds) {
changedFileIDs.add(fileId);
}
}
}
}
+148 -96
View File
@@ -29,12 +29,11 @@ import type ExcalidrawView from "src/view/ExcalidrawView";
import { IMAGE_MIME_TYPES, MimeType } from "src/types/embeddedFileLoaderTypes";
import type { PdfJsDocumentProxy } from "src/types/pdfJsTypes";
import { setElementDisplay } from "./htmlUtils";
import { NestedFileMap } from "src/types/utilTypes";
import {
collectReachableDependencyValues,
DependencyGraph,
DependencyGraphNode,
hasReachableDependency,
} from "./nestedDependencyTraversal";
nestedDependencyElapsedMs,
recordNestedTreeDiagnostic,
} from "./nestedDependencyDiagnostics";
export { splitFolderAndFilename } from "./pathUtils";
declare const mainDocument: Document;
@@ -590,82 +589,71 @@ export const fileShouldDefaultAsExcalidraw = (
);
};
export interface NestedFileDependencyGraph extends DependencyGraph<TFile> {
nodes: Map<string, DependencyGraphNode<TFile>>;
}
export interface NestedFileDependencyGraphContext
extends NestedFileDependencyGraph {
includeImages: boolean;
parsedExcalidrawPaths: Set<string>;
}
export const createNestedFileDependencyGraphContext = (
includeImages = false,
): NestedFileDependencyGraphContext => ({
includeImages,
nodes: new Map(),
parsedExcalidrawPaths: new Set(),
});
/**
* Builds a path-keyed dependency graph from Obsidian's metadata cache.
* A context may be shared by related queries so each Excalidraw file is parsed
* once. The context must remain scoped to one operation to avoid stale edges.
* Synchronously retrieves all nested Excalidraw files using the metadata cache.
* Returns an optimized Map containing the full dependency paths for every embedded file.
*
* @param {ExcalidrawPlugin} plugin - The Excalidraw plugin instance.
* @param {TFile} rootFile - The entry-point Excalidraw file.
* @param {boolean} includeImages - Whether to include ANY non-Excalidraw markdown links found in the embedded section.
* @returns {NestedFileMap} A map linking each embedded TFile to its paths from the root.
*/
export function getNestedFileDependencyGraph(
plugin: ExcalidrawPlugin,
export function getAllNestedExcalidrawFiles(
plugin: ExcalidrawPlugin, // Replace `any` with `ExcalidrawPlugin` type in your actual code
rootFile: TFile,
includeImages = false,
sharedContext?: NestedFileDependencyGraphContext,
): NestedFileDependencyGraph {
const context =
sharedContext?.includeImages === includeImages
? sharedContext
: createNestedFileDependencyGraphContext(includeImages);
const pending = [rootFile];
diagnosticCallSite = "unspecified",
): NestedFileMap {
const traversalStartedAt = performance.now();
const app = plugin.app;
while (pending.length > 0) {
const file = pending.pop();
if (!file || context.parsedExcalidrawPaths.has(file.path)) {
continue;
// Phase 1: Build the Adjacency List (Directed Acyclic Graph)
// This ensures we only parse the metadata cache for each file exactly once.
const adjacencyList = new Map<TFile, TFile[]>();
const parsedFiles = new Set<string>();
let dependencyEdges = 0;
function parseFile(file: TFile) {
if (parsedFiles.has(file.path)) {
return;
}
context.parsedExcalidrawPaths.add(file.path);
parsedFiles.add(file.path);
const uniqueChildren = new Map<string, TFile>();
const cache = plugin.app.metadataCache.getFileCache(file);
if (!cache?.links) {
context.nodes.set(file.path, { value: file, childKeys: [] });
continue;
const cache = app.metadataCache.getFileCache(file);
if (!cache || !cache.links) {
adjacencyList.set(file, []);
return;
}
let startLine = -1;
let endLine = Infinity;
let usingCommentFallback = false;
// 1. Standard approach: Look for "Embedded Files" heading
if (cache.headings) {
const embeddedFilesHeadingIndex = cache.headings.findIndex(
(heading) => heading.heading.toLowerCase() === "embedded files",
const embedHeadingIdx = cache.headings.findIndex(
(h) => h.heading.toLowerCase() === "embedded files",
);
if (embeddedFilesHeadingIndex !== -1) {
const embeddedFilesHeading = cache.headings[embeddedFilesHeadingIndex];
startLine = embeddedFilesHeading.position.start.line;
for (
let index = embeddedFilesHeadingIndex + 1;
index < cache.headings.length;
index++
) {
if (cache.headings[index].level <= embeddedFilesHeading.level) {
endLine = cache.headings[index].position.start.line;
if (embedHeadingIdx !== -1) {
const embedHeading = cache.headings[embedHeadingIdx];
startLine = embedHeading.position.start.line;
for (let i = embedHeadingIdx + 1; i < cache.headings.length; i++) {
if (cache.headings[i].level <= embedHeading.level) {
endLine = cache.headings[i].position.start.line;
break;
}
}
}
}
// 2. Fallback approach: The entire Excalidraw Data block is inside a %% comment %%
if (startLine === -1 && cache.sections) {
const commentSections = cache.sections.filter(
(section) => section.type === "comment",
(s) => s.type === "comment",
);
if (commentSections.length > 0) {
const lastComment = commentSections[commentSections.length - 1];
@@ -675,47 +663,102 @@ export function getNestedFileDependencyGraph(
}
}
if (startLine !== -1) {
for (const link of cache.links) {
if (
link.position.start.line <= startLine ||
link.position.start.line >= endLine ||
(usingCommentFallback && link.position.start.col <= 12)
) {
continue;
}
if (startLine === -1) {
adjacencyList.set(file, []);
return;
}
const linkpath = link.link.split("|")[0].split("#")[0];
const linkedFile = plugin.app.metadataCache.getFirstLinkpathDest(
linkpath,
file.path,
);
if (!linkedFile) {
continue;
}
// 3. Filter the links within the bounds
const embeddedLinks = cache.links.filter(
(link) =>
link.position.start.line > startLine &&
link.position.start.line < endLine,
);
for (const link of embeddedLinks) {
// Skip text elements and element links in commented blocks (heuristic)
if (usingCommentFallback && link.position.start.col <= 12) {
continue;
}
// Strip any alias (|) or block/header reference (#) to get the raw file path
const linkpath = link.link.split("|")[0].split("#")[0];
const linkedFile = app.metadataCache.getFirstLinkpathDest(
linkpath,
file.path,
);
if (linkedFile) {
if (plugin.isExcalidrawFile(linkedFile)) {
uniqueChildren.set(linkedFile.path, linkedFile);
pending.push(linkedFile);
parseFile(linkedFile); // Recurse to build the DAG
} else if (includeImages) {
uniqueChildren.set(linkedFile.path, linkedFile);
if (!context.nodes.has(linkedFile.path)) {
context.nodes.set(linkedFile.path, {
value: linkedFile,
childKeys: [],
});
}
// We do not recurse into non-Excalidraw files
}
}
}
context.nodes.set(file.path, {
value: file,
childKeys: Array.from(uniqueChildren.keys()),
});
dependencyEdges += uniqueChildren.size;
adjacencyList.set(file, Array.from(uniqueChildren.values()));
}
return context;
// Populate the adjacency list
parseFile(rootFile);
const parseElapsedMs = nestedDependencyElapsedMs(traversalStartedAt);
// Phase 2: Generate the paths from the in-memory Adjacency List
const result: NestedFileMap = new Map();
// Use a stack to perform a depth-first traversal of the DAG
const stack: { file: TFile; path: TFile[] }[] = [
{ file: rootFile, path: [rootFile] },
];
let generatedPaths = 0;
let maximumDepth = 0;
while (stack.length > 0) {
const { file, path } = stack.pop();
const children = adjacencyList.get(file) || [];
for (const child of children) {
// Cycle detection: If the child is already in the current path, skip it.
if (path.includes(child)) {
continue;
}
const childPath = [...path, child];
let node = result.get(child);
if (!node) {
node = { file: child, paths: [] };
result.set(child, node);
}
node.paths.push(childPath);
generatedPaths++;
maximumDepth = Math.max(maximumDepth, childPath.length - 1);
// Push to stack to continue generating paths for its children
stack.push({ file: child, path: childPath });
}
}
const totalElapsedMs = nestedDependencyElapsedMs(traversalStartedAt);
recordNestedTreeDiagnostic({
callSite: diagnosticCallSite,
includeImages,
uniqueFiles: result.size + 1,
parsedDrawings: parsedFiles.size,
dependencyEdges,
generatedPaths,
maximumDepth,
parseMs: parseElapsedMs,
pathsMs: Math.round((totalElapsedMs - parseElapsedMs) * 10) / 10,
totalMs: totalElapsedMs,
});
return result;
}
export const getExcalidrawEmbeddedFilesFiletree = (
@@ -726,31 +769,40 @@ export const getExcalidrawEmbeddedFilesFiletree = (
return [];
}
const graph = getNestedFileDependencyGraph(plugin, sourceFile, true);
return collectReachableDependencyValues(graph, sourceFile.path);
const result = getAllNestedExcalidrawFiles(
plugin,
sourceFile,
true,
"ea-filetree",
);
return Array.from(result.keys());
};
export const hasExcalidrawEmbeddedImagesTreeChanged = (
sourceFile: TFile,
mtime: number,
plugin: ExcalidrawPlugin,
sharedContext?: NestedFileDependencyGraphContext,
diagnosticCallSite = "cache-validation",
): boolean => {
if (!sourceFile || !plugin.isExcalidrawFile(sourceFile)) {
return false;
}
const graph = getNestedFileDependencyGraph(
// Include ordinary vault files because they may be Markdown-image sources
// nested inside an otherwise unchanged Excalidraw drawing.
const nestedTree = getAllNestedExcalidrawFiles(
plugin,
sourceFile,
true,
sharedContext,
);
return hasReachableDependency(
graph,
sourceFile.path,
(file) => file.stat.mtime > mtime,
diagnosticCallSite,
);
for (const file of nestedTree.keys()) {
if (file.stat.mtime > mtime) {
return true;
}
}
return false;
};
export async function exportImageToFile(
+91
View File
@@ -0,0 +1,91 @@
import { log } from "./debugHelper";
/**
* Temporary aggregate timing diagnostics for issue #2932. Each event is one
* copyable string and deliberately excludes vault paths and file contents.
* Remove this module and its call sites before merging a production fix.
*/
export const NESTED_DEPENDENCY_DIAGNOSTIC_PREFIX = "EXCALIDRAW_NESTED_2932";
let diagnosticSequence = 0;
type NestedTreeDiagnostic = {
callSite: string;
includeImages: boolean;
uniqueFiles: number;
parsedDrawings: number;
dependencyEdges: number;
generatedPaths: number;
maximumDepth: number;
parseMs: number;
pathsMs: number;
totalMs: number;
};
type TreeSummary = {
calls: number;
totalMs: number;
maximumMs: number;
totalGeneratedPaths: number;
maximumGeneratedPaths: number;
maximumDepth: number;
lastLoggedAt: number;
};
const treeSummaries = new Map<string, TreeSummary>();
export function logNestedDependencyDiagnostic(details: string): void {
log(
`${NESTED_DEPENDENCY_DIAGNOSTIC_PREFIX} seq=${++diagnosticSequence} ${details}`,
);
}
export function nestedDependencyElapsedMs(startedAt: number): number {
return Math.round((performance.now() - startedAt) * 10) / 10;
}
/** Log first/slow traversals and bounded cumulative summaries of quick ones. */
export function recordNestedTreeDiagnostic(event: NestedTreeDiagnostic): void {
const now = performance.now();
const summary = treeSummaries.get(event.callSite) ?? {
calls: 0,
totalMs: 0,
maximumMs: 0,
totalGeneratedPaths: 0,
maximumGeneratedPaths: 0,
maximumDepth: 0,
lastLoggedAt: now,
};
summary.calls++;
summary.totalMs += event.totalMs;
summary.maximumMs = Math.max(summary.maximumMs, event.totalMs);
summary.totalGeneratedPaths += event.generatedPaths;
summary.maximumGeneratedPaths = Math.max(
summary.maximumGeneratedPaths,
event.generatedPaths,
);
summary.maximumDepth = Math.max(summary.maximumDepth, event.maximumDepth);
treeSummaries.set(event.callSite, summary);
if (summary.calls === 1 || event.totalMs >= 100) {
logNestedDependencyDiagnostic(
`phase=tree callSite=${event.callSite} includeImages=${Number(event.includeImages)} ` +
`uniqueFiles=${event.uniqueFiles} parsedDrawings=${event.parsedDrawings} ` +
`dependencyEdges=${event.dependencyEdges} generatedPaths=${event.generatedPaths} ` +
`maximumDepth=${event.maximumDepth} parseMs=${event.parseMs} ` +
`pathsMs=${event.pathsMs} totalMs=${event.totalMs}`,
);
}
if (summary.calls % 25 === 0 || (summary.calls > 1 && now - summary.lastLoggedAt >= 2000)) {
logNestedDependencyDiagnostic(
`phase=tree-summary callSite=${event.callSite} calls=${summary.calls} ` +
`cumulativeMs=${Math.round(summary.totalMs * 10) / 10} ` +
`maximumMs=${summary.maximumMs} ` +
`cumulativePaths=${summary.totalGeneratedPaths} ` +
`maximumPaths=${summary.maximumGeneratedPaths} ` +
`maximumDepth=${summary.maximumDepth}`,
);
summary.lastLoggedAt = now;
}
}
-137
View File
@@ -1,137 +0,0 @@
export interface DependencyGraphNode<T> {
value: T;
childKeys: readonly string[];
}
export interface DependencyGraph<T> {
nodes: ReadonlyMap<string, DependencyGraphNode<T>>;
}
/**
* Returns each dependency reachable from rootKey once, excluding the root.
*/
export function collectReachableDependencyValues<T>(
graph: DependencyGraph<T>,
rootKey: string,
): T[] {
const root = graph.nodes.get(rootKey);
if (!root) {
return [];
}
const values: T[] = [];
const visited = new Set<string>([rootKey]);
const pending = [rootKey];
while (pending.length > 0) {
const key = pending.pop();
if (!key) {
continue;
}
const node = graph.nodes.get(key);
if (!node) {
continue;
}
for (const childKey of node.childKeys) {
if (visited.has(childKey)) {
continue;
}
visited.add(childKey);
const child = graph.nodes.get(childKey);
if (!child) {
continue;
}
values.push(child.value);
pending.push(childKey);
}
}
return values;
}
/**
* Tests each reachable dependency at most once and stops at the first match.
*/
export function hasReachableDependency<T>(
graph: DependencyGraph<T>,
rootKey: string,
predicate: (value: T) => boolean,
): boolean {
const root = graph.nodes.get(rootKey);
if (!root) {
return false;
}
const visited = new Set<string>([rootKey]);
const pending = [...root.childKeys];
while (pending.length > 0) {
const key = pending.pop();
if (!key || visited.has(key)) {
continue;
}
visited.add(key);
const node = graph.nodes.get(key);
if (!node) {
continue;
}
if (predicate(node.value)) {
return true;
}
pending.push(...node.childKeys);
}
return false;
}
/**
* Returns the root's requested direct dependencies that contain a matching
* file anywhere in their reachable subgraph. Cycles and shared descendants
* are visited once per top-level dependency; distinct dependency paths are
* deliberately never materialized.
*/
export function getMatchingTopLevelDependencyKeys<T>(
graph: DependencyGraph<T>,
rootKey: string,
requestedTopLevelKeys: ReadonlySet<string>,
predicate: (value: T) => boolean,
): Set<string> {
const matchingTopLevelKeys = new Set<string>();
const root = graph.nodes.get(rootKey);
if (!root || requestedTopLevelKeys.size === 0) {
return matchingTopLevelKeys;
}
for (const topLevelKey of root.childKeys) {
if (
!requestedTopLevelKeys.has(topLevelKey) ||
matchingTopLevelKeys.has(topLevelKey)
) {
continue;
}
// Exclude the root even when a nested drawing links back to it.
const visited = new Set<string>([rootKey]);
const pending = [topLevelKey];
while (pending.length > 0) {
const key = pending.pop();
if (!key || visited.has(key)) {
continue;
}
visited.add(key);
const node = graph.nodes.get(key);
if (!node) {
continue;
}
if (predicate(node.value)) {
matchingTopLevelKeys.add(topLevelKey);
break;
}
pending.push(...node.childKeys);
}
}
return matchingTopLevelKeys;
}
+6 -21
View File
@@ -582,27 +582,12 @@ export const foldExcalidrawSection = (view: MarkdownView) => {
}
};
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 setExcalidrawView(leaf: WorkspaceLeaf) {
await leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state: leaf.view.getState(),
popstate: true,
} as ViewState);
}
export async function closeLeafView(leaf: WorkspaceLeaf) {
+159 -566
View File
@@ -1,515 +1,107 @@
import {
normalizePath,
Notice,
request,
TFile,
TFolder,
type App,
} from "obsidian";
import { TFile, Notice, request } from "obsidian";
import { SCRIPT_INSTALL_FOLDER } from "src/constants/constants";
import { URLs } from "src/constants/safeUrls";
import { t } from "src/lang/helpers";
import type { RemoteDirectoryInfo } from "src/types/githubTypes";
import type { ScriptStoreInstallState } from "src/types/scriptStoreTypes";
import { RemoteDirectoryInfo } from "src/types/githubTypes";
import { ExcalidrawSidepanelView } from "src/view/sidepanel/Sidepanel";
import { errorlog } from "./coreUtils";
import { createOrOverwriteFile, getIMGFilename } from "./fileUtils";
import { getIMGFilename, createOrOverwriteFile } from "./fileUtils";
import { hideElement, setButtonBgColor, showElement } from "./styleUtils";
import type ExcalidrawPlugin from "src/core/main";
import {
getManagedScriptFileExtension,
getPreferredScriptFiles,
getScriptFileStem,
isScriptFilePath,
} from "./scriptFileUtils";
type ScriptLibrarySettings = {
scriptFolderPath: string;
allowJavaScriptFiles: boolean;
storeScriptFilesAsJavaScript: boolean;
};
type ScriptLibraryScriptEngine = {
getScriptName(file: TFile | string): string;
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>;
};
/** Narrow plugin surface required by the community-script library helpers. */
export type ScriptLibraryPluginContext = {
app: App;
settings: ScriptLibrarySettings;
scriptEngine: ScriptLibraryScriptEngine;
};
const REMOTE_METADATA_CACHE_TTL = 15 * 60 * 1000;
let directoryInfoPromise: Promise<Map<string, number> | null> | null = null;
let directoryInfoFetchedAt = 0;
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null;
const isRemoteDirectoryInfo = (value: unknown): value is RemoteDirectoryInfo =>
isRecord(value) &&
typeof value.fname === "string" &&
typeof value.mtime === "number";
const getDownloadedScriptsFolder = (
plugin: ScriptLibraryPluginContext,
): string =>
normalizePath(
`${plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`,
);
const decodeRemoteFilename = (source: string): string => {
try {
const decodedURI = decodeURI(source);
return decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
} catch (error: unknown) {
errorlog({
where: "scriptLibraryUtils.decodeRemoteFilename",
source,
error,
});
return source.substring(source.lastIndexOf("/") + 1);
}
};
const sortManagedCopies = (
plugin: ScriptLibraryPluginContext,
files: TFile[],
): TFile[] => {
const root = getDownloadedScriptsFolder(plugin);
return [...files].sort((a, b) => {
const aRelative = a.path.slice(root.length + 1);
const bRelative = b.path.slice(root.length + 1);
const aDepth = aRelative.split("/").length - 1;
const bDepth = bRelative.split("/").length - 1;
return aDepth - bDepth || a.path.localeCompare(b.path);
});
};
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);
return getManagedScriptFilesByStem(plugin).get(stem) ?? [];
};
const getLocalScriptFile = (
plugin: ScriptLibraryPluginContext,
remoteFilename: string,
): TFile | null => getLocalScriptFiles(plugin, remoteFilename)[0] ?? null;
/** Returns all managed local copies for one community script. */
export const getInstalledScriptFiles = (
plugin: ScriptLibraryPluginContext,
export const installButton = async (
plugin: ExcalidrawPlugin,
button: HTMLButtonElement,
button2: HTMLButtonElement,
source: string,
): TFile[] => getLocalScriptFiles(plugin, decodeRemoteFilename(source));
/**
* Returns the primary managed local copy for one community script.
* A copy directly under Downloaded wins; otherwise the shallowest grouped copy
* is used. Additional copies are intentionally ignored for update detection.
*/
export const getInstalledScriptFile = (
plugin: ScriptLibraryPluginContext,
source: string,
): TFile | null => getInstalledScriptFiles(plugin, source)[0] ?? null;
/** Returns existing group folders relative to the Downloaded folder. */
export const getInstalledScriptGroups = (
plugin: ScriptLibraryPluginContext,
): string[] => {
const rootPath = getDownloadedScriptsFolder(plugin);
const root = plugin.app.vault.getFolderByPath(rootPath);
if (!root) {
return [];
}
const groups: string[] = [];
const visit = (folder: TFolder): void => {
folder.children.forEach((child) => {
if (!(child instanceof TFolder)) {
return;
}
groups.push(child.path.slice(rootPath.length + 1));
visit(child);
});
};
visit(root);
return groups.sort((a, b) => a.localeCompare(b));
};
const getManagedScriptFile = (
plugin: ScriptLibraryPluginContext,
source: string,
localPath?: string,
): TFile | null => {
const files = getInstalledScriptFiles(plugin, source);
if (!localPath) {
return files[0] ?? null;
}
const normalizedPath = normalizePath(localPath);
return files.find((file) => file.path === normalizedPath) ?? null;
};
const ensureFolderPath = async (
plugin: ScriptLibraryPluginContext,
folderPath: string,
): Promise<void> => {
const normalized = normalizePath(folderPath);
const parts = normalized.split("/").filter(Boolean);
let current = "";
for (const part of parts) {
current = current ? `${current}/${part}` : part;
if (plugin.app.vault.getFolderByPath(current)) {
continue;
) => {
const setButtonText = (
text: "CHECKING" | "INSTALL" | "UPTODATE" | "UPDATE" | "ERROR",
) => {
if (button2) {
hideElement(button2);
}
if (plugin.app.vault.getFileByPath(current)) {
throw new Error(
`Cannot create script group because a file exists at ${current}`,
);
}
await plugin.app.vault.createFolder(current);
}
};
/** Moves an installed script and its optional icon to a relative script group. */
export const moveInstalledScriptToGroup = async (
plugin: ScriptLibraryPluginContext,
source: string,
relativeGroup: string,
localPath?: string,
): Promise<TFile> => {
const scriptFile = getManagedScriptFile(plugin, source, localPath);
if (!scriptFile) {
throw new Error("Script is not installed");
}
const root = getDownloadedScriptsFolder(plugin);
const requestedGroup = relativeGroup.trim();
const group = requestedGroup ? normalizePath(requestedGroup) : "";
const destinationFolder = group ? normalizePath(`${root}/${group}`) : root;
if (destinationFolder !== root && !destinationFolder.startsWith(`${root}/`)) {
throw new Error("Invalid script group");
}
await ensureFolderPath(plugin, destinationFolder);
const destinationPath = normalizePath(
`${destinationFolder}/${scriptFile.name}`,
);
if (destinationPath === scriptFile.path) {
return scriptFile;
}
const destinationStem = getScriptFileStem(scriptFile.name);
const conflictingScript = ["md", "js"]
.map((extension) =>
plugin.app.vault.getFileByPath(
normalizePath(`${destinationFolder}/${destinationStem}.${extension}`),
),
)
.find((file) => file && file.path !== scriptFile.path);
if (conflictingScript) {
throw new Error("A script with this name already exists in that group");
}
const sourceIconPath = getIMGFilename(scriptFile.path, "svg");
const destinationIconPath = getIMGFilename(destinationPath, "svg");
const iconFile = plugin.app.vault.getFileByPath(sourceIconPath);
if (iconFile && plugin.app.vault.getFileByPath(destinationIconPath)) {
throw new Error(
"A script icon with this name already exists in that group",
);
}
let iconMoved = false;
try {
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.scriptEngine.withScriptFileEventsSuspended(async () => {
await plugin.app.fileManager.renameFile(movedIcon, sourceIconPath);
});
} catch (rollbackError: unknown) {
errorlog({
where: "scriptLibraryUtils.moveInstalledScriptToGroup.rollback",
source: destinationIconPath,
error: rollbackError,
});
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;
}
throw error;
}
};
return plugin.app.vault.getFileByPath(destinationPath) ?? scriptFile;
};
/** Removes an installed community script and its optional local icon. */
export const uninstallScript = async (
plugin: ScriptLibraryPluginContext,
source: string,
localPath?: string,
): Promise<void> => {
const scriptFile = getManagedScriptFile(plugin, source, localPath);
if (!scriptFile) {
return;
}
const iconFile = plugin.app.vault.getFileByPath(
getIMGFilename(scriptFile.path, "svg"),
);
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.removeManagedScriptFile(scriptPath, scriptName);
};
const getDirectoryInfo = async (): Promise<Map<string, number> | null> => {
if (
!directoryInfoPromise ||
Date.now() - directoryInfoFetchedAt > REMOTE_METADATA_CACHE_TTL
) {
directoryInfoFetchedAt = Date.now();
directoryInfoPromise = (async () => {
try {
const parsed: unknown = JSON.parse(
await request({
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
}),
) as unknown;
if (!Array.isArray(parsed)) {
return null;
}
const files = new Map<string, number>();
parsed.forEach((entry: unknown) => {
if (isRemoteDirectoryInfo(entry)) {
files.set(entry.fname, entry.mtime);
}
});
return files.size > 0 ? files : null;
} catch (error: unknown) {
errorlog({
where: "scriptLibraryUtils.getDirectoryInfo",
error,
});
return null;
}
})();
}
return await directoryInfoPromise;
};
const getInstallStateFromDirectoryInfo = (
plugin: ScriptLibraryPluginContext,
scriptFile: TFile,
remoteFilename: string,
files: Map<string, number>,
): ScriptStoreInstallState => {
if (!files.has(remoteFilename)) {
return "error";
}
const scriptMtime = files.get(remoteFilename) ?? 0;
if (scriptMtime > scriptFile.stat.mtime) {
return "update";
}
const iconFilename = getIMGFilename(remoteFilename, "svg");
const iconMtime = files.get(iconFilename);
if (!iconMtime) {
return "up-to-date";
}
const iconFile = plugin.app.vault.getFileByPath(
getIMGFilename(scriptFile.path, "svg"),
);
return !iconFile || iconMtime > iconFile.stat.mtime
? "update"
: "up-to-date";
};
/**
* 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> =>
(await getScriptInstallStates(plugin, [source])).get(source) ?? "error";
const restartSidepanelTabIfActive = async (
plugin: ScriptLibraryPluginContext,
scriptFile: TFile,
): Promise<void> => {
const scriptName = plugin.scriptEngine.getScriptName(scriptFile);
const spView = ExcalidrawSidepanelView.getExisting(false);
if (!spView || !scriptName || !spView.getTabByScript(scriptName)) {
return;
}
button.addClass("mod-muted");
let decodedURI = source;
try {
await spView.restartTabForScript(scriptName);
} catch (error: unknown) {
decodedURI = decodeURI(source);
} catch (e: unknown) {
errorlog({
where: "scriptLibraryUtils.restartSidepanelTabIfActive",
error,
scriptName,
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
source,
error: e,
});
}
};
export type InstalledScriptResult = {
scriptFile: TFile;
iconFile: TFile | null;
};
/** Installs or updates one managed community script. */
export const installScript = async (
plugin: ScriptLibraryPluginContext,
source: string,
showNotice = true,
): Promise<InstalledScriptResult> => {
const remoteFilename = decodeRemoteFilename(source);
const scriptStem = getScriptFileStem(remoteFilename);
const folder = getDownloadedScriptsFolder(plugin);
let scriptFile = getLocalScriptFile(plugin, remoteFilename);
const getLocalScriptPath = (): string => {
const targetFolder = scriptFile?.parent?.path ?? folder;
return `${targetFolder}/${scriptStem}.${getManagedScriptFileExtension(
const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
const scriptStem = getScriptFileStem(fname);
const folder = `${plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
const getLocalScriptPath = (): string =>
`${folder}/${scriptStem}.${getManagedScriptFileExtension(
plugin.settings.allowJavaScriptFiles,
plugin.settings.storeScriptFilesAsJavaScript,
)}`;
};
let scriptFile =
plugin.app.vault.getFileByPath(`${folder}/${scriptStem}.md`) ??
plugin.app.vault.getFileByPath(`${folder}/${scriptStem}.js`);
let scriptPath = getLocalScriptPath();
let iconFile = plugin.app.vault.getFileByPath(
getIMGFilename(scriptPath, "svg"),
);
const svgPath = getIMGFilename(scriptPath, "svg");
let svgFile = plugin.app.vault.getFileByPath(svgPath);
setButtonText(scriptFile ? "CHECKING" : "INSTALL");
button.onclick = async () => {
const download = async (
url: string,
file: TFile,
localPath: string,
): Promise<TFile> => {
const data = await request({ url });
if (!data || data.startsWith("404: Not Found")) {
return null;
}
return await createOrOverwriteFile(
plugin.app,
file?.path ?? localPath,
data,
);
};
const fetchRemote = async (url: string): Promise<string | null> => {
const data = await request({ url });
if (!data || data.startsWith("404: Not Found")) {
return null;
}
return data;
};
try {
const [scriptData, iconData] = await Promise.all([
fetchRemote(source),
fetchRemote(getIMGFilename(source, "svg")),
]);
if (!scriptData) {
throw new Error("Script file not found");
}
await plugin.scriptEngine.withScriptFileEventsSuspended(async () => {
try {
scriptPath = getLocalScriptPath();
if (scriptFile && scriptFile.path !== scriptPath) {
if (plugin.app.vault.getFileByPath(scriptPath)) {
// Keep the authoritative Markdown variant when both extensions
// already exist; format migration reports and skips this pair.
scriptPath = scriptFile.path;
} else {
await plugin.scriptEngine.renameManagedScriptFile(
@@ -518,95 +110,96 @@ export const installScript = async (
);
}
}
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;
scriptFile = await download(source, scriptFile, scriptPath);
if (!scriptFile) {
setButtonText("ERROR");
throw new Error("File not found");
}
});
if (!scriptFile) {
throw new Error("Script file was not created");
svgFile = await download(getIMGFilename(source, "svg"), svgFile, svgPath);
setButtonText("UPTODATE");
if (Object.keys(plugin.scriptEngine.scriptIconMap).length === 0) {
await plugin.scriptEngine.loadScripts();
}
const restartSidepanelTabIfActive = async () => {
if (!plugin.scriptEngine || !(scriptFile instanceof TFile)) {
return;
}
const scriptName = plugin.scriptEngine.getScriptName(scriptFile);
const spView = ExcalidrawSidepanelView.getExisting(false);
if (!spView || !scriptName || !spView.getTabByScript(scriptName)) {
return;
}
try {
await spView.restartTabForScript(scriptName);
} catch (error: unknown) {
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.restartSidepanelTab",
error,
scriptName,
});
}
};
await restartSidepanelTabIfActive();
new Notice(`Installed: ${scriptFile.basename}`);
} catch (e: unknown) {
new Notice(`Error installing script: ${fname}`);
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
error: e,
});
}
await plugin.scriptEngine.refreshManagedScriptFile(scriptFile);
await restartSidepanelTabIfActive(plugin, scriptFile);
if (showNotice) {
new Notice(`${t("SCRIPT_INSTALLED_NOTICE")}: ${scriptFile.basename}`);
}
return { scriptFile, iconFile };
} catch (error: unknown) {
if (showNotice) {
new Notice(`${t("SCRIPT_INSTALL_ERROR_NOTICE")}: ${remoteFilename}`);
}
errorlog({
where: "scriptLibraryUtils.installScript",
source,
error,
});
throw error;
};
if (button2) {
button2.onclick = button.onclick;
}
};
/**
* Returns community scripts with updates, considering only managed copies under
* the Downloaded folder. When duplicate managed copies exist, update detection
* uses the same primary-copy selection as the script-store details page.
*/
export const getInstalledScriptUpdates = async (
plugin: ScriptLibraryPluginContext,
): Promise<string[]> => {
if (!plugin.settings.scriptFolderPath) {
return [];
//check modified date on github
//https://superuser.com/questions/1406875/how-to-get-the-latest-commit-date-of-a-file-from-a-given-github-reposotiry
if (!scriptFile || !(scriptFile instanceof TFile)) {
return;
}
const copiesByStem = getManagedScriptFilesByStem(plugin);
if (copiesByStem.size === 0) {
return [];
}
const files = await getDirectoryInfo();
if (!files) {
return [];
}
const files = new Map<string, number>();
const directoryInfo = JSON.parse(
await request({
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
}),
) as RemoteDirectoryInfo[];
directoryInfo.forEach((file) => files.set(file.fname, file.mtime));
const updates: string[] = [];
copiesByStem.forEach((copies, stem) => {
const scriptFile = copies[0];
if (!scriptFile) {
return;
const checkModifyDate = (
gitFilename: string,
file: TFile,
): "ERROR" | "UPDATE" | "UPTODATE" => {
if (files.size === 0 || !files.has(gitFilename)) {
//setButtonText("ERROR");
return "ERROR";
}
const remoteFilename = files.has(`${stem}.md`)
? `${stem}.md`
: files.has(`${stem}.js`)
? `${stem}.js`
: null;
if (!remoteFilename) {
return;
const mtime = files.get(gitFilename);
if (!file || mtime > file.stat.mtime) {
//setButtonText("UPDATE");
return "UPDATE";
}
if (
getInstallStateFromDirectoryInfo(
plugin,
scriptFile,
remoteFilename,
files,
) === "update"
) {
updates.push(stem);
}
});
return "UPTODATE";
};
const scriptButtonText = checkModifyDate(fname, scriptFile);
const svgButtonText = checkModifyDate(
getIMGFilename(fname, "svg"),
!svgFile || !(svgFile instanceof TFile) ? null : svgFile,
);
return updates.sort((a, b) => a.localeCompare(b));
setButtonText(
scriptButtonText === "UPTODATE" && svgButtonText === "UPTODATE"
? "UPTODATE"
: scriptButtonText === "UPTODATE" && svgButtonText === "ERROR"
? "UPTODATE"
: scriptButtonText === "ERROR"
? "ERROR"
: scriptButtonText === "UPDATE" || svgButtonText === "UPDATE"
? "UPDATE"
: "UPTODATE",
);
};
+50 -5
View File
@@ -16,6 +16,7 @@ import {
getCommonBoundingBox,
DEVICE,
getContainerElement,
SCRIPT_INSTALL_FOLDER,
VIEW_TYPE_EXCALIDRAW,
} from "../constants/constants";
import type ExcalidrawPlugin from "../core/main";
@@ -45,13 +46,18 @@ import { VersionMismatchPrompt } from "src/shared/Dialogs/VersionMismatch";
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
import { FileData } from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
import { RemoteDirectoryInfo } from "src/types/githubTypes";
import { UIMode } from "src/shared/Dialogs/UIModeSettingComponent";
import ExcalidrawView from "../view/ExcalidrawView";
import { getEmptyDrawingElementsRuntime } from "src/constants/emptydrawing";
import { makeEntitiesXmlSafe, sanitizedFragment } from "./htmlUtils";
import { URLs } from "src/constants/safeUrls";
import { isInstanceOfSVGSVGElement } from "./typechecks";
import { getInstalledScriptUpdates } from "./scriptLibraryUtils";
import {
getPreferredScriptFiles,
getScriptFileStem,
isScriptFilePath,
} from "./scriptFileUtils";
export { arrayToMap };
export { errorlog, getDataURL } from "./coreUtils";
export { addAppendUpdateCustomData } from "./elementCustomDataUtils";
@@ -158,11 +164,50 @@ async function checkScriptUpdates() {
return;
}
const updates = await getInstalledScriptUpdates(EXCALIDRAW_PLUGIN);
const folder = `${EXCALIDRAW_PLUGIN.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
const installedScripts = getPreferredScriptFiles(
EXCALIDRAW_PLUGIN.app.vault
.getFiles()
.filter(
(file) => file.parent?.path === folder && isScriptFilePath(file.path),
),
);
if (installedScripts.length === 0) {
return;
}
// Get directory info from GitHub
const files = new Map<string, number>();
const directoryInfo = JSON.parse(
await request({
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
}),
) as RemoteDirectoryInfo[];
directoryInfo.forEach((f: RemoteDirectoryInfo) =>
files.set(f.fname, f.mtime),
);
if (files.size === 0) {
return;
}
// Check if any installed scripts have updates
const updates: string[] = [];
for (const scriptFile of installedScripts) {
const stem = getScriptFileStem(scriptFile.name);
const remoteMtime = Math.max(
files.get(`${stem}.md`) ?? 0,
files.get(`${stem}.js`) ?? 0,
);
if (remoteMtime > scriptFile.stat.mtime) {
updates.push(stem);
}
}
if (updates.length > 0) {
const message = `${t("SCRIPT_UPDATES_AVAILABLE")}\n\n${updates.join("\n")}`;
const timeout = Math.min(60_000, 30_000 + updates.length * 2_000);
new Notice(message, timeout);
const message = `${t("SCRIPT_UPDATES_AVAILABLE")}\n\n${updates.sort().join("\n")}`;
new Notice(message, 8000 + updates.length * 1000);
log(message);
}
} catch (e: unknown) {
+3 -33
View File
@@ -1,4 +1,4 @@
import { App, FileView, WorkspaceLeaf, type ViewStateResult } from "obsidian";
import { App, FileView, WorkspaceLeaf } from "obsidian";
import { DEVICE, VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
@@ -18,11 +18,6 @@ export async function switchToExcalidraw(app: App) {
}
export class ExcalidrawLoading extends FileView {
private integrationState: {
mode?: "view" | "edit";
zoomToFit?: true;
} = {};
constructor(
leaf: WorkspaceLeaf,
private plugin: ExcalidrawPlugin,
@@ -35,44 +30,19 @@ 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;
}
+18 -87
View File
@@ -56,11 +56,7 @@ import {
sceneCoordsToViewportCoords,
} from "../constants/constants";
import ExcalidrawPlugin from "../core/main";
import {
ExcalidrawAutomate,
type ViewLinkClickHook,
} from "../shared/ExcalidrawAutomate";
import type { PaneTarget } from "../types/utilTypes";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import { TextMode, getTextMode } from "../shared/TextMode";
import { ExcalidrawSidepanelView } from "./sidepanel/Sidepanel";
import {
@@ -582,8 +578,6 @@ 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;
@@ -1684,22 +1678,8 @@ export default class ExcalidrawView
element: ExcalidrawElement,
link: string,
event: MouseEvent | null,
action?: PaneTarget,
): boolean {
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);
return this.linkNavigationManager.handleLinkHookCall(element, link, event);
}
private getLinkTextForElement(
@@ -3003,9 +2983,6 @@ 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);
}
@@ -4031,21 +4008,16 @@ 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 = requestedViewModeEnabled ?? (
!this.isLoaded
? excalidrawData.elements.length > 0
? om.viewModeEnabled
: false
: api.getAppState().viewModeEnabled
);
const viewModeEnabled = !this.isLoaded
? excalidrawData.elements.length > 0
? om.viewModeEnabled
: false
: api.getAppState().viewModeEnabled;
const zenModeEnabled = !this.isLoaded
? om.zenModeEnabled
: api.getAppState().zenModeEnabled;
@@ -4053,16 +4025,11 @@ export default class ExcalidrawView
this.updateScene(
{
elements: excalidrawData.elements.concat(deletedElements ?? []), //need to preserve deleted elements during autosave if images, links, etc. are updated
files: excalidrawData.files,
captureUpdate: CaptureUpdateAction.NEVER,
},
justloaded,
);
// updateScene() does not accept binary files. Legacy/external scenes may
// have no other source for their embedded image data.
const files = Object.values(excalidrawData.files ?? {});
if (files.length > 0) {
api.addFiles(files);
}
this.updateScene({
//elements: excalidrawData.elements.concat(deletedElements??[]), //need to preserve deleted elements during autosave if images, links, etc. are updated
appState: {
@@ -4132,9 +4099,8 @@ export default class ExcalidrawView
}
: {}),
zenModeEnabled: om.zenModeEnabled,
viewModeEnabled: requestedViewModeEnabled ?? (
excalidrawData.elements.length > 0 ? om.viewModeEnabled : false
),
viewModeEnabled:
excalidrawData.elements.length > 0 ? om.viewModeEnabled : false,
linkOpacity: this.excalidrawData.getLinkOpacity(),
penMode: penEnabled,
penDetected: penEnabled,
@@ -4527,7 +4493,7 @@ export default class ExcalidrawView
return ICON_NAME;
}
async setMarkdownView(eState?: MarkdownViewOpenState, active?: boolean) {
async setMarkdownView(eState?: MarkdownViewOpenState) {
//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
@@ -4560,11 +4526,7 @@ export default class ExcalidrawView
}
plugin.excalidrawFileModes[this.id || file.path] = "markdown";
await plugin.setMarkdownView(
leaf,
eState as ViewStateResult | undefined,
active,
);
await plugin.setMarkdownView(leaf, eState as ViewStateResult | undefined);
} catch (e: unknown) {
errorlog({
where: "ExcalidrawView.setMarkdownView",
@@ -4574,7 +4536,7 @@ export default class ExcalidrawView
}
}
public async openAsMarkdown(eState?: MarkdownViewOpenState, active?: boolean) {
public async openAsMarkdown(eState?: MarkdownViewOpenState) {
if (
this.plugin.settings.compress &&
this.plugin.settings.decompressForMDView
@@ -4584,7 +4546,7 @@ export default class ExcalidrawView
} else if (this.isDirty()) {
await this.save(true, true, true);
}
await this.setMarkdownView(eState, active);
void this.setMarkdownView(eState);
}
public async convertExcalidrawToMD() {
@@ -5353,7 +5315,6 @@ 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,
@@ -5362,7 +5323,6 @@ export default class ExcalidrawView
bindingPreference: st.bindingPreference,
isMidpointSnappingEnabled: st.isMidpointSnappingEnabled,
boxSelectionMode: st.boxSelectionMode,
inputDevice: st.inputDevice,
},
prevTextMode: this.prevTextMode,
files,
@@ -5977,24 +5937,11 @@ 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 &&
(pendingOpenZoomToFit || this.plugin.settings.zoomToFitOnOpen)
this.plugin.settings.zoomToFitOnOpen
) {
if (
pendingOpenZoomToFit ||
getExcalidraAndMarkdowViewsForFile(this.app, this.file).length === 1
) {
this.zoomToFit(false, true);
@@ -6724,24 +6671,8 @@ export default class ExcalidrawView
}
window.setTimeout(() => this.removeLinkTooltip(), 500);
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,
)
) {
let event = e?.detail?.nativeEvent;
if (this.handleLinkHookCall(element, link, event as MouseEvent)) {
return;
}
//if(openExternalLink(element.link, this.app, !isSHIFT(event) && !isWinCTRLorMacCMD(event) && !isWinMETAorMacCTRL(event) && !isWinALTorMacOPT(event) ? element : undefined)) return;
@@ -6749,7 +6680,7 @@ export default class ExcalidrawView
return;
}
if (!hasModifier) {
if (!event.shiftKey && !event.ctrlKey && !event.metaKey && !event.altKey) {
void this.linkClick(
null,
null,
+2 -21
View File
@@ -8,14 +8,7 @@ node.render();
container.appendChild(node.contentEl)
*/
import {
type App,
Editor,
TFile,
View,
WorkspaceLeaf,
WorkspaceSplit,
} from "obsidian";
import { Editor, TFile, View, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
import type ExcalidrawView from "src/view/ExcalidrawView";
import {
getContainerForDocument,
@@ -36,12 +29,6 @@ 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;
@@ -96,13 +83,7 @@ export class CanvasNodeFactory {
rootSplit.getRoot = () =>
app.workspace[doc === mainDocument ? "rootSplit" : "floatingSplit"];
rootSplit.getContainer = () => getContainerForDocument(doc);
// `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.leaf = app.workspace.createLeafInParent(rootSplit, 0);
this.canvas = canvasPlugin.views.canvas(this.leaf).canvas as ObsidianCanvas;
this.initialized = true;
}
+1 -45
View File
@@ -16,10 +16,6 @@ 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";
@@ -61,11 +57,6 @@ 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,
@@ -89,9 +80,6 @@ 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 {
@@ -114,41 +102,9 @@ 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,
@@ -594,7 +550,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, linkClickType)) {
if (this.view.handleLinkHookCall(el, linkText, ev)) {
return;
}
+39
View File
@@ -21,6 +21,12 @@ import {
MARKDOWN_IMAGE_CUSTOM_DATA_KEY,
type MarkdownImageCustomData,
} from "../../types/markdownImageTypes";
import {
logNestedDependencyDiagnostic,
nestedDependencyElapsedMs,
} from "../../utils/nestedDependencyDiagnostics";
let sceneLoaderDiagnosticSequence = 0;
/** Runtime dependencies supplied by the composition root to avoid adding a
* circular import.
@@ -246,6 +252,13 @@ export class ViewSceneFileManager {
const fileIDs = new Set(candidates.keys());
const currentFile = this.view.file.path;
const loader = this.dependencies.createEmbeddedFilesLoader();
const diagnosticOperationId = ++sceneLoaderDiagnosticSequence;
const scheduledAt = performance.now();
let emittedFiles = 0;
logNestedDependencyDiagnostic(
`phase=deferred-scheduled operation=${diagnosticOperationId} ` +
`candidates=${candidates.size} sceneCacheEnabled=${Number(this.view.plugin.settings.allowImageCacheInScene)}`,
);
this.deferredValidationFilePath = currentFile;
this.deferredValidationTimer = window.setTimeout(() => {
this.deferredValidationTimer = null;
@@ -257,6 +270,11 @@ export class ViewSceneFileManager {
}
this.deferredValidationLoader = loader;
const startedAt = performance.now();
logNestedDependencyDiagnostic(
`phase=deferred-start operation=${diagnosticOperationId} ` +
`candidates=${candidates.size} waitMs=${nestedDependencyElapsedMs(scheduledAt)}`,
);
// Second pass is intentionally conservative: revalidate only stale-first
// candidates, run one at a time, and emit only regenerated images.
void loader.loadSceneFiles({
@@ -277,12 +295,18 @@ export class ViewSceneFileManager {
return;
}
if (files && files.length > 0) {
emittedFiles += files.length;
void this.dependencies.addFiles(files, this.view, isDark);
}
if (!final) {
return;
}
this.view.lastSceneLoadTime = Date.now();
logNestedDependencyDiagnostic(
`phase=deferred-complete operation=${diagnosticOperationId} ` +
`candidates=${candidates.size} emittedFiles=${emittedFiles} ` +
`wallMs=${nestedDependencyElapsedMs(startedAt)}`,
);
if (this.deferredValidationLoader === loader) {
this.deferredValidationLoader = null;
}
@@ -411,6 +435,15 @@ export class ViewSceneFileManager {
this.nextLoader = null;
this.activeLoader = l;
const prioritizedFileIds = getVisibleImageFileIds(this.view);
const diagnosticOperationId = ++sceneLoaderDiagnosticSequence;
const startedAt = performance.now();
let emittedFiles = 0;
logNestedDependencyDiagnostic(
`phase=initial-start operation=${diagnosticOperationId} ` +
`entries=${Array.from(this.view.excalidrawData.getFileEntries()).length} ` +
`sceneCacheEnabled=${Number(this.view.plugin.settings.allowImageCacheInScene)} ` +
`visibleFileIds=${prioritizedFileIds.size}`,
);
void l.loadSceneFiles({
excalidrawData: this.view.excalidrawData,
sceneElements: this.view.getViewElements(),
@@ -434,12 +467,18 @@ export class ViewSceneFileManager {
callback();
}
if (files && files.length > 0) {
emittedFiles += files.length;
void this.dependencies.addFiles(files, this.view, isDark);
}
if (!final) {
return;
}
this.view.lastSceneLoadTime = Date.now();
logNestedDependencyDiagnostic(
`phase=initial-complete operation=${diagnosticOperationId} ` +
`emittedFiles=${emittedFiles} deferredCandidates=${this.pendingDeferredValidationCandidates.size} ` +
`wallMs=${nestedDependencyElapsedMs(startedAt)}`,
);
if (this.activeLoader === l) {
this.activeLoader = null;
}
-15
View File
@@ -98,18 +98,6 @@ const setBlockReferenceIcon = (button: ButtonComponent): void => {
button.setIcon(BLOCK_REFERENCE_ICON_ID);
};
/**
* Forces a Markdown-image editor view into edit mode, regardless of the
* user's `defaultViewMode` vault setting. Reading mode is not meaningful in
* this embedded editor and leaves the user with no way to switch back.
*/
const forceSourceMode = (view: MarkdownView): void => {
const modes = view.modes;
if (modes?.source) {
view.setMode?.(modes.source);
}
};
const getNativeColorValue = (color: string): string => {
if (/^#[0-9a-f]{6}$/i.test(color)) {
return color;
@@ -1685,7 +1673,6 @@ class MarkdownImageEditorController {
} else {
await leaf.openFile(sourceFile, {
active: false,
state: { mode: "source" },
});
}
if (
@@ -1698,7 +1685,6 @@ class MarkdownImageEditorController {
return;
}
if (leaf.view instanceof MarkdownView) {
forceSourceMode(leaf.view);
this.editorView = leaf.view;
this.prepareEditorView(host, leaf.view);
this.revealExternalSourceSubpath(leaf.view, sourceFile, ref);
@@ -1741,7 +1727,6 @@ class MarkdownImageEditorController {
return;
}
fragmentView.setViewData(source.markdown, true);
forceSourceMode(fragmentView);
this.editorView = fragmentView;
this.prepareEditorView(host, fragmentView);
this.watchEditorChanges();
+130 -831
View File
@@ -1014,6 +1014,10 @@ 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;
@@ -1092,12 +1096,12 @@ End Obsidian Sheets Plus support
min-width: calc(6 * var(--default-button-size));
}
/* 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 {
z-index: var(--layer-menu);
}
/* 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 {
z-index: var(--layer-menu);
}
.excalidraw-pen-settings-floating-actions {
position: sticky;
bottom: -20px;
@@ -1612,828 +1616,123 @@ button.excalidraw-font-picker {
}
.excalidraw-font-picker-menu-opening .menu,
.menu.excalidraw-font-picker-menu--desktop {
max-height: min(420px, 60vh);
overflow-y: auto;
}
.setting-item.excalidraw-declarative-full-width {
display: block;
width: 100%;
}
.excalidraw-declarative-settings-toolbar {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: var(--size-4-2) var(--size-4-3);
margin-bottom: var(--size-4-1);
font-size: var(--font-ui-smaller);
}
.excalidraw-declarative-settings-toolbar button,
.excalidraw-declarative-settings-toolbar a {
white-space: nowrap;
}
.excalidraw-declarative-settings-toolbar button {
font-size: inherit;
}
.excalidraw-declarative-settings-toolbar a {
color: var(--text-accent);
text-decoration: none;
}
.excalidraw-declarative-settings-toolbar a:hover {
color: var(--text-accent-hover);
text-decoration: underline;
}
.excalidraw-settings-breadcrumbs {
display: flex;
align-items: baseline;
justify-content: center;
flex-wrap: wrap;
gap: var(--size-4-1);
margin: 0;
color: var(--text-muted);
font-size: var(--font-ui-small);
}
.excalidraw-settings-breadcrumbs__link {
height: auto;
padding: 0;
border: 0;
background: transparent;
box-shadow: none;
color: var(--text-accent);
cursor: pointer;
font-size: inherit;
font-weight: inherit;
text-decoration: none;
touch-action: manipulation;
}
.excalidraw-settings-breadcrumbs__link:hover {
background: transparent;
box-shadow: none;
color: var(--text-accent-hover);
text-decoration: underline;
}
.excalidraw-settings-breadcrumbs__link.is-disabled {
color: var(--text-muted);
cursor: default;
pointer-events: none;
}
.is-mobile .excalidraw-settings-breadcrumbs__link,
.is-tablet .excalidraw-settings-breadcrumbs__link {
min-height: var(--interactive-normal);
padding-inline: var(--size-2-2);
}
.excalidraw-settings-breadcrumbs__current {
color: var(--text-normal);
font-weight: var(--font-semibold);
}
.excalidraw-settings-breadcrumbs__separator {
color: var(--text-faint);
}
.excalidraw-settings .setting-item-description a[href^="#"],
.excalidraw-settings-page .setting-item-description a[href^="#"] {
color: var(--text-accent);
font-weight: var(--font-medium);
text-decoration: underline;
}
.excalidraw-settings .setting-item-description a[href^="#"]:hover,
.excalidraw-settings-page .setting-item-description a[href^="#"]:hover {
color: var(--text-accent-hover);
}
.excalidraw-filename-information {
display: grid;
grid-template-columns: minmax(12rem, 0.8fr) minmax(18rem, 1.2fr);
gap: var(--size-4-4);
align-items: start;
}
.excalidraw-filename-information> :first-child {
min-width: 0;
}
@media (max-width: 700px) {
.excalidraw-filename-information {
grid-template-columns: 1fr;
}
}
/* Community Script Store */
.excalidraw-script-store .modal {
width: min(1100px, 96vw);
max-width: 1100px;
height: min(900px, 92vh);
max-height: 92vh;
}
.excalidraw-script-store .modal-content {
max-width: none;
user-select: text;
}
.excalidraw-script-store__content {
display: flex;
flex-direction: column;
gap: 1rem;
padding-bottom: 1rem;
}
.excalidraw-script-store__loading {
min-height: 16rem;
display: flex;
align-items: center;
justify-content: center;
gap: 0.75rem;
color: var(--text-muted);
}
.excalidraw-script-store__loading-icon svg {
animation: excalidraw-script-store-spin 1s linear infinite;
}
@keyframes excalidraw-script-store-spin {
to {
transform: rotate(360deg);
}
}
.excalidraw-script-store__support-bar {
display: grid;
grid-template-columns: 1fr 1fr;
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-l);
background: var(--background-secondary);
overflow: hidden;
}
.excalidraw-script-store__support-item {
display: flex;
align-items: center;
gap: 0.75rem;
min-width: 0;
padding: 0.65rem 0.85rem;
color: var(--text-normal);
text-decoration: none;
}
.excalidraw-script-store__support-item+.excalidraw-script-store__support-item {
border-left: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__support-item:hover {
background: var(--background-modifier-hover);
color: var(--text-normal);
text-decoration: none;
}
.excalidraw-script-store__support-logo {
flex: 0 0 auto;
width: 2.75rem;
height: 2.75rem;
object-fit: contain;
border-radius: 50%;
}
.excalidraw-script-store__support-icon {
flex: 0 0 2.75rem;
width: 2.75rem;
height: 2.75rem;
display: flex;
align-items: center;
justify-content: center;
color: var(--interactive-accent);
}
.excalidraw-script-store__support-icon svg {
width: 1.75rem;
height: 1.75rem;
}
.excalidraw-script-store__support-text {
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.1rem;
}
.excalidraw-script-store__support-text strong {
font-size: var(--font-ui-medium);
}
.excalidraw-script-store__support-text span {
color: var(--text-muted);
font-size: var(--font-ui-small);
}
.excalidraw-script-store__scripting-promo {
width: 100%;
}
.excalidraw-script-store__scripting-link {
display: block;
width: min(900px, 100%);
margin: 0 auto;
color: var(--text-normal);
text-decoration: none;
}
.excalidraw-script-store__scripting-link:hover {
color: var(--interactive-accent);
text-decoration: none;
}
.excalidraw-script-store__scripting-banner {
display: block;
width: 100%;
aspect-ratio: 3 / 1;
object-fit: cover;
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-l);
}
.excalidraw-script-store__scripting-caption {
padding: 0.45rem 0.5rem 0;
text-align: center;
font-size: var(--font-ui-small);
font-weight: var(--font-semibold);
}
.excalidraw-script-store__updates {
padding: 0.9rem;
border: 1px solid var(--interactive-accent);
border-radius: var(--radius-l);
background: var(--background-secondary);
}
.excalidraw-script-store__updates-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.excalidraw-script-store__updates h2,
.excalidraw-script-store__browse-header h2 {
margin: 0;
}
.excalidraw-script-store__updates p,
.excalidraw-script-store__browse-header p {
margin: 0.2rem 0 0;
color: var(--text-muted);
}
.excalidraw-script-store__inline-icon {
display: inline-flex;
margin-left: 0.45rem;
vertical-align: text-bottom;
}
.excalidraw-script-store__inline-icon svg {
width: 1em;
height: 1em;
}
.excalidraw-script-store__update-list {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
margin-top: 0.75rem;
}
.excalidraw-script-store__update-chip {
padding: 0.25rem 0.6rem;
border-radius: var(--radius-s);
font-size: var(--font-ui-smaller);
}
.excalidraw-script-store__browse-header {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.excalidraw-script-store__controls {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.excalidraw-script-store__search {
position: relative;
flex: 1 1 18rem;
min-width: 12rem;
}
.excalidraw-script-store__search>span {
position: absolute;
left: 0.65rem;
top: 50%;
transform: translateY(-50%);
display: flex;
color: var(--text-faint);
pointer-events: none;
}
.excalidraw-script-store__search svg {
width: 1rem;
height: 1rem;
}
.excalidraw-script-store__search input {
width: 100%;
padding-left: 2rem;
}
.excalidraw-script-store__controls select {
min-width: 12rem;
}
.excalidraw-script-store__view-toggle {
display: flex;
}
.excalidraw-script-store__view-toggle button {
border-radius: 0;
}
.excalidraw-script-store__view-toggle button:first-child {
border-radius: var(--button-radius) 0 0 var(--button-radius);
}
.excalidraw-script-store__view-toggle button:last-child {
border-radius: 0 var(--button-radius) var(--button-radius) 0;
}
.excalidraw-script-store__view-toggle button.is-active {
background: var(--interactive-accent);
color: var(--text-on-accent);
}
.excalidraw-script-store__result-summary {
margin-bottom: 0.55rem;
color: var(--text-muted);
font-size: var(--font-ui-small);
}
.excalidraw-script-store__grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 0.7rem;
}
.excalidraw-script-store__card {
display: flex;
flex-direction: column;
min-height: 15rem;
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-m);
background: var(--background-primary);
overflow: hidden;
transition:
border-color var(--anim-duration-fast) ease-in-out,
transform var(--anim-duration-fast) ease-in-out;
}
.excalidraw-script-store__card:hover {
border-color: var(--background-modifier-border-hover);
transform: translateY(-1px);
}
.excalidraw-script-store__card.has-update {
border-color: var(--interactive-accent);
}
.excalidraw-script-store__card-main {
flex: 1;
display: flex;
align-items: flex-start;
gap: 0.8rem;
width: 100%;
padding: 0.9rem;
border: 0;
border-radius: 0;
box-shadow: none;
background: transparent;
color: var(--text-normal);
text-align: left;
white-space: normal;
cursor: pointer;
}
.excalidraw-script-store__card-main:hover {
background: var(--background-modifier-hover);
}
.excalidraw-script-store__icon {
position: relative;
flex: 0 0 3.1rem;
width: 3.1rem;
height: 3.1rem;
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--radius-m);
background: var(--background-secondary);
overflow: hidden;
}
.excalidraw-script-store__icon img {
position: relative;
z-index: 1;
width: 2.55rem;
height: 2.55rem;
object-fit: contain;
}
/* Script icons are external SVG images and cannot inherit --icon-fill-color
* like the inline SVGs in the Excalidraw tools panel. Match Excalidraw's
* dark-theme image treatment (THEME_FILTER) so monochrome script icons stay
* legible on dark store backgrounds. */
.theme-dark .excalidraw-script-store__icon img,
.theme-dark .excalidraw-script-store__detail-icon img {
filter: invert(93%) hue-rotate(180deg) saturate(1.25);
}
.excalidraw-script-store__icon img.is-hidden,
.excalidraw-script-store__detail-icon img.is-hidden {
display: none;
}
.excalidraw-script-store__icon-fallback,
.excalidraw-script-store__detail-icon-fallback {
position: absolute;
display: none;
align-items: center;
justify-content: center;
color: var(--text-muted);
}
.excalidraw-script-store__icon-fallback.is-visible,
.excalidraw-script-store__detail-icon-fallback.is-visible {
display: flex;
}
.excalidraw-script-store__card-text {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
}
.excalidraw-script-store__title-row {
display: flex;
align-items: flex-start;
flex-wrap: wrap;
gap: 0.3rem;
}
.excalidraw-script-store__title-row h3 {
flex: 1 1 10rem;
min-width: 0;
margin: 0;
font-size: var(--font-ui-medium);
line-height: 1.25;
white-space: normal;
overflow-wrap: anywhere;
}
.excalidraw-script-store__author {
margin-top: 0.15rem;
color: var(--text-faint);
font-size: var(--font-ui-smaller);
}
.excalidraw-script-store__card-text p {
display: -webkit-box;
margin: 0.55rem 0 0;
overflow: hidden;
color: var(--text-muted);
font-size: var(--font-ui-small);
line-height: 1.45;
white-space: normal;
overflow-wrap: anywhere;
-webkit-box-orient: vertical;
-webkit-line-clamp: 5;
}
.excalidraw-script-store__badge,
.excalidraw-script-store__tag {
display: inline-flex;
align-items: center;
gap: 0.2rem;
padding: 0.12rem 0.4rem;
border-radius: var(--radius-s);
background: var(--background-secondary-alt);
color: var(--text-muted);
font-size: var(--font-ui-smaller);
font-weight: var(--font-medium);
}
.excalidraw-script-store__badge svg {
width: 0.85em;
height: 0.85em;
}
.excalidraw-script-store__badge.has-update,
.excalidraw-script-store__badge.is-featured {
color: var(--interactive-accent);
}
.excalidraw-script-store__card-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
min-height: 3.2rem;
padding: 0.65rem 0.8rem;
border-top: 1px solid var(--background-modifier-border);
background: var(--background-secondary);
}
.excalidraw-script-store__card-footer>span {
min-width: 0;
color: var(--text-faint);
font-size: var(--font-ui-smaller);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.excalidraw-script-store__empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 15rem;
text-align: center;
color: var(--text-muted);
}
.excalidraw-script-store__empty h3 {
margin-bottom: 0;
}
.excalidraw-script-store__back {
align-self: flex-start;
display: inline-flex;
align-items: center;
gap: 0.4rem;
}
.excalidraw-script-store__back svg {
width: 1em;
height: 1em;
}
.excalidraw-script-store__detail {
width: min(800px, 100%);
margin: 0 auto;
}
.excalidraw-script-store__detail-hero {
display: flex;
align-items: flex-start;
gap: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__detail-icon {
position: relative;
flex: 0 0 5rem;
width: 5rem;
height: 5rem;
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--radius-l);
background: var(--background-secondary);
color: var(--text-muted);
overflow: hidden;
}
.excalidraw-script-store__detail-icon img {
position: absolute;
width: 4.2rem;
height: 4.2rem;
object-fit: contain;
background: var(--background-secondary);
}
.excalidraw-script-store__detail-title {
min-width: 0;
flex: 1;
}
.excalidraw-script-store__detail-title h1 {
margin: 0;
}
.excalidraw-script-store__detail-byline {
margin-top: 0.25rem;
color: var(--text-muted);
}
.excalidraw-script-store__detail-tags,
.excalidraw-script-store__detail-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem;
margin-top: 0.7rem;
}
.excalidraw-script-store__local-management {
margin-top: 1rem;
padding: 1rem;
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-m);
background: var(--background-secondary);
}
.excalidraw-script-store__local-management h2 {
margin: 0 0 0.8rem;
font-size: var(--font-ui-medium);
}
.excalidraw-script-store__local-copy+.excalidraw-script-store__local-copy {
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__local-copy-label {
width: fit-content;
margin-bottom: 0.5rem;
padding: 0.12rem 0.4rem;
border-radius: var(--radius-s);
background: var(--background-primary-alt);
color: var(--text-muted);
font-size: var(--font-ui-smaller);
font-weight: var(--font-medium);
}
.excalidraw-script-store__local-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
}
.excalidraw-script-store__local-info {
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.excalidraw-script-store__local-info code {
max-width: 100%;
overflow: hidden;
color: var(--text-muted);
font-size: var(--font-ui-smaller);
text-overflow: ellipsis;
white-space: nowrap;
}
.excalidraw-script-store__local-actions {
display: flex;
flex: 0 0 auto;
gap: 0.4rem;
}
.excalidraw-script-store__local-note {
margin-top: 0.75rem;
padding: 0.6rem 0.7rem;
border-radius: var(--radius-s);
background: var(--background-primary-alt);
color: var(--text-muted);
font-size: var(--font-ui-smaller);
line-height: 1.4;
}
.excalidraw-script-store__group-row {
display: flex;
align-items: center;
gap: 0.75rem;
margin-top: 0.9rem;
padding-top: 0.9rem;
border-top: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__group-row>label {
flex: 0 0 auto;
font-weight: var(--font-medium);
}
.excalidraw-script-store__group-controls {
display: flex;
flex: 1 1 auto;
align-items: center;
gap: 0.4rem;
min-width: 0;
}
.excalidraw-script-store__group-controls select {
min-width: 10rem;
max-width: 15rem;
}
.excalidraw-script-store__group-controls input {
min-width: 8rem;
flex: 1 1 auto;
}
.excalidraw-script-store__detail-description {
margin-top: 1rem;
line-height: 1.55;
}
.excalidraw-script-store__detail-description img {
max-width: 100%;
height: auto;
border-radius: var(--radius-m);
}
@media (max-width: 700px) {
.excalidraw-script-store__support-bar {
grid-template-columns: 1fr;
}
.excalidraw-script-store__support-item+.excalidraw-script-store__support-item {
border-left: 0;
border-top: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__updates-header,
.excalidraw-script-store__detail-hero,
.excalidraw-script-store__local-row,
.excalidraw-script-store__group-row {
align-items: stretch;
flex-direction: column;
}
.excalidraw-script-store__local-actions button {
flex: 1 1 auto;
}
.excalidraw-script-store__group-controls {
flex-wrap: wrap;
}
.excalidraw-script-store__group-controls select,
.excalidraw-script-store__group-controls input {
max-width: none;
flex: 1 1 12rem;
}
.excalidraw-script-store__controls>select,
.excalidraw-script-store__view-toggle {
flex: 1 1 auto;
}
.excalidraw-script-store__view-toggle button {
flex: 1;
}
}
@media (max-width: 500px) {
.excalidraw-script-store .modal {
width: 100vw;
height: 100vh;
max-height: 100vh;
}
.excalidraw-script-store__grid {
grid-template-columns: 1fr;
}
.excalidraw-script-store__controls {
align-items: stretch;
}
.excalidraw-script-store__controls>select,
.excalidraw-script-store__view-toggle {
width: 100%;
}
}
.excalidraw .excalidraw-tooltip-wrapper {
--no-tooltip: true;
}
.menu.excalidraw-font-picker-menu--desktop {
max-height: min(420px, 60vh);
overflow-y: auto;
}
.setting-item.excalidraw-declarative-full-width {
display: block;
width: 100%;
}
.excalidraw-declarative-settings-toolbar {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: var(--size-4-2) var(--size-4-3);
margin-bottom: var(--size-4-1);
font-size: var(--font-ui-smaller);
}
.excalidraw-declarative-settings-toolbar button,
.excalidraw-declarative-settings-toolbar a {
white-space: nowrap;
}
.excalidraw-declarative-settings-toolbar button {
font-size: inherit;
}
.excalidraw-declarative-settings-toolbar a {
color: var(--text-accent);
text-decoration: none;
}
.excalidraw-declarative-settings-toolbar a:hover {
color: var(--text-accent-hover);
text-decoration: underline;
}
.excalidraw-settings-breadcrumbs {
display: flex;
align-items: baseline;
justify-content: center;
flex-wrap: wrap;
gap: var(--size-4-1);
margin: 0;
color: var(--text-muted);
font-size: var(--font-ui-small);
}
.excalidraw-settings-breadcrumbs__link {
height: auto;
padding: 0;
border: 0;
background: transparent;
box-shadow: none;
color: var(--text-accent);
cursor: pointer;
font-size: inherit;
font-weight: inherit;
text-decoration: none;
touch-action: manipulation;
}
.excalidraw-settings-breadcrumbs__link:hover {
background: transparent;
box-shadow: none;
color: var(--text-accent-hover);
text-decoration: underline;
}
.excalidraw-settings-breadcrumbs__link.is-disabled {
color: var(--text-muted);
cursor: default;
pointer-events: none;
}
.is-mobile .excalidraw-settings-breadcrumbs__link,
.is-tablet .excalidraw-settings-breadcrumbs__link {
min-height: var(--interactive-normal);
padding-inline: var(--size-2-2);
}
.excalidraw-settings-breadcrumbs__current {
color: var(--text-normal);
font-weight: var(--font-semibold);
}
.excalidraw-settings-breadcrumbs__separator {
color: var(--text-faint);
}
.excalidraw-settings .setting-item-description a[href^="#"],
.excalidraw-settings-page .setting-item-description a[href^="#"] {
color: var(--text-accent);
font-weight: var(--font-medium);
text-decoration: underline;
}
.excalidraw-settings .setting-item-description a[href^="#"]:hover,
.excalidraw-settings-page .setting-item-description a[href^="#"]:hover {
color: var(--text-accent-hover);
}
.excalidraw-filename-information {
display: grid;
grid-template-columns: minmax(12rem, 0.8fr) minmax(18rem, 1.2fr);
gap: var(--size-4-4);
align-items: start;
}
.excalidraw-filename-information > :first-child {
min-width: 0;
}
@media (max-width: 700px) {
.excalidraw-filename-information {
grid-template-columns: 1fr;
}
}