Compare commits

..
Author SHA1 Message Date
zsviczian 8f58faaa0d refactor: consolidate EA script execution lifecycles 2026-09-01 18:33:13 +02:00
zsviczian e9305f3501 Updated refactor plan with #11997 and #12018 comments and requirements 2026-09-01 14:28:40 +02:00
zsviczian 052dfe3c12 implemented #2916 2026-08-31 21:43:14 +02:00
zsviczian 59f655ed46 2.27.0-rc.2 2026-08-31 21:00:41 +02:00
zsviczian 1f20425f3d 2.27.0-rc.1 2026-08-30 21:59:34 +02:00
zsviczian 06647f8ea3 fixed inaccurate documentation of cloning and use of ea workbench. 2026-08-30 14:26:07 +02:00
zsviczian 5127f78def api updates 2026-08-30 12:08:10 +02:00
zsviczian 7f136e0618 2.27.0-beta.9, 0.18.130 2026-08-29 18:50:45 +02:00
zsviczian e079827dd3 Merge pull request #2915 from zsviczian/improved-scripting-skills
feat: Improved scripting skills
2026-08-29 13:42:11 +02:00
zsviczian d848084b59 Preserve JavaScript extensions in template sync 2026-08-29 13:37:44 +02:00
zsviczian 5bbf266455 Harden docs sync and checkpoint plan 2026-08-29 12:35:56 +02:00
zsviczian fc4f91339f Sync template bootstrap from docs generator 2026-08-29 11:15:12 +02:00
zsviczian 1ae56692aa Add preview image naming checks 2026-08-29 11:12:10 +02:00
zsviczian d1f87855e4 docs: decouple training docs from script PRs 2026-08-29 11:08:05 +02:00
zsviczian 04eee5f373 docs: clarify doc generation rationale 2026-08-29 11:05:08 +02:00
zsviczian c121056558 docs: add script publishing workflow guidance 2026-08-29 11:00:16 +02:00
zsviczian cd1d243ac5 docs: use absolute links in routing notes 2026-08-29 10:55:45 +02:00
zsviczian 0214eaed59 docs: route legacy training to curated skills 2026-08-29 10:42:10 +02:00
zsviczian 0245964a04 docs: fix scripting type export coverage 2026-08-29 10:37:42 +02:00
zsviczian a2263bc253 scripts: checkpoint 1 unify doc and skill generation 2026-08-29 10:20:46 +02:00
zsviczian a932f10e90 docs: add scripting support plan and baseline training outputs 2026-08-29 10:18:46 +02:00
zsviczian da124f019b 2.27.0-beta.8, 0.18.129 2026-08-28 22:26:33 +02:00
zsviczian 6f1f277ed9 Merge pull request #2913 from zsviczian/small-features-and-fixes
Fix legacy conversion assets and add JavaScript script support
2026-08-28 16:09:25 +02:00
zsviczian d7dd08fad6 feat: support JavaScript Excalidraw scripts 2026-08-28 15:54:28 +02:00
zsviczian 355d7c2d46 fix legacy conversion embedded files 2026-08-27 21:43:59 +02:00
zsviczian b9d12c09e3 2.27.0-beta.7 2026-08-27 20:20:45 +02:00
zsviczian 7a1a0d75ee fix: defer inline link suggestions until invoked (#2907) 2026-08-27 19:33:17 +02:00
zsviczian 263c09d07b docs: record React bundle size fallback 2026-08-27 19:22:41 +02:00
zsviczian 39346559ce React bundled normally instead of compressed to REACT_PACKAGES 2026-08-27 19:14:22 +02:00
zsviczian e4e9df0a49 Merge pull request #2911 from zsviczian/performance-refactor-batch2
Improve popout migration performance and lifecycle safety
2026-08-27 16:20:37 +02:00
zsviczian 149e1e5bf0 perf: publish migrated files progressively 2026-08-27 16:15:33 +02:00
zsviczian 0da7120a7d perf: adopt drawing state across window migration 2026-08-27 07:48:38 +02:00
zsviczian d94b3b19ad refactor: define drawing migration handoff 2026-08-26 22:18:24 +02:00
zsviczian 169ceb3cf3 fix: save dirty drawings for popout modals 2026-08-26 21:55:32 +02:00
zsviczian ded91c6882 fix: coalesce stencil library loading 2026-08-26 19:49:52 +02:00
zsviczian 4ce81be081 refactor: simplify shared runtime ownership 2026-08-26 19:33:33 +02:00
zsviczian 740ee455d3 refactor: share Excalidraw runtime across windows 2026-08-26 18:45:57 +02:00
zsviczian 81fbbf42b7 2.27.0-beta.6, 0.18.127 2026-08-26 07:20:52 +02:00
zsviczian ba6c45d621 Merge pull request #2908 from zsviczian/performance-refactor-pr
Improve save and popout lifecycle performance
2026-08-26 07:18:39 +02:00
zsviczian 1c76170bad fix: cancel image loading across popout teardown 2026-08-25 23:00:59 +02:00
zsviczian 4d60ce9263 fix: preserve dirty popout migrations 2026-08-25 21:02:50 +02:00
zsviczian d513935523 chore: remove local madge dependency 2026-08-25 15:26:00 +02:00
zsviczian 01fcb09f83 chore: remove performance refactor diagnostics 2026-08-25 15:25:19 +02:00
zsviczian 57240da793 perf: restore progressive scene image loading 2026-08-25 14:45:03 +02:00
zsviczian 91e78ec1ae perf: coalesce in-flight view saves 2026-08-25 08:19:13 +02:00
zsviczian 648a2a8ed8 refactor: extract view save coordinator 2026-08-25 07:45:56 +02:00
zsviczian 83c8493c02 chore: use explicit window globals 2026-08-25 06:10:39 +02:00
zsviczian 67352c9952 perf: define save side-effect policy 2026-08-24 23:03:28 +02:00
zsviczian b4170ac68c perf: coalesce drawing backup writes 2026-08-24 22:37:09 +02:00
zsviczian 767cacbcdc perf: reuse coherent save snapshots 2026-08-24 22:19:58 +02:00
zsviczian b708883e13 perf: index images during save synchronization 2026-08-24 21:51:24 +02:00
zsviczian ded19ad510 perf: linearize save synchronization indexes 2026-08-24 21:06:09 +02:00
zsviczian 3579dbf245 fix: retain Excalidraw classification during cache refresh 2026-08-24 20:39:03 +02:00
zsviczian 8a0714104a perf: decouple blur saves from scene refresh 2026-08-24 20:27:51 +02:00
zsviczian 61817b01c6 WIP: validate performance refactor phase 1A lifecycle fixes 2026-08-24 20:01:36 +02:00
zsviczian d3e7182ff2 generate repository zip 2026-08-24 18:09:31 +02:00
zsviczian 6a50ccd271 updated agents.md and contributing.md 2026-08-23 22:02:38 +02:00
zsviczian f4ff25f308 fixed tootltip appearing twice - registerElementActionProvider 2026-08-23 20:04:25 +02:00
zsviczian df95e5f2b0 fixed settings breadcrumbs on Obsidian Mobile (touch) 2026-08-23 19:23:04 +02:00
zsviczian b6e98a8231 Merge pull request #2905 from theslyprofessor/fix/stale-canvas-offsets-1544
Fix stale canvas offsets when the view moves without resizing
2026-08-23 18:57:55 +02:00
zsviczian 48a35c7982 Merge pull request #2906 from zsviczian/declarative-settings
Migrate Excalidraw settings to Obsidian's declarative settings API
2026-08-23 18:55:13 +02:00
zsviczian 13652c2832 bumped excalidraw to 0.18.126 2026-08-23 18:54:23 +02:00
zsviczian 02a4f37e32 Polish 2.27.0 release notes 2026-08-23 18:44:22 +02:00
zsviczian 1ce6198c39 Complete declarative settings migration 2026-08-23 18:40:04 +02:00
zsviczian 0fdc689b3b Finalize declarative settings activation 2026-08-23 17:58:47 +02:00
zsviczian 21bcb6be91 Migrate AI settings declaratively 2026-08-23 17:34:00 +02:00
zsviczian ed960eb909 Migrate remaining non-AI settings declaratively 2026-08-23 16:40:23 +02:00
zsviczian 5a0419d8f7 Migrate embed and export settings declaratively 2026-08-23 15:40:36 +02:00
zsviczian b429e41f62 Migrate display and link settings declaratively 2026-08-23 13:17:32 +02:00
Nakul Tiruviluamala 8bfcd23b77 Flush offset refresh synchronously on the pointerdown path
Per review: api.refresh() only enqueues a React state update, so the
capture-phase pointerdown guard alone could not correct the SAME event's
coordinates - the first tap after a layout shift with the pointer already
inside the view still used stale offsets. Wrap the pointerdown-path
refresh in flushSync (available on the plugin's private react-dom
runtime) so the corrected offsets are committed before React's delegated
handlers process the event. Falls back to the async refresh if flushSync
is unavailable or throws.
2026-08-23 03:32:46 -07:00
Nakul Tiruviluamala 74429eb4eb Fix stale canvas offsets when the view moves without resizing (#1544)
Excalidraw caches offsetLeft/offsetTop and recalculates on container
resize or scroll, but nothing above the canvas changing height (an
injected toolbar row, tab-header wrap) moves the canvas WITHOUT a size
change, so pointer and selection events land a few pixels off until the
next autosave tick refreshes offsets (up to 60s on desktop).

Adds a throttled drift guard on pointerenter/pointerdown that compares
the container's bounding rect to the cached appState offsets and calls
refreshCanvasOffset() when they disagree by more than 1px, plus a
css-change hook mirroring the existing layout-change refresh.
2026-08-23 03:10:30 -07:00
zsviczian 9f182616a5 Migrate initial settings sections declaratively 2026-08-23 11:21:13 +02:00
zsviczian 148318ec21 Recover corrupted settings safely 2026-08-23 05:47:05 +02:00
zsviczian 0caa6b7d90 Simplify settings persistence safeguards 2026-08-22 00:04:29 +02:00
zsviczian dd30833789 Recover interrupted settings saves 2026-08-21 22:52:10 +02:00
zsviczian f82f4cf5eb Coalesce settings persistence updates 2026-08-21 22:26:58 +02:00
zsviczian 3f8a04d893 Establish declarative settings adapters 2026-08-21 21:17:51 +02:00
zsviczian f6525d72f8 Add declarative settings compatibility types 2026-08-21 20:57:26 +02:00
zsviczian eeffa5749b Document declarative settings migration plan 2026-08-21 20:27:08 +02:00
zsviczian 36a32940ba Merge pull request #2896 from zsviczian/performance-improvement
Improve embedded scene loading performance
2026-08-16 19:30:14 +02:00
90 changed files with 24707 additions and 9681 deletions

No files matched your search

+37 -14
View File
@@ -73,9 +73,12 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- Prefer Obsidian's established classes such as `mod-warning` before adding plugin-specific CSS. Consult the Obsidian CSS variables and component conventions when styling settings or dialogs.
- Never use `document.createElement()`, `Document.createElement()`, or `Document.createDocumentFragment()`. Always use Obsidian's `createEl()`, `createDiv()`, `createSpan()`, `createSvg()`, and `createFragment()` helpers. When an element must deliberately belong to a specific document that Obsidian's helpers cannot target, such as a canvas used for drawing or an element inside an iframe, use the `deliberateCreateElement` function injected by `rollup.config.mjs` and declare it in the consuming module, for example `declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;`.
- Use semantic interactive elements and Obsidian's event helpers. Link-like navigation should use a real anchor, not a button merely styled as a link; use `onClickEvent` when applying custom navigation behavior. Validate touch interactions on a physical mobile device because desktop mobile emulation proves layout, not native touch activation.
- When a control already has a styled tooltip, do not also set an HTML `title` attribute. Keep its accessible name in `aria-label`; `title` produces a second native Chromium/Electron tooltip and must not replace accessible labeling.
- Do not write an element's `style` attribute directly. Use `setStyle` and `removeStyle` from `src/utils/styleUtils.ts` when a dynamic inline style is genuinely necessary.
- Use the existing visibility helpers instead of the native `hidden` property or attribute, which is not reliable in Obsidian's styled UI. Choose `hideElement`/`showElement` or `setComponentVisibility` from `src/utils/styleUtils.ts`, or `setElementHidden`/`setElementDisplay` from `src/utils/htmlUtils.ts` when a boolean/display-oriented API is clearer.
- Search `src/utils/styleUtils.ts` and `src/utils/htmlUtils.ts` before introducing new DOM styling helpers or display classes.
- Run Obsidian CodeScanner after CSS changes. Preserve compatibility with the declared minimum Obsidian version and prefer a widely supported property when it provides the same result; for example, a basic underline is preferable to optional underline-thickness/offset styling.
- For a known vault path, use the most specific synchronous lookup: `app.vault.getFolderByPath()` for folders and `app.vault.getFileByPath()` for files. Use `getAbstractFileByPath()` only when either type is intentionally accepted, and avoid adapter-level existence checks when the Vault API already models the target.
- Radix content in the customized Excalidraw package may be rendered through `ObsidianRadixPortal` directly under the owning document's body. A body portal escapes component ancestor selectors and modal stacking contexts. When a trigger is visible but its menu or popover is not, first inspect whether the content mounted behind a modal or lost ancestor-scoped styles. Use a class on the portaled content, a portal-safe selector, and an explicit stacking level when required; validate main-window, popout, click-outside, and Escape behavior.
@@ -111,6 +114,7 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- Don't assume desktop-only behavior unless `isDesktopOnly` is `true`.
- Avoid using desktop only objects and functions such as Node Buffer, SharedArrayBuffer, etc. For the special case when this is required, make proper mobile safe guards.
- Avoid large in-memory structures; be mindful of memory and storage constraints.
- Treat a physical phone or tablet as a separate validation environment for touch targets, synthesized clicks, scrolling gestures, focus, and the mobile WebView. Desktop mobile emulation is useful for responsive layout checks but is not a substitute for real touch testing.
## Agent do/don't
@@ -194,7 +198,6 @@ This project uses a non-trivial Rollup build because startup time, popout-window
The build embeds or injects runtime code for:
- React, ReactDOM/client, and the official JSX runtime entry points built from the installed npm packages
- the customized `@zsviczian/excalidraw` Obsidian artifact built from Excalidraw's ESM source graph
- `MathjaxToSVG`
- `lz-string`
@@ -202,7 +205,7 @@ The build embeds or injects runtime code for:
These payloads are executed or unpacked at runtime. This is intentional.
React and the Excalidraw package are separate payloads. React must not be bundled into the Excalidraw artifact, because the plugin creates a matching private React runtime in every Obsidian window. Mermaid is also intentionally absent from the artifact and is loaded lazily at runtime through Excalidraw Extras. All other required Excalidraw assets are expected to work offline except the deliberately lazy CJK font subsets.
React, ReactDOM, and the official JSX runtime entry points are normal modules in the main Rollup bundle, not separately compressed or evaluated payloads. React must remain external to the separately built Excalidraw artifact: the plugin supplies its one bundled private React runtime to the single evaluated Excalidraw runtime used by every view. Mermaid is also intentionally absent from the artifact and is loaded lazily at runtime through Excalidraw Extras. All other required Excalidraw assets are expected to work offline except the deliberately lazy CJK font subsets.
### Two-Repository Excalidraw Workflow
@@ -229,9 +232,9 @@ The customized Excalidraw runtime receives Obsidian capabilities through typed h
- Keep adapters narrow and semantic. They may expose operations such as reading a current limit or running a named action, but never the plugin instance, the complete settings object, or an active view.
- Capabilities used by `@excalidraw/common` or lower layers belong in `ObsidianCommonHostAdapter`. Capabilities used only by the Excalidraw package belong in `ObsidianExcalidrawHostAdapter`.
- View-specific state must remain instance-scoped. Do not put an active view into either window-runtime adapter; expose a semantic plugin-side action when the component genuinely requires such behavior.
- `PackageManager` registers both adapters once per evaluated Excalidraw runtime and window. React components and individual `ExcalidrawView` instances must not configure or dispose them.
- `PackageManager` registers both adapters once with the shared Excalidraw runtime. React components and individual `ExcalidrawView` instances must not configure or dispose them.
- Adapter methods must read live plugin state instead of capturing settings snapshots during registration.
- `PackageManager` owns the complete lifetime: dispose registrations before removing a package or window runtime, make cleanup idempotent, and roll back all registrations if configuring any adapter fails.
- `PackageManager` owns the complete lifetime: dispose registrations before releasing the shared runtime, make cleanup idempotent, and roll back all registrations if configuring either adapter fails.
A closure that references the plugin is not itself a memory leak. The risk is allowing a registry, listener, or evaluated runtime retaining that closure to outlive its owning `PackageManager` registration.
@@ -248,11 +251,16 @@ The host adapters are an internal protocol between this plugin and its exact `@z
### Popout Window Support
- `src/core/managers/PackageManager.ts` manages window-scoped React/ReactDOM/Excalidraw packages.
- This is necessary because the plugin must work in Obsidian/Electron popout windows.
- Do not replace this with a naive global singleton approach.
- The runtime is built from official npm package entry points and kept in plugin/package lexical scope. Do not assign React or ReactDOM to `window`; only the documented `window.ExcalidrawLib` compatibility surface remains global.
- Rendering, DOM ownership, events, observers, portals, and React roots must use the owning view window where appropriate.
- `src/core/managers/PackageManager.ts` combines the plugin bundle's one private React/ReactDOM runtime with one evaluated Excalidraw artifact in the main application realm and leases that package to every view.
- A lease retains the view's actual acquisition window for migration and persistence decisions; package evaluation ownership must never substitute for that identity.
- Popouts receive only a temporary `window.ExcalidrawLib` compatibility alias. Remove it after the final lease for that window while keeping the shared runtime alive until plugin unload.
- React and ReactDOM are bundled normally from their official npm entry points and kept in plugin/package lexical scope. Do not restore a compressed/evaluated React bootstrap or assign React or ReactDOM to `window`; only the documented `window.ExcalidrawLib` compatibility surface remains global.
- Every Excalidraw root must receive its stable owning document. Rendering, DOM ownership, events, observers, portals, realm constructors, fonts, timers, and React roots must derive from the owning view document/window where appropriate; do not turn the shared runtime into a mutable "current window" singleton.
- Treat `HTMLElement.onWindowMigrated()` as a destructive runtime boundary. Its callback runs after Obsidian has moved the view container to another document, while the existing React root and Excalidraw API still belong to the source window runtime.
- For a dirty migration, synchronously capture every API-owned value needed for persistence and unmount the source React root **before the first `await`**. Do not move synchronization, compression, Vault/native file access, `closeLeafView()`, or another asynchronous step ahead of that unmount. On macOS/Electron, doing so reproducibly allowed the source popout window to be destroyed before `root.unmount()`, freezing Obsidian and disconnecting DevTools.
- Cancel deferred initialization and scene-file loaders before migration unmount, and require delayed loader callbacks to match the exact API instance and file path that started them. Component-owned image decoding can still outlive a synchronous `addFiles()` call, so the Excalidraw runtime must also stop after an awaited decode when its editor has unmounted; never delay migration unmount to wait for image work.
- The migration callback owns the single persistence flush. Generic `onClose()` and `onUnloadFile()` safeguards must not start duplicate migration saves, and the retired source view must reject blur-save side effects and vault-modify synchronization after its API is unmounted.
- A popout-to-main migration may serialize from a synchronously captured drawing snapshot, but the replacement main-window view must perform the final drawing-file write. Never initiate the final Vault/native write from the source popout callback.
### Main-Window Persistent Storage
@@ -402,10 +410,10 @@ Backwards compatibility is a strong requirement in this repository.
## React Runtime Import Model
React usage in this repository is special because React and ReactDOM are package-managed per window to support Obsidian popout windows and runtime package injection.
React usage in this repository is special because one normally bundled private React/ReactDOM runtime is package-managed across main-window and popout roots.
- It is fine to import React for types, component definitions, JSX compilation, and nearby established patterns.
- Do not assume a single global React/ReactDOM runtime is safe for rendering, root creation, or view-owned objects.
- Import React, ReactDOM, and JSX runtime entry points normally. Rollup must bundle them into the main plugin but keep them external in the library build and in the separately built Excalidraw artifact.
- The shared runtime is safe only because each root and Excalidraw instance receives stable owner-document state. Never recover view ownership from the runtime's lexical main window.
- For view-bound rendering and roots, follow `src/view/ExcalidrawView.ts` and use `view.packages.react` and `view.packages.reactDOM` through the package-manager flow.
- For view-owned React objects such as refs or runtime-created elements, follow neighboring patterns such as `src/view/components/menu/ToolsPanel.tsx` and `src/view/components/CustomEmbeddable.tsx`, which intentionally use the package-managed React instance.
- Do not introduce a new direct `ReactDOM.createRoot()` path outside the package-manager model unless you have verified popout-window safety.
@@ -421,7 +429,7 @@ Use this routing guide before editing.
- Commands and command registration: `src/core/managers/CommandManager.ts`
- Vault or workspace event handling: `src/core/managers/EventManager.ts` and `src/core/managers/FileManager.ts`
- Markdown rendering or markdown embeds: `src/core/managers/MarkdownPostProcessor.ts`
- Package/runtime loading across windows: `src/core/managers/PackageManager.ts`
- Shared package/runtime loading and per-window leases: `src/core/managers/PackageManager.ts`
- Styling setup and style injection: `src/core/managers/StylesManager.ts`, `styles.css`, `src/utils/dynamicStyling.ts`
- Main canvas/editor behavior: `src/view/ExcalidrawView.ts`
- Sidepanel behavior: `src/view/sidepanel/`
@@ -444,6 +452,21 @@ If a task changes persisted settings, inspect all relevant pieces.
Settings changes are often incomplete if only one of these surfaces is updated.
## Declarative Settings And Persistence
The plugin supports Obsidian 1.8.7 while optionally using the declarative settings API introduced in Obsidian 1.13. Preserve both compatibility paths.
- Do not bump the `obsidian` dependency or `minAppVersion` merely to consume declarative settings. Gate the runtime path with `requireApiVersion("1.13.0")` and keep conservative placeholder declarations for the newer API.
- `getSettingDefinitions()` must return the complete tree only when the runtime supports declarative settings and the restart-applied compatibility preference enables them. Returning an empty array is the intentional fallback to the legacy renderer.
- The settings page model is the canonical hierarchy for declarative rendering, legacy single-page rendering, descriptions, search aliases, breadcrumbs, cross-page navigation, and Markdown export. Do not create separate setting lists or behavior implementations for the two layouts.
- Controls that change each other's options, visibility, or disabled state must share one integrated component or one shared configurator. Apply dependent state during initial render as well as after changes. Scope captured control references to one rendered definition tree; generating an export-only tree must never replace bindings used by the mounted UI.
- On Obsidian 1.13+, do not call `display()` to refresh a declarative page. Update the mounted controls through their binding/configurator path or ask Obsidian to rebuild definitions only when the definition tree itself changed.
- Declarative page navigation uses guarded unpublished Obsidian APIs. Prefer `openPagePath`; retain the checked `findTabById`/`navigateToPage` fallback, derive localized paths from the canonical page model, and degrade to non-navigating text when the API is unavailable.
- Route all settings writes through `PluginSettingsManager` and its serialized stable-snapshot writer. Save when values change; never make plugin shutdown or settings-tab closure the primary persistence boundary because Obsidian may not await asynchronous writes during termination. Avoid competing direct `saveData()` calls.
- Missing and invalid `data.json` states are different. A first installation with no file is valid; a missing file with a recovery snapshot requires a restore-or-defaults choice; invalid startup data should restore a valid device-local snapshot or ask the user how to proceed; invalid data arriving during a running session must be rejected and repaired from the valid in-memory settings.
- The last-known-good recovery snapshot is durable, device-local IndexedDB data owned by the main application window. Refresh it after every valid load or save, do not store large snapshots in `localStorage`, and do not create independent recovery databases for popouts.
- Preserve unknown persisted keys. Do not derive a sanitizer from the TypeScript settings interface or treat unfamiliar keys as corruption.
## Script Engine And Automation Notes
- Excalidraw Automate is a major public surface of this project.
@@ -467,7 +490,7 @@ These areas require extra care:
- `rollup.config.mjs`: payload injection, localization, manifest/versioning, CSS bundling
- `src/core/main.ts`: lifecycle order, settings migration, startup initialization
- `src/view/ExcalidrawView.ts`: very large, stateful, performance-sensitive, and central to user behavior
- `src/core/managers/PackageManager.ts`: cross-window package loading and runtime evaluation
- `src/core/managers/PackageManager.ts`: shared runtime evaluation, host registration, and cross-window lease/alias lifetime
- `src/lang/helpers.ts`: build-token compatibility for compressed locales
- AI/provider settings and persisted credentials handling
- PDF/export code paths and Electron/Obsidian-specific integrations
+20 -2
View File
@@ -35,6 +35,8 @@ Because Obsidian runs across a variety of environments, please manually test you
- Desktop: Mac, Windows, Linux
- Mobile: Android, iOS (Test on both Phones and Tablets)
Desktop mobile emulation is useful for checking responsive layout, but it does not reproduce every touch event, synthesized click, focus, scroll gesture, or mobile WebView behavior. If a change affects an interactive mobile control, validate it on at least one physical phone or tablet.
Use a risk-based test plan rather than a generic smoke test. Every change should identify the most likely regression and whether it needs separate coverage in:
- the main Obsidian window
@@ -43,6 +45,12 @@ Use a risk-based test plan rather than a generic smoke test. Every change should
- desktop and mobile layouts
- offline mode, when the change affects packaged assets or runtime loading
For UI and CSS changes:
- Use semantic controls and Obsidian's event helpers. Link-like navigation should use a real anchor; custom navigation handlers should use `onClickEvent`.
- Keep accessible names in `aria-label`. If a styled tooltip is already present, omit the HTML `title` attribute to avoid a second native browser tooltip.
- Run Obsidian CodeScanner and resolve compatibility warnings against the supported Obsidian baseline. Prefer simple, broadly supported CSS when advanced styling is only decorative.
Timers, observers, autosave coordination, and undocumented Obsidian API workarounds may exist for platform behavior outside the plugin's control. Trace their purpose before simplifying them.
## 🪵 Logging Requirement
@@ -62,9 +70,9 @@ Timers, observers, autosave coordination, and undocumented Obsidian API workarou
This project consists of multiple sub-components and non-standard integrations to support Obsidian-specific features.
### 1. React & Package Manager
Because the plugin must support Obsidian's native popout windows, React and Excalidraw cannot be loaded as simple global singletons.
The plugin bundles one private React/ReactDOM runtime and combines it with one evaluated Excalidraw runtime. Every main-window and popout view leases that shared package while supplying its own stable `ownerDocument`.
- References to React and ReactDOM are handled via `PackageManager.ts` (`src/core/managers/PackageManager.ts`).
- The runtime is assembled from official React npm entry points and loaded separately for each Obsidian window.
- React and its JSX runtimes are bundled normally from official npm entry points. They must remain external to the separately built Excalidraw artifact and to the plugin's library build so neither path creates a second React copy.
- Do not introduce direct `ReactDOM.createRoot()` calls outside this package-manager model.
- Do not publish React or ReactDOM on `window`. The documented `window.ExcalidrawLib` scripting surface is the deliberate exception.
@@ -156,6 +164,16 @@ Use `RefactorPlan.md` as the living record for ongoing structural work. Refactor
`ExcalidrawView` must remain an Obsidian `TextFileView`; it should not be converted wholesale into React. React owns the child UI, while the view remains the Obsidian lifecycle and compatibility boundary. ExcalidrawAutomate, command IDs, settings, serialized data, and existing plugin integrations must remain backwards compatible.
### 6. Settings UI and persistence
The plugin keeps Obsidian 1.8.7 compatibility while using searchable declarative settings on Obsidian 1.13 and newer.
- Do not bump the Obsidian dependency or minimum version just to use the declarative API. Gate it at runtime; returning an empty definition array is the intentional legacy fallback.
- Maintain one canonical settings hierarchy and shared control behavior for both the declarative multi-page and legacy single-page layouts, including descriptions and Markdown export. Do not fork the two experiences into independent implementations.
- Keep interdependent controls together and apply their visibility, options, and disabled state during initial render as well as after changes.
- Persist settings through `PluginSettingsManager`; do not add independent `saveData()` calls or rely on plugin shutdown to finish an asynchronous save.
- Treat a missing `data.json`, invalid/corrupted data, and a valid externally synchronized update as separate cases. Preserve the device-local recovery workflow and unknown forward-compatible setting keys.
## 🌍 Localization & User-Facing Text
- **No hardcoded strings:** There should be no hardcoded English strings directly in the UI components or logic.
+549 -192
View File
@@ -1,9 +1,10 @@
# Incremental refactor assessment and plan
Status: parked as of 2026-08-13 (see "Parked: next steps if resumed" near the
end). Focus has shifted to `src/core/settings.ts` and declarative-settings
readiness; this plan is not being actively worked but is left in a
resumable state.
Status: the `ExcalidrawView`/`main.ts` plan is parked as of 2026-08-13 (see
"Parked: next steps if resumed" near the end). The active refactor is the
dual-support migration of `src/core/settings.ts` to Obsidian's declarative
settings API; its checkpoint plan is recorded under "Active effort:
declarative settings migration."
This document is the working plan for reducing the size and coupling of
`src/core/main.ts` and `src/view/ExcalidrawView.ts` without destabilizing the
@@ -24,6 +25,7 @@ validated, and what remains uncertain.
| Assessment and baseline design | Complete | Initial architecture, risks, sequencing, and validation matrix documented |
| Retire legacy AI settings and fallbacks | Complete | Removed the retired migration, schema/default fields, GPT reset, and AI runtime fallbacks without filtering unknown persisted keys; manual testing found no issues |
| Extract settings implementation service | Implemented; awaiting manual validation | `PluginSettingsManager` now owns persistence, default assembly, remaining migrations, and API-key obfuscation; plugin methods and startup readiness remain intact, while temporary autosave enablement is now explicit plugin-instance state rather than persisted settings state |
| Migrate the settings tab to declarative settings with legacy fallback | Complete | Checkpoints 4A-4E migrated the full settings surface and passed focused manual validation. Checkpoints 5/6 finalized and activated the complete tree behind the persisted, restart-applied `useDeclarativeSettings` preference. The final checkpoint removed checkpoint-era names, dead adapter/type branches, unused declarations, and tab-lifetime references to controls owned by one rendered tree. Markdown export now rebuilds declarations without replacing the active control bindings. The supported legacy preference and empty-array fallback remain intentional. The final beta.5 production build is 4,798,339 bytes, 73,417 bytes above `master` and 2,450 bytes below the completed checkpoint-6 build; the Obsidian dependency/minimum remains `1.8.7` |
| Extract footer safe-area styling | Implemented; awaiting manual validation | `FooterSafeAreaManager` now owns device-specific stylesheet injection, open-document traversal, and unload cleanup; the plugin method remains as a settings-UI compatibility delegate |
| Extract font management | Implemented; awaiting manual validation | `FontManager` now owns CJK discovery/loading, custom-font registration, document stylesheets, readiness, and cleanup; plugin methods and the externally read `fourthFontLoaded` field remain intact |
| Extract startup instrumentation | Implemented; awaiting manual validation | `StartupTimer` now owns startup event history, delta tracking, and breakdown formatting; lifecycle calls, public methods, and the public `loadTimestamp` field remain intact |
@@ -37,10 +39,10 @@ validated, and what remains uncertain.
| Audit production bundle size | Complete | Ranked packaging, dependency, dead-data, and static-payload reductions; translation extraction remains a last resort |
| Use inflate-only Pako runtime | Complete | Replaced the full Pako distribution with its API-compatible inflate-only build; all existing Excalidraw and locale payloads retain their format and decompression path |
| Replace bundled YAML runtime | Implemented; awaiting manual validation | `mergeMarkdownFiles()` now uses Obsidian's public YAML APIs, and `yaml` is no longer a direct production dependency |
| Compress per-window React payload | Complete | React, ReactDOM, and the official JSX runtimes are inflated before React participates in plugin bootstrap; the decompressed source remains available for private popout-window package creation, and manual testing found no startup or runtime regression |
| Compress per-window React payload | Complete; superseded by the shared bundled runtime | React, ReactDOM, and the official JSX runtimes were previously inflated before plugin bootstrap for private popout-window package creation. The later shared-runtime architecture removed the need for retained/evaluated React source, and the current build bundles those modules normally |
| Replace bundled OpenType metric reader | Complete | A bounds-checked SFNT reader now extracts only the TTF/OTF metrics consumed by Excalidraw; WOFF/WOFF2 fallback behavior is unchanged, `opentype.js` is no longer bundled, and manual testing found no font regression |
| Migrate the Excalidraw runtime bundle | Implemented; production and development startup, color picker, runtime Mermaid loading, private npm-entrypoint React, and debugger payload validated | Added an isolated upstream-fork `build:obsidian` that bundles the ESM source graph into one function-evaluable artifact, preserves runtime Mermaid loading, removes the fork's retired UMD/webpack packaging path, and embeds the upstream Assistant UI fonts for offline use. The per-window React runtime is generated from official npm package entrypoints and kept in the plugin's lexical package scope rather than assigned to `window` |
| Upgrade the private React runtime to React 19 | Implemented; awaiting manual validation | Updated the paired React and ReactDOM runtime to stable 19.2.8 with matching React 19 types while retaining private per-window package creation and the official JSX runtime entrypoints |
| Migrate the Excalidraw runtime bundle | Implemented; production and development startup, color picker, runtime Mermaid loading, private npm-entrypoint React, and debugger payload validated | Added an isolated upstream-fork `build:obsidian` that bundles the ESM source graph into one function-evaluable artifact, preserves runtime Mermaid loading, removes the fork's retired UMD/webpack packaging path, and embeds the upstream Assistant UI fonts for offline use. React remains external to that artifact and is supplied by the plugin's lexical shared runtime rather than assigned to `window` |
| Upgrade the private React runtime to React 19 | Implemented; awaiting manual validation | Updated the paired React and ReactDOM runtime to stable 19.2.8 with matching React 19 types and official JSX runtime entrypoints. The later shared-runtime checkpoint replaced private per-window package creation with one normally bundled plugin runtime |
| Repair text-to-diagram history menu | Implemented; awaiting manual validation | Persistence is working and saved chats are loaded; the body-portaled history dropdown now retains its TTD styling and stacks above the text-to-diagram modal |
| Audit and consolidate duplicate logic | In progress | Consolidated `updateFrontmatterInString()`, `arrayToMap()`, `wrapTextAtCharLength()`, `getLinkParts()`/`LinkParts`, `getBinaryFileFromDataURL()`, `svgToBase64()`, `getFontDataURL()`, `cropCanvas()`, `getImageSize()`, `promiseTry()`, `isVersionNewerThanOther()`, `repositionElementsToCursor()`, the internal `cloneElement()`, and `getBoundTextElementId()`; continue one independently testable helper family at a time |
| Extract the React root (Phase 7) | Implemented; awaiting manual validation | `src/view/components/ExcalidrawRoot.ts` now owns the mechanical body of the former `excalidrawRootElement()`: menu/observer mount and teardown, and the full Excalidraw prop wiring. `ExcalidrawView` keeps `excalidrawRoot`/`createRoot()` ownership and the bound-function render call; ~30 previously private members the render tree touches were widened to `public` (type-only, no logic change) following the precedent already set by `packages`/`plugin`/`excalidrawAPI` |
@@ -54,12 +56,238 @@ validated, and what remains uncertain.
| Prioritize cached and direct scene assets before generated SVG misses | Desktop warm reopen validated; cancellation, popout, and mobile remain | Scene loading now treats Excalidraw cache lookup and SVG generation as separate priority tiers. Cache hits and direct vault assets finish in the first pool; Excalidraw cache misses and known bypasses such as color-mapped drawings are recorded without generating, the completed fast batch is sent to Excalidraw, and the loader yields a browser task before starting a second generation pool. Ordinary PNG/JPEG/SVG reads keep their existing order, while uncached generated drawings no longer begin early enough to prevent cached results from painting |
| Skip duplicate Excalidraw SVG normalization during scene loading | Desktop warm performance validated; ordinary SVG, popout, and mobile remain | The paired component `addFiles` API accepts an optional one-argument object carrying a non-serialized `ReadonlySet<FileId>` of caller-certified SVGs. The plugin derives that set only from embedded files whose source is an Excalidraw drawing. Those generated SVGs skip the component's base64 decode, DOM parse, serialization, and base64 re-encode cycle; legacy array callers and direct/arbitrary SVG files retain normalization |
| Investigate post-publication image decode/render latency | Pending; profile before changing behavior | The trusted-SVG bypass reduced synchronous `addFiles()` work from 12.76 seconds to 1.43 seconds, but the measured final batch still had roughly 3.2 seconds between publication and the next animation-frame callback. A future checkpoint should separate browser data-URL decoding, Excalidraw image-cache initialization, React/canvas work, and frame scheduling before selecting a fix; an animation-frame callback alone does not prove a completed paint |
| Performance baseline diagnostics (Phase 0) | Complete; instrumentation archived and removed | The runtime captures established the Phase 1A/1B priorities and supplied the acceptance evidence recorded below. The exact final instrumented checkpoint is preserved on the local `performance-refactor-1b-instrumented` branch for the future persistent-main-runtime feasibility spike. All `performanceDiagnostics` imports, counters, console checkpoint hooks, diagnostic-only callback parameters, and the `EXCALIDRAW_PERF_PHASE0` source module have been removed from the delivery branch; the historical findings remain in this plan without shipping temporary observability in the plugin |
| Share the main React/Excalidraw runtime with popouts (batch 2 checkpoint 1) | PackageManager simplification complete and lifecycle-validated | `PackageManager` now owns exactly one main-realm React/ReactDOM/Excalidraw package and one pair of typed host registrations. The strategy switch, per-window package map, fallback package, per-window evaluator, decompressed-source retention, and per-window host-disposer maps are gone. View leases still capture the real acquisition window for migration/persistence decisions and reference-count only the popout's temporary `ExcalidrawLib` alias. Custom font metrics register once with the shared runtime, while font styles remain per document. Upstream's stable `ownerDocument` boundary continues to own rendering, listeners, portals, fonts, timers, and realm constructors. This checkpoint deliberately does not change the destructive `onWindowMigrated` lifecycle, persistence handoff, React-root recreation, scene loading, or image transfer behavior |
| Bundle the shared React runtime normally | Implemented; awaiting focused runtime validation | Removed the nested React-runtime Rollup build, compressed `REACT_PACKAGES` bootstrap, regex postprocessing, and their obsolete source files/dependency. The main plugin now imports and bundles React, legacy/client ReactDOM, and both JSX runtimes once; the production `jsxDEV` fallback is preserved. The library build and separately built Excalidraw artifact still externalize React so no second copy crosses either boundary. `PackageManager` continues to own the shared package, host adapters, leases, and popout aliases; no view, migration, or persistence lifecycle changed. The obsolete `ownerDocument` compatibility cast in `ExcalidrawRoot` was removed because the published component contract now declares the prop directly. This packaging change was implemented in commit `39346559ced5aa349388d22954fa9a73a51f2959`. If the production bundle later approaches the 5 MiB limit, restoring that commit's compressed React packaging is a practical fallback and recovers approximately 114,871 bytes |
| Define bounded drawing-state handoffs (Phase 1C.1, batch 2) | Implemented; intentionally inert | Added a plugin-owned 15-second, one-shot registry for drawing-owned migration state. Entries are validated by token, leaf, path, and file mtime; a newer registration replaces the prior payload for the same leaf; consumption removes the candidate before validation; and plugin unload clears the sole timer and every retained payload. The contract carries scene/app state, current `BinaryFiles`, explicit `ExcalidrawData` metadata, and a settled save-revision baseline, but cannot retain an `ExcalidrawView`, React root, DOM node, `Window`, listener, or package lease. `ExcalidrawData` and `ViewSaveCoordinator` expose copy/adopt boundaries for the later destination-view checkpoint. No migration path calls these APIs yet, so the validated disk-backed migration lifecycle and image loading remain unchanged |
| Adopt drawing-owned state during window migration (Phase 1C.2a, batch 2) | Complete | `onWindowMigrated()` now takes one synchronous pre-unmount scene/app/files snapshot, retains the established dirty-save snapshot and popout-safe serialized persistence handoff, and registers drawing state only after the save is settled and the old view has closed. The replacement view receives a one-shot token through its transient view state, consumes the handoff before a popout→main persistence write can intentionally change file mtime, and adopts scene/app state, current `BinaryFiles`, explicit `ExcalidrawData` metadata, text/compatibility mode, and the settled save revision. The new owner-document-bound React/Excalidraw tree is still recreated. This checkpoint deliberately retains the complete ordinary scene-file loader after initialization as a correctness fallback; skipping or narrowing work for already-transferred files is a separate measured checkpoint. Runtime validation covered dirty migration and durable reopen in both directions, destination interaction/undo, partial and complete MOC EA file transfer, and mid-load cancellation without a freeze, lost edit, fallback, or console error |
| Measure post-handoff migration stages (Phase 1C.2b, batch 2) | Complete; diagnostics removed after Phase 1C.2c | Both measured directions showed that source teardown, handoff adoption, library access, destination readiness, and the ordinary scene-file loader complete in milliseconds. Passing all 46 transferred `BinaryFiles` through `initialData.files` instead blocked Excalidraw initialization for approximately 13–15 seconds and starved the zero-delay post-initialize callback for another approximately 4.45 seconds. The ordinary loader then emitted no files and completed in 3.5–24.6 ms. This selected destination image decoding/publication—not handoff validation, disk loading, or hashing—for Phase 1C.2c; the temporary trace was removed after that checkpoint's runtime acceptance |
| Publish transferred migration files progressively (Phase 1C.2c, batch 2) | Complete; published dependency installed and runtime-validated | A migrated destination now initializes its owner-document-bound Excalidraw tree with the transferred scene but no initial files, then publishes the exact in-memory `BinaryFiles` in visible-first batches of four through Excalidraw's ordinary `addFiles()` path. A narrow fork API waits only for decoding already started by each batch; the plugin yields two destination frames before the next batch and invokes the disk-backed loader only for image IDs still absent afterward. Trusted transferred SVGs retain the existing normalization bypass. No decoded image, DOM node, `Window`, React object, data-URL cache, or unbounded new cache crosses the handoff. MOC EA now becomes interactive immediately, shows its first image within approximately two seconds, and completes in approximately four seconds main→popout and eight seconds popout→main. Dirty and mid-load transfers retained edits without slowing or destabilizing the load. The final plugin consumes the registry-published `@zsviczian/excalidraw@0.18.128`; temporary local artifact replacement is no longer involved, and all migration timing diagnostics are removed |
| Complete upstream cross-document runtime ownership | Upstream PR #11997 open; final code review confirms the Obsidian paths | PR #11997 now includes the original owner-document font, tooltip, image, and animation fixes plus Márk's follow-up work: the current item font is prewarmed in the editor document, tooltip/hyperlink ownership no longer becomes stale across concurrent editors, hyperlink timers/listeners follow the owning window, and animation slots are instance-owned. Stacked PR #12018 retains those fixes while replacing the narrow image factory with the broader render-host contract. The current fork still carries the accepted local checkpoints until the upstream work is merged and adopted through a published fork dependency |
| Track upstream render-host abstraction (#12018) | Final head `ab6f203e9` satisfies the Obsidian shared-runtime/multi-window contract in code review; integration smoke test remains | `RenderEnvironment` supplies canvas, image, and path factories. A process-wide default serves detached/headless callers, while each mounted `App` derives a stable environment from its own `ownerDocument`/`ownerWindow`; explicit environments take precedence and host-object caches are keyed weakly by environment identity. The public prop is forwarded to `App`, and `App.updateImageCache()` uses the App environment. Text metrics, freedraw paths, rendering, exports, image decoding, and window-bound throttles now follow the appropriate scoped environment. This is compatible with one evaluated Excalidraw runtime hosting concurrent main-window and popout Apps, so the plugin must not call `setRenderEnvironment()` to follow focus. Final acceptance still requires merging into the fork, publishing/installing the exact package, and running the focused plugin tests below |
| Coalesce restored-view stencil-library initialization (batch 2 checkpoint 2) | Complete | Simultaneously restored main and popout views now share one in-flight vault-library load. The loader constructs an isolated item/source snapshot and publishes it atomically only if no vault invalidation occurred while files were being read; an invalidated load is discarded and retried. This preserves the existing plugin-global library cache and persistence behavior while preventing concurrent startup callers from clearing/populating the same map and reporting every item as a duplicate. The maintainer validated restored main/popout startup and library mutation with no new issue |
| Make shared-runtime editor instances owner-document-aware (batch 2 spike checkpoint 2) | Accepted upstream and merged into the fork; focused popout behavior validated | Excalidraw now exposes the optional stable `ownerDocument` host prop upstream and derives the owning window from it for editor DOM, listeners, realm constructors, fonts, WYSIWYG, portals, and related browser APIs. The plugin continues to pass each view's actual document through its root. The fuller fork-only spike was preserved in recovery stashes and then removed before merging upstream PR #11974, avoiding permanent fingerprint and merge churn. Conflict resolution retained only existing Obsidian-fork behavior plus five owner-realm conversions on fork-only `App.tsx` lines that upstream could not modify. The maintainer confirmed the shared runtime works well in a popout; the tray-menu tooltip ordering remains a separate pre-existing z-index issue. PackageManager simplification, migration state handoff, MOC EA, and memory work remain separate follow-up checkpoints |
| Explicit package/window runtime ownership (Phase 1A.1) | Ownership behavior validated; retained-heap investigation pending | `ExcalidrawView` now acquires an idempotent package lease that captures the package's owning window before any DOM migration. `PackageManager` reference-counts view leases per window, deletes a popout runtime after its final lease is released, and keeps the main startup/fallback runtime pinned. Five measured main↔popout round trips kept `packageWindows` bounded at 1–2 and produced five matching popout package creations/deletions. A two-view popout test then confirmed that the first close retains one lease and a usable sibling while only the final close deletes the runtime. Forced-GC heap nevertheless remained at the Phase 0 failure level, so deleting the map entry is necessary but not sufficient to release the retained runtime graph |
| Use explicit window ownership in package and performance diagnostics | Complete | Removed every `globalThis` reference from runtime source. `PackageManager` now compares package windows with the plugin bundle's main `window` directly, matching its existing lease logic; its `setPackage()` parameter was renamed from `window` to `win` to avoid shadowing that owner. Phase 0 diagnostics now read main-window local storage/performance and install the manual checkpoint on a narrowly typed `window`. These are lexical equivalents in the plugin's main bundle realm, preserve plugin-global diagnostic aggregation and main/popout labels, and satisfy Obsidian's popout-safety scanner without hiding the references in Rollup |
| Release individually removed Canvas nodes (Phase 1A.2) | Complete | `CanvasNodeFactory.removeNode()` now removes the map entry by its canonical Excalidraw element ID with a node-identity guard, and falls back to an identity lookup for compatibility with callers that omit the ID. Runtime validation confirmed individual removal `7→6`, undo recreation to 7, linear teardown to zero, a zero-node final purge, and complete close lifecycle with no console errors |
| Bound scene-file loader stalls (Phase 1A.3) | Complete for the observed failure scene; forced-timeout branch not triggered | Each scene-file task pool now has a 30-second inactivity watchdog reset whenever a task settles. A stalled pool records `terminalState=timed-out`, terminates remaining work, and guarantees exactly one final callback so the view releases `activeLoader` and advances its coalesced next request. Completed, externally terminated, depth-limited, and unexpected-failure paths also expose a terminal state. Missing-vault-file retries retain the existing 30-attempt bound but now whitelist only those missing file IDs; URL/local-link entries cannot turn recovery into repeated full-scene reloads. The prior 169-file SYL failure scene completed with all 169 files in 7.51 seconds; its three initially unresolved entries were external/local rather than missing vault files, and no loader remained active or stalled. The 46-file MOC EA regression scene and a subsequent forced save also completed normally |
| Decouple blur persistence from scene-file refresh (Phase 1B.1a) | Complete | The public `forceSave()` facade keeps its historical save-plus-scene-refresh behavior for scripts, manual save, and recovery callers. Its implementation now delegates to a private policy method, and only the window-blur path selects persistence without `loadSceneFiles()`. Runtime validation confirmed that blur persisted the edit with `refreshSceneFiles=0` and no blur-attributed scene-file request, while manual titlebar save retained `refreshSceneFiles=1` and its matching scene-file request. Disk serialization, backup scheduling, autoexport policy, embed-update notification, busy-save handling, active image/embeddable guards, and public method arguments remain unchanged |
| Linearize save synchronization and metadata lookup (Phase 1B.2a) | Complete | Save synchronization now indexes current linked non-text and text elements in one scene pass instead of filtering the full scene once per stored link/text entry. Markdown metadata generation builds a unique-ID index once, retaining the previous exactly-one-match rule for text-element links. Binary-file cleanup uses `Set<FileId>` membership in both the view snapshot and embedded-data registries. Map iteration and serialized section ordering, first-match behavior, save APIs, scene mutation ordering, compression, and persistence policy are unchanged. MOC EA testing exercised deletion cleanup, linked-text/image persistence, classification fallback, loader completion, and Canvas teardown. A Sidecar-off SYL run at the original 3,654-element/1,734-text/169-file scale reduced average synchronization from 183.96 ms to 37.20 ms and metadata generation from 76.44 ms to 2.60 ms. Coherent snapshot plumbing and mutation-sensitive duplicate-image grouping remain separate checkpoints |
| Index image elements by current file ID during save synchronization (Phase 1B.2b) | Complete | `syncFiles()` now builds its image list, original file-ID iteration snapshot, registry-membership set, and `FileId → image elements` groups in one scene traversal. Duplicate splitting keeps the historical original-ID iteration order and newest-element comparator while moving each reassigned element between live groups, so later duplicates see only elements that still carry the original ID. The final scene-file/Mermaid classification pass reads the same mutation-aware groups rather than filtering the full scene once per binary file. Registry rules for ordinary embedded files, equations, Mermaid, Markdown images, hyperlinks/local links, and fresh pasted images are unchanged. Runtime testing split three ordinary duplicates of one equation into three durable registry entries, then removed one cleanly. Sidecar-off SYL synchronization fell from the Phase 1B.2a 37.20 ms average/52.10 ms maximum to 15.50/19.60 ms |
| Reuse one coherent save snapshot through synchronization and serialization (Phase 1B.2c) | Complete | Each actual save now captures app state, the scene, selected-element IDs, and deleted elements once. Synchronization consumes the selected IDs from that app-state capture; a synchronization-triggered `loadDrawing()` and Markdown serialization consume the same deleted-element set; serialization consumes the same scene object that synchronization updates. The public `getScene()` and `prepareGetViewData()` signatures and fallback behavior remain unchanged through private helpers. The popout/view-unload workaround deliberately retains its second serialization call and delayed vault write, but both serializations now use the same save-owned snapshot. Compatibility-mode saves also serialize that one snapshot. Runtime validation covered the mutation-sensitive equation split, popout delayed-write workaround, deleted-element cleanup, compatibility serialization, and same-scale SYL save/reopen. The observed inline-link-suggester interruption was traced to the pre-existing body mutation observer saving when the suggester mounts, outside this snapshot checkpoint |
| Coalesce drawing-backup persistence by vault path (Phase 1B.3a) | Complete | The main-window-owned `ImageCache` now delegates delayed drawing backups to a plugin-global `BackupPersistenceQueue`. Each path retains at most one active IndexedDB transaction and the latest trailing payload; a new queued payload replaces an obsolete one while preserving the existing 50 ms post-save delay. Backup writes now resolve on transaction completion rather than request scheduling. Rename flushes queued data before moving the backup key, deletion and backup-cache clearing cancel queued data after any active transaction settles, and plugin unload drops timers/references without starting new writes. Image-cache clearing remains independent. Save diagnostics distinguish scheduling, coalescing, and completed physical writes. Runtime validation covered popout/main timer ownership, two completed IndexedDB transactions, rename/save/reopen, deletion, and package/loader lifecycle. Timing-sensitive replacement, trailing-write, flush, and pending-cancellation branches are covered by the deterministic queue harness. Autoexport policy and general save-reason semantics remain separate Phase 1B.3 checkpoints |
| Make save side-effect policy explicit (Phase 1B.3b) | Complete | The public `save()` and `forceSave()` facades retain their signatures and behavior while delegating to private policy-aware implementations. A force-save policy now independently states whether to refresh scene files and whether to run save-time autoexport; save diagnostics carry the originating reason and selected autoexport policy through request, export scheduling, and completion. The window-blur path remains persistence-only with respect to scene-file loading, but deliberately retains SVG/PNG/Excalidraw autoexport and `onTriggerAutoexportHook`: repository documentation promises autoexport each time a drawing is saved, so the handoff's contract exception applies. Runtime validation confirmed that blur persisted and autoexported without a scene-file refresh, manual save retained both behaviors, and close/reopen restored all edits |
| Extract view save coordination without changing semantics (Phase 1B.4a) | Complete | Added a view-scoped `ViewSaveCoordinator` that owns the existing public-save and force-save routing, explicit side-effect policies, dirty-state transitions, autosave timer/function, and teardown/navigation force-save orchestration. `ExcalidrawView` retains compatibility delegates and its `TextFileView`-bound serialization/disk-write body; the externally accessed `autosaveTimer` and `autosaveFunction` properties remain available through accessors. The shared save/autosave/dirty semaphores, timer intervals, busy-wait limits, notices, Excalibrain unload exception, blur/manual policies, loader refresh behavior, and close ordering are mechanically unchanged. Runtime validation covered autosave, manual and blur force-save policies, main↔popout migration, teardown persistence, runtime deletion, and durable reopen with all five edits. Revision tracking, in-flight coalescing, and `flush()` remain the separate Phase 1B.4b checkpoint |
| Preserve edits made during persistence with revision/coalescing semantics (Phase 1B.4b) | Complete | `ViewSaveCoordinator` now advances a monotonic current revision from Excalidraw durable store increments and existing explicit dirty calls, records the revision owned by each save request, and advances the saved revision only after persistence, an unchanged terminal result, or the established view-unload scheduled-write handoff. One save loop owns at most one active request and one merged trailing request. Edits during synchronization/compression remain dirty and update that trailing request; an overlapping request already satisfied by the active revision is discarded without reaching the old `save.skipped` path. Manual force-save busy/notice behavior remains compatible. `flush()` waits for the loop and force-persists any revision still dirty before close or migration; the Electron delayed view-unload write remains intact. Runtime validation on SYL exercised a manual save followed by edits during compression, continued editing across successive trailing saves, final convergence to the newest revision, immediate close/reopen, and the inline `[[` regression. Serialization snapshots, side-effect policies, loader behavior, and popout runtime ownership are unchanged |
| Persist dirty window migrations before source teardown | Complete | `onWindowMigrated()` now marks migration and terminates view loaders before closing the old view. It synchronously captures the coherent scene, deleted elements, files, app-state subset, and selected-element IDs while the source API is valid, then unmounts the source React root before the first asynchronous synchronization/compression step. Main→popout may persist through the stable main realm. Popout→main performs no final drawing-file write from the source callback: it registers only serialized drawing text and stable leaf/path identifiers in a bounded 15-second, one-shot plugin manager; the replacement main-window view consumes and persists that text before parsing it. No view, DOM node, Window, React runtime, or package lease crosses the boundary. The migration callback owns the single teardown flush; later generic `onClose()` and `onUnloadFile()` safeguards skip their redundant migration saves. Retired sources reject blur-save side effects and vault-modify synchronization after unmount. Runtime validation confirmed dirty migration in both directions without freezes, lost edits, unusable replacement views, or Excalidraw console errors; close/reopen confirmed durable persistence. Ordinary autosave, manual save, file navigation, public facades, and the existing delayed non-migration unload workaround remain unchanged |
| Cancel image-loading work across runtime teardown | Complete | Rapid migration before MOC EA finished loading exposed one non-fatal `null.scheduleAction` rejection. A progressive `addFiles()` call had already started component-owned image decoding when the old runtime unmounted; the fork's Obsidian teardown nulled its store before that decode resumed. The plugin now cancels its deferred initialization callback, rejects loader work unless the initiating API identity and file path are still current, and fences `addFiles()` immediately before publication. Published fork version `0.18.127` stops a completed decode from touching store/scene state after `componentWillUnmount()`. Migration still unmounts before its first await; it never waits for image completion. No persisted data, file format, batching size, or public API changed. Repeated rapid MOC EA migration attempts with edits before image completion preserved all data and did not reproduce the console rejection; the plugin's installed production and development artifacts exactly match the locally validated fork build |
| Restore progressive live-view image presentation | Complete; deeper warm-cache work parked | The live view now prioritizes image file IDs intersecting the initial viewport and publishes loaded assets in batches of at most eight, allowing the owning window two animation frames between immediately available batches. Export, automation, and deferred-validation loaders retain their existing unbounded collection behavior. MOC EA displayed its first image after about one second in the settled run and completed after about eight seconds; the startup-contention run displayed the first image after about four seconds and completed after about ten. Panning remains choppy while loading because later `addFiles()` calls still block for up to 346 ms and individual cached SVG materialization waits reached 1.25 seconds. Do not broaden this checkpoint into image-payload caching; profile and address warm-cache materialization only after the window-runtime migration direction is settled |
| In-memory popout migration handoff (Phase 1C) | Reverted and parked | The drawing-state handoff registry and ImageBitmap prototype were removed from the Phase 1A/1B delivery branch. Although state parsing and destination runtime initialization were fast, publishing transferred bitmaps through the newly created destination runtime blocked for roughly 17 seconds and drove heap use to roughly 2.19 GB; repeated MOC EA moves could freeze Obsidian after Electron destroyed the source window. The rejected work remains recoverable in local archival branch/stashes, but no fork API or plugin runtime dependency from that experiment is part of this checkpoint. A future branch should first spike whether one persistent main React object can create fresh roots across main/popout documents while preserving event, portal, observer, and owning-document behavior; only evidence from that spike may justify simplifying or removing `PackageManager`. Begin with small drawings before returning to MOC EA migration or drawing/image state transfer |
| Distinguish real modal opens from inline suggestion portals | Complete | `ObserverManager` now saves dirty drawings for real Obsidian modals in both the main workspace and popouts while excluding inline suggestion portals. Popout traces proved the observer was correctly bound to the destination document but the shared `instanceof`-based element guard rejected its mutation nodes. Modal classification now uses a local realm-independent node check, scans every direct body addition and its subtree for `.modal-container`, and retains the observed destination view rather than looking it up again during the callback. Same-leaf replacement initialization rebinds the observer because window migration may not emit `active-leaf-change`. Production observation remains limited to direct body child additions; the temporary subtree/attribute observer and all modal diagnostics were removed after validation |
| Stabilize known Excalidraw-file classification across metadata-cache refresh | Complete | Same-tab back navigation can begin loading a parent drawing immediately after its embedded child drawing finishes saving. During that interval Obsidian's metadata cache can temporarily lack the child's frontmatter. `PluginFileManager.isExcalidrawFile()` now treats parsed frontmatter as authoritative when present and otherwise falls back to the manager's existing set of previously confirmed Excalidraw files. Runtime validation reproduced the cache gap, exercised the fallback during both parent parsing and embedded-file loading, and immediately rendered the updated two-circle child correctly. The metadata `changed` event removed the remembered classification after deliberate frontmatter removal; the file then rendered as ordinary Markdown and no further fallback occurred. No vault reread, delay, retry, or navigation behavior was added |
| Defer vault-wide inline link suggestions until invocation | Implemented; awaiting focused runtime validation | `InlineLinkSuggester` now starts with no file-link candidates and takes its existing one-per-editor snapshot only when the caret first enters an active file wikilink after `[[`. Merely entering or editing ordinary text no longer calls Obsidian's synchronous full-vault `metadataCache.getLinkSuggestions()` filter/sort path. Heading, block, frame, clipped-frame, tag, alias, insertion, and popout behavior retain their existing paths; explicit refreshes remain no-ops until the lazy snapshot exists. Fixes [#2907](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2907) |
| Consolidate EA script compilation and lifecycle ownership for 2.27 | Implemented; automated validation complete, focused runtime validation pending | `ScriptEngine` now shares only compiled code for unchanged script files, with vault-event/stat invalidation and in-flight compilation coalescing. Manual, plugin-startup, view-autostart, sidepanel-restore, sidepanel-reload, and drawing-onload triggers retain distinct EA ownership. Automatic attachment is deduplicated per script path/view without restricting manual re-entry. The plugin startup script now uses ScriptEngine with the plugin-global EA, and every EA exposes synchronous `registerCleanup()`. Slideshow and Mindmap Builder remain compatibility canaries rather than migration targets |
| Remaining view phases | Parked | `MarkdownImageController` and `ViewSceneFileManager` are both closed (user-confirmed manual testing, no issues). The Phase 7 React-root extraction (`ExcalidrawRoot.ts`) was never explicitly re-confirmed after its own checkpoint note was written and should be the first thing re-validated if this plan resumes. `ViewInteractionController` (hover preview + pointer/key handling) was explicitly declined by the user for now and remains the last Phase 6 controller candidate if resumed. Phase 8 (converting the extracted React root to TSX) should follow only after the React-root checkpoint is confirmed closed. See "Parked: next steps if resumed" |
### Upstream cross-document host contract: PRs #11997 and #12018
This dependency may remain unresolved across several upstream release cycles.
The integration must therefore preserve the following context independently of
the current conversation and of either PR's temporary implementation details.
#### Required Obsidian architecture
- The plugin bundles one private React runtime and evaluates one Excalidraw
runtime. Multiple independent `App` instances may be mounted concurrently in
the main document and in one or more popout documents.
- Every mounted editor receives its stable `ownerDocument`; its `ownerWindow`
is derived from that document. A view migration synchronously destroys the
source React root and creates a new destination-owned root. The existing
`App` is never moved between documents.
- DOM nodes, events, observers, timers, fonts, portals, `Image` instances, and
canvases retained by an editor must belong to that editor's document/window.
A mutable process-global "current window" cannot represent concurrent Apps
and must not be changed as views gain focus.
- The process-wide render environment is appropriate only for detached calls
that have no mounted App (including headless/server callers). App-owned work
must use an instance- or call-scoped environment derived from the requesting
editor.
- Destroy/recreate what belongs to the Window; transfer what belongs to the
drawing. Do not retain a React tree, decoded DOM image cache, in-flight image
promise, DOM node, or Window across migration.
#### Upstream state audited on 2026-09-01
- [PR #11997](https://github.com/excalidraw/excalidraw/pull/11997) is open
against upstream `master`. Its current branch includes generic
cross-document handling for fonts, ordinary and hyperlink tooltips, scene
images, owner-window animation scheduling, and per-instance animation keys.
Márk's additions prewarm the actual current-item font rather than always
Excalifont and replace process-global tooltip/hyperlink ownership with
editor-owned lifecycle state. These changes directly benefit simultaneous
main/popout editors and popout teardown.
- [PR #12018](https://github.com/excalidraw/excalidraw/pull/12018) is stacked
on #11997 rather than directly on `master`. At audited head
`ab6f203e9d5473a6b5717ee6580ccfbecbe5b897`, it introduces
`RenderEnvironment` with `createCanvas()`, `createImage()`, and optional
`createPath()`, a global default for unscoped/headless operations, explicit
per-render overrides, and an App environment derived from
`ownerDocument`/`ownerWindow`. Canvas, image, text-measurement, freedraw,
export, placeholder/link-image, and render-cache paths are routed through
this contract. Environment identity and backing-store scale are part of the
cache isolation strategy.
- The narrow `createImage` argument in #11997 is an internal bridge used by
`App.updateImageCache()`; the plugin does not call it. It may disappear once
the broader contract replaces it, but the behavior it provides—creating the
retained scene-cache image in the requesting App's window—must remain.
- `blob.ts` currently uses the global/default environment for the transient
dimension probe during image insertion. The retained App image is decoded
again through the App-owned path. This has not caused an observed Obsidian
failure, but popout image insertion remains a required integration test.
App-triggered canvas export now passes its per-instance environment;
standalone `exportToSvg()`/`exportToBlob()` calls remain detached operations
and can use their explicit/default environment.
#### Final code-review conclusion at the audited head
The two functional gaps found at the earlier `b3e4cf963` head are resolved:
`ExcalidrawBase` forwards the public `renderEnvironment` prop to `App`, and
`App.updateImageCache()` creates retained scene images through
`this.renderEnvironment.createImage`. A focused public-prop test exercises the
supplied canvas and image factories. Further changes isolate text measurement
with environment-keyed weak caches, create freedraw paths through the
environment, and make static-scene throttles track the canvas's current owning
window so teardown or adoption does not leave callbacks in the source realm.
Upstream CI is green at this head.
The generic test describing inference when `ownerDocument` is omitted remains
less decisive than its name because the wrapper still has a module-document
default. This is not an Obsidian blocker: the plugin always supplies each
view's stable `ownerDocument`, and the explicit-document and explicit-
environment paths needed by the plugin are covered. Confirm this scoped code
review separately from runtime acceptance; the latter occurs only after the
final upstream work is merged into the fork and installed in the plugin.
#### Adoption and acceptance when upstream settles
1. Merge the final upstream commits into `@zsviczian/excalidraw`; remove only
fork deltas that are genuinely superseded. Preserve and line-fingerprint
fork-only highlighter, Obsidian WYSIWYG, host-adapter, and other
Obsidian-only ownership paths.
2. Prefer continuing to pass only the stable `ownerDocument` from the plugin
and let upstream derive the App environment. Pass an explicit
`renderEnvironment` only if the final API requires it; never configure the
process-global environment per active view.
3. Rebuild/publish the fork, install the exact published version in the
plugin, and rebuild before treating the integration as complete. Do not
commit a plugin dependency on unpublished local artifacts.
4. Run one focused concurrent-editor test with an image and linked element in
both main and popout windows; verify image decoding, link icons, ordinary
tooltips, hyperlink tooltips, click/Escape behavior, and closing one editor
without hiding, retaining, or breaking the other editor's UI.
5. Run one blank/new popout test using the selected current-item font, one
popout image-insertion test (the `blob.ts` probe), and SVG plus blob export
from both main and popout editors.
6. Run one dirty main→popout→main migration, including migration during
progressive image loading, and recheck the maximized-popout hand and laser
tools. The source root must still unmount before the first await, no edit may
be lost, and no source-window callback may survive teardown.
7. Re-run the bounded package/runtime and forced-GC check. Environment-keyed
weak caches and tooltip/timer ownership must not retain a destroyed popout
after its last view closes.
### Action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-09-01 | Synchronized the 2.27 EA lifecycle contract into `ea-script-template` and `ea-scripts` | Updated both repositories' ambient execution-source typings, added `registerCleanup()`, documented lifecycle ownership and manual-repeatability semantics, and refreshed their complete `.ai/excalidraw-automate` snapshots from the plugin's generated source. The only Slideshow source-adjacent change is its test fixture rename from the unreleased `autostart` value to `view-autostart`; the Slideshow runner and Mindmap Builder remain unchanged | Both repositories typecheck. Under Node 22, all `ea-script-template` tests pass (4/4) and all `ea-scripts` tests pass (91/91). Changed source files pass Prettier and `git diff --check`, and no stale literal `"autostart"` execution-source value remains outside excluded build/dependency artifacts. `ea-script-template` full lint passes; `ea-scripts` retains its pre-existing Slideshow lint backlog (105 findings, including seven errors) with no finding on the changed lifecycle fixture line |
| 2026-09-01 | Implemented the 2.27 EA script lifecycle and autostart execution refactor | Added compiled-file caching and concurrent compilation sharing without caching EAs or script runtime state; six explicit execution sources; per-view/path automatic-attachment deduplication with failure retry and unrestricted manual bypass; startup execution through ScriptEngine with the global EA; sidepanel restore/reload distinction; EA-owned synchronous cleanup; and a diagnostic for duplicate persistent-sidepanel creation from view autostart. Updated source API help, release notes, scripting documentation/template, and the documentation generator. Slideshow and Mindmap Builder source were inspected but intentionally not modified | `npm run build`, `npm run lib`, bundle syntax, touched-file ESLint, unused-symbol lint, `git diff --check`, and `npm run madge` pass. The established production build retains 33 circular-dependency warnings; full source lint reports 123 existing errors/0 warnings in 19 untouched files, and TypeScript reports 28 existing errors with none in touched files. `dist/main.js` is 4,975,687 bytes, 4,343 bytes above clean HEAD and 267,193 bytes below 5 MiB. Local generated documentation was refreshed and the two external script-authoring repositories were subsequently synchronized through their own `sync-refs` commands. Focused Obsidian runtime acceptance remains pending: cleanup across plugin reload/view close, `.md` and `.js` cache invalidation, the permission/view-initialization race, Slideshow mixed automatic/manual behavior, Mindmap Builder persistent-sidepanel re-entry, sidepanel restore/reload, drawing on-load, main/popout views, and failure retry |
| 2026-09-01 | Re-audited #11997 and final #12018 head `ab6f203e9` after Márk's fixes | Confirmed that the previously reported public-prop and retained-image-cache wiring gaps are resolved. The final abstraction also adds environment-scoped paths, weak cache isolation, and owner-window-aware throttling needed by concurrent main/popout Apps. Code review now supports confirming the Obsidian multi-window contract, while explicitly reserving runtime acceptance for the published-fork plugin smoke test | Verified the current GitHub heads and green checks, reviewed the final wiring and focused render-environment tests, and retained the existing risk-based adoption gate below. No plugin or fork runtime source changed; documentation-only validation uses `git diff --check` |
| 2026-09-01 | Audited upstream cross-document PR #11997 and stacked host-abstraction draft #12018 | Updated the durable architecture record from the obsolete per-window-package model to the shipped single React/Excalidraw runtime with concurrent document-owned Apps. Recorded Márk's font, tooltip/hyperlink, animation, per-instance render-environment, cache-isolation, and export work; the distinction between global detached/headless defaults and App-scoped host factories; the current fork/adoption strategy; and the risk-based acceptance gate. At #12018 head `b3e4cf963`, identified two concrete override-wiring gaps (`renderEnvironment` is not forwarded from `ExcalidrawBase`, and `App.updateImageCache()` bypasses it) plus a non-blocking fallback-test weakness. No plugin or fork runtime source changed | Reviewed both PR commit histories, changed-file lists, issue comments, line reviews, and the relevant current source/tests through GitHub. Cross-checked the local plugin/fork status and current fork commits. Documentation-only validation uses `git diff --check`; upstream remains draft and must be re-audited at its final head before any fork merge, package publish, or plugin dependency change |
| 2026-08-27 | Deferred issue #2907's full-vault link scan until `[[` is invoked | Removed `getLinkSuggestionsFiltered()` from `InlineLinkSuggester` construction and changed `getItems()` to expose only the current lazy snapshot. The first active file-wikilink context loads that snapshot once; subsequent characters and links in the same editor reuse it. Explicit refresh updates an existing snapshot but does not accidentally prime one during ordinary text editing. Specialized tag, heading, block, frame, and clipped-frame suggestions remain independent | Production build passes with the established 33 circular warnings; scoped lint and unused-symbol lint pass; bundle syntax and diff checks pass. Full source lint retains exactly the established 138-error/0-warning backlog with no finding in either changed source file. Source inspection confirms construction/focus contains no candidate scan and the only `InlineLinkSuggester` scan sites are the guarded lazy load and explicit post-load refresh. Focused runtime validation should first confirm that entering and editing ordinary text does not pause, then type `[[`, choose a file, and confirm insertion. Repeat `[[` in the same text element and test one heading or block target plus one tag. Run the ordinary-text and file-link checks once in a popout because the attached input and suggestion portal are document-owned. The highest-risk regression is an empty file-link menu caused by failing to populate the lazy snapshot; broad migration, MOC EA, save, export, and mobile testing are not required |
| 2026-08-27 | Replaced the obsolete compressed React bootstrap with normal Rollup bundling | Removed the nested `buildReactRuntime` build, its entry module, compressed/evaluated `REACT_PACKAGES` string, fragile regex insertion, and `@zsviczian/rollup-plugin-postprocess`. `PackageManager` imports the official React, ReactDOM legacy/client, and JSX runtime modules directly, preserving the production `jsxDEV` fallback and supplying the same instances to the separately evaluated Excalidraw artifact. React stays external only for the library build and the fork's own Obsidian artifact. Also removed the obsolete local `any`-dominated `ownerDocument` compatibility cast now that `@zsviczian/excalidraw` types the prop | Production, development, and library builds pass under Node 22.22.2; production retains only the established 33 circular warnings, and development retains its established sourcemap-option warning. The production bundle is 4,952,291 bytes: 114,871 bytes above the compressed-bootstrap baseline but still 290,589 bytes below 5 MiB. Bundle syntax, scoped ESLint, unused-symbol lint, dependency deduplication on React/ReactDOM 19.2.8, and temporary Madge 8 validation pass. Full source lint retains exactly the established 138-error/0-warning backlog with no finding in a changed source file. No emitted or source reference to `REACT_PACKAGES`, the deleted builder, React window globals, or external production `require("react")` remains. Focused runtime validation must prioritize one cold plugin restart and one dirty main↔popout round trip; the highest risks are bootstrap ordering/duplicate React and cross-document event ownership, not save serialization or scene-file policy |
| 2026-08-27 | Finalized the published Phase 1C.2c plugin checkpoint | Installed exact dependency `@zsviczian/excalidraw@0.18.128` after the accepted fork branch was merged to the fork's master. The package declarations expose `awaitImageFiles()`, so the plugin's bounded migration publication now rests on its committed internal protocol rather than a locally copied artifact. The dependency and lockfile contain only the expected `0.18.127`→`0.18.128` update | The maintainer ran `npm install`, a production build, and a plugin smoke test successfully. Independent final validation passed the production and library builds, bundle syntax, unused-symbol check, diagnostic-prefix absence, and Madge with no cycle. Scoped ESLint remains exactly at the established 18 `ExcalidrawView` unsafe-type findings and reports no finding in `ViewSceneFileManager` or the new migration code. The lockfile/manifest retain their intentional CRLF format |
| 2026-08-27 | Finalized the fork's cross-document delta and opened upstream Excalidraw PR [#11997](https://github.com/excalidraw/excalidraw/pull/11997) | Committed the fork-only, line-fingerprinted tooltip and image-realm completion as `c8fd88729`; the earlier empty-scene font fix remains in `8a6202cae`. Recreated the complete generic delta without fingerprints or Obsidian-only code on a clean branch from merged upstream PR #11974. No modal code changed because its owner-document portal is already correct. The only retained performance opportunity from the discarded handoff notes is to prevent the filtered disk fallback loader from overlapping progressive in-memory publication when every required file is already transferred; decoded `imageCache` transfer remains explicitly rejected because it contains document-owned images and promises | The fork cross-document suite passes 3/3, its Obsidian artifact/declaration build passes, and the plugin production bundle builds against the four refreshed local artifacts. Fork-wide typecheck retains its established unrelated test backlog. On the clean upstream branch, all six touched files pass ESLint, the focused suite passes 2/2, full `yarn test:typecheck` passes, and GitHub reports PR #11997 mergeable with lint, coverage, semantic-title, and Vercel checks passing |
| 2026-08-27 | Runtime-accepted and cleaned Phase 1C.2c | MOC EA's migration path is down from the pre-refactor 70–90 seconds to approximately 4–8 seconds. The empty editor appears immediately, the first image appears within approximately two seconds, and dirty or mid-load migration remains responsive and retains edits. Removed every `EXCALIDRAW_MIGRATION_TIMING_DIAG` source and manager hook after acceptance. Separating the plain `BinaryFiles` record from `App` would not improve this further because the exact record already crosses the handoff; the remaining decoded `imageCache` contains DOM-owned `HTMLImageElement` objects/in-flight promises and is cancelled and cleared on unmount. Making that cache transferable would require a new shared lifetime, cancellation, eviction, realm, and memory contract and is deliberately rejected as a non-targeted change | The final trace shows destination React initialization falling from 13–15 seconds to approximately 0.2–0.4 seconds and bounded publication of all 46 transferred files. One direction also started a filtered fallback loader during publication and completed more slowly; this is retained as a future narrow coalescing opportunity, not a reason to broaden the accepted checkpoint. The maintainer explicitly stress-tested edits and migration during loading in both directions without loss or slowdown. Production build, bundle syntax, targeted lint, unused-symbol lint, Madge, and diff checks pass after diagnostic removal |
| 2026-08-27 | Implemented Phase 1C.2c progressive in-memory migration-file publication | The replacement editor no longer receives all transferred files in `initialData`, which was the blocking decode point. It paints the scene/runtime first, prioritizes files intersecting the current viewport, and publishes bounded batches without rereading or rebuilding transferred assets. The fork adds only `awaitImageFiles(fileIds)`, an imperative completion boundary over its existing private image-cache promises; it does not expose or transfer the DOM-owned cache. Cancellation checks stop publication when the editor migrates or unloads, and the established loader remains the missing-file/error fallback | The fork's focused cross-document test proves that `awaitImageFiles()` remains pending until decoding started by `addFiles()` completes. That test, targeted ESLint, the Node-22 Obsidian artifact build, the plugin production build against the four locally copied artifacts, bundle syntax, unused-symbol lint, Madge, and `git diff --check` pass. The fork's repository-wide `test:typecheck` remains unusable because of its established test backlog (missing `window.h`, implicit-any fixtures, and related failures outside this change); the focused test is deliberately housed in the currently runnable cross-document suite. Runtime acceptance is one complete MOC EA main→popout→main round trip with one unsaved edit: record loading/UI/first/all-image times in both directions, pan and zoom during progressive loading, verify the edit survives, exercise undo on a second destination edit, reopen for durability, and report the filtered timing trace plus any unfiltered Excalidraw error. A separate rapid-reversal cancellation test follows only if this first comparison passes |
| 2026-08-27 | Closed Phase 1C.2b migration-stage measurement | In both directions the destination consumed the 246-element/46-file handoff in under 0.2 seconds and reached `reactRenderRequested` immediately. Excalidraw then took approximately 13.1 and 14.6 seconds to call `onInitialize`; during this interval its API changed from zero to all 46 files. The nominal zero-delay initialization callback was delayed approximately 4.46 and 4.45 seconds more, while the subsequent ordinary loader completed in approximately 3.5 and 24.6 ms without publishing a first batch. This directly attributes the long black loading and empty-editor intervals to all-at-once component image decoding/main-thread starvation | The maintainer's perceived timings matched the trace: 13–15 seconds of **Loading scene**, about 4 seconds of empty UI, then 2–3 seconds until all images appeared, with one direction briefly showing an unstyled editor. The next checkpoint therefore changes only how already-transferred files enter the new editor; it does not alter source capture, persistence, handoff identity, package loading, scene parsing, or normal non-migration loading |
| 2026-08-27 | Instrumented Phase 1C.2b migration-stage timing | Added the temporary `EXCALIDRAW_MIGRATION_TIMING_DIAG` trace to distinguish the black loading-view interval from library/readiness work, React initialization, and scene-file publication. The first test is deliberately the known worst complete-file return from a settled MOC EA popout to main; no edits or round trip are needed | Production build and bundle syntax pass on Node 22.22.2 with the established 33 circular warnings. The diagnostic helper and scene-file manager are clean under targeted ESLint; `ExcalidrawView.ts` retains exactly its 18 pre-existing findings. Unused-symbol lint, Madge, and `git diff --check` pass. Runtime acceptance is one popout→main move after all MOC EA images are already visible. Record the approximate loading-text end, empty-editor appearance, first image, and final image times; copy the complete filtered timing trace and report any unfiltered Excalidraw error. This targets the unexplained 15-second pre-editor delay without repeating dirty-save, partial-load cancellation, undo, modal, library, memory, or multi-cycle stress tests |
| 2026-08-27 | Runtime-validated and closed Phase 1C.2a drawing-state adoption | The small dirty round trip registered and adopted 13 elements main→popout and 14 elements popout→main; interaction, destination undo, both unsaved edits, and close/reopen durability passed without a freeze or console error. MOC EA migration interrupted the main loader after 2–3 seconds and adopted the 246-element scene plus its 24 currently available binary files in the popout; the retained loader completed the missing files. Returning the fully loaded scene adopted all 46 files in main. Removed the temporary `EXCALIDRAW_MIGRATION_HANDOFF_DIAG` trace after acceptance | Both directions reported registration followed by `found=true` adoption with no fallback. The partial round took roughly 17 seconds total; the complete return still showed approximately 15 seconds of loading view, 5–6 seconds of empty editor, and 3–4 seconds before images appeared. This proves the remaining latency is downstream of handoff validation and includes at least two stages: pre-editor initialization and destination image-cache decoding. The next checkpoint must measure those stages separately; merely reusing the exact `BinaryFiles` record cannot avoid decode work |
| 2026-08-26 | Implemented the inert Phase 1C.1 drawing-handoff boundary | Re-established only the safe contract/registry portion of the archived experiment after the single-runtime and upstream `ownerDocument` work succeeded. Kept the existing serialized persistence handoff separate because it is the proven Electron popout-teardown safety path. Deliberately excluded the rejected `ImageBitmap` cache transfer and made no `onWindowMigrated`, view initialization, scene-loader, or package behavior change. The future behavior checkpoint must destroy/recreate the document-bound editor tree because upstream requires `ownerDocument` to remain stable for an editor lifetime; it may transfer drawing state only after identity/freshness and settled-save validation, with ordinary disk loading as fallback | Production, development, and library builds pass on Node 22.22.2 with the established 33 Rollup circular warnings. The new registry and save-coordinator additions are clean under targeted ESLint; `main.ts` and `ExcalidrawData.ts` retain only their unrelated pre-existing findings. Unused-symbol lint, Madge, bundle syntax, and `git diff --check` pass. Madge was installed locally without changing either package manifest or lockfile. No manual runtime test is required because no production caller registers or consumes the new handoff; the next behavior checkpoint requires focused main→popout and popout→main tests before MOC EA stress testing |
| 2026-08-26 | Paused modal-observer changes and instrumented the unresolved popout path | Revisited the earlier inline-`[[` fix after an unsaved edit was lost when Restart Obsidian was selected from the command palette. Main-window modal saving and the LaTeX-duplicate `[[` regression both passed, but the popout command palette did not save. Subsequent attempts addressed batched mutation delivery, observing both documents, target-window `MutationObserver` construction, and explicit same-leaf destination-view rebinding. DevTools disproved the main-document placement hypothesis by showing both the command palette and Printable Layout Wizard modal in the popout DOM, and neither popout modal triggered saving after the latest attempt. No further behavioral hypothesis was applied without a trace. Temporary one-string diagnostics recorded view/leaf/document identity, observer lifetime, direct body additions, modal classification, dirty/unload/API guards, and save request/completion without filenames or scene data | The instrumented production build passed with the established circular-warning baseline; bundle syntax, scoped diagnostic-file ESLint, and `git diff --check` passed. Diagnostic reproduction used one small drawing without restarting Obsidian: main-window control followed by popout Printable Layout Wizard and command-palette attempts. The trace isolated the realm boundary recorded in the following action-log entry; all temporary diagnostics were later removed |
| 2026-08-26 | Isolated, fixed, and validated popout modal-node classification | The current-build trace bound generation 1 to the live popout document/view and received the modal's direct body insertion with `dirty=1`, `unload=0`, and `api=1`. The same callback contained an attribute mutation but reported no element target, and the added node was reduced to bare `div`; the cross-window element guard was therefore the boundary suppressing `.modal-container` matching. Replaced it only in this observer with a realm-independent element-node check. The observer scans every direct body addition and its current subtree for `.modal-container`, so Obsidian modals/command palette qualify while the inline suggestion portal does not. Removed the temporary `subtree`/`attributes` observation that generated an 898-record callback, then removed all diagnostic logging after acceptance | Production build passes on Node 22.22.2 with the established 33 circular warnings. The maintainer confirmed real modal saves in both main and popout documents. The popout command palette (`.modal-container.mod-dim`) and Printable Layout Wizard (`.modal-container`) each produced one successful save; the Excalidraw tray and inline `[[` suggester did not save, and the suggester remained usable. Targeted lint, unused-symbol lint, bundle syntax, diagnostic-prefix absence, and `git diff --check` pass after cleanup |
| 2026-08-26 | Coalesced concurrent stencil-library initialization during workspace restore | Traced the library host-adapter calls to the single plugin-owned `StencilLibraryManager`. Two views restored together could both observe `loaded=false`, enter `loadFromVault()`, and mutate the same `itemSource` map across awaited vault reads; sequential opens avoided the race. Added one shared in-flight promise and revision-checked snapshot publication. `invalidate()` now rejects an obsolete in-flight result, whose callers retry against current vault state. Persistence remains serialized by the existing save queue, and no runtime/package ownership changed | Production and library builds pass on Node 22.22.2; bundle syntax, scoped ESLint, unused-symbol lint, and `git diff --check` pass. No dependency/import graph changed, so the already-clean Madge result from the immediately preceding PackageManager checkpoint remains applicable. The maintainer confirmed restored main/popout startup, complete library contents, and the add/remove mutation safeguard with no new issue. No migration, MOC EA, memory, save, export, mobile, or broad performance rerun was required |
| 2026-08-26 | Permanently simplified PackageManager around the validated single runtime | Removed the feature switch and all code capable of evaluating React/Excalidraw in a popout. Replaced package and adapter-disposer maps with one runtime package and one disposer per typed host boundary. Kept only per-window lease counts and alias ownership because those represent view lifecycle, not runtime evaluation. The decompressed React and Excalidraw source strings and outer JSX-runtime references are released immediately after the one successful evaluation. `FontManager` now registers local metrics once against that runtime but continues injecting font styles into every open document. Updated `AGENTS.md` so future work preserves the distinction between shared runtime ownership and per-view document/window ownership | Production, development, and library builds pass against the locally built fork artifact with the established circular-warning baseline; bundle syntax and both worktree diff checks pass. Scoped lint reports zero findings in the changed manager/type/root files; full-source unused-symbol lint reports none. A temporary unsaved Madge 8 install processed the repository's configured roots with no circular dependency, then a normal Node 22 `npm install` restored the locked dependency tree; no audit fix was run and package manifests/lockfile are unchanged. The maintainer's two-view alias-lifetime, dirty bidirectional migration, plugin-reload cleanup, and popout local-font tests all passed without new issues. Concurrent startup exposed a separately scoped pre-existing stencil-library load race, recorded for the next checkpoint |
| 2026-08-26 | Added the empty-scene popout font checkpoint and completed the fork-only realm audit | A fresh editor had no scene font families, so the accepted owner-document path registered font faces in the correct document but never explicitly loaded Excalifont for the Welcome UI. The fork now adds Excalifont with a representative Latin glyph set only when the scene is empty. The accepted cross-document test forces the font-load path and proves it targets the supplied document. The post-merge fork delta audit also routed two fork-only delayed callbacks and the keyboard context menu's synthetic `MouseEvent` through `ownerWindow`. The generic follow-up findings were later consolidated into upstream PR #11997; fork-only paths remain locally fingerprinted | Focused common/cross-document tests pass (12 tests), targeted fork ESLint reports zero errors, and the fork Obsidian artifact/declaration build passes under explicit Node 22.22.2/Corepack Yarn. After copying only the four generated local artifacts, plugin development and production builds pass with the established circular-warning baseline. The maintainer confirmed that a fresh blank drawing opened directly in a popout renders the Welcome text in Excalifont and that the focused context-menu/owner-realm regression check passes |
| 2026-08-26 | Replaced the fork-only owner-document spike with accepted upstream Excalidraw PR #11974 | Stashed the superseded uncommitted spike, fetched upstream, and merged the two missing upstream commits into `performance-refactor-batch2` as fork merge commit `76647ecd8`. Resolved the four conflicts by taking upstream's public owner-document boundary while preserving existing fork behavior in embeds, fonts, WYSIWYG link suggestions, shape-action handling, cleanup, and Obsidian-specific canvas interactions. Added a concise `AGENTS.md` invariant requiring future browser/DOM additions to derive their document/window from the mounted editor. Auditing the fork-only `App.tsx` delta found and corrected five ownership gaps outside upstream's source: highlighter pixel ratio, the migration document query, active-element lookup, context-menu suppression, and right-click panning listeners. The earlier stashes remain recovery-only and should not be reapplied | The accepted cross-document test and common utility suite pass (12 tests). Targeted fork ESLint reports zero errors; `build:obsidian` and declaration generation pass under explicit Node 22.22.2/Corepack Yarn. Full fork typecheck retains its established disabled-`createTestHook` test backlog and reports no production build failure. After copying only the four generated local artifacts, plugin production and development builds pass with the existing circular-warning baseline. Plugin source lint remains at its established 138-error backlog |
| 2026-08-26 | Tightened fork fingerprinting, established a maintained fork test gate, and closed two remaining shared-runtime owner-document gaps | Replaced broad owner-document banners around existing upstream functions with line-local `// zsviczian -- reason` fingerprints; retained `START`/`END` only for cohesive fork-added units such as the host prop, owner-realm getter, DOM-realm helper, and empty-scene UI-font preload. Moved cross-realm utility coverage out of the upstream-owned `utils.test.ts` into clearly named fork-owned test files and added the explicit `yarn test:obsidian` command. `AGENTS.md` now requires line-local conflict fingerprints, restoration of formatter-only churn, a dedicated compatibility commit, a word-diff review, and the maintained fork gate during upstream merges. Empty scenes explicitly load Excalifont into the mounted editor's `FontFaceSet`; generic modal portal creation, dialog focus, and dialog timers now derive from the editor container's document/window, so reset and text-to-diagram dialogs no longer target the main document behind a popout. The hamburger/tray tooltip layering observation remains separately scoped because it is an existing z-index issue, not a document-ownership failure | `yarn test:obsidian` passes all 6 maintained files and 23 tests, including target-realm DOM guards, pointer/keyboard/clipboard/window-message/font listener ownership, explicit empty-scene Excalifont loading, tooltip placement, Radix portal behavior, and generic portal-container ownership. Targeted ESLint with `--quiet` reports zero errors. The fork Obsidian artifact and declaration build passes under explicit Node 22/Corepack Yarn; the four generated artifacts were refreshed locally and both plugin production and development builds pass with the established circular-warning baseline. Full fork `yarn test:typecheck` retains the documented historical test backlog and reports no changed-file diagnostic. Both worktree diff checks pass; focused manual popout validation remains required |
| 2026-08-26 | Extracted the shared-runtime owner-document boundary into a minimal upstream Excalidraw proposal | Preserved the working customized-fork spike unchanged, created `support-owner-document-runtime` from current `excalidraw/excalidraw` master in an isolated worktree, and reduced the proposal to the generic public `ownerDocument` contract plus the core input/listener, cross-realm element guard, font, and WYSIWYG paths needed to render a fresh editor root in another browsing context. The prop defaults to the runtime document and must remain stable for the mounted editor's lifetime. Unrelated Obsidian adapters, package management, migration logic, tooltip/portal cleanup, and fork-only formatting are absent. Commit `11261d7b7` is pushed to `zsviczian/excalidraw:support-owner-document-runtime`; upstream PR [#11974](https://github.com/excalidraw/excalidraw/pull/11974) is open for review | With dependencies installed from current upstream's own frozen lockfile under Node 22.22.2/Yarn 1.22.22, all 123 test files passed (1,862 passed, 47 skipped, 1 todo). The new iframe test verifies that pointer, keyboard, clipboard, window-message, and font listeners bind to the supplied document/window; common utility tests verify cross-realm input/writable/interactive/tool guards and scroll-container ownership. `yarn test:typecheck`, targeted ESLint with zero findings, `yarn build:excalidraw`, and `git diff --check` pass. The maintainer's focused Obsidian test of the fuller reference spike reported the shared-runtime popout behavior works well |
| 2026-08-26 | Added the explicit owner-document boundary required by the shared-runtime spike | The paired fork now accepts an optional per-instance `ownerDocument`; `App` derives its owner window and routes the input/history/clipboard/pointer listener lifecycle, DOM creation/lookups, cross-realm constructors, resize observer, pixel ratio, tooltip, and teardown through it. Font registration/loading and the text WYSIWYG's textarea, caret-measurement nodes, listeners, constructors, resize observer, and animation frame now belong to that document. Shared common input guards resolve constructors from the target's owner window, and scroll-container lookup returns the owning document. The plugin passes `view.ownerDocument` through its existing React root using a temporary widened local component type until the paired package is published. No migration/save/image/state-handoff logic changed | The fork Obsidian artifact/declaration build passes under explicit Node 22.22.2/Corepack Yarn 1.22.22. A new JSDOM iframe test proves input/writable/interactive/tool guards and scroll-container lookup accept nodes whose constructors differ from the main realm; all 11 focused utility tests pass. Only the four generated Obsidian artifacts were copied into the installed plugin package. The plugin production build passes with the established 33 circular warnings; bundle syntax, targeted plugin lint, unused-symbol lint, and both repositories' diff checks pass. Focused manual revalidation is required before expanding scope |
| 2026-08-26 | Minimized and fingerprinted the fork-only owner-document fallback | Removed formatter-only churn from the working fork spike while preserving all owner-realm behavior, reducing `App.tsx` from 590 to 253 changed lines and the original nine tracked source/test files from 921 to 565 changed lines after adding the required fingerprints; the new standalone regression test is 142 lines. Added cross-document coverage for listener/font ownership and tooltip placement, plus an `AGENTS.md` upstream-merge audit that requires reviewing new `document`, `window`, constructor, observer, timer, and listener usages against the stable per-instance owner realm. The complete pre-cleanup spike remains recoverable in the named fork stash `owner-document spike before minimal fingerprint pass` | The two focused test files pass (13 tests); `yarn build:obsidian` and its declaration generation pass under explicit Node 22; plugin production and development builds pass against the four refreshed local artifacts (`dist/main.js` production size 4,828,452 bytes). Repository-wide `yarn test:typecheck` and `yarn test:update` retain unrelated fork-baseline failures (`window.h` typing and missing `createTestHook` export); the latter's two generated snapshot-file edits were removed. No changed production source remains in the typecheck diagnostics, and `git diff --check` passes |
| 2026-08-26 | Started the batch-2 persistent-main-runtime feasibility spike | `PackageManager.getPackage()` now returns the already-evaluated main-window React/ReactDOM/Excalidraw package for a popout while preserving the popout as the lease's acquisition/migration window. It installs only a temporary `window.ExcalidrawLib` compatibility alias in the popout, removes that alias on the final popout lease, and leaves package-map and typed-host registration ownership with the single evaluated main runtime. The former per-window evaluation path remains intact behind one spike constant for immediate comparison or rollback. No fork source, root migration, save, scene/image loading, or drawing-state handoff changed. Static fork review found extensive lexical `window`/`document` use in `App.tsx`; therefore this checkpoint is only a feasibility probe, not evidence that PackageManager can yet be simplified | Node 22.22.2 production and library builds passed with the established 33 Rollup circular warnings; bundle syntax, targeted PackageManager/type lint, unused-symbol lint, `git diff --check`, and the repository Madge script passed. Full source lint remains exactly at the established 138-error/0-warning backlog, with no finding in either changed source/type file. Madge 8 was installed temporarily without saving it, the structural check processed its usual 8 roots with no cycle, and `npm install` restored the exact manifest dependency tree afterward; no audit fix was run and package manifests/lockfile are unchanged. The first small-drawing gate confirmed shared rendering and the owner-document Radix color picker, while pointer drawing and Cmd+Z failed and the active text editor used a fallback font until submission. Those failures match the audited lexical main-document listeners, cross-realm constructor checks, main-document WYSIWYG creation, and main-document font loading; the test correctly stopped before dirty migration, MOC EA, or memory work |
| 2026-08-25 | Fenced progressive image loading across rapid runtime teardown | A stress test moved MOC EA repeatedly without waiting for image completion and preserved every edit, but once exposed `updateImageCache()` resuming after unmount and reading the fork's nulled store. The view now clears the zero-delay initialization timer before migration/close/unload; all immediate, deferred, queued, and retry scene-file paths reject a migrating/unloaded view, a replaced/destroyed API, or a changed file; and the shared publication helper rechecks the same boundary immediately before `api.addFiles()`. Because `addFiles()` starts component-owned asynchronous decoding and returns `void`, the fork also returns an empty result if decoding resumes after `componentWillUnmount()`. Waiting for decode before unmount was rejected because it violates the proven Electron freeze invariant | The paired fork `build:obsidian` passed under a deterministic Node 22.22.2/Yarn 1.22.22 PATH. Its repository-wide typecheck retained the existing test-typing backlog and reported no error in `App.tsx`. The maintainer repeated rapid MOC EA migrations several times, editing before image completion; all edits survived and the `scheduleAction` rejection could not be reproduced. Fork `0.18.127` was then published and installed as the plugin's exact dependency; its production and development artifacts hash-identically match the local runtime used for manual acceptance. The published-artifact plugin production/library builds, unused-symbol lint, bundle syntax, scoped manager lint, and source/documentation diff checks passed; package manifests retain the repository's existing CRLF endings. Full lint remains at the established 138-error/0-warning backlog, and `ExcalidrawView.ts` retains its same 18 pre-existing unsafe-type findings. No further stress loop, memory run, SYL, export, backup, missing-file, mobile, or PDF Plus test is required |
| 2026-08-25 | Fenced null-API callbacks on the retired migration source | Moving the source React unmount before the first await eliminated the reproducible Electron freeze in both dirty popout→main and dirty main→popout tests, with edits preserved. The console then exposed two deterministic cleanup races: an already-started blur save reached autoexport after unmount, and the handoff's destination write caused `FileManager` to synchronize the still-discoverable retired source. Autoexport/dialog creation, blur post-save side effects, modify-event dispatch, and `synchronizeWithData()` now all reject a window-migrating/null-API source while leaving the replacement destination eligible. The crash invariant is also recorded in `AGENTS.md` and adjacent TSDoc so future lifecycle changes do not move unmount behind an asynchronous boundary | The final console-focused dirty round trip passed in both directions: no freeze, both edits persisted through close/reopen, destination interaction remained usable, and the `ExcalidrawView.save`/`synchronizeWithData` errors were gone. Existing PDF Plus errors were confirmed unrelated and remain out of scope |
| 2026-08-25 | Moved migration React teardown ahead of all asynchronous save work | Debugger tracing established that dirty migration invoked `forceSaveIfRequired()` three times (migration callback, `onClose()`, then `onUnloadFile()`) and that the reproducible freeze began specifically at `excalidrawRoot.unmount()`. Moving unmount outside `closeLeafView()` still froze, disproving reentrancy as the root cause and isolating the unsafe interval to the awaited synchronization/compression before teardown. The migration callback now synchronously captures one coherent save snapshot, unmounts immediately, and performs its sole flush from captured drawing-owned data; `onClose()`/`onUnloadFile()` retain only non-save cleanup for that migration. All non-migration lifecycle paths keep their original save-before-unmount behavior | Static/build validation precedes one risk-limited dirty popout→main rerun. Acceptance requires exactly the previously failing workflow: the destination appears without a freeze, the unique edit is immediately present and survives close/reopen, and no new Excalidraw console error appears. Stop after the first attempt if Obsidian still freezes |
| 2026-08-25 | Removed native file access from dirty popout→main teardown | The diagnostic-free smoke test first lost the popout edit and froze twice. Marking migration earlier and awaiting a main-realm Vault write made the edit durable but still froze twice, proving that any native write initiated by the old popout migration callback is unsafe. The source now performs serialization only and registers a bounded serialized-text handoff; after the old view closes, the replacement main view consumes and persists it before parsing. Main→popout keeps the simpler direct persistence path because the source main realm is not recycled | Production build, library build, unused-symbol lint, bundle syntax, scoped lint, and diff checking precede one focused rerun of the exact failing popout→main dirty migration. Acceptance requires no freeze, the edit to survive destination load and close/reopen, and no new Excalidraw console error. Also make one dirty main→popout move to confirm its already-working direction remains intact. No repeated cycles, memory, SYL, backup, export, missing-file, or mobile test is required |
| 2026-08-25 | Removed temporary Phase 0 diagnostics from the delivery branch | Preserved the exact validated source and instrumentation on local branch `performance-refactor-1b-instrumented`, then removed diagnostic imports, events, counters, timing callbacks, reason-only parameters, and the manual console checkpoint from production source. The backup queue, save coordinator, package leases, loader termination, Canvas-node removal, save indexes/snapshot, classification fallback, modal observer fix, and progressive image batching remain intact. Removed the locally installed Madge dependency and generated lockfile churn from the PR while keeping master’s existing script entry and the independent repository-zip script requested for delivery. The untracked handoff folder was removed at the end of batch 2 after its durable decisions and sole remaining optimization opportunity were consolidated into this plan | Production and library builds, unused-symbol lint, targeted lint, bundle syntax, diagnostic-prefix search, and scoped diff checking passed. Full lint remains exactly at its established 138-error/0-warning backlog, and the diagnostic-free production bundle is 4,821,700 bytes. The final risk-based runtime smoke test is one MOC EA main→popout→main round trip with one edit, close/reopen durability, progressive image completion, and no freeze or new console error; repeated migration, memory, SYL, backup, export, missing-file, and mobile retests are not required for this cleanup |
| 2026-08-25 | Restored bounded progressive image presentation and closed the pre-PR checkpoint | Live-view loads sort embedded-file work toward the image IDs intersecting the initial viewport, publish no more than eight files per batch, and wait for an owning-window paint opportunity before draining another immediately available batch. A 250 ms fallback prevents a hidden or destroyed window from holding loader completion. Non-view consumers do not opt in. The MOC EA viewport contained all 46 image IDs, so ordering did not distinguish them in this scene; bounded publication itself supplied the visible progress | Both MOC EA runs completed all 46 files in seven batches with `terminalState=completed`, scheduled background validation, emitted no changed files, and reported no errors. The startup-contention run took 9.16 seconds and first displayed an image at about four seconds; after settling, the first image appeared at about one second and completion took about eight seconds (diagnostic loader duration 9.84 seconds). The maximum synchronous batch fell from the earlier 37-file/628 ms publication to 346 ms, but total publication work increased and panning remained choppy. Cached SVG materialization, not hashing or save synchronization, is the remaining dominant interaction risk and stays parked until after the migration architecture decision |
| 2026-08-25 | Reverted the Phase 1C migration prototype before preparing the Phase 1A/1B PR | Preserved committed 1C.1/1C.2 on the original `performance-refactor` branch, stashed the rejected plugin 1C.3 bitmap handoff and all sibling-fork bitmap changes under explicit names, and created the delivery branch at the validated end of Phase 1B. The sibling fork source was clean and master-equivalent, and its clean Obsidian artifact replaced the experimental local runtime. The handoff folder remained untracked and outside that delivery; it was removed after batch 2 was accepted and its durable conclusions were consolidated here | This avoided carrying the prototype's 17-second destination `addFiles()` pause, approximately 2.19 GB heap peak, and source-window teardown freezes into the PR. The Phase 1A/1B commits and independent repository-zip script remain in history. Future work resumed with the persistent-main-runtime feasibility spike documented above |
| 2026-08-25 | Runtime-validated and closed Phase 1B.4b | SYL's asynchronous compression provided repeated in-flight edit windows. Each completed save advanced only its owned revision: when newer edits existed, diagnostics retained `dirty=1` and immediately consumed the single merged pending request. Continued drawing overlapped several successive 0.69–1.42 second saves, so the run produced nine trailing-queue updates and seven trailing executions rather than the single execution expected from three quick edits; this is correct one-active/one-pending behavior across multiple save generations, not an unbounded concurrent queue. Once editing stopped, revision 28 completed with `currentRevision=28`, `savedRevision=28`, and `dirty=0`. No request used the former `save.skipped reason=save-in-flight` path | The forced-save path waited through its trailing work before completing and its scene-file loaders reached `terminalState=completed`. Immediate close scheduled the established delayed view-unload write for revision 31; the same-revision overlapping request was recognized as satisfied, Canvas nodes were removed, and the reopened view accepted the delayed write update from 3,670 to 3,671 elements. The final checkpoint reports 14 actual saves, 13 completed backup writes before the checkpoint, one harmless same-revision coalescing event, and no failure/stall/timeout marker. No regression was reported while exercising the `[[` suggester and durable reopen workflow. No additional popout, MOC EA, memory, export, backup, or mobile test is required for this checkpoint |
| 2026-08-25 | Implemented Phase 1B.4b revision tracking, bounded trailing saves, and teardown flush | Traced the old dirty boolean against every save completion/early return, `clearDirty()` load/reload path, durable Excalidraw increment, external synchronization semaphore, autosave timer, force-save busy policy, and unload/migration sequence. Durable increments provide the precise low-overhead edit boundary, including changes made after a save snapshot while compression is asynchronous; no new full-scene hashing was introduced. Requests execute through one promise loop, merge into one latest trailing request while preserving forced-save priority and autoexport requirements, and carry explicit terminal results so failed/skipped work cannot advance the saved revision. Save-triggered `loadDrawing()` cannot clear the active revision. Close/navigation waits for the loop, then persists only if a newer revision remains. The pre-existing 200 ms Electron popout-unload write workaround is retained | Production build passes with the unchanged 33 Rollup circular warnings. The new coordinator remains clean under targeted ESLint; `ExcalidrawView.ts` retains its exact 18 pre-existing unsafe-type findings, and full lint remains exactly 138 errors/0 warnings. `npm run code:unused`, `npm run madge`, bundle syntax, and `git diff --check` pass. The diagnostic bundle is 4,848,203 bytes, 4,433 bytes above Phase 1B.4a and 394,677 bytes below 5 MiB. Runtime acceptance uses SYL only to provide a reliable compression window: start one manual save, create another durable element while compression is active, and require `saveCoordinator.trailingQueued` followed by exactly one `saveCoordinator.trailingStart`; the first completion must remain dirty with `currentRevision>savedRevision`, the trailing completion must equalize revisions and clear dirty, and no `save.skipped reason=save-in-flight` may occur. Add one final element and immediately close/reopen to validate `flush()` durability. As a targeted text-edit regression, type `[[` once and confirm the suggester remains open without a save interrupting active text. No MOC EA, image-loader, backup, export-output, repeated migration, memory, mobile, or broad performance rerun is required |
| 2026-08-25 | Runtime-validated and closed Phase 1B.4a | The disposable drawing produced an ordinary autosave with `reason=direct force=0 autosaving=1`, a manual titlebar force-save with `refreshSceneFiles=1`, and a window-blur force-save with `refreshSceneFiles=0`. Both migration directions rebuilt the appropriate window runtime; returning to main serialized the dirty four-element scene through the established `save.viewUnloadScheduled` path, deleted the abandoned popout package, and then accepted the delayed disk update. Final unsaved close serialized five elements through the same teardown path, and reopen parsed all five. All five scene-file loaders reached `terminalState=completed` | Public routing, timer ownership, force-save policy, teardown persistence, package ownership, and durable reopen all meet acceptance. One non-forced direct request arrived 8.4 ms after the final forced teardown save began and recorded `save.skipped reason=save-in-flight`; the winning save snapshot already contained the same five elements and reopened durably. This is the preserved pre-coordinator behavior and supplies a focused baseline for Phase 1B.4b trailing coalescing rather than blocking the mechanical checkpoint. The filtered trace contains no failure, stalled-loader, or timeout marker |
| 2026-08-25 | Implemented Phase 1B.4a mechanical `ViewSaveCoordinator` extraction | Audited public and internal `save()`, `forceSave()`, `forceSaveIfRequired()`, dirty-state, autosave, unload/close, window-blur, link-navigation, synchronization, and external timer call sites before editing. The new view-scoped coordinator owns orchestration while the view retains the `super.save()`-dependent serialization implementation and thin compatibility delegates. `FileManager` can still read, clear, and invoke `autosaveTimer`/`autosaveFunction`; all paths still share the existing view semaphores. Internal autosave and teardown requests still re-enter the public `save()` facade, preserving interception compatibility. No revision, coalescing, cache, migration, loader, export, or serialization behavior was added | Production build and bundle syntax pass with the unchanged 33 Rollup circular warnings. The new coordinator has zero targeted ESLint findings; `ExcalidrawView.ts` retains its exact 18 pre-existing unsafe-type findings, and full lint remains exactly 138 errors/0 warnings. `npm run code:unused`, the repository `npm run madge`, and `git diff --check` pass. The diagnostic bundle is 4,843,770 bytes, 1,785 bytes above the preceding scanner-cleanup checkpoint and 399,110 bytes below 5 MiB. Runtime acceptance is one small disposable drawing: validate one autosave, one manual titlebar force-save, one window-blur save, one unsaved close/reopen, and one main-to-popout-to-main migration with a dirty edit during the return. The trace must retain the expected direct/manual reasons and blur/manual scene-refresh policy; each save must reach either normal completion or the existing view-unload scheduled-write terminal path, every force-save and loader must complete, the dirty indicator must clear after ordinary completed persistence, and every edit must survive reopen. This targets coordinator routing, public facade compatibility, timer ownership, and the teardown path without repeating MOC EA/SYL performance, missing-asset, backup-queue, autoexport-output, or repeated memory-cycle tests |
| 2026-08-25 | Cleared Obsidian CodeScanner's nine `globalThis` popout warnings | Audited all four `PackageManager` and five Phase 0 diagnostic references against the per-window runtime architecture and the existing Rollup-injected `mainDocument`/`deliberateFetch` exceptions. No injection workaround was needed. Package comparison requires the plugin bundle's main realm, already represented by unqualified `window` throughout the same manager; renaming `setPackage(window, ...)` to `setPackage(win, ...)` makes that comparison unambiguous. Performance diagnostics are intentionally one main-window-owned singleton, so local-storage enablement, heap/timing reads, and the manual console checkpoint now use `window` with a narrow `PerformanceDiagnosticsWindow` extension. No package ownership, host-adapter lifetime, persistence, timing, or diagnostic payload changed | Targeted ESLint passes with zero findings in both changed files; `rg globalThis src` returns no matches. Full `npm run code` improved from 138 errors/9 warnings to the same 138-error backlog and zero warnings. Production build, bundle syntax, `npm run code:unused`, `npm run madge`, and `git diff --check` pass with the unchanged 33 Rollup circular warnings. The bundle is 4,841,985 bytes, 60 bytes smaller than commit `67352c99` and 400,895 bytes below 5 MiB. A separate manual test is not warranted for scanner-only lexical substitutions; the next popout-bearing runtime test should simply retain the existing diagnostic assertions that the main package is labelled `main`, a migrated runtime is labelled `popout`, the popout package is deleted on return, and `EXCALIDRAW_PERF_PHASE0_CHECKPOINT()` remains callable from the main DevTools console |
| 2026-08-24 | Runtime-validated and closed the inline `[[` suggester/save race | During the original reproduction, two equations and an actively edited text/link produced numerous scene changes while `saveRequest.count` remained at its earlier value of one; opening and using the body-portaled link suggester therefore caused no observer save or synchronization reload. After the text was committed and the final dirty edit was made, opening the real command-palette modal produced the expected `save.request reason=direct force=0 preventReload=1 dirty=1`. Synchronization deliberately reported `changed=1`, reloaded outside text-edit mode, serialized two equations plus one text element, completed the disk/backup writes, and the subsequent reopen parsed all four scene elements and loaded both equation files | The fix covers the reported interruption and preserves the adjacent modal durability safeguard. The modal-triggered save completed in 163.80 ms; its scene loader and the reopen loader both reached `terminalState=completed`. Teardown released the main package lease and purged Canvas nodes to zero. The filtered trace contains no failure marker. No further MOC EA, SYL, popout, export, backup, or mobile test is required before Phase 1B.4 |
| 2026-08-24 | Fixed the pre-Phase-1B.4 inline `[[` suggester/save race | Reconfirmed the exact lifecycle before editing. `SuggestionModal.open()` appends `.suggestion-container` directly to the input's document body. `ObserverManager` observed every direct body child addition and, despite its modal-specific name and comment, never checked the added node's identity; on a dirty drawing it called `save()`. After an equation duplicate made synchronization report a change, that unintended save called `loadDrawing()` and ended text editing before the suggester could be used. The observer now requires the sole added node to be a cross-window-safe `Element` matching `.modal-container`. This preserves the intended pre-modal save for Settings, command palette, and other Obsidian modals while excluding suggestion, menu, popover, and other body portals. Added a concise 2.27.0 release-note fix; no locale string or public API changed | Targeted ESLint is clean for `ObserverManager.ts` and `Messages.ts`. Production build and bundle syntax pass with the unchanged 33 Rollup circular warnings; `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains exactly 138 errors/9 warnings. The combined diagnostic bundle is 4,842,045 bytes, 243 bytes above the runtime-validated Phase 1B.3b build and 400,835 bytes below 5 MiB. Runtime acceptance must pair the original reproduction with the adjacent high-risk safeguard: create and duplicate a LaTeX formula, begin a text element, type `[[`, confirm the suggester opens without any save or loss of text editing, choose one suggestion, and continue typing; then commit the text, make one more dirty edit, immediately open the command palette, and confirm the real modal still triggers and completes a save. Close/reopen must retain the link and final edit. No MOC EA, SYL, popout, loader, export, backup, or mobile rerun is required |
| 2026-08-24 | Runtime-validated and closed Phase 1B.3b | The small SVG-autoexport drawing exercised one window-blur save and one titlebar save between the supplied checkpoints. Blur recorded `refreshSceneFiles=0 triggerAutoexport=1`, persisted two elements, scheduled/completed SVG export in 20.40 ms, and issued no `force-save:window-blur` scene-file request. Manual titlebar save recorded `refreshSceneFiles=1 triggerAutoexport=1`, persisted three elements, scheduled/completed SVG export in 17.00 ms, and completed the matching scene-file request. Closing and reopening parsed all three elements | The trace meets both policy branches and the documented autoexport contract. All three physical saves and SVG exports completed; every scene loader reached `terminalState=completed`; the main package lease released/reacquired normally; no failure marker appears. The initial setup save used the public default `reason=unspecified`, which is expected and outside the two policy assertions. The user separately confirmed the previously diagnosed inline `[[` race remained present; it is now the isolated correctness checkpoint immediately above, before Phase 1B.4 |
| 2026-08-24 | Implemented Phase 1B.3b explicit save side-effect policy | Audited every `save()`, `forceSave()`, private force-save-policy call, autoexport branch, export-manager delegate, and `onTriggerAutoexportHook` reference before editing. The first candidate was to suppress autoexport on window blur, but the README and hook TSDoc establish that autoexport is a save-time user contract. The implementation therefore separates `refreshSceneFiles` from `triggerAutoexport` without changing either public facade: ordinary/public force saves select both; window blur selects no scene-file refresh but retains autoexport. The save-owned diagnostic reason now reaches `save.request`, `autoexport.scheduled`, and `save.complete`, while force-save request/completion records both policy dimensions. A private suppression path exists for a future genuinely internal durability reason, but no existing save category is silently opted into it | Production build and `node --check dist/main.js` pass on Node 22.22.2 with the unchanged 33 Rollup circular warnings. `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains at exactly 138 errors and 9 warnings; targeted `ExcalidrawView.ts` lint retains its exact 18 pre-existing unsafe-type findings with none on a changed line. The diagnostic bundle is 4,841,802 bytes, 915 bytes above Phase 1B.3a and 401,078 bytes below 5 MiB. Runtime acceptance is deliberately one small main-window drawing with SVG autoexport enabled: establish its SVG with a manual save, edit once and blur the Obsidian window, then confirm the edit persists and the SVG updates. The trace must show `reason=window-blur refreshSceneFiles=0 triggerAutoexport=1`, `autoexport.scheduled reason=window-blur kind=svg`, and no `sceneFiles.request reason=force-save:window-blur`. Make a second edit and use the titlebar save once; confirm `reason=manual-titlebar refreshSceneFiles=1 triggerAutoexport=1`, a matching forced scene-file request, an SVG update, and durable reopen. This targets the highest-risk public autoexport regression without repeating MOC EA, SYL, popout, loader, backup, or mobile tests |
| 2026-08-24 | Runtime-validated and closed Phase 1B.3a | A manual popout titlebar save scheduled a 9,430-byte backup with `coalesced=0`; the IndexedDB transaction completed 3.50 ms after its 50 ms delay, and the drawing returned to main/reopened with all eight elements. After the file was renamed, a second main-window titlebar save scheduled 9,756 bytes and completed its backup transaction in 4.80 ms; close/reopen parsed all nine elements. The disposable drawing then deleted and closed normally. Final diagnostics reported exactly two backup schedules and two physical writes, with no `backupCoalesced` count, `ImageCache.backupWrites` failure, or other error | Runtime integration confirms that the main-window-owned queue continues after a popout save, transaction-completion callbacks fire, renamed drawings persist, and deletion does not introduce a lifecycle error. The run did not place a second payload inside the 50 ms pending window and deletion occurred after the second write completed, so runtime did not exercise `coalesced=1` or pending cancellation; the deterministic harness remains the evidence for latest-payload replacement, one-active/one-trailing ordering, maximum concurrency one, flush, and pending cancellation. All seven scene loaders reached `terminalState=completed`; the popout package was deleted on return to main; Canvas purges reached zero. No SYL/MOC timing or export retest was required |
| 2026-08-24 | Implemented Phase 1B.3a plugin-global drawing-backup queue | Audited all backup reads/writes/removals, save scheduling, file rename/delete handlers, cache clearing, plugin unload, and autoexport side effects before editing. Added a dependency-injected `BackupPersistenceQueue` keyed by vault path rather than by view, because the same drawing can be represented by multiple views or migrate between windows. Scheduling replaces the pending payload/callback, permits only one IndexedDB transaction plus one trailing latest payload, and keeps the historical 50 ms delay. `ImageCache.addBAKToCache()` now awaits transaction completion. File rename flushes the path first; deletion and backup-cache clear cancel queued data and wait for an active write; image-cache clear deliberately does not touch backups; unload clears timers without starting more persistence. The view's existing backup diagnostics now emit `coalesced=0/1` and count physical writes separately. Export behavior is unchanged | A deterministic queue harness passed latest-payload replacement, one-active/one-trailing ordering, maximum concurrency of one, callback replacement, pending cancellation, and immediate flush. Targeted ESLint passes for the new queue, `ImageCache.ts`, and `FileManager.ts`; `ExcalidrawView.ts` retains exactly its 18 pre-existing findings. Production build and bundle syntax pass with the unchanged 33 Rollup circular warnings. `npm run code:unused`, `npm run madge`, and `git diff --check` pass; full lint remains exactly 138 errors/9 warnings. The final build is 4,840,887 bytes, 2,360 bytes above Phase 1B.2c and 401,993 bytes below 5 MiB. Runtime acceptance is intentionally small: use one disposable non-empty drawing, move it to a popout, make one edit and manually save, and wait for matching `backup.scheduled coalesced=0` plus `backup.complete`; return it to main and reopen to confirm persistence. Make another edit/manual save and immediately rename the file; after 200 ms, close/reopen the renamed drawing and confirm the edit. Finally make one more edit/manual save and immediately delete the disposable drawing; there must be no unfiltered error or later backup completion for that canceled save. Share the filtered Phase 0 trace and report any unfiltered error. This covers the highest-risk main-window timer ownership, transaction completion, rename flush, and delete cancellation without repeating SYL, MOC EA, loader, export, or repeated-migration tests |
| 2026-08-24 | Runtime-validated and closed Phase 1B.2c | In a popout disposable drawing, equation creation/duplication caused the expected synchronization change, and both retained view-unload serialization calls reported `snapshotReused=1`/`snapshotMs=0`; reopening in main restored all three equations and the linked text. After deleting one equation and blur-saving, serialization reused the snapshot with one deleted element, and reopen restored the two remaining equations. A compatibility-mode blur save serialized one reused snapshot and reopened all eight elements. The Sidecar-off SYL save serialized/reopened 3,655 elements, 1,734 text entries, and 169 embedded files | SYL synchronization was 22.40 ms and metadata generation 5.40 ms: modestly above the Phase 1B.2b two-run averages but below its 37.20/52.10 ms pre-indexing acceptance reference, and respectively 87.8%/92.9% below the Phase 0 baselines. `save.serialize` reported `snapshotReused=1 snapshotMs=0`; all relevant loaders completed, the popout package was deleted, and the user reported no unfiltered errors. The user also reproduced an inline `[[` suggester interruption after duplicating an equation. Its trace shows `save.request force=0 preventReload=1 autosaving=0`, followed by `syncChanged=1` and `save.syncLoadDrawing`. Code tracing identifies the broad pre-existing `ObserverManager` body-child mutation hook: the suggester appends its `.suggestion-container` to `body`, the observer saves the dirty drawing, and equation duplicate synchronization reloads the scene, ending text editing. Snapshot reuse occurs only after that reload decision and did not cause the race; any fix belongs in a separate correctness checkpoint with modal/command-palette regression coverage |
| 2026-08-24 | Implemented Phase 1B.2c coherent save snapshot plumbing | Traced every `prepareGetViewData()`, `getScene()`, and `syncElements()` caller, the Markdown/compatibility serialization branches, synchronization-triggered `loadDrawing()`, selected-ID mutation, deleted-element concatenation, Markdown-image forced persistence, and the long-standing Electron popout-unload workaround. `save()` now obtains one app-state object, builds its scene from that object, and captures deleted elements in the same measured snapshot stage. It reuses those values for synchronization, reload, and serialization. `getSceneWithAppState()` and `prepareGetViewDataFromSnapshot()` are private; existing public facades retain their exact signatures and still capture current state when called independently. The view-unload path retains both compression calls and the 200 ms delayed write rather than removing an incompletely understood workaround | Production build and bundle syntax pass on Node 22.22.2 with the unchanged 33 Rollup circular warnings. `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains at exactly 138 errors and 9 warnings; targeted `ExcalidrawView.ts` lint retains its 18 pre-existing unsafe-type findings with none on a changed line. The diagnostic bundle is 4,838,527 bytes, 296 bytes above Phase 1B.2b and 404,353 bytes below 5 MiB. Runtime acceptance is risk-based: in a disposable Markdown drawing already moved to a popout, create one equation, ordinarily duplicate it twice, add linked text, and immediately close the popout without a deliberate save; after the delayed write, reopen in main and verify all three equations and the linked text. Delete one equation, make another visible edit, blur-save, and reopen to verify two equations plus the edit. This covers synchronization change, deleted elements, metadata, and view-unload persistence. Then make/save/reopen one edit in a disposable legacy `.excalidraw` file to guard compatibility serialization. Finally, after a plugin reload, make one Sidecar-off SYL blur save: its `save.serialize` record must show `snapshotReused=1 snapshotMs=0`, synchronization must remain near the Phase 1B.2b 15.50 ms average/19.60 ms maximum, and the drawing must reopen with the edit. In Markdown mode `save.serialize files=0` is expected because the reused sync-owned scene has already cleared transient binary payloads; embedded-file registries and reopened images must remain intact. No MOC EA, broad loader, package-lease, or repeated save test is required |
| 2026-08-24 | Runtime-validated and closed Phase 1B.2b | In a disposable drawing, one equation was ordinarily duplicated twice before the first save. Synchronization reported `changed=1` for three elements, serialization recorded `equations=3`, the synchronization reload reached `terminalState=completed` with all three binary files, and close/reopen parsed three elements and emitted all three equations. After deleting one, synchronization again reported `changed=1`, serialization recorded two active equations plus one deleted element, and the final close/reopen parsed and emitted exactly two. On SYL, two Sidecar-off blur saves at 3,655–3,656 elements/1,734 texts/169 embedded files averaged 15.50 ms in `saveSyncElements` with a 19.60 ms maximum | Duplicate split and cleanup behavior passed the mutation-sensitive regression. SYL synchronization improved 58.3% from Phase 1B.2a's 37.20 ms average and 62.4% from its 52.10 ms maximum; relative to Phase 0's 183.96 ms average, the combined 1B.2 indexing work is 91.6% lower. Metadata remained stable at 2.30 ms average. Both blur saves retained `refreshSceneFiles=0`, completed in 762.10/780.10 ms, and compression was stable at 676.40/676.20 ms. The initial 169-file loader and later 14-file synchronization loader both completed, and the filtered traces contain no failure marker |
| 2026-08-24 | Implemented Phase 1B.2b mutation-aware image grouping | Audited `syncFiles()` and all duplicate-image, equation, Mermaid, Markdown-image, pasted-image, URL/local-file, registry, loader, and explicit independent-duplicate paths before editing. One initial scene pass now constructs ordered images, the immutable original `fileIds` traversal, the membership set, and live file-ID groups. When the legacy duplicate logic assigns a new ID, it still sorts a copy of the current original-ID group with the exact prior comparator, mutates the same newest element, removes it from that group, and adds it to the new-ID group. This preserves repeated-duplicate behavior while eliminating both filter-inside-loop scene scans. A deterministic 5,000-case comparison, including equal timestamps and groups of two through nine duplicates, produced identical final element-to-file-ID assignments | Production build and bundle syntax pass on Node 22.22.2 with the unchanged 33 Rollup circular warnings. `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains at exactly 138 errors and 9 warnings; targeted `ExcalidrawData.ts` lint retains its 16 pre-existing unsafe-type findings with none on a changed line. The diagnostic bundle is 4,838,231 bytes, 145 bytes above Phase 1B.2a and 404,649 bytes below 5 MiB. Runtime acceptance is deliberately narrow: in a disposable drawing create one LaTeX equation and use ordinary Excalidraw duplication twice so three elements initially share its file ID; blur-save, close/reopen, verify all three render, delete one, blur-save, close/reopen, and verify two remain. This targets the mutation-sensitive registry split and cleanup behavior. Then run two small-edit blur saves on SYL with Sidecar off; `saveSyncElements` should not exceed the Phase 1B.2a 37.20 ms average/52.10 ms maximum and should improve if the removed file scans were material. No MOC EA, popout, general loader, linked-text, or ordinary image-deletion retest is required. Share the filtered diagnostic trace and whether any unfiltered errors appeared |
| 2026-08-24 | Runtime-validated and closed Phase 1B.2a on SYL without iPad Sidecar | Two blur saves on SYL contained 3,655–3,656 elements, 1,734 text entries, and 169 embedded files, matching the Phase 0 scale. `saveSyncElements` averaged 37.20 ms (52.10 ms maximum), down 79.8% from the 183.96 ms baseline. `serializeMetadata` averaged 2.60 ms (3.70 ms maximum), down 96.6% from 76.44 ms. Both saves persisted and completed; blur retained `refreshSceneFiles=0`; the initial 169-file load and subsequent 14-file synchronization load both reached `terminalState=completed` | The two changed hot paths comfortably beat the predefined 92/38 ms acceptance thresholds. Stringify averaged 40.55 ms versus the earlier 19.22 ms despite being untouched. Compression was 1,808.50 ms on its first worker use and 742.10 ms on the second, making total-save averages unsuitable for attributing this checkpoint; the warm second compression is near the historical 654.54 ms average. The filtered trace contains no lifecycle failure marker. Use the maintainer's drawing names going forward: MOC EA is the image-focused 245-element/46-file regression drawing; SYL is the text-heavy 3,654-element/1,734-text/169-file performance drawing |
| 2026-08-24 | Runtime-validated Phase 1B.2a correctness on MOC EA | Four completed saves on the 245–246-element/131-text MOC EA scene averaged 2.90 ms in `saveSyncElements`, 1.55 ms in `serializeMetadata`, 10.92 ms in stringify, 162.05 ms in compression, and 226.85 ms total. The first deletion save correctly reported `changed=1`, serialized 45 rather than 46 embedded files, and preserved one deleted element through its synchronization reload. After close/reopen the scene parsed with 246 elements and 45 embedded files. Three window-blur saves retained `refreshSceneFiles=0`; all seven loader runs reached `terminalState=completed`; both view teardowns removed Canvas nodes linearly to zero; the previously fixed transient classification fallback was exercised once | The changed registry-cleanup and durable-reopen paths are accepted on MOC EA, and the trace contains no lifecycle failure marker. This run is correctness evidence rather than the Phase 0 timing comparison; performance closure came from the separate same-scale SYL run |
| 2026-08-24 | Implemented Phase 1B.2a single-pass save indexes | Traced all `syncElements()`, `generateMD*()`, `prepareGetViewData()`, and scene snapshot call sites before changing the hot loops. `updateElementLinksFromScene()` and `updateTextElementsFromScene()` now share indexes built in one scene traversal; each index keeps the first eligible element for an ID, matching the former filtered-array `[0]` behavior. Metadata generation uses a fresh unique-ID index and stores `null` for duplicate IDs, preserving the prior requirement that a text-element link is serialized only when exactly one scene element has that ID. File registry and scene snapshot cleanup use sets rather than repeated array membership scans. No async boundary, save facade, output-section iteration order, duplicate-image mutation, or snapshot ownership changed | The raw Phase 0 round-2 source log establishes the comparison point on SYL at 3,654 elements/1,734 texts/169 files: five saves averaged 183.96 ms in `saveSyncElements`, 76.44 ms in `serializeMetadata`, 19.22 ms in stringify, 654.54 ms in compression, and 969.00 ms total. Production build passes on Node 22.22.2 with the unchanged 33 Rollup circular warnings; `node --check dist/main.js`, `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains at the exact 138-error/9-warning baseline with no finding on a changed line. The diagnostic bundle is 4,838,086 bytes, 260 bytes above the preceding checkpoint and 404,794 bytes below 5 MiB. Runtime acceptance deliberately splits risk coverage: MOC EA covers linked-text/image deletion and durable reopen; SYL provides the same-scale hot-path timing comparison |
| 2026-08-24 | Runtime-validated stable known-file classification and declassification | In the exact deconstruct/close/same-tab-edit/Back reproduction, the child save completed at 32,380.5 ms and parent loading began at 32,392.9 ms while metadata frontmatter was unavailable. `file.classificationFallback extension=md` fired once during parent parsing and once when the scene-file loader classified the embedded child; `knownExcalidrawFileFallback.count=2`. The loader then emitted the updated Excalidraw image normally, and the maintainer confirmed that the parent immediately displayed both circles instead of a Markdown embeddable. After removing the Excalidraw frontmatter from the disposable child and allowing metadata to refresh, it rendered as ordinary Markdown | The declassification checkpoint retained `knownExcalidrawFileFallback.count=2` with no third fallback, proving the metadata event removed the stable-set entry rather than leaving a stale Excalidraw classification. The declassified Markdown asset still loaded normally through the Markdown-rendering path. Every loader reached a terminal state and there was no `sceneFiles.loaderStalled`. The maintainer reported the issue resolved. This closes the separate correctness checkpoint without changing Phase 1B save policy |
| 2026-08-24 | Stabilized previously confirmed Excalidraw-file classification during transient metadata-cache gaps | Traced the exact deconstruct/save/back-navigation reproduction through file creation, metadata registration, same-leaf unload save, parent parsing, embedded-file classification, targeted dependency refresh, rename/delete handling, and every `isExcalidrawFile()` caller. The existing `excalidrawFiles` set already records files confirmed by metadata and removes them on a metadata `changed` event without Excalidraw frontmatter or on deletion. `isExcalidrawFile()` now consults live parsed frontmatter first; only when frontmatter is unavailable does it use that stable set. This avoids the observed Markdown misclassification without turning raw vault reads or arbitrary filename heuristics into a synchronous classification path. A temporary path-free diagnostic records fallback use | Production build passes with the unchanged 33 Rollup circular warnings; targeted `FileManager.ts` ESLint, `npm run code:unused`, `npm run madge`, bundle syntax, and `git diff --check` pass. Full lint remains at the exact 138-error/9-warning baseline. The bundle is 4,837,826 bytes, 173 bytes above Phase 1B.1a and 405,054 bytes below 5 MiB. Runtime acceptance: repeat the exact deconstruct → close child → same-tab open → add an unsaved second circle → Back sequence; the parent must immediately render the child as an Excalidraw image with both circles, and the trace should contain `file.classificationFallback extension=md` or `knownExcalidrawFileFallback.count>=1`. Then verify an ordinary Markdown embed still renders as Markdown. Finally, in a disposable drawing remove the `excalidraw-plugin` frontmatter, wait for metadata refresh, and confirm it is no longer opened/rendered as Excalidraw; this is the highest-risk stale-classification regression |
| 2026-08-24 | Runtime-validated Phase 1B.1a and isolated a pre-existing metadata-classification race | Window blur produced a forced disk write in 186.7 ms, completed with `refreshSceneFiles=0`/`loadSceneFilesMs=0`, and did not issue `sceneFiles.request reason=force-save:window-blur`. After reopen, the persisted scene contained the edit. Manual titlebar save then completed in 81.2 ms with `refreshSceneFiles=1` and a matching `force-save:manual-titlebar` loader run, preserving the compatibility path. The backing-image regression exercise uncovered a separate reproducible same-tab navigation race: the child save completed at 61,853.8 ms and parent `setViewData` began at 61,854.7 ms. The parent initially rendered the child as Markdown, then rendered it correctly after close/reopen | Phase 1B.1a acceptance passed for both the changed blur path and the preserved public/manual path. The race is not caused by Phase 1A/1B: navigation saved through the long-standing `forceSaveIfRequired()` path, while `PluginFileManager.isExcalidrawFile()` has relied solely on the live metadata cache since 2024. At the failing load, the parent parsed nine elements/one embedded file and its loader completed normally, consistent with a wrong transient file classification rather than a stalled loader or lost child save. The child was durably saved with two elements before navigation, explaining why reopening after metadata-cache convergence renders both circles correctly. Treat the classification fix as its own checkpoint rather than combining it with save-path optimization |
| 2026-08-24 | Decoupled window-blur persistence from scene-file refresh while preserving the public force-save facade (performance Phase 1B.1a) | Audited every `forceSave()`, `save()`, and `loadSceneFiles()` caller plus script/documentation references before changing behavior. Public and internal callers use `forceSave()` primarily as a disk-persistence guarantee, but some manual/recovery paths may depend on its historical refresh side effect. To avoid changing that compatibility surface, `forceSave()` still selects the original policy. A private policy method now makes the refresh decision explicit, and only the measured persistence-only window-blur callback selects `refreshSceneFiles=false`. The blur save still performs forced serialization, backup/autoexport behavior, embed-update notification, semaphore handling, and all existing active-tool guards | Production build passes with the unchanged 33 Rollup circular warnings; `node --check dist/main.js`, `npm run code:unused`, and `npm run madge` pass. Full lint retains the exact 138-error/9-warning baseline; targeted `ExcalidrawView.ts` lint retains its prior 18 unsafe-type errors with none on the new lines. The bundle is 4,837,653 bytes, 137 bytes above the Phase 1A.3 diagnostic bundle and 405,227 bytes below 5 MiB. Runtime acceptance is deliberately narrow and risk-based: edit a drawing, blur Obsidian, wait for the save, reopen it and confirm the edit persisted; the trace must contain `forceSave.request reason=window-blur refreshSceneFiles=0` and a completed forced save, with no `sceneFiles.request reason=force-save:window-blur`. Then use the manual save button once and confirm it still records `refreshSceneFiles=1` plus a matching `sceneFiles.request`, protecting the public/manual compatibility path. Finally change one already-visible backing image file and confirm the existing targeted synchronization refresh updates it; this guards the highest-impact adjacent regression without repeating broad image/popout testing |
| 2026-08-24 | Validated the Phase 1A.3 loader checkpoint on SYL and MOC EA | The first capture, despite its `large-terminal` checkpoint label, was MOC EA: it emitted all 46 files and completed normally in 9.05 seconds. Its subsequent command-save request started with no active loader and completed in 1.6 ms, demonstrating that completion released the loader and later work could advance. The later capture, despite its `normal` label, was SYL, the prior failure scene: it emitted all 169 files in five batches and completed normally in 7.51 seconds. The new diagnostic split identified zero missing vault files and three external/local entries, explaining why the missing-vault retry path was not applicable | All three `sceneFiles.runStart` records have matching `sceneFiles.runComplete terminalState=completed` records; there is no `sceneFiles.loaderStalled`, MOC EA closed cleanly to zero Canvas nodes, and the maintainer reported no unfiltered errors. This validates the normal terminal path, guards against false timeouts on both workloads, and shows SYL no longer leaves the manager wedged. Because every task settled, this run did not force the 30-second watchdog or exercise a missing-vault-file retry; those branches retain structural/build validation and should be targeted if an actual stalled or missing-vault case recurs rather than manufacturing another broad manual test now |
| 2026-08-24 | Bounded stalled scene-file loaders and isolated missing-file recovery (performance Phase 1A.3) | The raw 169-file capture published 168 files within about 16 seconds, then left one PromisePool task and `activeLoader` alive for the remainder of the run while six later requests queued. `EmbeddedFilesLoader` now resets a 30-second watchdog whenever any pool task settles; no-progress expiry marks the loader timed out, prevents late task results from being published, emits one final callback, clears PDF resources, and lets `ViewSceneFileManager` release the exact active loader and run its latest coalesced request. Every normal/failure/termination path records a terminal state. The retry loop now distinguishes missing vault files from URL/local-link entries and reloads only the missing IDs, preserving sync recovery without repeatedly touching a stalled external asset | Repeated production builds pass with the unchanged 33 Rollup circular warnings. Targeted ESLint is clean for `EmbeddedFileLoader.ts` and `ViewSceneFileManager.ts`; `npm run code:unused`, `npm run madge`, bundle syntax, and CRLF-aware `git diff --check` pass. Full `npm run code` retains the exact repository baseline of 138 errors and 9 warnings, with no finding in either changed loader file. The diagnostic bundle is 4,837,516 bytes, 405,364 bytes below 5 MiB. Runtime validation must use the same 169-file drawing: the initial request must reach `sceneFiles.runComplete terminalState=completed` or `timed-out`, `activeLoader` must be zero on a later checkpoint, a subsequent targeted/sync request must start rather than remain queued, and the 168 resolvable images must stay visible. Then make one missing vault image available and confirm its whitelisted retry loads it without a full-scene reload. The highest-risk regression is a false timeout during legitimate slow generation, so also open the fully resolvable 46-file representative drawing and confirm it completes normally without `sceneFiles.loaderStalled` |
| 2026-08-24 | Closed Phase 1A.2 and the Phase 1A.1 multi-view ownership risk after maintainer validation | Individual deletion emitted `before=7 after=6 mapEntryDeleted=1`; undo recreated node 7 and the embed remained usable. Main-window and both popout teardowns removed all seven nodes in order down to zero, after which purge remained zero. The added lifecycle markers showed unload, close request, and close completion with live file/root state. In the shared popout, acquiring the second view raised leases to 2; closing the first emitted `leases=1` with no package deletion and left the sibling usable; closing the second emitted exactly one popout deletion and `leases=0` | All requested diagnostic criteria passed and the maintainer reported no unfiltered console errors. Phase 1A.2 is complete and the explicit lease mechanism is validated for both repeated single-view migration and multiple views sharing one popout runtime. The separate retained-heap result remains open. The maintainer explicitly directed that `npm audit fix` must not be run because it previously caused runtime problems; the reported audit findings are believed to be development dependencies |
| 2026-08-24 | Fixed individual Canvas-node retention (performance Phase 1A.2) | Traced the sole `removeNode()` call from `CustomEmbeddable` plus the duplicate-ID replacement, clear, unload, migration, and destroy/purge paths. Individual cleanup now deletes the entry keyed by the Excalidraw element ID instead of incorrectly using `node.file.path`. It checks node identity before deleting that key so a stale effect cleanup cannot remove a newer replacement, and retains an identity-scan fallback for compatibility. No loader, save, package, or migration-handoff behavior was combined into this checkpoint. Added timing-only close/unload entry records because the supplied capture contained no final-tab-close marker, and installed the maintainer-authorized Madge development dependency without changing the existing script | Production builds pass with the unchanged 33 Rollup circular warnings; `node --check dist/main.js`, `npm run code:unused`, and CRLF-aware `git diff --check` pass. The diagnostic bundle is 4,835,882 bytes, 406,998 bytes below 5 MiB. Targeted lint is clean for `CanvasNodeFactory.ts`; the combined check reports only the pre-existing unsafe ref assignment at `CustomEmbeddable.tsx:1480`, outside the changed cleanup, while `ExcalidrawView.ts` retains exactly its existing 18 unsafe-type findings with none on the new diagnostic lines. The repository Madge script passes but covers only 8 root files; a supplemental TypeScript-aware run processes 229 source files and records a structural inventory of 46 cycles. Runtime acceptance requires one individual embedded Canvas/Markdown deletion to change the diagnostic map size by exactly one, undo to recreate a usable node, and final view teardown to leave zero nodes without a double-dispose error |
| 2026-08-24 | Reviewed the maintainer's Phase 1A.1 five-round-trip runtime capture | Across ten migrations the trace records five popout package creations and five deletions; `packageWindows` oscillates between 1 and 2 and every final popout lease reaches zero, validating explicit map/lease ownership for the single-view path. All ten post-baseline scene-file runs reached `runComplete`, so there is no new loader regression in this fully resolvable 46-file scene. Individual Canvas cleanup still remained `before=7 after=7 mapEntryDeleted=0`, confirming the separate Phase 1A.2 defect | The pre-test checkpoint was 841.95 MB and post-close forced GC was 1278.84 MB, a +436.89 MB delta versus the Phase 0 +435.63 MB result; retained-heap acceptance therefore did not improve. The capture has no final main-view `view.closeComplete` marker after cycle 5, so it cannot cleanly distinguish a missed final close from other retained popout/runtime references. The drawing had zero unresolved embedded files and therefore does not validate the Phase 1A.3 missing-asset path. Before closing 1A.1, run one two-view/same-popout lease test: closing the first view must leave one lease and a usable sibling; only the final release may delete the package |
| 2026-08-24 | Implemented explicit per-view ownership for window-scoped React/Excalidraw packages (performance Phase 1A.1) | Added a documented `PackageLease` contract and `PackageManager.acquirePackage()`. Each view captures its acquisition window and releases the lease after its React root and other window-bound resources are torn down. Releases are idempotent; multiple Excalidraw views in one window share a reference count; the last popout release disposes both typed host registrations and removes that window's package; the main runtime remains pinned for startup/fallback use. Removed the lifecycle decision that used the view's mutable post-migration `ownerWindow`, while retaining `getPackage()`/`deletePackage()` compatibility facades. No Canvas-node, loader, save, or migration-handoff behavior was combined into this checkpoint | The pre-change production build passed on Node 22.22.2 with the established 33 circular warnings and produced a 4,834,315-byte diagnostic bundle. Post-change production builds and `node --check dist/main.js` pass with the same warning baseline; `npm run code:unused` and `git diff --check` pass. Full `npm run code` retains the recorded repository baseline of 138 errors and 9 warnings, with no finding on a new lease/type/facade/view line. Targeted lint leaves only four Phase 0 `globalThis` diagnostic warnings in `PackageManager.ts`; `main.ts`/`ExcalidrawView.ts` retain their pre-existing no-unsafe findings. `npm run madge` remains unavailable because the dependency is not installed. The final bundle is 4,835,213 bytes (+898 bytes, 407,667 bytes below 5 MiB). Required runtime validation is five main↔popout round trips with Phase 0 diagnostics: package windows must oscillate with the active window set, every abandoned popout must emit final-lease/package deletion, sibling views in one popout must keep the runtime until the last closes, and final close plus forced GC must return heap substantially closer to the 842.00 MB baseline than the prior 1277.63 MB result. Also smoke-test cold startup, plugin reload, a restored popout, and moving a leaf in both directions; cross-window runtime deletion while a sibling view is still active is the highest-impact risk. Mobile needs only a basic open/close regression because native popout migration is desktop-specific |
| 2026-08-24 | Added Phase 0 performance diagnostics before the save/memory/popout optimization work | Added an opt-in `performanceDiagnostics` utility and instrumented the existing save, serialization/compression, image/scene-file, export, package, Canvas-node, view lifecycle, and window-migration paths. All records are emitted through the existing debug logger as one flat string prefixed `EXCALIDRAW_PERF_PHASE0`; no vault contents or file paths are logged. High-frequency `onChange`/full-scene-hash measurements are aggregated instead of logging per callback, and summaries are activity-driven rather than timer-driven to avoid introducing a diagnostic lifecycle leak | Full runtime validation requires the repository dependencies and Obsidian. In the provided VM, dependency installation remains blocked by registry DNS (`EAI_AGAIN`), so the production Rollup build cannot be completed here. Global TypeScript parsing reaches only the missing `node` type-definition blocker (`TS2688`) with no syntax diagnostics in the modified sources. Runtime capture is the next checkpoint and should cover continuous drawing/autosave, manual/blur save, image-heavy cold/warm load, main↔popout migration, and repeated open/close/migration memory behavior |
| 2026-08-24 | Extended Phase 0 diagnostics after reviewing the four baseline captures | Added stable scene-file `reason=` attribution across initial/reload, forced-save, sync, theme, ExcalidrawAutomate, retry, and active-leaf-validation paths; request records now include current API binary-file count, missing API files, unresolved embedded-file count, and explicit retry scheduling/execution. Warm cache reads now aggregate IndexedDB-read, dependency-check, cache-resolution, SVG Blob-read/parse/data-URL, raster object-URL, and total materialization durations plus cache-rejection reasons. `EXCALIDRAW_PERF_PHASE0_CHECKPOINT(label)` emits an on-demand flat-text summary/heap checkpoint for use immediately after DevTools forced GC. No save/image/migration behavior was optimized or fixed in this step | Local full build remains unavailable in the provided VM because the dependency tree cannot be completed through the blocked npm registry. Validate in the maintainer environment with `npm run dev`/`npm run build`, then rerun the focused save/reason, warm-cache, popout, and forced-GC lifecycle captures described with this checkpoint |
| 2026-08-23 | Removed duplicate native tooltips from registered element actions | Stopped assigning an HTML `title` attribute to buttons created for `registerElementActionProvider()` while retaining the action title as the button's `aria-label`. This follows the existing Excalidraw icon-button behavior: the styled tooltip remains, Chromium no longer creates a second native tooltip, and assistive technology keeps the accessible name | Targeted lint, production build, bundle syntax, and `git diff --check` are required before handoff. Highest-risk manual check: hover a registered action long enough for the browser tooltip delay and confirm exactly one styled tooltip appears; then inspect the button and confirm it has `aria-label` but no `title`. Also activate the action once to confirm pointer handling is unchanged |
| 2026-08-23 | Made declarative-settings breadcrumbs touch-accessible on Obsidian Mobile | Replaced the link-styled breadcrumb buttons with native anchors using Obsidian's `onClickEvent` convention, prevented the shared internal-hash delegate from processing the same activation, and added manipulation touch behavior plus mobile/tablet-only tap-target padding. Desktop remains visually compact, keyboard activation remains native, and failed unpublished navigation disables the anchor without leaving a live hash target. Removed the advanced underline thickness/offset styling flagged by Obsidian CodeScanner while retaining the basic underline on internal settings links | Targeted lint, production build, bundle syntax, and `git diff --check` are required before handoff. Highest-risk validation is unintended duplicate navigation or page jumps: tap a parent and the Excalidraw root breadcrumb on one physical phone, then click both once on desktop and activate one with the keyboard. Mobile emulation alone is insufficient because it did not reproduce the reported issue |
| 2026-08-23 | Finalized the 2.27.0 beta.5 release notes and declarative-settings handoff | Reordered the release notes to lead with user-visible settings improvements, followed by upstream Excalidraw features, fixes, maintenance, and Excalidraw Automate APIs. Consolidated implementation-heavy wording into a concise explanation that this is one of the plugin's largest internal maintenance releases, covering the settings and persistence architecture, lifecycle and manager boundaries, runtime packaging, React 19, and cache performance. Preserved the maintainer's `manifest-beta.json` bump to `2.27.0-beta.5` | Targeted release-note ESLint, production build, bundle syntax, and `git diff --check` pass. The leaner release notes reduce the final bundle by a further 1,722 bytes. The exact beta.5 build is 4,798,339 bytes, 73,417 bytes raw and 24,492 bytes gzip above a clean `master` build, and remains 444,541 bytes below 5 MiB |
| 2026-08-23 | Implemented declarative-settings checkpoint 7 and reviewed the complete branch against `master` | Removed the five checkpoint-numbered page factories in favor of semantic page-family names and made legacy rendering consume one `getSettingsPages()` result. Moved filename, grid, TODO, and embed/auto-export component references from tab lifetime into a state object owned by one generated settings tree, preserving live cross-control behavior without retaining detached controls after a rebuild. Removed the unused cached declaration array, the unused adapter batch method, unused action/group/file/folder/color/textarea compatibility branches, the unused `navigateToSearchResult` declaration, an unnecessary changed return type, and an unreferenced toolbar class. Deduplicated the recovery prompt's button construction. Review also found that Markdown export rebuilt declarations through the live binding adapter; separated export-only builds from live binding registration so selecting **Copy settings** cannot redirect later changes to an unmounted tree. Retained the default-enabled `useDeclarativeSettings` compatibility preference, legacy DOM Markdown export, persistence/recovery safeguards, guarded unpublished navigation, and custom integrated renderers because each remains actively required. Final source-map attribution shows that the branch's raw bundle growth is primarily `settings.ts` (about 35.6 KB), compressed/generated payloads including maintained locale additions (about 12.1 KB), English setting text (about 6.9 KB), settings recovery management (about 7.9 KB across manager/store/prompt/writer/validation), the binding and dual-render adapters (about 5.7 KB), Markdown export/navigation (about 2.2 KB), and release notes (about 0.7 KB); no new runtime dependency accounts for the increase | A clean `master` production build is 4,724,922 bytes. After final release-note cleanup, the branch build is 4,798,339 bytes: +73,417 bytes raw and +24,492 bytes gzip, while remaining 444,541 bytes below 5 MiB. Cleanup reduced the branch by 2,450 bytes from 4,800,789. Targeted ESLint and private-member/reference audits pass for every cleanup file; `npm run code:unused`, `npm run build`, `npm run lib`, bundle syntax, `git diff --check`, and unchanged Obsidian `1.8.7` pins pass. Full `npm run code` retains the established 138-error repository backlog with no finding in a cleanup file; the production build retains the established 33 circular-dependency warnings. Maintainer authorized the final commit; the most focused post-commit smoke scenarios remain copying declarative settings before mutating a dependent control, exercising auto-export/embed-option and dynamic-grid dependencies in legacy mode, and confirming filename-preview updates from both filename controls and Compatibility mode |
| 2026-08-23 | Combined declarative-settings checkpoints 5 and 6: final layout/search and activation audit | Confirmed the hierarchy already follows the approved grouping rule and retained the persisted compatibility preference as a supported debugging/user fallback rather than transitional code. The complete non-empty definition tree is returned only on Obsidian 1.13+ when that preference is enabled; otherwise the empty-array contract deliberately invokes the shared legacy renderer. Renamed the last `Converted` helpers and replaced their obsolete pre-activation TSDoc. Audited sibling page names across every shipped locale and found no collisions. Russian alone lacked four maintained page metadata strings, so Fonts, its description, Offline CJK support, and PDF Export Settings now remain localized instead of falling back to English. Audited rendered/integrated declarations for aliases and confirmed utilities, breadcrumbs, videos, descriptions, and Mastery are marked non-searchable so filtered results are not crowded | Targeted ESLint, `npm run code:unused`, production build, bundle syntax, `git diff --check`, the locale-path audit, and unchanged Obsidian `1.8.7` pins pass. `dist/main.js` is 4,800,789 bytes, only 79 bytes larger than the completed 4E build. Maintainer validation confirmed ordinary and integrated search results, deep page navigation and clickable breadcrumbs, and restart switching between searchable and legacy layouts in both directions. The final checkpoint will compare the complete branch against `master` and attribute/remediate bundle growth |
| 2026-08-23 | Implemented declarative-settings checkpoint 4E and final 4D follow-ups | Added AI as a shared page in its original position after Saving. AI enablement, session usage, verbose diagnostics, and both token limits have independent declarations for focused Obsidian search results and complete Markdown export. Provider profiles plus text/multimodal and image models remain one full-width integrated declaration because profile rename/removal/default restoration must update model references as one state machine; both layouts invoke the same editor logic and the existing settings manager remains responsible for encrypting provider keys on disk. Removed the standalone AI section renderer. Installed-script settings retain their conditional location under Excalidraw Automate, fall back safely during pre-layout indexing, and now ask a mounted settings tab to rebuild when a script saves its declarations. Replaced the unsuccessful delegated legacy hash-link handler with lifecycle-managed direct handlers bound to each rendered link and its active-tab target | Maintainer testing confirmed the AI settings, live installed-script page refresh, and the legacy PDF/Markdown cross-links. Release notes call out the moved installed-script location. Targeted settings/release-note ESLint, quiet Excalidraw Automate ESLint, `npm run code:unused`, `npm run lib`, production build, bundle syntax, `git diff --check`, and the unchanged Obsidian `1.8.7` pins pass; `main.ts` retains its four unrelated existing unpublished-API lint findings. Final review found no duplicate AI renderer, duplicate script-refresh path, stale delegated link handler, or unnecessary declaration left in this batch |
| 2026-08-23 | Closed checkpoint 4D after maintainer validation and final UI corrections | Maintainer validation confirmed Excalidraw Automate startup behavior and the rest of the 4D batch, then identified four focused presentation/dependency issues. Combined each declarative page's utility toolbar and breadcrumbs into one full-width rendered setting, centered both, and removed the separate setting-row divider and excess spacing. Fixed Taskbone search-result rendering by expressing API-key disabled state as the canonical control predicate applied after input creation, rather than relying on `capture` before the adapter's final row state. Replaced the long startup-script action text with dynamic Lucide `file-code-2`/`file-plus-2` icons and localized Open/Create tooltips. Added one lifecycle-managed legacy link delegate that opens all folded ancestor `<details>` elements and scrolls to the target, making the PDF Export/Markdown Reading Mode cross-links work in the single-page layout as well. Final review found no superseded breadcrumb definition, standalone 4D renderer, unused symbol, or duplicated behavior implementation worth retaining | Targeted ESLint, `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. `dist/main.js` is 4,797,578 bytes. The final fixes are localized to initial disabled-state evaluation, header composition/CSS, one icon-button presentation, and legacy in-page navigation; maintainer authorized committing once addressed. Lowest-cost post-commit smoke checks are opening Taskbone from search while disabled, hovering the startup file icon, and selecting PDF Export once in legacy mode |
| 2026-08-23 | Implemented declarative-settings checkpoint 4D: Fonts, Miscellaneous features, Excalidraw Automate, and Compatibility | Extended the shared page model with local-font controls, a nested Offline CJK page, miscellaneous/LaTeX/file-display controls, an integrated Taskbone page, Excalidraw Automate plus startup/autostart controls, a conditionally visible installed-script-settings page, and Compatibility. Font-picker cleanup remains owned by the existing tracker; Taskbone retains initial/toggled API-key disablement and first-enable initialization; startup-script create/open and vault-path behavior remain one shared custom row; arbitrary installed-script boolean/text/dropdown/textarea/number controls use one shared runtime renderer and are searchable by script and variable names. Removed the four superseded standalone legacy renderers. Added short group descriptions in all maintained locales, corrected the autostart-management location, and scoped internal `#...` settings links to an accent-colored underline in both layouts so PDF Export and similar links remain visible across themes | Targeted ESLint passed for settings, release notes, and all maintained locales; `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, static parity for all 27 prior canonical keys and four video links, and the unchanged `1.8.7` dependency/minimum assertion passed. Full `npm run code` retains its existing repository backlog, with no finding in a checkpoint-4D file. Manual validation then confirmed the batch apart from the four focused corrections recorded in the closing action above |
| 2026-08-23 | Completed checkpoint-4C cross-reference and duplication/dead-code review | Reused the guarded page navigator for every migrated internal settings link: legacy hash targets remain unchanged, while declarative descriptions intercept only the three known settings tags and resolve them through page metadata. This repairs the Markdown-reading/PDF-export pair and existing auto-export references without repetitive per-link buttons or hard-coded localized paths. Reciprocal inserted-file/auto-export buttons now use the same metadata resolver. Cached tag paths are rebuilt with each declaration tree, and the new built-in Markdown font ID map moved beside the canonical font-family list instead of duplicating those names in `settings.ts`. Confirmed that no superseded 4C renderer, duplicate target path, stale font-ID declaration, or unhandled internal hash remains | Maintainer testing confirmed the auto-export dependency, correct font faces, clickable breadcrumbs, and reciprocal navigation. Targeted ESLint for every changed source/locale, `npm run code:unused`, `npm run lib`, production build, bundle syntax, `git diff --check`, and the unchanged `1.8.7` assertion passed. Full `npm run code` still reports its existing 138-error repository backlog, with no finding in a checkpoint-4C file. The low-risk remaining smoke test is selecting the inline PDF-export/Markdown-reading cross-reference once in each direction; it uses the same now-validated navigator and declaration-derived paths |
| 2026-08-23 | Added guarded declarative page navigation after inspecting the live Obsidian 1.13 settings manager | The maintainer identified the unpublished settings-manager navigation methods. The first implementation followed an incorrect external interpretation and passed a tab ID to `navigateToPage`, causing `openTab()` to access `navEl` on a string. The supplied decompiled source and runtime capture established the actual contracts: `openPagePath(tabId, pagePath)` resolves the ID, while `navigateToPage(tabObject, pagePath)` requires the resolved `PluginSettingTab`; `navigateToSearchResult` also carries a tab object. The minimal optional surfaces are documented correctly, and one guarded helper uses `openPagePath` first with `findTabById` plus `navigateToPage` as its compatibility fallback. Declarative paths are derived recursively from the canonical localized `SettingsPageModel`. Every declarative subpage shows a breadcrumb, and reciprocal rows connect the inserted-file dropdown and auto-export page. If navigation is unavailable, context remains plain text and related rows are omitted. No synthetic clicking or public Obsidian version bump was introduced | Focused ESLint, `npm run code:unused`, `npm run lib`, production build, bundle syntax, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. Manual testing confirmed nested ancestor/root breadcrumbs and both directions of reciprocal auto-export navigation |
| 2026-08-23 | Fixed checkpoint-4C font previews and assessed cross-page navigation after manual testing | The shared picker correctly applied font-family names, but built-in Excalidraw font faces are registered by the window-scoped Excalidraw runtime. A Settings popout therefore fell back to one generic face while the sidepanel in an Excalidraw view rendered correctly. `FontPickerComponent` now accepts an optional built-in-font CSS provider; settings pickers install only their requested preview faces into the control's owning document and remove those styles during declarative page or legacy-tab cleanup. Sidepanel behavior remains unchanged. The official Obsidian 1.13 declarative-settings API supports rendered buttons and nested pages but exposes no documented arbitrary page-navigation method, breadcrumb hook, or page-header extension point, so no public-API implementation was available. This navigation assessment was superseded when the maintainer subsequently identified and requested guarded use of the unpublished settings-manager method | Targeted ESLint and `npm run code:unused` passed; the production build passed with the established 33 circular-dependency warnings. Manual testing confirmed that all built-in font previews render with their correct faces in the Settings popout |
| 2026-08-23 | Implemented declarative-settings checkpoint 4C: Embed/export, embedded files, and nonstandard features | Extended the shared page model with Previews/links/Canvas, Image caching, Export, Embed files, and nonstandard-feature pages. Export is divided into groups of at least three controls where practical: image sizing, theme/background, integrated PDF defaults, and auto-export. The auto-export SVG/PNG toggles and inserted-file dropdown retain their cross-page invariant; disabling the selected export type falls back to Excalidraw and hides the source-comment setting. PDF defaults and interactive Markdown defaults remain integrated components with aliases for their internal controls. Markdown image dimensions share the validated integer-input helper, the font picker now returns declarative cleanup, and custom-pen count retains live toolbar updates. All three superseded standalone legacy renderers were removed. The migrated interactive-Markdown component also now saves filename, properties, and locked-reading-mode toggles immediately and keeps its mutually exclusive background-source values consistent | Targeted ESLint, `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, parity checks for all 28 prior canonical keys, direct settings fields, and five video links, and the unchanged `1.8.7` dependency/minimum assertion passed. Highest-risk manual validation remains: auto-export/insert-type cross-page behavior; initial and toggled visibility plus persistence inside PDF and interactive-Markdown integrated components; Markdown image font/dimension reload with viewport preservation; and custom-pen count updating the toolbar. Repeat the dependency and integrated-component checks once in legacy mode before committing |
| 2026-08-23 | Completed final checkpoint-4B duplication/dead-code review | Confirmed the apparent legacy/declarative repetition around grid, laser, modifier, and transclusion controls is host-specific metadata/layout around shared control configurators, not duplicated behavior. No obsolete component, helper, import, locale key, or independent legacy implementation remains from the converted sections. Consolidated the duplicated viewport-filter calculation in `loadDrawing()` into one shared app-state value and added release-note coverage for viewport preservation and the maintainer-supplied completed-TODO default. No broader cleanup was mixed into the checkpoint | Node 22.22.2; targeted ESLint passed for settings, adapter, modifier component, release notes, and all maintained locales; `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. The build retains the established 33 circular-dependency warnings, and `ExcalidrawView.ts` retains exactly its existing 18 `no-unsafe-*` findings. User validation confirmed 4B overall and authorized commit after this review |
| 2026-08-23 | Preserved live viewports during rendering-related settings reloads | Toggling Parse TODO correctly requires open drawings to rebuild parsed scene content, but the settings queue used the general full reload path. When a view had no dirty drawing edits, its current navigation-only scroll/zoom was intentionally absent from disk, so the reload restored an older persisted viewport and visibly jumped. Added `ExcalidrawView.reloadAfterSettingsChange()` and routed only the settings action through it. It reuses the view's established multiple-leaf reload behavior by omitting `scrollX`, `scrollY`, and `zoom` from the incoming app state; Excalidraw therefore retains the live values while elements and setting-derived rendering refresh. General file-event, sync, save, and ordinary reload behavior remains unchanged | Targeted settings ESLint, `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed; the production build retains the established 33 circular-dependency warnings. `ExcalidrawView.ts` retains exactly its existing 18 `no-unsafe-*` findings, with no new lint finding from this change. Focused manual retest pending: pan and zoom an otherwise-clean open drawing, toggle Parse TODO, and verify the TODO rendering changes without moving the viewport; repeat once with an actual TODO text element and once with Zoom to fit on open enabled |
| 2026-08-23 | Fixed checkpoint-4B complex-component layout and initial dependent-control state after manual testing | The declarative full-width rule was incorrectly conditional on an `.excalidraw-settings` ancestor that Obsidian's navigated 1.13 sub-pages do not retain, leaving custom renderers in the default horizontal `Setting` layout. The dedicated class is now self-sufficient, restoring full-width ownership for HotkeyEditor, modifier matrices, and every other renderer using the shared helper without affecting legacy rows. `LegacySettingsAdapter` previously called `Setting.setDisabled()` before creating its input; because the method only affects existing components, TODO/Done (and any similar predicate-driven custom control) reopened enabled. Disabled state is now evaluated once and applied after control creation for toggle, text, dropdown, number-dropdown, and slider rows in both the legacy path and declarative custom-render fallback. The maintainer's separate `done` default change remains untouched | Targeted ESLint, `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. The build retains the established 33 circular-dependency warnings. Focused manual retest pending: Hotkey overrides layout, one modifier matrix layout and persistence, and TODO/Done initial disabled state after leaving/re-entering in both modes |
| 2026-08-23 | Implemented declarative-settings checkpoint 4B: Display and Links/transclusions | Extended the shared page model to the complete appearance/behavior and links/transclusion/TODO sections without keeping the former standalone legacy renderers. Display now groups Editing and previews, device UI modes, Hotkey overrides, Theme and styling, Zoom and pan, Pen, Grid, Laser pointer, and Link click/drag-and-drop modifier keys. The modifier page contains Link-opening gestures plus third-level pages for browser drag, OS-file drag, internal Obsidian drag, and link-click pane targets; the existing toggle-matrix component can render one category without adding a second fold. Links now groups behavior, pane/tab handling, appearance, TODOs, and text transclusions. Shared custom-row helpers preserve nested grid/laser values and numeric blank/validation semantics; dynamic grid color refreshes declarative visibility without refreshing legacy mode, TODO parsing immediately updates both icon inputs, and hotkey listeners unload when navigating away. All former section text, four YouTube thumbnails, setting keys, grid/laser fields, modifier matrices, and the reading-mode legacy anchor remain represented. Markdown export rebuilds fresh declarations so DocumentFragments consumed by a previously opened page cannot disappear from the copied document | Automated validation passed: targeted ESLint on all changed source/locales, `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion. The production build retains the established 33 circular-dependency warnings. Static parity checks found all 47 formerly canonical keys plus the six settings previously rendered by direct controls, all four grid fields, all three laser fields, the modifier configuration, HotkeyEditor, all four video IDs, and every prior locale reference. Manual validation is still required before committing. Prioritize: (1) toggle Dynamic grid color and verify the custom color row appears/disappears and an open drawing updates; (2) toggle Parse TODO and verify both icon inputs enable/disable, then edit an icon and reopen settings; (3) navigate to a third-level modifier page, change one non-default modifier, leave/re-enter, and verify persistence; (4) change a transclusion numeric field using a valid number, invalid text, and blank input; and (5) add/remove a hotkey override, navigate away, and verify it takes effect. Repeat checks 1-5 once in legacy mode after restart; one mobile smoke test should cover the mobile long-press and phone UI-mode controls, while popout coverage is only needed for hotkey capture if Settings is deliberately opened there |
| 2026-08-23 | Completed declarative-settings checkpoint 4A: shell, help/promotion, Basic, and Saving | Activated a partial declarative tree on Obsidian 1.13+ while retaining the complete legacy single-page fallback. A persisted, default-enabled layout preference can select the legacy interface after restart. One `SettingsPageModel` hierarchy supplies both renderers with Basic/Saving descriptions and the Updates and startup, Files and folders, Stencil Library, Storage and autosave, and Filename sections; Automation scripts now belongs to Files and folders in both modes. Declarative navigation repeats descriptions inside opened pages as required, while legacy folds show each description once and put a separator before every nested section. Both modes share the compact Copy settings/NotebookLM/help/support toolbar; Mastery remains root-only and legacy alone retains local search. Declarative Markdown export recursively includes unopened pages and writes `- **Title:** (type) Description`. Final review removed the unused ContentSearcher clipboard/custom-element API, a stale settings-links CSS family, an unused NotebookLM label, unnecessary public type exports and wrapper methods, and avoided recreating Markdown normalization helpers per row. Added an idempotent declarative-display preparation guard so rendering a nested utility bar cannot reset pending embed/reload actions. The user-supplied Wiki URL correction is preserved | User validation drove four UI revisions and confirmed the resulting layout before the final low-risk separator/review cleanup. Targeted ESLint passed for every changed TypeScript and maintained-locale file; `npm run code:unused`, `npm run build`, `npm run lib`, `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. The production build retains the established 33 circular-dependency warnings. Highest remaining risks for follow-up smoke testing are: toggle searchable/legacy layout in each direction and restart; navigate Basic/Saving nested pages and verify descriptions, toolbar, and root-only Mastery; inspect legacy separator/description/fold ordering; export Markdown before opening nested pages; and rapidly edit the filename prefix while checking its sample and persistence. Main-window desktop covers 4A behavior; use one mobile layout smoke test, while popout-specific coverage is only needed if Settings is deliberately opened there |
| 2026-08-23 | Removed startup recovery dead ends and preserved deliberate factory reset | Split cold startup into explicit missing/corrupt and recovery/no-recovery cases. Missing `data.json` with no IndexedDB record is now treated as a normal new installation: defaults are persisted without a corruption warning. Missing `data.json` with a recovery record displays a localized modal offering **Restore backup** or **Reset to defaults**; restoring is the data-preserving close/Escape default, while resetting immediately replaces both `data.json` and the stale recovery. Existing-but-corrupt data with no recovery displays a localized modal offering **Reset to defaults** or **Wait for restored file**; waiting is the data-preserving close/Escape default and intentionally leaves the corrupt file untouched until a valid external replacement arrives. Corrupt data with recovery still restores automatically, and invalid runtime synchronization still repairs from active memory. While either startup modal is open, the normal three-second settings wait is extended so layout initialization cannot race ahead using an unresolved choice | Focused executable manager tests passed seven scenarios: silent new install, missing-with-recovery restore, missing-with-recovery factory reset replacing recovery, corrupt-without-recovery reset with subsequent saving enabled, corrupt-without-recovery wait with writes blocked, corrupt-with-recovery automatic restore, and runtime corruption repaired from memory. Targeted ESLint passed for the manager, new modal, recovery store, maintained locales, and release note. Production build passed with the unchanged 33 circular-dependency warnings and produced a 4,743,857-byte `dist/main.js`; `node --check`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. Full `npm run code` remains at the established 138-error backlog with no finding in a new or behavior-changed module. Manual validation should prioritize: (1) rename/delete `data.json` after first establishing recovery, restart, and test both restore and reset choices on separate runs; (2) clear the recovery IndexedDB record, leave a zero-byte `data.json`, restart, and test both reset and wait/external-restore choices; (3) use a clean vault/new installation with neither file nor recovery and confirm there is no warning or question. The modal and IndexedDB path require one mobile smoke test; popouts do not need separate coverage because this is plugin-global startup state |
| 2026-08-22 | Corrected invalid settings recovery semantics before checkpoint 4 | Added a durable `SettingsRecoveryStore` backed by a vault-namespaced IndexedDB database with one atomically replaced `lastKnownGood` record; it does not use `localStorage` or a synchronized vault file. The encrypted persisted form (including unknown keys and any legacy in-data stencil library) is refreshed after every valid load, even when no setting is edited, and before every ordinary `data.json` write. A corrupt external/runtime load now leaves active settings untouched, displays a localized repair notice, and immediately serializes the active settings back through recovery and `saveData()`. A corrupt cold-start load automatically applies the last-known-good recovery, repairs `data.json`, and displays a distinct recovery notice. Valid `data.json` remains authoritative and replaces the device-local recovery, preventing stale cross-device recovery prompts. Only the cold-start case where both `data.json` and recovery are unusable retains the protective write block. The database connection is closed on plugin unload; API-key obfuscation, unknown-key retention, checkpoint-4 hold, empty declarative fallback, and Obsidian `1.8.7` compatibility are unchanged | Targeted ESLint passed with zero findings in the new store, manager, maintained locale changes, and release note. A focused executable store test passed for an empty database, a 12 MiB snapshot, an aborted transaction preserving the preceding record, close/reopen persistence, and teardown while the initial database open was pending. Production `npm run build` passed with the unchanged 33 circular-dependency warnings and produced a 4,739,807-byte `dist/main.js`; `node --check`, `git diff --check`, and the `1.8.7` dependency/minimum assertion passed. Full `npm run code` remains at the established 138-error backlog with no finding in a new or behavior-changed module. Before checkpoint 4 resumes, prioritize three manual checks: (1) with a recognizable active setting, empty `data.json` while Obsidian is running and confirm the repair notice, immediate non-empty rewrite, unchanged UI value, and persistence after restart; (2) make a valid manual `data.json` change while Obsidian is closed, start and close without editing settings, then empty the file and restart, confirming the recovery notice and restoration of that manual value; (3) after a recovery exists, synchronize/load a different valid file and then corrupt it, confirming the newer valid value—not the older recovery—is restored. The IndexedDB path is plugin-global, so popout coverage is not separate; repeat check 1 once on mobile, and use a legacy multi-megabyte stencil-in-settings profile for the highest storage-pressure validation |
| 2026-08-22 | Implemented the diagnosed settings persistence root fix before checkpoint 4 | Removed `SettingsRecoveryStore`, its local-storage journal, and automatic startup recovery authority. Added `SerializedSettingsWriter`, which captures an immutable JSON snapshot at request time and serializes every plugin-wide `saveData()` call; a rejected write does not poison later saves. The settings-tab queue retains burst coalescing, editable-focus deferral, immediate window-blur/hide flush, and latest-revision completion. Settings loads now distinguish a valid record, a genuinely missing first-installation file, and empty/malformed/failed data by inspecting the plugin `data.json` through the vault adapter before loading. Invalid runtime/external data leaves active settings untouched, suppresses stencil invalidation and all settings writes, and displays a localized warning until a valid file is synchronized or restored; an invalid cold-start file supplies defaults only in memory without writing them to disk. Excalidraw Mastery `<details>` initialization now persists only an actual state change, eliminating the diagnostic-confirmed save caused merely by displaying settings. API-key obfuscation, unknown keys, `1.8.7` compatibility, and the empty declarative fallback remain unchanged | Focused executable tests passed for immutable queued snapshots, strict write serialization, continuation after a rejected write, valid-object acceptance, genuine first-installation detection, and rejection of empty, failed, array, and runtime-missing loads. Targeted ESLint passed for every changed source and locale file except the four established unrelated `main.ts` findings. Production `npm run build` passed with the unchanged 33 circular-dependency warnings and produced a 4,734,998-byte `dist/main.js`; `node --check`, `git diff --check`, the unchanged `1.8.7` dependency/minimum assertion, and removal searches for the diagnostic prefix, recovery store, and journal key passed. Full `npm run code` retains the established 138-error repository backlog with no finding in a newly added or behavior-changed module. Before checkpoint 4 resumes, first open Excalidraw settings without touching anything and confirm `data.json` mtime does not change; then change a text setting and immediately use the reload hotkey from the main workspace, confirming persistence. Highest residual risk is the invalid-file safety gate on synchronized desktop/mobile vaults: in a backed-up test vault, replace `data.json` with an empty file while Obsidian is running, confirm the localized warning appears and active settings remain unchanged without a default rewrite, then restore the valid file and confirm external reload resumes normal saving. Popouts need the first two checks because the blur flush is window-owned; the adapter-based invalid-load check needs one mobile smoke test |
| 2026-08-21 | Paused declarative checkpoint 4 for root-cause settings persistence diagnosis | The automatic recovery design exposed unresolved multi-device and Obsidian Sync conflict semantics. Conversion batches are paused until temporary diagnostics distinguish overlapping writes, a single shutdown-interrupted `saveData()`, and an empty external reload that is merged with defaults and persisted. The target is to return to Obsidian's normal `saveData()` lifecycle with the smallest justified protections: one global serialized/coalesced writer, no shutdown-dependent save, and validation before applying externally loaded data. Temporary diagnostics use the unique `EXCALIDRAW_SETTINGS_DIAG_V1` prefix and record only timing/state/revision/serialized-size metadata. Static tracing also identified a non-user-initiated write: programmatically initializing the Excalidraw Mastery `<details>` element schedules a `toggle` event after its listener is attached, so merely displaying the settings tab calls `saveSettings()` | Three controlled shutdown traces did not reproduce corruption. The command-palette case coalesced four mutations into one 147,050-byte write that resolved in 53 ms and fully settled 68 ms after blur. The direct reload-hotkey case exercised a 96.5 ms write, which still resolved and cleared before the new process loaded the matching 147,046-byte object. Direct macOS Quit also preserved the changed setting and restarted from a valid 147,046-byte object. No trace showed overlapping writes, an external reload, or a recovery journal at startup; Reload did not emit plugin `onunload` events. The evidence points to the former unbounded/per-call persistence and cross-caller overlap—not normal termination of one isolated `saveData()`—as the original loss mechanism. Remove the automatic recovery authority and temporary diagnostics; retain one global serialized stable-snapshot writer plus tab-level coalescing, eliminate the display-time promotional save, and reject invalid external reloads without applying defaults. Checkpoint 4 remains blocked until that simpler root fix passes build and focused manual validation |
| 2026-08-21 | Hardened settings persistence against abrupt Obsidian reload before checkpoint 4 | Manual testing confirmed the coalesced queue fixed active-input disconnection, then exposed a higher-impact lifecycle case: an input could remain focused in the Obsidian 1.13 Settings window until the user clicked the main workspace and immediately invoked Reload; Obsidian does not await plugin teardown saves, so an interrupted `saveData()` could leave a zero-byte `data.json` and reset every setting. The settings tab now listens on its owning window and force-flushes synchronously on window blur, before the user can issue a main-window command. Added `SettingsRecoveryStore` at the plugin-wide persistence boundary: every encrypted stable snapshot is synchronously journaled through Obsidian's vault-scoped local-storage API before the asynchronous file write begins; all plugin settings writes are serialized; only the matching latest successful write clears the journal; and startup uses any pending journal without first parsing a possibly empty/corrupt `data.json`, then writes the recovered snapshot back. Unknown keys and API-key obfuscation remain intact, and the pinned Obsidian dependency/minimum remains `1.8.7`, where the local-storage API is already available | Focused executable tests passed for synchronous journal staging, successful clearing, serialized overlapping writes, latest-token ownership, a never-completing save followed by simulated restart/recovery, failure retention, recovery after a rejected write, and focus-loss forced flush. Targeted ESLint passed for the settings manager, recovery store, queue, binding registry, and settings tab. Production `npm run build` passed with the unchanged 33 circular-dependency warnings and produced a 4,733,983-byte `dist/main.js`; `node --check dist/main.js`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. Full `npm run code` retains the established 138-error repository backlog with no finding in a touched file. Before checkpoint 4, edit a text setting without blurring it, click directly into the main workspace, immediately invoke **Reload app without saving**, and confirm after restart that the new value remains and `.obsidian/plugins/obsidian-excalidraw-plugin/data.json` is non-empty. Repeat once after several rapid edits and once by closing Settings normally. Highest residual risk is local-storage quota exhaustion for unusually large legacy `data.json` stencil libraries; staging failures are logged and the immediate window-blur flush still runs, while moving the library to its vault-file storage mode removes that large payload from settings |
| 2026-08-21 | Completed the checkpoint 3 persistence follow-up before conversion batches | Manual testing showed rapid typing/backspace in both sanitized and ordinary text controls could disconnect the active input, collapse the legacy nested sections, and move the settings scroll position. DevTools confirmed `isConnected === false`: Obsidian 1.13 was rebuilding the empty-definition legacy-fallback tab after persistence. Replaced the one-full-write-per-input-event promise chain with documented `SettingsPersistenceQueue`: a 250 ms trailing edge coalesces bursts; persistence remains deferred while an editable control in this tab owns focus so a save cannot replace it mid-edit; hiding the tab flushes immediately. A mutation during an in-flight write produces one final latest-snapshot write, pending view actions run only after the final successful snapshot, declarative callers retain an awaitable completion promise, and a failed write does not poison the next update. No setting key, stored value, dependency, manifest minimum, or empty-array fallback changed | Focused executable tests passed for burst coalescing, editable-focus deferral, hide-style forced flush, one follow-up write during an in-flight save, pending-action ordering, failure propagation, and recovery. Targeted ESLint passed for the queue, binding registry, and settings tab. Production `npm run build` passed with the unchanged 33 circular-dependency warnings and produced a 4,731,467-byte `dist/main.js`; `node --check`, `git diff --check`, and the unchanged `1.8.7` dependency/minimum assertion passed. Full `npm run code` retains the established 138-error repository backlog with no finding in a touched file. Before checkpoint 4, reproduce the original three text-entry cases: rapidly type a filename prefix, continuously backspace a value, and edit/click away/click back immediately/continue deleting; the section and active input must remain stable, then closing/reopening settings must show the final value. Also change one reload-on-change control and immediately close settings to validate forced flush. Highest risk is either a host path that closes the modal without `hide()` or future native declarative text controls waiting on focus-aware persistence; repeat these checks when the first non-empty definition batch activates |
| 2026-08-21 | Completed declarative-settings checkpoint 3: establish canonical specifications and dual adapters | Moved the typed toggle, text, string/numeric dropdown, and slider dialect from `settings.ts` into `settingSpecs.ts`. Added `SettingBindingRegistry` as the single read/write transformation and persistence boundary for negate, sanitize, parse, scale, before/after/afterUpdate, reload, duplicate-key rejection, and invalid-value rejection. Added `LegacySettingsAdapter` and routed all 125 existing `buildSetting()` rows through it; rich names, sanitizers, vault-path controls, and custom-width sliders can be reused from declarative `render` definitions. Added `DeclarativeSettingsAdapter` for native definitions, search metadata, visibility/disabled predicates, and custom-render fallback. `getControlValue()`/`setControlValue()` now bridge registered native controls to the existing normalization, save queue, obfuscation, and pending view actions. Legacy callbacks retain their former completion boundary after `afterUpdate`, while declarative writes await queued persistence. `getSettingDefinitions()` clears stale bindings and still returns a literal empty array, so Obsidian 1.13.x continues to use `display()` | Focused executable Node tests passed for inverted toggles, hook order, immediate post-write sanitization, declarative-versus-legacy persistence completion, numeric parsing, slider scaling, duplicate/unknown keys, invalid types, native definition conversion, aliases/options, and custom-render selection. Targeted ESLint passed for every changed source module and the compatibility shim. Production `npm run build` passed under Node 22 with the unchanged 33 circular-dependency warnings and no TypeScript diagnostics, producing a 4,729,511-byte `dist/main.js`; `node --check dist/main.js`, `git diff --check`, the literal-empty-definition assertion, and the unchanged `1.8.7` dependency/minimum assertion passed. Repository-wide `npm run code` retains its pre-existing 138-error backlog with no finding in a touched file. Highest risk is subtle legacy behavior drift now that every canonical row uses the shared registry; manually test one example of negate, sanitize plus live preview, numeric dropdown, scaled slider, vault-path suggestion/warning, afterUpdate embed refresh, reload-on-change, and rapid queued edits. Also confirm all top help/promotion/search/export utilities still render, credentials remain obfuscated after an unrelated edit, and view effects work in the main window plus a popout; use one mobile smoke test for settings interaction and reload behavior |
| 2026-08-21 | Completed declarative-settings checkpoint 2: add the Obsidian 1.13 compatibility boundary | Replaced the temporary `SettingDefinitionItem = string` escape hatch with a documented local structural definition union for the 1.13.0 controls and containers planned by this migration. Added a guarded runtime facade for `getSettingDefinitions`, `getControlValue`, `setControlValue`, `update`, and `refreshDomState`; it returns `null` unless every required method exists. The shim deliberately avoids `declare module "obsidian"`, runtime imports, list/page-class APIs, secret controls, and features marked as newer than 1.13.0. `getSettingDefinitions()` still returns `[]`, so the imperative settings UI remains the only active path | Targeted ESLint passed for `src/core/settings.ts` and the new compatibility module. Production `npm run build` passed under Node 22 with the unchanged 33 circular-dependency warnings and produced a 4,724,922-byte `dist/main.js`; `node --check dist/main.js` and `git diff --check` passed. Repository-wide `npm run code` retains its pre-existing 138-error backlog, with no finding in either touched source file. The dependency/minimum-version assertion confirmed `package.json` and `manifest.json` remain at `1.8.7`, and the facade symbols are absent from the tree-shaken runtime bundle. Highest risk is structural drift between this local 1.13.0 subset and the actual host API; the strongest available test is to open the plugin settings on 1.13.x, confirm the complete legacy tab and all top utilities still render through the empty-array fallback, and later exercise both facade branches once checkpoint 3 introduces callers. No 1.8.7 installation is available, so the recorded temporary `return []` procedure remains the legacy-path test |
| 2026-08-21 | Completed declarative-settings checkpoint 1: record the approved migration plan | Promoted the dual-support settings migration to the active refactor; recorded the unchanged Obsidian `1.8.7` dependency/minimum, temporary `return []` legacy-test method, canonical dual-adapter architecture, mandatory persistence bridge, native visibility/disabled/update rules, custom-component cleanup ownership, five conversion batches, explicit preservation of NotebookLM/Excalidraw Mastery/help/promotion/clipboard features, filtered-search UX decision, and per-checkpoint validation-and-commit gate. No runtime source, dependency, manifest, persisted setting, locale, or generated artifact was changed as source | Documentation review and `git diff --check` passed. Production `npm run build` passed under Node 22 with the unchanged 33 circular-dependency warnings and produced a 4,724,922-byte `dist/main.js`; `node --check dist/main.js` passed. No Obsidian UI test is required for this documentation-only checkpoint. Highest-risk planning omission would be a setting or top utility disappearing at the eventual non-empty-array cutover; checkpoint 6 therefore requires a complete inventory, while the strongest immediate review is to verify the recorded batches, compatibility constraints, top-surface requirements, and validation matrix before checkpoint 2 begins |
| 2026-08-16 | Completed the published Excalidraw dependency handoff | Published fork version `0.18.125` is now the plugin's exact dependency in `package.json` and `package-lock.json`. `npm install` restored the installed package from npm, including the new `addFiles` declaration and all four Obsidian artifacts. The temporary local declaration cast was removed; the plugin now calls the typed options form directly | Production `npm run build` passed against the published package with the unchanged 33 circular-dependency warnings and produced a 4,724,922-byte `dist/main.js`; `node --check dist/main.js` and targeted lint for the changed cache/loader/manager/utility files passed. The published declaration and production artifact both contain `skipSvgNormalization` |
| 2026-08-16 | Removed temporary performance observability and completed paired commit review | Removed every `[TEMP PERF]` console line, timing accumulator, diagnostic cache callback, publication-name map, and animation-frame marker. The functional fast/deferred queue, browser-task yield, stale-first validation metadata, v2 cache behavior, and trusted-SVG normalization bypass remain. The review also hardened failed IndexedDB upgrades so a closed legacy connection cannot be advertised as a ready cache. Historical diagnostic checkpoints below remain as the record of how the bottlenecks were identified; no diagnostic code or marker is present in `src` or the production bundle | Fork `yarn build:obsidian` and plugin development/production builds pass under Node 22; the four locally copied fork artifacts match their build outputs byte-for-byte. `node --check dist/main.js` and both repositories' `git diff --check` pass; the production bundle is 4,724,926 bytes and contains the new normalization option. Targeted plugin lint is clean for every changed cache/loader/manager/utility file, while `ExcalidrawView.ts` retains 18 unrelated existing findings away from the changed boundary. Full plugin `npm run code` retains its repository backlog (138 errors), and fork `yarn test:typecheck` retains its documented test-harness backlog (`window.h`, disabled `createTestHook`, and stale fixtures), with no diagnostics in the touched fork files; focused fork ESLint has no findings in either touched range. The measured warm reopen improved synchronous `addFiles()` time from 12.76 seconds to 1.43 seconds. Before release, smoke-test cache-v2 migration/backup preservation, warm reopen, a stale nested drawing, PDF scale upgrade, ordinary SVG normalization, rapid close during deferred generation, popout, and mobile |
| 2026-08-16 | Bypassed duplicate SVG normalization for trusted embedded drawings | A runtime trace showed `addFiles()` synchronously consuming 12.76 seconds while publishing 194.8 MiB of data-URL text, closely proportional to batch size. The paired fork now extends the existing one-argument API with an optional object form containing files plus a `ReadonlySet<FileId>` whose SVG payloads are already normalized. The plugin certifies only SVGs backed by an Excalidraw source file; no marker enters `BinaryFileData`, scene JSON, cache records, or component state. In the component, all legacy array callers and every ID absent from the set execute the unchanged normalization path. Fork changes are confined to the imperative API declaration and `App.addFiles()`/`addMissingFiles()` and carry exact `zsviczian` fingerprints | Fork `yarn build:obsidian` passed and generated the four consumer artifacts plus updated declarations. Repository-wide `yarn test:typecheck` remains blocked by the documented pre-existing test-harness backlog (`window.h`, disabled `createTestHook`, stale fixtures), with no diagnostic in either touched file. Focused ESLint's normal formatter is broken by an ESM/CJS mismatch; JSON output confirms no diagnostic in the touched ranges after retaining the repository's unrelated existing warnings. After copying only the four local artifacts into the installed package, plugin development and production builds passed with the unchanged 33 circular-dependency warnings; `node --check dist/main.js`, touched-range ESLint, and both repositories' `git diff --check` passed. The production bundle is 4,732,562 bytes and contains the new option/bypass path. Manual validation should repeat the unchanged warm reopen trace and compare `add-files-flush.addFilesDurationMs`: the 84.2 MiB/20-file batch previously took 5,530 ms and all publication calls totaled 12,761 ms. Also open a drawing containing an ordinary vault SVG and confirm it renders unchanged; main window and popout need coverage, plus one mobile smoke test because reduced temporary SVG strings/DOM should help memory pressure there |
@@ -426,24 +654,30 @@ re-exports must not be misclassified as accidental duplication.
### React and popout windows
The current root renderer is already a React function component in substance:
`excalidrawRootElement()` calls hooks and is mounted with `createRoot()`. It is
embedded as a class method and written with `React.createElement()` rather than
living in a component module.
The root renderer now lives in `src/view/components/ExcalidrawRoot.ts` and is
mounted by `ExcalidrawView` with `createRoot()`. It remains written with
`React.createElement()` rather than TSX.
The unusual runtime binding is essential:
- Rollup embeds React, ReactDOM, and compressed Excalidraw payloads.
- `PackageManager` evaluates a fresh package set in each Obsidian window.
- `ExcalidrawView.onload()` resolves packages for `ownerWindow`.
- The root, hooks, refs, and elements use `this.packages.react` and
`this.packages.reactDOM`.
- The package is removed when the last relevant leaf in a window closes.
- Rollup normally bundles one private React/ReactDOM runtime. The separately
built compressed Excalidraw artifact externalizes React and is evaluated
once against exactly that runtime.
- `PackageManager` owns one shared `Packages` instance and typed host-adapter
registrations. View leases retain the actual acquisition window only for
lifecycle/persistence decisions and the temporary popout `ExcalidrawLib`
compatibility alias.
- Every root passes its view's stable `ownerDocument` into Excalidraw. The
shared runtime may therefore host concurrent, independent Apps in several
documents without a mutable current-window singleton.
- Window migration destroys the source React root synchronously before its
window can be torn down, then creates a destination-document root while
transferring drawing-owned state.
An extracted component must preserve that binding. A normal module-level
`import React from "react"` followed by global `ReactDOM.createRoot()` is not a
safe replacement. JSX is possible, but only after proving that every emitted
element and hook call is bound to the view's package-managed React instance.
Module-level React imports are now the intended binding because there is one
private bundled runtime. Do not assign React/ReactDOM to `window`, evaluate a
second copy for popouts, or confuse the shared JavaScript runtime with shared
DOM ownership. JSX remains possible only as a separate mechanical checkpoint.
## Architectural target
@@ -457,17 +691,18 @@ ExcalidrawPlugin (entry point and stable facade)
|
+--> explicitly ordered plugin managers/services
|
+--> PackageManager -- one Packages instance per Window
+--> PackageManager -- one shared Packages instance and host registrations
+ per-window compatibility-alias leases
|
v
ExcalidrawView (Obsidian TextFileView and stable facade)
|
+--> view-scoped controllers
|
+--> package-aware React root adapter
+--> shared-runtime React root with stable ownerDocument
|
v
Excalidraw and plugin React UI
document-owned Excalidraw App and plugin React UI
```
The target is not a strict line-count goal. It is successful when ownership is
@@ -704,7 +939,8 @@ Recommended order:
4. Implemented: `ViewExcalidrawExtensionRenderer` owns the plugin-specific
Excalidraw render slots for TTD, diagram-to-code, the welcome screen, custom
actions, and embeddables. The view retains its render delegates and supplies
all elements through its window-scoped React and Excalidraw packages.
all elements through the shared React/Excalidraw runtime while passing the
view's stable owner document.
5. `ViewSceneFileManager`: active/next/deferred embedded-file loaders and
deferred validation scheduling.
6. `MarkdownImageController`: deletion queue, edit handoff, conversion, and
@@ -719,23 +955,9 @@ that merely duplicates the monolith as an interface.
### Phase 7: extract the React root without changing rendering syntax
The first renderer extraction should be a mechanical move, not a state rewrite
or JSX conversion.
1. Define a narrow render-host contract containing runtime packages, refs,
callbacks, and render slots required by the root.
2. Move the body of `excalidrawRootElement()` to a component module.
3. Pass the `Packages` instance resolved for `view.ownerWindow` into that
component.
4. Inside the component, call hooks and `createElement()` from that package's
`react` object.
5. Continue creating the root with that package's `reactDOM.createRoot()`.
6. Keep API assignment, initialization callbacks, cleanup, and ref handoff
behavior identical.
7. Test main window, existing popout, moving a leaf to a popout, restored
workspace popout, and closing the last popout leaf.
A safe conceptual shape is:
The mechanical extraction is implemented. The runtime architecture changed
after the original plan: React/ReactDOM and Excalidraw are now shared rather
than evaluated per window. The resulting conceptual shape is:
```ts
const runtime = view.packages;
@@ -744,16 +966,20 @@ view.excalidrawRoot = runtime.reactDOM.createRoot(view.contentEl);
view.excalidrawRoot.render(runtime.react.createElement(Root));
```
The exact API can differ, but it must not fall back to a module-global React or
ReactDOM instance.
`runtime.react` and `runtime.reactDOM` are the plugin bundle's one private
module runtime, not window globals. Each invocation must still pass the view's
stable `ownerDocument`, and migration must unmount the source root before the
first await. If this parked phase is resumed, revalidate main, existing and
restored popouts, both migration directions, and closing the last popout leaf
before changing syntax or state ownership.
### Phase 8: convert the extracted root to TSX
Only after Phase 7 is stable should syntax change:
1. Rename the renderer to `.tsx` and convert a small render fragment at a time.
2. Ensure the configured classic JSX transform resolves `React.createElement`
to a lexically scoped, package-managed React object.
2. Ensure the configured JSX transform resolves to the plugin bundle's private
React runtime and does not introduce a second copy or a window global.
3. Use module-level React imports for types only where possible.
4. Do not combine JSX conversion with callback, prop, state, or menu changes.
5. Compare behavior and bundle size after each fragment conversion.
@@ -771,7 +997,7 @@ Introduce React state only where it eliminates imperative UI synchronization.
selected UI mode.
2. If multiple components need the snapshot, implement a tiny plain
TypeScript observable store owned by the view.
3. Subscribe with the package-managed React instance, potentially through
3. Subscribe with the shared private React instance, potentially through
`useSyncExternalStore()` after verifying availability in every loaded
runtime.
4. Migrate one existing imperative `ToolsPanel.setState()` pathway at a time.
@@ -904,6 +1130,96 @@ window modes, and distinguish automated validation from untested manual risk.
- Script engine startup, pinned scripts, and install-codeblock flow.
- ExcaliBrain or another companion integration if available.
## EA script lifecycle and autostart execution refactor — 2.27.0
The central invariant is: **compiled JavaScript may be shared; EA ownership
and script runtime semantics are not shared.** Low-level source loading and
compilation are consolidated without merging the four existing ownership
models.
| Trigger | `utils.executionSource` | EA ownership | Lifetime and behavior |
| --- | --- | --- | --- |
| Toolbar, command, hotkey, or other ordinary invocation | `manual` | fresh view EA | repeatable without limit; may re-enter and redirect existing script-owned UI |
| Configured plugin Startup Script | `plugin-startup` | plugin-global EA | once per plugin load; external resources can be released at plugin teardown |
| `ea.registerAutostart()` attachment | `view-autostart` | fresh view-local EA | one successful automatic attachment per script path and view; manual runs bypass attachment deduplication |
| Persisted sidepanel reconstruction | `sidepanel-restore` | sidepanel host EA | restored lazily with the sidepanel; host lives with its tab |
| Explicit backing-script reload | `sidepanel-reload` | replacement sidepanel host EA | previous tab/host is destroyed before re-execution |
| `excalidraw-onload-script` | `drawing-onload` | view-local EA | drawing-specific source and established view-load timing |
`ScriptEngine` caches a promise for the compiled `AsyncFunction` of each
unchanged script file, keyed by full vault path. It checks `mtime` and size,
invalidates on modify, rename, delete, script-folder changes and ScriptEngine
teardown, and removes rejected promises so a corrected script can compile on
the next request. Concurrent requests share compilation, then execute the
result independently with their own EA and utilities. Raw drawing-onload code
remains uncached because it is embedded source rather than the contents of its
associated drawing `TFile`.
The view-open and fresh-permission paths share one automatic-attachment
coordinator. It stores its promise before awaiting execution, keeps successful
entries for that `ExcalidrawView`, and removes failed entries for retry. It is
never consulted by `manual` execution. Existing autostart permissions,
failure-state reporting, per-view element-action providers, and duplicate
provider-ID protection remain unchanged.
Every `ExcalidrawAutomate` instance now provides
`registerCleanup(cleanup: () => void): () => void`. Remaining callbacks run
synchronously in reverse registration order with error isolation when that EA
is destroyed; the returned function only unregisters its callback. EA destroy
is idempotent. The cleanup lifetime follows the owning EA: plugin-global,
view-local/drawing-local, or sidepanel-host.
No `runOnce` or scope parameter was added to `registerAutostart()`. No global
mutable EA is reused across view attachments, no script runtime/closure is
cached, and persistent-sidepanel policy remains separate from view autostart.
A managed `EAScript` abstraction is explicitly deferred: scripts such as
Mindmap Builder demonstrate a possible future need, but `onLoad`, `onInvoke`,
`onViewOpen`, `onViewClose`, `onUnload`, and their EA ownership must be designed
as one complete contract before introducing such a class.
### Multi-repository script-contract synchronization
The coordinated working trees now expose the same lifecycle contract:
- **`ea-script-template`:** its ambient `ScriptExecutionSource` union uses the
six values above, `ExcalidrawAutomate` exposes `registerCleanup()`, and the
README, authoring guide, agent guidance, and generated `.ai` snapshot explain
lifecycle ownership and unrestricted manual invocation.
- **`ea-scripts`:** its ambient utilities and EA surface match the same
contract, its guidance and generated snapshot are synchronized, and the
Slideshow test fixture uses `view-autostart`. Slideshow behavior remains
unchanged because its runner intentionally branches only on
`executionSource !== "manual"`; Mindmap Builder was not modified.
- **Cross-check:** repository searches found no stale literal `"autostart"`
execution-source value in maintained source/reference files. Continue using
each repository's `sync-refs` command after future generated API changes, and
do not introduce a managed script runtime without designing its complete
ownership contract.
### Risk-based acceptance gate
1. Confirm `registerCleanup()` releases a startup-script listener/timer across
repeated plugin disable/re-enable and releases a view-autostart resource
when its drawing closes and reopens.
2. Restore several views with several allowed scripts, then edit both a `.md`
and enabled `.js` script and invoke/open again. Each view must execute with
an independent EA, unchanged source should compile once, and edits must be
visible without restarting Obsidian.
3. Grant permission while a view is initializing; the same script must attach
automatically only once to that view. A failing attachment must not block
other scripts and must be retryable after correction.
4. Use Slideshow as the mixed-lifecycle canary: view autostart registers
**Edit slideshow** without starting a presentation, repeated manual runs
still start/advance it, and its non-persistent sidepanel follows the right
main/popout view.
5. Use Mindmap Builder unchanged: repeated manual invocation must execute its
discovery branch, reuse the persistent tab/host EA, redirect it to the new
view, preserve event rebinding, and survive sidepanel/view migration.
6. Confirm persisted sidepanel reconstruction reports `sidepanel-restore`,
explicit backing-script reload reports `sidepanel-reload`, drawing
frontmatter receives `drawing-onload`, and ordinary invocations receive
`manual`.
## Per-change review checklist
Before merging any refactor step, answer all of the following:
@@ -1011,162 +1327,202 @@ to resume.
sequence of checkpoints rather than a promise to execute every proposed
module unchanged.
## Related, separate effort: settings.ts declarative-shape adoption
## Active effort: declarative settings migration
Started 2026-08-13, independent of the `ExcalidrawView`/`main.ts` plan above
(different file, different motivation — not part of the parked plan, not
blocked by it, and not blocking it). Tracked here because it's the other
active refactor in the codebase and future sessions should know it exists.
Started 2026-08-13 and promoted to the active refactor on 2026-08-21. This
effort is independent of the parked `ExcalidrawView`/`main.ts` plan above.
**Goal:** prepare for Obsidian's declarative settings API
(`getSettingDefinitions()`, requires Obsidian 1.13+) without bumping
`minAppVersion` past 1.8.7 yet, by modeling settings as data
(`SettingDefinition` objects with a `control` variant) that the *current*
`display()` interprets via a new `buildSetting()` method, rather than each
setting being hand-built with `new Setting(...).addToggle(...)` etc.
`render`/`visible` (for Obsidian's real API) are deliberately not
implemented yet — only the legacy-rendering interpreter exists so far.
### Objective and fixed compatibility decisions
**Sequence so far:** extracted `ExcalidrawSettings`/`DEFAULT_SETTINGS`/AI
config constants to `src/core/settingsDefaults.ts`; split
`ExcalidrawSettingTab.display()` into 14 per-section methods (pure code
motion, verified via reconstruction diff); added the `SettingDefinition`
type system and `buildSetting()` interpreter, piloted against one or two
settings per control type (toggle/text/dropdown/slider) before doing a
full pass; converted all plain toggles, then extended `ToggleControl` with
`before`/`after`/`afterUpdate` hooks (matching every side-effect ordering
found: before assignment, between assignment and `applySettingsUpdate()`,
after `applySettingsUpdate()`) and `negate` (for two inverted-boolean
settings), and made `buildSetting()` return the underlying `Setting` so
callers that need to keep manipulating it afterward (e.g.
`.nameEl.setAttribute(...)`, later show/hide) can capture it. Toggle
control type is fully closed out. Text control type is also now fully
closed out: extended `TextControl` with the same `before`/`after`/
`afterUpdate` hooks, a `vaultPath` hook that wires the text input into the
existing `addVaultPathSupport()` (path suggester + existence warning), and
a `capture` hook (called with the raw `TextComponent` before
placeholder/value/onChange are wired) for callers that need to keep
manipulating the component afterward (a sibling toggle disabling it,
`configurePasswordTextInput()`). Dropdown control type is also now fully
closed out: extended `DropdownControl` with the same `before`/`after`/
`afterUpdate` hooks, and added a new `NumberDropdownControl` variant for
dropdowns whose options are numbers stored as DOM strings but bind to a
numeric field (autosave intervals, PDF-export scale, custom-pen count) —
`parse: "int" | "float"` controls the `parseInt`/`parseFloat` conversion
back into the setting. Slider control type is also now fully closed out:
extended `SliderControl` with `after`/`afterUpdate` hooks (no `before` —
no existing slider needed one). Widened `SliderSetting.onChange` in
`sliderUtils.ts` from `(value: number) => void` to `(value: number) =>
void | Promise<void>` since the hooks can be async, and `createSliderWithText`'s
internal caller now awaits it (`no-misused-promises`/`no-floating-promises`
caught both sides of this at lint time — a real, correctly-caught gap, not
a false positive). All four control types are now fully converted.
Migrate `ExcalidrawSettingTab` to Obsidian's declarative settings API while
retaining the imperative `display()` path for compatibility:
**Deliberately left as legacy imperative code (toggle type), each because
it doesn't fit the current `control` shape cleanly:**
- Keep both `package.json`'s Obsidian dependency and `manifest.json`'s
`minAppVersion` at `1.8.7`. Do not create a misleading type/runtime gap by
bumping only the development dependency.
- Follow Obsidian's Path B dual-support model. On Obsidian 1.13+, a non-empty
`getSettingDefinitions()` activates declarative rendering and bypasses
`display()`; returning an empty array retains the legacy path.
- An Obsidian 1.8.7 test installation is not available. Validate the legacy
path on the available 1.13.x installation by temporarily returning `[]`
from `getSettingDefinitions()`. This is a local test-only edit and must be
reverted before committing a declarative checkpoint.
- Add a documented local type compatibility layer for only the Obsidian
1.13.0 definition/method subset the plugin uses. Do not import runtime
classes that are absent from 1.8.7, and do not use API additions introduced
after 1.13.0 without an explicit compatibility decision.
- Keep one canonical source of setting definitions. The legacy renderer and
the declarative adapter must consume the same specifications so Path B does
not become two manually synchronized settings implementations.
- Preserve current observable behavior, setting keys, persistence, migrations,
side-effect ordering, localization, and mobile support.
- `AI_ENABLED_NAME` (`aiEnabled`) — reads with a `?? true` defensive
fallback for legacy persisted data; `ToggleControl` has no way to express
a read-time default.
- `GRID_DIRECTION_NAME` — two `.addToggle()` calls chained onto one
`Setting` row (horizontal/vertical), bound to a nested,
migration-guarded field (`gridSettings.GRID_DIRECTION?.horizontal ??
true` with an inline "2.10.1 migration" backfill). `SettingDefinition`
assumes one control per row and a flat top-level key.
- `GRID_DYNAMIC_COLOR_NAME` (`gridSettings.DYNAMIC_COLOR`) — nested field,
not a flat `BooleanSettingKey`.
- `EXPORT_SVG_NAME` / `EXPORT_PNG_NAME` (`autoexportSVG`/`autoexportPNG`)
— each toggle mutates a *different* setting's dropdown options
(add/remove an "SVG"/"PNG" choice from the embed-type dropdown). A
genuine cross-control relationship, structurally the same category as
the deferred `visible` mechanism.
- The dynamic per-installed-script toggle in the Compatibility section —
not a real named setting at all (`variableName`/`getValue`/`setValue`
are runtime-generated per script), inherently `render`-only content once
that control type exists.
### Current implementation baseline
**Deliberately left as legacy imperative code (text type), each because it
doesn't fit the current `control` shape cleanly:**
The preparatory work already completed is substantial:
- `PAGE_TRANSCLUSION_CHARCOUNT_NAME`, `TRANSCLUSION_DEFAULT_WRAP_NAME`,
`MD_TRANSCLUDE_WIDTH_NAME`, `MD_TRANSCLUDE_HEIGHT_NAME` — numeric text
inputs with `parseInt`/`NaN` validation, an early return that leaves the
input unchanged (and unpersisted) on invalid input, and a different
fallback default per field on an empty string. A genuinely different
control shape (validated numeric text) than `TextControl`/`sanitize`
(a pure string-to-string transform) models; not worth a new control type
for 4 settings.
- The AI section's `addNumberSetting` closure — takes arbitrary
getter/setter functions rather than a fixed `ExcalidrawSettings` key,
used for token-limit fields with custom validation; structurally
incompatible with `TextControl.key: StringSettingKey`.
- `STARTUP_SCRIPT_NAME` — one `Setting` row chains both `.addText()` and
`.addButton()` (path input + an "Open"/"Create" button whose label the
text input's `onChange` updates). Same category as `GRID_DIRECTION_NAME`
above: `SettingDefinition` assumes one control per row, and this row has
a real cross-control dependency within itself.
- The two dynamic per-installed-script text closures (`addStringSetting`'s
array/plain branches) in Compatibility — same reasoning as the dynamic
script toggle above.
- `ExcalidrawSettings`, `DEFAULT_SETTINGS`, and AI configuration constants are
in `src/core/settingsDefaults.ts`.
- `display()` is split into 14 section methods.
- 125 fixed rows use the local `buildSetting()` interpreter.
- The local model covers toggle, text, dropdown, numeric-dropdown, and slider
controls, including existing before/after/afterUpdate hooks, inverted
booleans, sanitization, scaling, vault-path support, component capture, and
drawing-reload flags.
- 29 direct `new Setting()` sites remain outside `buildSetting()` (some create
a dynamic number of rows), plus custom components and three nested legacy
slider calls.
- `getSettingDefinitions()` still returns an empty array, so no released path
is declarative yet.
**Deliberately left as legacy imperative code (dropdown type), each because
it doesn't fit the current `control` shape cleanly:**
The local definition dialect is intentionally not returned directly to
Obsidian. Official controls have different option shapes and do not understand
the plugin's hook, scaling, sanitization, capture, or numeric-dropdown fields.
- `LIBRARY_STORAGE_NAME` — its `onChange` early-returns on no-op selection,
branches into async migration prompts, and in one branch assigns a fixed
`"vault"` rather than the selected value; ends with a full `this.display()`
re-render (one of only two such calls in the whole file). Doesn't fit the
"always assign the selected value" model at all.
- The AI provider/model dropdown (inside the dynamic `renderAISettings`
closure) — options are built from a runtime list, and the row also
chains `.addExtraButton()`; same dynamic/multi-control reasoning as the
AI text-model closures already excluded from toggle/text.
- `EMBED_TYPE_NAME` — this is the dropdown `EXPORT_SVG_NAME`/
`EXPORT_PNG_NAME` (excluded from the toggle pass) mutate: its own options
are conditionally built from `autoexportPNG`/`autoexportSVG`, it
self-corrects `embedType` back to `"excalidraw"` if the previously
selected option becomes unavailable, and its `onChange` shows/hides
`embedComment`'s row. A cross-control cluster, not a single setting.
- The dynamic per-installed-script dropdown closure in Compatibility —
same reasoning as the other dynamic script content.
### Non-negotiable persistence boundary
**Deliberately left as legacy imperative code (slider type), each because
it doesn't fit the current `control` shape cleanly:**
Obsidian's default declarative control path writes `this.plugin.settings` and
calls `saveData()` automatically. That default must not be used here because it
would bypass:
- `GRID_OPACITY_NAME` (`gridSettings.OPACITY`), `LASER_DECAY_TIME_NAME`
(`laserSettings.DECAY_TIME`), `LASER_DECAY_LENGTH_NAME`
(`laserSettings.DECAY_LENGTH`) — nested fields, not a flat
`NumberSettingKey`. Same reasoning as `GRID_DYNAMIC_COLOR_NAME` from the
toggle pass.
- `normalizeSettingsBeforeSave()`;
- the serialized `settingsPersistenceChain`;
- pending pen, dynamic-style, drawing-reload, and embed-update actions;
- `PluginSettingsManager.saveSettings()` and API-key obfuscation.
**All four control types (toggle/text/dropdown/slider) are now fully
converted.** What remains before this data structure could feed Obsidian's
real `getSettingDefinitions()`:
`ExcalidrawSettingTab` must override `getControlValue()` and
`setControlValue()`. A typed binding registry will read/write flat, nested, and
derived values; preserve negate/parse/scale/sanitize behavior; run the existing
hooks in their current order; and route persistence through
`applySettingsUpdate()`/`plugin.saveSettings()`. The bridge must also expose an
awaitable completion to the declarative host without silently reordering the
current before/after/afterUpdate semantics.
1. **`render` support in `buildSetting()`** — every exception listed across
the four sections above (roughly 20 settings) is a `render` candidate:
custom components (`HotkeyEditor`, `FontPickerComponent`,
`VaultPathSuggest`-only cases, `PDFExportSettingsComponent`,
`ModifierKeySettingsComponent`, `UIModeSettingsComponent`), multi-control
rows (`GRID_DIRECTION_NAME`, `STARTUP_SCRIPT_NAME`), nested/nonflat
fields (`gridSettings`/`laserSettings` members), cross-control clusters
(`EMBED_TYPE_NAME` + the SVG/PNG export toggles, `TASKBONE_ENABLE_NAME`'s
captured text component), branching/early-return logic
(`LIBRARY_STORAGE_NAME`), and the fully dynamic AI provider/model and
per-installed-script content.
2. **The `visible`/`registerVisibilityGate`/`refreshVisibilityGates`
mechanism** (designed but never implemented — see the investigation
findings near the top of this section) for the 6 existing show/hide
relationships, most of which are now `control` entries reaching into a
still-legacy sibling (`embedComment`, `aiEl`, `gridColorSection`).
3. Only after both of those does actually wiring up
`getSettingDefinitions()` (behind Path B — keep `display()` for pre-1.13
users) become the natural next step, and only once `minAppVersion` is a
decision the user is ready to make.
### Dependency and component strategy
Each remains its own small, separately-committed step per the same
full-type-closeout-before-commit, review-before-commit discipline used for
all four control types above.
Do not turn every cross-linked setting into one opaque custom row. Prefer a
component or factory that returns a declarative group containing separately
indexed child definitions. Use a single imperative `render` item only where
the children genuinely cannot be described independently.
- Use `visible` for AI content, the embed-comment row, and the fixed grid-color
row. Declarative controls refresh these predicates automatically; imperative
callbacks call `refreshDomState()`.
- Use `disabled` for the library path/file rows, TODO/done prefix inputs, and
the Taskbone API-key input.
- Use `update()` only when the definition structure or options change, such as
the library migration action, autoexport-dependent embed-type options,
provider/model collections, or dynamic script settings.
- Replace declarative-path calls to `display()` with a compatibility refresh
helper: `update()` for declarative definitions and `display()` for the legacy
test/fallback path.
- Put `aliases` on searchable child definitions. Groups and pages do not carry
aliases themselves. An opaque rendered component must list all relevant
search terms on its containing definition.
- Keep multi-control or behavior-heavy rows imperative where needed, including
grid direction, startup script, custom vault-path creation/validation,
password behavior, and numeric inputs whose blank/invalid semantics do not
exactly match Obsidian's native number control.
- Declarative `render` callbacks own teardown. Hotkey editors must unload and
font pickers must destroy themselves when a row/page is rebuilt, navigated
away from, or closed; tab-level `hide()` must tolerate either rendering path.
### Top help, navigation, and promotional surface
The migration must not silently remove or degrade the non-setting features at
the top of the current tab:
- the local settings search and settings-to-Markdown clipboard export;
- the NotebookLM self-help database link;
- the Excalidraw Mastery expandable help/promotion;
- coffee, issue tracker, wiki, YouTube, community, social, and book links.
Native Obsidian search replaces only part of `ContentSearcher`; it does not
replace clipboard export or these help surfaces. The normal, unfiltered
Excalidraw settings view must retain them. Before declarative cutover, perform a
dedicated UX checkpoint to determine how they behave while a global setting
search is active:
1. first investigate whether declarative settings exposes a supported
persistent/header surface during filtered results;
2. if not, compare a compact help/promotion result with carefully chosen
aliases against showing links only in the normal tab;
3. reject a solution that repeats a large promotional block for every matched
setting or crowds out the setting the user searched for;
4. retain clipboard export through either a declarative action backed by the
canonical specifications or a deliberately rendered utility component.
No help, self-service, navigation, promotion, or export feature is approved for
removal as part of this refactor.
### Checkpoint tracking
| Checkpoint | Status | Scope and completion condition |
| --- | --- | --- |
| 1. Record the approved migration plan | Complete | Compatibility decisions, architecture, persistence boundary, component strategy, top content requirements, batches, validation, and commit protocol are recorded here |
| 2. Add Obsidian 1.13 compatibility types | Complete | Added the minimal documented 1.13.0 structural type shim and capability-checked runtime-method facade without changing dependencies, manifests, declarative activation, or runtime behavior |
| 3. Establish canonical specifications and dual adapters | Complete | Extracted the local definition model and legacy interpreter, added declarative conversion plus typed get/set binding and persistence routing, and kept `getSettingDefinitions()` explicitly empty until full coverage is ready |
| 4A. Convert shell, help/promotion, General, and Saving | Complete | Added the staged declarative shell, separately indexed General/Saving controls, custom library storage/migration rows, filename preview, full top help/promotion/link surface, and shared canonical specs. Four manual revisions corrected custom-row layout, mount ownership, filename initialization, duplicate keys, flat groups, recursive Markdown export, descriptions, toolbar placement, the remaining structural fork through one shared page model, duplicate legacy descriptions, and legacy separator placement. The hard-coded activation constant was replaced by `useDeclarativeSettings`, a default-enabled persisted top-level toggle shown only on Obsidian 1.13+. The setting tab snapshots that choice when it is constructed, so changing it persists immediately but intentionally takes effect only after restarting Obsidian. Older versions remain on legacy without showing the toggle. Both modes retain the same hierarchy and compact toolbar; legacy nested and sub-nested sections render a separator immediately before their description and fold. Declarative Markdown bullets use `- **Title:** (type) Description`. Final duplication/dead-code review and automated validation passed; checkpoint 4A is ready for its commit |
| 4B. Convert Display and Links/transclusions | Complete | Migrated display modes, theme/zoom, grid/laser, three-level modifier navigation, link behavior, TODO dependencies, and validated transclusion inputs through the shared declarative/legacy page model. Manual validation drove shared fixes for full-width components, initial dependent-control state, and live viewport preservation during settings reloads. Final duplication/dead-code review and automated validation passed; committed as one independently testable batch |
| 4C. Convert Embed/export, Embedding, and nonstandard features | Complete | Migrated image cache actions, embed/autoexport dependency cluster, PDF/export custom UI, Markdown embeds, and custom pens through the shared declarative/legacy page model. Manual validation drove window-scoped font previews, guarded breadcrumbs, reciprocal navigation, and generic internal cross-reference routing. Final duplication/dead-code review and automated validation passed |
| 4D. Convert Fonts, Experimental, Excalidraw Automate, and Compatibility | Complete | Migrated local/CJK fonts, miscellaneous features and Taskbone, Excalidraw Automate startup/autostart controls, conditionally visible installed-script settings, and Compatibility through the shared page model. Removed the superseded legacy renderers; final validation corrected Taskbone's initial search state, compacted the page header, converted the startup action to an icon, and enabled legacy folded-section cross-link navigation |
| 4E. Convert AI | Complete | Migrated AI enablement, session usage, verbose logging, provider/model management, and token-limit inputs. The independent controls have individual search/Markdown declarations; the provider/profile/model cluster remains one integrated component shared with legacy because its add/edit/delete/restore operations update each other's references. Manual testing confirmed the AI settings, live installed-script refresh, and revised legacy cross-links |
| 5. Finalize declarative layout and search UX | Complete with checkpoint 6 | Retained the validated hierarchy, audited all shipped locales for unique sibling paths, completed Russian page metadata, confirmed aliases for integrated components, and kept utility/promotion definitions out of filtered search results. Manual validation confirmed both ordinary and integrated search results and deep breadcrumb navigation |
| 6. Activate Path B declarative rendering | Complete with checkpoint 5 | The complete tree is returned on Obsidian 1.13+ when `useDeclarativeSettings` is enabled. The persisted default-enabled preference remains supported so users and maintainers can select the legacy single-page renderer after restart; older versions always receive the empty-array fallback. Manual validation confirmed restart switching in both directions |
| 7. Remove transitional DOM coupling | Complete | Scoped dependent-control references to one generated settings tree, removed obsolete caches/methods/types and checkpoint naming, prevented Markdown export from replacing live bindings, reviewed the full branch against `master`, and recorded exact bundle attribution. The legacy compatibility preference remains intentionally supported |
Batch boundaries may be adjusted before implementation if call-site tracing
shows a stronger dependency boundary, but a batch must remain independently
buildable, manually testable, and reversible. Do not combine unrelated cleanup
or naming changes with a migration batch.
### Mandatory checkpoint workflow
Checkpoint 1, checkpoints 2-3 and 5-7, and every individual checkpoint-4 batch
follow the same completion gate:
1. implement only the recorded scope;
2. update the progress row and append an action-log entry in this document;
3. run `npm run build` and relevant targeted diagnostics; run `npm run lib` only
if the public/library surface is touched;
4. run the applicable manual Obsidian validation before committing;
5. list the highest-risk regressions and the best concrete test scenarios for
user validation, including whether main-window, popout, desktop, and mobile
need distinct coverage;
6. commit the independently validated checkpoint before starting the next one.
For implementation checkpoints, test both modes where applicable: the normal
declarative return and a temporary local `return []` legacy fallback. Revert
the test-only empty-array edit before reviewing and committing the checkpoint.
### Persistent high-risk validation matrix
- **Persistence and secrets:** change an unrelated setting while AI and
Taskbone credentials exist, then confirm persisted values remain obfuscated;
also test rapid consecutive edits and queued saves.
- **Early lifecycle/indexing:** `getSettingDefinitions()` runs when the tab is
registered, before layout-ready managers such as the stencil-library manager
and script engine exist. Definition generation must stay cheap and must not
touch those managers; defer such work to `render` or guarded update paths.
- **Cross-setting behavior:** test AI visibility, library field enablement and
migration prompts, TODO/done enablement, grid dynamic color, Taskbone
enablement/initialization, embed-comment visibility, and autoexport option
addition/removal with selected-value fallback.
- **Search and navigation:** test names and aliases, hidden-item exclusion,
nested page navigation, maintained-locales, duplicate localized sibling page
names, and the top help/promotion experience during normal and filtered use.
- **Custom UI cleanup:** close/navigate/update while hotkey capture, a font
picker menu, dynamic AI UI, or a custom component is active; test plugin
reload and settings-modal close.
- **View side effects:** change reload/embed/style settings while drawings are
open in both the main window and a popout; cover desktop and mobile when
layout or multi-control rows differ.
- **Legacy fallback:** temporarily return `[]` on 1.13.x and walk the same
changed batch through imperative `display()`; this is the available proxy
for an Obsidian 1.8.7 installation.
- **Structural completeness:** before checkpoint 6, inventory every current
setting, custom component, action, YouTube thumbnail, help/promotion item,
and utility so a non-empty array cannot make an unconverted feature vanish.
## Related, separate effort: no-unsafe-* lint cleanup — parked 2026-08-13
@@ -1582,8 +1938,8 @@ changes elsewhere, including `getViewColorPalette()` since its logic itself
was already confirmed correct and unchanged.
**Done (2026-08-14, session 4): `ExcalidrawAutomate.ts` fully triaged, 57 → 0.**
On `master` (the `excalidraw-type-import-fix` PR was merged as #2892 in the
interim; `master` is now at `2.27.0-beta.2`). Same methodology, three
On `master` after the `excalidraw-type-import-fix` was merged (now at
`2.27.0-beta.2`). Same methodology, three
clusters:
1. **Safe, fixed (49 of 57).** `cloneElement()`/`cloneElements()`'s inner
@@ -1802,7 +2158,7 @@ action reusing the same rendering component (matching how
| --- | --- | --- |
| 1. Type move | Complete | Moved `SelectedElementMenuAction`/`SelectedElementMenuProvider` from `SelectedElementActionsMenu.ts` to new `src/types/elementActionTypes.ts`. Pure mechanical move, no other file referenced the old location yet, so no compatibility re-export was needed. |
| 2. `registerElementActionProvider` | Implemented; user-tested, two fixes applied | Added the public method on `ExcalidrawAutomate` (delegates to the existing `view.selectedElementActionsMenu.registerProvider()`, id defaults to `this.activeScript ?? nanoid()`, matching `createSidepanelTab`'s precedent). Added `ScriptEngine.trackElementActionProvider()`/cleanup in `unloadScript()` (`src/shared/Scripts.ts`) for the one gap the existing mechanism didn't already cover: a script's file being deleted while a view using its registered action is still open (ordinary view-close cleanup was already handled by `SelectedElementActionsMenu.destroy()`). Added the `SuggesterInfo.ts` entry and a `## New` bullet in `Messages.ts` under `2.27.0` per the ExcalidrawAutomate Change Checklist. No new locale keys needed — this API produces no plugin-authored user-visible strings (button text/icon come from the registering script). User tested registering multiple menus and clearing them independently — both worked. Fix 1: `registerProvider()` primes the menu to recompute on its *next* `update()` call (by resetting `selectedElementId`), but nothing was triggering `update()` immediately — if an eligible element was already selected when a script registered (e.g. run via command palette), the button didn't appear until the user deselected and reselected. Fixed by having `registerElementActionProvider()` immediately call `selectedElementActionsMenu.update(view.getViewElements(), appState)` right after registering, mirroring the exact call `ExcalidrawRoot.ts`'s mount effect already makes at view-open time. Fix 2 (found later, during step 3/4 testing): running the same script a second time in the same view registered a second provider under the same id, producing a duplicate button, since `SelectedElementActionsMenu`'s `providers` array had no id-uniqueness enforcement. Fixed via new `SelectedElementActionsMenu.hasProvider(id)` + a guard in `registerElementActionProvider()` that logs via `errorMessage()` and returns `null` instead of double-registering. |
| 3. Autostart data + prompt flow | Implemented; pending user testing | Added `autostartScripts: { [scriptName: string]: "allow" \| "deny" \| "unknown" }` (default `{}`) to `ExcalidrawSettings`/`DEFAULT_SETTINGS` (`src/core/settingsDefaults.ts`) — deliberately a sibling of `scriptEngineSettings`, not reused, since this is plugin/user-trusted permission state a script must not silently flip. Added `ExcalidrawAutomate.registerAutostart(): Promise<"allow"\|"deny"\|"pending">` reusing the existing `MultiOptionConfirmationPrompt<T>` (`src/shared/Dialogs/Prompt.ts`, same class `MarkdownImageController.ts` already uses for its keep/delete prompt): no active script → `errorMessage()` + `"pending"`; missing entry → created as `"unknown"` and persisted immediately (visible in the future management UI right after the first run, before any button is clicked); `"allow"`/`"deny"` short-circuit with no prompt; `"unknown"` (including a dismissed-without-choosing prompt, which the class resolves as `null`) shows the Allow/Deny/Ask-me-later prompt, persists Allow/Deny, and leaves `"unknown"`+returns `"pending"` for Ask-me-later or dismissal. Added `SuggesterInfo.ts` entry, a `## New` bullet in `Messages.ts` under `2.27.0`, and new locale keys (`AUTOSTART_SCRIPT_PROMPT`/`_ALLOW`/`_DENY`/`_ASK_LATER`) in `en.ts` + `ru`/`es`/`zh-cn`/`zh-tw` — this step's prompt text and button labels are genuinely new plugin-authored user-visible strings, unlike step 2. Two scope additions made after initial user testing, both confirmed via `AskUserQuestion` before implementing: (a) a fresh "allow" now also immediately re-runs the script in every other currently-open Excalidraw view via new `ScriptEngine.attachAutostartScriptToOpenViews()` (enumerates `getExcalidrawViews(app, true)`, reuses `executeScript()` per view, per-view try/catch so one failure doesn't affect others) — otherwise approval only ever affected views opened afterward; (b) deleting or renaming a script's file now purges its `autostartScripts` entry via new `ScriptEngine.purgeAutostartPermission()`, called from the existing `deleteEventHandler`/`renameEventHandler` (not from `unloadScript()` itself, since that method is also called for non-identity-changing cases like a script-folder-path change or plugin unload, where purging would be wrong) — a renamed script now starts fresh under its new name instead of leaving a stale orphaned entry under the old one forever. No autostart-on-view-open execution/UI wiring yet (steps 4-5). |
| 3. Autostart data + prompt flow | Implemented; pending user testing | Added `autostartScripts: { [scriptName: string]: "allow" \| "deny" \| "unknown" }` (default `{}`) to `ExcalidrawSettings`/`DEFAULT_SETTINGS` (`src/core/settingsDefaults.ts`) — deliberately a sibling of `scriptEngineSettings`, not reused, since this is plugin/user-trusted permission state a script must not silently flip. Added `ExcalidrawAutomate.registerAutostart(message?: string): Promise<"allow"\|"deny"\|"pending">` reusing the existing `MultiOptionConfirmationPrompt<T>` (`src/shared/Dialogs/Prompt.ts`, same class `MarkdownImageController.ts` already uses for its keep/delete prompt): no active script → `errorMessage()` + `"pending"`; missing entry → created as `"unknown"` and persisted immediately (visible in the future management UI right after the first run, before any button is clicked); `"allow"`/`"deny"` short-circuit with no prompt; `"unknown"` (including a dismissed-without-choosing prompt, which the class resolves as `null`) shows the Allow/Deny/Ask-me-later prompt, persists Allow/Deny, and leaves `"unknown"`+returns `"pending"` for Ask-me-later or dismissal. The optional message is rendered as the second prompt paragraph between the permission question and the management hint. Added `SuggesterInfo.ts` entry, a `## New` bullet in `Messages.ts` under `2.27.0`, and new locale keys (`AUTOSTART_SCRIPT_PROMPT`/`_ALLOW`/`_DENY`/`_ASK_LATER`) in `en.ts` + `ru`/`es`/`zh-cn`/`zh-tw` — this step's prompt text and button labels are genuinely new plugin-authored user-visible strings, unlike step 2. Two scope additions made after initial user testing, both confirmed via `AskUserQuestion` before implementing: (a) a fresh "allow" now also immediately re-runs the script in every other currently-open Excalidraw view via new `ScriptEngine.attachAutostartScriptToOpenViews()` (enumerates `getExcalidrawViews(app, true)`, reuses `executeScript()` per view, per-view try/catch so one failure doesn't affect others) — otherwise approval only ever affected views opened afterward; (b) deleting or renaming a script's file now purges its `autostartScripts` entry via new `ScriptEngine.purgeAutostartPermission()`, called from the existing `deleteEventHandler`/`renameEventHandler` (not from `unloadScript()` itself, since that method is also called for non-identity-changing cases like a script-folder-path change or plugin unload, where purging would be wrong) — a renamed script now starts fresh under its new name instead of leaving a stale orphaned entry under the old one forever. No autostart-on-view-open execution/UI wiring yet (steps 4-5). |
| 4. Autostart execution | Implemented, user-tested, one addition applied | Added `ScriptEngine.runAutostartScripts(view: ExcalidrawView): void` (`src/shared/Scripts.ts`): reads `settings.autostartScripts`, filters `"allow"`, resolves each via the existing `getScriptFileByName()`, and runs it against the given view. Shares a new private `runAutostartScriptInView(scriptName, file, view, where)` helper with step 3's `attachAutostartScriptToOpenViews()` (read file → strip frontmatter → `executeScript()`, with its own try/catch so one bad script doesn't affect the others or block the view) — refactored out to avoid duplicating that logic between the two entry points. Wired into `ExcalidrawRoot.ts`'s mount effect with a single line, `view.plugin.scriptEngine.runAutostartScripts(view);`, placed right after the existing `selectedElementActionsMenu` setup/first `update()` call so registered element actions are ready before any autostart script runs against the new view. Fire-and-forget (not awaited), matching "keep startup light." Deliberately independent of the sidepanel autostart feature — different persisted field (`autostartScripts` vs `sidepanelTabs`), different trigger, different execution owner; `Sidepanel.ts` untouched. User confirmed manual testing passed. Addition from follow-up user feedback: `runAutostartScriptInView()` now records whether each autostart run succeeded or failed in a new sibling setting, `autostartScriptFailures: { [scriptName]: boolean }` (`settingsDefaults.ts`), via a new `recordAutostartResult(scriptName, failed)` helper — writes `settings` (and calls `saveSettings()`) only when the flag actually *changes* (clears on the first success after a failure, sets on the first failure after a success/never-run), not on every autostart run, to avoid a disk write every time an allow-listed script runs cleanly. Purely informational: never touches `autostartScripts` itself, so a failing script is never auto-removed from the allow list — surfacing the warning and any removal decision is left to the future settings/modal UI (step 5) and the user, respectively. `purgeAutostartPermission()` (rename/delete cleanup, from step 3) now also purges the failure flag alongside the permission entry. |
| 5. Autostart UI | Implemented; pending user testing (design revised four times before any testing occurred — see Action log) | Added `AutostartScriptsSettingsComponent` (`src/shared/Dialogs/AutostartScriptsSettingsComponent.ts`, new file): a plain class taking `(contentEl, plugin)`, matching the `EmbeddalbeMDFileCustomDataSettingsComponent` reuse pattern. `render()` renders as a bordered table (header row + one row per script), reusing the AI provider table's existing `.excalidraw-ai-provider-table`/`__header`/`__row` CSS as-is (no new `styles.css` rules), each script row a 3-option dropdown — Autostart / Manual start only / Ask every time (`allow`/`deny`/`unknown`) — writing straight to `autostartScripts[name]` + `saveSettings()`, reusing the exact same locale keys as the permission prompt's buttons so both surfaces speak one vocabulary. Shows a `var(--text-error)`-colored warning under any script whose `settings.autostartScriptFailures[name]` is set. Empty state (`AUTOSTART_SCRIPTS_EMPTY`) rendered as its own table row when no script has ever registered. Same file also has `AutostartScriptsModal extends Modal`, whose `onOpen()` mounts the component into `this.contentEl` (its own header row supplies the heading/description; the modal's native `titleEl` gets `AUTOSTART_SCRIPTS_HEAD` separately for the window chrome) and adds an explicit `PROMPT_BUTTON_CLOSE` button below it (in addition to Obsidian's built-in header close icon, per user request). Wired into Settings inside `renderExcalidrawAutomateSection()` (`src/core/settings.ts`), directly under the Startup script setting, in a child `createDiv()` of that section's own `<details>` — not its own foldable section. New command `view-autostart-scripts` (`src/core/managers/CommandManager.ts`), unconditional `callback` (not gated on an active Excalidraw view, since this manages global settings) opening `AutostartScriptsModal`. New locale keys `AUTOSTART_SCRIPTS_HEAD`/`_DESC`/`_EMPTY`/`AUTOSTART_SCRIPT_FAILED_WARNING` plus a new generic `PROMPT_BUTTON_CLOSE` in `en.ts` + `ru`/`es`/`zh-cn`/`zh-tw`; `AUTOSTART_SCRIPTS_HEAD` is reused as both the command name and the table/modal heading. No SuggesterInfo/Messages.ts entry needed — no new `ExcalidrawAutomate` API, and the command/settings-UI mention was already added to the `2.27.0` `## New` bullet back in step 3. This is UI/settings-only code (not part of the plugin's public API surface), so `npm run lib` was run as a matter of course but wasn't expected to be affected. |
@@ -1819,3 +2175,4 @@ action reusing the same rendering component (matching how
| 2026-08-14 | Two fixes from user manual testing of step 2/3: (a) running an already-registered script a second time in the same view created a duplicate action button; (b) the Allow/Deny/Ask-me-later prompt gave no hint of where to manage the decision afterward | Fixed both, no schema/settings changes | (a) Added `SelectedElementActionsMenu.hasProvider(id): boolean` (`src/view/components/menu/SelectedElementActionsMenu.ts`) and a check at the top of `ExcalidrawAutomate.registerElementActionProvider()`: if this script's id is already registered in the target view, it logs a message via the existing `errorMessage()` helper and returns `null` instead of pushing a second provider (previously `SelectedElementActionsMenu`'s `providers` array had no id-uniqueness enforcement, so re-running the same script produced two entries whose `getActions()` calls were both concatenated into the rendered button list). Updated the method's TSDoc and its `SuggesterInfo.ts` entry to document the new no-op-on-duplicate behavior. (b) Added `AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT` (new locale key, `en`/`ru`/`es`/`zh-cn`/`zh-tw`) and appended it to the prompt message in `registerAutostart()` as a muted, smaller-font second line pointing at the `view-autostart-scripts` command and the Settings → Compatibility → Autostart scripts section built in step 5 - only possible to write accurately once step 5's UI existed. | `npm run build`, `npm run lib`, `node --check dist/main.js` all passed; `tsc --noEmit` unchanged (526/526); ESLint on touched files plus full-repo run unchanged at the 470-problem baseline. Manual validation pending: run the same script twice in one view and confirm only one button appears (and a message is logged, not a thrown error); trigger the autostart prompt and confirm the hint line renders and reads correctly under both the Compatibility-section and command-palette-modal paths it references. |
| 2026-08-14 | Reverted step 5's remove-only trash button back to a dropdown, per user catching a design flaw before testing: a "Manual start only" (deny) decision was a dead end, since removing the entry only let a script re-decide by being *re-run*, with no way to flip it back to Autostart directly from Settings | Restored the dropdown in `AutostartScriptsSettingsComponent`, reworded all three option/button labels for clarity | The three `autostartScripts` values keep their internal names (`allow`/`deny`/`unknown`) but their *displayed* text changed everywhere at once, since the settings dropdown and the permission prompt's buttons share the same three locale keys (`AUTOSTART_SCRIPT_ALLOW`/`_DENY`/`_ASK_LATER`) - updating the strings fixed both surfaces' wording and their mutual ambiguity in one edit, and keeps them permanently in sync (one vocabulary, not two). New wording: "Allow"/"Deny"/"Ask me later" → "Autostart"/"Manual start only"/"Ask every time" (mirrored in `ru`/`es`/`zh-cn`/`zh-tw`). Dropped `AUTOSTART_SCRIPT_REMOVE` (tooltip for the now-removed trash button) and reworded `AUTOSTART_SCRIPTS_DESC` to no longer describe removal. `AutostartScriptsSettingsComponent.render()`'s row is back to `addDropdown()` (same code shape as the very first draft of this component, before the trash-button detour), writing straight to `autostartScripts[scriptName]` + `saveSettings()` - deliberately does *not* touch `autostartScriptFailures` on a dropdown change, since a permission change doesn't retroactively affect whether the last actual run failed. | `npm run build`, `npm run lib`, `node --check dist/main.js` all passed; `tsc --noEmit` unchanged (526/526); ESLint on touched files plus full-repo run unchanged at the 470-problem baseline. Manual validation pending: set a script to "Manual start only," confirm it's immediately switchable back to "Autostart" or "Ask every time" from both the Settings section and the command-palette modal without re-running the script; confirm the prompt dialog now shows the reworded button labels. |
| 2026-08-14 | Third step-5 revision, per user direction: relocate the Settings placement (out of its own top-level `<details>`/`Compatibility` area, into the ExcalidrawAutomate section, directly under the Startup script setting) and restyle as a bordered table instead of a foldable list | Moved and restyled, no behavior change to the underlying data/permission logic | Removed the standalone `<details>`/`<summary>` block this component used to sit in at the end of `renderCompatibilitySection()` (`src/core/settings.ts`); added a single `new AutostartScriptsSettingsComponent(detailsEl.createDiv(), this.plugin).render()` call at the end of `renderExcalidrawAutomateSection()`, right after the existing Startup script `Setting` block, inside that section's own (pre-existing) `<details>` - a *child* `createDiv()`, not the shared `detailsEl` itself, since the component's `render()` calls `.empty()` on its container and would otherwise wipe out the Startup script setting above it on every re-render. Restyled `AutostartScriptsSettingsComponent` to match the AI-provider table's exact look: a bordered, rounded, indented box with a header row (name=`AUTOSTART_SCRIPTS_HEAD`, desc=`AUTOSTART_SCRIPTS_DESC`) and one row per script below it. Initially implemented by *duplicating* `renderAISettings()`'s `.excalidraw-ai-provider-table` CSS (`styles.css:403-465`) under new `.excalidraw-autostart-scripts-table`/`__header`/`__row` class names, reasoning it would isolate the change from the AI section - user immediately (and correctly) pushed back: applying the AI table's *existing* classes to a second container changes nothing about the AI table itself, since no existing rule is edited, so the "isolation" bought nothing but 60-odd duplicate lines in `styles.css`. Reverted to reusing `.excalidraw-ai-provider-table`/`__header`/`__row` directly and deleted the duplicate block entirely - net effect on `styles.css` is now zero lines added. The empty state is its own `__row`-styled `Setting` (desc only, no name) rather than a plain paragraph, so it still renders inside the bordered box instead of looking detached from it. `AutostartScriptsModal` no longer duplicates the heading/description in its body (`this.contentEl.createDiv({text: AUTOSTART_SCRIPTS_DESC, ...})` removed) since the table's own header row already shows both - the modal's native `titleEl` still gets `AUTOSTART_SCRIPTS_HEAD` for the window chrome, which isn't visually duplicative of the in-body header. | `npm run build`, `npm run lib`, `node --check dist/main.js` all passed; `tsc --noEmit` unchanged (526/526); ESLint on touched files plus full-repo run unchanged at the 470-problem baseline; confirmed no `excalidraw-autostart-scripts-table*` class references remain anywhere (`styles.css`, `dist/styles.css`, or the component file) after the revert. Manual validation pending: open Settings → Excalidraw Automate, confirm the table appears directly under Startup script (not inside Compatibility, not foldable), confirm its bordered/indented look matches the AI provider table's, and confirm the command-palette modal still shows the same table plus its Close button. |
| 2026-08-30 | Extended `registerAutostart()` with an optional script explanation | `registerAutostart(message?)` renders the permission question, optional script explanation, and permission-management hint as three ordered paragraphs. Updated SuggesterInfo, 2.27.0 release notes, generated agent/API documentation, and template typings/guidance. | `npm run doc` (including `npm run lib`) passed; focused ESLint passed. Manual validation pending: reset a script to **Ask every time**, invoke it, and confirm its explanation is the second paragraph. |
+231
View File
@@ -0,0 +1,231 @@
# Excalidraw Automate scripting support plan
Status: active as of 2026-08-29.
This plan tracks the modernization of ExcalidrawAutomate AI support material while preserving compatibility with the long-lived training entrypoint.
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/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).
## Decisions captured
1. Unified generation command
- `npm run doc` is the single maintainer command for documentation generation.
- If a script-template repository is present in the current VS Code workspace, `npm run doc` should also refresh template-project references/artifacts.
2. Legacy entrypoint behavior
- The legacy training file remains the stable public entrypoint.
- 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
- `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.
- 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.
- Proposed name: `ea-script-template`.
- Once added to this workspace, the unified generator can optionally update it.
- Repository availability status: present and accessible at [../ea-script-template](../ea-script-template).
5. Image naming
- Adopt strict naming convention for script preview images, aligned to current patterns but enforceable.
6. Experimental script policy
- Scripts under [ea-scripts](ea-scripts) are treated as validated examples.
- No experimental bucket is introduced in this phase.
- Very large scripts (for example Mindmap Builder) are still valid; they should be tagged as "advanced/large-reference" rather than experimental.
7. Skill generation trigger
- Keep manual generation trigger. No automated regeneration in this phase.
## Progress tracking
Target branch: `improved-scripting-skills`.
| Phase | Status | Current outcome |
| --- | --- | --- |
| Baseline audit and constraints capture | Complete | Existing generators, outputs, and maintainer decisions captured in this plan |
| Create planning artifact in repository | Complete | Added [ScriptSupportPlan.md](ScriptSupportPlan.md) with phases, decisions, and action log |
| 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, 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 |
## Implementation checkpoints
### Checkpoint 1: Shared generator core and single command
Objective:
- Introduce a shared generator module and keep lightweight wrappers for backward command compatibility.
Planned changes:
- Consolidate duplicated logic currently split between:
- [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs)
- [scripts/skill-builder.mjs](scripts/skill-builder.mjs)
- Keep `npm run doc` as the single entrypoint command for maintainers.
- Keep manual run model. Do not add auto-run hooks in this phase.
Acceptance:
- One command (`npm run doc`) generates both legacy and skill outputs exactly once.
- Output files stay under [docs/AITrainingData](docs/AITrainingData).
### Checkpoint 2: Fix type-definition completeness regression
Objective:
- Ensure generated type references remain concrete after alias migrations.
Problem to solve:
- `lib/types/penTypes.d.ts` now aliases fork-owned types, and top import stripping can hide canonical shapes in generated docs.
Planned changes:
- Include canonical Obsidian type declarations from the fork type surface in generated reference outputs.
- Add a post-generation guard that fails if `ObsidianPenStrokeOptions` shape is missing.
Acceptance:
- Both:
- [docs/AITrainingData/Excalidraw Automate library and related type definitions.md](docs/AITrainingData/Excalidraw%20Automate%20library%20and%20related%20type%20definitions.md)
- [docs/AITrainingData/ExcalidrawAutomate full library for LLM training.md](docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md)
include concrete stroke option structure, not alias-only references.
Status:
- Complete.
- The generator now includes all declaration files under [src/types](src/types) and [lib/types](lib/types), plus the canonical fork-owned `obsidianTypes.d.ts` source for `ObsidianPenStrokeOptions`.
### Checkpoint 3: Curated legacy entrypoint messaging
Objective:
- Keep stable legacy entrypoint while steering agents to curated skill references.
Planned changes:
- Add a prominent warning that script generation can fail if linked references are not accessible.
- Include concrete note about environments requiring explicit URL enablement.
- Add short routing section pointing to curated skill/reference materials.
Acceptance:
- Legacy file remains backward compatible as an entrypoint.
- Warning is clear and placed before the main usage workflow.
Status:
- Complete.
- The generated legacy entrypoint now includes a top-level routing warning, the master repository URL, and direct absolute links to the curated skill and reference files.
### Checkpoint 4: Script publishing workflow guidance for agents
Objective:
- Teach agents to publish scripts through normal repository contribution workflow.
Planned changes:
- Add concise maintainer-approved workflow guidance in skill docs:
- add script to [ea-scripts](ea-scripts)
- add image to [images](images)
- 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
- Explicitly avoid automating `index-new.md`.
Acceptance:
- Publishing workflow appears in generated skill material.
- Guidance is PR-centric and does not suggest direct pushes.
Status:
- Complete.
- 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:
- Keep existing style while making naming consistent and enforceable.
Proposed naming rule:
- `scripts-{slug}.{ext}` where:
- `slug` = lowercase words joined by hyphen
- only `a-z`, `0-9`, `-`
- extensions allowed: `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.svg`
Examples:
- `scripts-add-link-to-existing-file-and-open.jpg`
- `scripts-boolean-operations-showcase.png`
Planned changes:
- Add validation in generator flow with clear error output.
- Keep compatibility mode for pre-existing files during initial rollout (warn-only first, strict fail in follow-up if desired).
Acceptance:
- New/updated script previews follow the naming contract.
- Validation output is actionable for contributors.
Status:
- Complete.
- The generator now warns on non-conforming preview filenames and surfaces the naming rule in the generated publishing workflow guidance.
### Checkpoint 6: Optional template repository sync
Objective:
- Allow `npm run doc` to refresh a co-located script-template repo if present.
Planned behavior:
- Detect a workspace folder named `ea-script-template` (or configurable path).
- If found, update agreed generated reference artifacts in that repo.
- If absent, continue without failure.
Current status:
- Repository now exists and is readable at [../ea-script-template](../ea-script-template).
- Checkpoint is considered unblocked and ready for scoped implementation once approved.
Design note: AI support files in template repo
- Preferred default: synchronized local snapshot under `.ai/excalidraw-automate/`, copied from canonical generated references in this repository.
- Routing note: keep canonical GitHub links in SKILL content, but ensure local references and script examples are present for environments without URL access.
- Reasoning: local snapshot gives immediate offline usability while preserving canonical source of truth in plugin-generated outputs.
Design note: template usage model
- Recommended model: single `ea-script-template` repository used as a multi-script workspace (one folder per script project) with shared utilities.
- Why: easier maintenance of common helpers, lint/build rules, and shared abstractions across scripts like Mindmap Builder, Slideshow, and Shade Master.
- Alternative supported pattern: per-script clones for strict isolation (useful for publishing independent repos), but this should be optional rather than the default path.
Acceptance:
- `npm run doc` succeeds in both cases:
- template repo present
- template repo absent
Status:
- Complete.
- `npm run doc` now refreshes a full local skill snapshot in the sibling `ea-script-template` workspace under `.ai/excalidraw-automate/` when the repo is available.
## Validation approach
For each implementation checkpoint:
- Run `npm run doc` from repository root.
- Verify generated files changed only in intended outputs.
- For script/reference changes, inspect key generated artifacts manually.
- Keep [ea-scripts/index-new.md](ea-scripts/index-new.md) untouched unless explicitly edited by maintainer.
## Risks and mitigations
Risk: duplicate logic drifts again across scripts.
- Mitigation: one shared generator core and wrapper entrypoints.
Risk: type aliasing hides critical concrete structures again.
- Mitigation: required-symbol guard (`ObsidianPenStrokeOptions`) and explicit canonical-source inclusion.
Risk: stricter image naming breaks existing contributions.
- Mitigation: staged rollout (warn-first) and clear remediation examples.
Risk: template sync introduces hard dependency on external repo.
- Mitigation: optional detection; never fail when repo is absent.
## Action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-08-29 | Captured maintainer decisions for scripting support modernization | Decisions documented for unified generator, manual index curation, PR workflow guidance, strict image naming, and optional template sync | Plan file created at [ScriptSupportPlan.md](ScriptSupportPlan.md) |
| 2026-08-29 | Confirmed template repository workspace availability and expanded publishing requirements | Verified [../ea-script-template](../ea-script-template) is present and readable; added mandatory [ea-scripts/directory-info.json](ea-scripts/directory-info.json) update rules to publishing workflow and checkpoint details | Directory listing succeeded for [../ea-script-template](../ea-script-template); plan updated |
| 2026-08-29 | Implemented checkpoint 1 unified generator | Consolidated duplicated generation logic into [scripts/excalidraw-docs-generator-core.mjs](scripts/excalidraw-docs-generator-core.mjs), with wrapper entrypoints preserved at [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs) and [scripts/skill-builder.mjs](scripts/skill-builder.mjs) | `npm run doc` completed successfully and regenerated legacy + skill outputs from one code path |
| 2026-08-29 | Implemented checkpoint 5 image naming validator | Added warning-only preview filename validation and surfaced the `scripts-{slug}.{ext}` rule in generated publishing guidance | `npm run doc` completed successfully and emitted the expected warning for legacy preview names |
| 2026-08-29 | Implemented checkpoint 6 template bootstrap sync | `npm run doc` now refreshes a link-first bootstrap in the sibling `ea-script-template` workspace under `.ai/excalidraw-automate/` | `npm run doc` completed successfully and refreshed the sibling template bootstrap files |
| 2026-08-29 | Hardened checkpoint 6 for offline and advanced script authoring | Template sync now mirrors full generated references and script examples instead of only link stubs | `npm run doc` and `npm run sync-refs` now produce local skill + references + scripts snapshot in `.ai/excalidraw-automate/` |
| 2026-08-29 | Aligned template script extensions and build output | Template-only reference snapshots now use `.js` filenames with rewritten local links; the template build emits executable `.md` scripts with purpose metadata and editable configuration constants before the bundle | `npm run doc` preserves `.js` reference filenames; template `npm run build`, `npm run check`, and package validation pass on Node 22 |
File diff suppressed because it is too large. Load diff
+335 -11
View File
@@ -12,7 +12,7 @@ Content structure:
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: 2026-07-12T12:50:29.769Z
Generated on: 2026-08-30T12:07:47.389Z
---
@@ -120,6 +120,7 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg"/></div>|[[#Mindmap Builder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20format.svg"/></div>|[[#Mindmap format]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.svg"/></div>|[[#Printable Layout Wizard]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.svg"/></div>|[[#Voronoi Diagram Generator]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.svg"/></div>|[[#Zoom to Fit Selected Elements]]|
## Connectors and Arrows
@@ -756,6 +757,23 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Printable%20Layout%20Wizard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.<br><a href="https://www.youtube.com/watch?v=29EWeglRm7s" target="_blank"><img src ="https://i.ytimg.com/vi/29EWeglRm7s/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/29EWeglRm7s' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=DqDnzCOoYMc" target="_blank"><img src ="https://i.ytimg.com/vi/DqDnzCOoYMc/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/DqDnzCOoYMc' target='_blank'>Link to video on YouTube</a><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-01.png" style="max-width: 400px;"><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-02.png" style="max-width: 400px;"></td></tr></table>
## Voronoi Diagram Generator
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/FreeCutter'>@FreeCutter</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/VoronoiDiagramGenerator.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script generates a Voronoi diagram from selected elements on the drawing canvas.
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
- Frame width (default: 100)
- Roughness (default: 0)
- Stroke width (default: 2)
- Grouping (default: checked)
Setting parameters could be set back to default values by click on button 'Default'.
See background information about [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) at Wikipedia.
Comments and discussion are welcomed in the [Sketch Your Mind Community](https://community.sketch-your-mind.com)<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/Voronoi_diagram_example.svg'></td></tr></table>
## Zoom to Fit Selected Elements
```excalidraw-script-install
@@ -798,6 +816,7 @@ elements.forEach((el)=>{
ea.addToGroup([el.id,ellipseId]);
});
await ea.addElementsToView(false,false,true);
```
---
@@ -870,6 +889,7 @@ if(openInCurrentPane) {
return;
}
ea.openFileInNewOrAdjacentLeaf(file);
```
---
@@ -967,6 +987,7 @@ if(openInCurrentPane) {
return;
}
ea.openFileInNewOrAdjacentLeaf(file);
```
---
@@ -1902,6 +1923,7 @@ function applyTranformationMatrix(vectors, transformationMatrix) {
return result;
}
```
---
@@ -2090,6 +2112,7 @@ function recalculateEndPointOfLine(line, el) {
line.points[line.points.length - 1] = [intersectA[0][0] - line.x, intersectA[0][1] - line.y];
}
}
```
---
@@ -5162,6 +5185,7 @@ if (elements.length>0) {
ea.copyViewElementsToEAforEditing(editedElements);
ea.addElementsToView(false,false);
```
---
@@ -7336,6 +7360,7 @@ async function main() {
// Execute Script
main();
```
---
@@ -7826,6 +7851,7 @@ if(element.type === 'arrow') {
appState.currentItemStartArrowhead = element.startArrowhead;
appState.currentItemEndArrowhead = element.endArrowhead;
}
```
---
@@ -7854,6 +7880,7 @@ const fname = await utils.inputPrompt("Filename for new file","Filename",folder)
const file = await app.fileManager.createAndOpenMarkdownFile(fname,true);
await ea.addImage(0,0,file);
ea.addElementsToView(true,true);
```
---
@@ -8017,6 +8044,7 @@ for (const el of ea.getElements()) {
}
}
await ea.addElementsToView(false, false);
```
---
@@ -8455,6 +8483,7 @@ for (const line of lines) {
ea.copyViewElementsToEAforEditing(lines);
await ea.addElementsToView(false,false);
```
---
@@ -8523,6 +8552,7 @@ id = ea.addEllipse(
ea.copyViewElementsToEAforEditing(elements);
ea.addToGroup([id].concat(elements.map((el)=>el.id)));
ea.addElementsToView(false,false);
```
---
@@ -11475,6 +11505,8 @@ const openConfigModal = () => {
};
openConfigModal();
```
---
@@ -11810,6 +11842,7 @@ const outfile = await app.vault.create(outputPath,result);
setTimeout(()=>{
ea.openFileInNewOrAdjacentLeaf(outfile);
}, 250);
```
---
@@ -13565,6 +13598,7 @@ function recalculateEndPointOfLine(line, el) {
line.points[line.points.length - 1] = [intersectA[0][0] - line.x, intersectA[0][1] - line.y];
}
}
```
---
@@ -13646,6 +13680,7 @@ for(var i=0; i<groups.length; i++) {
}
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -13780,6 +13815,7 @@ else if(fromBorder === 'right') {
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -13856,6 +13892,7 @@ for(var i=0; i<groups.length; i++) {
}
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -14015,6 +14052,7 @@ for(var i=0; i<groups.length; i++) {
}
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -14195,6 +14233,7 @@ do {
await ea.addElementsToView(false, false, true);
```
---
@@ -14951,6 +14990,7 @@ try {
} catch (err) {
_ = new Notice(err.toString())
}
```
---
@@ -17794,7 +17834,8 @@ try {
} catch (error) {
console.error("Error showing completion message:", error);
new Notice("Operation completed with some errors");
}
}
```
---
@@ -17923,6 +17964,7 @@ ea.viewUpdateScene({
elements: ea.getElements(),
storeAction: "capture" // Ensures the change is saved and added to the undo/redo history.
});
```
---
@@ -17982,6 +18024,7 @@ for (const el of ea.getElements()) {
}
}
await ea.addElementsToView(false, false);
```
---
@@ -18198,6 +18241,7 @@ const bottomHeaderY = START_Y + 160 + (12 * (CELL_HEIGHT + ROW_SPACING)) + 40;
drawDayHeaders(bottomHeaderY);
await ea.addElementsToView(false, false, true);
```
---
@@ -21594,11 +21638,36 @@ const zoomToFit = (mode) => {
elementID: sel.id,
level: nextLevel
}
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: getZoom(nextLevel),
animate: true
});
const targetZoom = getZoom(nextLevel);
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: targetZoom,
animate: true
});
} else {
// For the new API, we calculate a target rect centered on the element
// with dimensions that will force 'fit: "contain"' to reach our target zoom.
const appState = api().getAppState();
const targetW = appState.width / targetZoom;
const targetH = appState.height / targetZoom;
const cx = sel.x + sel.width / 2;
const cy = sel.y + sel.height / 2;
api().setViewport({
target: {
x: cx - targetW / 2,
y: cy - targetH / 2,
width: targetW,
height: targetH
},
fit: "contain",
animation: true
});
}
}
}
@@ -21627,10 +21696,20 @@ const focusSelected = () => {
if (!sel) return;
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
} else {
// fit: "none" recenters at the current zoom without changing it
api().setViewport({
target: [sel],
fit: "none",
animation: true
});
}
};
const getMindmapOrder = (node) => {
@@ -32328,6 +32407,7 @@ else {
}
await ea.addElementsToView(false,false,true);
```
---
@@ -32705,6 +32785,7 @@ generateTree(elements);
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);
```
---
@@ -33740,6 +33821,7 @@ async function run() {
}
run();
```
---
@@ -34654,6 +34736,7 @@ async function run() {
}
run();
```
---
@@ -34829,6 +34912,7 @@ for(i of img) {
await app.fileManager.renameFile(file,`${newPath}.${file.extension}`);
}
}
```
---
@@ -34952,6 +35036,7 @@ for(let i=0; i<repeatNum; i++) {
}
await ea.addElementsToView(false, false, true);
```
---
@@ -35054,6 +35139,8 @@ for(let i=0; i<repeatNum; i++) {
}
await ea.addElementsToView(false, false, true);
```
---
@@ -36149,6 +36236,7 @@ ea.copyViewElementsToEAforEditing(elements);
ea.getElements().forEach((el)=>el.strokeWidth=width);
await ea.addElementsToView(false,false);
ea.viewUpdateScene({appState: {currentItemStrokeWidth: width}});
```
---
@@ -37935,6 +38023,7 @@ if(
window.ExcalidrawSlideshowStartTimer = window.setTimeout(start,500);
}
```
---
@@ -40417,6 +40506,240 @@ ea.getElements().forEach(el=>{
const ids = ea.getElements().map(el=>el.id);
await ea.addElementsToView(false,true);
ea.getExcalidrawAPI().updateContainerSize(ea.getViewElements().filter(el=>ids.contains(el.id)));
```
---
## VoronoiDiagramGenerator.md
<!-- Source: ea-scripts/VoronoiDiagramGenerator.md -->
/*
This script generates a Voronoi diagram from selected elements on the drawing canvas.
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
- Frame width (default: 100)
- Roughness (default: 0)
- Stroke width (default: 2)
- Grouping (default: checked)
Setting parameters could be set back to default values by click on button 'Default'.
Check info button for howto help during applying the script.
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
```js*/
// ExcalidrawAutomate: Voronoi Diagram Generator
ea.clear();
const DEFAULTS = {
frameWidth: 100,
roughness: 0,
strokeWidth: 2,
groupVoronoi: true
};
let config = ea.getScriptSettings() || { ...DEFAULTS };
// --- UI SETTINGS MODAL ---
async function openSettings() {
return new Promise((resolve) => {
const modal = new ea.obsidian.Modal(app);
modal.contentEl.style.padding = "20px";
// Header container with Title and Info Button
const headerContainer = modal.contentEl.createDiv();
headerContainer.style.display = "flex";
headerContainer.style.justifyContent = "space-between";
headerContainer.style.alignItems = "center";
headerContainer.style.marginBottom = "20px";
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
// Info button using Obsidian's native icon
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
btnInfo.setAttribute("aria-label", "Information & Help");
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
// Info modal content on click
btnInfo.onclick = () => {
const infoModal = new ea.obsidian.Modal(app);
infoModal.contentEl.style.padding = "20px";
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
// Native Obsidian Icon as HTML string
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
const p = infoModal.contentEl.createEl("p");
p.innerHTML = `
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
<div line-height: 1.4;">
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
- <b>Frame width:</b> Spacing around the diagram.<br>
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
- <b>Stroke width:</b> Line thickness.<br>
- <b>Grouping:</b> Group generated cells together.<br>
</div>
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
</div><br>
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
</span>
`;
infoModal.open();
};
const inputs = {};
// Helper function to create input rows
const createInput = (label, key, type = "number") => {
const container = modal.contentEl.createDiv();
container.style.marginBottom = "15px";
container.createEl("label", { text: label });
const input = container.createEl("input", { type: type });
input.style.display = "block";
input.style.marginTop = "5px";
input.value = config[key];
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
inputs[key] = input;
};
createInput("Frame width:", "frameWidth");
createInput("Roughness (0-3):", "roughness");
createInput("Stroke width:", "strokeWidth");
const checkContainer = modal.contentEl.createDiv();
checkContainer.style.marginBottom = "25px";
checkContainer.createEl("label", { text: "Grouping: " });
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
inputs.groupVoronoi.checked = config.groupVoronoi;
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
// Button container
const btnContainer = modal.contentEl.createDiv();
btnContainer.style.display = "flex";
btnContainer.style.gap = "10px";
btnContainer.style.justifyContent = "flex-end";
const btnDefault = btnContainer.createEl("button", { text: "Default" });
const btnOk = btnContainer.createEl("button", { text: "OK" });
btnDefault.onclick = () => {
config = { ...DEFAULTS };
inputs.frameWidth.value = config.frameWidth;
inputs.roughness.value = config.roughness;
inputs.strokeWidth.value = config.strokeWidth;
inputs.groupVoronoi.checked = config.groupVoronoi;
new Notice("Settings reset to default");
};
btnOk.onclick = () => {
ea.setScriptSettings(config);
modal.close();
resolve(true);
};
modal.open();
});
}
// Wait for user to configure settings
const proceed = await openSettings();
if (!proceed) return;
// --- ALGORITHM & EXECUTION ---
const els = ea.getViewSelectedElements();
if (els.length < 2) {
new Notice("Please select at least two items!");
return;
}
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
if (seeds.length < 2) {
new Notice("Please select at least two items!");
return;
}
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
const bbox = [
{ x: minX, y: minY },
{ x: maxX, y: minY },
{ x: maxX, y: maxY },
{ x: minX, y: maxY }
];
function clipPolygon(poly, p1, p2) {
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
const intersect = (a, b) => {
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
if (den === 0) return null;
const t = -num / den;
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
};
const result = [];
for (let i = 0; i < poly.length; i++) {
const cur = poly[i];
const prev = poly[(i - 1 + poly.length) % poly.length];
const curIn = isInside(cur);
const prevIn = isInside(prev);
if (curIn !== prevIn) {
const ix = intersect(prev, cur);
if (ix) result.push(ix);
}
if (curIn) result.push(cur);
}
return result;
}
const polygons = seeds.map((s, i) => {
let poly = [...bbox];
seeds.forEach((_, j) => {
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
});
return poly;
});
ea.style.roughness = config.roughness;
ea.style.strokeWidth = config.strokeWidth;
ea.style.backgroundColor = "transparent";
const ids = [];
for (const poly of polygons) {
if (poly.length < 3) continue;
const points = poly.map(p => [p.x, p.y]);
points.push(points[0]);
ids.push(ea.addLine(points));
}
if (config.groupVoronoi && ids.length > 0) {
ea.addToGroup(ids);
}
await ea.addElementsToView(false, false);
// Clear selection so nothing remains selected on the canvas
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
new Notice("Voronoi diagram created!");
```
---
@@ -40439,4 +40762,5 @@ https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.h
elements = ea.getViewSelectedElements();
api = ea.getExcalidrawAPI();
api.zoomToFit(elements,10);
```
File diff suppressed because it is too large. Load diff
@@ -9,8 +9,17 @@ Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source E
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
**Routing note:** Prefer the curated skill package and reference set first. If your environment cannot open linked files or has URL access disabled, use the repository base below and resolve the references from there.
- Master repository: https://github.com/zsviczian/obsidian-excalidraw-plugin
- Start with: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/SKILL.md
- Type definitions: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/type-definitions.md
- API usage index: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/api-usage-index.md
- ExcalidrawLib signatures: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/excalidraw-lib-functions.md
- Startup examples: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/startup-scripts.md
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via `ea.getExcalidrawAPI()`. Note: the API is only available if `ea.targetView` is set. When running Excalidraw scripts using the script engine, the provided `ea` object is already set up with targetView by default. Otherwise you need to first run `ea.setView()`.
- The Excalidraw API available via `ea.getExcalidrawAPI()`. Note: the API is only available if `ea.targetView` is set. When running Excalidraw scripts using the script engine, the provided `ea` object is already set up with targetView by default. Otherwise call `ea.setView()` to select a sensible default or `ea.setView(view)` to bind explicitly. Calling `ea.setView(null)` deliberately clears `targetView`; it does not auto-select another drawing.
- `window.ExcalidrawLib` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via `ea` (ExcalidrawAutomate) methods, ALWAYS prefer `ea` over `window.ExcalidrawLib`. `ea` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
@@ -23,10 +32,17 @@ 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`.
- 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.
- `ea.registerElementActionProvider()` action descriptors take an Obsidian/Lucide icon name such as `"presentation"`, not serialized SVG markup. For buttons a script renders itself, obtain the SVG with `ea.obsidian.getIcon()` and recreate it in the button's owning document when popout support matters.
- When an Excalidraw API method requires an element, pass the known typed scene element. For example, call `api.startLineEditor(line, pointIndices)`; do not re-read selection state when the intended line is already known.
- For persistent workbench mutations, await `ea.addElementsToView()` with saving enabled (the default). Prefer this public EA save path over unpublished methods on `ea.targetView`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (`onOpen`, `onFocus(view)`, `onClose`, `onExcalidrawViewClosed`) and manage their own `ea.targetView` explicitly.
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with `ea.targetView === null`. Scripts must handle this by deferring view-bound work until `onFocus` delivers a view; call `ea.setView(view)` when you decide to bind.
- Persisted sidepanel scripts are restored lazily when the Excalidraw sidepanel initializes (often during startup, but not necessarily) with `ea.targetView === null`. Scripts must handle this by deferring view-bound work until `onFocus` delivers a view; call `ea.setView(view)` when you decide to bind. When `onFocus` supplies `null` or focus moves to a non-Excalidraw view, call `ea.setView(null)` to make the unbound state explicit and prevent later view operations from targeting a stale drawing.
- Each `ea` instance may host a single `sidepanelTab`. This sidepanel tab is stored in `ea.sidepanelTab`. Create the tab with `ea.createSidepanelTab(title, persist=false, reveal=true)`; the returned `ea.sidepanelTab` exposes `contentEl`, `setContent`, `setTitle`, `setDisabled`, `setCloseCallback`, `open/close`, and focus lifecycle hooks. Note auto-reveal during tab creation via `ea.createSidepanelTab()` is disabled during plugin startup. You can reveal a tab with `ea.sidepanelTab?.open()`. You can persist with `ea.persistSidepanelTab()` (tabs are restored and scripts re-run on next startup). Close with `ea.sidepanelTab?.close()`.
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-`ExcalidrawView` relevant, they can call `ea.closeSidepanelTab()` after completing the operation, and/or inside `ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }` to shut down when the user leaves the originating view.
@@ -64,14 +80,32 @@ To keep this training file concise, large external type definitions are not incl
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
* **Central Rule:** Elements returned from the Excalidraw scene are immutable and should never be modified directly. EA owns a stateful, in-memory "workbench" (`elementsDict` and `imagesDict`) where a script stages one coherent persistent or temporary operation independently of the scene.
* **The Workflow:**
1. Get elements from the current view using `ea.getViewElements()` or `ea.getViewSelectedElements()`.
2. Copy these elements into the EA workbench for editing using `ea.copyViewElementsToEAforEditing(elements)`.
3. Modify the properties of the element copies that are now in the EA workbench (e.g., `ea.getElement(id).locked = true;`).
4. Commit the changes back to the scene using `await ea.addElementsToView()`.
1. Start an independent transaction with `ea.clear()`. This clears only the workbench; it does not delete scene elements or reset style.
2. Read existing scene elements using `ea.getViewElements()` or `ea.getViewSelectedElements()`.
3. To work with mutable copies of those same scene elements, copy them into the workbench with `ea.copyViewElementsToEAforEditing(elements)`. Their IDs are preserved.
4. Modify the workbench copies retrieved by their original IDs (e.g., `ea.getElement(id).locked = true;`).
5. For a persistent scene edit, commit once with `await ea.addElementsToView()`; saving is enabled by default. For temporary transformations such as export or preview preparation, pass the workbench elements to the relevant EA operation without committing them to the scene.
6. Call `ea.clear()` after the operation to discard the workbench copies, preferably in a `finally` block when an awaited operation can fail.
* **Temporary workbench example:**
```javascript
ea.clear();
try {
const sceneElements = ea.getViewElements();
ea.copyViewElementsToEAforEditing(sceneElements);
ea.getElement(pathId).opacity = 0;
// elementsOverride replaces the export scene, so pass the complete workbench.
const svg = await ea.createViewSVG({ elementsOverride: ea.getElements() });
// Use svg. The live scene was never changed.
} finally {
ea.clear();
}
```
* **`elementsOverride` is a complete replacement:** In `createViewSVG()`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the SVG. When temporarily modifying an existing scene for export, the simplest safe workflow is to copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
* **Identity is the boundary:** `copyViewElementsToEAforEditing()` is the standard way to obtain mutable, identity-preserving copies of existing scene elements for both persistent edits and temporary EA operations. By contrast, `ea.cloneElement()` and `ea.cloneElements()` deliberately generate new IDs and are only for creating genuine duplicate scene elements. Never use them to obtain editable workbench copies of existing elements.
* **One workbench transaction at a time:** The workbench is shared mutable state on an EA instance. Do not interleave asynchronous preview/export preparation and scene mutation through the same workbench. Await the operation, then clear the workbench before starting another transaction.
* **Deletion:** To delete an element, set its `isDeleted` property to `true` on the workbench copy (`ea.getElement(id).isDeleted = true;`) and then commit with `await ea.addElementsToView()`.
* **Cleanup:** Use `ea.clear()` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
#### **2. User Interaction: Prompts and Dialogs**
@@ -125,11 +159,27 @@ To keep this training file concise, large external type definitions are not incl
* To permanently remove an element from the scene, set `element.isDeleted = true`.
* **Image Handling:** When dealing with image elements, use `ea.getViewFileForImageElement(imageElement)` to get the corresponding `TFile` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **6.1. Tests in a Multi-Script Workspace**
* **Tests are part of implementation:** Add or update focused automated tests for behavior changes. When fixing a regression, reproduce it with a failing test first when practical.
* **Co-locate by ownership:** Put script tests in `src/scripts/{slug}/__tests__/*.test.ts` and shared utility tests in `src/sharedUtils/__tests__/*.test.ts`. Do not maintain a separate root test tree that mirrors dozens of scripts.
* **Never import executable entrypoints:** `main.ts` runs immediately against the globals injected by Obsidian. Keep it as a thin bootstrap and move testable orchestration to `run.ts` or another import-safe module.
* **Use the universal runner:** Use Vitest. Run a focused suite while iterating, then run `npm run check`; the repository gate includes TypeScript, ESLint, and all test suites. Use `npm run test:watch` for continuous feedback.
* **Test behavior, not bundler details:** Prefer pure domain functions and narrow fakes for `ea`, the Excalidraw API, Obsidian globals, timers, and DOM boundaries. Build and perform an Obsidian smoke test for integration behavior automation cannot prove.
#### **6.2. Per-Script Localization**
* **Catalogs belong to the script:** Store strings in `src/scripts/{slug}/lang/`, with one file per locale. Never create one language catalog shared across unrelated scripts.
* **English defines the contract:** `lang/en.ts` is the typed source of truth. Maintain `de.ts`, `es.ts`, `fr.ts`, `ru.ts`, and `zh-cn.ts`; incomplete reviewed catalogs may rely on English fallback.
* **Use the shared helper:** Register catalogs in `lang/index.ts` with `createTranslator`. Resolve the locale with `ea.obsidian.moment.locale()` and pass the translator into import-safe script logic.
* **Interpolate by name:** Use placeholders such as `{count}` instead of string concatenation. Do not use dynamically constructed regular expressions for interpolation.
* **Keep UI copy out of logic:** Add user-visible strings to the script catalog rather than embedding them in controllers, runners, or helpers.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use `await ea.createSVG(null, ...)` or `await ea.createPNG(null, ...)` (passing `null` as the `templatePath`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to `createSVG` or `createPNG` (e.g., `await ea.createSVG(file.path, ...)`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)`. This is specifically for the open view. You can use the `elementsOverride` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)`. This is specifically for the open view. Its `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or a patch by ID. If supplied, include every existing or temporary element that should appear in the SVG. For temporary changes to existing elements, copy the complete desired export set into the EA workbench, modify it there, and pass `ea.getElements()`.
#### **8. Custom Pens and Perfect Freehand**
@@ -230,11 +280,23 @@ Example freedraw element carrying `customData.strokeOptions`:
## References
The `references/` directory contains supporting documentation necessary for writing scripts:
- `references/type-definitions.md`: Core type definitions for ExcalidrawAutomate.
- `references/excalidraw-lib-functions.md`: Function signatures for `window.ExcalidrawLib`.
- `references/startup-scripts.md`: ExcalidrawStartup script template and examples.
- `references/api-usage-index.md`: A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
- `references/scripts/`: A folder containing all the raw, real-world example scripts.
- [type-definitions.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/type-definitions.md): Core type definitions for ExcalidrawAutomate.
- [excalidraw-lib-functions.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/excalidraw-lib-functions.md): Function signatures for `window.ExcalidrawLib`.
- [startup-scripts.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/startup-scripts.md): ExcalidrawStartup script template and examples.
- [api-usage-index.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/api-usage-index.md): A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
- [scripts/](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/docs/AITrainingData/excalidraw-automate/references/scripts): A folder containing all the raw, real-world example scripts.
## Publishing Workflow
Use the normal repository contribution flow when publishing or updating scripts.
The AI training material is maintained independently from publishing PRs; do not bundle regenerated training artifacts into the script PR.
- Preview images must follow `scripts-{slug}.{ext}`, where `slug` uses lowercase `a-z`, `0-9`, and hyphens only.
- 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).
- 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
If you need to implement a specific function (e.g., `ea.addElementsToView`), do NOT guess its implementation context. Instead:
@@ -9,23 +9,23 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **addAppendUpdateCustomData**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **addArrow**: [Concatenate lines.md](scripts/Concatenate%20lines.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md)
- **addDiamond**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addElementsToView**: [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), [Auto Layout.md](scripts/Auto%20Layout.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), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%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), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Icon Library.md](scripts/Icon%20Library.md), [Lighten background color.md](scripts/Lighten%20background%20color.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), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.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), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.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 Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.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), [Uniform size.md](scripts/Uniform%20size.md)
- **addElementsToView**: [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), [Auto Layout.md](scripts/Auto%20Layout.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), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%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), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Icon Library.md](scripts/Icon%20Library.md), [Lighten background color.md](scripts/Lighten%20background%20color.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), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.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), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.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 Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.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), [Uniform size.md](scripts/Uniform%20size.md), [VoronoiDiagramGenerator.mLine truncated
- **addEllipse**: [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), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addEmbeddable**: [Capture Note.md](scripts/Capture%20Note.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addFrame**: [Capture Note.md](scripts/Capture%20Note.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
- **addImage**: [Capture Note.md](scripts/Capture%20Note.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addLaTex**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **addLine**: [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), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [To Line.md](scripts/To%20Line.md)
- **addLine**: [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), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [To Line.md](scripts/To%20Line.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **addMermaid**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **addRect**: [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.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), [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), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Slideshow.md](scripts/Slideshow.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **addText**: [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Scribble Helper.md](scripts/Scribble%20Helper.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)
- **addToGroup**: [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), [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), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.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), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **addToGroup**: [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), [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), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.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), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **analyzeAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **attachInlineLinkSuggester**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **canvas**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md)
- **checkAndCreateFolder**: [Capture Note.md](scripts/Capture%20Note.md)
- **checkForActiveSidepanelTabForScript**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
- **clear**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.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), [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)
- **clear**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.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), [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), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **cloneElement**: [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.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), [Slideshow.md](scripts/Slideshow.md), [Text Aura.md](scripts/Text%20Aura.md)
- **cloneElements**: [Capture Note.md](scripts/Capture%20Note.md)
- **colorNameToHex**: [Darken background color.md](scripts/Darken%20background%20color.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Repeat Elements.md](scripts/Repeat%20Elements.md)
@@ -71,7 +71,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **getPathForImageFileId**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getPolyBool**: [Boolean Operations.md](scripts/Boolean%20Operations.md)
- **getSceneFromFile**: [Palette loader.md](scripts/Palette%20loader.md)
- **getScriptSettings**: [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), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.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), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.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), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **getScriptSettings**: [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), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.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), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.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), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **getScriptSettingValue**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getSidepanelLeaf**: [Capture Note.md](scripts/Capture%20Note.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getSVGColorInfoForImgElement**: [Shade Master.md](scripts/Shade%20Master.md)
@@ -79,7 +79,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **getViewElements**: [Auto Layout.md](scripts/Auto%20Layout.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), [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), [Elbow connectors.md](scripts/Elbow%20connectors.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Invert colors.md](scripts/Invert%20colors.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.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), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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), [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), [Uniform size.md](scripts/Uniform%20size.md)
- **getViewFileForImageElement**: [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Shade Master.md](scripts/Shade%20Master.md)
- **getViewSelectedElement**: [Capture Note.md](scripts/Capture%20Note.md), [Copy Selected Element Styles to Global.md](scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Slideshow.md](scripts/Slideshow.md), [To Line.md](scripts/To%20Line.md)
- **getViewSelectedElements**: [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), [Auto Layout.md](scripts/Auto%20Layout.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), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%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 text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Image Occlusion.md](scripts/Image%20Occlusion.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), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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 Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.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), [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
- **getViewSelectedElements**: [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), [Auto Layout.md](scripts/Auto%20Layout.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), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%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 text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Image Occlusion.md](scripts/Image%20Occlusion.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), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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 Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.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), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md), [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
- **imagesDict**: [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Image Occlusion.md](scripts/Image%20Occlusion.md)
- **importSVG**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **intersectElementWithLine**: [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md)
@@ -90,7 +90,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **measureText**: [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **Modal**: [Image Occlusion.md](scripts/Image%20Occlusion.md)
- **moveViewElementToZIndex**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.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)
- **obsidian**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.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), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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)
- **obsidian**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.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), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **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), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
@@ -100,7 +100,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **reset**: [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md)
- **saveScriptSettings**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **selectElementsInView**: [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), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.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), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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), [Slideshow.md](scripts/Slideshow.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **setScriptSettings**: [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), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.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), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.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), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **setScriptSettings**: [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), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.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), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.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), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **setScriptSettingValue**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **setStrokeSharpness**: [Scribble Helper.md](scripts/Scribble%20Helper.md)
- **setValue**: [ExcaliAI.md](scripts/ExcaliAI.md)
@@ -110,7 +110,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **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), [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), [Slideshow.md](scripts/Slideshow.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)
- **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), [Slideshow.md](scripts/Slideshow.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), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%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)
- **tex2dataURL**: [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md)
- **toggleSidepanelView**: [Capture Note.md](scripts/Capture%20Note.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
@@ -84,7 +84,7 @@ export declare const getCommonBoundingBox: (elements: readonly ExcalidrawElement
/* ************************************** */
/* @excalidraw/element/groups -> node_modules/@zsviczian/excalidraw/types/element/src/groups.d.ts */
/* ************************************** */
export declare const getMaximumGroups: (elements: ExcalidrawElement[], elementsMap: ElementsMap) => ExcalidrawElement[][];
export declare const getMaximumGroups: <T extends NonDeletedExcalidrawElement | ExcalidrawElement>(elements: T[], elementsMap: ElementsMap) => T[][];
/* ************************************** */
/* @excalidraw/element/textMeasurements -> node_modules/@zsviczian/excalidraw/types/element/src/textMeasurements.d.ts */
@@ -101,7 +101,7 @@ export declare const wrapText: (text: string, font: FontString, maxWidth: number
/* @excalidraw/element/textElement -> node_modules/@zsviczian/excalidraw/types/element/src/textElement.d.ts */
/* ************************************** */
export declare const getBoundTextMaxWidth: (container: ExcalidrawElement, boundTextElement: ExcalidrawTextElement | null) => number;
export declare const getContainerElement: (element: ExcalidrawTextElement | null, elementsMap: ElementsMap) => ExcalidrawTextContainer | null;
export declare const getContainerElement: <T extends ExcalidrawTextElement, R extends ExcalidrawTextContainer>(element: T | null, elementsMap: ElementsMap) => R | null;
/* ************************************** */
/* ./components/TTDDialog/MermaidToExcalidrawLib -> node_modules/@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/MermaidToExcalidrawLib.d.ts */
@@ -223,21 +223,20 @@ export declare const TTDDialog: {
/* ************************************** */
/* ./components/TTDDialog/utils/TTDStreamFetch -> node_modules/@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/utils/TTDStreamFetch.d.ts */
/* ************************************** */
export declare function parseSSEStream(reader: ReadableStreamDefaultReader<Uint8Array>): AsyncGenerator<string, void, unknown>;
export declare function TTDStreamFetch(options: StreamingOptions): Promise<TTTDDialog.OnTextSubmitRetValue>;
/* ************************************** */
/* ./actions/actionCanvas -> node_modules/@zsviczian/excalidraw/types/excalidraw/actions/actionCanvas.d.ts */
/* ./viewport -> node_modules/@zsviczian/excalidraw/types/excalidraw/viewport.d.ts */
/* ************************************** */
export declare const zoomToFitBounds: ({ bounds, appState, canvasOffsets, fitToViewport, viewportZoomFactor, minZoom, maxZoom, }: {
export declare const zoomToFitBounds: ({ bounds, appState, canvasOffsets, fit, minZoom, maxZoom, steppedZoom, }: {
bounds: SceneBounds;
canvasOffsets?: Offsets;
appState: Readonly<AppState>;
/** whether to fit content to viewport (beyond >100%) */
fitToViewport: boolean;
/** zoom content to cover X of the viewport, when fitToViewport=true */
viewportZoomFactor?: number;
fit?: SetViewportOptions["fit"];
minZoom?: number;
maxZoom?: number;
steppedZoom?: boolean;
}) => {
appState: {
scrollX: number;
@@ -254,4 +253,36 @@ export declare const DiagramToCodePlugin: (props: {
/* ************************************** */
export declare const CommandPalette: ((props: CommandPaletteProps) => import("react/jsx-runtime").JSX.Element | null) & {
defaultItems: typeof defaultItems;
/* ************************************** */
/* ./obsidianExcalidrawHost -> node_modules/@zsviczian/excalidraw/types/excalidraw/obsidianExcalidrawHost.d.ts */
/* ************************************** */
export declare const OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION: 2;
/** Keyboard-blocking lifecycle returned by the host's inline suggester. */
export interface ObsidianKeyBlocker {
isBlockingKeys(): boolean;
close(): void;
}
/** Plugin-wide capabilities consumed by the Excalidraw package. */
export interface ObsidianExcalidrawHostAdapter {
readonly protocolVersion: typeof OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION;
isDoubleTapEraserEnabled(): boolean;
isRightClickPanEnabled(): boolean;
getZoomToFitMaxLevel(): number;
isPenModeCrosshairVisible(): boolean;
isSingleFingerPanningEnabled(): boolean;
isDoubleClickTextEditingDisabled(): boolean;
getZoomStep(): number;
getZoomMin(): number;
getZoomMax(): number;
isContextMenuDisabled(): boolean;
shouldSyncElementLinkWithText(): boolean;
loadFontFromFile(filename: string): Promise<ArrayBuffer | undefined>;
getMermaid(): Promise<MermaidToExcalidrawLibProps>;
runAction(action: "anyFile" | "LaTeX" | "card"): void;
getLabel(key: string): string;
attachInlineLinkSuggester(inputEl: HTMLInputElement | HTMLTextAreaElement, widthWrapper?: HTMLElement, container?: HTMLDivElement | null, suppressPlaceholder?: boolean): ObsidianKeyBlocker;
}
/** Idempotent cleanup returned when a package host is configured. */
export type ObsidianExcalidrawHostDisposer = () => void;
```
@@ -3378,11 +3378,36 @@ const zoomToFit = (mode) => {
elementID: sel.id,
level: nextLevel
}
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: getZoom(nextLevel),
animate: true
});
const targetZoom = getZoom(nextLevel);
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: targetZoom,
animate: true
});
} else {
// For the new API, we calculate a target rect centered on the element
// with dimensions that will force 'fit: "contain"' to reach our target zoom.
const appState = api().getAppState();
const targetW = appState.width / targetZoom;
const targetH = appState.height / targetZoom;
const cx = sel.x + sel.width / 2;
const cy = sel.y + sel.height / 2;
api().setViewport({
target: {
x: cx - targetW / 2,
y: cy - targetH / 2,
width: targetW,
height: targetH
},
fit: "contain",
animation: true
});
}
}
}
@@ -3411,10 +3436,20 @@ const focusSelected = () => {
if (!sel) return;
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
} else {
// fit: "none" recenters at the current zoom without changing it
api().setViewport({
target: [sel],
fit: "none",
animation: true
});
}
};
const getMindmapOrder = (node) => {
@@ -0,0 +1,227 @@
/*
This script generates a Voronoi diagram from selected elements on the drawing canvas.
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
- Frame width (default: 100)
- Roughness (default: 0)
- Stroke width (default: 2)
- Grouping (default: checked)
Setting parameters could be set back to default values by click on button 'Default'.
Check info button for howto help during applying the script.
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
```js*/
// ExcalidrawAutomate: Voronoi Diagram Generator
ea.clear();
const DEFAULTS = {
frameWidth: 100,
roughness: 0,
strokeWidth: 2,
groupVoronoi: true
};
let config = ea.getScriptSettings() || { ...DEFAULTS };
// --- UI SETTINGS MODAL ---
async function openSettings() {
return new Promise((resolve) => {
const modal = new ea.obsidian.Modal(app);
modal.contentEl.style.padding = "20px";
// Header container with Title and Info Button
const headerContainer = modal.contentEl.createDiv();
headerContainer.style.display = "flex";
headerContainer.style.justifyContent = "space-between";
headerContainer.style.alignItems = "center";
headerContainer.style.marginBottom = "20px";
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
// Info button using Obsidian's native icon
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
btnInfo.setAttribute("aria-label", "Information & Help");
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
// Info modal content on click
btnInfo.onclick = () => {
const infoModal = new ea.obsidian.Modal(app);
infoModal.contentEl.style.padding = "20px";
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
// Native Obsidian Icon as HTML string
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
const p = infoModal.contentEl.createEl("p");
p.innerHTML = `
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
<div line-height: 1.4;">
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
- <b>Frame width:</b> Spacing around the diagram.<br>
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
- <b>Stroke width:</b> Line thickness.<br>
- <b>Grouping:</b> Group generated cells together.<br>
</div>
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
</div><br>
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
</span>
`;
infoModal.open();
};
const inputs = {};
// Helper function to create input rows
const createInput = (label, key, type = "number") => {
const container = modal.contentEl.createDiv();
container.style.marginBottom = "15px";
container.createEl("label", { text: label });
const input = container.createEl("input", { type: type });
input.style.display = "block";
input.style.marginTop = "5px";
input.value = config[key];
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
inputs[key] = input;
};
createInput("Frame width:", "frameWidth");
createInput("Roughness (0-3):", "roughness");
createInput("Stroke width:", "strokeWidth");
const checkContainer = modal.contentEl.createDiv();
checkContainer.style.marginBottom = "25px";
checkContainer.createEl("label", { text: "Grouping: " });
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
inputs.groupVoronoi.checked = config.groupVoronoi;
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
// Button container
const btnContainer = modal.contentEl.createDiv();
btnContainer.style.display = "flex";
btnContainer.style.gap = "10px";
btnContainer.style.justifyContent = "flex-end";
const btnDefault = btnContainer.createEl("button", { text: "Default" });
const btnOk = btnContainer.createEl("button", { text: "OK" });
btnDefault.onclick = () => {
config = { ...DEFAULTS };
inputs.frameWidth.value = config.frameWidth;
inputs.roughness.value = config.roughness;
inputs.strokeWidth.value = config.strokeWidth;
inputs.groupVoronoi.checked = config.groupVoronoi;
new Notice("Settings reset to default");
};
btnOk.onclick = () => {
ea.setScriptSettings(config);
modal.close();
resolve(true);
};
modal.open();
});
}
// Wait for user to configure settings
const proceed = await openSettings();
if (!proceed) return;
// --- ALGORITHM & EXECUTION ---
const els = ea.getViewSelectedElements();
if (els.length < 2) {
new Notice("Please select at least two items!");
return;
}
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
if (seeds.length < 2) {
new Notice("Please select at least two items!");
return;
}
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
const bbox = [
{ x: minX, y: minY },
{ x: maxX, y: minY },
{ x: maxX, y: maxY },
{ x: minX, y: maxY }
];
function clipPolygon(poly, p1, p2) {
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
const intersect = (a, b) => {
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
if (den === 0) return null;
const t = -num / den;
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
};
const result = [];
for (let i = 0; i < poly.length; i++) {
const cur = poly[i];
const prev = poly[(i - 1 + poly.length) % poly.length];
const curIn = isInside(cur);
const prevIn = isInside(prev);
if (curIn !== prevIn) {
const ix = intersect(prev, cur);
if (ix) result.push(ix);
}
if (curIn) result.push(cur);
}
return result;
}
const polygons = seeds.map((s, i) => {
let poly = [...bbox];
seeds.forEach((_, j) => {
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
});
return poly;
});
ea.style.roughness = config.roughness;
ea.style.strokeWidth = config.strokeWidth;
ea.style.backgroundColor = "transparent";
const ids = [];
for (const poly of polygons) {
if (poly.length < 3) continue;
const points = poly.map(p => [p.x, p.y]);
points.push(points[0]);
ids.push(ea.addLine(points));
}
if (config.groupVoronoi && ids.length > 0) {
ea.addToGroup(ids);
}
await ea.addElementsToView(false, false);
// Clear selection so nothing remains selected on the canvas
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
new Notice("Voronoi diagram created!");
```
@@ -1,13 +1,23 @@
# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs once per Excalidraw plugin load using the plugin-global EA and utils.executionSource === 'plugin-startup'. Use ea.registerCleanup() for external listeners, timers, observers, or subscriptions that must be released when Excalidraw unloads. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
### Template
```js
/*
#exclude
```js*/
/**
* Startup scripts receive the plugin-global EA for the plugin lifetime and
* utils.executionSource === "plugin-startup". Register cleanup for resources
* outside EA so plugin reload/unload cannot accumulate them.
*/
// const ref = app.workspace.on("file-open", (file) => {});
// ea.registerCleanup(() => app.workspace.offref(ref));
//
// const interval = window.setInterval(() => {}, 1000);
// ea.registerCleanup(() => window.clearInterval(interval));
/**
* If set, this callback is triggered when the user closes an Excalidraw view.
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
File diff suppressed because it is too large. Load diff
+43 -5
View File
@@ -17,11 +17,49 @@ You will be able to access your scripts from Excalidraw via the Obsidian Command
![image](https://user-images.githubusercontent.com/14358394/145673652-6b1713e2-edc8-4bc8-8246-3f8df8a4b273.png)
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
![image](https://user-images.githubusercontent.com/14358394/145673633-83b6c969-cead-429b-9721-fd047f980279.png)
## Script development
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
![image](https://user-images.githubusercontent.com/14358394/145673633-83b6c969-cead-429b-9721-fd047f980279.png)
## EA script execution lifecycles
`utils.executionSource` describes why the current top-level script invocation
happened. It does not indicate whether the source was compiled previously,
whether the script has run before, or whether runtime state was retained.
| Trigger | `utils.executionSource` | EA received | Approximate lifetime |
| --- | --- | --- | --- |
| Script button, command, or hotkey | `manual` | fresh view EA | existing ordinary script/view lifecycle |
| Plugin startup script | `plugin-startup` | global plugin EA | plugin lifetime |
| `registerAutostart()` attachment | `view-autostart` | fresh view-local EA | view lifetime |
| Persisted sidepanel reconstruction | `sidepanel-restore` | sidepanel host EA | sidepanel tab lifetime |
| Sidepanel script reload | `sidepanel-reload` | reloaded sidepanel host EA | sidepanel tab lifetime |
| `excalidraw-onload-script` | `drawing-onload` | view-local EA | drawing/view lifetime |
Compilation caching is transparent: compiled JavaScript may be shared while
unchanged, but each invocation retains its existing EA ownership and execution
semantics. Manual execution remains repeatable even for a script that also uses
view autostart.
Use `ea.registerCleanup()` for resources that EA does not own directly:
```js
const ref = app.workspace.on("file-open", handler);
ea.registerCleanup(() => app.workspace.offref(ref));
window.addEventListener("resize", handler);
ea.registerCleanup(() => window.removeEventListener("resize", handler));
const interval = window.setInterval(callback, 1000);
ea.registerCleanup(() => window.clearInterval(interval));
```
Cleanup runs when that particular EA instance is destroyed, so its exact
lifetime depends on whether it is the plugin-startup EA, a view-local EA, or a
sidepanel host EA. The function returned by `registerCleanup()` unregisters the
callback without executing it.
## Script development
An Excalidraw script will automatically receive two objects:
- `ea`: The Script Engine will initialize the `ea` object including setting the active view to the View from which the script was called.
- `utils`: I have borrowed functions exposed on utils from [QuickAdd](https://github.com/chhoumann/quickadd/blob/master/docs/QuickAddAPI.md), though currently not all QuickAdd utility functions are implemented in Excalidraw. As of now, these are the available functions. See the example below for details.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.27.0-beta.4",
"version": "2.27.0-rc.2",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+4 -33
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.125",
"@zsviczian/excalidraw": "0.18.130",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -53,7 +53,6 @@
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@zsviczian/excalidraw-extras-api": "^0.0.13",
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
"cross-env": "^7.0.3",
"cssnano": "^6.0.2",
"eslint": "^9.39.4",
@@ -5255,9 +5254,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.125",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.125.tgz",
"integrity": "sha512-CKzhcdnVXiFf5wQTr9IN4vIsmz9AQpci8ciwC2KtA46bsoGp0AU0mqvdgfCFrzAGO3+SoWF2s9POOm/b1zsCOg==",
"version": "0.18.130",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.130.tgz",
"integrity": "sha512-+qsJ0B/qFWkT8ZZrgPn+FodZPko93NLIRsCrVqLG5fKFAqoEY22/IXcIRc72jion6D0XkN4wbJtBu/l6HtL7GQ==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
@@ -5342,26 +5341,6 @@
"integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==",
"license": "MIT"
},
"node_modules/@zsviczian/rollup-plugin-postprocess": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@zsviczian/rollup-plugin-postprocess/-/rollup-plugin-postprocess-1.0.3.tgz",
"integrity": "sha512-W3t9TgbjNnZ07h+Vg78qAo0lFkYoovdlp5ojbiSP6aMswDIDdkvwrt4qQataN2kJ9UlkcvKB0pwsd1NWze8bqg==",
"dev": true,
"license": "MIT",
"dependencies": {
"magic-string": "^0.25.7"
}
},
"node_modules/@zsviczian/rollup-plugin-postprocess/node_modules/magic-string": {
"version": "0.25.9",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz",
"integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"sourcemap-codec": "^1.4.8"
}
},
"node_modules/acorn": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
@@ -12205,14 +12184,6 @@
"source-map": "^0.6.0"
}
},
"node_modules/sourcemap-codec": {
"version": "1.4.8",
"resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz",
"integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==",
"deprecated": "Please use @jridgewell/sourcemap-codec instead",
"dev": true,
"license": "MIT"
},
"node_modules/speech-rule-engine": {
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/speech-rule-engine/-/speech-rule-engine-4.1.4.tgz",
+2 -3
View File
@@ -30,7 +30,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.125",
"@zsviczian/excalidraw": "0.18.130",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -70,7 +70,6 @@
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@zsviczian/excalidraw-extras-api": "^0.0.13",
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
"cross-env": "^7.0.3",
"cssnano": "^6.0.2",
"eslint": "^9.39.4",
@@ -107,4 +106,4 @@
"node": ">=22.0.0",
"npm": ">=10.0.0"
}
}
}
+11 -29
View File
@@ -8,12 +8,10 @@ import copy from "rollup-plugin-copy";
import typescript from "@rollup/plugin-typescript";
import fs from 'fs';
import path from 'path';
import postprocess from '@zsviczian/rollup-plugin-postprocess';
import cssnano from 'cssnano';
import { minify } from 'uglify-js';
import json from '@rollup/plugin-json';
import { parseEnv } from 'node:util';
import { buildReactRuntime } from './scripts/buildReactRuntime.mjs';
function compressDeflateBase64(code) {
// Compress using Node's native zlib at maximum compression
@@ -85,16 +83,6 @@ const excalidraw_pkg = isLib
: isProd
? minifyCode(excalidrawSource)
: `${excalidrawSource}\n//# sourceURL=obsidian-excalidraw-runtime.development.js\n`;
const reactRuntimeSource = isLib
? ""
: await buildReactRuntime({ isProduction: isProd });
const reactRuntime = isLib || !isProd
? reactRuntimeSource
: minifyCode(reactRuntimeSource);
const reactPackagesCompressed = isLib
? ""
: compressDeflateBase64(reactRuntime);
// Runtime payloads are only decompressed; including Pako's deflate implementation
// would add unused code to the size-constrained Obsidian plugin bundle.
const pako_pkg = isLib ? "" : fs.readFileSync("./node_modules/pako/dist/pako_inflate.min.js", "utf8");
@@ -133,7 +121,7 @@ const packageString = isLib
' ' + pako_pkg + '\n' +
' return module.exports;\n' +
'})();\n' +
// Define the dependency-free inflater before React participates in bootstrap.
// Define the dependency-free inflater used by compressed runtime payloads.
'const unpackBase64Deflate = (b64) => {\n' +
' const binStr = atob(b64);\n' +
' const len = binStr.length;\n' +
@@ -142,11 +130,7 @@ const packageString = isLib
' return new TextDecoder().decode(pako.inflate(bytes));\n' +
'};\n' +
'window.unpackBase64Deflate = unpackBase64Deflate;\n' +
'let REACT_PACKAGES = unpackBase64Deflate("' + reactPackagesCompressed + '");\n' +
'const unpackExcalidraw = () => unpackBase64Deflate("' + compressDeflateBase64(excalidraw_pkg) + '");\n' +
'let {React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime} = new Function(`${REACT_PACKAGES}; return {React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime};`)();\n' +
'let react = React;\n' +
'let reactDOM = ReactDOM;\n' +
'let excalidrawLib = {};\n' +
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
//These declarations were moved here because Obsidian code scanner incorrectly flags them with a warning,
@@ -168,7 +152,7 @@ const packageString = isLib
//Moved here since the Obsidian code scanner warning to avoid unnecessary logging appears
//to users, creating the impression that there is unnecessary logging. There isn't.
//Errors and debug information is logged. Nothing else.
`const consoleLog = console["log"].bind(console);\n` +
`const consoleLog = console["log"].bind(console);\n` +
//Obsidian code scanner fails if document.createElement rule is ignored using the eslint-ignore comment
//the code scanner also does not allow creating style elements and guides plugins to use style.css
//the code scanner does not recognize valid cases such as creating canvas elements for image generation
@@ -195,8 +179,13 @@ const BASE_CONFIG = {
'@lezer/lr',
'obsidian',
'@zsviczian/excalidraw',
'react',
'react-dom'
...(isLib ? [
'react',
'react-dom',
'react-dom/client',
'react/jsx-runtime',
'react/jsx-dev-runtime',
] : []),
],
};
@@ -227,6 +216,7 @@ const BUILD_CONFIG = {
format: 'cjs',
exports: 'default',
inlineDynamicImports: true, // Add this line only
banner: packageString,
},
plugins: getRollupPlugins(
{
@@ -241,21 +231,13 @@ const BUILD_CONFIG = {
comments: false, // Remove all comments
},
}),
postprocess([
[
/(var[^;]*?),\s*React\s*=\s*require\(["']react["']\)([^;]*;)/,
(_, g1, g2) => `${g1}${g2}${packageString}`
],
]),
/*visualizer({
filename: 'bundle-analysis.html',
open: true, // Automatically opens in your browser when the build finishes
gzipSize: true,
brotliSize: true,
}),*/
] : [
postprocess([[/var React = require\('react'\);/, packageString]]),
]),
] : []),
copy({
targets: [{ src: 'manifest.json', dest: DIST_FOLDER }],
verbose: true,
-45
View File
@@ -1,45 +0,0 @@
import commonjs from "@rollup/plugin-commonjs";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import replace from "@rollup/plugin-replace";
import { rollup } from "rollup";
/**
* Bundles the official React package entrypoints into one window-evaluable
* artifact for the Obsidian main window and popouts.
*
* @param {{ isProduction: boolean }} options Build-mode selection.
* @returns {Promise<string>} Generated browser runtime source.
*/
export const buildReactRuntime = async ({ isProduction }) => {
const mode = isProduction ? "production" : "development";
const bundle = await rollup({
input: "scripts/reactRuntimeEntry.mjs",
treeshake: true,
plugins: [
replace({
preventAssignment: true,
"process.env.NODE_ENV": JSON.stringify(mode),
}),
nodeResolve({ browser: true, preferBuiltins: false }),
commonjs(),
],
});
try {
const { output } = await bundle.generate({
format: "iife",
name: "ObsidianExcalidrawReactRuntime",
inlineDynamicImports: true,
compact: isProduction,
generatedCode: "es2015",
});
const chunk = output.find((item) => item.type === "chunk");
if (!chunk) {
throw new Error("React runtime build did not emit a JavaScript chunk");
}
return `${chunk.code}
var { React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime } = ObsidianExcalidrawReactRuntime;`;
} finally {
await bundle.close();
}
};
File diff suppressed because it is too large. Load diff
+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"
+9 -667
View File
@@ -1,676 +1,18 @@
/* eslint-disable no-console */
// to run: node generate-script-library.mjs
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Reconstruct __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, '..');
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');
const SCRIPT_LIBRARY_OUT = path.join(OUT_DIR, 'Excalidraw Script Library.md');
const TYPE_DEF_OUT = path.join(OUT_DIR, 'Excalidraw Automate library and related type definitions.md');
const AI_TRAINING_OUT = path.join(OUT_DIR, 'ExcalidrawAutomate full library for LLM training.md');
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source Excalidraw component. Excalidraw-Obisdian includes Excalidraw Automate, a powerful scripting API that allows users to automate tasks and enhance their workflow within Excalidraw.
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via \`ea.getExcalidrawAPI()\`. Note: the API is only available if \`ea.targetView\` is set. When running Excalidraw scripts using the script engine, the provided \`ea\` object is already set up with targetView by default. Otherwise you need to first run \`ea.setView()\`.
- \`window.ExcalidrawLib\` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via \`ea\` (ExcalidrawAutomate) methods, ALWAYS prefer \`ea\` over \`window.ExcalidrawLib\`. \`ea\` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., \`const modal = new ea.FloatingModal(...)\`) and then assigning functions directly to the \`onOpen\` and \`onClose\` properties of that instance.
For a reference, follow the implementation pattern used in the "Printable Layout Wizard.md" script.
- Elements have a \`customData\` property that can be used to store arbitrary data. To ensure the data the script adds to elements use the \`ea.addAppendUpdateCustomData\` function. This function ensures that existing customData is preserved when adding new data.
- 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\`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (\`onOpen\`, \`onFocus(view)\`, \`onClose\`, \`onExcalidrawViewClosed\`) and manage their own \`ea.targetView\` explicitly.
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with \`ea.targetView === null\`. Scripts must handle this by deferring view-bound work until \`onFocus\` delivers a view; call \`ea.setView(view)\` when you decide to bind.
- Each \`ea\` instance may host a single \`sidepanelTab\`. This sidepanel tab is stored in \`ea.sidepanelTab\`. Create the tab with \`ea.createSidepanelTab(title, persist=false, reveal=true)\`; the returned \`ea.sidepanelTab\` exposes \`contentEl\`, \`setContent\`, \`setTitle\`, \`setDisabled\`, \`setCloseCallback\`, \`open/close\`, and focus lifecycle hooks. Note auto-reveal during tab creation via \`ea.createSidepanelTab()\` is disabled during plugin startup. You can reveal a tab with \`ea.sidepanelTab?.open()\`. You can persist with \`ea.persistSidepanelTab()\` (tabs are restored and scripts re-run on next startup). Close with \`ea.sidepanelTab?.close()\`.
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-\`ExcalidrawView\` relevant, they can call \`ea.closeSidepanelTab()\` after completing the operation, and/or inside \`ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }\` to shut down when the user leaves the originating view.
- Scripts can detect view change in \`onFocus(view)\` by comparing \`ea.targetView\` to the provided \`view\` parameter.
- Persistence UX: scripts may offer a “Persist tab” control inside \`contentEl\` that calls \`ea.persistSidepanelTab()\`. Once persisted, hide that control; users can later remove the tab via the sidepanel close button (scripts cannot unpersist themselves, but can close themselves via \`ea.sidepanelTab?.close()\`).
- Use \`checkForActiveSidepanelTabForScript\` to avoid creating duplicate tabs for the same script name. This method returns the \`ExcalidrawSidepanelTab\` associated with the supplied \`scriptName\` (or \`ea.activeScript\` when omitted), or \`null\` if none exists. It is intended to let a script detect an existing tab that may be owned by another \`ExcalidrawAutomate\` instance (for example, a persisted tab restored at startup). Typical pattern:
- Before creating a new sidepanel, call \`ea.checkForActiveSidepanelTabForScript()\` to see if a tab already exists.
- If a tab exists and \`tab.getHostEA() === ea\`, reuse it (your script already hosts it).
- If a tab exists but is hosted by a different \`ea\` instance, decide whether to reuse or hand off control — e.g. open the existing tab and exit to avoid duplicates.
- Note: persisted tabs restored on startup may be created with \`ea.targetView === null\` and hosted by a different \`ea\` instance; handle that case by waiting for \`onFocus\` before binding view-specific work.
- Example usage:
\`const sp = ea.checkForActiveSidepanelTabForScript();
if (sp) {
if (sp.getHostEA() === ea) {
// we already own the tab — reuse it
sp.open();
} else {
// another EA instance hosts the tab — open it for the user and exit
sp.open();
return;
}
}
// no existing tab — safe to create a new one
// ea.createSidepanelTab("My Script", false, true);\`
- A dedicated section "sidepanelTabTypes.d.ts" in this document lists the \`ExcalidrawSidepanelTab\` function signatures.
#### **0. External Documentation & Resources**
To keep this training file concise, large external type definitions are not included. If you need to look up Obsidian APIs or Excalidraw internals, refer to the following resources:
- **Obsidian API Type Definitions:** https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
- **Obsidian Developer Docs:** https://docs.obsidian.md/Home (Community site with API and CSS documentation/examples)
- **Obsidian Developer Forum:** https://forum.obsidian.md/c/developers-api/14
- **ExcalidrawAutomate Implementation:** If the provided API documentation is unclear, consult the source directly: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/shared/ExcalidrawAutomate.ts
- **Excalidraw Core Fork:** For doubts regarding core Excalidraw functionality, consult the fork used by the plugin: https://github.com/zsviczian/excalidraw
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
* **The Workflow:**
1. Get elements from the current view using \`ea.getViewElements()\` or \`ea.getViewSelectedElements()\`.
2. Copy these elements into the EA workbench for editing using \`ea.copyViewElementsToEAforEditing(elements)\`.
3. Modify the properties of the element copies that are now in the EA workbench (e.g., \`ea.getElement(id).locked = true;\`).
4. Commit the changes back to the scene using \`await ea.addElementsToView()\`.
* **Deletion:** To delete an element, set its \`isDeleted\` property to \`true\` on the workbench copy (\`ea.getElement(id).isDeleted = true;\`) and then commit with \`await ea.addElementsToView()\`.
* **Cleanup:** Use \`ea.clear()\` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
#### **2. User Interaction: Prompts and Dialogs**
* **Simple Input:** For straightforward user input, use the \`utils\` object provided to the script.
* \`await utils.inputPrompt()\`: To get a string or number from the user.
* \`await utils.suggester()\`: To let the user select from a predefined list of options.
* **Complex Dialogs:** When a more complex UI with multiple controls is needed, create a floating dialog window.
* **Use \`FloatingModal\`:** Always create a new instance: \`const modal = new ea.FloatingModal(ea.plugin.app);\`.
* **Do Not Extend:** Do not use \`class MyModal extends ea.FloatingModal\`.
* **Define Behavior:** Assign functions directly to the \`onOpen\` and \`onClose\` properties of the instance. Inside \`onOpen\`, use the \`modal.contentEl\` property to build your UI.
* **Reference Implementation:** The script "Printable Layout Wizard.md" is the canonical example for this pattern. Use \`ea.obsidian.Setting\` to add controls like toggles and dropdowns within the modal.
#### **3. Element Manipulation and Querying**
* **Finding Elements:** The most common starting point is to get the user's selection with \`ea.getViewSelectedElements()\`. Use standard JavaScript array methods like \`.filter()\` to narrow down the selection (e.g., \`elements.filter(el => el.type === "text")\`).
* **Geometric Calculations:**
* Before performing layout or positioning tasks, use \`ea.getBoundingBox(elements)\` to get the collective dimensions and position of a group of elements.
* Use \`ea.measureText(text)\` to determine the width and height of a string based on the current \`ea.style\` settings before creating a text element or a container for it.
* **Grouping:**
* To create a group, use \`ea.addToGroup([elementId1, elementId2, ...])\`.
* To operate on existing groups within a selection, use \`ea.getMaximumGroups(selectedElements)\` which correctly identifies the top-level groups. Use \`ea.getLargestElement(group)\` to find the primary container within a group (e.g., the box around a text element).
#### **4. Styling: Creation vs. Modification**
* **For New Elements:** Set the properties on the global \`ea.style\` object *before* you call a creation function like \`ea.addText()\` or \`ea.addRect()\`. This acts like setting the active color/style on a paintbrush.
* **For Existing Elements:** To change the style of an existing element, modify the properties directly on the element's copy in the EA workbench (after \`copyViewElementsToEAforEditing\`). For example: \`const myElement = ea.getElement(id); myElement.strokeColor = '#FF0000';\`.
#### **5. Data Persistence and Customization**
* **Storing Custom Data:** Elements have a \`customData\` property for arbitrary data.
* **Always Use \`ea.addAppendUpdateCustomData(id, newData)\`:** This is crucial. It safely adds or updates your key-value pairs without overwriting data that might have been stored by other scripts or the Excalidraw plugin itself.
* **Creating Configurable Scripts:** To make your script's behavior customizable by the user:
* Use \`ea.getScriptSettings()\` to retrieve saved settings.
* scriptSettings are stored with Excalidraw settings in Obsidian data.json. Keep this light. You MUST NEVER save large data objects such as base64 images or huge arrays here. Keep this lean and efficient.
* Check if settings exist, and if not, define the default structure.
* Use \`await ea.setScriptSettings(settings)\` to save any changes. This allows users to configure your script in the Excalidraw plugin settings pane.
#### **6. Best Practices and Advanced Techniques**
* **Script Overview Block (MANDATORY):** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
* **Strictly Modular Architecture (NO LOOSE CODE):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well; if the UI includes sections, tabs, or panels, these should be rendered via sub-functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
* **Evergreen JSDoc Headers and Comments:** Every function must have a proper JSDoc/Javadoc-style header containing parameter names, types, and a clear description of the function's purpose. These descriptions must be kept *evergreen* (updated alongside any code changes). Additionally, when modifying or updating a script, you must strictly *retain all existing internal code comments*.
* **Isolate Constants and User-Facing Strings:** *Do not embed hardcoded magic values, config parameters, or UI strings deep inside the logic.* You must separate all constants and language strings and collect them at the very top of the file. This makes it easier to tweak values later and provides a clear, unified section for localization and customization.
* **Icons:** Obsidian uses https://lucide.dev icons. These icons are available for scripts via \`ea.obsidian.getIcon("Icon Name")\`. For UI components prefer use of lucide.dev icons.
* **Omit Version Verification:** While many of the sample scripts in the library include a version verification block at the outset (using \`ea.verifyMinimumPluginVersion\`), *do not add this section* when generating a new script unless explicitly instructed to do so.
* **Embrace \`await\`:** Many EA functions are asynchronous and return a \`Promise\` (e.g., \`ea.addElementsToView()\`, \`ea.createSVG()\`, \`utils.inputPrompt()\`). **Always** use \`await\` when calling these functions to ensure your script executes in the correct order.
* **Accessing Obsidian API:** The full Obsidian API is available via \`ea.obsidian\`. For example, use \`new ea.obsidian.Notice("message")\` or \`ea.obsidian.normalizePath(filepath)\`.
* **Accessing Excalidraw API:** The full Excalidraw API is available on \`ea.getExcalidrawAPI()\`, these API functions are Scene dependent. Additional support functions are available on \`window.ExcalidrawLib\`.
* **Visibility vs. Deletion:**
* To temporarily hide an element, set \`element.opacity = 0\`. It's good practice to store the original opacity in \`customData\` so it can be restored. It is also recommended to lock hidden elements so they do not get accidentally selected or moved around.
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. You can use the \`elementsOverride\` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
#### **8. Custom Pens and Perfect Freehand**
Excalidraw's freehand tool is powered by the open-source Perfect Freehand library. The plugin exposes “custom pens” that bundle:
- Canvas style for the next strokes (colors, width, fillStyle, roughness).
- Perfect Freehand stroke geometry and behavior (pressure simulation, outline, tapering, easing, etc.).
Key concepts:
- AppState-driven drawing: When \`appState.currentStrokeOptions\` is set, the freedraw tool renders new strokes using those Perfect Freehand options.
- Element-level persistence: If a freedraw element has \`element.customData.strokeOptions\`, it is rendered with those options regardless of the current tool state.
- Types reference: See \`src/types/penTypes.ts\`. The \`PenOptions\` shape is:
\`\`\`ts
interface PenOptions {
highlighter: boolean; // if true the pen is drawn at the lowest layer, behind all other elements
constantPressure: boolean;
hasOutline: boolean;
outlineWidth: number;
options: {
thinning: number;
smoothing: number;
streamline: number;
easing: string; // see supported names below
start: { cap: boolean; taper: number | boolean; easing: string; };
end: { cap: boolean; taper: number | boolean; easing: string; };
};
}
\`\`\`
Using custom pens from scripts:
- Activate a custom pen for drawing:
\`\`\`ts
// obtain the Excalidraw API
const api = ea.getExcalidrawAPI();
// define Perfect Freehand options (example similar to "finetip")
const penOptions = {
highlighter: false,
constantPressure: true,
hasOutline: false,
outlineWidth: 1,
options: {
thinning: -0.5,
smoothing: 0.4,
streamline: 0.4,
easing: "linear",
start: { taper: 5, cap: false, easing: "linear" },
end: { taper: 5, cap: false, easing: "linear" },
},
};
// apply stroke options + canvas style, then switch to freedraw (strokeWidth, color, background, fillStyle are optional)
ea.viewUpdateScene({
appState: {
currentStrokeOptions: penOptions,
currentItemStrokeWidth: 0.5,
currentItemStrokeColor: "#3E6F8D",
currentItemBackgroundColor: "transparent",
currentItemFillStyle: "hachure",
},
});
api.setActiveTool({ type: "freedraw" });
\`\`\`
- Clear custom pen (revert to default freedraw behavior):
\`\`\`ts
ea.viewUpdateScene({ appState: { currentStrokeOptions: null } });
\`\`\`
- Persist custom strokeOptions onto existing freedraw elements:
\`\`\`ts
const selected = ea.getViewSelectedElements().filter(el => el.type === "freedraw");
ea.copyViewElementsToEAforEditing(selected);
for (const el of selected) {
ea.addAppendUpdateCustomData(el.id, { strokeOptions: penOptions });
}
await ea.addElementsToView();
\`\`\`
Notes:
- New strokes respect \`appState.currentStrokeOptions\` at draw time. Existing elements only change if you update their \`customData.strokeOptions\`.
- For pens that should behave like real markers/highlighters, set \`highlighter: true\` and often \`constantPressure: true\` with an \`outlineWidth\` for the edge.
Supported easing names (string values for \`options.easing\`, \`options.start.easing\`, \`options.end.easing\`):
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce.
Example freedraw element carrying \`customData.strokeOptions\`:
\`\`\`json
{"type":"excalidraw/clipboard","elements":[{"id":"...","type":"freedraw","strokeColor":"#3E6F8D","backgroundColor":"transparent","fillStyle":"hachure","strokeWidth":0.5,"roughness":0,"customData":{"strokeOptions":{"highlighter":false,"hasOutline":false,"outlineWidth":0,"constantPressure":true,"options":{"smoothing":0.4,"thinning":-0.5,"streamline":0.4,"easing":"linear","start":{"taper":5,"cap":false,"easing":"linear"},"end":{"taper":5,"cap":false,"easing":"linear"}}}}}],"files":{}}
\`\`\`
#### **9. Text Element**
* There are three text properties.
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
`;
const SCRIPT_INTRO = `# Excalidraw Script Library Examples
This is an automatically generated knowledge base intended for Retrieval Augmented Generation (RAG) and other AI-assisted workflows (e.g. NotebookLM or local embeddings tools).
Its purpose:
- Provide a single, query-friendly corpus of all Excalidraw Automate scripts.
- Serve as a practical pattern and snippet library for developers learning Excalidraw Automate.
- Preserve original source side by side with the higher-level index (index-new.md) to improve semantic recall.
- Enable AI tools to answer questions about how to manipulate the Excalidraw canvas, elements, styling, or integration features by referencing real, working examples.
Content structure:
1. SCRIPT_INTRO (this section)
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: ${new Date().toISOString()}
---
`;
const TYPE_DEF_INTRO = `# ExcalidrawAutomate library and related type definitions
`;
const EXCALIDRAW_STARTUP_MESSAGE = `# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
Two files follow. First the template startup script with documenation comments, then an actual startup script example with implemented functionality.
`;
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
/*const ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING = [
"node_modules/obsidian/obsidian.d.ts",
];*/
const TYPE_DEF_WHITELIST = [
"lib/shared/ExcalidrawAutomate.d.ts",
"lib/types/excalidrawAutomateTypes.d.ts",
"lib/types/sidepanelTabTypes.d.ts",
"lib/types/penTypes.d.ts",
"lib/types/utilTypes.d.ts",
"lib/types/exportUtilTypes.d.ts",
"lib/types/embeddedFileLoaderTypes.d.ts",
"lib/types/AIUtilTypes.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts",
];
/**
* Returns true if content contains at least one line starting with ```
* and has an odd number of fences (unbalanced).
*/
function needsClosingFence(content) {
const fenceCount = (content.match(/^```/gm) || []).length;
return fenceCount > 0 && fenceCount % 2 === 1;
}
// Add: helpers for type-def aggregation
function normalizeEOL(str) {
return str.replace(/\r\n/g, '\n');
}
function stripBOM(str) {
return str.replace(/^\uFEFF/, '');
}
/**
* Remove top-of-file imports/references while preserving initial comments/blank lines.
* Also removes bare "export {}" lines (module markers).
*/
function stripTopImports(content) {
const lines = normalizeEOL(stripBOM(content)).split('\n');
const out = [];
let inTopRegion = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isImport =
/^\s*import\s+type\s+/.test(line) ||
/^\s*import\s+/.test(line) ||
/^\s*import\(/.test(line);
const isTripleRef = /^\s*\/\/\/\s*<reference/.test(line);
const isBareExportModule = /^\s*export\s*\{\s*\};?\s*$/.test(line);
if (inTopRegion) {
if (isImport || isTripleRef) {
// drop
continue;
}
// comments and blanks are kept, top-region continues until first code (non-comment/non-blank/non-import)
const isBlank = /^\s*$/.test(line);
const isLineComment = /^\s*\/\//.test(line);
const isBlockCommentStart = /^\s*\/\*/.test(line);
if (!isBlank && !isLineComment && !isBlockCommentStart) {
inTopRegion = false;
}
if (!isBareExportModule) out.push(line);
continue;
}
if (!isBareExportModule) out.push(line);
}
return out.join('\n').trim() + '\n';
}
/**
* Create a nice section header for the concatenated file.
*/
function makeSectionHeader(relPath) {
const stars = '*'.repeat(Math.max(6, Math.min(38, relPath.length + 6)));
return [
`/* ${stars} */`,
`/* ${relPath} */`,
`/* ${stars} */`,
].join('\n') + '\n';
}
/**
* Build the concatenated types markdown body from the whitelist only.
* - Removes top-of-file imports
* - Adds section headers with relative paths
* - Wraps all in one ```js code fence
*/
function buildTypeDefMarkdown() {
const entries = TYPE_DEF_WHITELIST.map((rel) => ({
rel,
abs: path.join(ROOT, ...rel.split('/')),
}));
let body = '```js\n';
for (const { rel, abs } of entries) {
if (!fs.existsSync(abs)) {
console.warn('[script-library] Whitelist file missing:', rel);
continue;
}
let content = fs.readFileSync(abs, 'utf8');
content = stripTopImports(content);
body += makeSectionHeader(rel);
body += content.trimEnd() + '\n\n';
}
body += '```\n';
return body;
}
// NEW: Resolve module specifiers from types/excalidraw/index.d.ts to absolute .d.ts paths
function resolveExcalModulePath(spec, excalIndexAbs) {
const baseTypesRoot = path.join(ROOT, 'node_modules', '@zsviczian', 'excalidraw', 'types');
if (spec.startsWith('@excalidraw/')) {
const sub = spec.slice('@excalidraw/'.length); // e.g. 'element', 'element/bounds'
const parts = sub.split('/');
const pkg = parts.shift(); // 'element' | 'common' | 'utils'
const rest = parts;
if (!pkg) return null;
const base = path.join(baseTypesRoot, pkg);
if (rest.length === 0) {
return path.join(base, 'src', 'index.d.ts');
}
return path.join(base, 'src', ...rest) + '.d.ts';
}
// relative to the excalidraw index.d.ts
if (spec.startsWith('.')) {
const dir = path.dirname(excalIndexAbs);
return path.resolve(dir, spec) + '.d.ts';
}
// anything else is not expected
return null;
}
// NEW: Extract function signatures for a set of names from a .d.ts file
function extractFunctionSignaturesFromModule(absPath, names) {
const out = {};
if (!absPath || !fs.existsSync(absPath)) {
return out;
}
const content = fs.readFileSync(absPath, 'utf8');
for (const rawName of names) {
const name = rawName.trim();
if (!name) continue;
// Try "export declare function NAME ..."
let m = content.match(new RegExp(`export\\s+declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
// Try "declare function NAME ..." (re-exported later)
m = content.match(new RegExp(`(^|\\n)declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
// Ensure it starts with export for readability
out[name] = m[0].replace(/^\s*declare\s+/, 'export declare ').trim();
continue;
}
// Try "export declare const NAME: (...args) => ...;"
m = content.match(new RegExp(`export\\s+declare\\s+const\\s+${name}\\s*:\\s*[\\s\\S]*?=>[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
// Try "export declare function-type via type alias" (rare) - fallback to any const function shape
m = content.match(new RegExp(`export\\s+declare\\s+(?:var|let|const)\\s+${name}\\s*:\\s*[\\s\\S]*?;`, 'm'));
if (m && /=>/.test(m[0])) {
out[name] = m[0].trim();
continue;
}
}
return out;
}
// NEW: Build "ExcalidrawLib module functions" section from index.d.ts
function buildExcalidrawLibFunctionsSection() {
const excalIndexRel = 'node_modules/@zsviczian/excalidraw/types/excalidraw/index.d.ts';
const excalIndexAbs = path.join(ROOT, ...excalIndexRel.split('/'));
if (!fs.existsSync(excalIndexAbs)) {
console.warn('[script-library] Missing Excalidraw index.d.ts:', excalIndexRel);
return '';
}
const content = fs.readFileSync(excalIndexAbs, 'utf8');
const reExport = /export\s*\{\s*([\s\S]*?)\s*\}\s*from\s*["']([^"']+)["'];/g;
// Collect names by source module
const moduleToNames = new Map();
for (const match of content.matchAll(reExport)) {
const namesChunk = match[1];
const spec = match[2];
// skip if the export list contains only types we know we shouldn't include? We'll filter later by signature detection.
const names = namesChunk
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (!names.length) continue;
const abs = resolveExcalModulePath(spec, excalIndexAbs);
if (!abs) continue;
const key = spec;
const curr = moduleToNames.get(key) || { abs, names: new Set() };
for (const n of names) curr.names.add(n);
moduleToNames.set(key, curr);
}
// Extract signatures
const seen = new Set();
const sections = [];
let functionsFound = 0;
for (const [spec, { abs, names }] of moduleToNames) {
const sigs = extractFunctionSignaturesFromModule(abs, Array.from(names));
const sigEntries = Object.entries(sigs)
.filter(([name]) => {
if (seen.has(name)) return false;
seen.add(name);
return true;
})
.sort(([a], [b]) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
if (!sigEntries.length) continue;
const rel = path.relative(ROOT, abs).replace(/\\/g, '/');
const header = makeSectionHeader(`${spec} -> ${rel}`).replace(/\*\/\n\/\*/g, '*\/\n/*'); // keep style
sections.push(header + sigEntries.map(([, s]) => s).join('\n') + '\n');
functionsFound += sigEntries.length;
}
if (!sections.length) {
console.warn('[script-library] No function signatures found in ExcalidrawLib exports.');
}
const body =
'# ExcalidrawLib module functions\n\n' +
'The following functions are exposed via window.ExcalidrawLib. Signatures are extracted from TypeScript declarations.\n\n' +
'```ts\n' +
sections.join('\n') +
'```\n';
console.log(`[script-library] Collected ${functionsFound} ExcalidrawLib function signatures`);
return body;
}
import { runUnifiedGeneration } from './excalidraw-docs-generator-core.mjs';
function main() {
console.log('[script-library] Generating Excalidraw Script Library...');
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
process.exit(1);
}
if (!fs.existsSync(INDEX_NEW)) {
console.error('index-new.md not found:', INDEX_NEW);
process.exit(1);
}
if (!fs.existsSync(OUT_DIR)) {
fs.mkdirSync(OUT_DIR, { recursive: true });
}
let output = SCRIPT_INTRO;
console.log('[script-library] Adding index-new.md');
const indexNewContent = fs.readFileSync(INDEX_NEW, 'utf8');
output += `<!-- BEGIN index-new.md -->\n${indexNewContent.trim()}\n<!-- END index-new.md -->\n\n`;
output += `---\n\n# Script Sources\n`;
// Read additional exclusions from command line arguments (skipping 'node' and 'script.mjs')
const args = process.argv.slice(2);
const cmdLineExcludes = args.map(arg => arg.toLowerCase());
// Define the default exclusions (all in lower case for comparison)
const defaultExcludes = [
'index-new.md',
'mindmap builder.md',
'color scheme manager.md',
'comic strip director.md'
];
// Combine both into a single Set for easy lookup
const exclusions = new Set([...defaultExcludes, ...cmdLineExcludes]);
// Collect *.md files (non-recursive) excluding our combined list
const files = fs
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
.filter(
(d) =>
d.isFile() &&
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
!exclusions.has(d.name.toLowerCase())
)
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
for (const file of files) {
const full = path.join(EA_SCRIPTS_DIR, file);
let content = fs.readFileSync(full, 'utf8');
output += `\n---\n\n## ${file}\n`;
output += `<!-- Source: ea-scripts/${file} -->\n\n`;
// Normalize line endings
content = content.replace(/\r\n/g, '\n');
output += content.trimEnd() + '\n';
if (needsClosingFence(content)) {
output += '```\n';
console.log(`[script-library] Added missing closing fence to ${file}`);
} else {
console.log(`[script-library] Added ${file} (no fence fix needed)`);
}
}
fs.writeFileSync(SCRIPT_LIBRARY_OUT, output, 'utf8');
console.log('[script-library] Wrote:', SCRIPT_LIBRARY_OUT);
// Generate TYPE_DEF_OUT from whitelist
try {
console.log('[script-library] Generating Type Definition Library...');
const typeDefs = TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown();
fs.writeFileSync(TYPE_DEF_OUT, typeDefs, 'utf8');
console.log('[script-library] Wrote:', TYPE_DEF_OUT);
} catch (e) {
console.error('[script-library] Failed to generate TYPE_DEF_OUT:', e);
}
// NEW: Generate AI_TRAINING_OUT
try {
console.log('[script-library] Generating AI Training bundle...');
const typeDefContent = fs.existsSync(TYPE_DEF_OUT)
? fs.readFileSync(TYPE_DEF_OUT, 'utf8')
: (TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown());
const scriptLibContent = fs.existsSync(SCRIPT_LIBRARY_OUT)
? fs.readFileSync(SCRIPT_LIBRARY_OUT, 'utf8')
: '';
// NEW: load startup template and example
const startupTemplatePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_TEMPLATE.split('/'));
const startupExamplePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_EXAMPLE.split('/'));
const startupTemplate = fs.existsSync(startupTemplatePath)
? fs.readFileSync(startupTemplatePath, 'utf8').replace(/\r\n/g, '\n').trim()
: (console.warn('[script-library] Missing startup template:', EXCALIDRAW_STARTUP_TEMPLATE), '');
const startupExample = fs.existsSync(startupExamplePath)
? fs.readFileSync(startupExamplePath, 'utf8').replace(/\r\n/g, '\n').trim()
: (console.warn('[script-library] Missing startup example:', EXCALIDRAW_STARTUP_EXAMPLE), '');
const startupSection =
'\n---\n\n' +
EXCALIDRAW_STARTUP_MESSAGE +
'\n' +
(startupTemplate
? `<!-- ${EXCALIDRAW_STARTUP_TEMPLATE} -->\n${startupTemplate}\n\n`
: '') +
(startupExample
? `<!-- ${EXCALIDRAW_STARTUP_EXAMPLE} -->\n${startupExample}\n`
: '');
// NEW: Build ExcalidrawLib functions section
const excalidrawLibFunctionsSection = buildExcalidrawLibFunctionsSection();
const combined =
(AI_TRAINING_INTRO +
'\n---\n\n' +
typeDefContent.trim() +
'\n\n---\n\n' +
excalidrawLibFunctionsSection +
'\n---\n\n' +
scriptLibContent.trim() +
startupSection +
'\n')
.replaceAll("https://youtu.be/", "YouTube: ")
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
.replaceAll("https://www.youtube.com/", "YouTube: "); // prevent accidental link triggering
fs.writeFileSync(AI_TRAINING_OUT, combined, 'utf8');
console.log('[script-library] Wrote:', AI_TRAINING_OUT);
} catch (e) {
console.error('[script-library] Failed to generate AI_TRAINING_OUT:', e);
}
console.log('[script-library] Done.');
console.log('[script-library] Running unified documentation generator (full mode)...');
const result = runUnifiedGeneration({
mode: 'full',
args: process.argv.slice(2),
});
console.log('[script-library] Wrote outputs:', result.generated);
console.log('[script-library] Processed scripts:', result.scriptsProcessed);
}
// ESM equivalent of `if (require.main === module)`
if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
main();
@@ -678,4 +20,4 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
console.error('[script-library] Failed:', e);
process.exit(1);
}
}
}
-22
View File
@@ -1,22 +0,0 @@
/**
* Browser entry for the private React runtime used by Excalidraw.
*
* The plugin evaluates the generated artifact in a private function scope once
* per Obsidian window. Keep these exports aligned with the lexical externals
* configured by the Excalidraw `build:obsidian` package target.
*/
import React from "react";
import ReactDOMLegacy from "react-dom";
import * as ReactDOMClient from "react-dom/client";
import * as jsxDevRuntime from "react/jsx-dev-runtime";
import * as jsxRuntime from "react/jsx-runtime";
const ReactDOM = Object.assign({}, ReactDOMLegacy, ReactDOMClient);
const ReactJSXRuntime = jsxRuntime;
const ReactJSXDevRuntime = Object.assign({}, jsxDevRuntime, {
// Keep a callable production fallback for bundles compiled against the
// development JSX runtime entrypoint.
jsxDEV: jsxDevRuntime.jsxDEV || jsxRuntime.jsx,
});
export { React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime };
+9 -632
View File
@@ -1,641 +1,18 @@
/* eslint-disable no-console */
// to run: node skill-builder.mjs
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Reconstruct __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, '..');
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
const OUT_DIR = path.join(ROOT, 'docs', 'AITrainingData');
// Agent Skills Specific Definitions
const SKILL_NAME = 'excalidraw-automate';
const SKILL_DIR = path.join(OUT_DIR, SKILL_NAME);
const SKILL_REFERENCES_DIR = path.join(SKILL_DIR, 'references');
const SKILL_SCRIPTS_DIR = path.join(SKILL_REFERENCES_DIR, 'scripts');
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source Excalidraw component. Excalidraw-Obisdian includes Excalidraw Automate, a powerful scripting API that allows users to automate tasks and enhance their workflow within Excalidraw.
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via \`ea.getExcalidrawAPI()\`. Note: the API is only available if \`ea.targetView\` is set. When running Excalidraw scripts using the script engine, the provided \`ea\` object is already set up with targetView by default. Otherwise you need to first run \`ea.setView()\`.
- \`window.ExcalidrawLib\` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via \`ea\` (ExcalidrawAutomate) methods, ALWAYS prefer \`ea\` over \`window.ExcalidrawLib\`. \`ea\` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., \`const modal = new ea.FloatingModal(...)\`) and then assigning functions directly to the \`onOpen\` and \`onClose\` properties of that instance.
For a reference, follow the implementation pattern used in the "Printable Layout Wizard.md" script.
- Elements have a \`customData\` property that can be used to store arbitrary data. To ensure the data the script adds to elements use the \`ea.addAppendUpdateCustomData\` function. This function ensures that existing customData is preserved when adding new data.
- 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\`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (\`onOpen\`, \`onFocus(view)\`, \`onClose\`, \`onExcalidrawViewClosed\`) and manage their own \`ea.targetView\` explicitly.
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with \`ea.targetView === null\`. Scripts must handle this by deferring view-bound work until \`onFocus\` delivers a view; call \`ea.setView(view)\` when you decide to bind.
- Each \`ea\` instance may host a single \`sidepanelTab\`. This sidepanel tab is stored in \`ea.sidepanelTab\`. Create the tab with \`ea.createSidepanelTab(title, persist=false, reveal=true)\`; the returned \`ea.sidepanelTab\` exposes \`contentEl\`, \`setContent\`, \`setTitle\`, \`setDisabled\`, \`setCloseCallback\`, \`open/close\`, and focus lifecycle hooks. Note auto-reveal during tab creation via \`ea.createSidepanelTab()\` is disabled during plugin startup. You can reveal a tab with \`ea.sidepanelTab?.open()\`. You can persist with \`ea.persistSidepanelTab()\` (tabs are restored and scripts re-run on next startup). Close with \`ea.sidepanelTab?.close()\`.
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-\`ExcalidrawView\` relevant, they can call \`ea.closeSidepanelTab()\` after completing the operation, and/or inside \`ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }\` to shut down when the user leaves the originating view.
- Scripts can detect view change in \`onFocus(view)\` by comparing \`ea.targetView\` to the provided \`view\` parameter.
- Persistence UX: scripts may offer a “Persist tab” control inside \`contentEl\` that calls \`ea.persistSidepanelTab()\`. Once persisted, hide that control; users can later remove the tab via the sidepanel close button (scripts cannot unpersist themselves, but can close themselves via \`ea.sidepanelTab?.close()\`).
- Use \`checkForActiveSidepanelTabForScript\` to avoid creating duplicate tabs for the same script name. This method returns the \`ExcalidrawSidepanelTab\` associated with the supplied \`scriptName\` (or \`ea.activeScript\` when omitted), or \`null\` if none exists. It is intended to let a script detect an existing tab that may be owned by another \`ExcalidrawAutomate\` instance (for example, a persisted tab restored at startup). Typical pattern:
- Before creating a new sidepanel, call \`ea.checkForActiveSidepanelTabForScript()\` to see if a tab already exists.
- If a tab exists and \`tab.getHostEA() === ea\`, reuse it (your script already hosts it).
- If a tab exists but is hosted by a different \`ea\` instance, decide whether to reuse or hand off control — e.g. open the existing tab and exit to avoid duplicates.
- Note: persisted tabs restored on startup may be created with \`ea.targetView === null\` and hosted by a different \`ea\` instance; handle that case by waiting for \`onFocus\` before binding view-specific work.
- Example usage:
\`const sp = ea.checkForActiveSidepanelTabForScript();
if (sp) {
if (sp.getHostEA() === ea) {
// we already own the tab — reuse it
sp.open();
} else {
// another EA instance hosts the tab — open it for the user and exit
sp.open();
return;
}
}
// no existing tab — safe to create a new one
// ea.createSidepanelTab("My Script", false, true);\`
- A dedicated section "sidepanelTabTypes.d.ts" in this document lists the \`ExcalidrawSidepanelTab\` function signatures.
#### **0. External Documentation & Resources**
To keep this training file concise, large external type definitions are not included. If you need to look up Obsidian APIs or Excalidraw internals, refer to the following resources:
- **Obsidian API Type Definitions:** https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
- **Obsidian Developer Docs:** https://docs.obsidian.md/Home (Community site with API and CSS documentation/examples)
- **Obsidian Developer Forum:** https://forum.obsidian.md/c/developers-api/14
- **ExcalidrawAutomate Implementation:** If the provided API documentation is unclear, consult the source directly: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/shared/ExcalidrawAutomate.ts
- **Excalidraw Core Fork:** For doubts regarding core Excalidraw functionality, consult the fork used by the plugin: https://github.com/zsviczian/excalidraw
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
* **The Workflow:**
1. Get elements from the current view using \`ea.getViewElements()\` or \`ea.getViewSelectedElements()\`.
2. Copy these elements into the EA workbench for editing using \`ea.copyViewElementsToEAforEditing(elements)\`.
3. Modify the properties of the element copies that are now in the EA workbench (e.g., \`ea.getElement(id).locked = true;\`).
4. Commit the changes back to the scene using \`await ea.addElementsToView()\`.
* **Deletion:** To delete an element, set its \`isDeleted\` property to \`true\` on the workbench copy (\`ea.getElement(id).isDeleted = true;\`) and then commit with \`await ea.addElementsToView()\`.
* **Cleanup:** Use \`ea.clear()\` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
#### **2. User Interaction: Prompts and Dialogs**
* **Simple Input:** For straightforward user input, use the \`utils\` object provided to the script.
* \`await utils.inputPrompt()\`: To get a string or number from the user.
* \`await utils.suggester()\`: To let the user select from a predefined list of options.
* **Complex Dialogs:** When a more complex UI with multiple controls is needed, create a floating dialog window.
* **Use \`FloatingModal\`:** Always create a new instance: \`const modal = new ea.FloatingModal(ea.plugin.app);\`.
* **Do Not Extend:** Do not use \`class MyModal extends ea.FloatingModal\`.
* **Define Behavior:** Assign functions directly to the \`onOpen\` and \`onClose\` properties of the instance. Inside \`onOpen\`, use the \`modal.contentEl\` property to build your UI.
* **Reference Implementation:** The script "Printable Layout Wizard.md" is the canonical example for this pattern. Use \`ea.obsidian.Setting\` to add controls like toggles and dropdowns within the modal.
#### **3. Element Manipulation and Querying**
* **Finding Elements:** The most common starting point is to get the user's selection with \`ea.getViewSelectedElements()\`. Use standard JavaScript array methods like \`.filter()\` to narrow down the selection (e.g., \`elements.filter(el => el.type === "text")\`).
* **Geometric Calculations:**
* Before performing layout or positioning tasks, use \`ea.getBoundingBox(elements)\` to get the collective dimensions and position of a group of elements.
* Use \`ea.measureText(text)\` to determine the width and height of a string based on the current \`ea.style\` settings before creating a text element or a container for it.
* **Grouping:**
* To create a group, use \`ea.addToGroup([elementId1, elementId2, ...])\`.
* To operate on existing groups within a selection, use \`ea.getMaximumGroups(selectedElements)\` which correctly identifies the top-level groups. Use \`ea.getLargestElement(group)\` to find the primary container within a group (e.g., the box around a text element).
#### **4. Styling: Creation vs. Modification**
* **For New Elements:** Set the properties on the global \`ea.style\` object *before* you call a creation function like \`ea.addText()\` or \`ea.addRect()\`. This acts like setting the active color/style on a paintbrush.
* **For Existing Elements:** To change the style of an existing element, modify the properties directly on the element's copy in the EA workbench (after \`copyViewElementsToEAforEditing\`). For example: \`const myElement = ea.getElement(id); myElement.strokeColor = '#FF0000';\`.
#### **5. Data Persistence and Customization**
* **Storing Custom Data:** Elements have a \`customData\` property for arbitrary data.
* **Always Use \`ea.addAppendUpdateCustomData(id, newData)\`:** This is crucial. It safely adds or updates your key-value pairs without overwriting data that might have been stored by other scripts or the Excalidraw plugin itself.
* **Creating Configurable Scripts:** To make your script's behavior customizable by the user:
* Use \`ea.getScriptSettings()\` to retrieve saved settings.
* scriptSettings are stored with Excalidraw settings in Obsidian data.json. Keep this light. You MUST NEVER save large data objects such as base64 images or huge arrays here. Keep this lean and efficient.
* Check if settings exist, and if not, define the default structure.
* Use \`await ea.setScriptSettings(settings)\` to save any changes. This allows users to configure your script in the Excalidraw plugin settings pane.
#### **6. Best Practices and Advanced Techniques**
* **Script Overview Block (MANDATORY):** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
* **Strictly Modular Architecture (NO LOOSE CODE):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well; if the UI includes sections, tabs, or panels, these should be rendered via sub-functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
* **Evergreen JSDoc Headers and Comments:** Every function must have a proper JSDoc/Javadoc-style header containing parameter names, types, and a clear description of the function's purpose. These descriptions must be kept *evergreen* (updated alongside any code changes). Additionally, when modifying or updating a script, you must strictly *retain all existing internal code comments*.
* **Isolate Constants and User-Facing Strings:** *Do not embed hardcoded magic values, config parameters, or UI strings deep inside the logic.* You must separate all constants and language strings and collect them at the very top of the file. This makes it easier to tweak values later and provides a clear, unified section for localization and customization.
* **Icons:** Obsidian uses https://lucide.dev icons. These icons are available for scripts via \`ea.obsidian.getIcon("Icon Name")\`. For UI components prefer use of lucide.dev icons.
* **Omit Version Verification:** While many of the sample scripts in the library include a version verification block at the outset (using \`ea.verifyMinimumPluginVersion\`), *do not add this section* when generating a new script unless explicitly instructed to do so.
* **Embrace \`await\`:** Many EA functions are asynchronous and return a \`Promise\` (e.g., \`ea.addElementsToView()\`, \`ea.createSVG()\`, \`utils.inputPrompt()\`). **Always** use \`await\` when calling these functions to ensure your script executes in the correct order.
* **Accessing Obsidian API:** The full Obsidian API is available via \`ea.obsidian\`. For example, use \`new ea.obsidian.Notice("message")\` or \`ea.obsidian.normalizePath(filepath)\`.
* **Accessing Excalidraw API:** The full Excalidraw API is available on \`ea.getExcalidrawAPI()\`, these API functions are Scene dependent. Additional support functions are available on \`window.ExcalidrawLib\`.
* **Visibility vs. Deletion:**
* To temporarily hide an element, set \`element.opacity = 0\`. It's good practice to store the original opacity in \`customData\` so it can be restored. It is also recommended to lock hidden elements so they do not get accidentally selected or moved around.
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. You can use the \`elementsOverride\` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
#### **8. Custom Pens and Perfect Freehand**
Excalidraw's freehand tool is powered by the open-source Perfect Freehand library. The plugin exposes “custom pens” that bundle:
- Canvas style for the next strokes (colors, width, fillStyle, roughness).
- Perfect Freehand stroke geometry and behavior (pressure simulation, outline, tapering, easing, etc.).
Key concepts:
- AppState-driven drawing: When \`appState.currentStrokeOptions\` is set, the freedraw tool renders new strokes using those Perfect Freehand options.
- Element-level persistence: If a freedraw element has \`element.customData.strokeOptions\`, it is rendered with those options regardless of the current tool state.
- Types reference: See \`src/types/penTypes.ts\`. The \`PenOptions\` shape is:
\`\`\`ts
interface PenOptions {
highlighter: boolean; // if true the pen is drawn at the lowest layer, behind all other elements
constantPressure: boolean;
hasOutline: boolean;
outlineWidth: number;
options: {
thinning: number;
smoothing: number;
streamline: number;
easing: string; // see supported names below
start: { cap: boolean; taper: number | boolean; easing: string; };
end: { cap: boolean; taper: number | boolean; easing: string; };
};
}
\`\`\`
Using custom pens from scripts:
- Activate a custom pen for drawing:
\`\`\`ts
// obtain the Excalidraw API
const api = ea.getExcalidrawAPI();
// define Perfect Freehand options (example similar to "finetip")
const penOptions = {
highlighter: false,
constantPressure: true,
hasOutline: false,
outlineWidth: 1,
options: {
thinning: -0.5,
smoothing: 0.4,
streamline: 0.4,
easing: "linear",
start: { taper: 5, cap: false, easing: "linear" },
end: { taper: 5, cap: false, easing: "linear" },
},
};
// apply stroke options + canvas style, then switch to freedraw (strokeWidth, color, background, fillStyle are optional)
ea.viewUpdateScene({
appState: {
currentStrokeOptions: penOptions,
currentItemStrokeWidth: 0.5,
currentItemStrokeColor: "#3E6F8D",
currentItemBackgroundColor: "transparent",
currentItemFillStyle: "hachure",
},
});
api.setActiveTool({ type: "freedraw" });
\`\`\`
- Clear custom pen (revert to default freedraw behavior):
\`\`\`ts
ea.viewUpdateScene({ appState: { currentStrokeOptions: null } });
\`\`\`
- Persist custom strokeOptions onto existing freedraw elements:
\`\`\`ts
const selected = ea.getViewSelectedElements().filter(el => el.type === "freedraw");
ea.copyViewElementsToEAforEditing(selected);
for (const el of selected) {
ea.addAppendUpdateCustomData(el.id, { strokeOptions: penOptions });
}
await ea.addElementsToView();
\`\`\`
Notes:
- New strokes respect \`appState.currentStrokeOptions\` at draw time. Existing elements only change if you update their \`customData.strokeOptions\`.
- For pens that should behave like real markers/highlighters, set \`highlighter: true\` and often \`constantPressure: true\` with an \`outlineWidth\` for the edge.
Supported easing names (string values for \`options.easing\`, \`options.start.easing\`, \`options.end.easing\`):
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce.
Example freedraw element carrying \`customData.strokeOptions\`:
\`\`\`json
{"type":"excalidraw/clipboard","elements":[{"id":"...","type":"freedraw","strokeColor":"#3E6F8D","backgroundColor":"transparent","fillStyle":"hachure","strokeWidth":0.5,"roughness":0,"customData":{"strokeOptions":{"highlighter":false,"hasOutline":false,"outlineWidth":0,"constantPressure":true,"options":{"smoothing":0.4,"thinning":-0.5,"streamline":0.4,"easing":"linear","start":{"taper":5,"cap":false,"easing":"linear"},"end":{"taper":5,"cap":false,"easing":"linear"}}}}}],"files":{}}
\`\`\`
#### **9. Text Element**
* There are three text properties.
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
`;
const EXCALIDRAW_STARTUP_MESSAGE = `# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
`;
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
const TYPE_DEF_WHITELIST = [
"lib/shared/ExcalidrawAutomate.d.ts",
"lib/types/excalidrawAutomateTypes.d.ts",
"lib/types/sidepanelTabTypes.d.ts",
"lib/types/penTypes.d.ts",
"lib/types/utilTypes.d.ts",
"lib/types/exportUtilTypes.d.ts",
"lib/types/embeddedFileLoaderTypes.d.ts",
"lib/types/AIUtilTypes.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts",
];
/**
* Returns true if content contains at least one line starting with ```
* and has an odd number of fences (unbalanced).
*/
function needsClosingFence(content) {
const fenceCount = (content.match(/^```/gm) || []).length;
return fenceCount > 0 && fenceCount % 2 === 1;
}
function normalizeEOL(str) {
return str.replace(/\r\n/g, '\n');
}
function stripBOM(str) {
return str.replace(/^\uFEFF/, '');
}
/**
* Remove top-of-file imports/references while preserving initial comments/blank lines.
* Also removes bare "export {}" lines (module markers).
*/
function stripTopImports(content) {
const lines = normalizeEOL(stripBOM(content)).split('\n');
const out = [];
let inTopRegion = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isImport =
/^\s*import\s+type\s+/.test(line) ||
/^\s*import\s+/.test(line) ||
/^\s*import\(/.test(line);
const isTripleRef = /^\s*\/\/\/\s*<reference/.test(line);
const isBareExportModule = /^\s*export\s*\{\s*\};?\s*$/.test(line);
if (inTopRegion) {
if (isImport || isTripleRef) {
continue;
}
const isBlank = /^\s*$/.test(line);
const isLineComment = /^\s*\/\//.test(line);
const isBlockCommentStart = /^\s*\/\*/.test(line);
if (!isBlank && !isLineComment && !isBlockCommentStart) {
inTopRegion = false;
}
if (!isBareExportModule) out.push(line);
continue;
}
if (!isBareExportModule) out.push(line);
}
return out.join('\n').trim() + '\n';
}
function makeSectionHeader(relPath) {
const stars = '*'.repeat(Math.max(6, Math.min(38, relPath.length + 6)));
return [
`/* ${stars} */`,
`/* ${relPath} */`,
`/* ${stars} */`,
].join('\n') + '\n';
}
function buildTypeDefMarkdown() {
const entries = TYPE_DEF_WHITELIST.map((rel) => ({
rel,
abs: path.join(ROOT, ...rel.split('/')),
}));
let body = '# ExcalidrawAutomate library and related type definitions\n\n```js\n';
for (const { rel, abs } of entries) {
if (!fs.existsSync(abs)) {
console.warn('[skill-builder] Whitelist file missing:', rel);
continue;
}
let content = fs.readFileSync(abs, 'utf8');
content = stripTopImports(content);
body += makeSectionHeader(rel);
body += content.trimEnd() + '\n\n';
}
body += '```\n';
return body;
}
function resolveExcalModulePath(spec, excalIndexAbs) {
const baseTypesRoot = path.join(ROOT, 'node_modules', '@zsviczian', 'excalidraw', 'types');
if (spec.startsWith('@excalidraw/')) {
const sub = spec.slice('@excalidraw/'.length);
const parts = sub.split('/');
const pkg = parts.shift();
const rest = parts;
if (!pkg) return null;
const base = path.join(baseTypesRoot, pkg);
if (rest.length === 0) {
return path.join(base, 'src', 'index.d.ts');
}
return path.join(base, 'src', ...rest) + '.d.ts';
}
if (spec.startsWith('.')) {
const dir = path.dirname(excalIndexAbs);
return path.resolve(dir, spec) + '.d.ts';
}
return null;
}
function extractFunctionSignaturesFromModule(absPath, names) {
const out = {};
if (!absPath || !fs.existsSync(absPath)) {
return out;
}
const content = fs.readFileSync(absPath, 'utf8');
for (const rawName of names) {
const name = rawName.trim();
if (!name) continue;
let m = content.match(new RegExp(`export\\s+declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
m = content.match(new RegExp(`(^|\\n)declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].replace(/^\s*declare\s+/, 'export declare ').trim();
continue;
}
m = content.match(new RegExp(`export\\s+declare\\s+const\\s+${name}\\s*:\\s*[\\s\\S]*?=>[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
m = content.match(new RegExp(`export\\s+declare\\s+(?:var|let|const)\\s+${name}\\s*:\\s*[\\s\\S]*?;`, 'm'));
if (m && /=>/.test(m[0])) {
out[name] = m[0].trim();
continue;
}
}
return out;
}
function buildExcalidrawLibFunctionsSection() {
const excalIndexRel = 'node_modules/@zsviczian/excalidraw/types/excalidraw/index.d.ts';
const excalIndexAbs = path.join(ROOT, ...excalIndexRel.split('/'));
if (!fs.existsSync(excalIndexAbs)) {
console.warn('[skill-builder] Missing Excalidraw index.d.ts:', excalIndexRel);
return '';
}
const content = fs.readFileSync(excalIndexAbs, 'utf8');
const reExport = /export\s*\{\s*([\s\S]*?)\s*\}\s*from\s*["']([^"']+)["'];/g;
const moduleToNames = new Map();
for (const match of content.matchAll(reExport)) {
const namesChunk = match[1];
const spec = match[2];
const names = namesChunk
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (!names.length) continue;
const abs = resolveExcalModulePath(spec, excalIndexAbs);
if (!abs) continue;
const key = spec;
const curr = moduleToNames.get(key) || { abs, names: new Set() };
for (const n of names) curr.names.add(n);
moduleToNames.set(key, curr);
}
const seen = new Set();
const sections = [];
for (const [spec, { abs, names }] of moduleToNames) {
const sigs = extractFunctionSignaturesFromModule(abs, Array.from(names));
const sigEntries = Object.entries(sigs)
.filter(([name]) => {
if (seen.has(name)) return false;
seen.add(name);
return true;
})
.sort(([a], [b]) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
if (!sigEntries.length) continue;
const rel = path.relative(ROOT, abs).replace(/\\/g, '/');
const header = makeSectionHeader(`${spec} -> ${rel}`);
sections.push(header + sigEntries.map(([, s]) => s).join('\n') + '\n');
}
return '# ExcalidrawLib module functions\n\n' +
'The following functions are exposed via window.ExcalidrawLib. Signatures are extracted from TypeScript declarations.\n\n' +
'```ts\n' +
sections.join('\n') +
'```\n';
}
import { runUnifiedGeneration } from './excalidraw-docs-generator-core.mjs';
function main() {
console.log('[skill-builder] Generating Excalidraw Agent Skill...');
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
process.exit(1);
}
// Ensure directories exist
fs.mkdirSync(SKILL_DIR, { recursive: true });
fs.mkdirSync(SKILL_REFERENCES_DIR, { recursive: true });
// Create or clean the scripts directory
if (fs.existsSync(SKILL_SCRIPTS_DIR)) {
fs.rmSync(SKILL_SCRIPTS_DIR, { recursive: true, force: true });
}
fs.mkdirSync(SKILL_SCRIPTS_DIR, { recursive: true });
// Read exclusions
const args = process.argv.slice(2);
const cmdLineExcludes = args.map(arg => arg.toLowerCase());
const defaultExcludes = ['index-new.md', 'mindmap builder.md', 'color scheme manager.md', 'comic strip director.md'];
const exclusions = new Set([...defaultExcludes, ...cmdLineExcludes]);
// Collect scripts
const files = fs
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
.filter(
(d) =>
d.isFile() &&
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
!exclusions.has(d.name.toLowerCase())
)
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
// Prepare API Index Map
const apiIndex = {
ExcalidrawAutomate: {},
ExcalidrawAPI: {},
ExcalidrawLib: {}
};
function addUsage(category, method, scriptName) {
// Filter out obvious noise or generic javascript attributes
const ignoreList = ['length', 'push', 'map', 'filter', 'forEach', 'includes', 'join', 'toString', 'toLowerCase'];
if (ignoreList.includes(method)) return;
if (method.length < 2) return;
if (!apiIndex[category][method]) {
apiIndex[category][method] = new Set();
}
apiIndex[category][method].add(scriptName);
}
console.log('[skill-builder] Processing scripts and building API Index...');
for (const file of files) {
const full = path.join(EA_SCRIPTS_DIR, file);
let content = fs.readFileSync(full, 'utf8').replace(/\r\n/g, '\n');
// Fix missing fences
if (needsClosingFence(content)) {
content += '\n```\n';
}
// Write individual script to references/scripts/
fs.writeFileSync(path.join(SKILL_SCRIPTS_DIR, file), content, 'utf8');
// Parse API Usage
// 1. ExcalidrawAutomate: ea.functionName
const eaMatches = [...content.matchAll(/ea\.([a-zA-Z0-9_]+)/g)];
eaMatches.forEach(m => addUsage('ExcalidrawAutomate', m[1], file));
// 2. ExcalidrawAPI: api.functionName or ea.getExcalidrawAPI().functionName
const apiMatches = [...content.matchAll(/(?:getExcalidrawAPI\(\)|api)\.([a-zA-Z0-9_]+)/g)];
apiMatches.forEach(m => addUsage('ExcalidrawAPI', m[1], file));
// 3. ExcalidrawLib: ExcalidrawLib.functionName or window.ExcalidrawLib.functionName
const libMatches = [...content.matchAll(/(?:window\.)?ExcalidrawLib\.([a-zA-Z0-9_]+)/g)];
libMatches.forEach(m => addUsage('ExcalidrawLib', m[1], file));
}
// Generate API Usage Index Markdown
console.log('[skill-builder] Writing api-usage-index.md...');
let apiIndexContent = `# Excalidraw API Usage Index\n\n`;
apiIndexContent += `This index maps methods and properties from ExcalidrawAutomate (\`ea\`), ExcalidrawAPI, and ExcalidrawLib to the example scripts that use them. Use this to find real-world examples of how to implement specific features.\n\n`;
for (const [category, methods] of Object.entries(apiIndex)) {
apiIndexContent += `## ${category}\n\n`;
const sortedMethods = Object.keys(methods).sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
if (sortedMethods.length === 0) {
apiIndexContent += `*No usages found.*\n\n`;
continue;
}
for (const method of sortedMethods) {
const scriptLinks = Array.from(methods[method])
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }))
.map(script => `[${script}](scripts/${script.replace(/ /g, '%20')})`)
.join(', ');
apiIndexContent += `- **${method}**: ${scriptLinks}\n`;
}
apiIndexContent += `\n`;
}
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'api-usage-index.md'), apiIndexContent, 'utf8');
// Write Type Definitions
console.log('[skill-builder] Writing type-definitions.md...');
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'type-definitions.md'), buildTypeDefMarkdown(), 'utf8');
// Write ExcalidrawLib Functions
console.log('[skill-builder] Writing excalidraw-lib-functions.md...');
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'excalidraw-lib-functions.md'), buildExcalidrawLibFunctionsSection(), 'utf8');
// Write Startup Scripts template
console.log('[skill-builder] Writing startup-scripts.md...');
const startupTemplatePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_TEMPLATE.split('/'));
const startupExamplePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_EXAMPLE.split('/'));
const startupTemplate = fs.existsSync(startupTemplatePath)
? fs.readFileSync(startupTemplatePath, 'utf8').replace(/\r\n/g, '\n').trim()
: '';
const startupExample = fs.existsSync(startupExamplePath)
? fs.readFileSync(startupExamplePath, 'utf8').replace(/\r\n/g, '\n').trim()
: '';
const startupSection = EXCALIDRAW_STARTUP_MESSAGE + '\n\n' +
(startupTemplate ? `### Template\n\`\`\`js\n${startupTemplate}\n\`\`\`\n\n` : '') +
(startupExample ? `### Example\n\`\`\`js\n${startupExample}\n\`\`\`\n` : '');
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'startup-scripts.md'), startupSection, 'utf8');
// Write SKILL.md
console.log('[skill-builder] Writing SKILL.md...');
const skillMdPath = path.join(SKILL_DIR, 'SKILL.md');
const skillFrontmatter = `---
name: ${SKILL_NAME}
description: Write and manipulate ExcalidrawAutomate scripts for Obsidian.md. Use when the user wants to create, modify, or understand an Excalidraw script.
---
`;
let skillIntro = AI_TRAINING_INTRO
.replaceAll("https://youtu.be/", "YouTube: ")
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
.replaceAll("https://www.youtube.com/", "YouTube: ");
skillIntro += `
## References
The \`references/\` directory contains supporting documentation necessary for writing scripts:
- \`references/type-definitions.md\`: Core type definitions for ExcalidrawAutomate.
- \`references/excalidraw-lib-functions.md\`: Function signatures for \`window.ExcalidrawLib\`.
- \`references/startup-scripts.md\`: ExcalidrawStartup script template and examples.
- \`references/api-usage-index.md\`: A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
- \`references/scripts/\`: A folder containing all the raw, real-world example scripts.
### How to use the Script Examples
If you need to implement a specific function (e.g., \`ea.addElementsToView\`), do NOT guess its implementation context. Instead:
1. Open \`references/api-usage-index.md\`.
2. Find the function name.
3. Note the scripts listed next to it.
4. Read the corresponding script inside the \`references/scripts/\` directory to see a complete, working example of how the function is used in context.
`;
fs.writeFileSync(skillMdPath, skillFrontmatter + skillIntro, 'utf8');
console.log('[skill-builder] Done.');
console.log('[skill-builder] Running unified documentation generator (full mode)...');
const result = runUnifiedGeneration({
mode: 'full',
args: process.argv.slice(2),
});
console.log('[skill-builder] Wrote outputs:', result.generated);
console.log('[skill-builder] Processed scripts:', result.scriptsProcessed);
}
// ESM equivalent of `if (require.main === module)`
if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
main();
@@ -643,4 +20,4 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
console.error('[skill-builder] Failed:', e);
process.exit(1);
}
}
}
+12 -1
View File
@@ -1,6 +1,17 @@
/*
#exclude
```js*/
/**
* Startup scripts receive the plugin-global EA for the plugin lifetime and
* utils.executionSource === "plugin-startup". Register cleanup for resources
* outside EA so plugin reload/unload cannot accumulate them.
*/
// const ref = app.workspace.on("file-open", (file) => {});
// ea.registerCleanup(() => app.workspace.offref(ref));
//
// const interval = window.setInterval(() => {}, 1000);
// ea.registerCleanup(() => window.clearInterval(interval));
/**
* If set, this callback is triggered when the user closes an Excalidraw view.
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
@@ -317,4 +328,4 @@
// elementCount: elements.length
// });
// }
// };
// };
+1 -1
View File
@@ -103,7 +103,7 @@ export const URL_REGISTRY = {
UrlPurpose.SUPPORT,
),
COMMUNITY_SKETCH_YOUR_MIND_COM_WIKI: defineUrl(
"https://community.sketch-your-mind.com/wiki",
"https://community.sketch-your-mind.com/Wiki",
UrlPurpose.SUPPORT,
),
WWW_YOUTUBE_COM_VISUALPKM: defineUrl(
+112 -36
View File
@@ -46,7 +46,6 @@ import {
getNewUniqueFilepath,
} from "../utils/fileUtils";
import {
errorlog,
isVersionNewerThanOther,
versionUpdateCheckTimer,
calculateUIModeValue,
@@ -66,7 +65,7 @@ import {
} from "./managers/MarkdownPostProcessor";
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes";
import { DeviceType, Packages } from "../types/types";
import { DeviceType, PackageLease, Packages } from "../types/types";
import { PaneTarget } from "../types/utilTypes";
import {
emulateCTRLClickForLinks,
@@ -112,6 +111,16 @@ import { PluginSettingsManager } from "./managers/PluginSettingsManager";
import { FooterSafeAreaManager } from "./managers/FooterSafeAreaManager";
import { FontManager } from "./managers/FontManager";
import { StartupTimer } from "./managers/StartupTimer";
import {
ViewMigrationPersistenceHandoffManager,
type ViewMigrationPersistenceHandoff,
} from "./managers/ViewMigrationPersistenceHandoffManager";
import {
ViewMigrationHandoffManager,
type ViewMigrationDrawingState,
type ViewMigrationHandoffRegistration,
type ViewMigrationHandoffRequest,
} from "./managers/ViewMigrationHandoffManager";
declare const PLUGIN_VERSION: string;
declare const INITIAL_TIMESTAMP: number;
@@ -154,9 +163,12 @@ export default class ExcalidrawPlugin extends Plugin {
private commandManager: CommandManager;
private eventManager: EventManager;
private settingsManager: PluginSettingsManager;
private settingsTab: ExcalidrawSettingTab;
private footerSafeAreaManager: FooterSafeAreaManager;
private fontManager: FontManager;
private startupTimer: StartupTimer;
private viewMigrationHandoffManager: ViewMigrationHandoffManager;
private viewMigrationPersistenceHandoffManager: ViewMigrationPersistenceHandoffManager;
public stencilLibraryManager: StencilLibraryManager;
public eaInstances = new WeakArray<ExcalidrawAutomate>();
public fourthFontLoaded: boolean = false;
@@ -200,6 +212,9 @@ export default class ExcalidrawPlugin extends Plugin {
super(app, manifest);
this.loadTimestamp = INITIAL_TIMESTAMP;
this.startupTimer = new StartupTimer(this.loadTimestamp, PLUGIN_VERSION);
this.viewMigrationHandoffManager = new ViewMigrationHandoffManager();
this.viewMigrationPersistenceHandoffManager =
new ViewMigrationPersistenceHandoffManager();
this.filesMaster = new Map<
FileId,
{
@@ -220,7 +235,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.settingsManager = new PluginSettingsManager(this);
this.footerSafeAreaManager = new FooterSafeAreaManager(this);
this.fontManager = new FontManager(this, () =>
this.packageManager.getPackageMap(),
this.packageManager.getRuntimePackage(),
);
setExcalidrawPlugin(this);
@@ -393,7 +408,8 @@ export default class ExcalidrawPlugin extends Plugin {
this.settings.onceOffCompressFlagReset = true;
await this.saveSettings();
}
this.addSettingTab(new ExcalidrawSettingTab(this.app, this));
this.settingsTab = new ExcalidrawSettingTab(this.app, this);
this.addSettingTab(this.settingsTab);
this.settingsReady = true;
}
@@ -562,7 +578,10 @@ export default class ExcalidrawPlugin extends Plugin {
public async awaitSettings() {
let counter = 0;
while (!this.settingsReady && counter < 150) {
while (
!this.settingsReady &&
(counter < 150 || this.settingsManager.isAwaitingStartupRecoveryChoice)
) {
await sleep(20);
counter++;
}
@@ -655,17 +674,16 @@ export default class ExcalidrawPlugin extends Plugin {
private registerInstallCodeblockProcessor() {
const codeblockProcessor = async (source: string, el: HTMLElement) => {
//Button next to the "List of available scripts" at the top
//In try/catch block because this approach is very error prone, depends on
//MarkdownRenderer() and index.md structure, in case these are not as
//expected this code will break
// 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;
try {
const link: HTMLElement = el.parentElement.querySelector(
`a[href="#${el.previousElementSibling.getAttribute(
"data-heading",
)}"]`,
);
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"));
@@ -673,12 +691,6 @@ export default class ExcalidrawPlugin extends Plugin {
setButtonBgColor(b, "success");
hideElement(b);
});
} catch (e: unknown) {
errorlog({
where: "this.registerInstallCodeblockProcessor",
source,
error: e,
});
}
source = source.trim();
@@ -746,6 +758,9 @@ export default class ExcalidrawPlugin extends Plugin {
keepOriginal: boolean = false,
): Promise<TFile> {
const data = await this.app.vault.read(file);
const hasEmbeddedFiles = Object.keys(
(JSON_parse<{ files?: Record<string, unknown> }>(data).files ?? {}),
).length > 0;
const filename =
file.name.substring(0, file.name.lastIndexOf(".excalidraw")) +
(replaceExtension ? ".md" : ".excalidraw.md");
@@ -755,11 +770,17 @@ export default class ExcalidrawPlugin extends Plugin {
normalizePath(file.path.substring(0, file.path.lastIndexOf(file.name))),
);
log(fname);
const result = await createOrOverwriteFile(
this.app,
fname,
FRONTMATTER + (await this.fileManager.exportSceneToMD(data, false)),
);
const initialMarkdown =
FRONTMATTER + (await this.fileManager.exportSceneToMD(data, false));
const result = await createOrOverwriteFile(this.app, fname, initialMarkdown);
if (hasEmbeddedFiles) {
const convertedMarkdown =
await this.fileManager.persistLegacySceneFilesInMarkdown(
initialMarkdown,
result,
);
await this.app.vault.modify(result, convertedMarkdown);
}
if (this.settings.keepInSync) {
EXPORT_TYPES.forEach((ext: string) => {
const oldIMGpath =
@@ -806,18 +827,20 @@ export default class ExcalidrawPlugin extends Plugin {
) {
return;
}
const path = this.settings.startupScriptPath.endsWith(".md")
? this.settings.startupScriptPath
: `${this.settings.startupScriptPath}.md`;
const path = this.scriptEngine.resolveStartupScriptPath(
this.settings.startupScriptPath,
);
if (!path) {
new Notice(t("STARTUP_SCRIPT_JS_DISABLED"));
return;
}
const f = this.app.vault.getFileByPath(path);
if (!f || !(f instanceof TFile)) {
new Notice(`Startup script not found: ${path}`);
return;
}
const script = await this.app.vault.read(f);
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
try {
await new AsyncFunction("ea", script)(this.ea);
await this.scriptEngine.executeStartupScript(f, this.ea);
} catch (e) {
new Notice(`Error running startup script: ${e}`);
}
@@ -965,11 +988,15 @@ export default class ExcalidrawPlugin extends Plugin {
this.activeExcalidrawView = null;
this.lastActiveExcalidrawFilePath = null;
this.settingsManager.destroy();
this.settingsTab = null;
this.settings = null;
//pluginPackages = null;
//PLUGIN_VERSION = null;
delete window.PolyBool;
this.packageManager.destroy();
this.viewMigrationHandoffManager.destroy();
this.viewMigrationPersistenceHandoffManager.destroy();
this.commandManager?.destroy();
this.eventManager.destroy();
terminateCompressionWorker();
@@ -987,10 +1014,17 @@ export default class ExcalidrawPlugin extends Plugin {
await this.settingsManager.saveSettings();
}
/** Refreshes the mounted settings tab after script-defined settings change. */
public refreshSettingsTab(): void {
this.settingsTab?.refreshAfterExternalSettingsChange();
}
/** Reloads externally changed settings and invalidates cached libraries. */
async onExternalSettingsChange() {
await this.loadSettings();
this.stencilLibraryManager?.invalidate();
const didLoadSettings = await this.settingsManager.loadSettings();
if (didLoadSettings) {
this.stencilLibraryManager?.invalidate();
}
}
public async openSidepanel(
@@ -1210,8 +1244,8 @@ export default class ExcalidrawPlugin extends Plugin {
this.observerManager.removeThemeObserver();
}
public addModalContainerObserver() {
this.observerManager.addModalContainerObserver();
public addModalContainerObserver(view?: ExcalidrawView) {
this.observerManager.addModalContainerObserver(view);
}
public removeModalContainerObserver() {
@@ -1226,10 +1260,52 @@ export default class ExcalidrawPlugin extends Plugin {
return this.packageManager.getPackage(win);
}
/** Acquires explicit ownership of the runtime package for one view window. */
public acquirePackage(win: Window): PackageLease {
return this.packageManager.acquirePackage(win);
}
public deletePackage(win: Window) {
this.packageManager.deletePackage(win);
}
/** Registers drawing-owned runtime state for one recreated view. */
public registerViewMigrationHandoff(
registration: ViewMigrationHandoffRegistration,
): string {
return this.viewMigrationHandoffManager.register(registration);
}
/** Consumes validated drawing-owned runtime state for one recreated view. */
public consumeViewMigrationHandoff(
request: ViewMigrationHandoffRequest,
): ViewMigrationDrawingState | null {
return this.viewMigrationHandoffManager.consume(request);
}
/** Registers serialized drawing text for a popout-to-main migration. */
public registerViewMigrationPersistenceHandoff(
handoff: ViewMigrationPersistenceHandoff,
): void {
this.viewMigrationPersistenceHandoffManager.register(handoff);
}
/** Consumes serialized drawing text for the replacement main-window view. */
public consumeViewMigrationPersistenceHandoff(
leafId: string,
filePath: string,
): string | null {
return this.viewMigrationPersistenceHandoffManager.consume(
leafId,
filePath,
);
}
/** Discards a handoff when the old view could not be replaced. */
public discardViewMigrationPersistenceHandoff(leafId: string): void {
this.viewMigrationPersistenceHandoffManager.discard(leafId);
}
get taskbone() {
return this.commandManager?.taskbone;
}
+7 -1
View File
@@ -136,6 +136,12 @@ export class EventManager {
),
);
//theme/snippet toggles can change header/toolbar heights and shift the canvas
//without firing layout-change; refresh cached canvas offsets the same way
this.registerEvent(
this.app.workspace.on("css-change", () => this.onLayoutChangeHandler()),
);
//File Save Trigger Handlers
//Save the drawing if the user clicks outside the Excalidraw Canvas
const onClickEventSaveActiveDrawing = (e: PointerEvent) =>
@@ -343,7 +349,7 @@ export class EventManager {
this.previouslyActiveLeaf = leaf;
if (newActiveviewEV) {
this.plugin.addModalContainerObserver();
this.plugin.addModalContainerObserver(newActiveviewEV);
this.plugin.lastActiveExcalidrawFilePath = newActiveviewEV.file?.path;
} else {
this.plugin.removeModalContainerObserver();
+58 -9
View File
@@ -79,6 +79,16 @@ export class PluginFileManager {
});
}
/**
* Returns whether a vault file is an Excalidraw drawing.
*
* Parsed frontmatter is authoritative when available. During a vault write,
* Obsidian can temporarily remove that frontmatter from the metadata cache;
* in that gap, retain the last confirmed classification from
* {@link excalidrawFiles}. The metadata `changed` event updates that set, so
* deliberately removing the Excalidraw frontmatter still declassifies the
* file once the replacement metadata is published.
*/
public isExcalidrawFile(f: TFile): boolean {
if (!f) {
return false;
@@ -86,11 +96,12 @@ export class PluginFileManager {
if (f.extension === "excalidraw") {
return true;
}
const fileCache = f ? this.plugin.app.metadataCache.getFileCache(f) : null;
return (
!!fileCache?.frontmatter &&
!!fileCache.frontmatter[FRONTMATTER_KEYS.plugin.name]
);
const frontmatter = this.plugin.app.metadataCache.getFileCache(f)?.frontmatter;
if (frontmatter) {
return !!frontmatter[FRONTMATTER_KEYS.plugin.name];
}
return this.excalidrawFiles.has(f);
}
//managing my own list of Excalidraw files because in the onDelete event handler
@@ -537,6 +548,40 @@ export class PluginFileManager {
);
}
/**
* Extracts binary files embedded in a converted legacy scene and rewrites
* the Markdown drawing with durable vault attachment links.
*
* The target file must already exist because Obsidian determines its
* attachment folder relative to that file. This method resolves only after
* every embedded file has been persisted.
*/
public async persistLegacySceneFilesInMarkdown(
markdown: string,
file: TFile,
): Promise<string> {
const convertedData = new ExcalidrawData(this.plugin);
try {
const loaded = await convertedData.loadData(
markdown,
file,
getTextMode(markdown),
);
if (!loaded) {
throw new Error(`Failed to load converted drawing: ${file.path}`);
}
convertedData.disableCompression = true;
await convertedData.syncElements(convertedData.scene);
return (
FRONTMATTER +
(await convertedData.generateMDAsync(convertedData.deletedElements))
);
} finally {
convertedData.destroy();
}
}
// -------------------------------------------------------
// ------------------ Event Handlers ---------------------
// -------------------------------------------------------
@@ -622,7 +667,10 @@ export class PluginFileManager {
const excalidrawViews = getExcalidrawViews(this.app);
excalidrawViews.forEach((excalidrawView) => {
void (async () => {
if (excalidrawView.semaphores?.viewunload) {
if (
excalidrawView.semaphores?.viewunload ||
excalidrawView.semaphores?.windowMigrating
) {
return;
}
if (
@@ -718,12 +766,13 @@ export class PluginFileManager {
return;
}
//this will not work in the short period when Obsidian is starting up, however
//this will only effect a very few files, statistically unlikely to cause
//much/any real user impact.
//a proper queuing feels overkill for this.
//this will only affect very few files, statistically unlikely to cause
//much/any real user impact. Flush the shared queue so a recently scheduled
//backup is moved with the drawing instead of later recreating the old key.
if (!getImageCache().isReady()) {
return;
}
await getImageCache().flushPendingBAK(oldPath);
const backup = await getImageCache().getBAKFromCache(oldPath);
if (backup) {
await getImageCache().addBAKToCache(newPath, `${backup}`);
+6 -8
View File
@@ -17,7 +17,7 @@ declare const deliberateCreateElement: (
tagName: string,
) => HTMLStyleElement;
type PackageMapProvider = () => Map<Window, Packages>;
type RuntimePackageProvider = () => Packages;
/**
* Owns CJK and custom-font discovery, registration, document stylesheets, and
@@ -30,7 +30,7 @@ export class FontManager {
public constructor(
private readonly plugin: ExcalidrawPlugin,
private readonly getPackageMap: PackageMapProvider,
private readonly getRuntimePackage: RuntimePackageProvider,
) {}
/** Whether font initialization permits the plugin readiness wait to finish. */
@@ -76,7 +76,7 @@ export class FontManager {
/**
* Loads configured CJK and custom fonts into every open Obsidian document
* and registers custom font metrics with each window-scoped Excalidraw package.
* and registers custom font metrics with the shared Excalidraw runtime.
*/
public async initializeFonts(): Promise<void> {
const cjkFontDataURLs = await getCJKDataURLs(this.plugin);
@@ -128,15 +128,13 @@ export class FontManager {
lineHeight: 1.2,
};
}
this.getPackageMap().forEach(({ excalidrawLib }) => {
if (!fontMetrics) {
return;
}
const { excalidrawLib } = this.getRuntimePackage();
if (fontMetrics) {
excalidrawLib.registerLocalFont(
{ metrics: fontMetrics },
fourthFontDataURL,
);
});
}
for (const ownerDocument of this.getOpenObsidianDocuments()) {
await this.addFonts(
[
+57 -21
View File
@@ -12,14 +12,30 @@ import {
isInstanceOfDocumentFragment,
isInstanceOfElement,
} from "src/utils/typechecks";
import type ExcalidrawView from "src/view/ExcalidrawView";
declare const mainDocument: Document;
const MODAL_CONTAINER_SELECTOR = ".modal-container";
/**
* Checks an observed DOM node without relying on cross-window constructors.
*
* Mutation records can contain nodes from an Obsidian popout realm whose
* `instanceof Element` identity is not reliable after window migration.
*/
const isObservedElement = (node: Node): node is Element =>
node.nodeType === 1 && typeof (node as Element).matches === "function";
export class ObserverManager {
private plugin: ExcalidrawPlugin;
private app: App;
private themeObserver: MutationObserver | CustomMutationObserver;
private fileExplorerObserver: MutationObserver | CustomMutationObserver;
private modalContainerObserver: MutationObserver | CustomMutationObserver;
private modalContainerObserver:
| MutationObserver
| CustomMutationObserver
| null = null;
private modalObservedView: ExcalidrawView | null = null;
private workspaceDrawerLeftObserver:
| MutationObserver
| CustomMutationObserver;
@@ -267,51 +283,70 @@ export class ObserverManager {
}
/**
* Monitors if the user clicks outside the Excalidraw view, and saves the drawing if it's dirty
* @returns
* Saves a dirty drawing when an Obsidian modal opens in its live document.
*
* @param view - The active or same-leaf replacement view to observe.
*/
public addModalContainerObserver() {
if (!this.plugin.activeExcalidrawView) {
public addModalContainerObserver(view = this.plugin.activeExcalidrawView) {
if (!view) {
return;
}
const activeViewDoc = view.containerEl.ownerDocument;
if (this.modalContainerObserver) {
if (
this.activeViewDoc === this.plugin.activeExcalidrawView.ownerDocument
this.activeViewDoc === activeViewDoc &&
this.modalObservedView === view
) {
return;
}
this.removeModalContainerObserver();
}
//The user clicks settings, or "open another vault", or the command palette
//The user clicks settings, or "open another vault", or the command palette.
//Other body portals, including inline suggestions, must not interrupt editing with a save.
const modalContainerObserverFn: MutationCallback = (
m: MutationRecord[],
mutations: MutationRecord[],
) => {
const view = this.plugin.activeExcalidrawView;
const observedView = this.modalObservedView;
const addedNodes = mutations.flatMap((mutation) =>
mutation.type === "childList"
? Array.from(mutation.addedNodes)
: [],
);
const modalOpened = addedNodes.some(
(node) =>
isObservedElement(node) &&
(node.matches(MODAL_CONTAINER_SELECTOR) ||
node.querySelector(MODAL_CONTAINER_SELECTOR) !== null),
);
if (
m.length !== 1 ||
m[0].type !== "childList" ||
m[0].addedNodes.length !== 1 ||
!view ||
view.semaphores?.viewunload ||
!view.isDirty()
!modalOpened ||
!observedView ||
observedView.semaphores?.viewunload ||
!observedView.isDirty() ||
!observedView.excalidrawAPI
) {
return;
}
const { errorMessage } = view.excalidrawAPI.getAppState();
const { errorMessage } = observedView.excalidrawAPI.getAppState();
if (!errorMessage) {
void this.plugin.activeExcalidrawView.save();
void observedView.save();
}
};
this.activeViewDoc = activeViewDoc;
this.modalObservedView = view;
// Keep the observer constructor and target in the same window realm so a
// migrated view never depends on its destroyed source window.
this.modalContainerObserver = DEBUGGING
? new CustomMutationObserver(
modalContainerObserverFn,
"modalContainerObserver",
)
: new MutationObserver(modalContainerObserverFn);
this.activeViewDoc = this.plugin.activeExcalidrawView.ownerDocument;
this.modalContainerObserver.observe(this.activeViewDoc.body, {
: new (activeViewDoc.defaultView?.MutationObserver ?? MutationObserver)(
modalContainerObserverFn,
);
this.modalContainerObserver.observe(activeViewDoc.body, {
childList: true,
});
}
@@ -321,8 +356,9 @@ export class ObserverManager {
return;
}
this.modalContainerObserver.disconnect();
this.activeViewDoc = null;
this.modalContainerObserver = null;
this.modalObservedView = null;
this.activeViewDoc = null;
}
private addWorkspaceDrawerObserver() {
+145 -150
View File
@@ -1,40 +1,52 @@
import { updateExcalidrawLib } from "src/constants/constants";
import { ExcalidrawLib } from "../../types/excalidrawLib";
import { Packages } from "../../types/types";
import { PackageLease, Packages } from "../../types/types";
import { Notice } from "obsidian";
import type ExcalidrawPlugin from "src/core/main";
import { errorHandler } from "../../utils/ErrorHandler";
import React from "react";
import ReactDOM from "react-dom/client";
import * as ReactDOMLegacy from "react-dom";
import * as ReactDOMClient from "react-dom/client";
import * as ReactJSXRuntime from "react/jsx-runtime";
import * as ReactJSXDevRuntime from "react/jsx-dev-runtime";
import { createObsidianCommonHostAdapter } from "./obsidianCommonHostAdapter";
import { createObsidianExcalidrawHostAdapter } from "./obsidianExcalidrawHostAdapter";
declare let REACT_PACKAGES: string;
declare let react: typeof React;
declare let reactDOM: typeof ReactDOM;
declare let excalidrawLib: typeof ExcalidrawLib;
declare let ReactJSXRuntime: unknown;
declare let ReactJSXDevRuntime: unknown;
declare const unpackExcalidraw: () => string;
const reactDOM = Object.assign({}, ReactDOMLegacy, ReactDOMClient);
const reactJSXDevRuntime = Object.assign({}, ReactJSXDevRuntime, {
// React's production jsx-dev-runtime deliberately leaves jsxDEV undefined,
// while the Excalidraw artifact accepts either external runtime entrypoint.
jsxDEV: ReactJSXDevRuntime.jsxDEV ?? ReactJSXRuntime.jsx,
});
const normalizeError = (error: unknown): Error =>
error instanceof Error
? error
: new Error(typeof error === "string" ? error : "Unknown error");
/**
* Owns the plugin's single private React/Excalidraw runtime.
*
* Each view receives the same package but retains an idempotent lease keyed by
* its actual window. The window key governs migration persistence and the
* temporary `ExcalidrawLib` compatibility alias only; rendering ownership is
* supplied independently through each Excalidraw instance's `ownerDocument`.
*/
export class PackageManager {
private packageMap: Map<Window, Packages> = new Map<Window, Packages>();
private EXCALIDRAW_PACKAGE: string;
private plugin: ExcalidrawPlugin;
private fallbackPackage: Packages | null = null;
private commonHostDisposerMap = new Map<Window, () => void>();
private excalidrawHostDisposerMap = new Map<Window, () => void>();
private runtimePackage: Packages | null = null;
private packageLeaseCountMap = new Map<Window, number>();
private commonHostDisposer: (() => void) | null = null;
private excalidrawHostDisposer: (() => void) | null = null;
private runtimeAliasWindows = new Set<Window>();
constructor(plugin: ExcalidrawPlugin) {
this.plugin = plugin;
constructor(private readonly plugin: ExcalidrawPlugin) {
let excalidrawPackage = "";
try {
this.EXCALIDRAW_PACKAGE = unpackExcalidraw();
excalidrawPackage = unpackExcalidraw();
// Evaluate Excalidraw in the main window with the same private React
// instance used by the plugin bundle. The runtime is passed explicitly
@@ -42,23 +54,23 @@ export class PackageManager {
const loadExcalidraw = errorHandler.safeEval<
(
reactInstance: typeof React,
reactDOMInstance: typeof ReactDOM,
reactDOMInstance: typeof reactDOM,
jsxRuntime: unknown,
jsxDevRuntime: unknown,
) => typeof ExcalidrawLib
>(
`(function(React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime) {
${this.EXCALIDRAW_PACKAGE};
${excalidrawPackage};
return ExcalidrawLib;
})`,
"PackageManager constructor - excalidrawLib initialization",
window,
);
excalidrawLib = loadExcalidraw(
react,
React,
reactDOM,
ReactJSXRuntime,
ReactJSXDevRuntime,
reactJSXDevRuntime,
);
if (!excalidrawLib) {
@@ -69,12 +81,11 @@ export class PackageManager {
updateExcalidrawLib();
// Create a package with the loaded libraries
const initialPackage = { react, reactDOM, excalidrawLib };
const initialPackage = { react: React, reactDOM, excalidrawLib };
// Validate the package before storing
if (this.validatePackage(initialPackage)) {
this.setPackage(window, initialPackage);
this.fallbackPackage = initialPackage; // Store a valid package as fallback
this.setRuntimePackage(initialPackage);
} else {
throw new Error("Invalid initial package");
}
@@ -88,6 +99,11 @@ export class PackageManager {
10000,
);
console.error("Error loading the Excalidraw package", e);
} finally {
// Per-window evaluation has been removed. Release the decompressed
// Excalidraw source after the one runtime is initialized instead of
// retaining it for hypothetical future popouts.
excalidrawPackage = "";
}
plugin.logStartupEvent("Excalidraw package unpacked");
@@ -119,9 +135,9 @@ export class PackageManager {
/**
* Registers plugin capabilities with one evaluated Excalidraw runtime.
*/
private configureObsidianCommonHost(win: Window, pkg: Packages): void {
this.commonHostDisposerMap.get(win)?.();
this.commonHostDisposerMap.delete(win);
private configureObsidianCommonHost(pkg: Packages): void {
this.commonHostDisposer?.();
this.commonHostDisposer = null;
const lib = pkg.excalidrawLib;
if (
@@ -136,16 +152,13 @@ export class PackageManager {
this.plugin,
lib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION,
);
this.commonHostDisposerMap.set(
win,
lib.configureObsidianCommonHost(adapter),
);
this.commonHostDisposer = lib.configureObsidianCommonHost(adapter);
}
/** Registers plugin-wide settings with one evaluated Excalidraw runtime. */
private configureObsidianExcalidrawHost(win: Window, pkg: Packages): void {
this.excalidrawHostDisposerMap.get(win)?.();
this.excalidrawHostDisposerMap.delete(win);
private configureObsidianExcalidrawHost(pkg: Packages): void {
this.excalidrawHostDisposer?.();
this.excalidrawHostDisposer = null;
const lib = pkg.excalidrawLib;
if (
@@ -162,136 +175,126 @@ export class PackageManager {
this.plugin,
lib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION,
);
this.excalidrawHostDisposerMap.set(
win,
lib.configureObsidianExcalidrawHost(adapter),
);
this.excalidrawHostDisposer =
lib.configureObsidianExcalidrawHost(adapter);
}
/** Disposes every host registration owned by an evaluated window runtime. */
private disposeObsidianHosts(win: Window): void {
this.commonHostDisposerMap.get(win)?.();
this.commonHostDisposerMap.delete(win);
this.excalidrawHostDisposerMap.get(win)?.();
this.excalidrawHostDisposerMap.delete(win);
/** Disposes the plugin capabilities registered with the shared runtime. */
private disposeObsidianHosts(): void {
this.commonHostDisposer?.();
this.commonHostDisposer = null;
this.excalidrawHostDisposer?.();
this.excalidrawHostDisposer = null;
}
/**
* Store a package for a specific window
*/
public setPackage(window: Window, pkg: Packages) {
/** Stores and configures the plugin's single evaluated runtime package. */
private setRuntimePackage(pkg: Packages): void {
if (this.validatePackage(pkg)) {
try {
this.configureObsidianCommonHost(window, pkg);
this.configureObsidianExcalidrawHost(window, pkg);
this.configureObsidianCommonHost(pkg);
this.configureObsidianExcalidrawHost(pkg);
} catch (error: unknown) {
this.disposeObsidianHosts(window);
this.disposeObsidianHosts();
throw normalizeError(error);
}
this.packageMap.set(window, pkg);
// Update fallback if we don't have one
if (!this.fallbackPackage) {
this.fallbackPackage = pkg;
}
this.runtimePackage = pkg;
} else {
errorHandler.handleError(
"Attempted to set invalid package",
"PackageManager.setPackage",
"PackageManager.setRuntimePackage",
);
}
}
public getPackageMap() {
return this.packageMap;
/** Returns the one runtime used by every main-window and popout view. */
public getRuntimePackage(): Packages {
if (!this.runtimePackage || !this.validatePackage(this.runtimePackage)) {
throw new Error("Excalidraw runtime package is unavailable");
}
return this.runtimePackage;
}
/**
* Gets a package for a window, creating it if necessary
* with robust error handling
* Acquires the shared runtime while retaining the view's actual window.
*
* @remarks
* Window identity remains view-owned migration/persistence state. Popout
* leases additionally own the temporary `window.ExcalidrawLib` compatibility
* alias and remove it when the final view in that window releases its lease.
*/
public getPackage(win: Window): Packages {
try {
// Return existing package if available
if (this.packageMap.has(win)) {
const pkg = this.packageMap.get(win);
if (this.validatePackage(pkg)) {
return pkg;
public acquirePackage(win: Window): PackageLease {
const packages = this.getPackage(win);
const leaseCount = (this.packageLeaseCountMap.get(win) ?? 0) + 1;
this.packageLeaseCountMap.set(win, leaseCount);
let released = false;
return {
window: win,
packages,
release: () => {
if (released) {
return;
}
// If package exists but is invalid, delete it so we can recreate it
this.deletePackage(win);
released = true;
this.releasePackageLease(win);
},
};
}
/** Releases one view-owned package lease without consulting mutable DOM. */
private releasePackageLease(win: Window): void {
const leaseCount = this.packageLeaseCountMap.get(win);
if (leaseCount === undefined) {
return;
}
const remainingLeases = Math.max(0, leaseCount - 1);
if (remainingLeases === 0) {
this.packageLeaseCountMap.delete(win);
if (win !== window) {
this.removeRuntimeAlias(win);
}
// Create new package
return errorHandler.wrapWithTryCatch(
() => {
// Use safe evaluation to load packages in the window context
const evalResult = errorHandler.safeEval<{
react: typeof React;
reactDOM: typeof ReactDOM;
excalidrawLib: typeof ExcalidrawLib;
}>(
`(function() {
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
return {
react: React,
reactDOM: ReactDOM,
excalidrawLib: ExcalidrawLib,
};
})()`,
"PackageManager.getPackage - package evaluation",
win,
);
if (!evalResult || !this.validatePackage(evalResult)) {
throw new Error("Failed to create valid package");
}
const newPackage = {
react: evalResult.react,
reactDOM: evalResult.reactDOM,
excalidrawLib: evalResult.excalidrawLib,
};
this.setPackage(win, newPackage);
return newPackage;
},
"PackageManager.getPackage",
this.fallbackPackage,
);
} catch (error: unknown) {
errorHandler.handleError(
normalizeError(error),
"PackageManager.getPackage",
);
// Return fallback package if available to prevent data loss
if (this.fallbackPackage) {
return this.fallbackPackage;
}
// If no fallback, throw error to prevent undefined behavior
throw new Error("Failed to get package and no fallback available");
} else {
this.packageLeaseCountMap.set(win, remainingLeases);
}
}
/**
* Returns the shared runtime and exposes its compatibility API in `win`.
*
* @remarks
* The runtime is never evaluated in the supplied window. Rendering ownership
* is provided separately through Excalidraw's stable `ownerDocument` prop.
*/
public getPackage(win: Window): Packages {
const pkg = this.getRuntimePackage();
if (win !== window) {
win.ExcalidrawLib = pkg.excalidrawLib;
this.runtimeAliasWindows.add(win);
}
return pkg;
}
/** Removes only the window-local alias; the shared runtime remains alive. */
private removeRuntimeAlias(win: Window): void {
const packageLib = this.runtimePackage?.excalidrawLib;
errorHandler.wrapWithTryCatch(() => {
if (packageLib && win.ExcalidrawLib === packageLib) {
delete win.ExcalidrawLib;
}
}, "PackageManager.removeRuntimeAlias");
this.runtimeAliasWindows.delete(win);
}
/**
* Compatibility facade retained for callers that explicitly clean a window.
* The plugin-wide runtime and host registrations live until `destroy()`.
*/
public deletePackage(win: Window) {
try {
this.disposeObsidianHosts(win);
const pkg = this.packageMap.get(win);
if (!pkg) {
return;
if (win !== window) {
this.removeRuntimeAlias(win);
}
const { excalidrawLib } = pkg;
if (win.ExcalidrawLib === excalidrawLib) {
errorHandler.wrapWithTryCatch(() => {
delete win.ExcalidrawLib;
}, "PackageManager.deletePackage - cleanup ExcalidrawLib");
}
this.packageMap.delete(win);
} catch (error: unknown) {
errorHandler.handleError(
normalizeError(error),
@@ -300,26 +303,18 @@ export class PackageManager {
}
}
public setExcalidrawPackage(pkg: string) {
this.EXCALIDRAW_PACKAGE = pkg;
}
public destroy() {
try {
REACT_PACKAGES = "";
Array.from(this.packageMap.entries()).forEach(([win, _]) => {
this.deletePackage(win);
Array.from(this.runtimeAliasWindows).forEach((win) => {
this.removeRuntimeAlias(win);
});
this.removeRuntimeAlias(window);
this.packageMap.clear();
this.commonHostDisposerMap.clear();
this.excalidrawHostDisposerMap.clear();
this.EXCALIDRAW_PACKAGE = "";
this.fallbackPackage = null;
this.packageLeaseCountMap.clear();
this.runtimeAliasWindows.clear();
this.disposeObsidianHosts();
this.runtimePackage = null;
react = null;
reactDOM = null;
excalidrawLib = null;
} catch (error: unknown) {
errorHandler.handleError(
+238 -8
View File
@@ -1,3 +1,4 @@
import { Notice, type App, type PluginManifest } from "obsidian";
import { JSON_parse } from "src/constants/constants";
import {
DEFAULT_SETTINGS,
@@ -8,33 +9,165 @@ import {
decryptPersistedAPIKeys,
encryptPersistedAPIKeys,
} from "src/utils/settingsKeyObfuscation";
import { SerializedSettingsWriter } from "src/core/settings/SerializedSettingsWriter";
import { SettingsRecoveryStore } from "src/core/settings/SettingsRecoveryStore";
import {
SettingsRecoveryPrompt,
type SettingsRecoveryChoice,
type SettingsRecoveryPromptMode,
} from "src/shared/Dialogs/SettingsRecoveryPrompt";
import {
classifySettingsDataLoad,
isSettingsDataRecord,
type SettingsDataFileState,
} from "src/core/settings/settingsDataValidation";
import { t } from "src/lang/helpers";
type PersistedExcalidrawSettings = Partial<ExcalidrawSettings> &
Record<string, unknown>;
interface PluginSettingsHost {
app: App;
manifest: PluginManifest;
settings: ExcalidrawSettings;
loadData(): Promise<unknown>;
saveData(data: unknown): Promise<void>;
}
interface SettingsRecoveryStoreLike {
load(): Promise<PersistedExcalidrawSettings | null>;
save(settings: PersistedExcalidrawSettings): Promise<void>;
destroy(): void;
}
type SettingsRecoveryPromptHandler = (
mode: SettingsRecoveryPromptMode,
) => Promise<SettingsRecoveryChoice>;
/**
* Owns plugin settings persistence, default assembly, and compatibility
* migrations while leaving startup readiness and settings UI registration to
* the plugin lifecycle.
*/
export class PluginSettingsManager {
public constructor(private readonly host: PluginSettingsHost) {}
private readonly writer: SerializedSettingsWriter<PersistedExcalidrawSettings>;
private readonly recoveryStore: SettingsRecoveryStoreLike;
private hasCompletedInitialLoad = false;
private persistenceBlockedByInvalidData = false;
private missingRecoveryNoticeShown = false;
private awaitingStartupRecoveryChoice = false;
private readonly promptForRecoveryChoice: SettingsRecoveryPromptHandler;
public constructor(
private readonly host: PluginSettingsHost,
recoveryStore?: SettingsRecoveryStoreLike,
promptForRecoveryChoice?: SettingsRecoveryPromptHandler,
) {
this.recoveryStore =
recoveryStore ??
new SettingsRecoveryStore({
databaseName: `Excalidraw Settings Recovery ${host.app.appId}`,
});
this.promptForRecoveryChoice =
promptForRecoveryChoice ??
((mode) => new SettingsRecoveryPrompt(host.app, mode).start());
this.writer = new SerializedSettingsWriter({
saveData: async (data) => {
await this.saveRecoverySnapshot(data);
await this.host.saveData(data);
},
});
}
/**
* Loads persisted settings, applies defaults and migrations, and decrypts
* protected API-key fields.
*
* @remarks Unknown persisted properties are intentionally retained.
* @returns `false` when the disk payload was invalid. Runtime callers use
* this to suppress cache invalidation for a rejected synchronized payload.
*/
public async loadSettings(): Promise<void> {
const persistedSettings = ((await this.host.loadData()) ??
{}) as PersistedExcalidrawSettings;
public async loadSettings(): Promise<boolean> {
const dataFileState = await this.getSettingsDataFileState();
let loadedSettings: unknown = null;
let loadFailed = false;
try {
loadedSettings = await this.host.loadData();
} catch {
loadFailed = true;
}
const classification = classifySettingsDataLoad({
value: loadedSettings,
fileState: dataFileState,
loadFailed,
isInitialLoad: !this.hasCompletedInitialLoad,
});
const hasInvalidSettings = classification === "invalid";
const isFirstInstallation = classification === "first-installation";
let persistedSettings: PersistedExcalidrawSettings;
let recoveredInvalidStartup = false;
let shouldPersistStartupChoice = false;
if (hasInvalidSettings) {
if (this.hasCompletedInitialLoad) {
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
new Notice(t("SETTINGS_DATA_REPAIRED_FROM_MEMORY"), 12000);
console.error(
"Excalidraw rejected invalid synchronized settings data and restored the active settings",
);
await this.persistSnapshot(
encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
),
);
return false;
}
const recoveredSettings = await this.loadRecoverySnapshot();
if (recoveredSettings) {
persistedSettings = recoveredSettings;
recoveredInvalidStartup = true;
shouldPersistStartupChoice = true;
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
} else {
this.host.settings = Object.assign({}, DEFAULT_SETTINGS);
const choice = await this.requestStartupRecoveryChoice(
"invalid-without-recovery",
);
persistedSettings = {};
if (choice === "reset-defaults") {
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
shouldPersistStartupChoice = true;
} else {
this.blockPersistenceWhileWaitingForFile();
}
}
} else if (isFirstInstallation) {
const recoveredSettings = await this.loadRecoverySnapshot();
if (recoveredSettings) {
this.host.settings = Object.assign({}, DEFAULT_SETTINGS);
const choice = await this.requestStartupRecoveryChoice(
"missing-with-recovery",
);
persistedSettings =
choice === "reset-defaults" ? {} : recoveredSettings;
} else {
persistedSettings = {};
}
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
shouldPersistStartupChoice = true;
} else {
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
persistedSettings = isSettingsDataRecord(loadedSettings)
? loadedSettings
: {};
}
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
let didSettingsMigration = false;
this.host.settings = Object.assign(
@@ -149,17 +282,114 @@ export class PluginSettingsManager {
const shouldPersistEncryptedSettings =
JSON.stringify(encryptedPersistedSettings) !==
JSON.stringify(persistedSettings);
if (didSettingsMigration || shouldPersistEncryptedSettings) {
await this.host.saveData(encryptedPersistedSettings);
if (shouldPersistStartupChoice) {
await this.persistSnapshot(encryptedPersistedSettings);
if (recoveredInvalidStartup) {
new Notice(t("SETTINGS_DATA_RECOVERED"), 12000);
}
} else if (
!this.persistenceBlockedByInvalidData &&
(didSettingsMigration || shouldPersistEncryptedSettings)
) {
await this.persistSnapshot(encryptedPersistedSettings);
} else if (!this.persistenceBlockedByInvalidData) {
await this.saveRecoverySnapshot(encryptedPersistedSettings);
}
this.hasCompletedInitialLoad = true;
return !hasInvalidSettings;
}
/** Encrypts protected fields and persists the current settings object. */
public async saveSettings(): Promise<void> {
await this.host.saveData(
public saveSettings(): Promise<void> {
if (this.persistenceBlockedByInvalidData) {
this.showMissingRecoveryNotice();
return Promise.resolve();
}
return this.persistSnapshot(
encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
),
);
}
/** Whether plugin startup is intentionally waiting for a recovery choice. */
public get isAwaitingStartupRecoveryChoice(): boolean {
return this.awaitingStartupRecoveryChoice;
}
private persistSnapshot(
settings: PersistedExcalidrawSettings,
): Promise<void> {
return this.writer.persist(settings);
}
/** Closes the device-local recovery database connection. */
public destroy(): void {
this.recoveryStore.destroy();
}
private async getSettingsDataFileState(): Promise<SettingsDataFileState> {
const pluginDirectory = this.host.manifest.dir;
if (!pluginDirectory) {
return "unknown";
}
try {
const stat = await this.host.app.vault.adapter.stat(
`${pluginDirectory}/data.json`,
);
if (!stat) {
return "missing";
}
return stat.size === 0 ? "empty" : "present";
} catch {
return "unknown";
}
}
private blockPersistenceWhileWaitingForFile(): void {
this.persistenceBlockedByInvalidData = true;
this.missingRecoveryNoticeShown = false;
}
private showMissingRecoveryNotice(): void {
if (this.missingRecoveryNoticeShown) {
return;
}
this.missingRecoveryNoticeShown = true;
console.error(
"Excalidraw settings data is empty or unreadable; waiting for a valid replacement file",
);
new Notice(t("SETTINGS_DATA_INVALID"), 12000);
}
private async requestStartupRecoveryChoice(
mode: SettingsRecoveryPromptMode,
): Promise<SettingsRecoveryChoice> {
this.awaitingStartupRecoveryChoice = true;
try {
return await this.promptForRecoveryChoice(mode);
} finally {
this.awaitingStartupRecoveryChoice = false;
}
}
private async loadRecoverySnapshot(): Promise<PersistedExcalidrawSettings | null> {
try {
const recoveredSettings = await this.recoveryStore.load();
return isSettingsDataRecord(recoveredSettings) ? recoveredSettings : null;
} catch (error) {
console.error("Could not load Excalidraw settings recovery", error);
return null;
}
}
private async saveRecoverySnapshot(
settings: PersistedExcalidrawSettings,
): Promise<void> {
try {
await this.recoveryStore.save(settings);
} catch (error) {
console.error("Could not update Excalidraw settings recovery", error);
}
}
}
+42 -9
View File
@@ -38,6 +38,8 @@ export class StencilLibraryManager {
private itemSource = new Map<LibraryItem["id"], string>();
private currentItems: LibraryItems = [];
private loaded = false;
private loadRevision = 0;
private loadPromise: Promise<void> | null = null;
private migrationPrompt: Promise<void> | null = null;
private saveQueue: Promise<void> = Promise.resolve();
private reloadTimer: number | null = null;
@@ -86,6 +88,7 @@ export class StencilLibraryManager {
}
public invalidate(): void {
this.loadRevision++;
this.loaded = false;
this.itemSource.clear();
this.currentItems = [];
@@ -109,7 +112,7 @@ export class StencilLibraryManager {
await this.migrateLegacyLibrary();
}
if (!this.loaded) {
await this.loadFromVault();
await this.ensureLoaded();
}
return this.currentItems;
}
@@ -156,7 +159,7 @@ export class StencilLibraryManager {
}
await this.saveQueue;
this.invalidate();
await this.loadFromVault();
await this.ensureLoaded();
this.isUpdatingOpenViews = true;
try {
for (const view of getExcalidrawViews(this.plugin.app, true)) {
@@ -286,8 +289,39 @@ export class StencilLibraryManager {
}
}
private async loadFromVault(): Promise<void> {
this.itemSource.clear();
/** Coalesces concurrent view initialization into one vault-library load. */
private async ensureLoaded(): Promise<void> {
while (!this.loaded) {
if (this.loadPromise === null) {
const revision = this.loadRevision;
this.loadPromise = this.loadFromVault().then(
({ itemSource, items }) => {
if (revision !== this.loadRevision) {
return;
}
this.itemSource = itemSource;
this.currentItems = items;
this.loaded = true;
},
);
}
const activeLoad: Promise<void> = this.loadPromise;
try {
await activeLoad;
} finally {
if (this.loadPromise === activeLoad) {
this.loadPromise = null;
}
}
}
}
/** Reads a coherent library snapshot without mutating the active cache. */
private async loadFromVault(): Promise<{
itemSource: Map<LibraryItem["id"], string>;
items: LibraryItems;
}> {
const itemSource = new Map<LibraryItem["id"], string>();
const folderPath = this.getFolderPath();
const localPath = this.getLocalLibraryPath();
const files = this.plugin.app.vault
@@ -315,25 +349,24 @@ export class StencilLibraryManager {
isLocalFile ? "unpublished" : "published",
);
for (const item of items) {
if (this.itemSource.has(item.id)) {
if (itemSource.has(item.id)) {
console.warn(
`Duplicate stencil library item id '${item.id}' in ${file.path}; keeping the first occurrence.`,
);
continue;
}
this.itemSource.set(item.id, file.path);
itemSource.set(item.id, file.path);
combined.push(
isLocalFile ? item : { ...item, status: "published" as const },
);
}
}
this.currentItems = combined;
this.loaded = true;
return { itemSource, items: combined };
}
private async persistChanges(nextItems: LibraryItems): Promise<void> {
if (!this.loaded) {
await this.loadFromVault();
await this.ensureLoaded();
}
const previousById = new Map(
this.currentItems.map((item) => [item.id, item]),
@@ -0,0 +1,186 @@
import type {
AppState,
BinaryFiles,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import type { ExcalidrawDataMigrationState } from "../../shared/ExcalidrawData";
import type { TextMode } from "../../shared/TextMode";
import type { ViewSaveMigrationState } from "../../view/managers/ViewSaveCoordinator";
const DEFAULT_HANDOFF_TTL_MS = 15_000;
/** Drawing-owned runtime state that may cross an Obsidian window migration. */
export interface ViewMigrationDrawingState {
elements: readonly ExcalidrawElement[];
appState: AppState;
files: BinaryFiles;
textMode: TextMode;
compatibilityMode: boolean;
excalidrawData: ExcalidrawDataMigrationState;
save: ViewSaveMigrationState;
}
/** Metadata used to register one transient migration handoff. */
export interface ViewMigrationHandoffRegistration {
leafId: string;
filePath: string;
fileMtime: number;
drawing: ViewMigrationDrawingState;
}
/** Identity and freshness checks required to consume a migration handoff. */
export interface ViewMigrationHandoffRequest {
token: string;
leafId: string;
filePath: string;
fileMtime: number;
}
interface ViewMigrationHandoffEntry extends ViewMigrationHandoffRegistration {
token: string;
expiresAt: number;
}
interface ViewMigrationHandoffScheduler {
now: () => number;
setTimeout: (callback: () => void, delay: number) => number;
clearTimeout: (timer: number) => void;
}
interface ViewMigrationHandoffManagerOptions {
ttlMs?: number;
scheduler?: ViewMigrationHandoffScheduler;
}
/**
* Owns bounded, one-shot drawing handoffs between recreated views.
*
* Entries contain drawing state only. They never retain an `ExcalidrawView`,
* React root, DOM node, `Window`, listener, or package lease. Consumption
* removes the entry before validation so stale or mismatched state cannot be
* retried, and a single expiry timer bounds abandoned payload lifetime.
*/
export class ViewMigrationHandoffManager {
private readonly ttlMs: number;
private readonly scheduler: ViewMigrationHandoffScheduler;
private readonly entries = new Map<string, ViewMigrationHandoffEntry>();
private readonly tokensByLeaf = new Map<string, string>();
private cleanupTimer: number | null = null;
private tokenSequence = 0;
public constructor(options: ViewMigrationHandoffManagerOptions = {}) {
this.ttlMs = options.ttlMs ?? DEFAULT_HANDOFF_TTL_MS;
if (!Number.isFinite(this.ttlMs) || this.ttlMs <= 0) {
throw new Error("View migration handoff TTL must be positive");
}
this.scheduler =
options.scheduler ??
{
now: () => Date.now(),
setTimeout: (callback, delay) => window.setTimeout(callback, delay),
clearTimeout: (timer) => window.clearTimeout(timer),
};
}
/** Registers a handoff, replacing any older payload for the same leaf. */
public register(registration: ViewMigrationHandoffRegistration): string {
this.pruneExpired();
const previousToken = this.tokensByLeaf.get(registration.leafId);
if (previousToken) {
this.deleteEntry(previousToken);
}
const now = this.scheduler.now();
const token = `view-migration-${now.toString(36)}-${(++this.tokenSequence).toString(36)}`;
this.entries.set(token, {
...registration,
token,
expiresAt: now + this.ttlMs,
});
this.tokensByLeaf.set(registration.leafId, token);
this.scheduleCleanup();
return token;
}
/**
* Consumes a matching handoff exactly once.
*
* A token mismatch, leaf/path mismatch, file modification, or TTL expiry
* returns `null` and discards the candidate so the caller must use its
* ordinary disk-backed load path.
*/
public consume(
request: ViewMigrationHandoffRequest,
): ViewMigrationDrawingState | null {
this.pruneExpired();
const entry = this.entries.get(request.token);
if (!entry) {
return null;
}
this.deleteEntry(request.token);
this.scheduleCleanup();
if (
entry.leafId !== request.leafId ||
entry.filePath !== request.filePath ||
entry.fileMtime !== request.fileMtime
) {
return null;
}
return entry.drawing;
}
/** Drops all retained drawing state and cancels expiry work. */
public destroy(): void {
if (this.cleanupTimer !== null) {
this.scheduler.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
this.entries.clear();
this.tokensByLeaf.clear();
}
private deleteEntry(token: string): void {
const entry = this.entries.get(token);
if (!entry) {
return;
}
this.entries.delete(token);
if (this.tokensByLeaf.get(entry.leafId) === token) {
this.tokensByLeaf.delete(entry.leafId);
}
}
private pruneExpired(): void {
const now = this.scheduler.now();
for (const [token, entry] of this.entries) {
if (entry.expiresAt <= now) {
this.deleteEntry(token);
}
}
if (this.entries.size === 0 && this.cleanupTimer !== null) {
this.scheduler.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
}
private scheduleCleanup(): void {
if (this.cleanupTimer !== null) {
this.scheduler.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
if (this.entries.size === 0) {
return;
}
let nextExpiry = Number.POSITIVE_INFINITY;
for (const entry of this.entries.values()) {
nextExpiry = Math.min(nextExpiry, entry.expiresAt);
}
this.cleanupTimer = this.scheduler.setTimeout(() => {
this.cleanupTimer = null;
this.pruneExpired();
this.scheduleCleanup();
}, Math.max(0, nextExpiry - this.scheduler.now()));
}
}
@@ -0,0 +1,95 @@
const DEFAULT_HANDOFF_TTL_MS = 15_000;
export interface ViewMigrationPersistenceHandoff {
leafId: string;
filePath: string;
data: string;
}
interface ViewMigrationPersistenceHandoffEntry extends ViewMigrationPersistenceHandoff {
expiresAt: number;
}
/**
* Owns bounded serialized drawing handoffs from a destroyed popout view to
* the replacement view in Obsidian's main window.
*
* Entries contain drawing text and stable identifiers only. They never retain
* a view, DOM node, React runtime, package lease, or Window. Consumption is
* one-shot, and abandoned entries expire promptly.
*/
export class ViewMigrationPersistenceHandoffManager {
private readonly entries = new Map<
string,
ViewMigrationPersistenceHandoffEntry
>();
private cleanupTimer: number | null = null;
/** Registers or replaces the pending drawing text for one workspace leaf. */
public register(handoff: ViewMigrationPersistenceHandoff): void {
this.pruneExpired();
this.entries.set(handoff.leafId, {
...handoff,
expiresAt: Date.now() + DEFAULT_HANDOFF_TTL_MS,
});
this.scheduleCleanup();
}
/** Consumes matching drawing text exactly once. */
public consume(leafId: string, filePath: string): string | null {
this.pruneExpired();
const entry = this.entries.get(leafId);
if (!entry) {
return null;
}
this.entries.delete(leafId);
this.scheduleCleanup();
return entry.filePath === filePath ? entry.data : null;
}
/** Discards an abandoned handoff after a failed view replacement. */
public discard(leafId: string): void {
this.entries.delete(leafId);
this.scheduleCleanup();
}
/** Clears retained text and its main-window cleanup timer. */
public destroy(): void {
if (this.cleanupTimer !== null) {
window.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
this.entries.clear();
}
private pruneExpired(): void {
const now = Date.now();
for (const [leafId, entry] of this.entries) {
if (entry.expiresAt <= now) {
this.entries.delete(leafId);
}
}
}
private scheduleCleanup(): void {
if (this.cleanupTimer !== null) {
window.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
if (this.entries.size === 0) {
return;
}
let nextExpiry = Number.POSITIVE_INFINITY;
for (const entry of this.entries.values()) {
nextExpiry = Math.min(nextExpiry, entry.expiresAt);
}
this.cleanupTimer = window.setTimeout(
() => {
this.cleanupTimer = null;
this.pruneExpired();
this.scheduleCleanup();
},
Math.max(0, nextExpiry - Date.now()),
);
}
}
+4245 -2603
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,149 @@
/**
* Obsidian 1.13 declarative adapter for canonical setting specifications.
*/
import type { SettingBindingRegistry } from "src/core/settings/SettingBindingRegistry";
import type { LegacySettingsAdapter } from "src/core/settings/LegacySettingsAdapter";
import type {
SettingBindingKey,
SettingSpec,
} from "src/core/settings/settingSpecs";
import type {
SettingDefinition,
} from "src/types/obsidianDeclarativeSettings";
import { annotateMarkdownDefinition } from "src/core/settings/declarativeSettingsMarkdown";
/** Converts canonical setting rows into Obsidian 1.13 definitions. */
export class DeclarativeSettingsAdapter {
private readonly bindings: SettingBindingRegistry;
private readonly legacyAdapter: LegacySettingsAdapter;
private registerBindings = true;
constructor(
bindings: SettingBindingRegistry,
legacyAdapter: LegacySettingsAdapter,
) {
this.bindings = bindings;
this.legacyAdapter = legacyAdapter;
}
/** Starts a definition build, optionally replacing the live control bindings. */
beginBuild(registerBindings: boolean = true): void {
this.registerBindings = registerBindings;
if (registerBindings) {
this.bindings.clear();
}
}
/** Converts one canonical row during the current definition build. */
toDefinition(spec: SettingSpec): SettingDefinition<SettingBindingKey> {
if (this.requiresCustomRender(spec)) {
return this.toRenderedDefinition(spec);
}
if (this.registerBindings) {
this.bindings.register(spec);
}
const base = {
name: this.toSearchText(spec.name),
desc: spec.desc,
aliases: spec.aliases,
searchable: spec.searchable,
visible: spec.visible,
};
const control = spec.control;
switch (control.type) {
case "toggle":
return {
...base,
control: {
type: "toggle",
key: control.key,
disabled: control.disabled,
},
};
case "text":
return {
...base,
control: {
type: "text",
key: control.key,
placeholder: control.placeholder,
disabled: control.disabled,
},
};
case "dropdown":
return {
...base,
control: {
type: "dropdown",
key: control.key,
options: Object.fromEntries(
control.options.map(({ value, label }) => [value, label]),
),
disabled: control.disabled,
},
};
case "number-dropdown":
return {
...base,
control: {
type: "dropdown",
key: control.key,
options: Object.fromEntries(
control.options.map(({ value, label }) => [
value.toString(),
label,
]),
),
disabled: control.disabled,
},
};
case "slider":
return {
...base,
control: {
type: "slider",
key: control.key,
min: control.min,
max: control.max,
step: control.step,
disabled: control.disabled,
},
};
}
}
private requiresCustomRender(spec: SettingSpec): boolean {
if (typeof spec.name !== "string") {
return true;
}
const control = spec.control;
return (
(control.type === "text" &&
Boolean(control.capture || control.sanitize || control.vaultPath)) ||
(control.type === "slider" && control.minWidth !== undefined)
);
}
private toRenderedDefinition(
spec: SettingSpec,
): SettingDefinition<SettingBindingKey> {
return annotateMarkdownDefinition(
{
name: this.toSearchText(spec.name),
desc:
spec.desc === undefined ? undefined : this.toSearchText(spec.desc),
aliases: spec.aliases,
searchable: spec.searchable,
visible: spec.visible,
render: (setting) => this.legacyAdapter.configure(setting, spec),
},
{ controlType: spec.control.type },
);
}
private toSearchText(value: string | DocumentFragment): string {
return typeof value === "string" ? value : (value.textContent ?? "");
}
}
+138
View File
@@ -0,0 +1,138 @@
/**
* Imperative renderer for canonical setting-row specifications.
*/
import { Setting, type TextComponent } from "obsidian";
import type { SettingBindingRegistry } from "src/core/settings/SettingBindingRegistry";
import type {
SettingSpec,
TextControl,
} from "src/core/settings/settingSpecs";
import { configureSliderWithText } from "src/utils/sliderUtils";
/** Legacy-only services used by custom text controls. */
export interface LegacySettingsAdapterHost {
addVaultPathSupport(
setting: Setting,
text: TextComponent,
kind: "file" | "folder",
options: NonNullable<TextControl["vaultPath"]>["options"],
): void;
}
/** Builds or configures imperative Obsidian setting rows from canonical specs. */
export class LegacySettingsAdapter {
constructor(
private readonly bindings: SettingBindingRegistry,
private readonly host: LegacySettingsAdapterHost,
) {}
/**
* Creates one legacy row. Slider return behavior remains `undefined` for
* compatibility with the former in-class interpreter.
*/
render(container: HTMLElement, spec: SettingSpec): Setting | undefined {
const visible =
typeof spec.visible === "function"
? spec.visible()
: (spec.visible ?? true);
if (!visible) {
return undefined;
}
const setting = new Setting(container);
this.configure(setting, spec);
return spec.control.type === "slider" ? undefined : setting;
}
/** Configures a row supplied by either the legacy or declarative host. */
configure(setting: Setting, spec: SettingSpec): void {
const control = spec.control;
const disabled =
typeof control.disabled === "function"
? control.disabled()
: (control.disabled ?? false);
if (control.type === "slider") {
configureSliderWithText(setting, {
name: spec.name,
desc: spec.desc,
value: this.bindings.getSpecValue(spec) as number,
min: control.min,
max: control.max,
step: control.step,
minWidth: control.minWidth,
onChange: (value) => this.bindings.setLegacySpecValue(spec, value),
});
setting.setDisabled(disabled);
return;
}
setting.setName(spec.name);
if (spec.desc) {
setting.setDesc(spec.desc);
}
switch (control.type) {
case "toggle":
setting.addToggle((toggle) =>
toggle
.setValue(this.bindings.getSpecValue(spec) as boolean)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value),
),
);
break;
case "text":
setting.addText((text) => {
control.capture?.(text);
if (control.placeholder !== undefined) {
text.setPlaceholder(control.placeholder);
}
text
.setValue(this.bindings.getSpecValue(spec) as string)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value, () => {
if (control.sanitize) {
text.setValue(this.bindings.getSpecValue(spec) as string);
}
}),
);
if (control.vaultPath) {
this.host.addVaultPathSupport(
setting,
text,
control.vaultPath.kind,
control.vaultPath.options,
);
}
});
break;
case "dropdown":
setting.addDropdown((dropdown) => {
for (const option of control.options) {
dropdown.addOption(option.value, option.label);
}
dropdown
.setValue(this.bindings.getSpecValue(spec) as string)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value),
);
});
break;
case "number-dropdown":
setting.addDropdown((dropdown) => {
for (const option of control.options) {
dropdown.addOption(option.value.toString(), option.label);
}
dropdown
.setValue(this.bindings.getSpecValue(spec) as string)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value),
);
});
}
// Setting#setDisabled only affects controls that already exist. Apply the
// initial predicate after configuring the row so dependent controls start
// in the same state in both legacy and declarative render paths.
setting.setDisabled(disabled);
}
}
@@ -0,0 +1,42 @@
/**
* Serialized stable-snapshot writer for plugin settings.
*/
/** Persistence operation required by the serialized settings writer. */
export interface SerializedSettingsWriterHost<Snapshot> {
saveData(data: Snapshot): Promise<void>;
}
/**
* Serializes complete settings writes so an older save cannot finish after a
* newer one. Each request captures an immutable JSON snapshot before waiting
* for an earlier write.
*/
export class SerializedSettingsWriter<
Snapshot extends Record<string, unknown>,
> {
private persistenceChain: Promise<void> = Promise.resolve();
public constructor(
private readonly host: SerializedSettingsWriterHost<Snapshot>,
) {}
/** Queues one stable snapshot and resolves when that snapshot is saved. */
public persist(settings: Snapshot): Promise<void> {
let snapshot: Snapshot;
try {
snapshot = JSON.parse(JSON.stringify(settings)) as Snapshot;
} catch (error) {
return Promise.reject(
error instanceof Error
? error
: new Error("Could not serialize settings snapshot"),
);
}
const persistence = this.persistenceChain
.catch((): void => undefined)
.then(() => this.host.saveData(snapshot));
this.persistenceChain = persistence;
return persistence;
}
}
+240
View File
@@ -0,0 +1,240 @@
/**
* Typed value and persistence bridge for canonical setting specifications.
*/
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
import type {
SettingBindingKey,
SettingControlSpec,
SettingSpec,
} from "src/core/settings/settingSpecs";
/** Services required to persist a canonical setting mutation. */
export interface SettingBindingHost {
getSettings(): ExcalidrawSettings;
queueSettingsUpdate(requestReloadDrawings: boolean): Promise<void>;
}
/**
* Resolves declarative control keys and applies the same transformations,
* hooks, save queue, and pending actions as the legacy controls.
*/
export class SettingBindingRegistry {
private readonly bindings = new Map<SettingBindingKey, SettingSpec>();
private readonly host: SettingBindingHost;
constructor(host: SettingBindingHost) {
this.host = host;
}
/** Clears bindings before a fresh declarative definition build. */
clear(): void {
this.bindings.clear();
}
/** Registers one native declarative control binding for the current build. */
register(spec: SettingSpec): void {
const { key } = spec.control;
if (this.bindings.has(key)) {
throw new Error(`Duplicate declarative setting binding: ${key}`);
}
this.bindings.set(key, spec);
}
/** Reads a registered declarative control value. */
getControlValue(key: string): unknown {
return this.getSpecValue(this.getBinding(key));
}
/** Writes a registered declarative control value and awaits persistence. */
setControlValue(key: string, value: unknown): Promise<void> {
return this.setSpecValue(this.getBinding(key), value);
}
/** Reads the UI-facing value for either adapter. */
getSpecValue(spec: SettingSpec): boolean | string | number {
const settings = this.host.getSettings();
const control = spec.control;
switch (control.type) {
case "toggle": {
const storedValue = settings[control.key];
return control.negate ? !storedValue : storedValue;
}
case "number-dropdown":
return settings[control.key].toString();
case "slider":
return settings[control.key] * (control.scale ?? 1);
default:
return settings[control.key];
}
}
/** Applies a UI-facing value from either adapter. */
setSpecValue(
spec: SettingSpec,
value: unknown,
afterWrite?: () => void,
): Promise<void> {
return this.setSpecValueInternal(spec, value, afterWrite, true);
}
/**
* Applies a legacy UI value without extending the component callback until
* queued disk persistence completes.
*/
setLegacySpecValue(
spec: SettingSpec,
value: unknown,
afterWrite?: () => void,
): Promise<void> {
return this.setSpecValueInternal(spec, value, afterWrite, false);
}
private async setSpecValueInternal(
spec: SettingSpec,
value: unknown,
afterWrite: (() => void) | undefined,
awaitPersistence: boolean,
): Promise<void> {
const control = spec.control;
switch (control.type) {
case "toggle": {
const nextValue = this.requireBoolean(control, value);
await control.before?.(nextValue);
this.setSettingValue(control.key, control.negate ? !nextValue : nextValue);
afterWrite?.();
await control.after?.(nextValue);
await this.persistAndRunAfterUpdate(
control,
nextValue,
awaitPersistence,
);
return;
}
case "text": {
const nextValue = this.requireString(control, value);
await control.before?.(nextValue);
this.setSettingValue(
control.key,
control.sanitize?.(nextValue) ?? nextValue,
);
afterWrite?.();
await control.after?.(nextValue);
await this.persistAndRunAfterUpdate(
control,
nextValue,
awaitPersistence,
);
return;
}
case "dropdown": {
const nextValue = this.requireString(control, value);
await control.before?.(nextValue);
this.setSettingValue(control.key, nextValue);
afterWrite?.();
await control.after?.(nextValue);
await this.persistAndRunAfterUpdate(
control,
nextValue,
awaitPersistence,
);
return;
}
case "number-dropdown": {
const rawValue = this.requireString(control, value);
const nextValue =
control.parse === "int" ? parseInt(rawValue) : parseFloat(rawValue);
await control.before?.(nextValue);
this.setSettingValue(control.key, nextValue);
afterWrite?.();
await control.after?.(nextValue);
await this.persistAndRunAfterUpdate(
control,
nextValue,
awaitPersistence,
);
return;
}
case "slider": {
const displayValue = this.requireNumber(control, value);
await control.before?.(displayValue);
this.setSettingValue(
control.key,
displayValue / (control.scale ?? 1),
);
afterWrite?.();
await control.after?.(displayValue);
await this.persistAndRunAfterUpdate(
control,
displayValue,
awaitPersistence,
);
}
}
}
private getBinding(key: string): SettingSpec {
const binding = this.bindings.get(key as SettingBindingKey);
if (!binding) {
throw new Error(`Unknown declarative setting binding: ${key}`);
}
return binding;
}
private setSettingValue<K extends keyof ExcalidrawSettings>(
key: K,
value: ExcalidrawSettings[K],
): void {
this.host.getSettings()[key] = value;
}
private async persistAndRunAfterUpdate<Value>(
control: SettingControlSpec & {
afterUpdate?: (value: Value) => void | Promise<void>;
},
value: Value,
awaitPersistence: boolean,
): Promise<void> {
const persistence = this.host.queueSettingsUpdate(control.reload ?? false);
if (awaitPersistence) {
try {
await control.afterUpdate?.(value);
} finally {
await persistence;
}
return;
}
await control.afterUpdate?.(value);
void persistence.catch((): void => undefined);
}
private requireBoolean(control: SettingControlSpec, value: unknown): boolean {
if (typeof value !== "boolean") {
throw this.invalidValueError(control, "boolean");
}
return value;
}
private requireString(control: SettingControlSpec, value: unknown): string {
if (typeof value !== "string") {
throw this.invalidValueError(control, "string");
}
return value;
}
private requireNumber(control: SettingControlSpec, value: unknown): number {
if (typeof value !== "number") {
throw this.invalidValueError(control, "number");
}
return value;
}
private invalidValueError(
control: SettingControlSpec,
expectedType: string,
): TypeError {
return new TypeError(
`Invalid value for setting '${control.key}': expected ${expectedType}`,
);
}
}
@@ -0,0 +1,145 @@
/**
* Coalesces settings mutations so rapid controls do not enqueue one complete
* `data.json` write per input event.
*/
/** Persistence operations owned by the settings tab. */
export interface SettingsPersistenceQueueHost {
/** Persists the latest in-memory settings snapshot. */
persistSettings(): Promise<void>;
/** Applies side effects that must observe a successfully persisted snapshot. */
applyPendingActions(): Promise<void>;
/** Returns true while persistence would replace a control being edited. */
shouldDeferPersistence?(): boolean;
}
interface PersistenceWaiter {
revision: number;
resolve: () => void;
reject: (reason: unknown) => void;
}
/**
* Trailing-edge persistence queue for settings mutations.
*
* Rapid mutations are collapsed into one write. If another mutation arrives
* while that write is in flight, one follow-up write persists the newest
* snapshot before pending actions and callers are released.
*/
export class SettingsPersistenceQueue {
private requestedRevision = 0;
private completedRevision = 0;
private debounceTimer: number | null = null;
private activeRun: Promise<void> | null = null;
private waiters: PersistenceWaiter[] = [];
constructor(
private readonly host: SettingsPersistenceQueueHost,
private readonly debounceMilliseconds: number = 250,
) {}
/**
* Records a mutation and resolves after a persisted snapshot containing it
* has had its pending actions applied.
*/
enqueue(): Promise<void> {
const revision = ++this.requestedRevision;
const persistence = new Promise<void>((resolve, reject) => {
this.waiters.push({ revision, resolve, reject });
});
this.schedule();
return persistence;
}
/** Immediately starts any scheduled persistence and awaits completion. */
flush(): Promise<void> {
this.cancelTimer();
if (this.activeRun !== null) {
return this.activeRun;
}
if (this.completedRevision >= this.requestedRevision) {
return Promise.resolve();
}
return this.startRun();
}
private schedule(): void {
if (this.activeRun !== null) {
return;
}
this.cancelTimer();
this.debounceTimer = window.setTimeout(() => {
this.debounceTimer = null;
if (this.host.shouldDeferPersistence?.()) {
this.schedule();
return;
}
void this.startRun().catch((): void => undefined);
}, this.debounceMilliseconds);
}
private cancelTimer(): void {
if (this.debounceTimer === null) {
return;
}
window.clearTimeout(this.debounceTimer);
this.debounceTimer = null;
}
private startRun(): Promise<void> {
if (this.activeRun !== null) {
return this.activeRun;
}
const run = this.persistLatestRevision();
this.activeRun = run;
void run
.finally(() => {
if (this.activeRun === run) {
this.activeRun = null;
}
})
.catch((): void => undefined);
return run;
}
private async persistLatestRevision(): Promise<void> {
try {
while (this.completedRevision < this.requestedRevision) {
const revisionToPersist = this.requestedRevision;
await this.host.persistSettings();
if (revisionToPersist !== this.requestedRevision) {
continue;
}
await this.host.applyPendingActions();
if (revisionToPersist !== this.requestedRevision) {
continue;
}
this.completedRevision = revisionToPersist;
this.resolveWaitersThrough(revisionToPersist);
}
} catch (error) {
this.rejectWaiters(error);
throw error;
}
}
private resolveWaitersThrough(revision: number): void {
const remaining: PersistenceWaiter[] = [];
for (const waiter of this.waiters) {
if (waiter.revision <= revision) {
waiter.resolve();
} else {
remaining.push(waiter);
}
}
this.waiters = remaining;
}
private rejectWaiters(reason: unknown): void {
const waiters = this.waiters;
this.waiters = [];
for (const waiter of waiters) {
waiter.reject(reason);
}
}
}
+185
View File
@@ -0,0 +1,185 @@
/**
* Device-local, transactional storage for the last known good settings.
*
* The recovery copy deliberately lives outside the vault and Obsidian's
* localStorage. IndexedDB can hold large legacy settings records and replaces
* the single recovery record atomically if a write completes.
*/
const DATABASE_VERSION = 1;
const STORE_NAME = "settingsRecovery";
const RECORD_KEY = "lastKnownGood";
const RECORD_VERSION = 1;
interface SettingsRecoveryRecord<Snapshot> {
version: typeof RECORD_VERSION;
settings: Snapshot;
}
interface SettingsRecoveryStoreOptions {
databaseName: string;
indexedDBFactory?: IDBFactory | null;
}
const normalizeError = (error: unknown, message: string): Error =>
error instanceof Error ? error : new Error(message);
/**
* Stores one durable last-known-good settings snapshot for the current vault.
*/
export class SettingsRecoveryStore<Snapshot extends Record<string, unknown>> {
private database: IDBDatabase | null = null;
private databasePromise: Promise<IDBDatabase> | null = null;
private readonly indexedDBFactory: IDBFactory | null;
private destroyed = false;
public constructor(private readonly options: SettingsRecoveryStoreOptions) {
this.indexedDBFactory =
"indexedDBFactory" in options
? (options.indexedDBFactory ?? null)
: typeof indexedDB === "undefined"
? null
: indexedDB;
}
/** Returns the last complete settings snapshot, if one is available. */
public async load(): Promise<Snapshot | null> {
const database = await this.getDatabase();
return new Promise<Snapshot | null>((resolve, reject) => {
let request: IDBRequest<SettingsRecoveryRecord<Snapshot> | undefined>;
try {
const transaction = database.transaction(STORE_NAME, "readonly");
request = transaction
.objectStore(STORE_NAME)
.get(RECORD_KEY) as IDBRequest<
SettingsRecoveryRecord<Snapshot> | undefined
>;
request.onsuccess = () => {
const record = request.result;
resolve(
record?.version === RECORD_VERSION &&
typeof record.settings === "object" &&
record.settings !== null &&
!Array.isArray(record.settings)
? record.settings
: null,
);
};
request.onerror = () => {
reject(
request.error ?? new Error("Could not read settings recovery"),
);
};
} catch (error) {
reject(normalizeError(error, "Could not read settings recovery"));
}
});
}
/** Atomically replaces the last-known-good settings snapshot. */
public async save(settings: Snapshot): Promise<void> {
const database = await this.getDatabase();
return new Promise<void>((resolve, reject) => {
try {
const transaction = database.transaction(STORE_NAME, "readwrite");
transaction.objectStore(STORE_NAME).put(
{
version: RECORD_VERSION,
settings,
} satisfies SettingsRecoveryRecord<Snapshot>,
RECORD_KEY,
);
transaction.oncomplete = () => resolve();
transaction.onerror = () => {
reject(
transaction.error ?? new Error("Could not save settings recovery"),
);
};
transaction.onabort = () => {
reject(
transaction.error ?? new Error("Settings recovery write aborted"),
);
};
} catch (error) {
reject(normalizeError(error, "Could not save settings recovery"));
}
});
}
/** Closes the database connection owned by this plugin instance. */
public destroy(): void {
this.destroyed = true;
this.database?.close();
this.database = null;
this.databasePromise = null;
}
private async getDatabase(): Promise<IDBDatabase> {
if (this.destroyed) {
throw new Error("Settings recovery store has been destroyed");
}
if (this.database) {
return this.database;
}
const indexedDBFactory = this.indexedDBFactory;
if (!indexedDBFactory) {
throw new Error("IndexedDB is unavailable for settings recovery");
}
if (this.databasePromise === null) {
this.databasePromise = this.openDatabase(indexedDBFactory);
}
try {
return await this.databasePromise;
} catch (error) {
this.database?.close();
this.database = null;
this.databasePromise = null;
throw error;
}
}
private openDatabase(indexedDBFactory: IDBFactory): Promise<IDBDatabase> {
return new Promise<IDBDatabase>((resolve, reject) => {
let requestCompleted = false;
const request = indexedDBFactory.open(
this.options.databaseName,
DATABASE_VERSION,
);
request.onupgradeneeded = () => {
const database = request.result;
if (!database.objectStoreNames.contains(STORE_NAME)) {
database.createObjectStore(STORE_NAME);
}
};
request.onsuccess = () => {
const database = request.result;
if (requestCompleted || this.destroyed) {
database.close();
if (!requestCompleted) {
requestCompleted = true;
reject(new Error("Settings recovery store has been destroyed"));
}
return;
}
requestCompleted = true;
database.onversionchange = () => {
database.close();
if (this.database === database) {
this.database = null;
this.databasePromise = null;
}
};
this.database = database;
resolve(database);
};
request.onerror = () => {
requestCompleted = true;
reject(request.error ?? new Error("Could not open settings recovery"));
};
request.onblocked = () => {
requestCompleted = true;
reject(new Error("Settings recovery database upgrade was blocked"));
};
});
}
}
@@ -0,0 +1,138 @@
/**
* Markdown export for Obsidian's declarative settings tree.
*
* The exporter reads the declarations rather than the currently mounted page,
* so nested and conditionally rendered settings remain discoverable in one
* document.
*/
import { htmlToMarkdown } from "obsidian";
import type {
SettingDefinition,
SettingDefinitionItem,
} from "src/types/obsidianDeclarativeSettings";
declare const mainDocument: Document;
declare const deliberateCreateElement: (
document: Document,
tagName: string,
) => HTMLElement;
interface MarkdownDefinitionMetadata {
controlType?: string;
omit?: boolean;
}
const definitionMetadata = new WeakMap<object, MarkdownDefinitionMetadata>();
/** Adds export-only metadata without exposing custom fields to Obsidian. */
export function annotateMarkdownDefinition<T extends object>(
definition: T,
metadata: MarkdownDefinitionMetadata,
): T {
definitionMetadata.set(definition, metadata);
return definition;
}
function toMarkdown(value: string | DocumentFragment | undefined): string {
if (value === undefined) {
return "";
}
if (typeof value === "string") {
return htmlToMarkdown(value).trim();
}
const container = deliberateCreateElement(mainDocument, "div");
container.appendChild(value.cloneNode(true));
return htmlToMarkdown(container.innerHTML).trim();
}
function normalizeControlType(controlType: string): string {
switch (controlType) {
case "text":
return "text input";
case "number-dropdown":
return "dropdown";
case "textarea":
return "text area";
default:
return controlType;
}
}
function getControlType(definition: SettingDefinition): string | undefined {
const metadata = definitionMetadata.get(definition);
if (metadata?.controlType) {
return normalizeControlType(metadata.controlType);
}
if ("control" in definition && definition.control) {
return normalizeControlType(definition.control.type);
}
if ("render" in definition && definition.render) {
return "custom control";
}
return undefined;
}
function renderSetting(definition: SettingDefinition): string | null {
const metadata = definitionMetadata.get(definition);
if (metadata?.omit) {
return null;
}
const description = toMarkdown(definition.desc);
const controlType = getControlType(definition);
const typePrefix = controlType ? ` (${controlType})` : "";
return `- **${definition.name}:**${typePrefix}${description ? ` ${description}` : ""}`;
}
function renderItems(
items: readonly SettingDefinitionItem[],
headingLevel: number,
): string[] {
const output: string[] = [];
for (const item of items) {
if ("type" in item) {
output.push(`${"#".repeat(headingLevel)} ${item.name}`);
const description = toMarkdown(item.desc);
if (description) {
output.push(description);
}
if (item.items?.length) {
output.push(...renderItems(item.items, headingLevel + 1));
}
continue;
}
const setting = renderSetting(item);
if (setting) {
output.push(setting);
}
}
return output;
}
/** Converts a complete declarative settings tree into one Markdown document. */
export function declarativeSettingsToMarkdown(
definitions: readonly SettingDefinitionItem[],
): string {
const blocks = renderItems(definitions, 1);
if (blocks.length === 0) {
return "";
}
let markdown = "";
let previousBlock = "";
for (const block of blocks) {
const separator =
markdown.length === 0
? ""
: previousBlock.startsWith("- **") && block.startsWith("- **")
? "\n"
: "\n\n";
markdown += `${separator}${block}`;
previousBlock = block;
}
return `${markdown}\n`;
}
+126
View File
@@ -0,0 +1,126 @@
/**
* Canonical setting-row specifications shared by the legacy and declarative
* settings adapters.
*/
import type { TextComponent } from "obsidian";
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
/** Keys of {@link ExcalidrawSettings} whose value type is boolean. */
export type BooleanSettingKey = {
[K in keyof ExcalidrawSettings]: ExcalidrawSettings[K] extends boolean
? K
: never;
}[keyof ExcalidrawSettings];
/** Keys whose value type is exactly `string`, excluding literal unions. */
export type StringSettingKey = {
[K in keyof ExcalidrawSettings]: string extends ExcalidrawSettings[K]
? ExcalidrawSettings[K] extends string
? K
: never
: never;
}[keyof ExcalidrawSettings];
/** Keys whose value is a string or a narrower string-literal union. */
export type StringLikeSettingKey = {
[K in keyof ExcalidrawSettings]: ExcalidrawSettings[K] extends string
? K
: never;
}[keyof ExcalidrawSettings];
/** Keys of {@link ExcalidrawSettings} whose value type is number. */
export type NumberSettingKey = {
[K in keyof ExcalidrawSettings]: ExcalidrawSettings[K] extends number
? K
: never;
}[keyof ExcalidrawSettings];
/** Every persisted key currently supported by a canonical row binding. */
export type SettingBindingKey =
| BooleanSettingKey
| StringLikeSettingKey
| NumberSettingKey;
type SettingControlBase<Value, Key extends SettingBindingKey> = {
key: Key;
before?: (value: Value) => void | Promise<void>;
after?: (value: Value) => void | Promise<void>;
afterUpdate?: (value: Value) => void | Promise<void>;
reload?: boolean;
disabled?: boolean | (() => boolean);
};
/** Canonical toggle control, including support for an inverted stored value. */
export type ToggleControl = SettingControlBase<boolean, BooleanSettingKey> & {
type: "toggle";
negate?: boolean;
};
/** Canonical text control and its legacy-only component integrations. */
export type TextControl = SettingControlBase<string, StringSettingKey> & {
type: "text";
placeholder?: string;
sanitize?: (value: string) => string;
vaultPath?: {
kind: "file" | "folder";
options?: {
optional?: boolean;
extensions?: readonly string[];
resolvePath?: (value: string) => string;
createFolder?: boolean;
validate?: boolean;
};
};
capture?: (text: TextComponent) => void;
};
/** Canonical string-valued dropdown control. */
export type DropdownControl = SettingControlBase<
string,
StringLikeSettingKey
> & {
type: "dropdown";
options: readonly { value: string; label: string }[];
};
/** Canonical numeric value represented by string-valued dropdown options. */
export type NumberDropdownControl = SettingControlBase<
number,
NumberSettingKey
> & {
type: "number-dropdown";
options: readonly { value: number; label: string }[];
parse?: "int" | "float";
};
/** Canonical numeric slider control. */
export type SliderControl = SettingControlBase<number, NumberSettingKey> & {
type: "slider";
min: number;
max: number;
step: number;
minWidth?: string;
scale?: number;
};
/** Controls currently understood by both settings adapters. */
export type SettingControlSpec =
| ToggleControl
| TextControl
| DropdownControl
| NumberDropdownControl
| SliderControl;
/**
* One canonical setting row. Search metadata is declarative-only; visibility
* and disabled predicates are interpreted by both adapters.
*/
export interface SettingSpec {
name: string | DocumentFragment;
desc?: string | DocumentFragment;
aliases?: string[];
searchable?: boolean | (() => boolean);
visible?: boolean | (() => boolean);
control: SettingControlSpec;
}
@@ -0,0 +1,44 @@
/** Classification helpers for safely loading plugin settings data. */
/** Observable state of the plugin's `data.json` file before loading it. */
export type SettingsDataFileState =
| "missing"
| "empty"
| "present"
| "unknown";
/** Result of validating one settings load attempt. */
export type SettingsDataLoadClassification =
| "valid"
| "first-installation"
| "invalid";
/** Returns true for the object shape accepted as persisted settings data. */
export const isSettingsDataRecord = (
value: unknown,
): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/**
* Distinguishes a genuine first installation from an empty, malformed, or
* failed settings load that must not replace already loaded settings.
*/
export function classifySettingsDataLoad(options: {
value: unknown;
fileState: SettingsDataFileState;
loadFailed: boolean;
isInitialLoad: boolean;
}): SettingsDataLoadClassification {
if (isSettingsDataRecord(options.value)) {
return "valid";
}
if (
options.isInitialLoad &&
!options.loadFailed &&
(options.value === null || typeof options.value === "undefined") &&
options.fileState === "missing"
) {
return "first-installation";
}
return "invalid";
}
+51
View File
@@ -0,0 +1,51 @@
import type { App } from "obsidian";
/** Returns whether the current Obsidian runtime exposes page navigation. */
export function canNavigateSettingsPages(app: App): boolean {
return (
typeof app.setting.openPagePath === "function" ||
(typeof app.setting.findTabById === "function" &&
typeof app.setting.navigateToPage === "function")
);
}
/**
* Navigates to a declarative settings page through Obsidian's unpublished
* settings API.
*
* The method is deliberately isolated behind structural and exception guards
* because it is not part of Obsidian's public compatibility contract.
*
* @returns `true` when Obsidian accepted the navigation request, otherwise
* `false` so callers can leave the current page intact.
*/
export function navigateToSettingsPage(
app: App,
tabId: string,
pagePath: readonly string[],
): boolean {
try {
if (typeof app.setting.openPagePath === "function") {
return app.setting.openPagePath(tabId, [...pagePath]) !== null;
}
if (
typeof app.setting.findTabById !== "function" ||
typeof app.setting.navigateToPage !== "function"
) {
return false;
}
const tab = app.setting.findTabById(tabId);
if (!tab) {
return false;
}
app.setting.navigateToPage(tab, [...pagePath]);
return true;
} catch (error) {
console.warn(
"Excalidraw: Obsidian settings page navigation is unavailable.",
error,
);
return false;
}
}
+7 -1
View File
@@ -56,6 +56,8 @@ export interface ExcalidrawSettings {
embedUseExcalidrawFolder: boolean;
templateFilePath: string;
scriptFolderPath: string;
allowJavaScriptFiles: boolean;
storeScriptFilesAsJavaScript: boolean;
fontAssetsPath: string;
loadChineseFonts: boolean;
loadJapaneseFonts: boolean;
@@ -197,6 +199,7 @@ export interface ExcalidrawSettings {
};
previousRelease: string;
showReleaseNotes: boolean;
useDeclarativeSettings: boolean;
excalidrawMasteryPromoCollapsed: boolean;
compareManifestToPluginVersion: boolean;
showNewVersionNotification: boolean;
@@ -500,6 +503,8 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
embedUseExcalidrawFolder: false,
templateFilePath: "Excalidraw/Template.excalidraw",
scriptFolderPath: "Excalidraw/Scripts",
allowJavaScriptFiles: false,
storeScriptFilesAsJavaScript: false,
fontAssetsPath: "Excalidraw/CJK Fonts",
loadChineseFonts: false,
loadJapaneseFonts: false,
@@ -560,7 +565,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
urlPrefix: "",
parseTODO: false,
todo: "☐",
done: "🗹",
done: "☑",
hoverPreviewWithoutCTRL: false,
linkOpacity: 1,
openInAdjacentPane: true,
@@ -650,6 +655,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
autostartScriptFailures: {},
previousRelease: "0.0.0",
showReleaseNotes: true,
useDeclarativeSettings: true,
excalidrawMasteryPromoCollapsed: false,
compareManifestToPluginVersion: true,
showNewVersionNotification: true,
+156 -6
View File
@@ -22,6 +22,21 @@ export default {
SELECT_FILE_TO_INSERT: "Select a file to insert",
// main.ts
ERROR_INITIALIZING_EA: "Error initializing Excalidraw Automate",
SETTINGS_DATA_INVALID:
"Excalidraw is waiting for a valid replacement data.json. Setting changes will not be saved until that file is restored, or you restart Obsidian and choose Reset to defaults.",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"An empty or unreadable Excalidraw settings file was received and rejected. The active settings were written back to repair data.json.",
SETTINGS_DATA_RECOVERED:
"Excalidraw data.json was empty or unreadable. The last known good settings were restored automatically.",
SETTINGS_RECOVERY_MISSING_TITLE: "Excalidraw settings file is missing",
SETTINGS_RECOVERY_MISSING_DESC:
"A last known good settings backup exists on this device. Restore that backup, or reset Excalidraw to factory defaults. Closing this message restores the backup.",
SETTINGS_RECOVERY_CORRUPT_TITLE: "Excalidraw settings file is corrupted",
SETTINGS_RECOVERY_CORRUPT_DESC:
"The settings file is empty or unreadable, and no recovery backup is available on this device. Reset Excalidraw to factory defaults, or leave the file unchanged while you restore a valid data.json from another source. Closing this message waits for a replacement file.",
SETTINGS_RECOVERY_RESTORE_BACKUP: "Restore backup",
SETTINGS_RECOVERY_RESET_DEFAULTS: "Reset to defaults",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "Wait for restored file",
CONVERT_URL_TO_FILE: "Save image from URL to local file",
UNZIP_CURRENT_FILE: "Decompress current Excalidraw file",
PUBLISH_SVG_CHECK:
@@ -384,6 +399,18 @@ export default {
SEARCH_SHOWHIDE_ARIA: "Show/Hide search bar",
SEARCH_NEXT: "Next",
SEARCH_PREVIOUS: "Previous",
SETTINGS_TOOLBAR_COPY: "Copy settings",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "Bugs",
SETTINGS_TOOLBAR_WIKI: "Wiki",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "Learn",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "Read Book",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "Use searchable settings",
USE_DECLARATIVE_SETTINGS_DESC:
"Use Obsidian's searchable, multi-page settings interface. Turn this off to use Excalidraw's legacy single-page settings. Requires restarting Obsidian.",
//settings.ts
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
@@ -418,8 +445,6 @@ export default {
"Disables the Excalidraw context menu. This can be useful on Mobile devices where the context menu pops up in unwanted moments.",
NOTEBOOKLM_LINK_ARIA:
"Ask NotebookLM for help about the plugin. This model is pre-loaded with all my video transcripts, release notes and other helpful content. Chat with NotebookLM to explore my 250+ videos and the Excalidraw documentation.",
NOTEBOOKLM_LINK_TEXT:
"Learn the Plugin. Access the NotebookLM knowledgebase.",
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_ARIA: "Open Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>Feeling lost in the toggles and menus?</b></p><p>Excalidraw is a Visual PKM powerhouse built for heavy-duty workflows like <b>Visual-First Daily Notes</b>, deep <b>PDF research</b>, <b>automation</b>, <b>AI integration</b>, and <b>Visual Zettelkasten</b>. But all this power comes with complexity.</p><p>Skip the trial and error. <a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 Join Excalidraw Mastery</a> to learn these exact setups step-by-step. Overcome tool friction and master your knowledge alongside a supportive community of visual thinkers!</p>`,
@@ -453,6 +478,15 @@ export default {
"<b><u>Toggle OFF:</u></b> Silent mode. You need to check for plugin updates in Community Plugins.",
BASIC_HEAD: "Basic",
BASIC_UPDATES_STARTUP_HEAD: "Updates and startup",
BASIC_UPDATES_STARTUP_DESC:
"Release notes, update checks and notifications, and the startup splash screen.",
BASIC_FILES_FOLDERS_HEAD: "Files and folders",
BASIC_FILES_FOLDERS_DESC:
"Default folders and paths for drawings, crops, annotations, templates, and Excalidraw Automate scripts.",
BASIC_STENCIL_LIBRARY_HEAD: "Stencil Library",
BASIC_STENCIL_LIBRARY_DESC:
"Choose where stencil library data is stored and configure its vault folder and local library file.",
BASIC_DESC: `In the "Basic" settings, you can configure options such as displaying release notes after updates, receiving plugin update notifications, setting the default location for new drawings, specifying the Excalidraw folder for embedding drawings into active documents, defining an Excalidraw template file, and designating an Excalidraw Automate script folder for managing automation scripts.`,
FOLDER_NAME: "Excalidraw folder (CAsE sEnsITive!)",
FOLDER_DESC:
@@ -652,6 +686,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"View AI token consumption for the current Obsidian session broken down by model. Usage resets on restart.",
SAVING_HEAD: "Saving",
SAVING_STORAGE_AUTOSAVE_HEAD: "Storage and autosave",
SAVING_STORAGE_AUTOSAVE_DESC:
"Control drawing JSON compression and choose desktop and mobile autosave intervals.",
SAVING_DESC:
"In the 'Saving' section of Excalidraw Settings, you can configure how your drawings are saved. This includes options for compressing Excalidraw JSON in Markdown, setting autosave intervals for both desktop and mobile, defining filename formats, and choosing whether to use the .excalidraw.md or .md file extension. ",
COMPRESS_NAME: "Compress Excalidraw JSON in Markdown",
@@ -685,6 +722,8 @@ export default {
"Excalidraw will not be able to save your work when terminating Obsidian directly (i.e. swiping it away). Also note, that when you switch apps on a Mobile device, sometimes Android and iOS closes " +
"Obsidian in the background to save system resources. In such a case Excalidraw will not be able to save the latest changes.",
FILENAME_HEAD: "Filename",
FILENAME_GROUP_DESC:
"Configure how new, embedded, cropped, and annotated drawing filenames are generated.",
FILENAME_DESC:
`<p>Click this link for the <a href="${URLs.MOMENTJS_COM_DOCS}">` +
"date and time format reference</a>.</p>",
@@ -712,6 +751,9 @@ export default {
DISPLAY_HEAD: "Excalidraw appearance and behavior",
DISPLAY_DESC:
"In the 'appearance and behavior' section of Excalidraw Settings, you can fine-tune how Excalidraw appears and behaves. This includes options for dynamic styling, left-handed mode, matching Excalidraw and Obsidian themes, default modes, and more.",
DISPLAY_EDITOR_PREVIEWS_HEAD: "Editing and previews",
DISPLAY_EDITOR_PREVIEWS_DESC:
"Configure canvas editing gestures and how Excalidraw files appear in reading mode and hover previews.",
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "Limit Obsidian Font Size to Editor Text",
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
"Obsidian's custom font size setting affects the entire interface, including Excalidraw and themes that depend on the default font size. " +
@@ -792,6 +834,8 @@ export default {
}'>Markdown Reading Mode</a> under 'Appearance and Behavior' further above.<br>` +
`⚠️ You must close and reopen the Excalidraw/markdown file for changes to take effect. ⚠️`,
MODES_HEAD: "UI Modes",
MODES_DESC:
"Choose device-specific Excalidraw interface layouts, title-bar controls, and left- or right-handed tray placement.",
DESKTOP_UI_MODE_NAME: "Preferred Desktop Mode",
DESKTOP_UI_MODE_DESC: "Select the default UI mode for desktop devices.",
TABLET_UI_MODE_NAME: "Preferred Tablet Mode",
@@ -804,12 +848,19 @@ export default {
MODE_PHONE: "Phone-mode",
REAPPLY_UI_MODE_BUTTON: "Reapply UI mode now",
HOTKEY_OVERRIDE_HEAD: "Hotkey overrides",
HOTKEY_OVERRIDE_GROUP_DESC:
"Manage Excalidraw key combinations that should take priority over conflicting Obsidian hotkeys.",
HOTKEY_OVERRIDE_CONTROL_NAME: "Manage hotkey overrides",
HOTKEY_OVERRIDE_DESC:
`Some of the Excalidraw hotkeys such as <code>${labelCTRL()}+Enter</code> to edit text or <code>${labelCTRL()}+K</code> to create an element link ` +
"conflict with Obsidian hotkey settings. The hotkey combinations you add below will override Obsidian's hotkey settings while using Excalidraw, thus " +
`you can add <code>${labelCTRL()}+G</code> if you want to default to Group Object in Excalidraw instead of opening Graph View.`,
THEME_HEAD: "Theme and styling",
THEME_DESC:
"Control interface styling, drawing and embed themes, opening mode, and mobile safe-area spacing.",
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.",
@@ -842,7 +893,11 @@ export default {
ZOOM_MAX_DESC:
"Upper zoom limit. Default: 3000%. Usually no need to change; included for completeness.",
PEN_HEAD: "Pen",
PEN_DESC:
"Configure automatic pen mode, touch gestures, the eraser, and the freedraw crosshair.",
GRID_HEAD: "Grid",
GRID_DESC:
"Configure grid direction, automatic or custom color, and opacity.",
GRID_DYNAMIC_COLOR_NAME: "Dynamic grid color",
GRID_DYNAMIC_COLOR_DESC:
"<b><u>Toggle ON:</u></b>Change grid color to match the canvas color<br><b><u>Toggle OFF:</u></b>Use the color below as the grid color",
@@ -856,6 +911,8 @@ export default {
GRID_HORIZONTAL: "Render horizontal grid",
GRID_VERTICAL: "Render vertical grid",
LASER_HEAD: "Laser pointer",
LASER_DESC:
"Configure the laser pointer color and how quickly and how far its trail fades.",
LASER_COLOR: "Laser pointer color",
LASER_DECAY_TIME_NAME: "Laser pointer decay time",
LASER_DECAY_TIME_DESC:
@@ -875,6 +932,21 @@ export default {
"When Obsidian files change, the matching <code>[[link]]</code> in your drawings will also change. " +
"If you don't want text accidentally changing in your drawings use <code>[[links|with aliases]]</code>.",
DRAG_MODIFIER_NAME: "Link Click and Drag&Drop Modifier Keys",
DRAG_MODIFIER_GROUP_DESC:
"Configure link-opening gestures and platform-specific modifier combinations for clicks and drag-and-drop actions.",
LINK_OPENING_GESTURES_HEAD: "Link-opening gestures",
LINK_OPENING_GESTURES_DESC:
"Configure long-press delays and double-click link opening for embedded drawings and view mode.",
WEB_BROWSER_DRAG_ACTION_DESC:
"Choose modifier combinations for links, images, imports, and embeddables dragged from a web browser.",
LOCAL_FILE_DRAG_ACTION_DESC:
"Choose modifier combinations for links, images, imports, and embeddables dragged from the operating system.",
INTERNAL_DRAG_ACTION_DESC:
"Choose modifier combinations for links, images, full-size images, and embeddables dragged inside Obsidian.",
PANE_TARGET_DESC:
"Choose modifier combinations that determine where clicked links open.",
MODIFIER_KEY_USAGE_NAME: "Configuring modifier keys",
MODIFIER_KEY_COMBINATIONS: "Modifier combinations",
DRAG_MODIFIER_DESC:
`Modifier key behavior when clicking links and dragging and dropping elements. ` +
`Excalidraw will not validate your configuration... pay attention to avoid conflicting settings. ` +
@@ -972,6 +1044,22 @@ export default {
"Use the <code>http" +
"s://noembed" +
".com/embed?url=</code> to get title of page when dropping an HTTPS link into Excalidraw",
LINK_BEHAVIOR_HEAD: "Link behavior",
LINK_BEHAVIOR_DESC:
"Configure link synchronization, related links, hover previews, click handling, and web-page title lookup.",
LINK_USAGE_NAME: "Using links in Excalidraw",
LINK_OPENING_HEAD: "Pane and tab behavior",
LINK_OPENING_DESC:
"Choose whether opened links reuse, focus, or move between panes, tabs, and the main workspace.",
LINK_APPEARANCE_HEAD: "Link appearance",
LINK_APPEARANCE_DESC:
"Configure brackets, prefixes, icons, and opacity used when links are displayed.",
TODO_HEAD: "TODOs",
TODO_GROUP_DESC:
"Configure TODO parsing and the icons used for open and completed tasks.",
TRANSCLUSION_HEAD: "Text transclusions",
TRANSCLUSION_DESC:
"Configure character limits, wrapping, and quote cleanup for transcluded Markdown text.",
PDF_TO_IMAGE: "PDF to Image",
PDF_TO_IMAGE_SCALE_NAME: "PDF to Image conversion scale",
PDF_TO_IMAGE_SCALE_DESC:
@@ -981,7 +1069,12 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"In the Embed Files section of Excalidraw Settings, you can configure how various files are embedded into Excalidraw. This includes options for embedding interactive markdown files, PDFs, and markdown files as images.",
MD_HEAD: "Embed markdown into Excalidraw as image",
MD_GROUP_DESC:
"Set dimensions, font, colors, borders, and CSS for Markdown files rendered as images.",
MD_EMBED_CUSTOMDATA_HEAD_NAME: "Interactive Markdown Files",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"Configure editing and default appearance for future interactive Markdown embeds.",
MD_EMBED_DEFAULTS_CONTROL_NAME: "Interactive Markdown appearance defaults",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `The below settings will only effect future embeds. Current embeds remain unchanged. The theme setting of embedded frames is under the "Excalidraw appearance and behavior" section.`,
MD_EMBED_SINGLECLICK_EDIT_NAME: "Single click to edit embedded markdown",
MD_EMBED_SINGLECLICK_EDIT_DESC:
@@ -1025,12 +1118,17 @@ export default {
EMBED_HEAD: "Embedding Excalidraw into your Notes and Exporting",
EMBED_DESC: `In the "Embed & Export" settings, you can configure how images and Excalidraw drawings are embedded and exported within your documents. Key settings include choosing the image type for markdown preview (such as Native SVG or PNG), specifying the type of file to insert into the document (original Excalidraw, PNG, or SVG), and managing image caching for embedding in markdown. You can also control image sizing, whether to embed drawings using wiki links or markdown links, and adjust settings related to image themes, background colors, and Obsidian integration.
Additionally, there are settings for auto-export, which automatically generates SVG and/or PNG files to match the title of your Excalidraw drawings, keeping them in sync with file renames and deletions.`,
EMBED_PREVIEW_LINKS_HEAD: "Previews, links, and Canvas",
EMBED_PREVIEW_LINKS_DESC:
"Choose preview and inserted-file formats, source-link behavior, placeholders, and immersive Canvas embeds.",
EMBED_CANVAS: "Obsidian Canvas support",
EMBED_CANVAS_NAME: "Immersive embedding",
EMBED_CANVAS_DESC:
"Hide canvas node border and background when embedding an Excalidraw drawing to Canvas. " +
"Note that for a full transparent background for your image, you will still need to configure Excalidraw to export images with transparent background.",
EMBED_CACHING: "Image caching and rendering optimization",
EMBED_CACHING_DESC:
"Tune rendering concurrency and local image caches, purge cached images or backups, and optionally reuse exported previews.",
RENDERING_CONCURRENCY_NAME: "Image rendering concurrency",
RENDERING_CONCURRENCY_DESC:
"Number of parallel workers to use for image rendering. Increasing this number will speed up the rendering process, but may slow down the rest of the system. " +
@@ -1043,8 +1141,14 @@ export default {
"The practical impact is local disk or browser-storage usage inside Obsidian. This can matter on phones and on desktops with tighter browser storage quotas or limited free disk space.<br><br>" +
"Lower values reclaim local cache space sooner but may force more rerendering of PDFs and embedded drawings. Higher values keep repeat loads faster at the cost of more local cache storage.",
EXPORT_SUBHEAD: "Export Settings",
EXPORT_SUBHEAD_DESC:
"Configure PDF rendering and exported scene data, image dimensions, theme and background, PDF defaults, and automatic PNG/SVG copies.",
EMBED_SIZING: "Image sizing",
EMBED_SIZING_DESC:
"Set default embedded-image dimensions, PNG scale, and export padding.",
EMBED_THEME_BACKGROUND: "Image theme and background color",
EMBED_THEME_BACKGROUND_DESC:
"Choose exported-image background and theme behavior and whether previews follow Obsidian's theme.",
EMBED_IMAGE_CACHE_NAME: "Cache images for embedding in markdown",
EMBED_IMAGE_CACHE_DESC:
"Cache images for embedding in markdown. This will speed up the embedding process, but in case you compose images of several sub-component drawings, " +
@@ -1125,7 +1229,18 @@ export default {
"Embed Excalidraw scene in exported image. Can be overridden at a file level by adding the <code>excalidraw-export-embed-scene: true/false</code> frontmatter key. " +
"The setting only takes effect the next time you (re)open drawings.",
PDF_EXPORT_SETTINGS: "PDF Export Settings",
PDF_EXPORT_SETTINGS_DESC:
"Choose default PDF page size, orientation, tiling, margins, paper color, and alignment.",
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "Default PDF export layout",
EXPORT_HEAD: "Auto-export Settings",
EXPORT_AUTOEXPORT_DESC:
"Keep exported files synchronized and automatically create SVG, PNG, light, and dark variants.",
SETTINGS_NAVIGATION_OPEN: "Open",
SETTINGS_BREADCRUMB_ARIA: "Settings path",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"Enable automatic PNG or SVG copies to make those formats available in the inserted-file dropdown.",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"Choose whether Excalidraw, PNG, or SVG is inserted when you embed a drawing in a document.",
EXPORT_SYNC_NAME:
"Keep the .SVG and/or .PNG filenames in sync with the drawing file",
EXPORT_SYNC_DESC:
@@ -1199,8 +1314,11 @@ export default {
CUSTOM_PEN_DESC:
"You will see these pens next to the Obsidian Menu on the canvas. You can customize the pens on the canvas by long-pressing the pen button.",
EXPERIMENTAL_HEAD: "Miscellaneous features",
EXPERIMENTAL_DESC: `These miscellaneous features in Excalidraw include options for setting default LaTeX formulas for new equations, enabling a Field Suggester for autocompletion, displaying type indicators for Excalidraw files, enabling immersive image embedding in live preview editing mode, and experimenting with Taskbone Optical Character Recognition for text extraction from images and drawings. Users can also enter a Taskbone API key for extended usage of the OCR service.`,
EXPERIMENTAL_DESC:
"Configure LaTeX defaults, file type indicators, live preview behavior, property suggestions, and the experimental Taskbone OCR integration.",
EA_HEAD: "Excalidraw Automate",
EA_GROUP_DESC:
"Configure Excalidraw Automate scripting, startup and autostart behavior, command links, and settings exposed by installed scripts.",
EA_DESC:
"ExcalidrawAutomate is a scripting and automation API for Excalidraw. Unfortunately, the documentation of the API is sparse. " +
`I recommend reading the <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> file, ` +
@@ -1211,6 +1329,33 @@ export default {
FIELD_SUGGESTER_DESC:
"Field Suggester borrowed from Breadcrumbs and Templater plugins. The Field Suggester will show an autocomplete menu " +
"when you type <code>excalidraw-</code> or <code>ea.</code> with function description as hints on the individual items in the list.",
ALLOW_JS_FILES_NAME: "Load JavaScript files from the Scripts folder",
ALLOW_JS_FILES_DESC:
"When enabled, Excalidraw Automate monitors and runs <code>.js</code> files in the Scripts folder and accepts a <code>.js</code> startup script. " +
"By default, Obsidian Sync does not sync non-Markdown files, Obsidian does not open <code>.js</code> files for editing, and File Explorer hides them. Enable <b>Sync all other types</b> and <b>Show all file types</b> in Obsidian when needed. If matching <code>.md</code> and <code>.js</code> scripts exist, the Markdown file is used.",
STORE_SCRIPTS_AS_JS_NAME: "Store downloaded scripts as",
STORE_SCRIPTS_AS_JS_DESC:
"Choose the local file type used for new Script Library downloads and updates. This is independent of whether the remote source is <code>.md</code> or <code>.js</code>.",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "Move existing script files",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Move existing scripts to .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Move existing scripts to .md",
MIGRATE_SCRIPT_FILES_STATUS:
"{eligible} script file(s) can be moved to {extension}. {skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"Back up your vault before continuing.<br><br><b>{count}</b> script file(s) will be renamed to <code>{extension}</code>. Pinned script paths will be updated. {startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"The configured startup script and its setting will also be updated.",
MIGRATE_SCRIPT_FILES_SKIPPED:
"{count} same-named .md/.js pair(s) will not be moved.",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"Skipped {count} script file(s) because the destination already exists:\n{files}",
MIGRATE_SCRIPT_FILES_NONE: "No eligible script files were found to move.",
MIGRATE_SCRIPT_FILES_COMPLETE:
"Moved {count} script file(s) to {extension}.",
MIGRATE_SCRIPT_FILES_FAILED:
"Could not move the script files. Completed renames were rolled back where possible.",
ENABLE_ONLOAD_SCRIPTS_NAME: "Enable onload scripts",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"This file includes an <code>excalidraw-onload-script</code>. Do you want to enable onload scripts?",
@@ -1223,7 +1368,7 @@ export default {
AUTOSTART_SCRIPT_PROMPT:
"wants to run automatically every time you open an Excalidraw drawing. Do you want to allow this?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
'You can change this later from the Command Palette ("Autostart scripts") or in Settings → Compatibility → Autostart scripts.',
'You can change this later from the Command Palette ("Autostart scripts") or in Settings → Excalidraw Automate → Autostart scripts.',
AUTOSTART_SCRIPT_ALLOW: "Autostart",
AUTOSTART_SCRIPT_DENY: "Manual start only",
AUTOSTART_SCRIPT_ASK_LATER: "Ask every time",
@@ -1243,9 +1388,10 @@ export default {
"This creates a risk if you open drawings from unknown sources: a malicious drawing can make a normal click trigger privileged commands. " +
"Only enable this if you trust the file and its source.",
STARTUP_SCRIPT_NAME: "Startup script",
STARTUP_SCRIPT_JS_DISABLED:
"JavaScript startup scripts are disabled. Enable JavaScript files in Excalidraw Automate settings first.",
STARTUP_SCRIPT_DESC:
"If set, excalidraw will execute the script at plugin startup. This is useful if you want to set any of the Excalidraw Automate hooks. The startup script is a markdown file " +
"that should contain the javascript code you want to execute when Excalidraw starts.",
"If set, Excalidraw will execute the script at plugin startup. This is useful for configuring Excalidraw Automate hooks. Extensionless paths use a Markdown file; <code>.js</code> files are accepted when JavaScript-file loading is enabled.",
STARTUP_SCRIPT_BUTTON_CREATE: "Create startup script",
STARTUP_SCRIPT_BUTTON_OPEN: "Open startup script",
FILETYPE_NAME: "Display type (✏️) for excalidraw.md files in File Explorer",
@@ -1289,6 +1435,8 @@ export default {
"For optimal performance, it is recommended to use a .woff2 file, as Excalidraw will encode only the necessary glyphs when exporting images to SVG. " +
"Other font formats will embed the entire font in the exported file, potentially resulting in significantly larger file sizes.",
OFFLINE_CJK_NAME: "Offline CJK font support",
OFFLINE_CJK_GROUP_DESC:
"Download and selectively preload Chinese, Japanese, and Korean fonts so Excalidraw can render them without an internet connection.",
OFFLINE_CJK_DESC: `<strong>Changes you make here will only take effect after restarting Obsidian.</strong><br>
Excalidraw.com offers handwritten CJK fonts. By default these fonts are not included in the plugin locally, but are served from the Internet.
If you prefer to keep Excalidraw fully local, allowing it to work without Internet access you can download the necessary <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">font files from GitHub</a>.
@@ -1305,6 +1453,8 @@ export default {
SCRIPT_SETTINGS_DESC:
"Some of the Excalidraw Automate Scripts include settings. Settings are organized by script. Settings will only become visible in this list after you have executed the newly downloaded script once.",
TASKBONE_HEAD: "Taskbone Optical Character Recognition",
TASKBONE_GROUP_DESC:
"Configure the optional Taskbone online OCR service for extracting searchable text from drawings and images.",
TASKBONE_DESC:
"This is an experimental integration of optical character recognition into Excalidraw. Please note, that taskbone is an independent external service not provided by Excalidraw, nor the Excalidraw-Obsidian plugin project. " +
"The OCR service will grab legible text from freedraw lines and embedded pictures on your canvas and place the recognized text in the frontmatter of your drawing as well as onto clipboard. " +
+161 -6
View File
@@ -19,6 +19,23 @@ export default {
// Sugester
SELECT_FILE_TO_INSERT: "Selecciona un archivo para insertar",
// main.ts
SETTINGS_DATA_INVALID:
"Excalidraw está esperando un archivo data.json válido. Los cambios no se guardarán hasta que se restaure el archivo o reinicies Obsidian y elijas Restablecer valores predeterminados.",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"Se recibió y rechazó un archivo de configuración de Excalidraw vacío o ilegible. La configuración activa se volvió a guardar para reparar data.json.",
SETTINGS_DATA_RECOVERED:
"El archivo data.json de Excalidraw estaba vacío o no se podía leer. La última configuración válida se restauró automáticamente.",
SETTINGS_RECOVERY_MISSING_TITLE:
"Falta el archivo de configuración de Excalidraw",
SETTINGS_RECOVERY_MISSING_DESC:
"Existe una copia válida de la configuración en este dispositivo. Restaura la copia o restablece Excalidraw a los valores de fábrica. Al cerrar este mensaje se restaurará la copia.",
SETTINGS_RECOVERY_CORRUPT_TITLE:
"El archivo de configuración de Excalidraw está dañado",
SETTINGS_RECOVERY_CORRUPT_DESC:
"El archivo está vacío o no se puede leer y no hay una copia de recuperación en este dispositivo. Restablece Excalidraw a los valores de fábrica o deja el archivo sin cambios mientras restauras un data.json válido desde otra fuente. Al cerrar este mensaje se esperará un archivo de reemplazo.",
SETTINGS_RECOVERY_RESTORE_BACKUP: "Restaurar copia",
SETTINGS_RECOVERY_RESET_DEFAULTS: "Restablecer valores predeterminados",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "Esperar archivo restaurado",
CONVERT_URL_TO_FILE: "Guardar imagen desde el URL en un archivo local",
UNZIP_CURRENT_FILE: "Descomprimir el archivo Excalidraw actual",
PUBLISH_SVG_CHECK:
@@ -373,12 +390,22 @@ export default {
SEARCH_SHOWHIDE_ARIA: "Mostrar/Ocultar barra de búsqueda",
SEARCH_NEXT: "Siguiente",
SEARCH_PREVIOUS: "Anterior",
SETTINGS_TOOLBAR_COPY: "Copiar ajustes",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "Errores",
SETTINGS_TOOLBAR_WIKI: "Wiki",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "Aprender",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "Leer libro",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "Usar ajustes con búsqueda",
USE_DECLARATIVE_SETTINGS_DESC:
"Usa la interfaz de ajustes de Obsidian con búsqueda y varias páginas. Desactívala para usar los ajustes heredados de Excalidraw en una sola página. Requiere reiniciar Obsidian.",
//settings.ts
NOTEBOOKLM_LINK_ARIA:
"Pídele ayuda a NotebookLM sobre el complemento. Este modelo viene precargado con todas mis transcripciones de videos, notas de lanzamiento y otro contenido útil. Chatea con NotebookLM para explorar mis más de 250 videos y la documentación de Excalidraw.",
NOTEBOOKLM_LINK_TEXT:
"Aprende sobre el complemento. Accede a la base de conocimientos de NotebookLM.",
LINKS_BUGS_ARIA:
"Reporta errores y solicita nuevas funciones en la página de GitHub del complemento",
LINKS_BUGS: "Reportar Errores",
@@ -408,6 +435,15 @@ export default {
"<b><u>Desactivado:</u></b> Modo silencioso. Necesitarás verificar las actualizaciones del complemento en Complementos Comunitarios.",
BASIC_HEAD: "Básico",
BASIC_UPDATES_STARTUP_HEAD: "Actualizaciones e inicio",
BASIC_UPDATES_STARTUP_DESC:
"Notas de la versión, comprobaciones y avisos de actualizaciones, y la pantalla de inicio.",
BASIC_FILES_FOLDERS_HEAD: "Archivos y carpetas",
BASIC_FILES_FOLDERS_DESC:
"Carpetas y rutas predeterminadas para dibujos, recortes, anotaciones, plantillas y scripts de Excalidraw Automate.",
BASIC_STENCIL_LIBRARY_HEAD: "Biblioteca de elementos",
BASIC_STENCIL_LIBRARY_DESC:
"Elige dónde se guardan los datos de la biblioteca de elementos y configura su carpeta y archivo local.",
BASIC_DESC: `En la configuración "Básico", puedes configurar opciones como mostrar las notas de la versión después de las actualizaciones, recibir notificaciones de actualización del complemento, establecer la ubicación predeterminada para nuevos bosquejos, especificar la carpeta de Excalidraw para incrustar bosquejos en documentos activos, definir un archivo de plantilla de Excalidraw, y designar una carpeta de scripts de Excalidraw Automate para gestionar scripts de automatización.`,
FOLDER_NAME: "Carpeta de Excalidraw (¡Sensible a MAYÚSCULAS/minúsculas!)",
FOLDER_DESC:
@@ -621,6 +657,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"Ver el consumo de tokens de IA en la sesión actual de Obsidian desglosado por modelo. El uso se reinicia al reiniciar.",
SAVING_HEAD: "Guardar",
SAVING_STORAGE_AUTOSAVE_HEAD: "Almacenamiento y guardado automático",
SAVING_STORAGE_AUTOSAVE_DESC:
"Controla la compresión del JSON de los dibujos y los intervalos de guardado automático en escritorio y móvil.",
SAVING_DESC:
"En la sección 'Guardar' de la Configuración de Excalidraw, puedes configurar cómo se guardan tus bosquejos. Esto incluye opciones para comprimir el JSON de Excalidraw en Markdown, establecer intervalos de autoguardado para escritorio y móvil, definir formatos de nombre de archivo y elegir si usar la extensión de archivo .excalidraw.md o .md. ",
COMPRESS_NAME: "Comprimir JSON de Excalidraw en Markdown",
@@ -655,6 +694,8 @@ export default {
"Excalidraw no podrá guardar tu trabajo al cerrar Obsidian directamente (es decir, al deslizar la aplicación para cerrarla). También ten en cuenta que cuando cambias de aplicación en un dispositivo móvil, a veces Android e iOS cierran " +
"Obsidian en segundo plano para ahorrar recursos del sistema. En tal caso, Excalidraw no podrá guardar los últimos cambios.",
FILENAME_HEAD: "Nombre de archivo",
FILENAME_GROUP_DESC:
"Configura cómo se generan los nombres de dibujos nuevos, incrustados, recortados y anotados.",
FILENAME_DESC:
`<p>Haz click en este enlace para la <a href="${URLs.MOMENTJS_COM_DOCS}">` +
`referencia de formato de fecha y hora</a>.</p>`,
@@ -683,6 +724,9 @@ export default {
DISPLAY_HEAD: "Apariencia y Comportamiento de Excalidraw",
DISPLAY_DESC:
"En la sección 'Apariencia y Comportamiento' de la Configuración de Excalidraw, puedes ajustar cómo se ve y se comporta Excalidraw. Esto incluye opciones para estilos dinámicos, modo para zurdos, coincidencia de temas de Excalidraw y Obsidian, modos predeterminados y más.",
DISPLAY_EDITOR_PREVIEWS_HEAD: "Edición y vistas previas",
DISPLAY_EDITOR_PREVIEWS_DESC:
"Configura los gestos de edición del lienzo y cómo aparecen los archivos de Excalidraw en el modo de lectura y las vistas previas al pasar el cursor.",
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME:
"Limitar tamaño de fuente de Obsidian al texto del editor",
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
@@ -762,13 +806,22 @@ export default {
}'>Modo de Lectura de Markdown</a> en 'Apariencia y Comportamiento' más arriba.<br>` +
`⚠️ Debes cerrar y volver a abrir el archivo de Excalidraw/Markdown para que los cambios surtan efecto. ⚠️`,
MODES_HEAD: "Modos",
MODES_DESC:
"Elige diseños de interfaz específicos para cada dispositivo, controles de la barra de título y la posición de la bandeja para diestros o zurdos.",
HOTKEY_OVERRIDE_HEAD: "Anulaciones de atajos de teclado",
HOTKEY_OVERRIDE_GROUP_DESC:
"Administra las combinaciones de Excalidraw que deben tener prioridad sobre los atajos de Obsidian en conflicto.",
HOTKEY_OVERRIDE_CONTROL_NAME: "Administrar anulaciones de atajos",
HOTKEY_OVERRIDE_DESC:
`Algunos de los atajos de teclado de Excalidraw, como <code>${labelCTRL()}+Enter</code> para editar texto o <code>${labelCTRL()}+K</code> para crear un enlace de elemento ` +
"entran en conflicto con la configuración de atajos de teclado de Obsidian. Las combinaciones de atajos de teclado que agregues a continuación anularán la configuración de atajos de teclado de Obsidian mientras usas Excalidraw. Por lo tanto, " +
`puedes agregar <code>${labelCTRL()}+G</code> si quieres que el comportamiento predeterminado sea Agrupar Objeto en Excalidraw en lugar de abrir la Vista de Gráfico.`,
THEME_HEAD: "Tema y estilo",
THEME_DESC:
"Controla el estilo de la interfaz, los temas de dibujos e incrustaciones, el modo de apertura y el espacio seguro en móviles.",
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:
@@ -802,7 +855,11 @@ export default {
ZOOM_MAX_DESC:
"Límite superior del zoom. Predeterminado: 3000%. Por lo general, no es necesario cambiarlo; se incluye para ser exhaustivos.",
PEN_HEAD: "Lápiz",
PEN_DESC:
"Configura el modo lápiz automático, los gestos táctiles, el borrador y la cruz de dibujo libre.",
GRID_HEAD: "Cuadrícula",
GRID_DESC:
"Configura la dirección de la cuadrícula, el color automático o personalizado y la opacidad.",
GRID_DYNAMIC_COLOR_NAME: "Color de cuadrícula dinámica",
GRID_DYNAMIC_COLOR_DESC:
"<b><u>Activado:</u></b> Cambia el color de la cuadrícula para que coincida con el color del lienzo<br><b><u>Desactivado:</u></bUsar el color de abajo como color de la cuadrícula",
@@ -817,6 +874,8 @@ export default {
GRID_HORIZONTAL: "Renderizar cuadrícula horizontal",
GRID_VERTICAL: "Renderizar cuadrícula vertical",
LASER_HEAD: "Puntero láser",
LASER_DESC:
"Configura el color del puntero láser y la rapidez y distancia con que se desvanece su rastro.",
LASER_COLOR: "Color del puntero láser",
LASER_DECAY_TIME_NAME: "Tiempo de desvanecimiento del puntero láser",
LASER_DECAY_TIME_DESC:
@@ -837,6 +896,21 @@ export default {
"Si no quieres que el texto cambie accidentalmente en tus bosquejos, usa <code>[[enlaces|con alias]]</code>.",
DRAG_MODIFIER_NAME:
"Teclas modificadoras para click de enlace y Arrastrar y Soltar(Drag&Drop)",
DRAG_MODIFIER_GROUP_DESC:
"Configura gestos para abrir enlaces y combinaciones de modificadores para clics y acciones de arrastrar y soltar.",
LINK_OPENING_GESTURES_HEAD: "Gestos para abrir enlaces",
LINK_OPENING_GESTURES_DESC:
"Configura retrasos de pulsación prolongada y la apertura con doble clic en dibujos incrustados y el modo de vista.",
WEB_BROWSER_DRAG_ACTION_DESC:
"Elige modificadores para enlaces, imágenes, importaciones e incrustaciones arrastradas desde un navegador web.",
LOCAL_FILE_DRAG_ACTION_DESC:
"Elige modificadores para enlaces, imágenes, importaciones e incrustaciones arrastradas desde el sistema operativo.",
INTERNAL_DRAG_ACTION_DESC:
"Elige modificadores para enlaces, imágenes, imágenes a tamaño completo e incrustaciones arrastradas dentro de Obsidian.",
PANE_TARGET_DESC:
"Elige combinaciones de modificadores que determinan dónde se abren los enlaces.",
MODIFIER_KEY_USAGE_NAME: "Configurar teclas modificadoras",
MODIFIER_KEY_COMBINATIONS: "Combinaciones de modificadores",
DRAG_MODIFIER_DESC:
`Comportamiento de la tecla modificadora al hacer click en enlaces y arrastrar y soltar elementos. ` +
`Excalidraw no validará tu configuración... presta atención para evitar configuraciones conflictivas. ` +
@@ -935,6 +1009,22 @@ export default {
"Usa <code>http" +
"s://noembed" +
".com/embed?url=</code> para obtener el título de la página al soltar un enlace HTTPS en Excalidraw.",
LINK_BEHAVIOR_HEAD: "Comportamiento de enlaces",
LINK_BEHAVIOR_DESC:
"Configura la sincronización, enlaces relacionados, vistas previas, clics y la búsqueda de títulos web.",
LINK_USAGE_NAME: "Usar enlaces en Excalidraw",
LINK_OPENING_HEAD: "Comportamiento de paneles y pestañas",
LINK_OPENING_DESC:
"Elige si los enlaces reutilizan, enfocan o cambian entre paneles, pestañas y el espacio de trabajo principal.",
LINK_APPEARANCE_HEAD: "Apariencia de enlaces",
LINK_APPEARANCE_DESC:
"Configura corchetes, prefijos, iconos y opacidad al mostrar enlaces.",
TODO_HEAD: "Tareas pendientes",
TODO_GROUP_DESC:
"Configura el análisis de tareas y los iconos para tareas abiertas y completadas.",
TRANSCLUSION_HEAD: "Transclusiones de texto",
TRANSCLUSION_DESC:
"Configura límites de caracteres, ajuste de línea y limpieza de citas para texto Markdown transcluido.",
PDF_TO_IMAGE: "PDF a Image",
PDF_TO_IMAGE_SCALE_NAME: "Escala de conversión de PDF a imagen",
PDF_TO_IMAGE_SCALE_DESC:
@@ -944,7 +1034,13 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"En la sección 'Incrustar archivos' de la Configuración de Excalidraw, puedes configurar cómo se incrustan varios tipos de archivos en Excalidraw. Esto incluye opciones para incrustar archivos Markdown interactivos, PDFs y archivos Markdown como imágenes.",
MD_HEAD: "Incrustar Markdown en Excalidraw como imagen",
MD_GROUP_DESC:
"Configura las dimensiones, la fuente, los colores, los bordes y el CSS de los archivos Markdown renderizados como imágenes.",
MD_EMBED_CUSTOMDATA_HEAD_NAME: "Archivos Markdown interactivos",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"Configura la edición y la apariencia predeterminada de futuras incrustaciones interactivas de Markdown.",
MD_EMBED_DEFAULTS_CONTROL_NAME:
"Valores predeterminados de apariencia de Markdown interactivo",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `Las siguientes configuraciones solo afectarán a futuras incrustaciones. Las incrustaciones actuales no se modificarán. La configuración del tema de los marcos incrustados se encuentra en la sección "Apariencia y comportamiento de Excalidraw`,
MD_EMBED_SINGLECLICK_EDIT_NAME:
"Un solo click para editar Markdown incrustado",
@@ -990,19 +1086,30 @@ export default {
EMBED_HEAD: "Incrustar Excalidraw en tus notas y exportar",
EMBED_DESC: `En la configuración de "Incrustar y exportar", puedes configurar cómo se incrustan y exportan las imágenes y los bosquejos de Excalidraw en tus documentos. Las configuraciones clave incluyen elegir el tipo de imagen para la vista previa de Markdown (como SVG nativo o PNG), especificar el tipo de archivo a insertar en el documento (Excalidraw original, PNG o SVG) y gestionar el almacenamiento en caché de imágenes para incrustarlas en Markdown. También puedes controlar el tamaño de la imagen, si incrustar los bosquejos usando wikienlaces o enlaces Markdown y ajustar la configuración relacionada con los temas de imagen, colores de fondo y la integración de Obsidian.
Además, hay configuraciones para la autoexportación, que genera automáticamente archivos SVG y/o PNG que coinciden con el título de tus bosquejos de Excalidraw, manteniéndolos sincronizados con los cambios de nombre y eliminaciones de archivos.`,
EMBED_PREVIEW_LINKS_HEAD: "Vistas previas, enlaces y Canvas",
EMBED_PREVIEW_LINKS_DESC:
"Elige los formatos de vista previa y de archivo insertado, los enlaces de origen, los marcadores de posición y las incrustaciones inmersivas en Canvas.",
EMBED_CANVAS: "Soporte para Obsidian Canvas",
EMBED_CANVAS_NAME: "Incrustación inmersiva",
EMBED_CANVAS_DESC:
"Oculta el borde y el fondo del nodo del Canvas al incrustar un bosquejo de Excalidraw en un Canvas. " +
"Ten en cuenta que para un fondo completamente transparente en tu imagen, aún necesitarás configurar Excalidraw para que exporte las imágenes con fondo transparente.",
EMBED_CACHING: "Caché de imágenes y optimización de renderizado",
EMBED_CACHING_DESC:
"Ajusta la concurrencia de renderizado y las cachés locales, elimina imágenes o copias de seguridad almacenadas y reutiliza vistas previas exportadas.",
RENDERING_CONCURRENCY_NAME: "Concurrencia de renderizado de imágenes",
RENDERING_CONCURRENCY_DESC:
"Número de parallel workers(trabajadores paralelos) a usar para el renderizado de imágenes. Aumentar este número acelerará el proceso de renderizado, pero puede ralentizar el resto del sistema. " +
"El valor predeterminado es 3. Puedes aumentar este número si tienes un sistema potente.",
EXPORT_SUBHEAD: "Configuraciones de Exportación",
EXPORT_SUBHEAD_DESC:
"Configura el renderizado de PDF, los datos de escena exportados, las dimensiones, el tema y fondo, los valores predeterminados de PDF y las copias PNG/SVG automáticas.",
EMBED_SIZING: "Tamaño de imagen",
EMBED_SIZING_DESC:
"Define las dimensiones predeterminadas de las imágenes incrustadas, la escala PNG y el margen de exportación.",
EMBED_THEME_BACKGROUND: "Tema de la imagen y color de fondo",
EMBED_THEME_BACKGROUND_DESC:
"Elige el fondo y el tema de las imágenes exportadas y si las vistas previas siguen el tema de Obsidian.",
EMBED_IMAGE_CACHE_NAME:
"Guardar imágenes en caché para incrustar en Markdown",
EMBED_IMAGE_CACHE_DESC:
@@ -1088,7 +1195,19 @@ export default {
"Incrusta la escena de Excalidraw en la imagen exportada. Se puede anular a nivel de archivo añadiendo la clave frontmatter <code>excalidraw-export-embed-scene: true/false</code> . " +
"La configuración solo surtirá efecto la próxima vez que (re)abras los bosquejos.",
PDF_EXPORT_SETTINGS: "Configuración de exportación a PDF",
PDF_EXPORT_SETTINGS_DESC:
"Elige el tamaño de página, la orientación, la distribución, los márgenes, el color del papel y la alineación predeterminados del PDF.",
PDF_EXPORT_DEFAULTS_CONTROL_NAME:
"Diseño predeterminado de exportación a PDF",
EXPORT_HEAD: "Configuración de auto-exportación",
EXPORT_AUTOEXPORT_DESC:
"Mantén sincronizados los archivos exportados y crea automáticamente variantes SVG, PNG, claras y oscuras.",
SETTINGS_NAVIGATION_OPEN: "Abrir",
SETTINGS_BREADCRUMB_ARIA: "Ruta de configuración",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"Activa las copias automáticas PNG o SVG para que esos formatos estén disponibles en el menú del tipo de archivo insertado.",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"Elige si se inserta Excalidraw, PNG o SVG al incrustar un bosquejo en un documento.",
EXPORT_SYNC_NAME:
"Mantiene los nombres de archivo .SVG y/o .PNG sincronizados con el archivo del bosquejo",
EXPORT_SYNC_DESC:
@@ -1164,8 +1283,11 @@ export default {
CUSTOM_PEN_DESC:
"Verás estos lápices junto al Menú de Obsidian en el lienzo. Puedes personalizarlos manteniendo presionado el botón del lápiz en el lienzo.",
EXPERIMENTAL_HEAD: "Funcionalidades misceláneas",
EXPERIMENTAL_DESC: `Estas funcionalidades misceláneas en Excalidraw incluyen opciones para establecer fórmulas LaTeX predeterminadas para nuevas ecuaciones, habilitar un sugeridor de campos para autocompletar, mostrar indicadores de tipo para archivos de Excalidraw, habilitar la incrustación de imágenes inmersivas en el modo de edición de vista en vivo y experimentar con el Reconocimiento Óptico de Caracteres (OCR) de Taskbone para la extracción de texto de imágenes y bosquejos. Los usuarios también pueden ingresar una clave de API de Taskbone para un uso extendido del servicio de OCR.`,
EXPERIMENTAL_DESC:
"Configura los valores predeterminados de LaTeX, los indicadores de tipo de archivo, el comportamiento de la vista previa en vivo, las sugerencias de propiedades y la integración experimental de OCR con Taskbone.",
EA_HEAD: "Excalidraw Automate",
EA_GROUP_DESC:
"Configura los scripts de Excalidraw Automate, el comportamiento de inicio y autoarranque, los enlaces de comandos y los ajustes expuestos por los scripts instalados.",
EA_DESC:
"ExcalidrawAutomate es una API de scripting y automatización para Excalidraw. Desafortunadamente, la documentación de la API es escasa. " +
`Te recomiendo leer el archivo <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a>, ` +
@@ -1176,6 +1298,34 @@ export default {
FIELD_SUGGESTER_DESC:
"El sugeridor de campos, tomado de los complementos Breadcrumbs y Templater, mostrará un menú de autocompletar " +
"cuando escribas <code>excalidraw-</code> o <code>ea.</code> , con descripciones de las funciones como pistas para cada elemento en la lista.",
ALLOW_JS_FILES_NAME: "Cargar archivos JavaScript desde la carpeta Scripts",
ALLOW_JS_FILES_DESC:
"Cuando está activado, Excalidraw Automate supervisa y ejecuta archivos <code>.js</code> en la carpeta Scripts y acepta un script de inicio <code>.js</code>. " +
"De forma predeterminada, Obsidian Sync no sincroniza archivos que no sean Markdown, Obsidian no abre archivos <code>.js</code> para editarlos y el Explorador de archivos los oculta. Activa <b>Sincronizar todos los demás tipos</b> y <b>Mostrar todos los tipos de archivo</b> en Obsidian cuando sea necesario. Si existen scripts <code>.md</code> y <code>.js</code> con el mismo nombre, se utiliza el archivo Markdown.",
STORE_SCRIPTS_AS_JS_NAME: "Guardar los scripts descargados como",
STORE_SCRIPTS_AS_JS_DESC:
"Elige el tipo de archivo local para las nuevas descargas y actualizaciones de la Biblioteca de scripts. Es independiente de si la fuente remota es <code>.md</code> o <code>.js</code>.",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "Mover archivos de script existentes",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Mover scripts existentes a .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Mover scripts existentes a .md",
MIGRATE_SCRIPT_FILES_STATUS:
"Se pueden mover {eligible} archivo(s) de script a {extension}. {skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"Haz una copia de seguridad de tu bóveda antes de continuar.<br><br>Se cambiará la extensión de <b>{count}</b> archivo(s) de script a <code>{extension}</code>. Se actualizarán las rutas de los scripts fijados. {startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"También se actualizarán el script de inicio configurado y su ajuste.",
MIGRATE_SCRIPT_FILES_SKIPPED:
"No se moverán {count} par(es) .md/.js con el mismo nombre.",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"Se omitieron {count} archivo(s) de script porque el destino ya existe:\n{files}",
MIGRATE_SCRIPT_FILES_NONE:
"No se encontraron archivos de script aptos para mover.",
MIGRATE_SCRIPT_FILES_COMPLETE:
"Se movieron {count} archivo(s) de script a {extension}.",
MIGRATE_SCRIPT_FILES_FAILED:
"No se pudieron mover los archivos de script. Los cambios completados se revirtieron cuando fue posible.",
ENABLE_ONLOAD_SCRIPTS_NAME: "Habilitar scripts de carga",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"Este archivo incluye un <code>excalidraw-onload-script</code>. ¿Quieres habilitar los scripts de carga?",
@@ -1188,7 +1338,7 @@ export default {
AUTOSTART_SCRIPT_PROMPT:
"quiere ejecutarse automáticamente cada vez que abras un dibujo de Excalidraw. ¿Deseas permitirlo?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
'Puedes cambiar esto más tarde desde la paleta de comandos ("Scripts de inicio automático") o en Ajustes → Compatibilidad → Scripts de inicio automático.',
'Puedes cambiar esto más tarde desde la paleta de comandos ("Scripts de inicio automático") o en Ajustes → Excalidraw Automate → Scripts de inicio automático.',
AUTOSTART_SCRIPT_ALLOW: "Inicio automático",
AUTOSTART_SCRIPT_DENY: "Solo manual",
AUTOSTART_SCRIPT_ASK_LATER: "Preguntar cada vez",
@@ -1209,9 +1359,10 @@ export default {
"Esto crea un riesgo si abres dibujos de fuentes desconocidas: un dibujo malicioso puede hacer que un clic normal ejecute comandos privilegiados. " +
"Actívalo solo si confías en el archivo y en su origen.",
STARTUP_SCRIPT_NAME: "Script de inicio",
STARTUP_SCRIPT_JS_DISABLED:
"Los scripts de inicio JavaScript están desactivados. Primero habilita los archivos JavaScript en la configuración de Excalidraw Automate.",
STARTUP_SCRIPT_DESC:
"Si está configurado, Excalidraw ejecutará el script al iniciar el complemento. Esto es útil si quieres establecer cualquiera de los hooks de Excalidraw Automate. El script de inicio es un archivo Markdown " +
"que debe contener el código Javascript que quieres ejecutar cuando Excalidraw se inicie",
"Si está configurado, Excalidraw ejecutará el script al iniciar el complemento. Es útil para configurar hooks de Excalidraw Automate. Las rutas sin extensión utilizan un archivo Markdown; los archivos <code>.js</code> se aceptan cuando está habilitada la carga de archivos JavaScript.",
STARTUP_SCRIPT_BUTTON_CREATE: "Crear script de inicio",
STARTUP_SCRIPT_BUTTON_OPEN: "Abrir script de inicio",
FILETYPE_NAME:
@@ -1258,6 +1409,8 @@ export default {
"Otros formatos de fuente incrustarán la fuente completa en el archivo exportado, lo que podría resultar en tamaños de archivo significativamente mayores.",
OFFLINE_CJK_NAME:
"Soporte de fuentes CJK (chino, japonés y coreano) sin conexión",
OFFLINE_CJK_GROUP_DESC:
"Descarga y precarga de forma selectiva fuentes chinas, japonesas y coreanas para que Excalidraw pueda mostrarlas sin conexión a internet.",
OFFLINE_CJK_DESC: `<strong>Los cambios que hagas aquí solo se aplicarán después de reiniciar Obsidian.</strong><br>
Excalidraw.com ofrece fuentes CJK (chino, japonés, coreano) escritas a mano. Por defecto, estas fuentes no se incluyen en el complemento de forma local, sino que se obtienen de internet.
Si prefieres que Excalidraw funcione completamente sin conexión a internet, puedes descargar los <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">archivos de fuentes necesarios desde GitHub</a>.
@@ -1276,6 +1429,8 @@ export default {
SCRIPT_SETTINGS_DESC:
"Algunos de los scripts de Excalidraw Automate incluyen configuraciones. Las configuraciones están organizadas por script. Solo se harán visibles en esta lista después de que hayas ejecutado el script recién descargado al menos una vez.",
TASKBONE_HEAD: "Reconocimiento Óptico de Caracteres de Taskbone",
TASKBONE_GROUP_DESC:
"Configura el servicio opcional de OCR en línea Taskbone para extraer texto que se pueda buscar de dibujos e imágenes.",
TASKBONE_DESC:
"Esta es una integración experimental del reconocimiento óptico de caracteres en Excalidraw. Ten en cuenta que Taskbone es un servicio externo independiente y no es proporcionado por Excalidraw ni por el proyecto del complemento Excalidraw-Obsidian. " +
"El servicio de OCR capturará texto legible de las líneas de dibujo a mano alzada y de las imágenes incrustadas en tu lienzo y colocará el texto reconocido en el frontmatter de tu bosquejo, así como en el portapapeles. " +
+165 -4
View File
@@ -15,6 +15,21 @@ import {
// русский
export default {
// main.ts
SETTINGS_DATA_INVALID:
"Excalidraw ожидает корректный файл data.json. Изменения настроек не будут сохранены, пока файл не будет восстановлен или вы не перезапустите Obsidian и не выберете сброс настроек.",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"Получен пустой или нечитаемый файл настроек Excalidraw, поэтому он был отклонён. Активные настройки записаны обратно для восстановления data.json.",
SETTINGS_DATA_RECOVERED:
"Файл Excalidraw data.json был пуст или недоступен для чтения. Последняя исправная версия настроек восстановлена автоматически.",
SETTINGS_RECOVERY_MISSING_TITLE: "Файл настроек Excalidraw отсутствует",
SETTINGS_RECOVERY_MISSING_DESC:
"На этом устройстве есть последняя исправная резервная копия настроек. Восстановите её или сбросьте Excalidraw к заводским настройкам. При закрытии этого сообщения будет восстановлена резервная копия.",
SETTINGS_RECOVERY_CORRUPT_TITLE: "Файл настроек Excalidraw повреждён",
SETTINGS_RECOVERY_CORRUPT_DESC:
"Файл пуст или недоступен для чтения, а резервная копия на этом устройстве отсутствует. Сбросьте Excalidraw к заводским настройкам или оставьте файл без изменений, пока восстанавливаете корректный data.json из другого источника. При закрытии этого сообщения Excalidraw будет ждать замену файла.",
SETTINGS_RECOVERY_RESTORE_BACKUP: "Восстановить копию",
SETTINGS_RECOVERY_RESET_DEFAULTS: "Сбросить настройки",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "Ждать восстановленный файл",
CONVERT_URL_TO_FILE: "Сохранить изображение из URL в локальный файл",
UNZIP_CURRENT_FILE: "Распаковать текущий файл Excalidraw",
PUBLISH_SVG_CHECK:
@@ -352,6 +367,18 @@ export default {
"Для повышения производительности рассмотрите возможность разделения больших рисунков на несколько файлов меньшего размера.",
//settings.ts
SETTINGS_TOOLBAR_COPY: "Копировать настройки",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "Ошибки",
SETTINGS_TOOLBAR_WIKI: "Вики",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "Обучение",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "Читать книгу",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "Использовать настройки с поиском",
USE_DECLARATIVE_SETTINGS_DESC:
"Использовать многостраничный интерфейс настроек Obsidian с поиском. Отключите, чтобы использовать прежнюю одностраничную страницу настроек Excalidraw. Требуется перезапуск Obsidian.",
RELEASE_NOTES_NAME: "Отображение информации о выпуске после обновления",
RELEASE_NOTES_DESC:
`<b><u>Переключатель ВКЛ:</u></b> Отображение информации о выпуске при каждом обновлении Excalidraw до новой версии.<br>` +
@@ -366,6 +393,15 @@ export default {
"<b><u>Переключатель ВЫКЛ:</u></b> Тихий режим. Вам необходимо проверить обновления плагинов в разделе Community Plugins.",
BASIC_HEAD: "Основные",
BASIC_UPDATES_STARTUP_HEAD: "Обновления и запуск",
BASIC_UPDATES_STARTUP_DESC:
"Примечания к выпуску, проверка и уведомления об обновлениях, а также заставка при запуске.",
BASIC_FILES_FOLDERS_HEAD: "Файлы и папки",
BASIC_FILES_FOLDERS_DESC:
"Папки и пути по умолчанию для рисунков, обрезок, аннотаций, шаблонов и скриптов Excalidraw Automate.",
BASIC_STENCIL_LIBRARY_HEAD: "Библиотека элементов",
BASIC_STENCIL_LIBRARY_DESC:
"Выберите место хранения библиотеки элементов и настройте её папку в хранилище и локальный файл.",
BASIC_DESC: `В настройках "Основные" можно настроить такие параметры, как отображение заметок о выпуске после обновлений, получение уведомлений об обновлении плагинов, установка местоположения по умолчанию для новых чертежей, указание папки Excalidraw для вставки чертежей в активные документы, определение файла шаблона Excalidraw и указание папки сценария Excalidraw Automate для управления сценариями автоматизации.`,
FOLDER_NAME: "Папка Excalidraw",
FOLDER_DESC:
@@ -564,6 +600,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"Просмотр потребления токенов ИИ в текущей сессии Obsidian с разбивкой по моделям. Данные сбрасываются при перезапуске.",
SAVING_HEAD: "Сохранение",
SAVING_STORAGE_AUTOSAVE_HEAD: "Хранение и автосохранение",
SAVING_STORAGE_AUTOSAVE_DESC:
"Настройте сжатие JSON рисунков и интервалы автосохранения на компьютере и мобильных устройствах.",
SAVING_DESC:
"В разделе 'Сохранение' раздела Настройки Excalidraw вы можете настроить способ сохранения ваших чертежей. Сюда входят опции сжатия Excalidraw JSON в Markdown, установки интервалов автосохранения для настольных и мобильных компьютеров, определения форматов имен файлов, а также выбора расширения файла .excalidraw.md или .md. ",
COMPRESS_NAME: "Сжатие Excalidraw JSON в формате Markdown",
@@ -599,6 +638,8 @@ export default {
"Excalidraw не сможет сохранить вашу работу при прямом завершении работы Obsidian (т.е. смахнув ее). Также обратите внимание, что при переключении приложений на мобильном устройстве, иногда Android и iOS закрываются " +
"Obsidian в фоновом режиме для экономии системных ресурсов. В этом случае Excalidraw не сможет сохранить последние изменения.",
FILENAME_HEAD: "Имя файла",
FILENAME_GROUP_DESC:
"Настройте создание имён новых, встроенных, обрезанных и аннотированных рисунков.",
FILENAME_DESC:
`<p>Нажмите на эту ссылку, чтобы получить <a href="${URLs.MOMENTJS_COM_DOCS}">` +
`справочник по формату даты и времени</a>.</p>`,
@@ -626,6 +667,9 @@ export default {
DISPLAY_HEAD: "Внешний вид и поведение Excalidraw",
DISPLAY_DESC:
"В разделе 'Внешний вид и поведение' раздела Настройки Excalidraw вы можете настроить внешний вид и поведение Excalidraw. Сюда входят опции динамической стилизации, режима для левой руки, соответствия тем Excalidraw и Obsidian, режимов по умолчанию и многое другое.",
DISPLAY_EDITOR_PREVIEWS_HEAD: "Редактирование и предпросмотр",
DISPLAY_EDITOR_PREVIEWS_DESC:
"Настройте жесты редактирования холста и отображение файлов Excalidraw в режиме чтения и предпросмотре при наведении.",
DYNAMICSTYLE_NAME: "Динамическая стилизация",
DYNAMICSTYLE_DESC:
"Изменение цветов пользовательского интерфейса Excalidraw в соответствии с цветом холста",
@@ -688,13 +732,23 @@ export default {
"<li>Если <b>заблокировать</b>, то в PDF будет отображаться разметка документа.</li></ul>" +
`См. другие связанные настройки для <a href='#${TAG_MDREADINGMODE}'>режима чтения разметки</a> в разделе 'Внешний вид и поведение' выше.<br>` +
"⚠️ Обратите внимание, что необходимо закрыть активный файл excalidraw/markdown и открыть его снова, чтобы изменения вступили в силу. ⚠️",
MODES_HEAD: "Режимы интерфейса",
MODES_DESC:
"Выберите интерфейс Excalidraw для каждого устройства, кнопки заголовка и расположение панели для правой или левой руки.",
HOTKEY_OVERRIDE_HEAD: "Переопределение горячих клавиш",
HOTKEY_OVERRIDE_GROUP_DESC:
"Управляйте сочетаниями Excalidraw, которые должны иметь приоритет над конфликтующими горячими клавишами Obsidian.",
HOTKEY_OVERRIDE_CONTROL_NAME: "Управление переопределениями клавиш",
HOTKEY_OVERRIDE_DESC:
`Некоторые горячие клавиши Excalidraw, такие как <code>${labelCTRL()}+Enter</code> для редактирования текста или <code>${labelCTRL()}+K</code> создания ссылки на элемент ` +
"конфликтуют с настройками горячих клавиш Obsidian. Комбинации горячих клавиш, которые вы добавите ниже, отменят настройки горячих клавиш Obsidian при использовании Excalidraw, таким образом " +
`Вы можете добавить <code>${labelCTRL()}+G</code>, если хотите по умолчанию перейти к Группе Объектов в Excalidraw вместо открытия Режима просмотра Графиков.`,
THEME_HEAD: "Тема и стиль",
THEME_DESC:
"Настройте стиль интерфейса, темы рисунков и вставок, режим открытия и безопасные отступы на мобильных устройствах.",
ZOOM_AND_PAN_HEAD: "Масштаб и панорамирование",
ZOOM_AND_PAN_DESC:
"Настройте поведение мыши, сенсорного ввода, открытия, изменения размера и диапазона масштаба.",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME:
"Перемещение холста правой кнопкой мыши (открыть меню с 'm')",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
@@ -719,7 +773,12 @@ export default {
"Увеличение до максимального уровня масштабирования",
ZOOM_TO_FIT_MAX_LEVEL_DESC:
"Установите максимальный уровень, до которого масштабирование будет увеличивать чертеж. Минимальное значение - 0,5 (50 %), максимальное - 10 (1000 %).",
PEN_HEAD: "Перо",
PEN_DESC:
"Настройте автоматический режим пера, сенсорные жесты, ластик и перекрестие свободного рисования.",
GRID_HEAD: "Сетка",
GRID_DESC:
"Настройте направление сетки, автоматический или пользовательский цвет и прозрачность.",
GRID_DYNAMIC_COLOR_NAME: "Динамический цвет сетки",
GRID_DYNAMIC_COLOR_DESC:
"<b><u>Переключатель ВКЛ:</u></b>Измените цвет сетки, чтобы он соответствовал цвету холста<br><b><u>Переключатель ВЫКЛ:</u></b>Используйте цвет, указанный ниже, в качестве цвета сетки",
@@ -729,6 +788,8 @@ export default {
"Прозрачность сетки также будет управлять прозрачностью поля привязки при привязке стрелки к элементу.<br>" +
"Установите прозрачность сетки. 0 - прозрачная, 100 - непрозрачная.",
LASER_HEAD: "Лазерный указатель",
LASER_DESC:
"Настройте цвет лазерного указателя, скорость и длину затухания его следа.",
LASER_COLOR: "Цвет лазерного указателя",
LASER_DECAY_TIME_NAME: "Время затухания лазерного указателя",
LASER_DECAY_TIME_DESC:
@@ -748,6 +809,21 @@ export default {
"Когда файлы Obsidian изменяются, соответствующие <code>[[link]]</code> в ваших чертежах также изменится. " +
"Если вы не хотите, чтобы текст случайно менялся в ваших чертежах, используйте <code>[[links|with aliases]]</code>.",
DRAG_MODIFIER_NAME: "Щелкните ссылку и перетащите клавиши-модификаторы",
DRAG_MODIFIER_GROUP_DESC:
"Настройте жесты открытия ссылок и платформенные сочетания модификаторов для щелчков и перетаскивания.",
LINK_OPENING_GESTURES_HEAD: "Жесты открытия ссылок",
LINK_OPENING_GESTURES_DESC:
"Настройте задержку долгого нажатия и открытие ссылок двойным щелчком во встроенных рисунках и режиме просмотра.",
WEB_BROWSER_DRAG_ACTION_DESC:
"Выберите модификаторы для ссылок, изображений, импорта и вставок, перетаскиваемых из веб-браузера.",
LOCAL_FILE_DRAG_ACTION_DESC:
"Выберите модификаторы для ссылок, изображений, импорта и вставок, перетаскиваемых из операционной системы.",
INTERNAL_DRAG_ACTION_DESC:
"Выберите модификаторы для ссылок, изображений, полноразмерных изображений и вставок внутри Obsidian.",
PANE_TARGET_DESC:
"Выберите сочетания модификаторов, определяющие место открытия ссылок.",
MODIFIER_KEY_USAGE_NAME: "Настройка клавиш-модификаторов",
MODIFIER_KEY_COMBINATIONS: "Сочетания модификаторов",
DRAG_MODIFIER_DESC:
`Поведение клавиши-модификатора при нажатии на ссылки и перетаскивании элементов. ` +
`Excalidraw не будет проверять вашу конфигурацию... обратите внимание, чтобы избежать конфликтов настроек. ` +
@@ -844,6 +920,22 @@ export default {
"Используйте <code>http" +
"s://noembed" +
".com/embed?url=</code> для получения заголовка страницы при переходе по HTTPS-ссылке в Excalidraw",
LINK_BEHAVIOR_HEAD: "Поведение ссылок",
LINK_BEHAVIOR_DESC:
"Настройте синхронизацию ссылок, связанные ссылки, предпросмотр, щелчки и получение заголовков веб-страниц.",
LINK_USAGE_NAME: "Использование ссылок в Excalidraw",
LINK_OPENING_HEAD: "Поведение панелей и вкладок",
LINK_OPENING_DESC:
"Выберите, будут ли ссылки повторно использовать, фокусировать или переключать панели, вкладки и главное рабочее пространство.",
LINK_APPEARANCE_HEAD: "Внешний вид ссылок",
LINK_APPEARANCE_DESC:
"Настройте скобки, префиксы, значки и прозрачность отображаемых ссылок.",
TODO_HEAD: "Задачи TODO",
TODO_GROUP_DESC:
"Настройте распознавание TODO и значки открытых и завершенных задач.",
TRANSCLUSION_HEAD: "Текстовые включения",
TRANSCLUSION_DESC:
"Настройте ограничения символов, перенос строк и очистку цитат для включенного текста Markdown.",
PDF_TO_IMAGE: "PDF в изображение",
PDF_TO_IMAGE_SCALE_NAME: "Шкала преобразования PDF в изображения",
PDF_TO_IMAGE_SCALE_DESC:
@@ -853,7 +945,13 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"В разделе Встраивание файлов раздела Настройки Excalidraw вы можете настроить, как различные файлы будут встраиваться в Excalidraw. Сюда входят опции для встраивания интерактивных файлов разметки (Markdown), PDF-файлов и файлов разметки (Markdown) в виде изображений.",
MD_HEAD: "Встраивать разметку в Excalidraw в виде изображения",
MD_GROUP_DESC:
"Настройте размеры, шрифт, цвета, границы и CSS для файлов Markdown, отображаемых как изображения.",
MD_EMBED_CUSTOMDATA_HEAD_NAME: "Интерактивные файлы Markdown",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"Настройте редактирование и внешний вид по умолчанию для будущих интерактивных вставок Markdown.",
MD_EMBED_DEFAULTS_CONTROL_NAME:
"Внешний вид интерактивного Markdown по умолчанию",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `Приведенные ниже настройки будут влиять только на будущие вставки. Текущие вставки остаются неизменными. Настройки темы для встроенных фреймов находятся в разделе "Внешний вид и поведение Excalidraw".`,
MD_EMBED_SINGLECLICK_EDIT_NAME:
"Редактирование встроенной разметки (Markdown) одним щелчком мыши",
@@ -899,12 +997,17 @@ export default {
EMBED_HEAD: "Встраивание Excalidraw в заметки и экспорт",
EMBED_DESC: `В настройках "Вставка и экспорт" можно настроить вставку и экспорт изображений и рисунков Excalidraw в документы. Основные настройки включают выбор типа изображения для предварительного просмотра в формате разметки (например, Native SVG или PNG), указание типа файла для вставки в документ (оригинальный Excalidraw, PNG или SVG) и управление кэшированием изображений для вставки в разметку. Вы также можете управлять размерами изображений, вставлять рисунки с помощью ссылок на вики или ссылок на разметку, а также настраивать темы изображений, цвета фона и интеграцию с Obsidian.
Кроме того, есть настройки автоэкспорта, который автоматически генерирует файлы SVG и/или PNG, соответствующие названию ваших рисунков Excalidraw, сохраняя их синхронизацию при переименовании и удалении файлов.`,
EMBED_PREVIEW_LINKS_HEAD: "Предпросмотр, ссылки и Canvas",
EMBED_PREVIEW_LINKS_DESC:
"Выберите форматы предпросмотра и вставляемых файлов, поведение исходных ссылок, заполнители и иммерсивные вставки Canvas.",
EMBED_CANVAS: "Поддержка Obsidian Canvas",
EMBED_CANVAS_NAME: "Иммерсивное встраивание",
EMBED_CANVAS_DESC:
"Скрывайте границы и фон узлов холста при встраивании чертежа Excalidraw в холст. " +
"Обратите внимание, что для создания полностью прозрачного фона изображения вам все равно придется настроить Excalidraw на экспорт изображений с прозрачным фоном.",
EMBED_CACHING: "Кэширование изображений",
EMBED_CACHING_DESC:
"Настройте параллельный рендеринг и локальные кэши, очищайте изображения или резервные копии и повторно используйте экспортированные предпросмотры.",
IMAGE_CACHE_RETENTION_DAYS_NAME: "Срок хранения локального кэша изображений",
IMAGE_CACHE_RETENTION_DAYS_DESC:
"Определяет, сколько дней Excalidraw должен хранить локально закэшированные отрендеренные ресурсы, такие как вложенные изображения Excalidraw и страницы PDF, прежде чем неиспользуемые записи кэша будут удалены. " +
@@ -913,8 +1016,14 @@ export default {
"Практически это влияет только на локальное использование диска или браузерного хранилища внутри Obsidian. Это может быть особенно заметно на телефонах и на настольных системах с более жёсткими лимитами браузерного хранилища или ограниченным свободным местом на диске.<br><br>" +
"Меньшие значения быстрее освобождают локальное место, но могут приводить к более частому повторному рендерингу PDF и встроенных рисунков. Большие значения ускоряют повторные загрузки ценой большего локального кэша.",
EXPORT_SUBHEAD: "Настройки экспорта",
EXPORT_SUBHEAD_DESC:
"Настройте рендеринг PDF, данные экспортируемой сцены, размеры, тему и фон, параметры PDF по умолчанию и автоматические копии PNG/SVG.",
EMBED_SIZING: "Размер изображения",
EMBED_SIZING_DESC:
"Задайте размеры встроенных изображений по умолчанию, масштаб PNG и отступ экспорта.",
EMBED_THEME_BACKGROUND: "Тема изображения и цвет фона",
EMBED_THEME_BACKGROUND_DESC:
"Выберите фон и тему экспортируемых изображений, а также следование предпросмотра теме Obsidian.",
EMBED_IMAGE_CACHE_NAME: "Кэширование изображений для вставки в markdown",
EMBED_IMAGE_CACHE_DESC:
"Кэшируйте изображения для вставки в markdown. Это ускорит процесс встраивания, но в случае, если вы составите изображения из нескольких чертежей-субкомпонентов, " +
@@ -996,7 +1105,19 @@ export default {
EXPORT_EMBED_SCENE_DESC:
"Вставка сцены Excalidraw в экспортируемое изображение. Можно переопределить на уровне файла, добавив ключ frontmatter. <code>excalidraw-export-embed-scene: true/false</code>. " +
"Настройка вступит в силу только при следующем (повторном) открытии чертежей.",
PDF_EXPORT_SETTINGS: "Настройки экспорта PDF",
PDF_EXPORT_SETTINGS_DESC:
"Выберите размер страницы PDF, ориентацию, разбиение, поля, цвет бумаги и выравнивание по умолчанию.",
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "Макет экспорта PDF по умолчанию",
EXPORT_HEAD: "Настройки автоэкспорта",
EXPORT_AUTOEXPORT_DESC:
"Синхронизируйте экспортированные файлы и автоматически создавайте варианты SVG, PNG, для светлой и тёмной темы.",
SETTINGS_NAVIGATION_OPEN: "Открыть",
SETTINGS_BREADCRUMB_ARIA: "Путь настроек",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"Включите автоматические копии PNG или SVG, чтобы эти форматы стали доступны в списке типа вставляемого файла.",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"Выберите, что вставлять в документ при встраивании рисунка: Excalidraw, PNG или SVG.",
EXPORT_SYNC_NAME:
"Поддерживайте синхронизацию имен файлов .SVG и/или .PNG с файлом чертежа",
EXPORT_SYNC_DESC:
@@ -1069,8 +1190,11 @@ export default {
CUSTOM_PEN_DESC:
"Вы увидите эти ручки рядом с меню Obsidian на холсте. Вы можете настроить ручки на холсте, долго нажимая на кнопку ручки.",
EXPERIMENTAL_HEAD: "Разные возможности",
EXPERIMENTAL_DESC: `Среди прочих возможностей Excalidraw - установка формул LaTeX по умолчанию для новых уравнений, включение Предложение полей (Suggester) для автозаполнения, отображение индикаторов типов файлов Excalidraw, включение иммерсивного встраивания изображений в режиме предварительного просмотра и эксперименты с оптическим распознаванием символов Taskbone для извлечения текста из изображений и чертежей. Пользователи также могут ввести API-ключ Taskbone для расширенного использования сервиса OCR.`,
EXPERIMENTAL_DESC:
"Настройте значения LaTeX по умолчанию, индикаторы типов файлов, режим живого предварительного просмотра, подсказки свойств и экспериментальную интеграцию OCR Taskbone.",
EA_HEAD: "Автоматизация Excalidraw",
EA_GROUP_DESC:
"Настройте сценарии Excalidraw Automate, запуск и автозапуск, командные ссылки и параметры, предоставляемые установленными сценариями.",
EA_DESC:
"Excalidraw Автоматизация - это скриптовый и автоматизированный API для Excalidraw. К сожалению, документация по API скудна. " +
`Рекомендую прочитать <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> файл, ` +
@@ -1081,6 +1205,34 @@ export default {
FIELD_SUGGESTER_DESC:
"Предложение полей (Suggester) позаимствован у плагинов Breadcrumbs и Templater. Предложение полей (Suggester) полей будет показывать " +
"меню автозаполнения при вводе текста с описанием функций <code>excalidraw-</code> или <code>ea.</code> в качестве подсказок для отдельных элементов в списке.",
ALLOW_JS_FILES_NAME: "Загружать файлы JavaScript из папки скриптов",
ALLOW_JS_FILES_DESC:
"Если включено, Excalidraw Automate отслеживает и запускает файлы <code>.js</code> в папке скриптов и принимает скрипт запуска <code>.js</code>. " +
"По умолчанию Obsidian Sync не синхронизирует файлы, отличные от Markdown, Obsidian не открывает файлы <code>.js</code> для редактирования, а проводник файлов скрывает их. При необходимости включите <b>Синхронизировать все остальные типы</b> и <b>Показывать все типы файлов</b> в Obsidian. Если существуют одноимённые скрипты <code>.md</code> и <code>.js</code>, используется файл Markdown.",
STORE_SCRIPTS_AS_JS_NAME: "Хранить загруженные скрипты как",
STORE_SCRIPTS_AS_JS_DESC:
"Выберите локальный тип файла для новых загрузок и обновлений из библиотеки скриптов. Он не зависит от того, имеет ли удалённый источник расширение <code>.md</code> или <code>.js</code>.",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "Переместить существующие файлы скриптов",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Переместить существующие скрипты в .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Переместить существующие скрипты в .md",
MIGRATE_SCRIPT_FILES_STATUS:
"Можно переместить файлов скриптов в {extension}: {eligible}. {skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"Перед продолжением создайте резервную копию хранилища.<br><br><b>{count}</b> файл(ов) скриптов будет переименовано в <code>{extension}</code>. Пути закреплённых скриптов будут обновлены. {startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"Настроенный скрипт запуска и его параметр также будут обновлены.",
MIGRATE_SCRIPT_FILES_SKIPPED:
"Одноимённых пар .md/.js, которые не будут перемещены: {count}.",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"Пропущено файлов скриптов, поскольку целевой файл уже существует: {count}.\n{files}",
MIGRATE_SCRIPT_FILES_NONE:
"Не найдено подходящих файлов скриптов для перемещения.",
MIGRATE_SCRIPT_FILES_COMPLETE:
"Перемещено файлов скриптов в {extension}: {count}.",
MIGRATE_SCRIPT_FILES_FAILED:
"Не удалось переместить файлы скриптов. Выполненные переименования по возможности отменены.",
ENABLE_ONLOAD_SCRIPTS_NAME: "Включить onload-скрипты",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"Этот файл содержит <code>excalidraw-onload-script</code>. Включить onload-скрипты?",
@@ -1093,7 +1245,7 @@ export default {
AUTOSTART_SCRIPT_PROMPT:
"хочет запускаться автоматически каждый раз, когда вы открываете рисунок Excalidraw. Разрешить это?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
"Позже это можно изменить в командной палитре («Автозапуск скриптов») или в Настройках → Совместимость → Автозапуск скриптов.",
"Позже это можно изменить в командной палитре («Автозапуск скриптов») или в Настройках → Автоматизация Excalidraw → Автозапуск скриптов.",
AUTOSTART_SCRIPT_ALLOW: "Автозапуск",
AUTOSTART_SCRIPT_DENY: "Только вручную",
AUTOSTART_SCRIPT_ASK_LATER: "Спрашивать каждый раз",
@@ -1113,9 +1265,10 @@ export default {
"Это создаёт риск при открытии рисунков из неизвестных источников: вредоносный рисунок может превратить обычный клик в запуск привилегированной команды. " +
"Включайте это только если доверяете файлу и его источнику.",
STARTUP_SCRIPT_NAME: "Сценарий запуска",
STARTUP_SCRIPT_JS_DISABLED:
"Сценарии запуска JavaScript отключены. Сначала включите файлы JavaScript в настройках Excalidraw Automate.",
STARTUP_SCRIPT_DESC:
"Если этот параметр установлен, excalidraw будет выполнять скрипт при запуске плагина. Это полезно, если вы хотите установить какой-либо из крючков Excalidraw Automate. " +
"Скрипт запуска - это файл в формате markdown, который должен содержать код javascript, который вы хотите выполнять при запуске Excalidraw.",
"Если задано, Excalidraw выполнит скрипт при запуске плагина. Это полезно для настройки крючков Excalidraw Automate. Пути без расширения используют файл Markdown; файлы <code>.js</code> принимаются, когда включена загрузка файлов JavaScript.",
STARTUP_SCRIPT_BUTTON_CREATE: "Создание сценария запуска",
STARTUP_SCRIPT_BUTTON_OPEN: "Открыть сценарий запуска",
FILETYPE_NAME:
@@ -1144,6 +1297,9 @@ export default {
"Включение этой функции упрощает использование свойств титульного листа Excalidraw, позволяя использовать множество мощных настроек. Если вы предпочитаете не загружать эти свойства автоматически, " +
"Вы можете отключить эту функцию, но при этом вам придется вручную удалить все ненужные свойства из предложения. " +
"Обратите внимание, что включение этой настройки требует перезапуска плагина, так как свойства загружаются при запуске.",
FONTS_HEAD: "Шрифты",
FONTS_DESC:
"Настройте локальные гарнитуры и загруженные шрифты CJK для Excalidraw.",
CUSTOM_FONT_HEAD: "Локальный шрифт",
ENABLE_FOURTH_FONT_NAME: "Включите опцию локального шрифта",
ENABLE_FOURTH_FONT_DESC:
@@ -1157,10 +1313,15 @@ export default {
"Если файл не выбран, Excalidraw по умолчанию использует шрифт Virgil. " +
"Для оптимальной производительности рекомендуется использовать файл .woff2, так как Excalidraw закодирует только необходимые глифы при экспорте изображений в SVG. " +
"Другие форматы шрифтов будут встраивать весь шрифт в экспортируемый файл, что может привести к значительному увеличению размера файла.",
OFFLINE_CJK_NAME: "Поддержка шрифтов CJK без подключения к Интернету",
OFFLINE_CJK_GROUP_DESC:
"Загрузите и выборочно предварительно загружайте китайские, японские и корейские шрифты, чтобы Excalidraw мог отображать их без подключения к Интернету.",
SCRIPT_SETTINGS_HEAD: "Настройки для установленных сценариев",
SCRIPT_SETTINGS_DESC:
"Некоторые сценарии Excalidraw Automate Scripts включают в себя настройки. Настройки упорядочены по сценариям. Настройки станут видны в этом списке только после того, как вы один раз выполните загруженный скрипт.",
TASKBONE_HEAD: "Taskbone Оптический распознаватель символов",
TASKBONE_GROUP_DESC:
"Настройте дополнительный онлайн-сервис OCR Taskbone для извлечения доступного для поиска текста из рисунков и изображений.",
TASKBONE_DESC:
"Это экспериментальная интеграция оптического распознавания символов в Excalidraw. Обратите внимание, что taskbone - это независимый внешний сервис, не предоставляемый ни Excalidraw, ни проектом плагинов Excalidraw-Obsidian. " +
"Сервис OCR выхватывает разборчивый текст из произвольных линий и встроенных изображений на вашем холсте и помещает распознанный текст на передний план вашего рисунка, а также в буфер обмена. " +
+148 -5
View File
@@ -15,6 +15,21 @@ export default {
// Sugester
SELECT_FILE_TO_INSERT: "选择要嵌入到当前绘图中的文件",
// main.ts
SETTINGS_DATA_INVALID:
"Excalidraw 正在等待有效的替代 data.json。在恢复该文件,或重新启动 Obsidian 并选择重置为默认值之前,设置更改不会保存。",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"收到的 Excalidraw 设置文件为空或无法读取,已拒绝该文件。当前设置已写回,以修复 data.json。",
SETTINGS_DATA_RECOVERED:
"Excalidraw 的 data.json 为空或无法读取。已自动恢复最近的有效设置。",
SETTINGS_RECOVERY_MISSING_TITLE: "Excalidraw 设置文件缺失",
SETTINGS_RECOVERY_MISSING_DESC:
"此设备上存在最近的有效设置备份。你可以恢复该备份,或将 Excalidraw 重置为出厂默认值。关闭此消息将恢复备份。",
SETTINGS_RECOVERY_CORRUPT_TITLE: "Excalidraw 设置文件已损坏",
SETTINGS_RECOVERY_CORRUPT_DESC:
"设置文件为空或无法读取,并且此设备上没有恢复备份。你可以将 Excalidraw 重置为出厂默认值,或保持文件不变,同时从其他来源恢复有效的 data.json。关闭此消息将等待替代文件。",
SETTINGS_RECOVERY_RESTORE_BACKUP: "恢复备份",
SETTINGS_RECOVERY_RESET_DEFAULTS: "重置为默认值",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "等待恢复文件",
ERROR_INITIALIZING_EA: "初始化 Excalidraw Automate 时出错",
CONVERT_URL_TO_FILE: "从 URL 下载图片到本地",
UNZIP_CURRENT_FILE: "解压当前 Excalidraw 文件",
@@ -340,6 +355,18 @@ export default {
SEARCH_SHOWHIDE_ARIA: "显示/隐藏搜索栏",
SEARCH_NEXT: "下一个",
SEARCH_PREVIOUS: "上一个",
SETTINGS_TOOLBAR_COPY: "复制设置",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "问题",
SETTINGS_TOOLBAR_WIKI: "Wiki",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "学习",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "阅读书籍",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "使用可搜索设置",
USE_DECLARATIVE_SETTINGS_DESC:
"使用 Obsidian 可搜索的多页面设置界面。关闭后将使用 Excalidraw 的旧版单页面设置。需要重启 Obsidian。",
//settings.ts
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
@@ -373,7 +400,6 @@ export default {
"禁用 Excalidraw 的上下文菜单。这在移动设备上很有用,因为上下文菜单有时会在不需要的时候弹出。",
NOTEBOOKLM_LINK_ARIA:
"向 NotebookLM 咨询有关插件的帮助。此模型已预加载了我所有的视频转录稿、发布说明和其他帮助内容。与 NotebookLM 聊天,浏览我的 250+ 视频和 Excalidraw 文件。",
NOTEBOOKLM_LINK_TEXT: "学习插件。访问 NotebookLM 知识库。",
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_ARIA: "打开 Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>在各种开关和菜单里找不着北?</b></p><p>Excalidraw 是一款为高强度工作流打造的 Visual PKM 强力工具,适合 <b>Visual-First Daily Notes</b>、深度 <b>PDF 研究</b>、<b>自动化</b>、<b>AI 集成</b> 和 <b>Visual Zettelkasten</b>。但强大能力也伴随着复杂度。</p><p>跳过反复试错。<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 加入 Excalidraw Mastery</a>,一步一步学会这些具体配置。减少工具摩擦,与视觉思维社区伙伴一起掌握知识!</p>`,
@@ -404,6 +430,14 @@ export default {
"<b>关闭:</b>您需要手动检查插件更新(设置 - 第三方插件 - 检查更新)。",
BASIC_HEAD: "基本",
BASIC_UPDATES_STARTUP_HEAD: "更新与启动",
BASIC_UPDATES_STARTUP_DESC: "发行说明、更新检查与通知,以及启动欢迎画面。",
BASIC_FILES_FOLDERS_HEAD: "文件与文件夹",
BASIC_FILES_FOLDERS_DESC:
"设置绘图、裁剪、批注、模板和 Excalidraw Automate 脚本的默认文件夹与路径。",
BASIC_STENCIL_LIBRARY_HEAD: "素材库",
BASIC_STENCIL_LIBRARY_DESC:
"选择素材库数据的存储位置,并配置其仓库文件夹和本地素材库文件。",
BASIC_DESC: `包括:更新说明,更新通知,新绘图文件、模板文件、脚本文件的存储路径等。`,
FOLDER_NAME: "Excalidraw 文件夹(區分大小寫!)",
FOLDER_DESC: "新绘图的默认存储路径。若为空,将在仓库根目录中创建新绘图。",
@@ -584,6 +618,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"按模型查看当前 Obsidian 会话的 AI Token 消耗明细。重启后将重置。",
SAVING_HEAD: "保存",
SAVING_STORAGE_AUTOSAVE_HEAD: "存储与自动保存",
SAVING_STORAGE_AUTOSAVE_DESC:
"控制绘图 JSON 压缩,并选择桌面端和移动端的自动保存间隔。",
SAVING_DESC: "包括:压缩,自动保存的时间间隔,文件的命名格式和扩展名等。",
COMPRESS_NAME: "压缩 Excalidraw JSON",
COMPRESS_DESC:
@@ -616,6 +653,8 @@ export default {
"直接退出 Obsidian 应用(在应用切换器中划掉)不会触发自动保存。" +
"此外,当您切换到其他应用时,有时系统会自动清理 Obsidian 后台以释放资源。这种情况下,自动保存会失效。",
FILENAME_HEAD: "文件名",
FILENAME_GROUP_DESC:
"配置新建、嵌入、裁剪和批注绘图文件名的生成方式。",
FILENAME_DESC: `<p>点击阅读 <a href="${URLs.MOMENTJS_COM_DOCS}">日期和时间格式参考</a>。</p>`,
FILENAME_SAMPLE: "“新建绘图”系列命令创建的文件名如:",
FILENAME_EMBED_SAMPLE:
@@ -641,6 +680,9 @@ export default {
DISPLAY_HEAD: "界面 & 行为",
DISPLAY_DESC:
"包括:左手模式、动态样式、匹配 Excalidraw 和 Obsidian 主题、默认运行模式等。",
DISPLAY_EDITOR_PREVIEWS_HEAD: "编辑与预览",
DISPLAY_EDITOR_PREVIEWS_DESC:
"配置画布编辑手势,以及 Excalidraw 文件在阅读模式和悬停预览中的显示方式。",
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "限制 Obsidian 字体大小为编辑器文本",
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
"Obsidian 的自定义字体大小设置会影响整个界面,包括 Excalidraw 和依赖默认字体大小的主题。" +
@@ -715,6 +757,8 @@ export default {
`请参阅下方 <a href='#${TAG_PDFEXPORT}'>PDF 导出设置</a>。<br>` +
`⚠️ 关闭并重新打开 Excalidraw/Markdown 文件后生效。`,
MODES_HEAD: "UI 模式",
MODES_DESC:
"选择不同设备的 Excalidraw 界面布局、标题栏控件和左右手托盘位置。",
DESKTOP_UI_MODE_NAME: "桌面端偏好模式",
DESKTOP_UI_MODE_DESC: "桌面端设备默认 UI 模式。",
TABLET_UI_MODE_NAME: "平板端偏好模式",
@@ -727,12 +771,19 @@ export default {
MODE_PHONE: "Phone-mode",
REAPPLY_UI_MODE_BUTTON: "重新应用 UI 模式",
HOTKEY_OVERRIDE_HEAD: "热键覆盖",
HOTKEY_OVERRIDE_GROUP_DESC:
"管理应优先于冲突 Obsidian 热键的 Excalidraw 按键组合。",
HOTKEY_OVERRIDE_CONTROL_NAME: "管理热键覆盖",
HOTKEY_OVERRIDE_DESC:
`一些 Excalidraw 的热键,如 ${labelCTRL()}+Enter 用于编辑文本,或 ${labelCTRL()}+K 用于创建元素链接,` +
"与 Obsidian 的热键设置冲突。您在下面添加的热键组合将在使用 Excalidraw 时覆盖 Obsidian 的热键设置," +
`因此如果您希望在 Excalidraw 中默认“编组”,而不是“查看关系图谱”(核心插件 - 关系图谱),您可以添加 ${labelCTRL()}+G。`,
THEME_HEAD: "主题和样式",
THEME_DESC:
"控制界面样式、绘图和嵌入主题、打开模式以及移动设备安全区域间距。",
ZOOM_AND_PAN_HEAD: "缩放和平移",
ZOOM_AND_PAN_DESC:
"配置鼠标、触控、打开、调整大小和缩放范围行为。",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右键拖动平移",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"右键点击并拖动来平移绘图(和在线白板工具 Miro 类似)。按 'm' 键打开上下文菜单。",
@@ -765,7 +816,9 @@ export default {
ZOOM_MAX_DESC:
"绘图放大的极限。默认:3000%。通常无需修改,考虑完整性而提供。",
PEN_HEAD: "手写笔",
PEN_DESC: "配置自动手写笔模式、触控手势、橡皮擦和自由绘制十字线。",
GRID_HEAD: "网格",
GRID_DESC: "配置网格方向、自动或自定义颜色以及不透明度。",
GRID_DYNAMIC_COLOR_NAME: "动态网格颜色",
GRID_DYNAMIC_COLOR_DESC:
"<b>开启:</b>更改网格颜色以匹配绘图颜色。<br><b>关闭:</b>将以下颜色用作网格颜色。",
@@ -778,6 +831,7 @@ export default {
GRID_HORIZONTAL: "渲染水平网格",
GRID_VERTICAL: "渲染垂直网格",
LASER_HEAD: "激光笔工具(更多工具 > 激光笔)",
LASER_DESC: "配置激光笔颜色及其轨迹淡出的速度和长度。",
LASER_COLOR: "激光笔颜色",
LASER_DECAY_TIME_NAME: "激光笔消失时间",
LASER_DECAY_TIME_DESC: "单位是毫秒,默认 1000(即 1 秒)。",
@@ -796,6 +850,20 @@ export default {
"链接的源文件被重命名时,绘图中相应的 <code>[[内部链接]]</code> 也会同步更新。" +
"若您不愿绘图中的链接外观因此而变化,可使用 <code>[[内部链接|别名]]</code>。",
DRAG_MODIFIER_NAME: "修饰键",
DRAG_MODIFIER_GROUP_DESC:
"配置链接打开手势,以及点击和拖放操作的平台特定修饰键组合。",
LINK_OPENING_GESTURES_HEAD: "链接打开手势",
LINK_OPENING_GESTURES_DESC:
"配置嵌入绘图和查看模式中的长按延迟与双击打开链接。",
WEB_BROWSER_DRAG_ACTION_DESC:
"选择从网页浏览器拖入链接、图片、导入项和嵌入内容时的修饰键组合。",
LOCAL_FILE_DRAG_ACTION_DESC:
"选择从操作系统拖入链接、图片、导入项和嵌入内容时的修饰键组合。",
INTERNAL_DRAG_ACTION_DESC:
"选择在 Obsidian 内拖动链接、图片、全尺寸图片和嵌入内容时的修饰键组合。",
PANE_TARGET_DESC: "选择决定点击链接打开位置的修饰键组合。",
MODIFIER_KEY_USAGE_NAME: "配置修饰键",
MODIFIER_KEY_COMBINATIONS: "修饰键组合",
DRAG_MODIFIER_DESC:
`在您按住点击链接或拖动元素时,可以触发某些行为。您可以为这些行为添加修饰键。` +
`Excalidraw 不会检查您的设置是否合理,因此请谨慎设置,避免冲突。` +
@@ -891,6 +959,20 @@ export default {
"拖动链接到 Excalidraw 时,使用 <code>http" +
"s://noembed" +
".com/embed?url=</code> 来获取 HTTPS 页面标题。",
LINK_BEHAVIOR_HEAD: "链接行为",
LINK_BEHAVIOR_DESC:
"配置链接同步、相关链接、悬停预览、点击处理和网页标题查询。",
LINK_USAGE_NAME: "在 Excalidraw 中使用链接",
LINK_OPENING_HEAD: "窗格和标签页行为",
LINK_OPENING_DESC:
"选择链接是否复用、聚焦或切换窗格、标签页和主工作区。",
LINK_APPEARANCE_HEAD: "链接外观",
LINK_APPEARANCE_DESC: "配置链接显示时使用的括号、前缀、图标和不透明度。",
TODO_HEAD: "待办事项",
TODO_GROUP_DESC: "配置待办事项解析以及未完成和已完成任务使用的图标。",
TRANSCLUSION_HEAD: "文本嵌入",
TRANSCLUSION_DESC:
"配置嵌入 Markdown 文本的字符限制、换行和引用符号清理。",
PDF_TO_IMAGE: "以图像形式嵌入到绘图中的 PDF",
PDF_TO_IMAGE_SCALE_NAME: "分辨率",
PDF_TO_IMAGE_SCALE_DESC:
@@ -900,8 +982,13 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"包括:以图像形式嵌入到绘图中的 PDF、以交互或图像形式嵌入到绘图中的 Markdown 文档等。",
MD_HEAD: "以图像形式嵌入到绘图中的 Markdown 文档(MD-Embed)",
MD_GROUP_DESC:
"设置以图像呈现的 Markdown 文件的尺寸、字体、颜色、边框和 CSS。",
MD_EMBED_CUSTOMDATA_HEAD_NAME:
"以交互形式嵌入到绘图中的 Markdown 文档(MD-Embeddable)",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"配置未来交互式 Markdown 嵌入的编辑方式和默认外观。",
MD_EMBED_DEFAULTS_CONTROL_NAME: "交互式 Markdown 默认外观",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `以下设置只会影响以后的嵌入。已存在的嵌入保持不变。嵌入框的主题设置位于“界面 & 行为”部分。`,
MD_EMBED_SINGLECLICK_EDIT_NAME: "单击编辑嵌入的 Markdown",
MD_EMBED_SINGLECLICK_EDIT_DESC:
@@ -941,12 +1028,17 @@ export default {
EMBED_HEAD: "嵌入到 Markdown 文档中的绘图",
EMBED_DESC: `包括:嵌入到 Markdown 文档中的绘图的预览图类型(SVG、PNG)、源文件类型(Excalidraw、SVG、PNG)、缓存、图像尺寸、图像主题,以及嵌入的语法等。
此外,还有自动导出 SVG 或 PNG 文件并保持与绘图文件状态同步的设置。`,
EMBED_PREVIEW_LINKS_HEAD: "预览、链接与 Canvas",
EMBED_PREVIEW_LINKS_DESC:
"选择预览和插入文件的格式、源链接行为、占位图像及沉浸式 Canvas 嵌入。",
EMBED_CANVAS: "Obsidian 白板支持",
EMBED_CANVAS_NAME: "沉浸式嵌入",
EMBED_CANVAS_DESC:
"当嵌入绘图到 Obsidian 白板中时,隐藏节点的边界和背景。" +
"注意:如果想要背景完全透明,您依然需要设置导出背景为透明(关闭“导出图片包含背景”)。",
EMBED_CACHING: "图像缓存和渲染优化",
EMBED_CACHING_DESC:
"调整并行渲染和本地图像缓存,清除缓存图像或备份,并可复用已导出的预览。",
RENDERING_CONCURRENCY_NAME: "图像渲染并发性",
RENDERING_CONCURRENCY_DESC:
"用于图像渲染的并行工作线程数。增加该值可以加快渲染速度,但可能会减慢系统其他部分的运行速度。" +
@@ -959,8 +1051,13 @@ export default {
"实际影响在于 Obsidian 内部的本地磁盘或浏览器存储占用。在手机以及浏览器存储配额较紧、剩余磁盘空间有限的桌面设备上需要留意。<br><br>" +
"较小的值会更快回收本地缓存空间,但可能导致 PDF 和嵌入绘图更频繁地重新渲染。较大的值会保留更久的缓存,以换取更快的加载速度。",
EXPORT_SUBHEAD: "导出",
EXPORT_SUBHEAD_DESC:
"配置 PDF 渲染、导出的场景数据、图像尺寸、主题与背景、PDF 默认值及自动 PNG/SVG 副本。",
EMBED_SIZING: "图像尺寸",
EMBED_SIZING_DESC: "设置嵌入图像的默认尺寸、PNG 缩放比例和导出边距。",
EMBED_THEME_BACKGROUND: "图像的主题和背景色",
EMBED_THEME_BACKGROUND_DESC:
"选择导出图像的背景和主题,以及预览是否跟随 Obsidian 主题。",
EMBED_IMAGE_CACHE_NAME: "为嵌入到 Markdown 文档中的绘图创建预览图缓存",
EMBED_IMAGE_CACHE_DESC:
"可提高下次嵌入的速度。" +
@@ -1040,7 +1137,18 @@ export default {
"在导出图片中嵌入 Excalidraw 场景。可以在其 frontmatter 中添加如 <code>excalidraw-export-embed-scene: true/false</code> 的键值对来覆盖该项。" +
"该项仅在您下次(重新)打开绘图时生效。",
PDF_EXPORT_SETTINGS: "PDF 导出设置",
PDF_EXPORT_SETTINGS_DESC:
"选择默认 PDF 页面大小、方向、分页、边距、纸张颜色和对齐方式。",
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "默认 PDF 导出布局",
EXPORT_HEAD: "导出设置",
EXPORT_AUTOEXPORT_DESC:
"保持导出文件同步,并自动创建 SVG、PNG、浅色和深色版本。",
SETTINGS_NAVIGATION_OPEN: "打开",
SETTINGS_BREADCRUMB_ARIA: "设置路径",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"启用自动 PNG 或 SVG 副本,使这些格式可在插入文件类型下拉列表中选择。",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"选择在文档中嵌入绘图时插入 Excalidraw、PNG 还是 SVG。",
EXPORT_SYNC_NAME: "保持 SVG/PNG 文件名与绘图文件同步",
EXPORT_SYNC_DESC:
"打开后,当绘图文件被重命名时,插件将同步更新同文件夹下的同名 .SVG 和 .PNG 文件。" +
@@ -1113,8 +1221,11 @@ export default {
CUSTOM_PEN_DESC:
"在绘图上的 Obsidian 菜单按钮旁边切换自定义画笔。长按(双击)画笔按钮可以修改其样式。",
EXPERIMENTAL_HEAD: "杂项",
EXPERIMENTAL_DESC: `包括:默认的 LaTeX 公式,字段建议,绘图文件的类型标识符,OCR 等。`,
EXPERIMENTAL_DESC:
"配置 LaTeX 默认值、文件类型标识、实时预览行为、属性建议以及实验性的 Taskbone OCR 集成。",
EA_HEAD: "Excalidraw 自动化",
EA_GROUP_DESC:
"配置 Excalidraw Automate 脚本、启动和自动启动行为、命令链接,以及已安装脚本提供的设置。",
EA_DESC:
`ExcalidrawAutomate 是用于 Excalidraw 自动化脚本的 API,但是目前说明文档还不够完善,` +
`建议阅读 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> 文件源码,` +
@@ -1125,6 +1236,33 @@ export default {
FIELD_SUGGESTER_DESC:
"开启后,当您在编辑器中输入 <code>excalidraw-</code> 或者 <code>ea.</code> 时,会弹出一个带有函数说明的自动补全提示菜单。<br>" +
"该功能借鉴了 Breadcrumbs 和 Templater 插件。",
ALLOW_JS_FILES_NAME: "从 Scripts 文件夹加载 JavaScript 文件",
ALLOW_JS_FILES_DESC:
"启用后,Excalidraw Automate 会监视并运行 Scripts 文件夹中的 <code>.js</code> 文件,也允许使用 <code>.js</code> 启动脚本。" +
"默认情况下,Obsidian Sync 不同步非 Markdown 文件,Obsidian 不会打开 <code>.js</code> 文件进行编辑,文件列表也会隐藏它们。需要时请在 Obsidian 中启用<b>同步所有其他文件类型</b>和<b>显示所有文件类型</b>。如果存在同名的 <code>.md</code> 和 <code>.js</code> 脚本,将使用 Markdown 文件。",
STORE_SCRIPTS_AS_JS_NAME: "将下载的脚本存储为",
STORE_SCRIPTS_AS_JS_DESC:
"选择脚本库新下载和更新在本地使用的文件类型。无论远程源是 <code>.md</code> 还是 <code>.js</code>,都会使用此设置。",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "迁移现有脚本文件",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "将现有脚本迁移为 .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "将现有脚本迁移为 .md",
MIGRATE_SCRIPT_FILES_STATUS:
"有 {eligible} 个脚本文件可迁移为 {extension}。{skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"继续前请备份仓库。<br><br><b>{count}</b> 个脚本文件将重命名为 <code>{extension}</code>,固定脚本的路径也会更新。{startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"已配置的启动脚本及其设置也会更新。",
MIGRATE_SCRIPT_FILES_SKIPPED:
"有 {count} 对同名 .md/.js 文件不会被迁移。",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"因目标文件已存在,已跳过 {count} 个脚本文件:\n{files}",
MIGRATE_SCRIPT_FILES_NONE: "没有找到可迁移的脚本文件。",
MIGRATE_SCRIPT_FILES_COMPLETE:
"已将 {count} 个脚本文件迁移为 {extension}。",
MIGRATE_SCRIPT_FILES_FAILED:
"无法迁移脚本文件。已尽可能回滚完成的重命名。",
ENABLE_ONLOAD_SCRIPTS_NAME: "加载期脚本(onload)",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"此文件包含 <code>excalidraw-onload-script</code>。是否启用加载期脚本?",
@@ -1137,7 +1275,7 @@ export default {
AUTOSTART_SCRIPT_PROMPT:
"希望在你每次打开 Excalidraw 绘图时自动运行。是否允许?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
"你以后可以在命令面板(“自动启动脚本”)或设置 → 兼容性 → 自动启动脚本中更改此设置。",
"你以后可以在命令面板(“自动启动脚本”)或设置 → Excalidraw 自动化 → 自动启动脚本中更改此设置。",
AUTOSTART_SCRIPT_ALLOW: "自动启动",
AUTOSTART_SCRIPT_DENY: "仅手动启动",
AUTOSTART_SCRIPT_ASK_LATER: "每次都询问",
@@ -1156,9 +1294,10 @@ export default {
"如果你打开未知来源的绘图,这会带来风险:恶意绘图可以让一次普通点击触发高权限命令。" +
"只有在你信任该文件及其来源时才启用此功能。",
STARTUP_SCRIPT_NAME: "启动期脚本(startup)",
STARTUP_SCRIPT_JS_DISABLED:
"JavaScript 启动脚本已禁用。请先在 Excalidraw Automate 设置中启用 JavaScript 文件。",
STARTUP_SCRIPT_DESC:
"插件启动时将自动执行该脚本。可用于设置 Excalidraw 自动化钩子。" +
"该脚本是包含 javascript 代码的 Markdown 文件。",
"插件启动时将自动执行该脚本,可用于设置 Excalidraw Automate 钩子。没有扩展名的路径使用 Markdown 文件;启用 JavaScript 文件加载后可使用 <code>.js</code> 文件。",
STARTUP_SCRIPT_BUTTON_CREATE: "创建启动期脚本",
STARTUP_SCRIPT_BUTTON_OPEN: "打开启动期脚本",
FILETYPE_NAME: "在文件浏览器中为 excalidraw.md 文件添加类型标识符(如 ✏️)",
@@ -1199,6 +1338,8 @@ export default {
"为了获得最佳性能,建议使用 .woff2 文件,因为当导出 SVG 格式的图片时,Excalidraw 只会编码必要的字形。" +
`其他字体格式将在导出文件中嵌入整个字体,可能会导致文件大小显著增加。<b>译者注:</b>可在 <a href="${URLs.WANGCHUJIANG_COM_FREE_FONT}" target='_blank'>Free Font</a> 获取免费商用中文手写字体。`,
OFFLINE_CJK_NAME: "离线 CJK 字体支持",
OFFLINE_CJK_GROUP_DESC:
"下载并按需预加载中文、日文和韩文字体,使 Excalidraw 无需互联网连接也能显示这些字体。",
OFFLINE_CJK_DESC: `<strong>该项需要重启 Obsidian 才能生效。</strong><br>
Excalidraw.com 提供手写风格的 CJK 字体。默认情况下,这些字体不会包含在插件本地,而是从互联网获取。
如果您希望 Excalidraw 完全本地化,以便在没有互联网连接的情况下使用,可以从 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">GitHub 下载所需的字体文件</a>。
@@ -1215,6 +1356,8 @@ export default {
SCRIPT_SETTINGS_DESC:
"有些 Excalidraw 自动化脚本包含设置项,当执行这些脚本时,它们会在该列表下添加设置项。",
TASKBONE_HEAD: "Taskbone OCR(光学符号识别)",
TASKBONE_GROUP_DESC:
"配置可选的 Taskbone 在线 OCR 服务,从绘图和图像中提取可搜索文本。",
TASKBONE_DESC:
"这是一个将 OCR 融入 Excalidraw 的实验性功能。请注意,Taskbone 是一项独立的外部服务,而不是由 Excalidraw 或 obsidian-excalidraw-plugin 项目提供的。" +
"OCR 能够对绘图上用自由画笔工具写下的涂鸦或者嵌入的图像进行文本识别,并将识别出来的文本写入绘图文件的 frontmatter,同时复制到剪贴板。" +
+148 -5
View File
@@ -15,6 +15,21 @@ export default {
// Sugester
SELECT_FILE_TO_INSERT: "選擇要嵌入到當前繪圖中的檔案",
// main.ts
SETTINGS_DATA_INVALID:
"Excalidraw 正在等待有效的替代 data.json。在復原該檔案,或重新啟動 Obsidian 並選擇重設為預設值之前,設定變更不會儲存。",
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
"收到的 Excalidraw 設定檔為空或無法讀取,已拒絕該檔案。目前的設定已寫回,以修復 data.json。",
SETTINGS_DATA_RECOVERED:
"Excalidraw 的 data.json 為空或無法讀取。已自動復原最近的有效設定。",
SETTINGS_RECOVERY_MISSING_TITLE: "Excalidraw 設定檔遺失",
SETTINGS_RECOVERY_MISSING_DESC:
"此裝置上有最近的有效設定備份。你可以復原該備份,或將 Excalidraw 重設為出廠預設值。關閉此訊息將復原備份。",
SETTINGS_RECOVERY_CORRUPT_TITLE: "Excalidraw 設定檔已損壞",
SETTINGS_RECOVERY_CORRUPT_DESC:
"設定檔為空或無法讀取,且此裝置上沒有復原備份。你可以將 Excalidraw 重設為出廠預設值,或保持檔案不變,同時從其他來源復原有效的 data.json。關閉此訊息將等待替代檔案。",
SETTINGS_RECOVERY_RESTORE_BACKUP: "復原備份",
SETTINGS_RECOVERY_RESET_DEFAULTS: "重設為預設值",
SETTINGS_RECOVERY_WAIT_FOR_FILE: "等待復原檔案",
ERROR_INITIALIZING_EA: "初始化 Excalidraw Automate 時出錯",
CONVERT_URL_TO_FILE: "從 URL 下載圖片到本地",
UNZIP_CURRENT_FILE: "解壓當前 Excalidraw 檔案",
@@ -340,6 +355,18 @@ export default {
SEARCH_SHOWHIDE_ARIA: "顯示/隱藏搜尋欄",
SEARCH_NEXT: "下一個",
SEARCH_PREVIOUS: "上一個",
SETTINGS_TOOLBAR_COPY: "複製設定",
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
SETTINGS_TOOLBAR_BUGS: "問題",
SETTINGS_TOOLBAR_WIKI: "Wiki",
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
SETTINGS_TOOLBAR_LEARN: "學習",
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
SETTINGS_TOOLBAR_READ: "閱讀書籍",
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
USE_DECLARATIVE_SETTINGS_NAME: "使用可搜尋設定",
USE_DECLARATIVE_SETTINGS_DESC:
"使用 Obsidian 可搜尋的多頁面設定介面。關閉後將使用 Excalidraw 的舊版單頁面設定。需要重新啟動 Obsidian。",
//settings.ts
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
@@ -373,7 +400,6 @@ export default {
"停用 Excalidraw 的上下文選單。這在移動裝置上很有用,因為上下文選單有時會在不需要的時候彈出。",
NOTEBOOKLM_LINK_ARIA:
"向 NotebookLM 諮詢有關外掛的幫助。此模型已預載入了我所有的影片轉錄稿、釋出說明和其他幫助內容。與 NotebookLM 聊天,瀏覽我的 250+ 影片和 Excalidraw 檔案。",
NOTEBOOKLM_LINK_TEXT: "學習外掛。訪問 NotebookLM 知識庫。",
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_ARIA: "開啟 Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>在各種開關和選單裡找不著北?</b></p><p>Excalidraw 是一款為高強度工作流打造的 Visual PKM 強力工具,適合 <b>Visual-First Daily Notes</b>、深度 <b>PDF 研究</b>、<b>自動化</b>、<b>AI 整合</b> 和 <b>Visual Zettelkasten</b>。但強大能力也伴隨著複雜度。</p><p>跳過反覆試錯。<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 加入 Excalidraw Mastery</a>,一步一步學會這些具體配置。減少工具摩擦,與視覺思維社群夥伴一起掌握知識!</p>`,
@@ -404,6 +430,14 @@ export default {
"<b>關閉:</b>您需要手動檢查外掛更新(設定 - 第三方外掛 - 檢查更新)。",
BASIC_HEAD: "基本",
BASIC_UPDATES_STARTUP_HEAD: "更新與啟動",
BASIC_UPDATES_STARTUP_DESC: "版本說明、更新檢查與通知,以及啟動歡迎畫面。",
BASIC_FILES_FOLDERS_HEAD: "檔案與資料夾",
BASIC_FILES_FOLDERS_DESC:
"設定繪圖、裁切、註解、範本和 Excalidraw Automate 指令碼的預設資料夾與路徑。",
BASIC_STENCIL_LIBRARY_HEAD: "素材庫",
BASIC_STENCIL_LIBRARY_DESC:
"選擇素材庫資料的儲存位置,並設定其儲存庫資料夾和本機素材庫檔案。",
BASIC_DESC: `包括:更新說明,更新通知,新繪圖檔案、模板檔案、指令碼檔案的儲存路徑等。`,
FOLDER_NAME: "Excalidraw 資料夾(區分大小寫!)",
FOLDER_DESC: "新繪圖的預設儲存路徑。若為空,將在倉庫根目錄中建立新繪圖。",
@@ -584,6 +618,9 @@ export default {
AI_USAGE_SETTINGS_BUTTON_DESC:
"按模型檢視當前 Obsidian 會話的 AI Token 消耗明細。重啟後將重置。",
SAVING_HEAD: "儲存",
SAVING_STORAGE_AUTOSAVE_HEAD: "儲存與自動儲存",
SAVING_STORAGE_AUTOSAVE_DESC:
"控制繪圖 JSON 壓縮,並選擇桌面版和行動版的自動儲存間隔。",
SAVING_DESC: "包括:壓縮,自動儲存的時間間隔,檔案的命名格式和副檔名等。",
COMPRESS_NAME: "壓縮 Excalidraw JSON",
COMPRESS_DESC:
@@ -616,6 +653,8 @@ export default {
"直接退出 Obsidian 應用(在應用切換器中劃掉)不會觸發自動儲存。" +
"此外,當您切換到其他應用時,有時系統會自動清理 Obsidian 後臺以釋放資源。這種情況下,自動儲存會失效。",
FILENAME_HEAD: "檔名",
FILENAME_GROUP_DESC:
"設定新建、嵌入、裁切和註解繪圖檔名的產生方式。",
FILENAME_DESC: `<p>點選閱讀 <a href="${URLs.MOMENTJS_COM_DOCS}">日期和時間格式參考</a>。</p>`,
FILENAME_SAMPLE: "“新建繪圖”系列命令建立的檔名如:",
FILENAME_EMBED_SAMPLE:
@@ -641,6 +680,9 @@ export default {
DISPLAY_HEAD: "介面 & 行為",
DISPLAY_DESC:
"包括:左手模式、動態樣式、匹配 Excalidraw 和 Obsidian 主題、預設執行模式等。",
DISPLAY_EDITOR_PREVIEWS_HEAD: "編輯與預覽",
DISPLAY_EDITOR_PREVIEWS_DESC:
"設定畫布編輯手勢,以及 Excalidraw 檔案在閱讀模式和懸停預覽中的顯示方式。",
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "限制 Obsidian 字型大小為編輯器文字",
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
"Obsidian 的自定義字型大小設定會影響整個介面,包括 Excalidraw 和依賴預設字型大小的主題。" +
@@ -715,6 +757,8 @@ export default {
`請參閱下方 <a href='#${TAG_PDFEXPORT}'>PDF 匯出設定</a>。<br>` +
`⚠️ 關閉並重新開啟 Excalidraw/Markdown 檔案後生效。`,
MODES_HEAD: "UI 模式",
MODES_DESC:
"選擇不同裝置的 Excalidraw 介面配置、標題列控制項和左右手托盤位置。",
DESKTOP_UI_MODE_NAME: "桌面端偏好模式",
DESKTOP_UI_MODE_DESC: "桌面端裝置預設 UI 模式。",
TABLET_UI_MODE_NAME: "平板端偏好模式",
@@ -727,12 +771,19 @@ export default {
MODE_PHONE: "Phone-mode",
REAPPLY_UI_MODE_BUTTON: "重新應用 UI 模式",
HOTKEY_OVERRIDE_HEAD: "熱鍵覆蓋",
HOTKEY_OVERRIDE_GROUP_DESC:
"管理應優先於衝突 Obsidian 熱鍵的 Excalidraw 按鍵組合。",
HOTKEY_OVERRIDE_CONTROL_NAME: "管理熱鍵覆蓋",
HOTKEY_OVERRIDE_DESC:
`一些 Excalidraw 的熱鍵,如 ${labelCTRL()}+Enter 用於編輯文字,或 ${labelCTRL()}+K 用於建立元素連結,` +
"與 Obsidian 的熱鍵設定衝突。您在下面新增的熱鍵組合將在使用 Excalidraw 時覆蓋 Obsidian 的熱鍵設定," +
`因此如果您希望在 Excalidraw 中預設“編組”,而不是“檢視關係圖譜”(核心外掛 - 關係圖譜),您可以新增 ${labelCTRL()}+G。`,
THEME_HEAD: "主題和樣式",
THEME_DESC:
"控制介面樣式、繪圖和嵌入主題、開啟模式以及行動裝置安全區域間距。",
ZOOM_AND_PAN_HEAD: "縮放和平移",
ZOOM_AND_PAN_DESC:
"設定滑鼠、觸控、開啟、調整大小和縮放範圍行為。",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右鍵拖動平移",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
"右鍵點選並拖動來平移繪圖(和線上白板工具 Miro 類似)。按 'm' 鍵開啟上下文選單。",
@@ -765,7 +816,9 @@ export default {
ZOOM_MAX_DESC:
"繪圖放大的極限。預設:3000%。通常無需修改,考慮完整性而提供。",
PEN_HEAD: "手寫筆",
PEN_DESC: "設定自動手寫筆模式、觸控手勢、橡皮擦和自由繪製十字線。",
GRID_HEAD: "網格",
GRID_DESC: "設定網格方向、自動或自訂顏色以及不透明度。",
GRID_DYNAMIC_COLOR_NAME: "動態網格顏色",
GRID_DYNAMIC_COLOR_DESC:
"<b>開啟:</b>更改網格顏色以匹配繪圖顏色。<br><b>關閉:</b>將以下顏色用作網格顏色。",
@@ -778,6 +831,7 @@ export default {
GRID_HORIZONTAL: "渲染水平網格",
GRID_VERTICAL: "渲染垂直網格",
LASER_HEAD: "雷射筆工具(更多工具 > 雷射筆)",
LASER_DESC: "設定雷射筆顏色及其軌跡淡出的速度和長度。",
LASER_COLOR: "雷射筆顏色",
LASER_DECAY_TIME_NAME: "雷射筆消失時間",
LASER_DECAY_TIME_DESC: "單位是毫秒,預設 1000(即 1 秒)。",
@@ -796,6 +850,20 @@ export default {
"連結的原始檔被重新命名時,繪圖中相應的 <code>[[內部連結]]</code> 也會同步更新。" +
"若您不願繪圖中的連結外觀因此而變化,可使用 <code>[[內部連結|別名]]</code>。",
DRAG_MODIFIER_NAME: "修飾鍵",
DRAG_MODIFIER_GROUP_DESC:
"設定連結開啟手勢,以及點擊和拖放操作的平台特定修飾鍵組合。",
LINK_OPENING_GESTURES_HEAD: "連結開啟手勢",
LINK_OPENING_GESTURES_DESC:
"設定嵌入繪圖和檢視模式中的長按延遲與雙擊開啟連結。",
WEB_BROWSER_DRAG_ACTION_DESC:
"選擇從網頁瀏覽器拖入連結、圖片、匯入項目和嵌入內容時的修飾鍵組合。",
LOCAL_FILE_DRAG_ACTION_DESC:
"選擇從作業系統拖入連結、圖片、匯入項目和嵌入內容時的修飾鍵組合。",
INTERNAL_DRAG_ACTION_DESC:
"選擇在 Obsidian 內拖動連結、圖片、完整尺寸圖片和嵌入內容時的修飾鍵組合。",
PANE_TARGET_DESC: "選擇決定點擊連結開啟位置的修飾鍵組合。",
MODIFIER_KEY_USAGE_NAME: "設定修飾鍵",
MODIFIER_KEY_COMBINATIONS: "修飾鍵組合",
DRAG_MODIFIER_DESC:
`在您按住點選連結或拖動元素時,可以觸發某些行為。您可以為這些行為新增修飾鍵。` +
`Excalidraw 不會檢查您的設定是否合理,因此請謹慎設定,避免衝突。` +
@@ -891,6 +959,20 @@ export default {
"拖動連結到 Excalidraw 時,使用 <code>http" +
"s://noembed" +
".com/embed?url=</code> 來獲取 HTTPS 頁面標題。",
LINK_BEHAVIOR_HEAD: "連結行為",
LINK_BEHAVIOR_DESC:
"設定連結同步、相關連結、懸停預覽、點擊處理和網頁標題查詢。",
LINK_USAGE_NAME: "在 Excalidraw 中使用連結",
LINK_OPENING_HEAD: "窗格和分頁行為",
LINK_OPENING_DESC:
"選擇連結是否重複使用、聚焦或切換窗格、分頁和主要工作區。",
LINK_APPEARANCE_HEAD: "連結外觀",
LINK_APPEARANCE_DESC: "設定連結顯示時使用的括號、前綴、圖示和不透明度。",
TODO_HEAD: "待辦事項",
TODO_GROUP_DESC: "設定待辦事項解析以及未完成和已完成任務使用的圖示。",
TRANSCLUSION_HEAD: "文字嵌入",
TRANSCLUSION_DESC:
"設定嵌入 Markdown 文字的字元限制、換行和引用符號清理。",
PDF_TO_IMAGE: "以影像形式嵌入到繪圖中的 PDF",
PDF_TO_IMAGE_SCALE_NAME: "解析度",
PDF_TO_IMAGE_SCALE_DESC:
@@ -900,8 +982,13 @@ export default {
EMBED_TOEXCALIDRAW_DESC:
"包括:以影像形式嵌入到繪圖中的 PDF、以互動或影像形式嵌入到繪圖中的 Markdown 文件等。",
MD_HEAD: "以影像形式嵌入到繪圖中的 Markdown 文件(MD-Embed)",
MD_GROUP_DESC:
"設定以影像呈現的 Markdown 檔案之尺寸、字型、顏色、邊框和 CSS。",
MD_EMBED_CUSTOMDATA_HEAD_NAME:
"以互動形式嵌入到繪圖中的 Markdown 文件(MD-Embeddable)",
MD_EMBED_CUSTOMDATA_GROUP_DESC:
"設定未來互動式 Markdown 嵌入的編輯方式和預設外觀。",
MD_EMBED_DEFAULTS_CONTROL_NAME: "互動式 Markdown 預設外觀",
MD_EMBED_CUSTOMDATA_HEAD_DESC: `以下設定只會影響以後的嵌入。已存在的嵌入保持不變。嵌入框的主題設定位於“介面 & 行為”部分。`,
MD_EMBED_SINGLECLICK_EDIT_NAME: "單擊編輯嵌入的 Markdown",
MD_EMBED_SINGLECLICK_EDIT_DESC:
@@ -941,12 +1028,17 @@ export default {
EMBED_HEAD: "嵌入到 Markdown 文件中的繪圖",
EMBED_DESC: `包括:嵌入到 Markdown 文件中的繪圖的預覽圖型別(SVG、PNG)、原始檔型別(Excalidraw、SVG、PNG)、快取、影像尺寸、影像主題,以及嵌入的語法等。
此外,還有自動匯出 SVG 或 PNG 檔案並保持與繪圖檔案狀態同步的設定。`,
EMBED_PREVIEW_LINKS_HEAD: "預覽、連結與 Canvas",
EMBED_PREVIEW_LINKS_DESC:
"選擇預覽和插入檔案的格式、來源連結行為、預留影像及沉浸式 Canvas 嵌入。",
EMBED_CANVAS: "Obsidian 白板支援",
EMBED_CANVAS_NAME: "沉浸式嵌入",
EMBED_CANVAS_DESC:
"當嵌入繪圖到 Obsidian 白板中時,隱藏節點的邊界和背景。" +
"注意:如果想要背景完全透明,您依然需要設定匯出背景為透明(關閉“匯出圖片包含背景”)。",
EMBED_CACHING: "影像快取和渲染最佳化",
EMBED_CACHING_DESC:
"調整平行渲染和本機圖片快取、清除快取圖片或備份,並可重用已匯出的預覽。",
RENDERING_CONCURRENCY_NAME: "影像渲染併發性",
RENDERING_CONCURRENCY_DESC:
"用於影像渲染的並行工作執行緒數。增加該值可以加快渲染速度,但可能會減慢系統其他部分的執行速度。" +
@@ -959,8 +1051,13 @@ export default {
"實際影響在於 Obsidian 內部的本地磁碟或瀏覽器儲存佔用。在手機以及瀏覽器儲存配額較緊、剩餘磁碟空間有限的桌面裝置上需要留意。<br><br>" +
"較小的值會更快回收本地快取空間,但可能導致 PDF 和嵌入繪圖更頻繁地重新渲染。較大的值會保留更久的快取,以換取更快的載入速度。",
EXPORT_SUBHEAD: "匯出",
EXPORT_SUBHEAD_DESC:
"設定 PDF 渲染、匯出的場景資料、影像尺寸、主題與背景、PDF 預設值及自動 PNG/SVG 副本。",
EMBED_SIZING: "影像尺寸",
EMBED_SIZING_DESC: "設定嵌入影像的預設尺寸、PNG 縮放比例和匯出邊距。",
EMBED_THEME_BACKGROUND: "影像的主題和背景色",
EMBED_THEME_BACKGROUND_DESC:
"選擇匯出影像的背景和主題,以及預覽是否跟隨 Obsidian 主題。",
EMBED_IMAGE_CACHE_NAME: "為嵌入到 Markdown 文件中的繪圖建立預覽圖快取",
EMBED_IMAGE_CACHE_DESC:
"可提高下次嵌入的速度。" +
@@ -1040,7 +1137,18 @@ export default {
"在匯出圖片中嵌入 Excalidraw 場景。可以在其 frontmatter 中新增如 <code>excalidraw-export-embed-scene: true/false</code> 的鍵值對來覆蓋該項。" +
"該項僅在您下次(重新)開啟繪圖時生效。",
PDF_EXPORT_SETTINGS: "PDF 匯出設定",
PDF_EXPORT_SETTINGS_DESC:
"選擇預設 PDF 頁面大小、方向、分頁、邊距、紙張顏色和對齊方式。",
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "預設 PDF 匯出配置",
EXPORT_HEAD: "匯出設定",
EXPORT_AUTOEXPORT_DESC:
"保持匯出檔案同步,並自動建立 SVG、PNG、淺色和深色版本。",
SETTINGS_NAVIGATION_OPEN: "開啟",
SETTINGS_BREADCRUMB_ARIA: "設定路徑",
SETTINGS_RELATED_AUTOEXPORT_DESC:
"啟用自動 PNG 或 SVG 副本,使這些格式可在插入檔案類型下拉清單中選擇。",
SETTINGS_RELATED_EMBED_TYPE_DESC:
"選擇在文件中嵌入繪圖時插入 Excalidraw、PNG 還是 SVG。",
EXPORT_SYNC_NAME: "保持 SVG/PNG 檔名與繪圖檔案同步",
EXPORT_SYNC_DESC:
"開啟後,當繪圖檔案被重新命名時,外掛將同步更新同文件夾下的同名 .SVG 和 .PNG 檔案。" +
@@ -1113,8 +1221,11 @@ export default {
CUSTOM_PEN_DESC:
"在繪圖上的 Obsidian 選單按鈕旁邊切換自定義畫筆。長按(雙擊)畫筆按鈕可以修改其樣式。",
EXPERIMENTAL_HEAD: "雜項",
EXPERIMENTAL_DESC: `包括:預設的 LaTeX 公式,欄位建議,繪圖檔案的型別識別符號,OCR 等。`,
EXPERIMENTAL_DESC:
"設定 LaTeX 預設值、檔案類型標記、即時預覽行為、屬性建議,以及實驗性的 Taskbone OCR 整合。",
EA_HEAD: "Excalidraw 自動化",
EA_GROUP_DESC:
"設定 Excalidraw Automate 指令碼、啟動與自動啟動行為、命令連結,以及已安裝指令碼提供的設定。",
EA_DESC:
`ExcalidrawAutomate 是用於 Excalidraw 自動化指令碼的 API,但是目前說明文件還不夠完善,` +
`建議閱讀 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> 檔案原始碼,` +
@@ -1125,6 +1236,33 @@ export default {
FIELD_SUGGESTER_DESC:
"開啟後,當您在編輯器中輸入 <code>excalidraw-</code> 或者 <code>ea.</code> 時,會彈出一個帶有函式說明的自動補全提示選單。<br>" +
"該功能借鑑了 Breadcrumbs 和 Templater 外掛。",
ALLOW_JS_FILES_NAME: "從 Scripts 資料夾載入 JavaScript 檔案",
ALLOW_JS_FILES_DESC:
"啟用後,Excalidraw Automate 會監視並執行 Scripts 資料夾中的 <code>.js</code> 檔案,也允許使用 <code>.js</code> 啟動指令碼。" +
"預設情況下,Obsidian Sync 不會同步非 Markdown 檔案,Obsidian 不會開啟 <code>.js</code> 檔案進行編輯,檔案總管也會隱藏它們。需要時請在 Obsidian 中啟用<b>同步所有其他檔案類型</b>和<b>顯示所有檔案類型</b>。如果存在同名的 <code>.md</code> 和 <code>.js</code> 指令碼,將使用 Markdown 檔案。",
STORE_SCRIPTS_AS_JS_NAME: "將下載的指令碼儲存為",
STORE_SCRIPTS_AS_JS_DESC:
"選擇指令碼庫新下載與更新在本機使用的檔案類型。無論遠端來源是 <code>.md</code> 或 <code>.js</code>,都會使用此設定。",
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
MIGRATE_SCRIPT_FILES_NAME: "遷移現有指令碼檔案",
MIGRATE_SCRIPTS_TO_JS_BUTTON: "將現有指令碼遷移為 .js",
MIGRATE_SCRIPTS_TO_MD_BUTTON: "將現有指令碼遷移為 .md",
MIGRATE_SCRIPT_FILES_STATUS:
"有 {eligible} 個指令碼檔案可遷移為 {extension}。{skipped}",
MIGRATE_SCRIPT_FILES_CONFIRM:
"繼續前請先備份儲存庫。<br><br><b>{count}</b> 個指令碼檔案將重新命名為 <code>{extension}</code>,釘選指令碼的路徑也會更新。{startup} {skipped}",
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
"已設定的啟動指令碼及其設定也會更新。",
MIGRATE_SCRIPT_FILES_SKIPPED:
"有 {count} 對同名 .md/.js 檔案不會被遷移。",
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
"因目標檔案已存在,已略過 {count} 個指令碼檔案:\n{files}",
MIGRATE_SCRIPT_FILES_NONE: "找不到可遷移的指令碼檔案。",
MIGRATE_SCRIPT_FILES_COMPLETE:
"已將 {count} 個指令碼檔案遷移為 {extension}。",
MIGRATE_SCRIPT_FILES_FAILED:
"無法遷移指令碼檔案。已盡可能回復完成的重新命名。",
ENABLE_ONLOAD_SCRIPTS_NAME: "載入期指令碼(onload)",
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
"此檔案包含 <code>excalidraw-onload-script</code>。是否啟用載入期指令碼?",
@@ -1137,7 +1275,7 @@ export default {
AUTOSTART_SCRIPT_PROMPT:
"希望在你每次開啟 Excalidraw 繪圖時自動執行。是否允許?",
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
"你之後可以在命令選擇區(「自動啟動指令碼」)或設定 → 相容性 → 自動啟動指令碼中變更此設定。",
"你之後可以在命令選擇區(「自動啟動指令碼」)或設定 → Excalidraw 自動化 → 自動啟動指令碼中變更此設定。",
AUTOSTART_SCRIPT_ALLOW: "自動啟動",
AUTOSTART_SCRIPT_DENY: "僅手動啟動",
AUTOSTART_SCRIPT_ASK_LATER: "每次都詢問",
@@ -1156,9 +1294,10 @@ export default {
"如果你開啟未知來源的繪圖,這會帶來風險:惡意繪圖可以讓一次普通點選觸發高許可權命令。" +
"只有在你信任該檔案及其來源時才啟用此功能。",
STARTUP_SCRIPT_NAME: "啟動期指令碼(startup)",
STARTUP_SCRIPT_JS_DISABLED:
"JavaScript 啟動指令碼已停用。請先在 Excalidraw Automate 設定中啟用 JavaScript 檔案。",
STARTUP_SCRIPT_DESC:
"外掛啟動時將自動執行該指令碼。可用於設定 Excalidraw 自動化鉤子。" +
"該指令碼是包含 javascript 程式碼的 Markdown 檔案。",
"外掛啟動時將自動執行該指令碼,可用於設定 Excalidraw Automate 鉤子。沒有副檔名的路徑使用 Markdown 檔案;啟用 JavaScript 檔案載入後可使用 <code>.js</code> 檔案。",
STARTUP_SCRIPT_BUTTON_CREATE: "建立啟動期指令碼",
STARTUP_SCRIPT_BUTTON_OPEN: "開啟啟動期指令碼",
FILETYPE_NAME: "在檔案瀏覽器中為 excalidraw.md 檔案新增型別識別符號(如 ✏️)",
@@ -1199,6 +1338,8 @@ export default {
"為了獲得最佳效能,建議使用 .woff2 檔案,因為當匯出 SVG 格式的圖片時,Excalidraw 只會編碼必要的字形。" +
`其他字型格式將在匯出檔案中嵌入整個字型,可能會導致檔案大小顯著增加。<b>譯者注:</b>可在 <a href="${URLs.WANGCHUJIANG_COM_FREE_FONT}" target='_blank'>Free Font</a> 獲取免費商用中文手寫字型。`,
OFFLINE_CJK_NAME: "離線 CJK 字型支援",
OFFLINE_CJK_GROUP_DESC:
"下載並按需預先載入中文、日文和韓文字型,讓 Excalidraw 在沒有網際網路連線時也能顯示這些字型。",
OFFLINE_CJK_DESC: `<strong>該項需要重啟 Obsidian 才能生效。</strong><br>
Excalidraw.com 提供手寫風格的 CJK 字型。預設情況下,這些字型不會包含在外掛本地,而是從網際網路獲取。
如果您希望 Excalidraw 完全本地化,以便在沒有網際網路連線的情況下使用,可以從 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">GitHub 下載所需的字型檔案</a>。
@@ -1215,6 +1356,8 @@ export default {
SCRIPT_SETTINGS_DESC:
"有些 Excalidraw 自動化指令碼包含設定項,當執行這些指令碼時,它們會在該列表下新增設定項。",
TASKBONE_HEAD: "Taskbone OCR(光學符號識別)",
TASKBONE_GROUP_DESC:
"設定選用的 Taskbone 線上 OCR 服務,從繪圖與影像中擷取可搜尋文字。",
TASKBONE_DESC:
"這是一個將 OCR 融入 Excalidraw 的實驗性功能。請注意,Taskbone 是一項獨立的外部服務,而不是由 Excalidraw 或 obsidian-excalidraw-plugin 專案提供的。" +
"OCR 能夠對繪圖上用自由畫筆工具寫下的塗鴉或者嵌入的影像進行文字識別,並將識別出來的文字寫入繪圖檔案的 frontmatter,同時複製到剪貼簿。" +
+165
View File
@@ -0,0 +1,165 @@
type PendingBackup = {
data: string;
};
type BackupWriteState = {
timer: number | null;
inFlight: Promise<void> | null;
pending: PendingBackup | null;
};
type BackupPersistenceQueueOptions = {
ownerWindow: Window;
write: (filepath: string, data: string) => Promise<void>;
onError?: (error: unknown, stage: "write") => void;
};
/**
* Coalesces plugin-global drawing backups by vault path.
*
* @remarks
* Each path owns at most one IndexedDB write and one latest trailing payload.
* The timer belongs to the main application window because persistent plugin
* storage is shared by main and popout views.
*/
export class BackupPersistenceQueue {
private readonly ownerWindow: Window;
private readonly write: BackupPersistenceQueueOptions["write"];
private readonly onError?: BackupPersistenceQueueOptions["onError"];
private readonly writes = new Map<string, BackupWriteState>();
constructor(options: BackupPersistenceQueueOptions) {
this.ownerWindow = options.ownerWindow;
this.write = options.write;
this.onError = options.onError;
}
/**
* Schedules the latest payload for a path.
*
* @returns `true` when an older pending payload was replaced or the new
* payload was coalesced behind an active write.
*/
public schedule(filepath: string, data: string, delayMs: number): boolean {
let state = this.writes.get(filepath);
if (!state) {
state = { timer: null, inFlight: null, pending: null };
this.writes.set(filepath, state);
}
const coalesced = state.pending !== null || state.inFlight !== null;
state.pending = { data };
this.clearTimer(state);
if (state.inFlight === null) {
this.scheduleDrain(filepath, state, delayMs);
}
return coalesced;
}
/** Writes all currently pending data for one path without the normal delay. */
public async flush(filepath: string): Promise<void> {
const state = this.writes.get(filepath);
if (!state) {
return;
}
this.clearTimer(state);
while (this.writes.get(filepath) === state) {
this.clearTimer(state);
if (state.inFlight !== null) {
try {
await state.inFlight;
} catch {
// The owning drain reports the write failure and releases state.
}
continue;
}
if (state.pending === null) {
break;
}
await this.drain(filepath, state, 0);
}
}
/** Cancels queued data and waits for an already-active write to settle. */
public async cancel(filepath: string): Promise<void> {
const state = this.writes.get(filepath);
if (!state) {
return;
}
this.clearTimer(state);
state.pending = null;
this.writes.delete(filepath);
if (state.inFlight !== null) {
try {
await state.inFlight;
} catch {
// The owning drain reports the write failure; cancellation still wins.
}
}
}
/** Cancels every queued backup before the backup store is cleared. */
public async cancelAll(): Promise<void> {
await Promise.all(
Array.from(this.writes.keys(), (filepath) => this.cancel(filepath)),
);
}
/** Drops timers and references during plugin unload without starting writes. */
public destroy(): void {
this.writes.forEach((state) => this.clearTimer(state));
this.writes.clear();
}
private clearTimer(state: BackupWriteState): void {
if (state.timer !== null) {
this.ownerWindow.clearTimeout(state.timer);
state.timer = null;
}
}
private scheduleDrain(
filepath: string,
state: BackupWriteState,
delayMs: number,
): void {
state.timer = this.ownerWindow.setTimeout(() => {
state.timer = null;
void this.drain(filepath, state, delayMs);
}, delayMs);
}
private async drain(
filepath: string,
state: BackupWriteState,
trailingDelayMs: number,
): Promise<void> {
if (
this.writes.get(filepath) !== state ||
state.inFlight !== null ||
state.pending === null
) {
return;
}
const pending = state.pending;
state.pending = null;
const write = this.write(filepath, pending.data);
state.inFlight = write;
try {
await write;
} catch (error: unknown) {
this.onError?.(error, "write");
} finally {
if (this.writes.get(filepath) === state) {
state.inFlight = null;
if (state.pending !== null) {
this.scheduleDrain(filepath, state, trailingDelayMs);
} else {
this.writes.delete(filepath);
}
}
}
}
}
@@ -53,6 +53,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.setValue(this.mdCustomData.filenameVisible)
.onChange((value) => {
this.mdCustomData.filenameVisible = value;
this.update();
}),
);
@@ -72,6 +73,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.setValue(this.mdCustomData.propertiesVisible ?? true)
.onChange((value) => {
this.mdCustomData.propertiesVisible = value;
this.update();
});
if (!this.isFullFile || isGlobalHidden) {
toggle.setDisabled(true);
@@ -91,6 +93,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.setValue(!!this.mdCustomData.lockedReadingMode)
.onChange((value) => {
this.mdCustomData.lockedReadingMode = value;
this.update();
}),
);
}
@@ -120,6 +123,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
if (value) {
hideElement(bgSetting.settingEl);
if (this.mdCustomData.backgroundMatchCanvas) {
this.mdCustomData.backgroundMatchCanvas = false;
bgMatchCanvasToggle.setValue(false);
}
} else if (!this.mdCustomData.backgroundMatchCanvas) {
@@ -140,6 +144,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
if (value) {
hideElement(bgSetting.settingEl);
if (this.mdCustomData.backgroundMatchElement) {
this.mdCustomData.backgroundMatchElement = false;
bgMatchElementToggle.setValue(false);
}
} else if (!this.mdCustomData.backgroundMatchElement) {
+38 -18
View File
@@ -18,33 +18,53 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.27.0": `
## Maintenance
- Refactoring the plugin. Removed unused functions, improved code structure and readability. Removed the obsolete Draw.io/Diagram plugin integration (since the other plugin no longer works and is not maintained) and retired the Create DrawIO file script from the script library.
- Migrated the embedded Excalidraw runtime from the retired UMD build path to a dedicated ESM-source-based Obsidian package while preserving offline operation, popout windows, and runtime Mermaid loading through Excalidraw Extras. The Assistant UI font is now bundled instead of fetched from the internet, and the plugin-private React runtime is generated from the official npm package entrypoints instead of legacy UMD files.
- Updated the plugin-private React and ReactDOM runtime to React 19.
- Improved loading performance for drawings with many cached embedded files by avoiding large cache rewrites, SVG reconstruction, unnecessary image measurement and hashing, premature cache-read timeouts, and duplicate SVG normalization when cached drawings are handed to the canvas. Cached and direct images now appear before uncached generated drawings. The disposable image cache is rebuilt once after updating; drawing backups are preserved.
## Fixed
- The Excalidraw color palette now uses its natural height when space is available instead of being unnecessarily limited to a short, vertically scrolling panel. Its native color control also remains aligned with the hex input.
- The text-to-diagram chat history menu is visible again, allowing saved chats to be restored and deleted.
- Stencil library is persisted with tab-indented JSON to support Git diffs. [#2883](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2883)
- Custom color-picker top picks (pinned by dragging a color onto the strip) are now saved with the drawing instead of being forgotten on reload.
- Changing the canvas background color from the color-picker popover no longer leaves the popover's own theming out of sync until it's closed and reopened.
## New
- On Obsidian 1.13 and newer, Excalidraw now uses Obsidian's searchable, multi-page settings. Settings are organized into clearer sections with breadcrumbs, compact help links, and clickable links between related options.
- Prefer the previous experience? Turn off **Use searchable settings** at the top of Excalidraw settings and restart Obsidian. Older Obsidian versions continue using the legacy single-page layout automatically.
- Settings exposed by installed Excalidraw Automate scripts have moved to **Excalidraw Automate → Settings for installed scripts** and update when a script adds or changes its settings.
- Excalidraw Automate can optionally load and monitor JavaScript (\`.js\`) files in the Scripts folder, use an explicit \`.js\` startup script, and store Script Library downloads as either Markdown or JavaScript. Existing scripts can be moved between the two formats while updating startup and pinned-script paths. [#2901](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2901)
- Markdown notes created from unresolved links in a drawing now follow Obsidian's **Default location for new notes** setting. [#2916](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2916)
## New from Excalidraw.com
- Improved bucket tool and eyedropper support [#11849](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11849)
- Respect box selection mode ('contain' vs 'overlap') in lasso selection [#11862](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11862)
- Color-picker top picks can now be customized by dragging a color from the palette onto the strip; right-click the strip to reset [#11872](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11872)
- Improved bucket tool and eyedropper support. [#11849](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11849)
- Lasso selection now respects box selection mode: contain or overlap. [#11862](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11862)
- Customize color-picker top picks by dragging colors onto the strip; right-click the strip to reset it. [#11872](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11872)
## Fixed
- Moving a dirty drawing out of a popout window now safely transfers and persists its latest edits from the replacement main-window view.
- Opening the command palette or another Obsidian modal reliably saves dirty drawings, while inline link suggestions no longer trigger a save that can end text editing.
- Converting a legacy ".excalidraw" drawing now persists its embedded images as vault attachments during conversion, before the source file can be removed. [#2898](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2898)
- Entering text editing no longer scans and sorts the entire vault for link suggestions; file-link candidates are loaded only after typing \`[[\`. [#2907](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2907)
- Settings changes are saved promptly without collapsing sections or interrupting fast typing. Writes are serialized, and Excalidraw keeps a device-local recovery copy so an empty or corrupted synchronized **data.json** cannot silently erase a large settings configuration.
- Interdependent settings now initialize and refresh consistently, including TODO icons, auto-export formats, Taskbone credentials, filename previews, and custom grid colors. Built-in font previews also use the correct typeface in secondary Obsidian windows.
- Applying a rendering-related setting no longer resets the live zoom and scroll position of an open drawing. New configurations use ☑ as the completed-TODO marker.
- Interactive Markdown embed defaults now save filename, properties, locked-reading-mode, and background-source changes reliably.
- The color palette uses the available height, keeps its native picker aligned, remembers customized top picks after reload, and updates popover theming immediately after a canvas background change.
- Text-to-diagram chat history is visible again, so saved chats can be restored or deleted.
- Stencil-library JSON is now tab-indented for cleaner Git diffs. [#2883](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2883)
## Maintenance
- This is one of the Plugin's largest internal maintenance releases. The settings system, persistence pipeline, plugin lifecycle, runtime packaging, and several major managers were reorganized into clearer, independently maintained components. The visible workflow remains familiar, but the foundation is substantially safer for future features and fixes.
- The embedded Excalidraw runtime now uses a modern ESM-source build and React 19 instead of the retired UMD pipeline. Offline use and popout windows remain supported; the Assistant UI font is bundled locally and Mermaid still loads on demand through Excalidraw Extras.
- Drawings with many cached embedded files load more efficiently by avoiding redundant cache rewrites, SVG reconstruction, image measurement, hashing, and normalization. Cached and direct images can appear before slower generated drawings, while drawing backups remain protected.
- Removed unused code and the obsolete Draw.io/Diagram integration, and retired the non-functional Create DrawIO file script.
## New in Excalidraw Automate
- Scripts can now register custom buttons in the selected-element context menu (the small toolbar shown above a selected element):
- \`setView(null)\` now explicitly clears \`ea.targetView\`. Use \`setView()\` or \`setView("auto")\` when you want EA to select a sensible default drawing.
- Scripts can register custom buttons in the selected-element context menu:
\`\`\`ts
registerElementActionProvider(getActions: (element: ExcalidrawElement) => readonly {id: string, title: string, icon: string, action: () => void}[]): (() => void) | null;
\`\`\`
- Scripts can now ask to be automatically re-run every time a new Excalidraw view is opened, with a user-confirmed Allow/Deny/Ask-me-later prompt; a fresh Allow also attaches the script to every other currently-open view immediately. Manage which scripts are allowed to autostart from the "Autostart scripts" command or the Compatibility settings section:
- Scripts can request permission to run automatically whenever an Excalidraw view opens. Manage permissions with the **Autostart scripts** command or under Excalidraw Automate settings:
\`\`\`ts
registerAutostart(): Promise<"allow" | "deny" | "pending">;
registerAutostart(message?: string): Promise<"allow" | "deny" | "pending">;
\`\`\`
- Pass an optional message to explain what the script does during autostart. It appears between the permission question and the settings hint.
- Scripts can release listeners, timers, observers, and other external resources with EA-owned cleanup:
\`\`\`ts
registerCleanup(cleanup: () => void): () => void;
\`\`\`
- Scripts can distinguish \`manual\`, \`plugin-startup\`, \`view-autostart\`, \`sidepanel-restore\`, \`sidepanel-reload\`, and \`drawing-onload\` execution through \`utils.executionSource\`. Compilation caching is transparent and does not retain script runtime state.
`,
"2.26.4": `
## Fixed
+115 -94
View File
@@ -8,17 +8,26 @@ import {
} from "src/utils/modifierkeyHelper";
import { setStyle } from "src/utils/styleUtils";
type ModifierKeyCategories = Partial<{
[modifierSetType in ModifierSetType]: string;
}>;
const CATEGORIES: ModifierKeyCategories = {
const CATEGORIES: Record<ModifierSetType, string> = {
WebBrowserDragAction: t("WEB_BROWSER_DRAG_ACTION"),
LocalFileDragAction: t("LOCAL_FILE_DRAG_ACTION"),
InternalDragAction: t("INTERNAL_DRAG_ACTION"),
LinkClickAction: t("PANE_TARGET"),
};
/** Modifier-key categories rendered by the settings component. */
export const MODIFIER_KEY_CATEGORIES = [
"WebBrowserDragAction",
"LocalFileDragAction",
"InternalDragAction",
"LinkClickAction",
] as const satisfies readonly ModifierSetType[];
/** Returns the localized heading for one modifier-key category. */
export const getModifierKeyCategoryName = (
modifierSetType: ModifierSetType,
): string => CATEGORIES[modifierSetType];
export class ModifierKeySettingsComponent {
private isMacOS: boolean;
@@ -28,12 +37,22 @@ export class ModifierKeySettingsComponent {
Mac: Record<string, ModifierKeySet>;
Win: Record<string, ModifierKeySet>;
},
private update?: () => void,
private update: () => void,
) {
this.isMacOS = DEVICE.isMacOS || DEVICE.isIOS;
}
render() {
render(): void {
MODIFIER_KEY_CATEGORIES.forEach((modifierSetType) =>
this.renderCategory(modifierSetType, true),
);
}
/** Renders one modifier-key category, optionally with its legacy fold. */
renderCategory(
modifierSetType: ModifierSetType,
includeSummary: boolean,
): void {
const platform = this.isMacOS ? "Mac" : "Win";
const modifierKeysConfig = this.modifierKeyConfig[platform];
const tooltipMessages = modifierKeyTooltipMessages() as Record<
@@ -41,102 +60,104 @@ export class ModifierKeySettingsComponent {
Record<string, string>
>;
Object.entries(CATEGORIES).forEach(([modifierSetType, label]) => {
const detailsEl = this.contentEl.createEl("details");
const detailsEl = includeSummary
? this.contentEl.createEl("details")
: this.contentEl;
if (includeSummary) {
detailsEl.createEl("summary", {
text: label,
text: getModifierKeyCategoryName(modifierSetType),
cls: "excalidraw-setting-h4",
});
}
const modifierKeys = modifierKeysConfig[modifierSetType];
detailsEl.createDiv({
text:
t("DEFAULT_ACTION_DESC") +
(tooltipMessages[modifierSetType]?.[modifierKeys.defaultAction] ??
""),
cls: "setting-item-description",
});
// Ensure all LinkClickAction rules have ctrl_cmd enabled
if (modifierSetType === "LinkClickAction") {
let dirty = false;
modifierKeys.rules.forEach((rule) => {
if (!rule.ctrl_cmd) {
rule.ctrl_cmd = true;
dirty = true;
}
});
if (dirty) {
this.update?.();
const modifierKeys = modifierKeysConfig[modifierSetType];
detailsEl.createDiv({
text:
t("DEFAULT_ACTION_DESC") +
(tooltipMessages[modifierSetType]?.[modifierKeys.defaultAction] ??
""),
cls: "setting-item-description",
});
// Ensure all LinkClickAction rules have ctrl_cmd enabled
if (modifierSetType === "LinkClickAction") {
let dirty = false;
modifierKeys.rules.forEach((rule) => {
if (!rule.ctrl_cmd) {
rule.ctrl_cmd = true;
dirty = true;
}
});
if (dirty) {
this.update();
}
}
// Column header row
const headerSetting = new Setting(detailsEl);
headerSetting.settingEl.addClass("modifier-key-header-row");
headerSetting.infoEl.remove();
[
"SHIFT",
this.isMacOS ? "CMD" : "CTRL",
this.isMacOS ? "OPT" : "ALT",
this.isMacOS ? "CTRL" : "META",
].forEach((key) => {
headerSetting.controlEl.createSpan({
text: key,
cls: "modifier-key-col-header",
});
// Column header row
const headerSetting = new Setting(detailsEl);
headerSetting.settingEl.addClass("modifier-key-header-row");
headerSetting.infoEl.remove();
[
"SHIFT",
this.isMacOS ? "CMD" : "CTRL",
this.isMacOS ? "OPT" : "ALT",
this.isMacOS ? "CTRL" : "META",
].forEach((key) => {
headerSetting.controlEl.createSpan({
text: key,
cls: "modifier-key-col-header",
});
});
modifierKeys.rules.forEach((rule) => {
const setting = new Setting(detailsEl).setName(
tooltipMessages[modifierSetType]?.[rule.result],
);
setting.addToggle((toggle) =>
toggle
.setValue(rule.shift)
.setTooltip("SHIFT")
.onChange((value) => {
rule.shift = value;
this.update();
}),
);
setting.addToggle((toggle) => {
const isLinkClick = modifierSetType === "LinkClickAction";
toggle
.setValue(isLinkClick ? true : rule.ctrl_cmd)
.setTooltip(this.isMacOS ? "CMD" : "CTRL")
.onChange((value) => {
rule.ctrl_cmd = value;
this.update();
});
if (isLinkClick || this.isMacOS) {
// CMD is always required for link-click actions (Excalidraw detects
// the click via CMD being held). On macOS, CMD is also reserved for
// non-link-click actions.
toggle.setDisabled(true);
setStyle(toggle.toggleEl, { opacity: "0.5" });
}
});
Object.entries(modifierKeys.rules).forEach(([_, rule]) => {
const setting = new Setting(detailsEl).setName(
tooltipMessages[modifierSetType]?.[rule.result],
);
setting.addToggle((toggle) =>
toggle
.setValue(rule.shift)
.setTooltip("SHIFT")
.onChange((value) => {
rule.shift = value;
this.update();
}),
);
setting.addToggle((toggle) => {
const isLinkClick = modifierSetType === "LinkClickAction";
toggle
.setValue(isLinkClick ? true : rule.ctrl_cmd)
.setTooltip(this.isMacOS ? "CMD" : "CTRL")
.onChange((value) => {
rule.ctrl_cmd = value;
this.update();
});
if (isLinkClick || this.isMacOS) {
// CMD is always required for link-click actions (Excalidraw detects
// the click via CMD being held). On macOS, CMD is also reserved for
// non-link-click actions.
toggle.setDisabled(true);
setStyle(toggle.toggleEl, { opacity: "0.5" });
}
});
setting.addToggle((toggle) =>
toggle
.setValue(rule.alt_opt)
.setTooltip(this.isMacOS ? "OPT" : "ALT")
.onChange((value) => {
rule.alt_opt = value;
this.update();
}),
);
setting.addToggle((toggle) =>
toggle
.setValue(rule.meta_ctrl)
.setTooltip(this.isMacOS ? "CTRL" : "META")
.onChange((value) => {
rule.meta_ctrl = value;
this.update();
}),
);
});
setting.addToggle((toggle) =>
toggle
.setValue(rule.alt_opt)
.setTooltip(this.isMacOS ? "OPT" : "ALT")
.onChange((value) => {
rule.alt_opt = value;
this.update();
}),
);
setting.addToggle((toggle) =>
toggle
.setValue(rule.meta_ctrl)
.setTooltip(this.isMacOS ? "CTRL" : "META")
.onChange((value) => {
rule.meta_ctrl = value;
this.update();
}),
);
});
}
}
+45 -10
View File
@@ -5,6 +5,7 @@ import {
FuzzyMatch,
FuzzySuggestModal,
Instruction,
normalizePath,
TFile,
Notice,
TextAreaComponent,
@@ -1096,6 +1097,7 @@ export class NewFileActions extends Modal {
private openNewFile: boolean;
private parentFile: TFile;
private sourceElement: ExcalidrawElement;
private followObsidianNewNoteLocation: boolean;
constructor({
plugin,
@@ -1105,6 +1107,7 @@ export class NewFileActions extends Modal {
openNewFile = true,
parentFile,
sourceElement,
followObsidianNewNoteLocation = false,
}: {
plugin: ExcalidrawPlugin;
path: string;
@@ -1113,6 +1116,7 @@ export class NewFileActions extends Modal {
openNewFile?: boolean;
parentFile?: TFile;
sourceElement?: ExcalidrawElement;
followObsidianNewNoteLocation?: boolean;
}) {
super(plugin.app);
this.plugin = plugin;
@@ -1122,6 +1126,7 @@ export class NewFileActions extends Modal {
this.openNewFile = openNewFile;
this.sourceElement = sourceElement;
this.parentFile = parentFile ?? view.file;
this.followObsidianNewNoteLocation = followObsidianNewNoteLocation;
this.waitForClose = new Promise<TFile | null>((resolve, reject) => {
this.resolvePromise = resolve;
this.rejectPromise = reject;
@@ -1183,15 +1188,42 @@ export class NewFileActions extends Modal {
return true;
};
const createFile = async (data: string): Promise<TFile> => {
if (!this.path.includes("/")) {
const re = new RegExp(`${escapeRegExp(this.parentFile.name)}$`, "g");
this.path = this.parentFile.path.replace(re, this.path);
const createFile = async (
data: string,
useObsidianNewNoteLocation: boolean,
): Promise<TFile> => {
let path = this.path;
if (!path.match(/\.md$/)) {
path = `${path}.md`;
}
if (!this.path.match(/\.md$/)) {
this.path = `${this.path}.md`;
if (!path.includes("/")) {
if (
useObsidianNewNoteLocation &&
this.followObsidianNewNoteLocation
) {
const newFileLocation = this.app.vault.getConfig("newFileLocation");
let targetFolder = this.parentFile.parent?.path ?? "";
if (newFileLocation === "root") {
targetFolder = "";
} else if (newFileLocation === "folder") {
const configuredFolder = this.app.vault.getConfig(
"newFileFolderPath",
);
targetFolder =
typeof configuredFolder === "string" ? configuredFolder : "";
}
path = normalizePath(
targetFolder ? `${targetFolder}/${path}` : path,
);
} else {
const re = new RegExp(
`${escapeRegExp(this.parentFile.name)}$`,
"g",
);
path = this.parentFile.path.replace(re, path);
}
}
return await createOrOverwriteFile(this.app, this.path, data);
return await createOrOverwriteFile(this.app, path, data);
};
if (this.sourceElement) {
@@ -1203,7 +1235,7 @@ export class NewFileActions extends Modal {
if (!checks) {
return;
}
const f = await createFile("");
const f = await createFile("", true);
if (f) {
const ea: ExcalidrawAutomate = getEA(this.view);
ea.copyViewElementsToEAforEditing([this.sourceElement]);
@@ -1231,7 +1263,7 @@ export class NewFileActions extends Modal {
if (!checks) {
return;
}
const f = await createFile("");
const f = await createFile("", true);
this.openFile(f);
this.close();
};
@@ -1244,7 +1276,10 @@ export class NewFileActions extends Modal {
if (!checks) {
return;
}
const f = await createFile(await this.plugin.getBlankDrawing());
const f = await createFile(
await this.plugin.getBlankDrawing(),
false,
);
await sleep(200); //wait for metadata cache to update, so file opens as excalidraw
this.openFile(f);
this.close();
@@ -0,0 +1,85 @@
import { type App, Modal, Setting } from "obsidian";
import { t } from "src/lang/helpers";
export type SettingsRecoveryChoice =
| "restore-recovery"
| "reset-defaults"
| "wait-for-file";
export type SettingsRecoveryPromptMode =
| "missing-with-recovery"
| "invalid-without-recovery";
/** Resolves ambiguous startup settings loss without silently choosing for the user. */
export class SettingsRecoveryPrompt extends Modal {
private resolvePromise: (choice: SettingsRecoveryChoice) => void;
private choice: SettingsRecoveryChoice;
public constructor(
app: App,
private readonly mode: SettingsRecoveryPromptMode,
) {
super(app);
this.choice =
mode === "missing-with-recovery"
? "restore-recovery"
: "wait-for-file";
}
/** Opens the prompt and resolves after the user chooses or closes it. */
public start(): Promise<SettingsRecoveryChoice> {
const result = new Promise<SettingsRecoveryChoice>((resolve) => {
this.resolvePromise = resolve;
});
this.open();
return result;
}
public onOpen(): void {
const hasRecovery = this.mode === "missing-with-recovery";
this.titleEl.setText(
t(
hasRecovery
? "SETTINGS_RECOVERY_MISSING_TITLE"
: "SETTINGS_RECOVERY_CORRUPT_TITLE",
),
);
this.contentEl.createEl("p", {
text: t(
hasRecovery
? "SETTINGS_RECOVERY_MISSING_DESC"
: "SETTINGS_RECOVERY_CORRUPT_DESC",
),
});
const buttons = new Setting(this.contentEl);
buttons.addButton((button) =>
button
.setButtonText(t("SETTINGS_RECOVERY_RESET_DEFAULTS"))
.onClick(() => {
this.choice = "reset-defaults";
this.close();
}),
);
buttons.addButton((button) =>
button
.setCta()
.setButtonText(
t(
hasRecovery
? "SETTINGS_RECOVERY_RESTORE_BACKUP"
: "SETTINGS_RECOVERY_WAIT_FOR_FILE",
),
)
.onClick(() => {
this.choice = hasRecovery ? "restore-recovery" : "wait-for-file";
this.close();
}),
);
}
public onClose(): void {
this.contentEl.empty();
this.resolvePromise?.(this.choice);
}
}
+34 -10
View File
@@ -287,7 +287,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "createViewSVG",
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean}): Promise<SVGSVGElement>",
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean, elementsOverride?: readonly ExcalidrawElement[]}): Promise<SVGSVGElement>",
desc:
"Creates an SVG representation of the current view with specified options.\n" +
"\n" +
@@ -299,6 +299,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"@param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.\n" +
"@param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.\n" +
"@param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.\n" +
"@param {readonly ExcalidrawElement[]} [options.elementsOverride] - Complete replacement for the exported elements. It is not merged with the current scene or treated as a patch by ID. Include every element that should appear in the SVG.\n" +
"@returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.\n" +
"\n" +
"@typedef {Object} FrameRenderingOptions\n" +
@@ -315,6 +316,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
" selectedOnly: false,\n" +
" skipInliningFonts: false,\n" +
" embedScene: false,\n" +
" // elementsOverride: ea.getElements(), // Must contain the complete export set.\n" +
"});",
},
{
@@ -506,24 +508,25 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "targetView",
code: "targetView: ExcalidrawView;",
desc: "The Obsidian view currently edited",
code: "targetView: ExcalidrawView | null;",
desc: "The targeted Obsidian Excalidraw view, or null when EA is unbound",
after: "",
},
{
field: "setView",
code: 'setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show: boolean = false): ExcalidrawView;',
code: 'setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show: boolean = false): ExcalidrawView | null;',
desc:
"Sets the target view for EA. All the view operations and the access to Excalidraw API will be performed on this view. " +
"Typically you will use setView() (to pick a sensible default) or setView(excalidrawView) (to explicitly target a specific view).\n" +
"Typically you will use setView() (to pick a sensible default), setView(excalidrawView) (to explicitly target a specific view), or setView(null) (to explicitly clear targetView).\n" +
'"auto" is equivalent to calling setView() and can read nicer when you want to show the view (e.g. setView("auto", true)).\n' +
'"active" and "first" are deprecated and are kept for backward compatibility.\n' +
'If view is null or undefined (or "auto"), EA will pick a sensible default: first the currently active Excalidraw view (if any), otherwise the last active Excalidraw view (if it is still available), otherwise the "first" Excalidraw view in the workspace.\n' +
'If view is undefined (or "auto"), EA will pick a sensible default: first the currently active Excalidraw view (if any), otherwise the last active Excalidraw view (if it is still available), otherwise the "first" Excalidraw view in the workspace.\n' +
"If view is explicitly null, EA clears targetView. This is useful when a sidepanel becomes unbound because focus moved to a Markdown view or no drawing is eligible.\n" +
"If show is true, the view will be brought to front and focused.\n" +
'If "first" is provided, the target will be the first Excalidraw view returned by Obsidian\'s workspace leaf collection (i.e., the first item in getExcalidrawViews()). ' +
"This ordering is managed by Obsidian and does not necessarily match what a user would consider the “first” view; from a user's perspective it may appear random.\n" +
'If "active" is provided, the currently active Excalidraw view in the workspace will be used. If that is not available, then the last active Excalidraw view will be used.\n' +
"The function returns the ExcalidrawView that was set as targetView.",
"The function returns the ExcalidrawView that was set as targetView, or null when cleared or no view was found.",
after: '("auto",true);',
},
{
@@ -996,6 +999,16 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"In case the script wants to replace the sidepanel tab it created earlier, call closeSidepanelTab() first, then createSidepanelTab() again.",
after: "",
},
{
field: "registerCleanup",
code: "registerCleanup(cleanup: () => void): () => void;",
desc:
"Registers synchronous cleanup owned by this ExcalidrawAutomate instance. " +
"Use it for external Obsidian or DOM listeners, observers, timers, and subscriptions. " +
"The callback runs when this EA is destroyed; the returned function unregisters it without running it. " +
"The exact lifetime depends on the lifecycle that created the EA.",
after: "(() => releaseExternalResource());",
},
{
field: "registerElementActionProvider",
code:
@@ -1003,6 +1016,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc:
"Registers custom action buttons in the selected-element context menu (the small toolbar shown above a single selected element). " +
"getActions is called with the selected element whenever the selection, element type, fileId, or customData changes; return an empty array to show nothing. " +
"The menu is temporarily hidden while the selected frame title is being edited. " +
"Registration is cleared automatically when the view closes, and cleared for this script specifically if the script's file is deleted while the view is still open. " +
"Calling this again for the same script in the same view (e.g. running the script again while it is already registered) does not create a duplicate - it is a no-op that returns null. " +
"Returns a cleanup function to unregister manually, or null if there is no active target view or this script is already registered in it.",
@@ -1010,13 +1024,14 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "registerAutostart",
code: 'registerAutostart(): Promise<"allow" | "deny" | "pending">;',
code: 'registerAutostart(message?: string): Promise<"allow" | "deny" | "pending">;',
desc:
"Requests permission for this script to be automatically re-run every time a new Excalidraw view is opened. " +
"The optional message is shown as a separate second paragraph after the permission question and before the hint explaining where the permission can be changed. Use it to clarify what the script registers or performs during autostart. " +
"The first time a given script calls this, the user is prompted to Allow, Deny, or decide later; the decision persists and is not asked again unless the user changes it (via the \"Autostart scripts\" command or settings section) or previously picked \"Ask me later\". " +
"A fresh Allow also immediately re-runs the script in every other currently-open Excalidraw view, so it attaches everywhere right away instead of only the next time each view is opened. " +
'Returns "allow", "deny", or "pending" (no active script, or the user has not yet decided). Typically called near the top of a script, guarding whatever the script wants to re-register on autostart, e.g. registerElementActionProvider().',
after: "();",
'Returns "allow", "deny", or "pending" (no active script, or the user has not yet decided). Typically called near the top of a script, guarding whatever the script wants to re-register on autostart, e.g. registerElementActionProvider(). Use utils.executionSource === "view-autostart" when only the view-autostart execution should stop after registration.',
after: '("Autostart registers this script’s drawing tools; it does not run its main action.");',
},
{
field: "getSidepanelLeaf",
@@ -1413,6 +1428,15 @@ export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
desc: "The TFile of the currently running script",
after: "",
},
{
field: "executionSource",
code: 'executionSource: "manual" | "plugin-startup" | "view-autostart" | "sidepanel-restore" | "sidepanel-reload" | "drawing-onload"',
desc:
"Identifies why the script engine invoked the current script. " +
'Use "view-autostart" for registration-only setup, while "manual" covers the script button, command palette, and hotkey. ' +
"This value describes the trigger, not compilation-cache reuse or retained runtime state.",
after: "",
},
];
export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
+217 -40
View File
@@ -103,6 +103,16 @@ declare const mainDocument: Document;
const markdownRendererRecursionWatcthdog = new Set<TFile>();
type CacheValidationMode = "validated" | "stale-first";
const SCENE_FILE_LOAD_STALL_TIMEOUT_MS = 30_000;
const SCENE_FILE_PROGRESSIVE_BATCH_SIZE = 8;
export type EmbeddedFilesLoaderTerminalState =
| "idle"
| "running"
| "completed"
| "terminated"
| "timed-out"
| "failed";
/** Describes the lightweight work required after a stale-first cache hit. */
export type DeferredCacheValidation =
@@ -681,6 +691,7 @@ export class EmbeddedFilesLoader {
private plugin: ExcalidrawPlugin;
private isDark: boolean;
public terminate = false;
public terminalState: EmbeddedFilesLoaderTerminalState = "idle";
public uid: string;
constructor(plugin: ExcalidrawPlugin, isDark?: boolean) {
@@ -868,7 +879,6 @@ export class EmbeddedFilesLoader {
},
})
: undefined;
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
@@ -893,38 +903,39 @@ export class EmbeddedFilesLoader {
};
}
const generatedSVG = await createSVG(
hasFilenameParts
? filenameParts.hasGroupref ||
filenameParts.hasBlockref ||
filenameParts.hasSectionref ||
filenameParts.hasFrameref ||
filenameParts.hasClippedFrameref
? filenameParts.filepath + filenameParts.linkpartReference
: file.path
: file?.path,
false, //false
hasFilenameParts && filenameParts.hasClippedFrameref
? {
...exportSettings,
frameRendering: {
enabled: true,
name: false,
outline: false,
clip: true,
},
}
: exportSettings,
this,
forceTheme,
null,
null,
elements,
this.plugin,
depth + 1,
getExportPadding(this.plugin, file),
);
const svg = replaceSVGColors(
await createSVG(
hasFilenameParts
? filenameParts.hasGroupref ||
filenameParts.hasBlockref ||
filenameParts.hasSectionref ||
filenameParts.hasFrameref ||
filenameParts.hasClippedFrameref
? filenameParts.filepath + filenameParts.linkpartReference
: file.path
: file?.path,
false, //false
hasFilenameParts && filenameParts.hasClippedFrameref
? {
...exportSettings,
frameRendering: {
enabled: true,
name: false,
outline: false,
clip: true,
},
}
: exportSettings,
this,
forceTheme,
null,
null,
elements,
this.plugin,
depth + 1,
getExportPadding(this.plugin, file),
),
generatedSVG,
inFile instanceof EmbeddedFile ? inFile.colorMap : null,
) as SVGSVGElement;
if (this.terminate) {
@@ -1212,14 +1223,15 @@ export class EmbeddedFilesLoader {
? inFile.filenameparts?.linkpartReference
: undefined,
));
const loadedFromCache = isExcalidrawFile
? excalidrawLoadedFromCache
: pdfLoadedFromCache;
return {
mimeType,
fileId: generatedFileId,
dataURL,
created: isHyperLink || isLocalLink ? 0 : file.stat.mtime,
loadedFromCache: isExcalidrawFile
? excalidrawLoadedFromCache
: pdfLoadedFromCache,
loadedFromCache,
hasSVGwithBitmap,
size,
pdfPageViewProps,
@@ -1256,6 +1268,8 @@ export class EmbeddedFilesLoader {
onDeferredValidationCandidates,
deferredCacheValidation,
sceneElements,
waitForRender,
prioritizedFileIds,
}: {
excalidrawData: ExcalidrawData;
addFiles: (files: FileData[], isDark: boolean, final?: boolean) => void;
@@ -1271,12 +1285,36 @@ export class EmbeddedFilesLoader {
) => void;
deferredCacheValidation?: ReadonlyMap<FileId, DeferredCacheValidation>;
sceneElements?: readonly ExcalidrawElement[];
waitForRender?: () => Promise<void>;
prioritizedFileIds?: ReadonlySet<FileId>;
}) {
this.terminalState = "running";
if (this.isDark === undefined) {
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
}
if (depth > 7) {
this.terminalState = "failed";
new Notice(t("INFINITE_LOOP_WARNING") + depth.toString(), 6000);
try {
addFiles([], this.isDark, true);
} catch (error: unknown) {
errorlog({
where: "EmbeddedFileLoader.loadSceneFiles",
uid: this.uid,
phase: "depth-limit",
error,
});
}
return;
}
const entries = Array.from(excalidrawData.getFileEntries());
if (prioritizedFileIds?.size) {
entries.sort(
([fileIdA], [fileIdB]) =>
Number(prioritizedFileIds.has(fileIdB)) -
Number(prioritizedFileIds.has(fileIdA)),
);
}
const markdownImageElements = (
sceneElements ?? excalidrawData.scene.elements
).filter(
@@ -1288,9 +1326,7 @@ export class EmbeddedFilesLoader {
markdownImageElements.map((element) => element.fileId),
);
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,isDark:this.isDark,sceneTheme:excalidrawData.scene.appState.theme});
if (this.isDark === undefined) {
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
}
let onLoadTaskSettled: (() => void) | null = null;
const createSafeLoadTask = (
task: () => Promise<void>,
context: Record<string, unknown>,
@@ -1305,6 +1341,8 @@ export class EmbeddedFilesLoader {
...context,
error,
});
} finally {
onLoadTaskSettled?.();
}
});
const files: FileData[][] = [];
@@ -1637,10 +1675,55 @@ export class EmbeddedFilesLoader {
}
}
const runLoadPool = async (
iterator: Generator<Promise<void>>,
concurrency: number,
): Promise<boolean> => {
let stallTimer: number | null = null;
let resolveStall!: () => void;
const stalled = new Promise<"stalled">((resolve) => {
resolveStall = () => resolve("stalled");
});
const resetStallTimer = () => {
if (stallTimer !== null) {
window.clearTimeout(stallTimer);
}
stallTimer = window.setTimeout(
resolveStall,
SCENE_FILE_LOAD_STALL_TIMEOUT_MS,
);
};
onLoadTaskSettled = resetStallTimer;
resetStallTimer();
const poolCompleted = new PromisePool(iterator, concurrency)
.all()
.then(() => "completed" as const);
const result = await Promise.race([poolCompleted, stalled]);
onLoadTaskSettled = null;
if (stallTimer !== null) {
window.clearTimeout(stallTimer);
}
if (result === "completed") {
return true;
}
this.terminalState = "timed-out";
this.terminate = true;
return false;
};
let finalFlushed = false;
const flushFiles = (
batchFiles: FileData[] | undefined,
final: boolean,
) => {
if (final && finalFlushed) {
return;
}
if (final) {
finalFlushed = true;
}
try {
addFiles(batchFiles, this.isDark, final);
} catch (e: unknown) {
@@ -1648,6 +1731,61 @@ export class EmbeddedFilesLoader {
}
};
let progressivePaintPromise: Promise<void> | null = null;
const flushProgressiveBatch = (): boolean => {
if (
!waitForRender ||
files[batch].length <= SCENE_FILE_PROGRESSIVE_BATCH_SIZE
) {
return false;
}
if (prioritizedFileIds?.size) {
files[batch].sort(
(fileA, fileB) =>
Number(prioritizedFileIds.has(fileB.id)) -
Number(prioritizedFileIds.has(fileA.id)),
);
}
const batchFiles = files[batch]
.splice(0, SCENE_FILE_PROGRESSIVE_BATCH_SIZE)
.filter((f) => emitPolicy === "all" || !f.loadedFromCache);
if (batchFiles.length === 0) {
return false;
}
flushFiles(batchFiles, false);
const paintPromise = Promise.resolve()
.then(waitForRender)
.catch((error: unknown) => {
errorlog({
where: "EmbeddedFileLoader.loadSceneFiles",
phase: "progressive-batch-paint",
error,
});
});
progressivePaintPromise = paintPromise;
void paintPromise.finally(() => {
if (progressivePaintPromise === paintPromise) {
progressivePaintPromise = null;
}
});
return true;
};
const waitForProgressivePaint = async () => {
if (progressivePaintPromise !== null) {
await progressivePaintPromise;
}
};
const drainProgressiveBatches = async () => {
await waitForProgressivePaint();
while (flushProgressiveBatch()) {
await waitForProgressivePaint();
}
};
const addFilesTimer = window.setInterval(() => {
if (this.terminate) {
window.clearInterval(addFilesTimer);
@@ -1656,6 +1794,12 @@ export class EmbeddedFilesLoader {
if (files[batch].length === 0) {
return;
}
if (progressivePaintPromise !== null) {
return;
}
if (flushProgressiveBatch()) {
return;
}
// During deferred validation, only regenerated results should reach addFiles.
const batchFiles = files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
@@ -1670,16 +1814,20 @@ export class EmbeddedFilesLoader {
validationConcurrency ?? this.plugin.settings.renderingConcurrency;
const iterator = loadIterator(this, entries, true, true);
if (!this.terminate) {
await new PromisePool(iterator, concurency).all();
await runLoadPool(iterator, concurency);
}
if (this.terminate) {
if (this.terminalState === "running") {
this.terminalState = "terminated";
}
flushFiles(undefined, true);
return;
}
if (deferredGenerationEntries.length > 0) {
// Publish everything that was available from cache or direct file reads
// before expensive generated SVG work can monopolize the main thread.
await drainProgressiveBatches();
const fastFiles = files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
);
@@ -1699,11 +1847,14 @@ export class EmbeddedFilesLoader {
false,
false,
);
await new PromisePool(deferredIterator, concurency).all();
await runLoadPool(deferredIterator, concurency);
}
}
if (this.terminate) {
if (this.terminalState === "running") {
this.terminalState = "terminated";
}
flushFiles(undefined, true);
return;
}
@@ -1711,15 +1862,41 @@ export class EmbeddedFilesLoader {
if (deferredValidationCandidates.size > 0) {
onDeferredValidationCandidates?.(deferredValidationCandidates);
}
await drainProgressiveBatches();
// Same filter for the final flush so validated cache hits remain a no-op.
const batchFiles = files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
);
// The helper retains the try/catch because the user may have closed the
// view by the time the asynchronous image work completes.
this.terminalState = "completed";
flushFiles(batchFiles, true);
} catch (error: unknown) {
this.terminalState = "failed";
errorlog({
where: "EmbeddedFileLoader.loadSceneFiles",
uid: this.uid,
phase: "pool",
error,
});
const batchFiles = files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
);
flushFiles(batchFiles, true);
} finally {
onLoadTaskSettled = null;
window.clearInterval(addFilesTimer);
if (!finalFlushed) {
if (this.terminalState === "running") {
this.terminalState = this.terminate ? "terminated" : "failed";
}
const batchFiles = this.terminate
? undefined
: files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
);
flushFiles(batchFiles, true);
}
this.emptyPDFDocsMap();
}
}
+113 -23
View File
@@ -245,10 +245,12 @@ const GAP = 4;
/**
* ExcalidrawAutomate is a utility class that provides a simplified API to interact with Excalidraw elements and the Excalidraw canvas.
* Elements in the Excalidraw Scene are immutable. You should never directly change element properties in the scene object.
* ExcalidrawAutomate provides a "workbench" where you can create, modify, and delete elements before committing them to the Excalidraw Scene.
* The basic workflow is to create elements in ExcalidrawAutomate and once ready commit them to the Excalidraw Scene using addElementsToView().
* To modify elements in the scene, you should first copy them over to EA using copyViewElementsToEAforEditing, make the necessary modifications,
* then commit them back to the scene using addElementsToView().
* ExcalidrawAutomate provides a stateful, in-memory "workbench" where you can create, modify, and delete elements independently of the Excalidraw Scene.
* Begin each independent transaction with clear(). To modify existing scene elements while preserving their identity, copy them to the workbench with
* copyViewElementsToEAforEditing() and modify the copies returned by getElement(originalId). Commit persistent edits with addElementsToView(),
* or use the modified workbench elements for a temporary EA operation such as export and then discard them with clear() without committing.
* cloneElement() and cloneElements() deliberately generate new IDs and are only for creating genuine duplicates, never for editing an existing scene element.
* Do not interleave asynchronous operations that mutate the same EA workbench; await the operation, then clear before starting another transaction.
* To delete an element from the view set element.isDeleted = true and commit the changes to the scene using addElementsToView().
*
* At a very high level, EA has 3 type of functions:
@@ -841,6 +843,8 @@ export class ExcalidrawAutomate {
};
colorPalette: object;
sidepanelTab: ExcalidrawSidepanelTab | null = null;
private cleanupCallbacks: Array<{ callback: () => void }> = [];
private destroyed = false;
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView) {
this.plugin = plugin;
@@ -848,6 +852,37 @@ export class ExcalidrawAutomate {
this.targetView = view;
}
/**
* Registers synchronous cleanup owned by this EA instance. Use this for
* external listeners, observers, timers, and subscriptions that EA cannot
* release itself. Cleanup runs when this EA is destroyed.
* @param cleanup - Synchronous cleanup callback.
* @returns A function that unregisters this callback without running it.
*/
public registerCleanup(cleanup: () => void): () => void {
if (typeof cleanup !== "function") {
errorMessage("cleanup must be a function", "registerCleanup()");
return () => undefined;
}
if (this.destroyed) {
try {
cleanup();
} catch (error: unknown) {
log("ExcalidrawAutomate cleanup failed", error);
}
return () => undefined;
}
const registration = { callback: cleanup };
this.cleanupCallbacks.push(registration);
return () => {
const index = this.cleanupCallbacks.indexOf(registration);
if (index !== -1) {
this.cleanupCallbacks.splice(index, 1);
}
};
}
/**
* Return the active sidepanel tab for a script, if one exists.
* If scriptName is omitted the function checks ea.activeScript.
@@ -887,6 +922,18 @@ export class ExcalidrawAutomate {
persist: boolean = false,
reveal: boolean = true,
): Promise<ExcalidrawSidepanelTab | null> {
const existingSidepanel = ExcalidrawSidepanelView.getExisting(false);
if (
persist &&
this.activeScript &&
this.plugin?.scriptEngine?.isViewAutostartExecution(this) &&
existingSidepanel?.hasPersistentScript(this.activeScript) &&
existingSidepanel.getTabByScript(this.activeScript)
) {
log(
`Warning: script "${this.activeScript}" attempted to create an already-active persistent sidepanel during view autostart. Consider branching on utils.executionSource === "view-autostart".`,
);
}
if (this.sidepanelTab) {
this.sidepanelTab.close();
}
@@ -1671,7 +1718,7 @@ export class ExcalidrawAutomate {
* @param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.
* @param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.
* @param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.
* @param {ExcalidrawElement[]} [options.elementsOverride] - Optional override for the elements to include in the SVG. Primary to support the Printable Layout Wizard script
* @param {readonly ExcalidrawElement[]} [options.elementsOverride] - Optional complete replacement for the view's exported elements. This array is not merged with the current scene or treated as a patch by ID: when supplied, only its non-deleted elements are exported. Include every element that should appear in the SVG.
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
*/
async createViewSVG({
@@ -1691,7 +1738,7 @@ export class ExcalidrawAutomate {
selectedOnly?: boolean;
skipInliningFonts?: boolean;
embedScene?: boolean;
elementsOverride?: ExcalidrawElement[];
elementsOverride?: readonly ExcalidrawElement[];
}): Promise<SVGSVGElement> {
if (!this.targetView || !this.targetView.file || !this.targetView._loaded) {
log("No view loaded");
@@ -3084,7 +3131,9 @@ export class ExcalidrawAutomate {
}
/**
* Clears elementsDict and imagesDict only.
* Clears the EA workbench (`elementsDict` and `imagesDict`) without changing
* the scene, target view, or current style. Call this before each independent
* workbench transaction and before repurposing an EA instance.
*/
clear(): void {
this.elementsDict = {};
@@ -3131,7 +3180,7 @@ export class ExcalidrawAutomate {
return this.plugin.isExcalidrawFile(f);
}
targetView: ExcalidrawView = null; //the view currently edited
targetView: ExcalidrawView | null = null; //the view currently edited
/**
* Sets the target view for EA. All view operations and all access to the Excalidraw API
* will be performed on this view.
@@ -3139,12 +3188,15 @@ export class ExcalidrawAutomate {
* Typical usage:
* - `setView()` to pick a sensible default automatically
* - `setView(excalidrawView)` to explicitly target a specific view
* - `setView(null)` to explicitly clear `targetView`
*
* Selectors:
* - If `view` is `null` or `undefined` (or `"auto"`), EA will pick a sensible default:
* - If `view` is `undefined` (or `"auto"`), EA will pick a sensible default:
* 1) the currently active Excalidraw view (if any),
* 2) otherwise the last active Excalidraw view (if it is still available),
* 3) otherwise the `"first"` Excalidraw view in the workspace.
* - If `view` is explicitly `null`, EA clears `targetView`. This is useful for
* sidepanels when focus moves to a Markdown view or no drawing is eligible.
* - If `show` is `true`, the view will be revealed (brought to front) and focused.
*
* Deprecated selectors (kept for backward compatibility):
@@ -3156,18 +3208,22 @@ export class ExcalidrawAutomate {
* necessarily match what a user would consider the “first”/“leftmost”/“topmost” view;
* from a user's perspective it may appear effectively random.**
*
* @param {ExcalidrawView | "auto" | "first" | "active" | null | undefined} [view] - The view (or selector) to set as target.
* @param {ExcalidrawView | "auto" | "first" | "active" | null | undefined} [view] - The view or selector to set as target. Pass `null` to clear the target.
* @param {boolean} [show=false] - Whether to reveal/focus the target view.
* @returns {ExcalidrawView} The ExcalidrawView that was set as `targetView` (or `null` if none found).
* @returns {ExcalidrawView | null} The ExcalidrawView that was set as `targetView`, or `null` when cleared or none was found.
*/
setView(
view?: ExcalidrawView | "auto" | "first" | "active" | null,
show: boolean = false,
): ExcalidrawView {
): ExcalidrawView | null {
const app = this.plugin.app;
const workspace = app.workspace;
const setView = () => {
if (!view || view === "auto") {
if (view === null) {
this.targetView = null;
return;
}
if (view === undefined || view === "auto") {
view = workspace.getActiveViewOfType(ExcalidrawView);
if (view instanceof ExcalidrawView) {
this.targetView = view;
@@ -3406,7 +3462,12 @@ export class ExcalidrawAutomate {
if (fileIDWhiteList.size > 0) {
this.targetView.setDirty();
await new Promise<void>((resolve) => {
void this.targetView.loadSceneFiles(false, fileIDWhiteList, resolve);
void this.targetView.loadSceneFiles(
false,
fileIDWhiteList,
resolve,
undefined,
);
});
}
}
@@ -3567,12 +3628,15 @@ export class ExcalidrawAutomate {
}
/**
* Copies elements from the view to elementsDict for editing.
* Copies existing scene elements to the workbench as mutable, identity-preserving copies.
* The copies can be committed with `addElementsToView()` to update the original
* scene elements, or used temporarily by another EA operation and discarded with
* `clear()` without modifying the scene.
* @param {ExcalidrawElement[]} elements - Array of elements to copy.
* @param {boolean} [copyImages=false] - Whether to copy images as well.
*/
copyViewElementsToEAforEditing(
elements: ExcalidrawElement[],
elements: readonly ExcalidrawElement[],
copyImages: boolean = false,
): void {
if (copyImages && elements.some((el) => el.type === "image")) {
@@ -3854,7 +3918,9 @@ export class ExcalidrawAutomate {
* `getActions` is called with the currently selected element whenever the
* selection, element type, fileId, or customData changes, and should
* return the buttons to show for that element (an empty array shows
* nothing). Registration is tied to the current view: it is automatically
* nothing). The menu is temporarily hidden while the selected frame's
* title is being edited, so custom actions do not obstruct the title editor.
* Registration is tied to the current view: it is automatically
* cleared when the view closes, and cleared for this script specifically
* if the script's file is deleted while the view is still open. Calling
* this a second time for the same script in the same view (e.g. running
@@ -3924,11 +3990,14 @@ export class ExcalidrawAutomate {
* A fresh "allow" also immediately re-runs the script in every other
* currently-open Excalidraw view, so it attaches everywhere right away
* instead of only the next time each view is opened.
* @param {string} [message] - Optional script-provided explanation displayed as the second paragraph of the permission prompt.
* @returns "allow" if the script is permitted to autostart, "deny" if
* the user has denied it, or "pending" if there is no active script or
* the user has not yet made a decision.
*/
public async registerAutostart(): Promise<"allow" | "deny" | "pending"> {
public async registerAutostart(
message?: string,
): Promise<"allow" | "deny" | "pending"> {
const scriptName = this.activeScript;
if (!scriptName) {
errorMessage("no active script", "registerAutostart()");
@@ -3944,13 +4013,15 @@ export class ExcalidrawAutomate {
if (state === "allow" || state === "deny") {
return state;
}
const explanation = message?.trim();
const prompt = new MultiOptionConfirmationPrompt<
"allow" | "deny" | "pending" | null
>(
this.plugin,
`<b>${scriptName}</b> ${t("AUTOSTART_SCRIPT_PROMPT")}<br><br>` +
`<span style="color: var(--text-muted); font-size: var(--font-smaller);">` +
`${t("AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT")}</span>`,
`<p><b>${scriptName}</b> ${t("AUTOSTART_SCRIPT_PROMPT")}</p>` +
(explanation ? `<p>${explanation}</p>` : "") +
`<p><span style="color: var(--text-muted); font-size: var(--font-smaller);">` +
`${t("AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT")}</span></p>`,
new Map([
[t("AUTOSTART_SCRIPT_ALLOW"), "allow"],
[t("AUTOSTART_SCRIPT_DENY"), "deny"],
@@ -4497,6 +4568,7 @@ export class ExcalidrawAutomate {
}
this.plugin.settings.scriptEngineSettings[this.activeScript] = settings;
await this.plugin.saveSettings();
this.plugin.refreshSettingsTab();
}
public setScriptSettingValue(key: string, value: ScriptSettingValue): void {
@@ -4521,6 +4593,7 @@ export class ExcalidrawAutomate {
public async saveScriptSettings(): Promise<void> {
ensureActiveScriptSettingsObject(this);
await this.plugin.saveSettings();
this.plugin.refreshSettingsTab();
}
/**
@@ -4709,7 +4782,10 @@ export class ExcalidrawAutomate {
}
/**
* Clones the specified element with a new ID.
* Clones the specified element with a new ID for insertion as a genuine duplicate.
* Do not use this to edit an existing scene element; use
* `copyViewElementsToEAforEditing()` and retrieve the workbench copy by its
* original ID instead.
* @param {ExcalidrawElement} element - The element to clone.
* @returns {ExcalidrawElement} The cloned element with a new ID.
*/
@@ -5103,9 +5179,23 @@ export class ExcalidrawAutomate {
}
/**
* Destroys the ExcalidrawAutomate instance, clearing all references and data.
* Destroys this EA once, first releasing registered external resources and
* then clearing the ordinary EA state and references.
*/
destroy(): void {
if (this.destroyed) {
return;
}
this.destroyed = true;
const cleanups = this.cleanupCallbacks.reverse();
this.cleanupCallbacks = [];
cleanups.forEach(({ callback }) => {
try {
callback();
} catch (error: unknown) {
log("ExcalidrawAutomate cleanup failed", error);
}
});
this.sidepanelTab?.close();
this.targetView = null;
this.plugin = null;
+247 -60
View File
@@ -120,7 +120,7 @@ type LegacyGridColor = NonNullable<
* `.find()` call on `scene.elements` to `any`. Omitting them first makes
* this an actual override.
*/
type ExcalidrawDataScene = Omit<
export type ExcalidrawDataScene = Omit<
SceneDataWithFiles,
"elements" | "appState"
> & {
@@ -139,6 +139,11 @@ type ExcalidrawDataScene = Omit<
type RegExpMatchIteratorResult = IteratorResult<RegExpMatchArray, undefined>;
type SceneElementIndexes = {
linkedNonTextElementsById: Map<string, ExcalidrawElement>;
textElementsById: Map<string, Mutable<ExcalidrawTextElement>>;
};
type MarkdownBlockNode = {
type: string;
id?: string;
@@ -246,11 +251,37 @@ export const REG_LINKINDEX_HYPERLINK = /^\w+:\/\//;
export type EquationItem = { latex: string; isLoaded: boolean };
export type MermaidItem = { mermaid: string; isLoaded: boolean };
type TextElementData = {
raw: string;
parsed: string;
hasTextLink: boolean;
};
/** Drawing-owned metadata transferred without retaining an old view. */
export interface ExcalidrawDataMigrationState {
sourceFilePath: string;
textElements: ReadonlyMap<string, TextElementData>;
scene: ExcalidrawDataScene;
deletedElements: readonly ExcalidrawElement[];
showLinkBrackets: boolean;
linkPrefix: string;
embeddableTheme: "light" | "dark" | "auto" | "default";
urlPrefix: string;
autoexportPreference: AutoexportPreference;
textMode: TextMode;
loaded: boolean;
elementLinks: ReadonlyMap<string, string>;
files: ReadonlyMap<FileId, EmbeddedFile>;
markdownImages: ReadonlyMap<FileId, MarkdownImageData>;
equations: ReadonlyMap<FileId, EquationItem>;
mermaids: ReadonlyMap<FileId, MermaidItem>;
compatibilityMode: boolean;
textElementCommentedOut: boolean;
selectedElementIds: Readonly<Record<string, boolean>>;
}
export class ExcalidrawData {
public textElements: Map<
string,
{ raw: string; parsed: string; hasTextLink: boolean }
> = null;
public textElements: Map<string, TextElementData> = null;
public scene: ExcalidrawDataScene = null;
public deletedElements: ExcalidrawElement[] = [];
public file: TFile = null;
@@ -312,6 +343,110 @@ export class ExcalidrawData {
this.selectedElementIds = null;
}
/**
* Exports drawing-owned state for a one-shot window migration.
*
* Collection containers and mutable metadata records are copied. Immutable
* Excalidraw elements and `EmbeddedFile` descriptors are transferred by
* reference: neither owns a view, DOM node, `Window`, React runtime, or
* package lease, and retaining their cached asset metadata is intentional.
*/
public exportMigrationState(): ExcalidrawDataMigrationState | null {
if (
!this.loaded ||
!this.file ||
!this.scene ||
!this.textElements ||
!this.elementLinks ||
!this.files ||
!this.markdownImages ||
!this.equations ||
!this.mermaids
) {
return null;
}
return {
sourceFilePath: this.file.path,
textElements: new Map(
Array.from(this.textElements, ([id, value]) => [id, { ...value }]),
),
scene: {
...this.scene,
elements: [...this.scene.elements],
appState: { ...this.scene.appState },
files: { ...(this.scene.files ?? {}) },
},
deletedElements: [...this.deletedElements],
showLinkBrackets: this.showLinkBrackets,
linkPrefix: this.linkPrefix,
embeddableTheme: this.embeddableTheme,
urlPrefix: this.urlPrefix,
autoexportPreference: this.autoexportPreference,
textMode: this.textMode,
loaded: this.loaded,
elementLinks: new Map(this.elementLinks),
files: new Map(this.files),
markdownImages: new Map(
Array.from(this.markdownImages, ([id, value]) => [
id,
{ ...value },
]),
),
equations: new Map(
Array.from(this.equations, ([id, value]) => [id, { ...value }]),
),
mermaids: new Map(
Array.from(this.mermaids, ([id, value]) => [id, { ...value }]),
),
compatibilityMode: this.compatibilityMode,
textElementCommentedOut: this.textElementCommentedOut,
selectedElementIds: { ...this.selectedElementIds },
};
}
/** Adopts a validated drawing-state export into this new view-owned model. */
public adoptMigrationState(
state: ExcalidrawDataMigrationState,
file: TFile,
): boolean {
if (!file || state.sourceFilePath !== file.path || !state.loaded) {
return false;
}
this.textElements = new Map(
Array.from(state.textElements, ([id, value]) => [id, { ...value }]),
);
this.scene = {
...state.scene,
elements: [...state.scene.elements],
appState: { ...state.scene.appState },
files: { ...(state.scene.files ?? {}) },
};
this.deletedElements = [...state.deletedElements];
this.file = file;
this.showLinkBrackets = state.showLinkBrackets;
this.linkPrefix = state.linkPrefix;
this.embeddableTheme = state.embeddableTheme;
this.urlPrefix = state.urlPrefix;
this.autoexportPreference = state.autoexportPreference;
this.textMode = state.textMode;
this.loaded = state.loaded;
this.elementLinks = new Map(state.elementLinks);
this.files = new Map(state.files);
this.markdownImages = new Map(
Array.from(state.markdownImages, ([id, value]) => [id, { ...value }]),
);
this.equations = new Map(
Array.from(state.equations, ([id, value]) => [id, { ...value }]),
);
this.mermaids = new Map(
Array.from(state.mermaids, ([id, value]) => [id, { ...value }]),
);
this.compatibilityMode = state.compatibilityMode;
this.textElementCommentedOut = state.textElementCommentedOut;
this.selectedElementIds = { ...state.selectedElementIds };
return true;
}
/**
* 1.5.4: for backward compatibility following the release of container bound text elements and the depreciation boundElementIds field
*/
@@ -1111,17 +1246,35 @@ export class ExcalidrawData {
return dirty;
}
private updateElementLinksFromScene() {
private getSceneElementIndexes(): SceneElementIndexes {
const linkedNonTextElementsById = new Map<string, ExcalidrawElement>();
const textElementsById = new Map<
string,
Mutable<ExcalidrawTextElement>
>();
for (const element of this.scene.elements) {
if (element.type === "text") {
if (!textElementsById.has(element.id)) {
textElementsById.set(element.id, element);
}
} else if (element.link && !linkedNonTextElementsById.has(element.id)) {
linkedNonTextElementsById.set(element.id, element);
}
}
return { linkedNonTextElementsById, textElementsById };
}
private updateElementLinksFromScene(
linkedNonTextElementsById: Map<string, ExcalidrawElement>,
) {
for (const key of this.elementLinks.keys()) {
//find element in the scene
const el = this.scene.elements?.filter(
(el: ExcalidrawElement) =>
el.type !== "text" && el.id === key && el.link, //&&
);
if (el.length === 0) {
const element = linkedNonTextElementsById.get(key);
if (!element) {
this.elementLinks.delete(key); //if no longer in the scene, delete the text element
} else {
this.elementLinks.set(key, el[0].link);
this.elementLinks.set(key, element.link);
}
}
}
@@ -1130,21 +1283,20 @@ export class ExcalidrawData {
* update text element map by deleting entries that are no long in the scene
* and updating the textElement map based on the text updated in the scene
*/
private async updateTextElementsFromScene() {
private async updateTextElementsFromScene(
sceneTextElementsById: Map<string, Mutable<ExcalidrawTextElement>>,
) {
for (const key of this.textElements.keys()) {
//find text element in the scene
const el = this.scene.elements?.filter(
(el: ExcalidrawElement) => el.type === "text" && el.id === key,
) as Mutable<ExcalidrawTextElement>[];
if (el.length === 0) {
const element = sceneTextElementsById.get(key);
if (!element) {
this.textElements.delete(key); //if no longer in the scene, delete the text element
} else {
const text = await this.getText(key);
const raw =
this.scene.prevTextMode === TextMode.parsed
? el[0].rawText
: (el[0].originalText ?? el[0].text);
if (text !== (el[0].originalText ?? el[0].text)) {
? element.rawText
: (element.originalText ?? element.text);
if (text !== (element.originalText ?? element.text)) {
const parseRes = await this.parse(text);
this.textElements.set(key, {
raw,
@@ -1384,20 +1536,29 @@ export class ExcalidrawData {
outString += `\n^_dummy!_\n\n`;
}
const textElementLinks = new Map<string, string>();
const uniqueSceneElementsById = new Map<
string,
ExcalidrawElement | null
>();
for (const element of this.scene.elements) {
uniqueSceneElementsById.set(
element.id,
uniqueSceneElementsById.has(element.id) ? null : element,
);
}
for (const key of this.textElements.keys()) {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/566
const element = this.scene.elements.filter(
(el: ExcalidrawElement) => el.id === key,
) as Mutable<ExcalidrawTextElement>[];
const element = uniqueSceneElementsById.get(key) as Mutable<
ExcalidrawTextElement
> | null;
const elementString = this.textElements.get(key).raw;
if (
element &&
element.length === 1 &&
element[0].link &&
(!syncTextLinks || element[0].rawText === element[0].originalText)
element.link &&
(!syncTextLinks || element.rawText === element.originalText)
) {
//if(element[0].link.match(/^\[\[[^\]]*]]$/g)) { //apply this only to markdown links
textElementLinks.set(key, element[0].link);
textElementLinks.set(key, element.link);
//elementString = `%%***>>>text element-link:${element[0].link}<<<***%%` + elementString;
//}
}
@@ -1475,11 +1636,11 @@ export class ExcalidrawData {
sceneJSONstring,
this.disableCompression ? false : this.plugin.settings.compress,
);
const result =
return (
outString +
(this.textElementCommentedOut ? "" : "%%\n") +
drawingSection;
return result;
drawingSection
);
}
generateMDSync(deletedElements: ExcalidrawElement[] = []): string {
@@ -1488,11 +1649,11 @@ export class ExcalidrawData {
sceneJSONstring,
this.disableCompression ? false : this.plugin.settings.compress,
);
const result =
return (
outString +
(this.textElementCommentedOut ? "" : "%%\n") +
drawingSection;
return result;
drawingSection
);
}
public async saveDataURLtoVault(
@@ -1601,33 +1762,49 @@ export class ExcalidrawData {
const scene = this.scene;
//remove files and equations that no longer have a corresponding image element
const images = scene.elements.filter(
(e) => e.type === "image",
) as ExcalidrawImageElement[];
const fileIds = images.map((e) => e.fileId);
const images: Mutable<ExcalidrawImageElement>[] = [];
const fileIds: FileId[] = [];
const imagesByFileId = new Map<
FileId,
Mutable<ExcalidrawImageElement>[]
>();
for (const element of scene.elements) {
if (element.type !== "image") {
continue;
}
images.push(element);
fileIds.push(element.fileId);
const imagesForFile = imagesByFileId.get(element.fileId);
if (imagesForFile) {
imagesForFile.push(element);
} else {
imagesByFileId.set(element.fileId, [element]);
}
}
const fileIdSet = new Set(imagesByFileId.keys());
this.files.forEach((value, key) => {
if (!fileIds.contains(key)) {
if (!fileIdSet.has(key)) {
this.files.delete(key);
dirty = true;
}
});
this.equations.forEach((value, key) => {
if (!fileIds.contains(key)) {
if (!fileIdSet.has(key)) {
this.equations.delete(key);
dirty = true;
}
});
this.mermaids.forEach((value, key) => {
if (!fileIds.contains(key)) {
if (!fileIdSet.has(key)) {
this.mermaids.delete(key);
dirty = true;
}
});
this.markdownImages.forEach((value, key) => {
if (!fileIds.contains(key)) {
if (!fileIdSet.has(key)) {
this.markdownImages.delete(key);
dirty = true;
}
@@ -1644,6 +1821,9 @@ export class ExcalidrawData {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/601
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/593
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/297
// Keep fileIds as the original iteration snapshot, while imagesByFileId
// follows mutations so each later duplicate selects only elements that
// still carry the original ID and the scene.files pass sees current IDs.
const processedIds = new Set<string>();
fileIds.forEach((fileId, idx) => {
if (processedIds.has(fileId)) {
@@ -1683,19 +1863,24 @@ export class ExcalidrawData {
return;
}
const newId = fileid();
(
scene.elements
.filter((el: ExcalidrawImageElement) => el.fileId === fileId)
.sort((a, b) =>
a.updated < b.updated ? 1 : -1,
)[0] as Mutable<ExcalidrawImageElement>
).fileId = newId as FileId;
const newId = fileid() as FileId;
const imagesForFile = imagesByFileId.get(fileId);
const newestImage = imagesForFile
.slice()
.sort((a, b) => (a.updated < b.updated ? 1 : -1))[0];
newestImage.fileId = newId;
imagesForFile.splice(imagesForFile.indexOf(newestImage), 1);
const imagesForNewId = imagesByFileId.get(newId);
if (imagesForNewId) {
imagesForNewId.push(newestImage);
} else {
imagesByFileId.set(newId, [newestImage]);
}
dirty = true;
processedIds.add(newId);
if (embeddedFile) {
this.setFile(
newId as FileId,
newId,
new EmbeddedFile(
this.plugin,
this.file.path,
@@ -1704,7 +1889,7 @@ export class ExcalidrawData {
);
}
if (equation) {
this.setEquation(newId as FileId, {
this.setEquation(newId, {
latex: equation.latex,
isLoaded: false,
});
@@ -1718,9 +1903,7 @@ export class ExcalidrawData {
name?: string;
};
const mermaidElements = getMermaidImageElements(
scene.elements.filter(
(el: ExcalidrawImageElement) => el.fileId === key,
),
imagesByFileId.get(key as FileId) ?? [],
);
if (
!(
@@ -1754,7 +1937,9 @@ export class ExcalidrawData {
result = await this.syncFiles();
this.scene.files = {}; //files contains the dataURLs of files. Once synced these are all saved to disk
}
this.updateElementLinksFromScene();
const { linkedNonTextElementsById, textElementsById } =
this.getSceneElementIndexes();
this.updateElementLinksFromScene(linkedNonTextElementsById);
result =
result ||
this.syncCroppedPDFs() ||
@@ -1762,21 +1947,23 @@ export class ExcalidrawData {
this.setUrlPrefix() ||
this.setShowLinkBrackets() ||
this.findNewElementLinksInScene();
await this.updateTextElementsFromScene();
await this.updateTextElementsFromScene(textElementsById);
return result || this.findNewTextElementsInScene(selectedElementIds);
}
public async updateScene(newScene: string) {
//console.log("Excalidraw.Data.updateScene()");
this.scene = JSON_parse(newScene);
this.updateElementLinksFromScene();
const { linkedNonTextElementsById, textElementsById } =
this.getSceneElementIndexes();
this.updateElementLinksFromScene(linkedNonTextElementsById);
const result =
this.setLinkPrefix() ||
this.setUrlPrefix() ||
this.setShowLinkBrackets() ||
this.setembeddableThemePreference() ||
this.findNewElementLinksInScene();
await this.updateTextElementsFromScene();
await this.updateTextElementsFromScene(textElementsById);
if (result || this.findNewTextElementsInScene()) {
await this.updateSceneTextElements();
return true;
+63 -13
View File
@@ -9,6 +9,7 @@ import { hasExcalidrawEmbeddedImagesTreeChanged } from "../utils/fileUtils";
import { EXCALIDRAW_PLUGIN } from "src/constants/constants";
import { blobToDataURL } from "../utils/coreUtils";
import { isInstanceOfSVGSVGElement } from "../utils/typechecks";
import { BackupPersistenceQueue } from "./BackupPersistenceQueue";
type FileCacheData = {
schemaVersion: 2;
@@ -87,6 +88,16 @@ class ImageCache {
private purgeInvalidBackupTimer: number = null;
private touchedCacheKeys = new Set<string>();
private cacheReadinessPromise: Promise<void> | null = null;
private backupWrites = new BackupPersistenceQueue({
ownerWindow: window,
write: (filepath, data) => this.addBAKToCache(filepath, data),
onError: (error, stage) =>
errorlog({
where: "ImageCache.backupWrites",
fn: stage,
error,
}),
});
private getCacheRetentionCutoff(): number {
const retentionDays = Math.max(
@@ -128,6 +139,7 @@ class ImageCache {
if (this.purgeInvalidBackupTimer) {
window.clearTimeout(this.purgeInvalidBackupTimer);
}
this.backupWrites.destroy();
this.db?.close();
this.db = null;
this.plugin = null;
@@ -519,6 +531,7 @@ class ImageCache {
try {
await this.ensureCacheStoreReady();
const cachedData = await this.getCacheData(key);
if (!cachedData) {
return undefined;
@@ -541,15 +554,15 @@ class ImageCache {
if (cachedData.mtime < file.stat.mtime) {
return undefined;
}
if (
!options?.skipDependencyCheck &&
hasExcalidrawEmbeddedImagesTreeChanged(
if (!options?.skipDependencyCheck) {
const dependencyChanged = hasExcalidrawEmbeddedImagesTreeChanged(
file,
cachedData.mtime,
this.plugin,
)
) {
return undefined;
);
if (dependencyChanged) {
return undefined;
}
}
// Validated reads can require a minimum render scale so lower-resolution PDF
// snapshots are upgraded in the background without blocking the first paint.
@@ -614,7 +627,8 @@ class ImageCache {
if (options?.svgFormat === "data-url") {
return blobToDataURL(cacheData.blob);
}
return convertSVGStringToElement(await cacheData.blob.text());
const svgText = await cacheData.blob.text();
return convertSVGStringToElement(svgText);
}
if (this.obsidanURLCache.has(key)) {
return this.obsidanURLCache.get(key);
@@ -624,6 +638,11 @@ class ImageCache {
return obsidianURL;
}
/** Returns the number of live raster blob URLs retained by the session cache. */
public getObsidianURLCacheSize(): number {
return this.obsidanURLCache?.size ?? 0;
}
public releaseObsidianURL(url: string): void {
if (!url || !this.obsidanURLCache) {
return;
@@ -667,12 +686,11 @@ class ImageCache {
const isSVGElement = isInstanceOfSVGSVGElement(image);
const payloadKind =
isSVGElement || image.type === "image/svg+xml" ? "svg" : "raster";
const blob =
isSVGElement
? new Blob([image.outerHTML.replaceAll("&nbsp;", " ")], {
type: "image/svg+xml",
})
: image;
const blob = isSVGElement
? new Blob([image.outerHTML.replaceAll("&nbsp;", " ")], {
type: "image/svg+xml",
})
: image;
const now = Date.now();
const data: FileCacheData = {
schemaVersion: 2,
@@ -713,9 +731,40 @@ class ImageCache {
const transaction = this.db.transaction(this.backupStoreName, "readwrite");
const store = transaction.objectStore(this.backupStoreName);
store.put(data, filepath);
return new Promise<void>((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onerror = () =>
reject(
transaction.error ??
new Error(`Failed to update backup file with key: ${filepath}`),
);
transaction.onabort = () =>
reject(
transaction.error ??
new Error(`Backup update aborted for key: ${filepath}`),
);
});
}
/**
* Schedules the latest backup payload through the plugin-global queue.
*/
public scheduleBAKToCache(
filepath: string,
data: BackupData,
delayMs: number,
): boolean {
return this.backupWrites.schedule(filepath, data, delayMs);
}
/** Flushes any queued backup before a drawing path is renamed. */
public async flushPendingBAK(filepath: string): Promise<void> {
await this.backupWrites.flush(filepath);
}
public async removeBAKFromCache(filepath: string): Promise<void> {
await this.backupWrites.cancel(filepath);
if (!this.isReady()) {
return; // Database not initialized yet
}
@@ -750,6 +799,7 @@ class ImageCache {
}
public async clearBackupCache(): Promise<void> {
await this.backupWrites.cancelAll();
if (!this.isReady()) {
return; // Database not initialized yet
}
+670 -152
View File
@@ -20,11 +20,49 @@ import {
} from "../utils/obsidianUtils";
import { ButtonDefinition, InputPromptOptions } from "src/types/promptTypes";
import { errorlog } from "src/utils/coreUtils";
import {
type ScriptFileExtension,
getPreferredScriptFiles,
isScriptFilePath,
replaceScriptFileExtension,
resolveConfiguredStartupScriptPath,
} from "src/utils/scriptFileUtils";
export type ScriptIconMap = {
[key: string]: { name: string; group: string; svgString: string };
};
/** Identifies why the script engine invoked a script. */
export type ScriptExecutionSource =
| "manual"
| "plugin-startup"
| "view-autostart"
| "sidepanel-restore"
| "sidepanel-reload"
| "drawing-onload";
type ScriptExecutable = (
ea: ExcalidrawAutomate,
utils: Record<string, unknown>,
) => Promise<unknown>;
type CompiledScript = {
path: string;
mtime: number;
size: number;
executable: ScriptExecutable | null;
};
export interface ScriptFileRenamePlan {
renames: Array<{
file: TFile;
sourcePath: string;
destinationPath: string;
}>;
conflicts: string[];
includesStartupScript: boolean;
}
export class ScriptEngine {
private plugin: ExcalidrawPlugin;
private app: App;
@@ -39,12 +77,24 @@ export class ScriptEngine {
* linger in views that are still open.
*/
private elementActionProviders = new Map<string, Set<() => void>>();
private scriptFileEventsSuspended = false;
private scriptRegistryGeneration = 0;
private loadedScriptPaths = new Set<string>();
/** Compiled code keyed by vault path. EA instances and script state are never cached. */
private compiledScripts = new Map<string, Promise<CompiledScript>>();
/** Successful or in-flight automatic attachments, scoped to a view and script path. */
private autostartAttachments = new WeakMap<
ExcalidrawView,
Map<string, Promise<void>>
>();
/** EAs whose top-level script invocation currently has a view-autostart trigger. */
private viewAutostartEAs = new WeakSet<ExcalidrawAutomate>();
constructor(plugin: ExcalidrawPlugin) {
this.plugin = plugin;
this.app = plugin.app;
this.scriptIconMap = {};
this.loadScripts();
void this.loadScripts();
this.registerEventHandlers();
}
@@ -69,63 +119,230 @@ export class ScriptEngine {
this.eaInstances.clear();
this.eaInstances = null;
this.elementActionProviders.clear();
this.loadedScriptPaths.clear();
this.compiledScripts.clear();
this.autostartAttachments = new WeakMap();
this.viewAutostartEAs = new WeakSet();
this.scriptIconMap = null;
this.plugin = null;
this.scriptPath = null;
}
private handleSvgFileChange(path: string) {
if (!path.endsWith(".svg")) {
return;
}
const scriptFile = this.app.vault.getAbstractFileByPath(
getIMGFilename(path, "md"),
private isInScriptFolder(path: string): boolean {
return Boolean(
this.scriptPath && path.startsWith(`${normalizePath(this.scriptPath)}/`),
);
if (scriptFile && scriptFile instanceof TFile) {
this.unloadScript(this.getScriptName(scriptFile), scriptFile.path);
this.loadScript(scriptFile);
}
private isJavaScriptPath(path: string): boolean {
return path.toLowerCase().endsWith(".js");
}
private isScriptPath(path: string): boolean {
return (
path.toLowerCase().endsWith(".md") ||
(this.plugin.settings.allowJavaScriptFiles && this.isJavaScriptPath(path))
);
}
/**
* Resolves the configured startup-script path without changing the stored
* setting. Extensionless paths retain the historical `.md` default; an
* explicit `.js` path is accepted only when JavaScript-file loading is
* enabled.
*/
public resolveStartupScriptPath(configuredPath: string): string | null {
const path = resolveConfiguredStartupScriptPath(configuredPath);
if (!path) {
return null;
}
if (this.isJavaScriptPath(path)) {
return this.plugin.settings.allowJavaScriptFiles ? path : null;
}
return path;
}
/** Returns whether an EA is currently running because of view autostart. */
public isViewAutostartExecution(ea: ExcalidrawAutomate): boolean {
return this.viewAutostartEAs.has(ea);
}
private invalidateCompiledScript(path: string): void {
this.compiledScripts.delete(path);
}
private clearCompiledScripts(): void {
this.compiledScripts.clear();
}
private clearAutostartAttachment(path: string): void {
getExcalidrawViews(this.app, true).forEach((view) => {
this.autostartAttachments.get(view)?.delete(path);
});
}
private compileScript(source: string): ScriptExecutable | null {
const script = stripYamlFrontmatter(source);
if (!script) {
return null;
}
const AsyncFunction = (async () => {}).constructor as unknown as {
new (...args: string[]): ScriptExecutable;
};
return new AsyncFunction("ea", "utils", script);
}
/**
* Returns compiled code for the current file version. In-flight requests for
* the same path share one promise, while event and stat checks prevent stale
* code from surviving edits or renames.
*/
private async getCompiledScript(
file: TFile,
): Promise<ScriptExecutable | null> {
while (true) {
const path = file.path;
const mtime = file.stat.mtime;
const size = file.stat.size;
const cachedPromise = this.compiledScripts.get(path);
if (cachedPromise !== undefined) {
try {
const cached = await cachedPromise;
if (this.compiledScripts.get(path) !== cachedPromise) {
continue;
}
if (
file.path === cached.path &&
file.stat.mtime === cached.mtime &&
file.stat.size === cached.size
) {
return cached.executable;
}
this.compiledScripts.delete(path);
} catch (error: unknown) {
if (this.compiledScripts.get(path) === cachedPromise) {
this.compiledScripts.delete(path);
}
throw error;
}
continue;
}
const compilePromise = (async (): Promise<CompiledScript> => {
const source = await this.app.vault.read(file);
return {
path,
mtime,
size,
executable: this.compileScript(source),
};
})();
this.compiledScripts.set(path, compilePromise);
try {
const compiled = await compilePromise;
if (this.compiledScripts.get(path) !== compilePromise) {
continue;
}
if (
file.path !== path ||
file.stat.mtime !== mtime ||
file.stat.size !== size
) {
this.compiledScripts.delete(path);
continue;
}
return compiled.executable;
} catch (error: unknown) {
if (this.compiledScripts.get(path) === compilePromise) {
this.compiledScripts.delete(path);
}
throw error;
}
}
}
private modifyEventHandler(file: TAbstractFile): void {
if (file instanceof TFile && this.compiledScripts.has(file.path)) {
this.invalidateCompiledScript(file.path);
}
}
private async deleteEventHandler(file: TFile) {
if (this.scriptFileEventsSuspended) {
return;
}
if (!(file instanceof TFile)) {
return;
}
if (!file.path.startsWith(this.scriptPath)) {
this.invalidateCompiledScript(file.path);
this.clearAutostartAttachment(file.path);
if (!this.isInScriptFolder(file.path)) {
return;
}
const scriptName = this.getScriptName(file);
this.unloadScript(scriptName, file.path);
await this.purgeAutostartPermission(scriptName);
this.handleSvgFileChange(file.path);
if (isScriptFilePath(file.path)) {
const scriptName = this.getScriptName(file);
const wasLoaded = Boolean(this.scriptIconMap[file.path]);
if (wasLoaded || !this.isJavaScriptPath(file.path)) {
await this.reloadScripts();
}
if (!this.getScriptFileByName(scriptName)) {
await this.purgeAutostartPermission(scriptName);
}
return;
}
if (file.extension.toLowerCase() === "svg") {
await this.reloadScripts();
}
}
private async createEventHandler(file: TFile) {
if (this.scriptFileEventsSuspended) {
return;
}
if (!(file instanceof TFile)) {
return;
}
if (!file.path.startsWith(this.scriptPath)) {
this.invalidateCompiledScript(file.path);
if (!this.isInScriptFolder(file.path)) {
return;
}
this.loadScript(file);
this.handleSvgFileChange(file.path);
if (
this.isScriptPath(file.path) ||
file.extension.toLowerCase() === "svg"
) {
await this.reloadScripts();
}
}
private async renameEventHandler(file: TAbstractFile, oldPath: string) {
if (this.scriptFileEventsSuspended) {
return;
}
if (!(file instanceof TFile)) {
return;
}
const oldFileIsScript = oldPath.startsWith(this.scriptPath);
const newFileIsScript = file.path.startsWith(this.scriptPath);
if (oldFileIsScript) {
const oldScriptName = this.getScriptName(oldPath);
this.unloadScript(oldScriptName, oldPath);
await this.purgeAutostartPermission(oldScriptName);
this.handleSvgFileChange(oldPath);
this.invalidateCompiledScript(oldPath);
this.invalidateCompiledScript(file.path);
this.clearAutostartAttachment(oldPath);
const oldPathWasLoaded = Boolean(this.scriptIconMap[oldPath]);
const oldFileWasScript =
this.isInScriptFolder(oldPath) && isScriptFilePath(oldPath);
const newFileIsScript =
this.isInScriptFolder(file.path) && this.isScriptPath(file.path);
const iconChanged =
(this.isInScriptFolder(oldPath) &&
oldPath.toLowerCase().endsWith(".svg")) ||
(this.isInScriptFolder(file.path) &&
file.extension.toLowerCase() === "svg");
const oldScriptName = oldFileWasScript ? this.getScriptName(oldPath) : null;
if (oldPathWasLoaded || newFileIsScript || iconChanged) {
await this.reloadScripts();
}
if (newFileIsScript) {
this.loadScript(file);
this.handleSvgFileChange(file.path);
if (oldScriptName && !this.getScriptFileByName(oldScriptName)) {
await this.purgeAutostartPermission(oldScriptName);
}
}
@@ -145,16 +362,20 @@ export class ScriptEngine {
this.renameEventHandler(file, oldPath),
),
);
this.plugin.registerEvent(
this.app.vault.on("modify", (file: TAbstractFile) =>
this.modifyEventHandler(file),
),
);
}
updateScriptPath() {
if (this.scriptPath === this.plugin.settings.scriptFolderPath) {
return;
}
if (this.scriptPath) {
this.unloadScripts();
}
this.loadScripts();
this.clearCompiledScripts();
this.autostartAttachments = new WeakMap();
void this.reloadScripts();
}
public getListofScripts(): TFile[] {
@@ -163,19 +384,210 @@ export class ScriptEngine {
return;
}
this.scriptPath = normalizePath(this.scriptPath);
if (!this.app.vault.getAbstractFileByPath(this.scriptPath)) {
if (!this.app.vault.getFolderByPath(this.scriptPath)) {
return;
}
return this.app.vault
.getFiles()
.filter(
(f: TFile) =>
f.path.startsWith(`${this.scriptPath}/`) && f.extension === "md",
);
return getPreferredScriptFiles(
this.app.vault
.getFiles()
.filter(
(file) =>
this.isInScriptFolder(file.path) && this.isScriptPath(file.path),
),
);
}
loadScripts() {
this.getListofScripts()?.forEach((f) => this.loadScript(f));
async loadScripts(
generation: number = this.scriptRegistryGeneration,
): Promise<void> {
await Promise.all(
this.getListofScripts()?.map((file) =>
this.loadScript(file, generation),
) ?? [],
);
}
/** Reloads the script command and toolbar registry after discovery changes. */
public async reloadScripts(): Promise<void> {
const generation = ++this.scriptRegistryGeneration;
this.unloadScripts();
await this.loadScripts(generation);
if (generation !== this.scriptRegistryGeneration) {
return;
}
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
* included. Same-named destination files are reported and skipped.
*/
public getScriptFileMigrationPlan(
targetExtension: ScriptFileExtension,
): ScriptFileRenamePlan {
const sourceExtension = targetExtension === "js" ? "md" : "js";
const scriptFolder = normalizePath(
this.plugin.settings.scriptFolderPath.trim(),
);
const scriptFolderPrefix = scriptFolder ? `${scriptFolder}/` : "";
const renamesBySource = new Map<
string,
ScriptFileRenamePlan["renames"][number]
>();
if (scriptFolderPrefix) {
this.app.vault
.getFiles()
.filter(
(file) =>
file.path.startsWith(scriptFolderPrefix) &&
file.extension.toLowerCase() === sourceExtension,
)
.forEach((file) => {
renamesBySource.set(file.path, {
file,
sourcePath: file.path,
destinationPath: replaceScriptFileExtension(
file.path,
targetExtension,
),
});
});
}
const resolvedStartupPath = resolveConfiguredStartupScriptPath(
this.plugin.settings.startupScriptPath,
);
if (resolvedStartupPath?.toLowerCase().endsWith(`.${sourceExtension}`)) {
const startupFile = this.app.vault.getFileByPath(resolvedStartupPath);
if (startupFile) {
const destinationPath = replaceScriptFileExtension(
startupFile.path,
targetExtension,
);
if (!renamesBySource.has(startupFile.path)) {
renamesBySource.set(startupFile.path, {
file: startupFile,
sourcePath: startupFile.path,
destinationPath,
});
}
}
}
const renames: ScriptFileRenamePlan["renames"] = [];
const conflicts: string[] = [];
for (const rename of renamesBySource.values()) {
if (this.app.vault.getAbstractFileByPath(rename.destinationPath)) {
conflicts.push(rename.sourcePath);
} else {
renames.push(rename);
}
}
return {
renames,
conflicts,
includesStartupScript: Boolean(
resolvedStartupPath &&
renames.some(({ sourcePath }) => sourcePath === resolvedStartupPath),
),
};
}
/**
* Applies a previously confirmed script-extension migration. File events
* are suppressed during the batch, pinned paths and the startup path are
* updated atomically with settings, and completed renames are rolled back
* if a later rename or settings write fails.
*/
public async migrateScriptFiles(plan: ScriptFileRenamePlan): Promise<number> {
for (const rename of plan.renames) {
if (
rename.file.path !== rename.sourcePath ||
this.app.vault.getAbstractFileByPath(rename.destinationPath)
) {
throw new Error(`Script migration plan is stale: ${rename.sourcePath}`);
}
}
const originalPinnedScripts = [...this.plugin.settings.pinnedScripts];
const originalStartupScriptPath = this.plugin.settings.startupScriptPath;
const destinationBySource = new Map(
plan.renames.map(({ sourcePath, destinationPath }) => [
sourcePath,
destinationPath,
]),
);
const resolvedStartupPath = resolveConfiguredStartupScriptPath(
originalStartupScriptPath,
);
const completed: ScriptFileRenamePlan["renames"] = [];
this.scriptFileEventsSuspended = true;
try {
for (const rename of plan.renames) {
await this.app.fileManager.renameFile(
rename.file,
rename.destinationPath,
);
completed.push(rename);
}
this.plugin.settings.pinnedScripts = originalPinnedScripts.map(
(path) => destinationBySource.get(path) ?? path,
);
const startupDestinationPath = resolvedStartupPath
? destinationBySource.get(resolvedStartupPath)
: null;
if (startupDestinationPath) {
this.plugin.settings.startupScriptPath = startupDestinationPath;
}
await this.plugin.saveSettings();
return completed.length;
} catch (error: unknown) {
this.plugin.settings.pinnedScripts = originalPinnedScripts;
this.plugin.settings.startupScriptPath = originalStartupScriptPath;
for (const rename of completed.reverse()) {
try {
await this.app.fileManager.renameFile(rename.file, rename.sourcePath);
} catch (rollbackError: unknown) {
errorlog({
where: "ScriptEngine.migrateScriptFiles.rollback",
sourcePath: rename.sourcePath,
error: rollbackError,
});
}
}
throw error;
} finally {
this.scriptFileEventsSuspended = false;
this.clearCompiledScripts();
this.autostartAttachments = new WeakMap();
await this.reloadScripts();
}
}
/**
* Renames one managed script to the requested local extension while keeping
* pinned-script and startup-script paths synchronized.
*/
public async renameManagedScriptFile(
file: TFile,
destinationPath: string,
): Promise<void> {
const sourcePath = file.path;
const startupScriptPath = resolveConfiguredStartupScriptPath(
this.plugin.settings.startupScriptPath,
);
await this.migrateScriptFiles({
renames: [{ file, sourcePath, destinationPath }],
conflicts: [],
includesStartupScript: startupScriptPath === sourcePath,
});
}
public getScriptName(f: TFile | string): string {
@@ -210,11 +622,17 @@ export class ScriptEngine {
);
}
async addScriptIconToMap(scriptPath: string, name: string) {
async addScriptIconToMap(
scriptPath: string,
name: string,
generation: number = this.scriptRegistryGeneration,
): Promise<void> {
const svgFilePath = getIMGFilename(scriptPath, "svg");
const file = this.app.vault.getAbstractFileByPath(svgFilePath);
const svgString: string =
file && file instanceof TFile ? await this.app.vault.read(file) : null;
const file = this.app.vault.getFileByPath(svgFilePath);
const svgString: string = file ? await this.app.vault.read(file) : null;
if (generation !== this.scriptRegistryGeneration) {
return;
}
this.scriptIconMap = {
...this.scriptIconMap,
};
@@ -227,12 +645,15 @@ export class ScriptEngine {
this.updateToolPannels();
}
loadScript(f: TFile) {
if (f.extension !== "md") {
async loadScript(
f: TFile,
generation: number = this.scriptRegistryGeneration,
): Promise<void> {
if (!this.isScriptPath(f.path)) {
return;
}
const scriptName = this.getScriptName(f);
void this.addScriptIconToMap(f.path, scriptName);
const iconLoad = this.addScriptIconToMap(f.path, scriptName, generation);
this.plugin.addCommand({
id: scriptName,
name: `(Script) ${scriptName}`,
@@ -244,25 +665,19 @@ export class ScriptEngine {
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
void (async () => {
const script = stripYamlFrontmatter(await this.app.vault.read(f));
if (script) {
await this.executeScript(view, script, scriptName, f);
}
})();
void this.executeScriptFile(view, f, scriptName);
return true;
}
return false;
},
});
this.loadedScriptPaths.add(f.path);
await iconLoad;
}
unloadScripts() {
const scripts = this.app.vault
.getFiles()
.filter((f: TFile) => f.path.startsWith(this.scriptPath));
scripts.forEach((f) => {
this.unloadScript(this.getScriptName(f), f.path);
Array.from(this.loadedScriptPaths).forEach((path) => {
this.unloadScript(this.getScriptName(path), path);
});
}
@@ -330,26 +745,51 @@ export class ScriptEngine {
}
/**
* Reads and executes a single autostart-permitted script against a single
* view, catching and logging its own error so one bad script never
* affects the caller's other scripts/views. Shared by
* `attachAutostartScriptToOpenViews()` and `runAutostartScripts()`.
* Ensures one automatic attachment per script path and view. A successful
* attachment remains recorded for that view; a failed one is removed so a
* later automatic request can retry. Manual execution bypasses this method.
*/
private async runAutostartScriptInView(
private async ensureViewAutostartAttachment(
scriptName: string,
file: TFile,
view: ExcalidrawView,
where: string,
): Promise<void> {
try {
const script = stripYamlFrontmatter(await this.app.vault.read(file));
if (script) {
await this.executeScript(view, script, scriptName, file);
let attachments = this.autostartAttachments.get(view);
if (!attachments) {
attachments = new Map();
this.autostartAttachments.set(view, attachments);
}
const scriptPath = file.path;
const existing = attachments.get(scriptPath);
if (existing !== undefined) {
await existing;
return;
}
let succeeded = false;
const run = (async (): Promise<void> => {
try {
await this.executeScriptFile(
view,
file,
scriptName,
"view-autostart",
);
succeeded = true;
} catch (error: unknown) {
errorlog({ where, scriptName, error });
}
await this.recordAutostartResult(scriptName, false);
} catch (error: unknown) {
errorlog({ where, scriptName, error });
await this.recordAutostartResult(scriptName, true);
try {
await this.recordAutostartResult(scriptName, !succeeded);
} catch (error: unknown) {
errorlog({ where: `${where}.recordAutostartResult`, scriptName, error });
}
})();
attachments.set(scriptPath, run);
await run;
if (!succeeded && attachments.get(scriptPath) === run) {
attachments.delete(scriptPath);
}
}
@@ -357,8 +797,8 @@ export class ScriptEngine {
* Called by `ExcalidrawAutomate.registerAutostart()` right after a script
* is freshly granted autostart permission, so the script attaches to
* every other currently-open Excalidraw view immediately instead of only
* the next time each view is opened. Reuses the same `executeScript()`
* path `runAutostartScripts()` uses for newly-opened views; one script
* the next time each view is opened. Reuses the same compiled-file path
* `runAutostartScripts()` uses for newly-opened views; one script
* failing does not affect the others.
*/
public attachAutostartScriptToOpenViews(
@@ -373,7 +813,7 @@ export class ScriptEngine {
(view) => view !== excludeView,
);
views.forEach((view) => {
void this.runAutostartScriptInView(
void this.ensureViewAutostartAttachment(
scriptName,
file,
view,
@@ -400,7 +840,7 @@ export class ScriptEngine {
if (!file) {
return;
}
void this.runAutostartScriptInView(
void this.ensureViewAutostartAttachment(
scriptName,
file,
view,
@@ -410,9 +850,7 @@ export class ScriptEngine {
}
unloadScript(basename: string, path: string) {
if (!path.endsWith(".md")) {
return;
}
this.loadedScriptPaths.delete(path);
delete this.scriptIconMap[path];
this.scriptIconMap = { ...this.scriptIconMap };
this.updateToolPannels();
@@ -430,15 +868,90 @@ export class ScriptEngine {
delete this.app.commands.commands[commandId];
}
async executeScript(
/** Executes a script file through the transparent compiled-code cache. */
public async executeScriptFile(
view: ExcalidrawView = undefined,
file: TFile,
title: string,
executionSource: ScriptExecutionSource = "manual",
): Promise<unknown> {
if (!file || !title) {
return;
}
const executable = await this.getCompiledScript(file);
if (!executable) {
return;
}
return this.executeExecutable(
view,
executable,
title,
file,
executionSource,
);
}
/**
* Executes the configured startup file using the plugin-global EA while
* sharing ScriptEngine's loading, compilation, utilities, and error path.
*/
public async executeStartupScript(
file: TFile,
ea: ExcalidrawAutomate,
): Promise<unknown> {
const executable = await this.getCompiledScript(file);
if (!executable) {
return;
}
return this.executeExecutable(
undefined,
executable,
file.basename,
file,
"plugin-startup",
ea,
false,
false,
);
}
/**
* Executes supplied source with a fresh EA. Raw source remains uncached
* because drawing-onload callers pass code embedded inside another file.
*/
public async executeScript(
view: ExcalidrawView = undefined,
script: string,
title: string,
file: TFile,
) {
executionSource: ScriptExecutionSource = "manual",
): Promise<unknown> {
if (!script || !title) {
return;
}
const executable = this.compileScript(script);
if (!executable) {
return;
}
return this.executeExecutable(
view,
executable,
title,
file,
executionSource,
);
}
private async executeExecutable(
view: ExcalidrawView | undefined,
executable: ScriptExecutable,
title: string,
file: TFile,
executionSource: ScriptExecutionSource,
eaOverride?: ExcalidrawAutomate,
trackEA: boolean = true,
setActiveScript: boolean = true,
): Promise<unknown> {
//addresses the situation when after paste text element IDs are not updated to 8 characters
//linked to onPaste save issue with the false parameter
if (
@@ -452,78 +965,83 @@ export class ScriptEngine {
await view.save(false, true);
}
script = stripYamlFrontmatter(script);
const ea = getEA(view);
this.eaInstances.push(ea);
ea.activeScript = title;
const ea = eaOverride ?? getEA(view);
if (trackEA) {
this.eaInstances.push(ea);
}
if (setActiveScript) {
ea.activeScript = title;
}
//https://stackoverflow.com/questions/45381204/get-asyncfunction-constructor-in-typescript changed tsconfig to es2017
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
let result = null;
//try {
result = await new AsyncFunction("ea", "utils", script)(ea, {
inputPrompt: (
header: string | InputPromptOptions,
placeholder?: string,
value?: string,
buttons?: ButtonDefinition[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
controlsOnTop?: boolean,
draggable?: boolean,
) => {
if (typeof header === "object") {
const options = header;
header = options.header;
placeholder = options.placeholder;
value = options.value;
buttons = options.buttons;
lines = options.lines;
displayEditorButtons = options.displayEditorButtons;
customComponents = options.customComponents;
blockPointerInputOutsideModal = options.blockPointerInputOutsideModal;
controlsOnTop = options.controlsOnTop;
draggable = options.draggable;
}
return ScriptEngine.inputPrompt(
view,
this.plugin,
this.app,
header,
placeholder,
value,
buttons,
lines,
displayEditorButtons,
customComponents,
blockPointerInputOutsideModal,
controlsOnTop,
draggable,
);
},
suggester: (
displayItems: string[],
items: unknown[],
hint?: string,
instructions?: Instruction[],
) =>
ScriptEngine.suggester(
this.app,
displayItems,
items,
hint,
instructions,
),
scriptFile: file,
});
/*} catch (e) {
new Notice(t("SCRIPT_EXECUTION_ERROR"), 4000);
errorlog({ script: this.plugin.ea.activeScript, error: e });
}*/
return result;
const isViewAutostart = executionSource === "view-autostart";
if (isViewAutostart) {
this.viewAutostartEAs.add(ea);
}
try {
return await executable(ea, {
inputPrompt: (
header: string | InputPromptOptions,
placeholder?: string,
value?: string,
buttons?: ButtonDefinition[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
controlsOnTop?: boolean,
draggable?: boolean,
) => {
if (typeof header === "object") {
const options = header;
header = options.header;
placeholder = options.placeholder;
value = options.value;
buttons = options.buttons;
lines = options.lines;
displayEditorButtons = options.displayEditorButtons;
customComponents = options.customComponents;
blockPointerInputOutsideModal =
options.blockPointerInputOutsideModal;
controlsOnTop = options.controlsOnTop;
draggable = options.draggable;
}
return ScriptEngine.inputPrompt(
view,
this.plugin,
this.app,
header,
placeholder,
value,
buttons,
lines,
displayEditorButtons,
customComponents,
blockPointerInputOutsideModal,
controlsOnTop,
draggable,
);
},
suggester: (
displayItems: string[],
items: unknown[],
hint?: string,
instructions?: Instruction[],
) =>
ScriptEngine.suggester(
this.app,
displayItems,
items,
hint,
instructions,
),
scriptFile: file,
executionSource,
});
} finally {
if (isViewAutostart) {
this.viewAutostartEAs.delete(ea);
}
}
}
private updateToolPannels() {
+21 -3
View File
@@ -88,6 +88,7 @@ export class InlineLinkSuggester
private paragraphItems: ParagraphSuggestion[] = [];
private frameItems: FrameSuggestion[] = [];
private tagItems: TagSuggestion[] = [];
private linkItemsLoaded = false;
constructor(
app: App,
@@ -98,8 +99,7 @@ export class InlineLinkSuggester
surpessPlaceholder: boolean = false,
collisionBoundary?: HTMLElement,
) {
const items = getLinkSuggestionsFiltered(app);
super(app, inputEl, items, collisionBoundary);
super(app, inputEl, [], collisionBoundary);
this.plugin = plugin;
this.getSourcePath = getSourcePath;
this.widthHost = widthWrapper ?? inputEl;
@@ -152,7 +152,7 @@ export class InlineLinkSuggester
}
getItems(): InlineSuggestion[] {
return getLinkSuggestionsFiltered(this.app);
return this.items;
}
/**
@@ -205,9 +205,23 @@ export class InlineLinkSuggester
* Refreshes the suggestion data (e.g. when vault changes) without recreating the instance.
*/
public refreshItems() {
if (!this.linkItemsLoaded) {
return;
}
this.items = getLinkSuggestionsFiltered(this.app);
}
/**
* Loads the vault-wide file-link candidates only after a wikilink is active.
*/
private ensureLinkItemsLoaded() {
if (this.linkItemsLoaded) {
return;
}
this.items = getLinkSuggestionsFiltered(this.app);
this.linkItemsLoaded = true;
}
modifyInput(input: string): string {
return input;
}
@@ -248,6 +262,10 @@ export class InlineLinkSuggester
return;
}
if (this.mode === "file") {
this.ensureLinkItemsLoaded();
}
void (async () => {
if (this.mode === "heading") {
await this.loadHeadings(this.activeFile);
+51 -75
View File
@@ -5,26 +5,26 @@ import { setStyle } from "src/utils/styleUtils";
import { isInstanceOfHTMLElement } from "src/utils/typechecks";
declare const mainDocument: Document;
declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;
declare const deliberateCreateElement: (
document: Document,
tagName: string,
) => HTMLElement;
export class ContentSearcher {
private contentDiv: HTMLElement;
private searchBar: HTMLInputElement;
private prevButton: HTMLButtonElement;
private nextButton: HTMLButtonElement;
private exportMarkdown: HTMLButtonElement;
private showHideButton: HTMLButtonElement;
private customElemenentContainer: HTMLDivElement;
private inputContainer: HTMLDivElement;
private customElement: HTMLElement;
private hitCount: HTMLSpanElement;
private searchBarWrapper: HTMLDivElement;
constructor(contentDiv: HTMLElement, customElement?: HTMLElement) {
constructor(contentDiv: HTMLElement) {
this.contentDiv = contentDiv;
this.customElement = customElement;
this.createSearchElements();
this.setupEventListeners();
contentDiv.prepend(this.getSearchBarWrapper());
contentDiv.prepend(this.searchBarWrapper);
}
/**
@@ -68,16 +68,6 @@ export class ContentSearcher {
});
setIcon(this.nextButton, "arrow-down");
this.exportMarkdown = createEl("button", {
cls: ["clickable-icon", "document-search-button"],
attr: {
"aria-label": t("SEARCH_COPY_TO_CLIPBOARD_ARIA"),
"data-tooltip-position": "top",
},
type: "button",
});
setIcon(this.exportMarkdown, "clipboard-copy");
this.showHideButton = createEl("button", {
cls: ["clickable-icon", "document-search-button", "search-visible"],
attr: {
@@ -90,19 +80,12 @@ export class ContentSearcher {
buttonContainer.appendChild(this.prevButton);
buttonContainer.appendChild(this.nextButton);
buttonContainer.appendChild(this.exportMarkdown);
buttonContainer.appendChild(this.showHideButton);
documentSearch.appendChild(this.inputContainer);
documentSearch.appendChild(buttonContainer);
this.searchBarWrapper.appendChild(documentSearch);
this.customElemenentContainer = createDiv();
if (this.customElement) {
this.customElemenentContainer.appendChild(this.customElement);
this.searchBarWrapper.appendChild(this.customElemenentContainer);
}
}
/**
@@ -111,56 +94,11 @@ export class ContentSearcher {
private setupEventListeners(): void {
this.nextButton.onclick = () => this.navigateSearchResults("next");
this.prevButton.onclick = () => this.navigateSearchResults("previous");
this.exportMarkdown.onclick = () => {
const exportContent = this.contentDiv.cloneNode(true) as HTMLElement;
exportContent.querySelector(".excalidraw-search")?.remove();
const childNodes = Array.from(exportContent.childNodes);
const startIndex = childNodes.findIndex(
(node) => isInstanceOfHTMLElement(node) && node.tagName === "HR",
);
const nodesToExport =
startIndex > -1 ? childNodes.slice(startIndex) : childNodes;
// div should never be attached to the DOM
const htmlContainer = deliberateCreateElement(mainDocument, "div");
nodesToExport.forEach((node) => {
htmlContainer.appendChild(node.cloneNode(true));
});
const html = htmlContainer.innerHTML;
function replaceHeading(html: string, level: number): string {
const re = new RegExp(
`<summary class="excalidraw-setting-h${level}">([^<]+)</summary>`,
"g",
);
return html.replaceAll(
re,
`<summary class="excalidraw-setting-h${level}"><h${level}>$1</h${level}></summary>`,
);
}
let x = replaceHeading(html, 1);
x = replaceHeading(x, 2);
x = replaceHeading(x, 3);
x = replaceHeading(x, 4);
x = x.replaceAll(
/<div class="setting-item-name">([^<]+)<\/div>/g,
"<h5>$1</h5>",
);
const md = htmlToMarkdown(x);
void window.navigator.clipboard.writeText(md);
new Notice(t("SEARCH_COPIED_TO_CLIPBOARD"));
};
this.showHideButton.onclick = () => {
const setOpacity = (value: string | null) => {
setStyle(this.inputContainer, { opacity: value });
setStyle(this.prevButton, { opacity: value });
setStyle(this.nextButton, { opacity: value });
setStyle(this.exportMarkdown, { opacity: value });
setStyle(this.customElemenentContainer, { opacity: value });
};
if (this.showHideButton.hasClass("search-visible")) {
this.showHideButton.removeClass("search-visible");
@@ -207,11 +145,49 @@ export class ContentSearcher {
});
}
/**
* Get the search bar wrapper element to add to the DOM
*/
public getSearchBarWrapper(): HTMLElement {
return this.searchBarWrapper;
/** Copies the complete legacy settings DOM as Markdown. */
public copyContentAsMarkdown(): void {
const exportContent = this.contentDiv.cloneNode(true) as HTMLElement;
exportContent.querySelector(".excalidraw-search")?.remove();
exportContent
.querySelectorAll(".excalidraw-declarative-settings-toolbar")
.forEach((toolbar) => toolbar.remove());
const childNodes = Array.from(exportContent.childNodes);
const startIndex = childNodes.findIndex(
(node) => isInstanceOfHTMLElement(node) && node.tagName === "HR",
);
const nodesToExport =
startIndex > -1 ? childNodes.slice(startIndex) : childNodes;
const htmlContainer = deliberateCreateElement(mainDocument, "div");
nodesToExport.forEach((node) => {
htmlContainer.appendChild(node.cloneNode(true));
});
const replaceHeading = (html: string, level: number): string => {
const expression = new RegExp(
`<summary class="excalidraw-setting-h${level}">([^<]+)</summary>`,
"g",
);
return html.replaceAll(
expression,
`<summary class="excalidraw-setting-h${level}"><h${level}>$1</h${level}></summary>`,
);
};
let html = htmlContainer.innerHTML;
for (let level = 1; level <= 4; level++) {
html = replaceHeading(html, level);
}
html = html.replaceAll(
/<div class="setting-item-name">([^<]+)<\/div>/g,
"<h5>$1</h5>",
);
const markdown = htmlToMarkdown(html);
void window.navigator.clipboard.writeText(markdown);
new Notice(t("SEARCH_COPIED_TO_CLIPBOARD"));
}
/**
@@ -239,7 +215,7 @@ export class ContentSearcher {
nodesToReplace.forEach((node) => {
const nodeContent = node.nodeValue;
const newNode = createFragment();
let lastIndex = 0;
let match;
const regex = new RegExp(escapeRegExp(searchTerm), "gi");
+55 -1
View File
@@ -3,6 +3,15 @@ import { DEVICE } from "src/constants/constants";
import type { SelectableFontOption } from "src/types/fontTypes";
import { removeStyle, setStyle } from "src/utils/styleUtils";
declare const deliberateCreateElement: (
document: Document,
tagName: "style",
) => HTMLStyleElement;
type BuiltInFontCssProvider = (
fontFamily: string,
) => Promise<string | null>;
type LoadedPreviewFont = {
document: Document;
face: FontFace;
@@ -21,7 +30,8 @@ const quoteFontFamily = (fontFamily: string): string =>
* The option provider is invoked whenever the menu opens, allowing vault font
* additions, removals, and renames to appear without maintaining a file cache.
* Local font binaries are loaded only for the selected option and visible menu
* rows, and are registered in the document that owns the control.
* rows. Callers may also provide built-in font CSS when their owning document
* does not already receive Excalidraw's window-scoped font registration.
*/
export class FontPickerComponent extends ValueComponent<string> {
public readonly buttonEl: HTMLButtonElement;
@@ -33,12 +43,15 @@ export class FontPickerComponent extends ValueComponent<string> {
private menu: Menu | null = null;
private optionObserver: IntersectionObserver | null = null;
private readonly loadedPreviewFonts = new Map<string, LoadedPreviewFont>();
private readonly builtInPreviewStyles = new Map<string, HTMLStyleElement>();
private readonly builtInPreviewLoads = new Map<string, Promise<void>>();
private readonly handleClick = (): void => this.openMenu();
public constructor(
containerEl: HTMLElement,
private readonly app: App,
private readonly getOptions: () => SelectableFontOption[],
private readonly getBuiltInFontCss?: BuiltInFontCssProvider,
) {
super();
this.buttonEl = containerEl.createEl("button", {
@@ -97,6 +110,11 @@ export class FontPickerComponent extends ValueComponent<string> {
loaded.document.fonts.delete(loaded.face);
}
this.loadedPreviewFonts.clear();
for (const styleElement of this.builtInPreviewStyles.values()) {
styleElement.remove();
}
this.builtInPreviewStyles.clear();
this.builtInPreviewLoads.clear();
this.buttonEl.remove();
}
@@ -232,6 +250,42 @@ export class FontPickerComponent extends ValueComponent<string> {
return;
}
setStyle(element, { fontFamily: quoteFontFamily(family) });
if (!option.fontFile) {
void this.ensureBuiltInPreviewFont(family).catch((): void => undefined);
}
}
private async ensureBuiltInPreviewFont(fontFamily: string): Promise<void> {
if (
!this.getBuiltInFontCss ||
this.builtInPreviewStyles.has(fontFamily)
) {
return;
}
const pendingLoad = this.builtInPreviewLoads.get(fontFamily);
if (pendingLoad !== undefined) {
await pendingLoad;
return;
}
const load = this.loadBuiltInPreviewFont(fontFamily).finally(() => {
this.builtInPreviewLoads.delete(fontFamily);
});
this.builtInPreviewLoads.set(fontFamily, load);
await load;
}
private async loadBuiltInPreviewFont(fontFamily: string): Promise<void> {
const css = await this.getBuiltInFontCss?.(fontFamily);
if (!css || !this.buttonEl.isConnected) {
return;
}
const doc = this.buttonEl.ownerDocument;
const styleElement = deliberateCreateElement(doc, "style");
styleElement.textContent = css;
doc.head.appendChild(styleElement);
this.builtInPreviewStyles.set(fontFamily, styleElement);
await doc.fonts.load(`20px ${quoteFontFamily(fontFamily)}`);
}
private ensureLocalPreviewFont(file: TFile): string | null {
+1
View File
@@ -105,6 +105,7 @@ export interface ViewSemaphores {
//flag to prevent overwriting the changes the user makes in an embeddable view editing the back side of the drawing
embeddableIsEditingSelf: boolean;
popoutUnload: boolean; //the unloaded Excalidraw view was the last leaf in the popout window
windowMigrating: boolean; //the current runtime is being replaced after its container moved between windows
viewloaded: boolean; //onLayoutReady in view.onload has completed.
viewunload: boolean;
//first time initialization of the view
+140
View File
@@ -0,0 +1,140 @@
/**
* Type-only compatibility boundary for Obsidian's declarative settings API.
*
* The project intentionally remains compiled against Obsidian 1.8.7. These
* structural types mirror only the Obsidian 1.13.0 surface used by the
* settings migration and must not be treated as evidence that the methods are
* available at runtime. Keep runtime calls behind
* {@link getDeclarativeSettingTabRuntime}.
*
* Features introduced after 1.13.0 are deliberately excluded. When the
* pinned Obsidian dependency eventually includes these declarations, replace
* this file with type-only imports from `obsidian`.
*/
import type {
PluginSettingTab,
Setting,
} from "obsidian";
type SettingControlBase<V, K extends string> = {
key: K;
defaultValue?: V;
validate?: (value: V) => string | void | Promise<string | void>;
disabled?: boolean | (() => boolean);
};
type SettingToggleControl<K extends string> = SettingControlBase<boolean, K> & {
type: "toggle";
};
type SettingDropdownControl<K extends string> = SettingControlBase<string, K> & {
type: "dropdown";
options: Record<string, string>;
};
type SettingTextControl<K extends string> = SettingControlBase<string, K> & {
type: "text";
placeholder?: string;
};
type SettingSliderControl<K extends string> = SettingControlBase<number, K> & {
type: "slider";
min: number;
max: number;
step: number;
};
type SettingControl<K extends string> =
| SettingToggleControl<K>
| SettingDropdownControl<K>
| SettingTextControl<K>
| SettingSliderControl<K>;
type SettingDefinitionBase = {
name: string;
desc?: string | DocumentFragment;
aliases?: string[];
searchable?: boolean | (() => boolean);
visible?: boolean | (() => boolean);
};
type SettingDefinitionControl<K extends string> = SettingDefinitionBase & {
control: SettingControl<K>;
action?: never;
render?: never;
};
/** Minimal structural surface passed to a declarative `render` callback. */
interface SettingGroupLike {
listEl: HTMLElement;
}
type SettingDefinitionRender = SettingDefinitionBase & {
render: (
setting: Setting,
group: SettingGroupLike,
) => void | (() => void);
action?: never;
control?: never;
};
export type SettingDefinition<K extends string = string> =
| SettingDefinitionControl<K>
| SettingDefinitionRender;
type SettingDefinitionPage<K extends string = string> = {
type: "page";
name: string;
desc?: string | DocumentFragment;
items?: SettingDefinitionItem<K>[];
visible?: boolean | (() => boolean);
};
/**
* Minimal Obsidian 1.13.0 definition union used by this migration.
*
* This is intentionally a local structural equivalent rather than an
* augmentation of the installed Obsidian 1.8.7 module.
*/
export type SettingDefinitionItem<K extends string = string> =
| SettingDefinition<K>
| SettingDefinitionPage<K>;
/**
* Obsidian 1.13.0 methods required by the declarative settings adapter.
* Their presence must be checked at runtime before use.
*/
export interface DeclarativeSettingTabRuntime<K extends string = string> {
getSettingDefinitions(): SettingDefinitionItem<K>[];
getControlValue(key: string): unknown;
setControlValue(key: string, value: unknown): void | Promise<void>;
update(): void;
refreshDomState(): void;
}
const DECLARATIVE_SETTING_TAB_METHODS = [
"getSettingDefinitions",
"getControlValue",
"setControlValue",
"update",
"refreshDomState",
] as const satisfies readonly (keyof DeclarativeSettingTabRuntime)[];
/**
* Returns the Obsidian 1.13.0 declarative settings facade when every required
* runtime method exists, otherwise returns `null` for the legacy path.
*/
export function getDeclarativeSettingTabRuntime<K extends string = string>(
tab: PluginSettingTab,
): (PluginSettingTab & DeclarativeSettingTabRuntime<K>) | null {
const candidate = tab as unknown as Record<string, unknown>;
if (
!DECLARATIVE_SETTING_TAB_METHODS.every(
(method) => typeof candidate[method] === "function",
)
) {
return null;
}
return tab as PluginSettingTab & DeclarativeSettingTabRuntime<K>;
}
+33 -1
View File
@@ -9,6 +9,7 @@ import {
Component,
EventRef,
WorkspaceContainer,
PluginSettingTab,
} from "obsidian";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import { ExcalidrawLib } from "./excalidrawLib";
@@ -45,7 +46,23 @@ type ObsidianInternalPluginsManager = {
type ObsidianSettingsManager = {
open(): void;
findTabById?(tabId: string): PluginSettingTab | null;
openTabById(tabId: string): void;
/**
* Resolves a settings-tab identifier and opens its declarative page path.
* This is an unpublished Obsidian 1.13+ API and may be absent or change
* without notice; callers must guard it at runtime.
*/
openPagePath?(
tabId: string,
pagePath: string[],
): PluginSettingTab | null;
/**
* Opens a declarative settings page for a resolved tab object and localized
* page-name path. This is an unpublished Obsidian 1.13+ API and may be
* absent or change without notice; callers must guard it at runtime.
*/
navigateToPage?(tab: PluginSettingTab, pagePath: string[]): void;
};
type ObsidianViewRegistry = {
@@ -128,10 +145,25 @@ export type ConnectionPoint = "top" | "bottom" | "left" | "right" | null;
export type Packages = {
react: typeof import("react");
reactDOM: typeof import("react-dom/client");
reactDOM: typeof import("react-dom") & typeof import("react-dom/client");
excalidrawLib: typeof ExcalidrawLib | null;
};
/**
* An idempotent handle for the shared runtime acquired by one view.
*
* @remarks
* The captured window remains the view's acquisition window even if Obsidian
* reparents its DOM before teardown completes. All leases share the one package
* evaluated in the main application realm, so lifecycle code must use `window`
* for migration ownership and never infer package evaluation ownership from it.
*/
export type PackageLease = {
readonly window: Window;
readonly packages: Packages;
release(): void;
};
export type ValueOf<T> = T[keyof T];
export type DynamicStyle = "none" | "gray" | "colorful";
+3 -1
View File
@@ -57,7 +57,9 @@ export class CustomMutationObserver {
}
};
this.observer = new MutationObserver(wrappedCallback);
const Observer =
target.ownerDocument?.defaultView?.MutationObserver ?? MutationObserver;
this.observer = new Observer(wrappedCallback);
// Start observing with the modified callback
this.observer.observe(target, options);
+24 -7
View File
@@ -3,13 +3,30 @@ import type { SelectableFontOption } from "src/types/fontTypes";
const LOCAL_FONT_EXTENSIONS = ["ttf", "woff", "woff2", "otf"];
export const MARKDOWN_FONT_FAMILIES = [
"Virgil",
"Cascadia",
"Excalifont",
"Comic Shanns",
"Liberation Sans",
] as const;
const MARKDOWN_FONT_FAMILY_IDS = {
Virgil: 1,
Cascadia: 3,
Excalifont: 5,
"Comic Shanns": 8,
"Liberation Sans": 9,
} as const;
type MarkdownFontFamily = keyof typeof MARKDOWN_FONT_FAMILY_IDS;
export const MARKDOWN_FONT_FAMILIES: readonly MarkdownFontFamily[] =
Object.freeze(
Object.keys(MARKDOWN_FONT_FAMILY_IDS) as MarkdownFontFamily[],
);
/** Returns Excalidraw's numeric identifier for a built-in Markdown font. */
export function getMarkdownFontFamilyId(fontFamily: string): number | null {
return Object.prototype.hasOwnProperty.call(
MARKDOWN_FONT_FAMILY_IDS,
fontFamily,
)
? MARKDOWN_FONT_FAMILY_IDS[fontFamily as MarkdownFontFamily]
: null;
}
/** Returns vault font files that are eligible for user-selectable font lists. */
export function getSelectableFontFiles(
+61
View File
@@ -0,0 +1,61 @@
import { normalizePath, type TFile } from "obsidian";
export type ScriptFileExtension = "md" | "js";
/** Returns whether a path names a supported Excalidraw Automate script file. */
export const isScriptFilePath = (path: string): boolean =>
/\.(?:md|js)$/i.test(path);
/** Returns a script path with its final `.md` or `.js` suffix replaced. */
export const replaceScriptFileExtension = (
path: string,
extension: ScriptFileExtension,
): string =>
isScriptFilePath(path)
? path.replace(/\.(?:md|js)$/i, `.${extension}`)
: path;
/** Returns the filename stem shared by equivalent `.md` and `.js` scripts. */
export const getScriptFileStem = (filename: string): string =>
filename.replace(/\.(?:md|js)$/i, "");
/**
* Collapses equivalent `.md` and `.js` paths to one script, preferring the
* Markdown file when both exist.
*/
export const getPreferredScriptFiles = (files: Iterable<TFile>): TFile[] => {
const filesByStem = new Map<string, TFile>();
for (const file of files) {
const stem = getScriptFileStem(file.path);
const existing = filesByStem.get(stem);
if (
!existing ||
(existing.extension.toLowerCase() === "js" &&
file.extension.toLowerCase() === "md")
) {
filesByStem.set(stem, file);
}
}
return Array.from(filesByStem.values());
};
/**
* Returns the extension used for locally managed scripts. JavaScript storage
* is effective only when JavaScript script loading is also enabled.
*/
export const getManagedScriptFileExtension = (
allowJavaScriptFiles: boolean,
storeScriptFilesAsJavaScript: boolean,
): ScriptFileExtension =>
allowJavaScriptFiles && storeScriptFilesAsJavaScript ? "js" : "md";
/** Resolves a configured startup path while preserving the `.md` default. */
export const resolveConfiguredStartupScriptPath = (
configuredPath: string,
): string | null => {
const path = normalizePath(configuredPath.trim());
if (!path) {
return null;
}
return isScriptFilePath(path) ? path : `${path}.md`;
};
+33 -11
View File
@@ -8,6 +8,10 @@ import { errorlog } from "./coreUtils";
import { getIMGFilename, createOrOverwriteFile } from "./fileUtils";
import { hideElement, setButtonBgColor, showElement } from "./styleUtils";
import type ExcalidrawPlugin from "src/core/main";
import {
getManagedScriptFileExtension,
getScriptFileStem,
} from "./scriptFileUtils";
export const installButton = async (
plugin: ExcalidrawPlugin,
@@ -61,13 +65,17 @@ export const installButton = async (
});
}
const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
const scriptStem = getScriptFileStem(fname);
const folder = `${plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
const downloaded = plugin.app.vault
.getFiles()
.filter((f) => f.path.startsWith(folder) && f.name === fname)
.sort((a, b) => (a.path > b.path ? 1 : -1));
let scriptFile = downloaded[0];
const scriptPath = scriptFile?.path ?? `${folder}/${fname}`;
const 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();
const svgPath = getIMGFilename(scriptPath, "svg");
let svgFile = plugin.app.vault.getFileByPath(svgPath);
setButtonText(scriptFile ? "CHECKING" : "INSTALL");
@@ -89,6 +97,19 @@ export const installButton = 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(
scriptFile,
scriptPath,
);
}
}
scriptFile = await download(source, scriptFile, scriptPath);
if (!scriptFile) {
setButtonText("ERROR");
@@ -97,7 +118,7 @@ export const installButton = async (
svgFile = await download(getIMGFilename(source, "svg"), svgFile, svgPath);
setButtonText("UPTODATE");
if (Object.keys(plugin.scriptEngine.scriptIconMap).length === 0) {
plugin.scriptEngine.loadScripts();
await plugin.scriptEngine.loadScripts();
}
const restartSidepanelTabIfActive = async () => {
if (!plugin.scriptEngine || !(scriptFile instanceof TFile)) {
@@ -110,7 +131,7 @@ export const installButton = async (
}
try {
await spView.restartTabForScript(scriptName);
} catch (error) {
} catch (error: unknown) {
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.restartSidepanelTab",
@@ -121,7 +142,7 @@ export const installButton = async (
};
await restartSidepanelTabIfActive();
new Notice(`Installed: ${scriptFile.basename}`);
} catch (e) {
} catch (e: unknown) {
new Notice(`Error installing script: ${fname}`);
errorlog({
where:
@@ -141,11 +162,12 @@ export const installButton = async (
}
const files = new Map<string, number>();
JSON.parse(
const directoryInfo = JSON.parse(
await request({
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
}),
).forEach((f: RemoteDirectoryInfo) => files.set(f.fname, f.mtime));
) as RemoteDirectoryInfo[];
directoryInfo.forEach((file) => files.set(file.fname, file.mtime));
const checkModifyDate = (
gitFilename: string,
+13 -1
View File
@@ -15,10 +15,22 @@ export type SliderSetting = {
export const createSliderWithText = (
container: HTMLElement,
settings: SliderSetting,
): void => {
configureSliderWithText(new Setting(container), settings);
};
/**
* Configures an existing setting row with the plugin's slider-plus-value UI.
* This supports declarative `render` callbacks, where Obsidian owns creation
* of the row but the plugin must preserve its established slider layout.
*/
export const configureSliderWithText = (
setting: Setting,
settings: SliderSetting,
): void => {
let valueText: HTMLDivElement;
new Setting(container)
setting
.setName(settings.name)
.setDesc(settings.desc || "")
.addSlider((slider) =>
+22 -14
View File
@@ -53,6 +53,11 @@ import { getEmptyDrawingElementsRuntime } from "src/constants/emptydrawing";
import { makeEntitiesXmlSafe, sanitizedFragment } from "./htmlUtils";
import { URLs } from "src/constants/safeUrls";
import { isInstanceOfSVGSVGElement } from "./typechecks";
import {
getPreferredScriptFiles,
getScriptFileStem,
isScriptFilePath,
} from "./scriptFileUtils";
export { arrayToMap };
export { errorlog, getDataURL } from "./coreUtils";
export { addAppendUpdateCustomData } from "./elementCustomDataUtils";
@@ -159,10 +164,14 @@ async function checkScriptUpdates() {
return;
}
const folder = `${EXCALIDRAW_PLUGIN.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}/`;
const installedScripts = EXCALIDRAW_PLUGIN.app.vault
.getFiles()
.filter((f) => f.path.startsWith(folder) && f.extension === "md");
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;
@@ -185,24 +194,23 @@ async function checkScriptUpdates() {
// Check if any installed scripts have updates
const updates: string[] = [];
let hasUpdates = false;
for (const scriptFile of installedScripts) {
const filename = scriptFile.name;
if (files.has(filename)) {
const mtime = files.get(filename);
if (mtime > scriptFile.stat.mtime) {
updates.push(scriptFile.path.split(folder)?.[1]?.split(".md")[0]);
hasUpdates = true;
}
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 (hasUpdates) {
if (updates.length > 0) {
const message = `${t("SCRIPT_UPDATES_AVAILABLE")}\n\n${updates.sort().join("\n")}`;
new Notice(message, 8000 + updates.length * 1000);
log(message);
}
} catch (e) {
} catch (e: unknown) {
log({ where: "Utils/checkScriptUpdates", error: e });
}
}
+760 -290
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -956,7 +956,7 @@ function RenderObsidianView({
if (!leafRef.current) {
return;
}
view.canvasNodeFactory.removeNode(leafRef.current.node);
view.canvasNodeFactory.removeNode(leafRef.current.node, element.id);
leafRef.current.leaf?.detach();
leafRef.current = null;
}; //cleanup on unmount
+1 -1
View File
@@ -3,7 +3,6 @@ import {
ExcalidrawInitialDataState,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { DEVICE, obsidianToExcalidrawMap } from "../../constants/constants";
import { t } from "../../lang/helpers";
import { isMarkdownImageElement } from "../../shared/MarkdownImage";
@@ -163,6 +162,7 @@ export function createExcalidrawRootElement(
React.createElement(
Excalidraw,
{
ownerDocument: view.ownerDocument,
onExcalidrawAPI: (api) => view.setExcalidrawAPI(api),
onInitialize: (api) => view.onExcalidrawInitialize(api),
UIOptions: {
+2 -3
View File
@@ -219,11 +219,10 @@ export class ObsidianMenu {
void (async () => {
const f = this.view.app.vault.getAbstractFileByPath(key);
if (f && f instanceof TFile) {
await this.plugin.scriptEngine.executeScript(
await this.plugin.scriptEngine.executeScriptFile(
this.view,
await this.view.app.vault.read(f),
this.plugin.scriptEngine.getScriptName(f),
f,
this.plugin.scriptEngine.getScriptName(f),
);
}
})();
@@ -74,6 +74,13 @@ export class SelectedElementActionsMenu {
this.hide();
return;
}
// Frame-title editing uses the same space above the frame as the selected-element
// action menu. Clear the cached selection so actions are recomputed as soon as
// editing ends, even when the frame itself remains selected throughout.
if (appState.editingFrame === selectedId) {
this.hide();
return;
}
const selectionChanged = selectedId !== this.selectedElementId;
if (selectionChanged) {
@@ -148,7 +155,8 @@ export class SelectedElementActionsMenu {
cls: "ToolIcon_type_button ToolIcon_size_small ToolIcon_type_button--show ToolIcon",
attr: {
type: "button",
title: action.title,
// A title attribute adds a native browser tooltip alongside the
// styled Excalidraw tooltip. Keep the accessible name only.
"aria-label": action.title,
},
});
+2 -3
View File
@@ -465,11 +465,10 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
}
const f = plugin.app.vault.getAbstractFileByPath(key);
if (f && f instanceof TFile) {
void plugin.scriptEngine.executeScript(
void plugin.scriptEngine.executeScriptFile(
view,
await plugin.app.vault.read(f),
plugin.scriptEngine.getScriptName(f),
f,
plugin.scriptEngine.getScriptName(f),
);
}
}
+18 -2
View File
@@ -207,11 +207,27 @@ export class CanvasNodeFactory {
}
}
removeNode(node: ObsidianCanvasNode) {
/**
* Removes a Canvas node and releases the factory's reference to it.
*
* The optional element ID is the map's canonical key. The identity check
* prevents a stale React cleanup from deleting a replacement node that was
* already registered for the same Excalidraw element.
*/
public removeNode(node: ObsidianCanvasNode, elementId?: string) {
if (!this.initialized || !node) {
return;
}
this.nodes.delete(node.file.path);
if (elementId && this.nodes.get(elementId) === node) {
this.nodes.delete(elementId);
} else {
for (const [registeredElementId, registeredNode] of this.nodes) {
if (registeredNode === node) {
this.nodes.delete(registeredElementId);
break;
}
}
}
this.canvas.removeNode(node);
node.detach();
}
@@ -565,6 +565,7 @@ export class ViewLinkNavigationManager {
keys,
view: this.view,
sourceElement: el,
followObsidianNewNoteLocation: true,
}).open();
return;
}
+529
View File
@@ -0,0 +1,529 @@
import { Notice } from "obsidian";
import type { AppState } from "@zsviczian/excalidraw/types/excalidraw/types";
import { t } from "../../lang/helpers";
import type ExcalidrawView from "../ExcalidrawView";
/** Side effects selected for one save request. */
export interface SaveSideEffectPolicy {
triggerAutoexport: boolean;
}
/** Terminal outcome reported by the view-owned persistence implementation. */
export type SaveExecutionStatus =
| "persisted"
| "window-migration-handed-off"
| "window-migration-persisted"
| "view-unload-scheduled"
| "unchanged"
| "skipped"
| "failed";
/** Result used by the coordinator to advance the saved revision safely. */
export interface SaveExecutionResult {
status: SaveExecutionStatus;
}
/** Clean durability baseline transferred with a migrated drawing. */
export interface ViewSaveMigrationState {
currentRevision: number;
savedRevision: number;
}
/** Side effects selected for one forced-save request. */
export interface ForceSavePolicy {
refreshSceneFiles: boolean;
triggerAutoexport: boolean;
}
export const DIRECT_SAVE_SIDE_EFFECT_POLICY: Readonly<SaveSideEffectPolicy> = {
triggerAutoexport: true,
};
export const PUBLIC_FORCE_SAVE_POLICY: Readonly<ForceSavePolicy> = {
refreshSceneFiles: true,
triggerAutoexport: true,
};
export const WINDOW_BLUR_FORCE_SAVE_POLICY: Readonly<ForceSavePolicy> = {
refreshSceneFiles: false,
// Autoexport is a documented save-time contract, including for blur-triggered saves.
triggerAutoexport: true,
};
/** Private view operations retained by the composition root during the
* mechanical coordinator extraction. */
export interface ViewSaveCoordinatorDependencies {
performSave: (
preventReload: boolean,
forcesave: boolean,
overrideEmbeddableIsEditingSelfDebounce: boolean,
sideEffectPolicy: Readonly<SaveSideEffectPolicy>,
) => Promise<SaveExecutionResult>;
requestSave: (
preventReload?: boolean,
forcesave?: boolean,
overrideEmbeddableIsEditingSelfDebounce?: boolean,
) => Promise<void>;
isDirty: () => boolean;
checkSceneVersion: () => void;
refreshCanvasOffset: () => void;
getFreedrawLastActiveTimestamp: () => number;
markDirtyVisuals: () => void;
clearDirtyVisuals: () => void;
}
interface SaveRequest {
preventReload: boolean;
forcesave: boolean;
overrideEmbeddableIsEditingSelfDebounce: boolean;
sideEffectPolicy: Readonly<SaveSideEffectPolicy>;
revision: number;
}
/**
* Coordinates persistence entry points, dirty state, and autosave scheduling
* for one Excalidraw view.
*
* The view retains its public facade and the `TextFileView.save()` disk-write
* implementation. Durable edit revisions prevent a completed save from
* clearing newer changes, and one merged trailing request bounds concurrent
* persistence work without dropping edits made while a save is in flight.
*/
export class ViewSaveCoordinator {
public autosaveTimer: number | null = null;
public autosaveFunction: (() => void) | null = null;
private currentRevision = 0;
private savedRevision = 0;
private activeSaveRevision: number | null = null;
private pendingSaveRequest: SaveRequest | null = null;
private saveLoopPromise: Promise<void> | null = null;
public constructor(
private readonly view: ExcalidrawView,
private readonly dependencies: ViewSaveCoordinatorDependencies,
) {}
/** Runs the historical public save policy. */
public async save(
preventReload: boolean = true,
forcesave: boolean = false,
overrideEmbeddableIsEditingSelfDebounce: boolean = false,
): Promise<void> {
await this.enqueueSave({
preventReload,
forcesave,
overrideEmbeddableIsEditingSelfDebounce,
sideEffectPolicy: DIRECT_SAVE_SIDE_EFFECT_POLICY,
revision: this.currentRevision,
});
}
private enqueueSave(request: SaveRequest): Promise<void> {
if (this.pendingSaveRequest) {
this.pendingSaveRequest = this.mergeSaveRequests(
this.pendingSaveRequest,
request,
);
} else {
this.pendingSaveRequest = request;
}
if (this.saveLoopPromise !== null) {
return this.saveLoopPromise;
}
const loop = Promise.resolve().then(() => this.drainSaveQueue());
const trackedLoop = loop.finally(() => {
if (this.saveLoopPromise === trackedLoop) {
this.saveLoopPromise = null;
}
});
this.saveLoopPromise = trackedLoop;
return trackedLoop;
}
private mergeSaveRequests(
current: SaveRequest,
incoming: SaveRequest,
): SaveRequest {
const selected =
current.forcesave && !incoming.forcesave ? current : incoming;
return {
...selected,
forcesave: current.forcesave || incoming.forcesave,
overrideEmbeddableIsEditingSelfDebounce:
current.overrideEmbeddableIsEditingSelfDebounce ||
incoming.overrideEmbeddableIsEditingSelfDebounce,
sideEffectPolicy: {
triggerAutoexport:
current.sideEffectPolicy.triggerAutoexport ||
incoming.sideEffectPolicy.triggerAutoexport,
},
revision: Math.max(current.revision, incoming.revision),
};
}
private async drainSaveQueue(): Promise<void> {
let completedRequest = false;
while (this.pendingSaveRequest) {
const request = this.pendingSaveRequest;
this.pendingSaveRequest = null;
if (
completedRequest &&
!request.forcesave &&
request.revision <= this.savedRevision
) {
continue;
}
this.activeSaveRevision = request.revision;
try {
const result = await this.dependencies.performSave(
request.preventReload,
request.forcesave,
request.overrideEmbeddableIsEditingSelfDebounce,
request.sideEffectPolicy,
);
this.completeSaveRevision(request, result);
} finally {
this.activeSaveRevision = null;
}
completedRequest = true;
}
}
private completeSaveRevision(
request: SaveRequest,
result: SaveExecutionResult,
): void {
if (
result.status === "persisted" ||
result.status === "window-migration-handed-off" ||
result.status === "window-migration-persisted" ||
result.status === "view-unload-scheduled" ||
result.status === "unchanged"
) {
this.savedRevision = Math.max(this.savedRevision, request.revision);
this.reconcileDirtyState();
}
}
private queueTrailingSave(): void {
const request: SaveRequest = {
preventReload: true,
forcesave: false,
overrideEmbeddableIsEditingSelfDebounce: false,
sideEffectPolicy: DIRECT_SAVE_SIDE_EFFECT_POLICY,
revision: this.currentRevision,
};
this.pendingSaveRequest = this.pendingSaveRequest
? this.mergeSaveRequests(this.pendingSaveRequest, request)
: request;
}
private reconcileDirtyState(): void {
if (this.currentRevision > this.savedRevision) {
this.view.semaphores.dirty = this.view.file?.path;
this.dependencies.markDirtyVisuals();
return;
}
if (this.view.semaphores.viewunload || !this.view.excalidrawAPI) {
return;
}
this.view.semaphores.dirty = null;
this.dependencies.clearDirtyVisuals();
}
/** Runs the historical public force-save policy. */
public async forceSave(
silent: boolean = false,
waitIfBusy: boolean = false,
): Promise<void> {
await this.forceSaveWithPolicy(
silent,
waitIfBusy,
PUBLIC_FORCE_SAVE_POLICY,
);
}
/** Runs a forced save with an explicitly selected side-effect policy. */
public async forceSaveWithPolicy(
silent: boolean,
waitIfBusy: boolean,
policy: Readonly<ForceSavePolicy>,
): Promise<void> {
if (waitIfBusy) {
let counter = 0;
while (
(this.view.semaphores.autosaving ||
this.view.semaphores.saving ||
this.saveLoopPromise !== null) &&
counter++ < 100
) {
await sleep(50);
}
}
if (
this.view.semaphores.autosaving ||
this.view.semaphores.saving ||
this.saveLoopPromise !== null
) {
if (!silent) {
new Notice(t("FORCE_SAVE_ABORTED"));
}
return;
}
this.view.clearPreventReloadTimer();
this.view.semaphores.preventReload = false;
this.view.semaphores.forceSaving = true;
await this.enqueueSave({
preventReload: false,
forcesave: true,
overrideEmbeddableIsEditingSelfDebounce: true,
sideEffectPolicy: {
triggerAutoexport: policy.triggerAutoexport,
},
revision: this.currentRevision,
});
if (this.view.semaphores.windowMigrating) {
this.view.semaphores.forceSaving = false;
return;
}
this.view.plugin.triggerEmbedUpdates();
if (policy.refreshSceneFiles) {
await this.view.loadSceneFiles();
}
this.view.semaphores.forceSaving = false;
if (!silent) {
new Notice("Save successful", 1000);
}
}
/** Saves scene changes found during view teardown or navigation. */
public async forceSaveIfRequired(): Promise<boolean> {
let watchdog = 0;
let dirty = false;
if (!this.view.excalidrawAPI) {
return false;
}
this.dependencies.checkSceneVersion();
if (!this.dependencies.isDirty()) {
if (!this.view.semaphores.saving && this.saveLoopPromise === null) {
return false;
}
// Preserve the existing Excalibrain unload compatibility check.
if (
this.view.hookServer &&
this.view.hookServer.onViewUnloadHook?.toString() ===
"e=>{this.scene&&this.scene.leaf===e.leaf&&this.stop()}"
) {
return false;
}
}
if (this.saveLoopPromise !== null) {
dirty = true;
await this.saveLoopPromise;
} else {
while (this.view.semaphores.saving && watchdog++ < 200) {
dirty = true;
await sleep(40);
}
}
if (this.view.excalidrawAPI) {
this.dependencies.checkSceneVersion();
if (this.dependencies.isDirty()) {
const path = this.view.file?.path;
const plugin = this.view.plugin;
window.setTimeout(() => {
plugin.triggerEmbedUpdates(path);
}, 400);
dirty = true;
await this.flush();
}
}
return dirty;
}
/** Waits for queued saves, then persists any revision still left dirty. */
public async flush(): Promise<void> {
if (this.saveLoopPromise !== null) {
await this.saveLoopPromise;
}
if (!this.isDirty()) {
return;
}
await this.enqueueSave({
preventReload: true,
forcesave: true,
overrideEmbeddableIsEditingSelfDebounce: true,
sideEffectPolicy: DIRECT_SAVE_SIDE_EFFECT_POLICY,
revision: this.currentRevision,
});
}
/** Starts the recursive autosave timer with the existing scheduling rules. */
public setupAutosaveTimer(): void {
const timer = () => {
void (async () => {
if (!this.view.isLoaded) {
this.autosaveTimer = window.setTimeout(
timer,
this.view.autosaveInterval,
);
return;
}
const api = this.view.excalidrawAPI;
if (!api) {
new Notice(t("WARNING_SERIOUS_ERROR"), 60000);
return;
}
const st = api.getAppState() as AppState;
const isFreedrawActive =
st.activeTool?.type === "freedraw" &&
this.dependencies.getFreedrawLastActiveTimestamp() >
Date.now() - 2000;
const isEditingText = st.editingTextElement !== null;
const isEditingNewElement = st.newElement !== null;
this.dependencies.refreshCanvasOffset();
if (
this.dependencies.isDirty() &&
this.view.plugin.autosaveEnabled &&
!this.view.semaphores.forceSaving &&
!this.view.semaphores.autosaving &&
!this.view.semaphores.embeddableIsEditingSelf &&
!isFreedrawActive &&
!isEditingText &&
!isEditingNewElement
) {
this.autosaveTimer = null;
if (this.view.excalidrawAPI) {
this.view.semaphores.autosaving = true;
// Preserve the non-blocking save used to avoid lag on large files.
void this.dependencies
.requestSave()
.then(() => (this.view.semaphores.autosaving = false));
}
this.autosaveTimer = window.setTimeout(
timer,
this.view.autosaveInterval,
);
} else {
this.autosaveTimer = window.setTimeout(
timer,
this.view.plugin.activeExcalidrawView === this.view &&
this.view.semaphores.dirty &&
this.view.plugin.autosaveEnabled
? 1000
: this.view.autosaveInterval,
);
}
})();
};
this.autosaveFunction = timer;
this.resetAutosaveTimer();
}
/** Restarts the autosave interval after a completed save or first edit. */
public resetAutosaveTimer(): void {
if (!this.autosaveFunction) {
return;
}
if (this.autosaveTimer) {
window.clearTimeout(this.autosaveTimer);
this.autosaveTimer = null;
}
this.autosaveTimer = window.setTimeout(
this.autosaveFunction,
this.view.autosaveInterval,
);
}
/** Cancels autosave work owned by this view. */
public destroy(): void {
if (this.autosaveTimer) {
window.clearTimeout(this.autosaveTimer);
this.autosaveTimer = null;
}
this.autosaveFunction = null;
}
/** Advances the edit revision and queues one trailing save when necessary. */
public setDirty(): void {
if (this.view.semaphores.saving && this.activeSaveRevision === null) {
return;
}
if (!this.dependencies.isDirty()) {
this.resetAutosaveTimer();
}
this.currentRevision += 1;
this.view.semaphores.dirty = this.view.file?.path;
this.dependencies.markDirtyVisuals();
if (this.saveLoopPromise !== null) {
this.queueTrailingSave();
}
}
/** Returns whether the dirty marker belongs to the current file. */
public isDirty(): boolean {
return (
this.currentRevision > this.savedRevision &&
Boolean(this.view.semaphores?.dirty) &&
this.view.semaphores.dirty === this.view.file?.path
);
}
/** Clears the current file's dirty marker and updates its clean baseline. */
public clearDirty(): void {
if (
this.saveLoopPromise !== null ||
this.view.semaphores.viewunload ||
!this.view.excalidrawAPI
) {
return;
}
this.currentRevision += 1;
this.savedRevision = this.currentRevision;
this.view.semaphores.dirty = null;
this.dependencies.clearDirtyVisuals();
}
/** Exports a settled revision baseline for a migration handoff. */
public exportMigrationState(): ViewSaveMigrationState | null {
if (
this.saveLoopPromise !== null ||
this.activeSaveRevision !== null ||
this.pendingSaveRequest !== null ||
this.currentRevision !== this.savedRevision ||
this.isDirty()
) {
return null;
}
return {
currentRevision: this.currentRevision,
savedRevision: this.savedRevision,
};
}
/** Adopts a validated, settled durability baseline in a new view. */
public adoptMigrationState(state: ViewSaveMigrationState): boolean {
if (
this.saveLoopPromise !== null ||
this.activeSaveRevision !== null ||
this.pendingSaveRequest !== null ||
!Number.isSafeInteger(state.currentRevision) ||
!Number.isSafeInteger(state.savedRevision) ||
state.currentRevision < 0 ||
state.savedRevision < 0 ||
state.currentRevision !== state.savedRevision
) {
return false;
}
this.currentRevision = state.currentRevision;
this.savedRevision = state.savedRevision;
this.view.semaphores.dirty = null;
this.dependencies.clearDirtyVisuals();
return true;
}
}
+180 -48
View File
@@ -1,4 +1,7 @@
import type { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import type {
ExcalidrawImperativeAPI,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import type {
DeferredCacheValidation,
@@ -23,6 +26,63 @@ export interface ViewSceneFileManagerDependencies {
addFiles: typeof import("../ExcalidrawView").addFiles;
}
/** Waits for two frames in the current view window, with a bounded fallback. */
export const waitForWindowPaint = (
getOwnerWindow: () => Window,
): Promise<void> =>
new Promise((resolve) => {
let settled = false;
const finish = () => {
if (settled) {
return;
}
settled = true;
window.clearTimeout(fallbackTimer);
resolve();
};
const fallbackTimer = window.setTimeout(finish, 250);
try {
const ownerWindow = getOwnerWindow();
ownerWindow.requestAnimationFrame(() => {
ownerWindow.requestAnimationFrame(finish);
});
} catch {
finish();
}
});
/** Returns image file IDs intersecting the view's current scene viewport. */
export const getVisibleImageFileIds = (
view: ExcalidrawView,
): Set<FileId> => {
const visibleFileIds = new Set<FileId>();
const appState = view.excalidrawAPI?.getAppState();
if (!appState) {
return visibleFileIds;
}
const zoom = appState.zoom.value;
const left = -appState.scrollX;
const top = -appState.scrollY;
const right = left + appState.width / zoom;
const bottom = top + appState.height / zoom;
for (const element of view.getViewElements()) {
if (
element.type === "image" &&
!element.isDeleted &&
element.fileId &&
element.x + element.width >= left &&
element.y + element.height >= top &&
element.x <= right &&
element.y <= bottom
) {
visibleFileIds.add(element.fileId);
}
}
return visibleFileIds;
};
/**
* Owns the embedded-file loading pipeline (RefactorPlan.md Phase 6,
* "ViewSceneFileManager"): the active/next loader pair, the deferred
@@ -65,6 +125,21 @@ export class ViewSceneFileManager {
private readonly dependencies: ViewSceneFileManagerDependencies,
) {}
private isRuntimeCurrent(
api: ExcalidrawImperativeAPI,
filePath: string | null,
): boolean {
// A replacement view can open the same file while callbacks from the
// source window are still queued, so file identity alone is insufficient.
return (
this.view.excalidrawAPI === api &&
!api.isDestroyed &&
!this.view.semaphores?.windowMigrating &&
!this.view.semaphores?.viewunload &&
(this.view.file?.path ?? null) === filePath
);
}
/** Terminates any in-flight loaders and cancels deferred validation. Called
* from `ExcalidrawView.onClose()`, `onunload()`, and `clear()`. */
public terminateActiveLoaders(): void {
@@ -112,11 +187,15 @@ export class ViewSceneFileManager {
emitPolicy: "changed-only" | "all" = "changed-only",
) {
this.cancelDeferredSceneFileValidation();
const api = this.view.excalidrawAPI;
if (
!candidates ||
candidates.size === 0 ||
!this.view.file ||
!this.view.excalidrawAPI
!api ||
api.isDestroyed ||
this.view.semaphores?.windowMigrating ||
this.view.semaphores?.viewunload
) {
return;
}
@@ -127,11 +206,9 @@ export class ViewSceneFileManager {
this.deferredValidationFilePath = currentFile;
this.deferredValidationTimer = window.setTimeout(() => {
this.deferredValidationTimer = null;
if (
!this.view.file ||
!this.view.excalidrawAPI ||
this.view.file.path !== currentFile
) {
if (!this.isRuntimeCurrent(api, currentFile)) {
loader.terminate = true;
loader.emptyPDFDocsMap();
this.deferredValidationFilePath = null;
return;
}
@@ -147,12 +224,10 @@ export class ViewSceneFileManager {
isDark: boolean,
final: boolean = true,
) => {
if (
!this.view.file ||
!this.view.excalidrawAPI ||
this.view.file.path !== currentFile
) {
if (final && this.deferredValidationLoader === loader) {
if (!this.isRuntimeCurrent(api, currentFile)) {
loader.terminate = true;
loader.emptyPDFDocsMap();
if (this.deferredValidationLoader === loader) {
this.deferredValidationLoader = null;
this.deferredValidationFilePath = null;
}
@@ -197,7 +272,15 @@ export class ViewSceneFileManager {
isThemeChange: boolean = false,
forceEmitFromCache: boolean = false,
) {
if (!this.view.excalidrawAPI || !fileIDs || fileIDs.size === 0) {
const api = this.view.excalidrawAPI;
if (
!api ||
api.isDestroyed ||
this.view.semaphores?.windowMigrating ||
this.view.semaphores?.viewunload ||
!fileIDs ||
fileIDs.size === 0
) {
return;
}
if (this.activeLoader) {
@@ -229,11 +312,19 @@ export class ViewSceneFileManager {
callback?: () => void,
forceReloadFileIDs?: Set<FileId>,
) {
if (!this.view.excalidrawAPI) {
const requestAPI = this.view.excalidrawAPI;
if (
!requestAPI ||
requestAPI.isDestroyed ||
this.view.semaphores?.windowMigrating ||
this.view.semaphores?.viewunload
) {
return;
}
const requestFilePath = this.view.file?.path ?? null;
const requestIsCurrent = () =>
this.isRuntimeCurrent(requestAPI, requestFilePath);
const deferredValidationForSameFile =
!!requestFilePath &&
this.deferredValidationFilePath === requestFilePath &&
@@ -259,8 +350,20 @@ export class ViewSceneFileManager {
const loader = this.dependencies.createEmbeddedFilesLoader();
const runLoader = (l: EmbeddedFilesLoader) => {
if (!requestIsCurrent()) {
l.terminate = true;
l.emptyPDFDocsMap();
if (this.activeLoader === l) {
this.activeLoader = null;
}
if (this.nextLoader === l) {
this.nextLoader = null;
}
return;
}
this.nextLoader = null;
this.activeLoader = l;
const prioritizedFileIds = getVisibleImageFileIds(this.view);
void l.loadSceneFiles({
excalidrawData: this.view.excalidrawData,
sceneElements: this.view.getViewElements(),
@@ -269,12 +372,20 @@ export class ViewSceneFileManager {
isDark: boolean,
final: boolean = true,
) => {
if (!requestIsCurrent()) {
l.terminate = true;
l.emptyPDFDocsMap();
if (this.activeLoader === l) {
this.activeLoader = null;
}
if (this.nextLoader === l) {
this.nextLoader = null;
}
return;
}
if (callback && final) {
callback();
}
if (!this.view.file || !this.view.excalidrawAPI) {
return; //The view was closed in the mean time
}
if (files && files.length > 0) {
void this.dependencies.addFiles(files, this.view, isDark);
}
@@ -282,9 +393,12 @@ export class ViewSceneFileManager {
return;
}
this.view.lastSceneLoadTime = Date.now();
this.activeLoader = null;
if (this.activeLoader === l) {
this.activeLoader = null;
}
if (this.nextLoader) {
runLoader(this.nextLoader);
const nextLoader = this.nextLoader;
runLoader(nextLoader);
} else {
// Once the scene is painted, validate cached candidates in the background
// so unchanged cache hits do not delay the initial scene load.
@@ -292,39 +406,54 @@ export class ViewSceneFileManager {
this.scheduleDeferredSceneFileValidation(
new Map(this.pendingDeferredValidationCandidates),
isThemeChange,
"changed-only",
);
this.pendingDeferredValidationCandidates.clear();
}
//in case one or more files have not loaded retry later hoping that sync has delivered the file in the mean time.
this.view.excalidrawData.getFiles().some((ef) => {
if (ef && !ef.file && ef.attemptCounter < 30) {
const currentFile = this.view.file.path;
const retryLoadSceneFiles = () => {
if (
!this ||
!this.view.excalidrawAPI ||
currentFile !== this.view.file.path
) {
return;
}
// Keep deferred validation uninterrupted. If it is running,
// retry again once it completes.
if (
this.deferredValidationLoader ||
this.deferredValidationTimer
) {
window.setTimeout(retryLoadSceneFiles, 500);
return;
}
void this.loadSceneFiles();
};
window.setTimeout(() => {
retryLoadSceneFiles();
}, 2000);
return true;
}
return false;
});
const retryCandidates = Array.from(
this.view.excalidrawData.getFileEntries(),
).filter(
([, embeddedFile]) =>
embeddedFile &&
!embeddedFile.file &&
!embeddedFile.isHyperLink &&
!embeddedFile.isLocalLink &&
embeddedFile.attemptCounter < 30,
);
if (retryCandidates.length > 0) {
const retryFileIDs = new Set(
retryCandidates.map(([fileId]) => fileId),
);
const currentFile = this.view.file.path;
const retryLoadSceneFiles = () => {
if (
!this ||
!requestIsCurrent() ||
currentFile !== this.view.file.path
) {
return;
}
// Keep deferred validation uninterrupted. If it is running,
// retry again once it completes.
if (
this.deferredValidationLoader ||
this.deferredValidationTimer
) {
window.setTimeout(retryLoadSceneFiles, 500);
return;
}
void this.loadSceneFiles(
false,
retryFileIDs,
undefined,
undefined,
);
};
window.setTimeout(() => {
retryLoadSceneFiles();
}, 2000);
}
}
},
depth: 0,
@@ -335,6 +464,9 @@ export class ViewSceneFileManager {
onDeferredValidationCandidates: (candidates) => {
this.addDeferredValidationCandidates(candidates);
},
waitForRender: () =>
waitForWindowPaint(() => this.view.ownerWindow ?? window),
prioritizedFileIds,
});
};
if (!this.activeLoader) {
+13 -4
View File
@@ -520,7 +520,7 @@ export class ExcalidrawSidepanelView extends ItemView {
const previousSilent = ExcalidrawSidepanelView.restoreSilent;
ExcalidrawSidepanelView.restoreSilent = true;
try {
await this.runScriptByName(scriptName, title);
await this.runScriptByName(scriptName, title, "sidepanel-reload");
const restarted = this.getTabByScript(scriptName);
if (wasPersisted && restarted) {
this.markTabPersistent(restarted);
@@ -533,7 +533,12 @@ export class ExcalidrawSidepanelView extends ItemView {
/**
* Executes a script by name to reconstruct its sidepanel tab, updating title if needed.
*/
private async runScriptByName(scriptName: string, title: string) {
private async runScriptByName(
scriptName: string,
title: string,
executionSource: "sidepanel-restore" | "sidepanel-reload" =
"sidepanel-restore",
) {
const scriptEngine = this.plugin.scriptEngine;
if (!scriptEngine) {
return;
@@ -548,8 +553,12 @@ export class ExcalidrawSidepanelView extends ItemView {
return;
}
try {
const script = await this.plugin.app.vault.read(file);
await scriptEngine.executeScript(undefined, script, scriptName, file);
await scriptEngine.executeScriptFile(
undefined,
file,
scriptName,
executionSource,
);
const restoredTab = this.scriptTabs.get(scriptName);
if (restoredTab) {
restoredTab.setTitle(title);
+126 -27
View File
@@ -723,29 +723,6 @@ root {
--excalidraw-caret-color: initial;
}
.excalidraw-settings-links-container {
align-items: center;
color: inherit;
display: flex;
gap: .3em;
text-align: center;
text-decoration: none;
flex-wrap: wrap;
justify-content: center;
flex-direction: row;
}
.excalidraw-settings-links-container a {
display: flex;
/* Align children horizontally */
align-items: center;
/* Center items vertically */
text-align: left;
margin-right: 4px;
margin-left: 4px;
}
.excalidraw-settings-links-container svg,
.ex-setting-actions-container svg {
margin-right: 8px;
height: 30px;
@@ -1119,6 +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);
}
.excalidraw-pen-settings-floating-actions {
position: sticky;
bottom: -20px;
@@ -1633,7 +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;
}
.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;
}
}