mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-11-27 06:32:42 +00:00
Compare commits
71
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f9b8093250 | ||
|
|
ff728e0023 | ||
|
|
9d26574170 | ||
|
|
f25410e686 | ||
|
|
65ac23d9b3 | ||
|
|
1c8b10130a | ||
|
|
4e7f46993c | ||
|
|
e6f3e59aec | ||
|
|
ed60ee1ddf | ||
|
|
76bc65f664 | ||
|
|
992f14797a | ||
|
|
af6824d9ac | ||
|
|
402023519f | ||
|
|
d1e6a73e8b | ||
|
|
ad6b2b8b4d | ||
|
|
fe8a96ee7f | ||
|
|
f1bf213898 | ||
|
|
9be221a313 | ||
|
|
58081803a1 | ||
|
|
ba0e66888c | ||
|
|
0a92beec06 | ||
|
|
c1d471bb1f | ||
|
|
529d584f01 | ||
|
|
98b8aa2eba | ||
|
|
8f58faaa0d | ||
|
|
e9305f3501 | ||
|
|
052dfe3c12 | ||
|
|
59f655ed46 | ||
|
|
1f20425f3d | ||
|
|
06647f8ea3 | ||
|
|
5127f78def | ||
|
|
7f136e0618 | ||
|
|
e079827dd3 | ||
|
|
d848084b59 | ||
|
|
5bbf266455 | ||
|
|
fc4f91339f | ||
|
|
1ae56692aa | ||
|
|
d1f87855e4 | ||
|
|
04eee5f373 | ||
|
|
c121056558 | ||
|
|
cd1d243ac5 | ||
|
|
0214eaed59 | ||
|
|
0245964a04 | ||
|
|
a2263bc253 | ||
|
|
a932f10e90 | ||
|
|
da124f019b | ||
|
|
6f1f277ed9 | ||
|
|
d7dd08fad6 | ||
|
|
355d7c2d46 | ||
|
|
b9d12c09e3 | ||
|
|
7a1a0d75ee | ||
|
|
263c09d07b | ||
|
|
39346559ce | ||
|
|
e4e9df0a49 | ||
|
|
149e1e5bf0 | ||
|
|
0da7120a7d | ||
|
|
d94b3b19ad | ||
|
|
169ceb3cf3 | ||
|
|
ded91c6882 | ||
|
|
4ce81be081 | ||
|
|
740ee455d3 | ||
|
|
81fbbf42b7 | ||
|
|
ba6c45d621 | ||
|
|
1c76170bad | ||
|
|
4d60ce9263 | ||
|
|
d513935523 | ||
|
|
01fcb09f83 | ||
|
|
57240da793 | ||
|
|
91e78ec1ae | ||
|
|
648a2a8ed8 | ||
|
|
83c8493c02 |
No files matched your search
@@ -72,7 +72,12 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
|
||||
## DOM Styling And Visibility
|
||||
|
||||
- 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;`.
|
||||
- Never use `document.createElement()`, `Document.createElement()`, or `Document.createDocumentFragment()`. Prefer Obsidian's `createEl()`, `createDiv()`, `createSpan()`, `createSvg()`, and `createFragment()` helpers, following these established patterns:
|
||||
- Create detached typed rendering elements whose owning document is irrelevant through a fragment, for example `const canvas = createFragment().createEl("canvas")` or `const image = createFragment().createEl("img")`.
|
||||
- Before creating a temporary wrapper solely for serialization, check whether the consumer accepts a `DocumentFragment` or DOM node directly. For example, `htmlToMarkdown()` accepts a fragment; clone and transform that detached tree before passing it to the consumer. Do not substitute `XMLSerializer` without verifying that its XML serialization is equivalent to the required HTML representation.
|
||||
- Register known runtime font sources through document-scoped `FontFace` objects and `document.fonts.add()`/`delete()`. Preserve descriptors such as `unicodeRange`, retain each face for replacement and cleanup, and do not build a generic CSS parser merely to translate arbitrary stylesheet text into `FontFace` objects.
|
||||
- `setCssProps()`/`setCssStyles()` are suitable for dynamic declarations on one element, not for CSS requiring selectors, pseudo-elements, at-rules, or arbitrary rule text. Creating the same `<style>` through `createEl("style")` does not resolve the separate CodeScanner policy finding for dynamic style elements.
|
||||
- `deliberateCreateElement`, injected by `rollup.config.mjs`, is restricted to the remaining reviewed `<style>` cases: document-scoped runtime stylesheets that cannot be represented as element declarations, and styles that must belong to an iframe's `contentDocument`, where Obsidian's DOM helpers are not installed. Do not broaden this exception without first exhausting the patterns above and documenting why document-specific native creation is intrinsic. Track the upstream policy discussion in [obsidianmd/eslint-plugin#196](https://github.com/obsidianmd/eslint-plugin/issues/196).
|
||||
- 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.
|
||||
@@ -206,7 +211,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 and the Excalidraw package are separate compressed payloads. React must remain external to the Excalidraw artifact, because the plugin inflates one matching private React runtime and supplies it 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
|
||||
|
||||
@@ -233,9 +238,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.
|
||||
|
||||
@@ -252,11 +257,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.
|
||||
- The bundle bootstrap inflates and indirectly evaluates one compressed private React/ReactDOM payload in the main application realm before module-level React consumers run. `src/core/managers/PackageManager.ts` then evaluates one Excalidraw artifact and leases the combined shared 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.
|
||||
- The React runtime is built from official npm entry points, inflated once during bundle bootstrap, and kept in plugin/package lexical scope. Do not 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
|
||||
|
||||
@@ -406,10 +416,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 compressed 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.
|
||||
- It is fine to import React for types, component definitions, JSX compilation, and nearby established patterns. The plugin build resolves those imports through the inflated private runtime; the library build and separately built Excalidraw artifact keep React external.
|
||||
- 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.
|
||||
@@ -425,7 +435,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/`
|
||||
@@ -486,7 +496,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
|
||||
|
||||
+2
-2
@@ -70,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 inflates 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 built from official npm entry points, compressed into the plugin, and inflated once during bundle bootstrap. The bootstrap uses a local window alias with the same indirect evaluation mechanism that underlies Excalidraw's error-handled evaluator. They 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.
|
||||
|
||||
|
||||
+312
-49
@@ -27,7 +27,8 @@ validated, and what remains uncertain.
|
||||
| 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 font management | Implemented; awaiting manual validation | `FontManager` now owns CJK discovery/loading, document-scoped custom-font registration, readiness, and cleanup; plugin methods and the externally read `fourthFontLoaded` field remain intact |
|
||||
| Remove avoidable native element creation | Complete | Five detached image/canvas operations now obtain their typed elements from an Obsidian `DocumentFragment`; the two settings-to-Markdown paths pass fragments directly to `htmlToMarkdown()` and perform required heading conversion on cloned DOM; `FontManager` registers only its known CJK/local faces as document-scoped `FontFace` objects with explicit replacement and cleanup. The historical `addFonts(string[])` delegate and its first-pass CSSOM parser were removed after confirming they were neither part of the package entrypoint nor used or documented externally. CJK subsets now retain their source `unicodeRange` descriptors. The seven non-iframe dynamic stylesheet sites and five iframe-owned stylesheet sites remain deliberately unchanged; focused manual testing passed |
|
||||
| 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 |
|
||||
| Remove confirmed dead `main.ts` code | Implemented; awaiting manual validation | Removed the uncalled cache-registration method and the never-assigned duplicate file-explorer observer field/cleanup; the active observer in `ObserverManager` remains unchanged |
|
||||
| Extract view export pipeline | Implemented; awaiting manual validation | `ViewExportManager` now owns raw scene, SVG, PNG, clipboard, PDF, option-resolution, and alternate-theme embedded-file export behavior; all view methods and `exportDialog` compatibility remain intact |
|
||||
@@ -39,11 +40,13 @@ 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 the shared React runtime payload | Implemented; awaiting focused runtime validation | Restored the official-entrypoint React/ReactDOM/JSX nested build after Obsidian CodeScanner exposed three dormant ReactDOM `createElement("script")` branches in the normally bundled production output. Production deflates the runtime at build time, then the bundle bootstrap inflates and indirectly evaluates it once before module-level React consumers run, releases the source string, and supplies the resulting private runtime to the one shared Excalidraw package. Popouts still lease that package rather than evaluating React per window |
|
||||
| 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 |
|
||||
| Keep body-portaled floating UI with its owning Obsidian tab | Implemented; awaiting manual validation | The fork's `ObsidianRadixPortal` keeps its body target for correct fixed positioning in popouts, but its view-owned bridge now mirrors the source Excalidraw container's layout visibility. A hidden tab hides the still-mounted floating content without clearing its canonical open state, and returning to the tab reveals the same popover |
|
||||
| Resolve embeddables with platform-valid filename punctuation | Implemented; awaiting manual validation | Existing-file lookup for Obsidian embeddables now delegates path resolution to Obsidian instead of rejecting a fixed cross-platform character set, so filenames containing characters such as `?` work on operating systems that permit them |
|
||||
| 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` |
|
||||
| Extract `MarkdownImageController` (Phase 6 item 6) | Complete | `src/view/managers/MarkdownImageController.ts` now owns the deletion queue (`queueMarkdownImageDeletion`/`processMarkdownImageDeletionQueue` + its 3 state fields) and the edit/convert trio (`openMarkdownImageEditor`, `convertEmbeddableToMarkdownImage`, `convertMarkdownImageToEmbeddable`). `ExcalidrawView` keeps all three as public delegates (called from `CommandManager`, `ExcalidrawRoot`, and `EmbeddableActionsMenu`), calls `queueMarkdownImageDeletion` from `onExcalidrawIncrement`, and reads `markdownImageController.markdownImageDeletionPrompt` from `save()` exactly where it read the field directly before. Cross-module functions from the existing `ExcalidrawData`/`MarkdownImage`/`MarkdownImageEditor`/`Dialogs/Prompt`/`excalidrawViewUtils` cycle are constructor-injected rather than imported directly, matching the `ViewLinkNavigationManager`/`ViewExcalidrawExtensionRenderer` precedent. Manual testing found no issues |
|
||||
@@ -56,8 +59,19 @@ 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) | Baseline captured; focused diagnostic extension awaiting rerun | The first four runtime captures confirmed expensive large-scene save synchronization/serialization, repeated mostly-no-op `loadSceneFiles()` requests, costly warm image-cache reconstruction, full image reload during popout migration, and the `CanvasNodeFactory.removeNode()` map-key mismatch. The temporary flat-text diagnostics now also tag every view-scoped scene-file request with a stable `reason=`, expose unresolved/missing scene-file counts and retry scheduling/execution, break warm-cache work into IndexedDB/dependency/materialization stages, and provide a manual console checkpoint for before/after forced-GC measurements. No performance behavior has been changed in this checkpoint |
|
||||
| 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 | Superseded by the restored compressed runtime | Commit `39346559ced5aa349388d22954fa9a73a51f2959` established normal React bundling and remains the comparison point. Obsidian CodeScanner later reported the three ReactDOM dynamic-script creation branches that this exposed in `main.js`, so the documented compressed fallback is active again. The single shared-runtime, typed-host, owner-document, lease, migration, and persistence architecture remains unchanged |
|
||||
| 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 |
|
||||
@@ -66,14 +80,173 @@ validated, and what remains uncertain.
|
||||
| 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 |
|
||||
| Ignore inline suggestion portals in the modal-save observer | Complete | `ObserverManager` now saves a dirty active drawing only when the direct body child added to the active view document is an actual `.modal-container`. The inline link suggester's body-portaled `.suggestion-container` no longer masquerades as Settings or the command palette and cannot trigger synchronization/reload while a text element is being edited. Real modal-open persistence, outside-canvas clicks, file menus, leaf changes, window blur, autosave, and view teardown retain their existing save paths. Runtime validation confirmed that `[[` opened and remained usable after duplicating an equation without changing the save counter, while the next real command-palette modal triggered the intended save and durable reopen restored the complete scene |
|
||||
| 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; dirty-signal correction awaiting manual validation | `ViewSaveCoordinator` advances a monotonic current revision from actual element increments, explicitly tracked drawing app-state changes, and existing explicit dirty calls; selection-only history increments no longer mark the drawing dirty. Each save request records its revision 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. The original 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. The corrected dirty-input policy requires the focused 2026-09-02 validation recorded below |
|
||||
| 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-05 | Closed the avoidable native-element-creation checkpoint | Retained the fragment, direct-DOM serialization, and document-scoped `FontFace` solution after the full risk-based manual test pass; documented the accepted patterns and narrowed the Rollup shim rationale to the 12 remaining reviewed style-element cases. No dynamic stylesheet creation was changed | User confirmed all requested font, settings-Markdown, cropped/exported image, screenshot, canvas-snapshot, popout/mobile, and scanner validation passed successfully |
|
||||
| 2026-09-05 | Removed the eight approved `deliberateCreateElement` cases without changing dynamic stylesheet creation | Replaced five detached canvas/image creations with `createFragment().createEl()`, removed the now-unneeded owner-document argument from EA view-PNG cropping, converted the two temporary settings-serialization containers to direct `DocumentFragment` input (with DOM-based heading conversion for the legacy exporter), and replaced `FontManager`'s generated `@font-face` style element with document-owned `FontFace` registrations. A follow-up API audit rejected the first-pass CSSOM parser: `addFonts(string[])` had no source consumer, documentation, or package-entrypoint export and was an accidental historical public method, so its plugin/manager delegates and parser were removed. `getCJKFontFaceData()` now keeps each data URL paired with its original `unicodeRange`; CJK faces remain lazy and the user-selected fourth font retains eager readiness. No `CSSStyleSheet` constructor dependency remains. No `Messages.ts` entry was added. All seven non-iframe dynamic style-element sites and all five iframe-owned style-element sites are untouched | Node 22.22.2 production and library builds pass with the established 33 production circular warnings; the simplified production bundle is 4,872,998 bytes. `node --check dist/main.js`, focused ESLint, unused-symbol lint, and `git diff --check` pass. Repository TypeScript retains its established generated-doc/library/dependency declaration failures and reports no changed-source diagnostic. Generated declarations contain neither `addFonts()` nor the removed parser. The source inventory fell from 20 to 12 `deliberateCreateElement()` calls, all of which create `style` elements: seven intentionally excluded non-iframe sites and five deferred iframe sites. Manual validation pending: local/CJK font registration and cleanup across main/popout documents; declarative and legacy settings Markdown copy fidelity; EA cropped view PNG, crop-mask PNG, desktop screenshot stitching, and Markdown canvas snapshot export, with popout/mobile coverage where applicable |
|
||||
| 2026-09-04 | Allowed embeddables to resolve existing files whose names contain platform-valid punctuation | Traced blank back-of-the-note cards in drawings whose own filename contains `?` to `processLinkText()`: after separating the heading subpath, it applied the shared Windows-style invalid-character expression to the existing vault path and returned `file: null` before calling Obsidian. Removed that pre-resolution blacklist from the embeddable path only; link parsing and heading/block handling are unchanged, creation dialogs still retain their cross-platform filename guidance, and Obsidian's metadata cache remains the source of truth for whether the target exists | An exact transpiled-function regression assertion passes for `Cards/Why?.md#Back`, proving the full path reaches `getFirstLinkpathDest()` and returns the file with `#Back` preserved. Focused ESLint and the Node 22.22.2 production build pass; the build retains the established 33 circular-dependency warnings. Manual validation should open a drawing whose filename contains `?`, insert or reopen its back-of-the-note card, and verify both reading and editing modes; also smoke-test an ordinary same-note card and an embeddable pointing to another Markdown note. macOS/Linux coverage is required because Windows does not permit this filename |
|
||||
| 2026-09-04 | Kept body-portaled Excalidraw menus owned by their source tab without closing them | Reworked the first attempted fix after manual testing showed that clearing each menu's canonical open state lost intentionally persistent UI. The Radix portal still targets the owning document body because nesting its fixed-position wrapper under Excalidraw's transformed Obsidian popout ancestors causes vertical displacement. Its bridge now uses one owner-window `ResizeObserver` on the source container and reversibly mirrors whether that container has a layout box: `display: none` while the tab is hidden and `display: contents` when it returns. The earlier ancestor-wide `MutationObserver`, attribute filters, and child-list tracking were removed as redundant because losing or regaining the source container's rendered box itself triggers resize observation. No dropdown, properties popover, or tool popover receives a close callback, so the same mounted content and open state survive tab switching; ordinary click-outside, Escape, and explicit close paths remain unchanged | Node 22.22.2. The focused portal and legacy Popover suites pass (4 tests) without React warnings; the regression test directly drives the resize-observer callback and verifies that hidden content remains mounted and that the exact DOM node is revealed again. JSON ESLint and Prettier report zero findings in the changed source and test. The fork's `yarn build:obsidian` passes and emits declarations plus all four artifacts. Repository-wide `yarn test:typecheck` retains its established unrelated test backlog with no diagnostic in either changed file. The four generated artifacts were copied into the plugin's ignored installed-package paths; the plugin production build and focused lint pass with the established 33 circular-dependency warnings and produce a 4,871,599-byte `dist/main.js`. Focused Obsidian validation remains the acceptance gate: leave the tray/main menu and each canvas/shape/color/font/tool popover open, switch to another tab and confirm no top-left leak, then return and confirm the same UI is still open and correctly positioned. Repeat in the main window and a popout; also verify click-outside, Escape, dynamic theme/canvas-color changes, and a narrow/mobile layout |
|
||||
| 2026-09-03 | Restored compressed packaging for the single shared React runtime | Reintroduced the nested official-entrypoint React runtime build, production minification/deflation, eager bootstrap inflation/evaluation, official JSX runtime surfaces, and the production `jsxDEV` fallback. React now uses `runtimeWindow.eval.call(...)`, matching the indirect mechanism and neutral receiver shape used by the already-compressed Excalidraw artifact's error-handled evaluator, instead of emitting direct `window.eval(...)` or `new Function()` syntax that CodeScanner may separately recommend against. Eager evaluation is required because module-level icon constants consume React before `PackageManager` is constructed. The inflated source is cleared immediately after evaluation, and `PackageManager` releases its JSX bootstrap references after constructing the one shared Excalidraw package. This deliberately restores only packaging: React is not evaluated per popout, no React/ReactDOM window global is introduced, and the current shared-runtime leases, typed hosts, owner-document boundary, migration, and persistence behavior are unchanged. The change addresses both scanner-visible symptoms of bundling the locally packaged runtime: three dormant ReactDOM `createElement("script")` branches when bundled normally and direct dynamic-execution syntax when compressed | Production, development, and library builds pass under Node 22.22.2; production retains the established 33 circular warnings and development retains its established sourcemap-option warning. The emitted production runtime initializes React 19.2.8 with callable `createRoot`, `jsx`, and `jsxDEV`, immediately releases its inflated source, and leaves `window.React`/`window.ReactDOM` undefined. Bundle syntax, scoped ESLint, unused-symbol lint, dependency deduplication, and CRLF-aware diff checks pass. Full source lint retains exactly the established 123-error/0-warning backlog with no finding in a changed source file. The optional Madge command was unavailable after the dependency tree was restored; this evaluator-only follow-up adds no module edge. `dist/main.js` remains below the normally bundled build, with zero scanner-visible `createElement("script")` calls, zero direct `new Function()` calls, zero direct `eval()` calls, zero direct `window.eval` calls, and zero external React `require(...)` calls. Re-run Obsidian CodeScanner, then manually validate one cold plugin restart, ordinary main-window editing, plugin disable/re-enable, and one dirty main→popout→main round trip. Bootstrap ordering/duplicate React is the highest-impact risk; view migration and persistence logic did not change |
|
||||
| 2026-09-02 | Separated Excalidraw history increments from drawing dirty state | Corrected the Phase 1B.4b assumption that every durable Excalidraw store increment represents a persistence-relevant edit. Selection is intentionally captured by Excalidraw history, but now advances the save revision only when the increment contains element changes. Added an explicit app-state dirty projection for theme, canvas background, grid size/step/mode, custom palettes/top picks, frame rendering, object snapping, the durable binding preference, midpoint snapping, and box-selection mode. Scroll and zoom participate only when **Zoom to fit on file open** is disabled. Transient selection/editor state is excluded. Effective `isBindingEnabled` is neither tracked nor serialized because Excalidraw temporarily derives it from modifier-key state; `bindingPreference` remains the persisted source of truth. Generated `gridColor` does not independently mark the drawing dirty, but remains serialized because `getSceneWithAppState()` also backs the public `getScene()` contract; removing it requires a separate compatibility decision | Production build passes under Node 22.22.2 with the established 33 circular-dependency warnings. Direct tracker assertions cover selection exclusion, equivalent nested values, grid changes, conditional viewport changes, exclusion of modifier-derived `isBindingEnabled`, and inclusion of the durable `bindingPreference`. The new tracker has no ESLint findings; `ExcalidrawView.ts` retains exactly its 18 pre-existing findings. Full source lint retains the established 123-error/0-warning backlog with no finding in the new module. Unused-symbol lint, bundle syntax, Madge, and `git diff --check` pass. Focused runtime validation is pending: selection-only and modifier-only clean state, one real element edit, each tracked app-state family, viewport behavior with zoom-to-fit both enabled and disabled, save/reopen durability, and one dirty popout round trip |
|
||||
| 2026-09-01 | Made the default startup-script asset build-generated | Renamed the misspelled `starutpscript.ts` module to `startupScript.ts` and removed its hand-maintained Base64 literal and Obsidian-console conversion recipe. Every plugin build now reads `src/constants/assets/startupScript.md`, Base64-encodes it in Rollup, and embeds the payload while preserving the existing `startupScript()` runtime contract. Library builds do not read or embed the asset | Production and library builds, Rollup/bundle syntax, exact source-to-embedded-Base64 parity, scoped ESLint, unused-symbol lint, Madge, and `git diff --check` pass. Full source lint retains exactly the established 123-error/0-warning backlog with no finding in either touched TypeScript file. Focused runtime validation should delete or temporarily clear the configured startup-script path, select the settings action that creates the default script, and confirm the created file exactly includes the current lifecycle/cleanup header from the asset |
|
||||
| 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 |
|
||||
@@ -491,24 +664,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
|
||||
|
||||
@@ -522,17 +701,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
|
||||
@@ -769,7 +949,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
|
||||
@@ -784,23 +965,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;
|
||||
@@ -809,16 +976,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.
|
||||
@@ -836,7 +1007,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.
|
||||
@@ -969,6 +1140,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:
|
||||
@@ -1687,8 +1948,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
|
||||
@@ -1907,7 +2168,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. |
|
||||
|
||||
@@ -1924,3 +2185,5 @@ 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. |
|
||||
| 2026-09-04 | Preserved a valid open drawing when synchronized Drawing JSON is malformed | Confirmed the destructive parse/save fallback was already present in tag `2.26.4`, then applied the narrow invariant fix without another `ExcalidrawData`: `loadData()` now performs its existing single scene parse before clearing loaded state, reload stages incoming text until parsing succeeds, and both active synchronization paths log and show a long-lived warning when incoming data is rejected. Forced save now consumes the existing execution result, never reports success for `failed`/`skipped`, and always clears `forceSaving` in `finally`. No recovery-file, post-write validation, conflict-state, or broader persistence layer was added. | Node 22.22.2 production build and `node --check dist/main.js` pass with the established 33 circular warnings; unused-symbol lint and `git diff --check` pass. Targeted ESLint is clean for `FileManager.ts`, `ViewSaveCoordinator.ts`, and `en.ts`; the large `ExcalidrawData.ts`/`ExcalidrawView.ts` files retain only findings outside the changed lines. Repository-wide `tsc --noEmit` retains its existing generated-docs/library/dependency declaration failures and reports no changed-source diagnostic. No executable view/model unit-test harness exists. Manual validation pending: corrupt the synchronized `## Drawing` JSON while a valid dirty canvas is open, once in the active-view merge path and once after the five-minute full-reload threshold; confirm the canvas and dirty marker remain, the warning appears, Ctrl/Cmd+S writes the live scene without a false success on rejection, and navigation still saves. Repeat the full-reload case in a popout; mobile needs one smoke test because the logic is shared but persistence timing differs. |
|
||||
@@ -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 |
|
||||
+3462
-1411
File diff suppressed because it is too large.
Load diff
@@ -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-09-01T18:22:12.027Z
|
||||
|
||||
---
|
||||
|
||||
@@ -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,33 @@ 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()` and `createViewPNG()`, 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 image. When temporarily modifying an existing scene for export, copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
|
||||
* **Use `exportArea` for bounded view exports:** Both view export methods accept `exportArea: {x, y, width, height}`. EA filters the candidate elements with the same logic exposed as `getElementsIntersectionArea()` (and its backward-compatible `getElementsInArea()` alias), retains required bound elements, and anchors the result to that exact viewport. This prevents a small preview or PDF page from retaining every image in a large scene.
|
||||
* **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 +160,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(...)` for vector output or `await ea.createViewPNG(...)` for raster output. Their `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or patch by ID. Use `exportArea` when only a rectangular viewport is needed; it filters out off-area elements and their unused image payloads instead of exporting the full scene and merely changing the SVG viewBox. For temporary changes, 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 +281,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) => {
|
||||
|
||||
+227
@@ -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
@@ -17,11 +17,49 @@ You will be able to access your scripts from Excalidraw via the Obsidian Command
|
||||
|
||||

|
||||
|
||||
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
|
||||
|
||||

|
||||
|
||||
## Script development
|
||||
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
|
||||
|
||||

|
||||
|
||||
## 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,331 +1,573 @@
|
||||
/*
|
||||
# Deconstruct Selected Elements Into New Drawing
|
||||
|
||||

|
||||
|
||||
Select some elements in the scene. The script will take these elements and move them into a new Excalidraw file, and open that file. The selected elements will also be replaced in your original drawing with the embedded Excalidraw file (the one that was just created). You will be prompted for the file name of the new deconstructed image. The script is useful if you want to break a larger drawing into smaller reusable parts that you want to reference in multiple drawings.
|
||||
Select elements in the current Excalidraw scene. The script moves the selected elements into a new Excalidraw file, replaces the original selection with an embedded reference to that new drawing, and optionally opens the new file.
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=HRtaaD34Zzg" target="_blank"><img src ="https://i.ytimg.com/vi/HRtaaD34Zzg/maxresdefault.jpg" style="width:560px;"></a>
|
||||
The modal lets you choose the destination folder, filename, template, whether to open the new drawing, whether to reuse an adjacent tab, and whether the inserted embed should be anchored at 100% size.
|
||||
|
||||
<a href="https://www.youtube.com/watch?v=mvMQcz401yo" target="_blank"><img src ="https://i.ytimg.com/vi/mvMQcz401yo/maxresdefault.jpg" style="width:560px;"></a>
|
||||
Destination names are validated before creation. Filenames reject path separators and characters that are invalid or unsafe across common vault platforms (`\\ / : * ? " < > |` and control characters). Folder paths use `/` only as the path separator and validate each folder name independently.
|
||||
|
||||
```js
|
||||
## Usage
|
||||
|
||||
1. Select one or more elements in an Excalidraw drawing.
|
||||
2. Run **Deconstruct Selected Elements Into New Drawing**.
|
||||
3. Choose the destination folder, file name, and optional template.
|
||||
4. Choose **Insert** or **Insert @100%**.
|
||||
|
||||
The default filename and additional template paths can be configured through the script settings.
|
||||
|
||||
## Original demonstrations
|
||||
|
||||

|
||||

|
||||
|
||||
Build version: 2026-09-04T17:17:37.900Z
|
||||
|
||||
```javascript
|
||||
*/
|
||||
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.7.3")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
|
||||
// -------------------------------
|
||||
// Utility variables and functions
|
||||
// -------------------------------
|
||||
const excalidrawTemplates = ea.getListOfTemplateFiles();
|
||||
if(typeof window.ExcalidrawDeconstructElements === "undefined") {
|
||||
window.ExcalidrawDeconstructElements = {
|
||||
openDeconstructedImage: true,
|
||||
reuseTab: true,
|
||||
templatePath: excalidrawTemplates?.[0]?.path??""
|
||||
};
|
||||
} else if (typeof window.ExcalidrawDeconstructElements.reuseTab === "undefined") {
|
||||
window.ExcalidrawDeconstructElements.reuseTab = true;
|
||||
}
|
||||
|
||||
// Helper class for Folder Autocomplete
|
||||
class FolderSuggest extends ea.obsidian.AbstractInputSuggest {
|
||||
constructor(app, inputEl) {
|
||||
super(app, inputEl);
|
||||
this.inputEl = inputEl;
|
||||
// Script bundle
|
||||
/* EA Script — deconstruct-selected-elements-into-new-drawing | ea-scripts v1.0.0 */
|
||||
(() => {
|
||||
// src/sharedUtils/i18n.ts
|
||||
function interpolateTranslation(template, params = {}) {
|
||||
return Object.entries(params).reduce(
|
||||
(result, [key, value]) => result.split(`{${key}}`).join(String(value)),
|
||||
template
|
||||
);
|
||||
}
|
||||
|
||||
getSuggestions(query) {
|
||||
const folders = app.vault.getAllLoadedFiles().filter(f => f instanceof ea.obsidian.TFolder);
|
||||
const lowerQuery = query.toLowerCase();
|
||||
|
||||
// Filter folders that match the query
|
||||
const matches = folders.filter(f => f.path.toLowerCase().includes(lowerQuery));
|
||||
|
||||
// Custom Sort
|
||||
matches.sort((a, b) => {
|
||||
const aPath = a.path;
|
||||
const bPath = b.path;
|
||||
const aLower = aPath.toLowerCase();
|
||||
const bLower = bPath.toLowerCase();
|
||||
|
||||
// Priority 1: Starts with query (e.g. "Projects" comes before "Hobbies/Projects")
|
||||
const aStarts = aLower.startsWith(lowerQuery);
|
||||
const bStarts = bLower.startsWith(lowerQuery);
|
||||
|
||||
if (aStarts && !bStarts) return -1;
|
||||
if (!aStarts && bStarts) return 1;
|
||||
|
||||
// Priority 2: Alphabetical
|
||||
return aPath.localeCompare(bPath);
|
||||
});
|
||||
|
||||
return matches.map(f => f.path);
|
||||
}
|
||||
|
||||
renderSuggestion(value, el) {
|
||||
el.setText(value);
|
||||
}
|
||||
|
||||
selectSuggestion(value, evt) {
|
||||
this.inputEl.value = value;
|
||||
this.inputEl.dispatchEvent(new Event('input'));
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
|
||||
let settings = ea.getScriptSettings();
|
||||
//set default values on first run
|
||||
if(!settings["Templates"]) {
|
||||
settings = {
|
||||
"Templates" : {
|
||||
value: "",
|
||||
description: "Comma-separated list of template filepaths"
|
||||
}
|
||||
};
|
||||
await ea.setScriptSettings(settings);
|
||||
}
|
||||
|
||||
if(!settings["Default file name"]) {
|
||||
settings["Default file name"] = {
|
||||
value: "deconstructed",
|
||||
description: "The default filename to use when deconstructing elements."
|
||||
};
|
||||
await ea.setScriptSettings(settings);
|
||||
}
|
||||
|
||||
const DEFAULT_FILENAME = settings["Default file name"].value;
|
||||
|
||||
const templates = settings["Templates"]
|
||||
.value
|
||||
.split(",")
|
||||
.map(p=>app.metadataCache.getFirstLinkpathDest(p.trim(),""))
|
||||
.concat(excalidrawTemplates)
|
||||
.filter(f=>Boolean(f))
|
||||
.sort((a,b) => a.basename.localeCompare(b.basename));
|
||||
|
||||
|
||||
// ------------------------------------
|
||||
// Prepare elements to be deconstructed
|
||||
// ------------------------------------
|
||||
const els = ea.getViewSelectedElements();
|
||||
if (els.length === 0) {
|
||||
new Notice("You must select elements first")
|
||||
return;
|
||||
}
|
||||
|
||||
const bb = ea.getBoundingBox(els);
|
||||
ea.copyViewElementsToEAforEditing(els);
|
||||
|
||||
// Handle Image elements logic from original script
|
||||
ea.getElements().filter(el=>el.type==="image").forEach(el=>{
|
||||
const img = ea.targetView.excalidrawData.getFile(el.fileId);
|
||||
const path = (img?.linkParts?.original)??(img?.file?.path);
|
||||
const hyperlink = img?.hyperlink;
|
||||
if(img && (path || hyperlink)) {
|
||||
const colorMap = ea.getColorMapForImageElement(el);
|
||||
ea.imagesDict[el.fileId] = {
|
||||
mimeType: img.mimeType,
|
||||
id: el.fileId,
|
||||
dataURL: img.img,
|
||||
created: img.mtime,
|
||||
file: path,
|
||||
hyperlink,
|
||||
hasSVGwithBitmap: img.isSVGwithBitmap,
|
||||
latex: null,
|
||||
colorMap,
|
||||
function createTranslator(requestedLocale, catalogs, fallbackLocale = "en") {
|
||||
const locale = requestedLocale.toLowerCase().replaceAll("_", "-");
|
||||
const baseLocale = locale.split("-")[0] ?? locale;
|
||||
return (key, params = {}) => {
|
||||
const template = catalogs[locale]?.[key] ?? catalogs[baseLocale]?.[key] ?? catalogs[fallbackLocale]?.[key] ?? key;
|
||||
return interpolateTranslation(template, params);
|
||||
};
|
||||
return;
|
||||
}
|
||||
const equation = ea.targetView.excalidrawData.getEquation(el.fileId);
|
||||
const eqImg = ea.targetView.getScene()?.files[el.fileId]
|
||||
if(equation && eqImg) {
|
||||
ea.imagesDict[el.fileId] = {
|
||||
mimeType: eqImg.mimeType,
|
||||
id: el.fileId,
|
||||
dataURL: eqImg.dataURL,
|
||||
created: eqImg.created,
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/lang/de.ts
|
||||
var de = {};
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/lang/en.ts
|
||||
var en = {
|
||||
requiresNewerVersion: "This script requires Excalidraw 2.27.0 or newer. Please install the latest version.",
|
||||
selectElements: "You must select elements first.",
|
||||
templatesSettingDesc: "Comma-separated list of template filepaths",
|
||||
defaultFilenameSettingDesc: "The default filename to use when deconstructing elements.",
|
||||
modalTitle: "Deconstruct Elements",
|
||||
folderPath: "Folder path",
|
||||
fileName: "File name",
|
||||
selectTemplate: "Select template",
|
||||
noTemplate: "none",
|
||||
openDeconstructedImage: "Open deconstructed image",
|
||||
reuseExistingTab: "Reuse existing tab",
|
||||
reuseExistingTabDesc: "If available, open in an adjacent tab. Otherwise open in a new tab.",
|
||||
insert: "Insert",
|
||||
insertTooltip: "Insert without anchoring",
|
||||
insertAt100: "Insert @100%",
|
||||
insertAt100Tooltip: "Anchor to 100% size",
|
||||
filenameRequired: "Filename is required.",
|
||||
invalidFilenameCharacter: 'File name contains an invalid character: "{character}".',
|
||||
invalidFolderCharacter: 'Folder path contains an invalid character: "{character}".',
|
||||
invalidFilename: 'Invalid file name: "{name}".',
|
||||
invalidFolderPath: 'Invalid folder path near: "{name}".',
|
||||
somethingWentWrong: "Something went wrong while creating the deconstructed drawing.",
|
||||
deconstructionReady: "Deconstruction ready."
|
||||
};
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/lang/es.ts
|
||||
var es = {};
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/lang/fr.ts
|
||||
var fr = {};
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/lang/ru.ts
|
||||
var ru = {};
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/lang/zh-cn.ts
|
||||
var zhCn = {};
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/lang/index.ts
|
||||
var CATALOGS = { en, de, es, fr, ru, "zh-cn": zhCn };
|
||||
function createDeconstructTranslator(locale) {
|
||||
return createTranslator(locale, CATALOGS);
|
||||
}
|
||||
|
||||
// src/sharedUtils/eaEmbeddedFiles.ts
|
||||
function copyImageFile(ea2, element, fileId) {
|
||||
const view = ea2.targetView;
|
||||
if (!view) return false;
|
||||
const image = view.excalidrawData.getFile(fileId);
|
||||
const filePath = image?.linkParts?.original ?? image?.file?.path;
|
||||
const hyperlink = image?.hyperlink;
|
||||
if (!image || !filePath && !hyperlink) return false;
|
||||
ea2.imagesDict[fileId] = {
|
||||
mimeType: image.mimeType,
|
||||
id: fileId,
|
||||
dataURL: image.img,
|
||||
created: image.mtime,
|
||||
file: filePath,
|
||||
hyperlink,
|
||||
hasSVGwithBitmap: image.isSVGwithBitmap,
|
||||
latex: null,
|
||||
colorMap: ea2.getColorMapForImageElement(element)
|
||||
};
|
||||
return true;
|
||||
}
|
||||
function copyEquationFile(ea2, element, fileId) {
|
||||
const view = ea2.targetView;
|
||||
if (!view) return;
|
||||
const equation = view.excalidrawData.getEquation(fileId);
|
||||
const sceneFile = view.getScene()?.files[fileId];
|
||||
if (!equation || !sceneFile) return;
|
||||
ea2.imagesDict[fileId] = {
|
||||
mimeType: sceneFile.mimeType,
|
||||
id: fileId,
|
||||
dataURL: sceneFile.dataURL,
|
||||
created: sceneFile.created,
|
||||
file: null,
|
||||
hasSVGwithBitmap: null,
|
||||
latex: equation.latex,
|
||||
latex: equation.latex
|
||||
};
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// ----------------------
|
||||
// Execution Logic
|
||||
// ----------------------
|
||||
const executeDeconstruction = async (folderPath, fileName, shouldAnchor) => {
|
||||
// Ensure filename has extension
|
||||
if (!fileName.endsWith(".md")) fileName += ".md";
|
||||
|
||||
// Construct full path
|
||||
// normalizePath handles cases where folderPath might be empty or root
|
||||
const fullPath = ea.obsidian.normalizePath(`${folderPath}/${fileName}`);
|
||||
|
||||
// Separate back into folder and filename for ea.create
|
||||
const pathParts = fullPath.split("/");
|
||||
const finalFileName = pathParts.pop();
|
||||
const finalFolderName = pathParts.join("/");
|
||||
|
||||
// We use silent: true to prevent ea.create from opening the file automatically.
|
||||
// We handle opening manually based on user preference.
|
||||
const newPath = await ea.create ({
|
||||
filename: finalFileName,
|
||||
foldername: finalFolderName,
|
||||
templatePath: window.ExcalidrawDeconstructElements.templatePath,
|
||||
onNewPane: true,
|
||||
silent: true
|
||||
});
|
||||
|
||||
let f = app.vault.getAbstractFileByPath(newPath);
|
||||
let counter = 0;
|
||||
while((!f || !ea.isExcalidrawFile(f)) && counter++<100) {
|
||||
await sleep(50);
|
||||
f = app.vault.getAbstractFileByPath(newPath);
|
||||
}
|
||||
|
||||
if(!f || !ea.isExcalidrawFile(f)) {
|
||||
new Notice("Something went wrong");
|
||||
return;
|
||||
}
|
||||
|
||||
let padding = parseFloat(app.metadataCache.getCache(f.path)?.frontmatter["excalidraw-export-padding"]);
|
||||
if(isNaN(padding)) {
|
||||
padding = ea.plugin.settings.exportPaddingSVG;
|
||||
}
|
||||
|
||||
// Remove elements from current view and replace with image of new file
|
||||
ea.getElements().forEach(el=>el.isDeleted = true);
|
||||
await ea.addImage(bb.topX-padding, bb.topY-padding, f, false, shouldAnchor);
|
||||
await ea.addElementsToView(false, true, true);
|
||||
ea.getExcalidrawAPI().history.clear();
|
||||
|
||||
if(window.ExcalidrawDeconstructElements.openDeconstructedImage) {
|
||||
const reuse = window.ExcalidrawDeconstructElements.reuseTab;
|
||||
if (reuse) {
|
||||
ea.openFileInNewOrAdjacentLeaf(f);
|
||||
} else {
|
||||
// Force new tab
|
||||
await app.workspace.getLeaf('tab').openFile(f);
|
||||
function copyEmbeddedFilesToEa(ea2, elements) {
|
||||
for (const element of elements) {
|
||||
if (element.type !== "image" || !element.fileId) continue;
|
||||
if (!copyImageFile(ea2, element, element.fileId)) {
|
||||
copyEquationFile(ea2, element, element.fileId);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
new Notice("Deconstruction ready");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// ----------------------
|
||||
// Floating Modal UI
|
||||
// ----------------------
|
||||
|
||||
const modal = new ea.FloatingModal(ea.plugin.app);
|
||||
modal.titleEl.setText("Deconstruct Elements");
|
||||
|
||||
modal.onOpen = () => {
|
||||
const content = modal.contentEl;
|
||||
content.empty();
|
||||
|
||||
// -- Folder Path Input --
|
||||
const folderDiv = content.createDiv({ cls: "setting-item" });
|
||||
folderDiv.createDiv({ cls: "setting-item-info" }).createEl("label", { text: "Folder path" });
|
||||
const folderControl = folderDiv.createDiv({ cls: "setting-item-control" });
|
||||
const folderInput = new ea.obsidian.TextComponent(folderControl);
|
||||
|
||||
// Set default folder to current file's parent
|
||||
const currentFolder = ea.targetView.file.parent.path;
|
||||
folderInput.setValue(currentFolder);
|
||||
folderInput.inputEl.style.width = "100%";
|
||||
|
||||
// Attach Autocomplete
|
||||
new FolderSuggest(ea.plugin.app, folderInput.inputEl);
|
||||
|
||||
// -- Filename Input --
|
||||
const fileDiv = content.createDiv({ cls: "setting-item" });
|
||||
fileDiv.createDiv({ cls: "setting-item-info" }).createEl("label", { text: "File name" });
|
||||
const fileControl = fileDiv.createDiv({ cls: "setting-item-control" });
|
||||
const fileInput = new ea.obsidian.TextComponent(fileControl);
|
||||
fileInput.setValue(DEFAULT_FILENAME);
|
||||
fileInput.inputEl.style.width = "100%";
|
||||
|
||||
// Set focus to file input
|
||||
setTimeout(() => fileInput.inputEl.focus(), 50);
|
||||
|
||||
// -- Template Dropdown --
|
||||
new ea.obsidian.Setting(content)
|
||||
.setName(`Select template`)
|
||||
.addDropdown(dropdown => {
|
||||
templates.forEach(file => dropdown.addOption(file.path, file.basename));
|
||||
if(templates.length === 0) dropdown.addOption(null, "none");
|
||||
dropdown
|
||||
.setValue(window.ExcalidrawDeconstructElements.templatePath)
|
||||
.onChange(value => {
|
||||
window.ExcalidrawDeconstructElements.templatePath = value;
|
||||
})
|
||||
// src/sharedUtils/vaultPaths.ts
|
||||
var INVALID_FILE_NAME_CHARACTER = /[\\/:*?"<>|\u0000-\u001F]/u;
|
||||
var INVALID_FOLDER_SEGMENT_CHARACTER = /[\\:*?"<>|\u0000-\u001F]/u;
|
||||
var WINDOWS_RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/iu;
|
||||
function isVaultRootFolderPath(folderPath) {
|
||||
return folderPath === "" || folderPath === "/";
|
||||
}
|
||||
function firstInvalidCharacter(value, pattern) {
|
||||
return value.match(pattern)?.[0] ?? null;
|
||||
}
|
||||
function validateSegment(segment, invalidCharacterPattern, allowEmpty) {
|
||||
if (!segment) {
|
||||
return allowEmpty ? { valid: true } : { valid: false, reason: "empty", segment };
|
||||
}
|
||||
if (segment === "." || segment === "..") {
|
||||
return { valid: false, reason: "dot-segment", segment };
|
||||
}
|
||||
const invalidCharacter = firstInvalidCharacter(segment, invalidCharacterPattern);
|
||||
if (invalidCharacter !== null) {
|
||||
return {
|
||||
valid: false,
|
||||
reason: "invalid-character",
|
||||
segment,
|
||||
character: invalidCharacter
|
||||
};
|
||||
}
|
||||
if (WINDOWS_RESERVED_NAME.test(segment)) {
|
||||
return { valid: false, reason: "reserved-name", segment };
|
||||
}
|
||||
if (/[. ]$/u.test(segment)) {
|
||||
return { valid: false, reason: "trailing-dot-or-space", segment };
|
||||
}
|
||||
return { valid: true };
|
||||
}
|
||||
function validateVaultFileName(fileName) {
|
||||
return validateSegment(fileName, INVALID_FILE_NAME_CHARACTER, false);
|
||||
}
|
||||
function validateVaultFolderPath(folderPath) {
|
||||
if (isVaultRootFolderPath(folderPath)) return { valid: true };
|
||||
if (folderPath.startsWith("/") || folderPath.endsWith("/") || folderPath.includes("//")) {
|
||||
return { valid: false, reason: "invalid-path-shape", segment: folderPath };
|
||||
}
|
||||
for (const segment of folderPath.split("/")) {
|
||||
const result = validateSegment(segment, INVALID_FOLDER_SEGMENT_CHARACTER, false);
|
||||
if (!result.valid) return result;
|
||||
}
|
||||
return { valid: true };
|
||||
}
|
||||
function getUniqueVaultFilePath(folderPath, fileName, pathExists) {
|
||||
const resolvedFolderPath = isVaultRootFolderPath(folderPath) ? "" : folderPath;
|
||||
const lastDot = fileName.lastIndexOf(".");
|
||||
const hasExtension = lastDot > 0;
|
||||
const stem = hasExtension ? fileName.slice(0, lastDot) : fileName;
|
||||
const extension = hasExtension ? fileName.slice(lastDot) : "";
|
||||
const joinPath = (name) => resolvedFolderPath ? `${resolvedFolderPath}/${name}` : name;
|
||||
let candidate = joinPath(fileName);
|
||||
let suffix = 1;
|
||||
while (pathExists(candidate)) {
|
||||
candidate = joinPath(`${stem} ${suffix}${extension}`);
|
||||
suffix += 1;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
function formatVaultInvalidCharacter(character) {
|
||||
const codePoint = character.codePointAt(0);
|
||||
if (codePoint === void 0 || codePoint >= 32) return character;
|
||||
return `U+${codePoint.toString(16).toUpperCase().padStart(4, "0")}`;
|
||||
}
|
||||
function rankVaultFolderSuggestions(folderPaths, query) {
|
||||
const lowerQuery = query.toLowerCase();
|
||||
return [...new Set(folderPaths)].filter((path) => path.toLowerCase().includes(lowerQuery)).sort((left, right) => {
|
||||
const leftStarts = left.toLowerCase().startsWith(lowerQuery);
|
||||
const rightStarts = right.toLowerCase().startsWith(lowerQuery);
|
||||
if (leftStarts !== rightStarts) return leftStarts ? -1 : 1;
|
||||
return left.localeCompare(right);
|
||||
});
|
||||
}
|
||||
|
||||
// -- Open Toggle --
|
||||
new ea.obsidian.Setting(content)
|
||||
.setName(`Open deconstructed image`)
|
||||
.addToggle((toggle) => toggle
|
||||
.setValue(window.ExcalidrawDeconstructElements.openDeconstructedImage)
|
||||
.onChange(value => {
|
||||
window.ExcalidrawDeconstructElements.openDeconstructedImage = value;
|
||||
// Update visibility of the sub-toggle
|
||||
reuseSetting.settingEl.style.display = value ? "" : "none";
|
||||
// src/sharedUtils/windowTiming.ts
|
||||
function sleepInWindow(ownerWindow, milliseconds) {
|
||||
return new Promise((resolve) => ownerWindow.setTimeout(resolve, milliseconds));
|
||||
}
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/deconstruction.ts
|
||||
async function waitForVaultFile(ea2, app2, path, ownerWindow) {
|
||||
for (let attempt = 0; attempt <= 100; attempt += 1) {
|
||||
const file = app2.vault.getAbstractFileByPath(path);
|
||||
if (file instanceof ea2.obsidian.TFile) {
|
||||
return file;
|
||||
}
|
||||
if (attempt < 100) await sleepInWindow(ownerWindow, 50);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
async function waitForDrawingFile(ea2, app2, path, ownerWindow) {
|
||||
for (let attempt = 0; attempt <= 100; attempt += 1) {
|
||||
const file = app2.vault.getAbstractFileByPath(path);
|
||||
if (file instanceof ea2.obsidian.TFile && ea2.isExcalidrawFile(file)) {
|
||||
return file;
|
||||
}
|
||||
if (attempt < 100) await sleepInWindow(ownerWindow, 50);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function getExportPadding(ea2, app2, file) {
|
||||
const rawPadding = app2.metadataCache.getCache(file.path)?.frontmatter?.["excalidraw-export-padding"];
|
||||
const parsedPadding = Number.parseFloat(String(rawPadding));
|
||||
return Number.isNaN(parsedPadding) ? ea2.plugin.settings.exportPaddingSVG : parsedPadding;
|
||||
}
|
||||
async function replaceSelectionWithEmbed(context, file, padding, shouldAnchor) {
|
||||
const { ea: ea2, bounds } = context;
|
||||
for (const element of ea2.getElements()) {
|
||||
element.isDeleted = true;
|
||||
}
|
||||
await ea2.addImage(bounds.topX - padding, bounds.topY - padding, file, false, shouldAnchor);
|
||||
await ea2.addElementsToView(false, true, true);
|
||||
ea2.getExcalidrawAPI()?.history.clear();
|
||||
}
|
||||
async function openCreatedDrawing(context, file) {
|
||||
const { ea: ea2, app: app2, uiState } = context;
|
||||
if (!uiState.openDeconstructedImage) return;
|
||||
if (uiState.reuseTab) {
|
||||
ea2.openFileInNewOrAdjacentLeaf(file);
|
||||
return;
|
||||
}
|
||||
await app2.workspace.getLeaf("tab").openFile(file);
|
||||
}
|
||||
function isVaultRootFilePath(path) {
|
||||
return path.length > 0 && !path.includes("/");
|
||||
}
|
||||
async function createDrawingAtDestination(context, destination) {
|
||||
const { ea: ea2, app: app2, uiState, ownerWindow } = context;
|
||||
const requestedVaultRoot = isVaultRootFolderPath(destination.folderPath);
|
||||
const intendedRootPath = requestedVaultRoot ? getUniqueVaultFilePath(
|
||||
"/",
|
||||
destination.fileName,
|
||||
(path) => Boolean(app2.vault.getAbstractFileByPath(path))
|
||||
) : null;
|
||||
const createOptions = {
|
||||
filename: destination.fileName,
|
||||
foldername: destination.folderPath,
|
||||
templatePath: uiState.templatePath,
|
||||
onNewPane: true,
|
||||
silent: true
|
||||
};
|
||||
const newPath = await ea2.create(createOptions);
|
||||
const normalizedNewPath = ea2.obsidian.normalizePath(newPath);
|
||||
if (!requestedVaultRoot || isVaultRootFilePath(normalizedNewPath)) {
|
||||
return normalizedNewPath;
|
||||
}
|
||||
const createdFile = await waitForVaultFile(ea2, app2, normalizedNewPath, ownerWindow);
|
||||
if (!createdFile) {
|
||||
return normalizedNewPath;
|
||||
}
|
||||
if (!intendedRootPath) return normalizedNewPath;
|
||||
const rootTarget = app2.vault.getAbstractFileByPath(intendedRootPath) ? getUniqueVaultFilePath(
|
||||
"/",
|
||||
destination.fileName,
|
||||
(path) => Boolean(app2.vault.getAbstractFileByPath(path))
|
||||
) : intendedRootPath;
|
||||
await app2.fileManager.renameFile(createdFile, rootTarget);
|
||||
return rootTarget;
|
||||
}
|
||||
async function executeDeconstruction(context, destination, shouldAnchor) {
|
||||
const { ea: ea2, app: app2, t: t2, uiState, ownerWindow } = context;
|
||||
const newPath = await createDrawingAtDestination(context, destination);
|
||||
const file = await waitForDrawingFile(ea2, app2, newPath, ownerWindow);
|
||||
if (!file) {
|
||||
new Notice(t2("somethingWentWrong"));
|
||||
return;
|
||||
}
|
||||
const padding = getExportPadding(ea2, app2, file);
|
||||
await replaceSelectionWithEmbed(context, file, padding, shouldAnchor);
|
||||
await openCreatedDrawing(context, file);
|
||||
if (!uiState.openDeconstructedImage) new Notice(t2("deconstructionReady"));
|
||||
}
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/destination.ts
|
||||
function validateDeconstructionDestination(folderPath, fileName) {
|
||||
const fileValidation = validateVaultFileName(fileName);
|
||||
if (!fileValidation.valid) {
|
||||
return { valid: false, field: "file", validation: fileValidation };
|
||||
}
|
||||
const folderValidation = validateVaultFolderPath(folderPath);
|
||||
if (!folderValidation.valid) {
|
||||
return { valid: false, field: "folder", validation: folderValidation };
|
||||
}
|
||||
return {
|
||||
valid: true,
|
||||
folderPath: folderPath === "/" ? "" : folderPath,
|
||||
fileName: fileName.toLowerCase().endsWith(".md") ? fileName : `${fileName}.md`
|
||||
};
|
||||
}
|
||||
function formatDestinationValidationError(t2, result) {
|
||||
const { validation } = result;
|
||||
if (result.field === "file" && validation.reason === "empty") {
|
||||
return t2("filenameRequired");
|
||||
}
|
||||
if (validation.reason === "invalid-character" && validation.character !== void 0) {
|
||||
const character = formatVaultInvalidCharacter(validation.character);
|
||||
return t2(result.field === "file" ? "invalidFilenameCharacter" : "invalidFolderCharacter", {
|
||||
character
|
||||
});
|
||||
}
|
||||
return t2(result.field === "file" ? "invalidFilename" : "invalidFolderPath", {
|
||||
name: validation.segment
|
||||
});
|
||||
}
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/folderSuggest.ts
|
||||
function attachFolderSuggest(ea2, app2, inputEl) {
|
||||
const BaseSuggest = ea2.obsidian.AbstractInputSuggest;
|
||||
class FolderSuggest extends BaseSuggest {
|
||||
targetInput;
|
||||
constructor() {
|
||||
super(app2, inputEl);
|
||||
this.targetInput = inputEl;
|
||||
}
|
||||
getSuggestions(query) {
|
||||
const folderPaths = app2.vault.getAllLoadedFiles().filter((file) => file instanceof ea2.obsidian.TFolder).map((folder) => folder.path);
|
||||
return rankVaultFolderSuggestions(folderPaths, query);
|
||||
}
|
||||
renderSuggestion(value, el) {
|
||||
el.setText(value);
|
||||
}
|
||||
selectSuggestion(value, _event) {
|
||||
this.targetInput.value = value;
|
||||
const ownerWindow = this.targetInput.ownerDocument.defaultView;
|
||||
if (ownerWindow) {
|
||||
this.targetInput.dispatchEvent(new ownerWindow.Event("input", { bubbles: true }));
|
||||
}
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
return new FolderSuggest();
|
||||
}
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/modal.ts
|
||||
function createTextInput(context, content, label, value) {
|
||||
const row = content.createDiv({ cls: "setting-item" });
|
||||
row.createDiv({ cls: "setting-item-info" }).createEl("label", { text: label });
|
||||
const control = row.createDiv({ cls: "setting-item-control" });
|
||||
const input = new context.ea.obsidian.TextComponent(control);
|
||||
input.setValue(value);
|
||||
input.inputEl.style.width = "100%";
|
||||
return input;
|
||||
}
|
||||
function addBehaviorSettings(context, content) {
|
||||
const { ea: ea2, t: t2, config, uiState } = context;
|
||||
new ea2.obsidian.Setting(content).setName(t2("selectTemplate")).addDropdown((dropdown) => {
|
||||
if (config.templates.length === 0) dropdown.addOption("", t2("noTemplate"));
|
||||
for (const file of config.templates) dropdown.addOption(file.path, file.basename);
|
||||
dropdown.setValue(uiState.templatePath).onChange((value) => {
|
||||
uiState.templatePath = value;
|
||||
});
|
||||
});
|
||||
let reuseSetting = null;
|
||||
new ea2.obsidian.Setting(content).setName(t2("openDeconstructedImage")).addToggle(
|
||||
(toggle) => toggle.setValue(uiState.openDeconstructedImage).onChange((value) => {
|
||||
uiState.openDeconstructedImage = value;
|
||||
if (reuseSetting) reuseSetting.settingEl.style.display = value ? "" : "none";
|
||||
})
|
||||
);
|
||||
|
||||
// -- Reuse Tab Toggle --
|
||||
const reuseSetting = new ea.obsidian.Setting(content)
|
||||
.setName(`Reuse existing tab`)
|
||||
.setDesc("If available, open in an adjacent tab. Otherwise open in a new tab.")
|
||||
.setClass("reuse-tab-setting")
|
||||
.addToggle((toggle) => toggle
|
||||
.setValue(window.ExcalidrawDeconstructElements.reuseTab)
|
||||
.onChange(value => {
|
||||
window.ExcalidrawDeconstructElements.reuseTab = value;
|
||||
reuseSetting = new ea2.obsidian.Setting(content).setName(t2("reuseExistingTab")).setDesc(t2("reuseExistingTabDesc")).setClass("reuse-tab-setting").addToggle(
|
||||
(toggle) => toggle.setValue(uiState.reuseTab).onChange((value) => {
|
||||
uiState.reuseTab = value;
|
||||
})
|
||||
);
|
||||
|
||||
// Initialize visibility and style
|
||||
reuseSetting.settingEl.style.display = window.ExcalidrawDeconstructElements.openDeconstructedImage ? "" : "none";
|
||||
reuseSetting.settingEl.style.borderTop = "none";
|
||||
|
||||
// -- Buttons --
|
||||
const buttonContainer = content.createDiv({ cls: "excalidraw-dialog-buttons", style: "margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;" });
|
||||
|
||||
const btnInsert = new ea.obsidian.ButtonComponent(buttonContainer)
|
||||
.setButtonText("Insert")
|
||||
.setTooltip("Insert without anchoring")
|
||||
.onClick(async () => {
|
||||
const folder = folderInput.getValue();
|
||||
const filename = fileInput.getValue();
|
||||
if (!filename) {
|
||||
new Notice("Filename is required");
|
||||
return;
|
||||
}
|
||||
modal.close();
|
||||
await executeDeconstruction(folder, filename, false);
|
||||
});
|
||||
reuseSetting.settingEl.style.display = uiState.openDeconstructedImage ? "" : "none";
|
||||
reuseSetting.settingEl.style.borderTop = "none";
|
||||
}
|
||||
async function submitDeconstruction(context, modal, inputs, shouldAnchor) {
|
||||
const destination = validateDeconstructionDestination(
|
||||
inputs.folder.getValue(),
|
||||
inputs.file.getValue()
|
||||
);
|
||||
if (!destination.valid) {
|
||||
new Notice(formatDestinationValidationError(context.t, destination));
|
||||
return;
|
||||
}
|
||||
modal.close();
|
||||
await executeDeconstruction(context, destination, shouldAnchor);
|
||||
}
|
||||
function addButtons(context, modal, content, inputs) {
|
||||
const buttons = content.createDiv({ cls: "excalidraw-dialog-buttons" });
|
||||
buttons.style.marginTop = "20px";
|
||||
buttons.style.display = "flex";
|
||||
buttons.style.gap = "12px";
|
||||
buttons.style.justifyContent = "flex-end";
|
||||
new context.ea.obsidian.ButtonComponent(buttons).setButtonText(context.t("insert")).setTooltip(context.t("insertTooltip")).onClick(async () => submitDeconstruction(context, modal, inputs, false));
|
||||
new context.ea.obsidian.ButtonComponent(buttons).setButtonText(context.t("insertAt100")).setTooltip(context.t("insertAt100Tooltip")).setCta().onClick(async () => submitDeconstruction(context, modal, inputs, true));
|
||||
}
|
||||
function openDeconstructModal(context) {
|
||||
const { ea: ea2, app: app2, t: t2, config } = context;
|
||||
const modal = new ea2.FloatingModal(app2);
|
||||
modal.setTitle(t2("modalTitle"));
|
||||
let folderSuggest = null;
|
||||
modal.onOpen = () => {
|
||||
const content = modal.contentEl;
|
||||
content.empty();
|
||||
const currentFolder = ea2.targetView?.file.parent?.path ?? "";
|
||||
const folderInput = createTextInput(context, content, t2("folderPath"), currentFolder);
|
||||
folderSuggest = attachFolderSuggest(ea2, app2, folderInput.inputEl);
|
||||
const fileInput = createTextInput(context, content, t2("fileName"), config.defaultFileName);
|
||||
ea2.targetView?.ownerWindow.setTimeout(() => fileInput.inputEl.focus(), 50);
|
||||
addBehaviorSettings(context, content);
|
||||
addButtons(context, modal, content, { folder: folderInput, file: fileInput });
|
||||
};
|
||||
modal.onClose = () => {
|
||||
folderSuggest?.close();
|
||||
modal.contentEl.empty();
|
||||
};
|
||||
modal.open();
|
||||
}
|
||||
|
||||
const btnInsertAnchor = new ea.obsidian.ButtonComponent(buttonContainer)
|
||||
.setButtonText("Insert @100%")
|
||||
.setTooltip("Anchor to 100% size")
|
||||
.setCta()
|
||||
.onClick(async () => {
|
||||
const folder = folderInput.getValue();
|
||||
const filename = fileInput.getValue();
|
||||
if (!filename) {
|
||||
new Notice("Filename is required");
|
||||
return;
|
||||
}
|
||||
modal.close();
|
||||
await executeDeconstruction(folder, filename, true);
|
||||
});
|
||||
};
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/settings.ts
|
||||
var TEMPLATES_SETTING = "Templates";
|
||||
var DEFAULT_FILE_NAME_SETTING = "Default file name";
|
||||
var DEFAULT_FILE_NAME = "deconstructed";
|
||||
function asTextScriptSetting(value) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const record = value;
|
||||
if (typeof record.value !== "string") return null;
|
||||
return {
|
||||
value: record.value,
|
||||
description: typeof record.description === "string" ? record.description : ""
|
||||
};
|
||||
}
|
||||
async function ensureSettings(ea2, t2) {
|
||||
const current = ea2.getScriptSettings() ?? {};
|
||||
const templates = asTextScriptSetting(current[TEMPLATES_SETTING]);
|
||||
const defaultFileName = asTextScriptSetting(current[DEFAULT_FILE_NAME_SETTING]);
|
||||
if (templates && defaultFileName) return current;
|
||||
const next = { ...current };
|
||||
if (!templates) {
|
||||
next[TEMPLATES_SETTING] = {
|
||||
value: "",
|
||||
description: t2("templatesSettingDesc")
|
||||
};
|
||||
}
|
||||
if (!defaultFileName) {
|
||||
next[DEFAULT_FILE_NAME_SETTING] = {
|
||||
value: DEFAULT_FILE_NAME,
|
||||
description: t2("defaultFilenameSettingDesc")
|
||||
};
|
||||
}
|
||||
await ea2.setScriptSettings(next);
|
||||
return next;
|
||||
}
|
||||
function resolveTemplates(ea2, app2, configuredPaths) {
|
||||
const customTemplates = configuredPaths.split(",").map((path) => path.trim()).filter(Boolean).map((path) => app2.metadataCache.getFirstLinkpathDest(path, "")).filter((file) => file !== null);
|
||||
const byPath = /* @__PURE__ */ new Map();
|
||||
for (const file of [...customTemplates, ...ea2.getListOfTemplateFiles() ?? []]) {
|
||||
byPath.set(file.path, file);
|
||||
}
|
||||
return [...byPath.values()].sort((left, right) => left.basename.localeCompare(right.basename));
|
||||
}
|
||||
async function loadDeconstructConfig(ea2, app2, t2) {
|
||||
const settings = await ensureSettings(ea2, t2);
|
||||
const templatesSetting = asTextScriptSetting(settings[TEMPLATES_SETTING]);
|
||||
const defaultFileNameSetting = asTextScriptSetting(settings[DEFAULT_FILE_NAME_SETTING]);
|
||||
const configuredTemplatePaths = templatesSetting?.value ?? "";
|
||||
return {
|
||||
defaultFileName: defaultFileNameSetting?.value || DEFAULT_FILE_NAME,
|
||||
templates: resolveTemplates(ea2, app2, configuredTemplatePaths)
|
||||
};
|
||||
}
|
||||
|
||||
modal.open();
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/uiState.ts
|
||||
function getDeconstructUiState(ownerWindow, defaultTemplatePath) {
|
||||
const deconstructWindow = ownerWindow;
|
||||
const existing = deconstructWindow.ExcalidrawDeconstructElements;
|
||||
if (!existing) {
|
||||
const state = {
|
||||
openDeconstructedImage: true,
|
||||
reuseTab: true,
|
||||
templatePath: defaultTemplatePath
|
||||
};
|
||||
deconstructWindow.ExcalidrawDeconstructElements = state;
|
||||
return state;
|
||||
}
|
||||
if (typeof existing.reuseTab !== "boolean") existing.reuseTab = true;
|
||||
if (typeof existing.openDeconstructedImage !== "boolean") {
|
||||
existing.openDeconstructedImage = true;
|
||||
}
|
||||
if (typeof existing.templatePath !== "string") existing.templatePath = defaultTemplatePath;
|
||||
return existing;
|
||||
}
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/run.ts
|
||||
async function runDeconstructSelectedElements(scriptEa, app2, t2) {
|
||||
if (!scriptEa.verifyMinimumPluginVersion("2.27.0")) {
|
||||
new Notice(t2("requiresNewerVersion"));
|
||||
return;
|
||||
}
|
||||
const targetView = scriptEa.targetView;
|
||||
if (!targetView) return;
|
||||
const selectedElements = scriptEa.getViewSelectedElements();
|
||||
if (selectedElements.length === 0) {
|
||||
new Notice(t2("selectElements"));
|
||||
return;
|
||||
}
|
||||
const ea2 = scriptEa;
|
||||
const bounds = ea2.getBoundingBox(selectedElements);
|
||||
ea2.clear();
|
||||
ea2.copyViewElementsToEAforEditing(selectedElements);
|
||||
copyEmbeddedFilesToEa(ea2, ea2.getElements());
|
||||
const config = await loadDeconstructConfig(ea2, app2, t2);
|
||||
const defaultTemplatePath = config.templates[0]?.path ?? "";
|
||||
const uiState = getDeconstructUiState(targetView.ownerWindow, defaultTemplatePath);
|
||||
if (uiState.templatePath && !config.templates.some((file) => file.path === uiState.templatePath)) {
|
||||
uiState.templatePath = defaultTemplatePath;
|
||||
}
|
||||
openDeconstructModal({
|
||||
ea: ea2,
|
||||
app: app2,
|
||||
t: t2,
|
||||
config,
|
||||
uiState,
|
||||
bounds,
|
||||
ownerWindow: targetView.ownerWindow
|
||||
});
|
||||
}
|
||||
|
||||
// src/scripts/deconstruct-selected-elements-into-new-drawing/main.ts
|
||||
var t = createDeconstructTranslator(ea.obsidian.moment.locale());
|
||||
void runDeconstructSelectedElements(ea, app, t);
|
||||
})();
|
||||
|
||||
/* end of bundle */
|
||||
+7133
-926
File diff suppressed because it is too large.
Load diff
@@ -393,7 +393,7 @@
|
||||
},
|
||||
{
|
||||
"fname": "Deconstruct selected elements into new drawing.md",
|
||||
"mtime": 1771009405621
|
||||
"mtime": 1788542446871
|
||||
},
|
||||
{
|
||||
"fname": "Deconstruct selected elements into new drawing.svg",
|
||||
@@ -401,7 +401,7 @@
|
||||
},
|
||||
{
|
||||
"fname": "Slideshow.md",
|
||||
"mtime": 1764868375422
|
||||
"mtime": 1788618307127
|
||||
},
|
||||
{
|
||||
"fname": "Slideshow.svg",
|
||||
@@ -703,4 +703,4 @@
|
||||
"fname": "VoronoiDiagramGenerator.svg",
|
||||
"mtime": 1785564296587
|
||||
}
|
||||
]
|
||||
]
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.27.0-beta.5",
|
||||
"version": "2.27.2",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.26.4",
|
||||
"version": "2.27.2",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+15
-1246
File diff suppressed because it is too large.
Load diff
+3
-4
@@ -30,7 +30,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.126",
|
||||
"@zsviczian/excalidraw": "0.18.132",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -75,10 +75,9 @@
|
||||
"cssnano": "^6.0.2",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-plugin-obsidianmd": "^0.4.0",
|
||||
"eslint-plugin-obsidianmd": "^0.4.2",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"jiti": "^2.6.1",
|
||||
"madge": "^8.0.0",
|
||||
"obsidian": "1.8.7",
|
||||
"postcss": "^8.5.25",
|
||||
"prettier": "^3.0.1",
|
||||
@@ -108,4 +107,4 @@
|
||||
"node": ">=22.0.0",
|
||||
"npm": ">=10.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
+123
-36
@@ -94,7 +94,6 @@ const reactRuntime = isLib || !isProd
|
||||
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");
|
||||
@@ -120,10 +119,75 @@ if (!isLib) {
|
||||
|
||||
const manifestStr = isLib ? "" : fs.readFileSync("manifest-beta.json", "utf-8");
|
||||
const manifest = isLib ? {} : JSON.parse(manifestStr);
|
||||
const startupScriptBase64 = isLib
|
||||
? ""
|
||||
: Buffer.from(
|
||||
fs.readFileSync("src/constants/assets/startupScript.md", "utf-8"),
|
||||
"utf-8",
|
||||
).toString("base64");
|
||||
if (!isLib) {
|
||||
console.log(manifest.version);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OBSIDIAN COMMUNITY PLUGIN SCANNER COMPATIBILITY NOTES
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// Some declarations and build-time transformations below preserve intentional
|
||||
// Excalidraw behavior that has produced false-positive or non-actionable findings
|
||||
// in the Obsidian Community Plugin scanner. The scanner currently has no general
|
||||
// Some declarations and build-time transformations below preserve intentional
|
||||
// Excalidraw behavior that has produced false-positive or non-actionable findings
|
||||
// in the Obsidian Community Plugin scanner. In several cases there is currently no
|
||||
// equivalent source-level change that preserves the required behavior while also
|
||||
// satisfying the scanner. Rule-specific upstream reports are referenced below.
|
||||
//
|
||||
// These compatibility measures are not intended to conceal unsafe behavior. Each
|
||||
// one documents the legitimate runtime requirement, references an upstream report
|
||||
// where available, and should be removed when the scanner can represent the use
|
||||
// case correctly or provides an auditable exception mechanism. New scanner-specific
|
||||
// workarounds should receive the same documentation before being added.
|
||||
//
|
||||
// The React/ReactDOM runtime is built from the plugin's installed packages and
|
||||
// shipped as part of main.js; it is not downloaded from an external source at
|
||||
// runtime.
|
||||
//
|
||||
// The runtime is DEFLATE-compressed primarily to help keep the shipped plugin
|
||||
// below the Community Plugin scanner's 5 MB bundle-size limit. Obsidian plugins
|
||||
// currently cannot ship these runtime packages separately, so without this
|
||||
// packaging step React/ReactDOM must contribute their normal bundled size to
|
||||
// main.js.
|
||||
//
|
||||
// In the current production bundle this reduces main.js by approximately 106.5 KB.
|
||||
//
|
||||
// Base64 is NOT used for compression. DEFLATE produces arbitrary binary bytes,
|
||||
// while main.js is a JavaScript text file. Base64 provides a simple, deterministic
|
||||
// text-safe representation of that compressed binary payload which can be embedded
|
||||
// directly in the generated source. At runtime it is decoded with atob(), converted
|
||||
// to bytes, and inflated locally. Removing Base64 while retaining compression would
|
||||
// therefore require another binary-to-JavaScript representation (for example a
|
||||
// byte array or escaped binary string); it would not eliminate the need to encode
|
||||
// the compressed bytes somehow.
|
||||
//
|
||||
// A previous Community Plugin scan also flagged dynamic <script> element creation
|
||||
// originating inside the bundled React/ReactDOM implementation. This was a
|
||||
// Community Plugin static-analysis finding, separate from the
|
||||
// `obsidianmd/prefer-create-el` ESLint rule.
|
||||
//
|
||||
// The presence of createElement("script") in third-party library code does not by
|
||||
// itself establish that the plugin dynamically loads external executable code;
|
||||
// that depends on how the created element is subsequently configured and used.
|
||||
//
|
||||
// A related scanner limitation affecting bundled third-party libraries is documented
|
||||
// by another plugin author here:
|
||||
// https://github.com/obsidianmd/eslint-plugin/issues/152
|
||||
//
|
||||
// Even if the dynamic-script scanner limitation is resolved, this compressed payload
|
||||
// may remain necessary because of the independent 5 MB plugin-size constraint.
|
||||
// Revisit this packaging if Obsidian supports shipping dependency packages separately
|
||||
// or otherwise removes the need to keep the complete runtime within main.js.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const packageString = isLib
|
||||
? ""
|
||||
: ';const INITIAL_TIMESTAMP=Date.now();\n' +
|
||||
@@ -133,7 +197,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' +
|
||||
@@ -144,39 +208,70 @@ const packageString = isLib
|
||||
'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' +
|
||||
'const evaluateRuntimeInstructions = (win, instruction) => win.eval.call(win, instruction);\n' +
|
||||
'const reactRuntimeInstructions = `(function() {${REACT_PACKAGES}; return {React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime};})()`;\n' +
|
||||
'let {React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime} = evaluateRuntimeInstructions(window, reactRuntimeInstructions);\n' +
|
||||
'REACT_PACKAGES = "";\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,
|
||||
//but without offering a proper resolution, or a stepout process to remove them from scanner results.
|
||||
//for context you can read different issues I raised with the Obsidian team about these.
|
||||
//Once there is a workable resolution I am moving them back to their original locations, since having them here
|
||||
//is not at all ideal.
|
||||
//https://github.com/obsidianmd/eslint-plugin/issues/175
|
||||
// Scanner compatibility shim: deprecated caret API used only as a compatibility fallback.
|
||||
// Excalidraw uses Document.caretPositionFromPoint() where supported and falls back to
|
||||
// caretRangeFromPoint() for supported Obsidian/Electron/WebKit runtimes where the newer
|
||||
// API is unavailable. Removing the fallback would break compatibility without improving
|
||||
// plugin safety. The upstream false-positive report remains open:
|
||||
// https://github.com/obsidianmd/eslint-plugin/issues/175
|
||||
// Remove this shim when the scanner recognizes feature-detected compatibility fallbacks
|
||||
// or all supported Obsidian runtimes provide caretPositionFromPoint().
|
||||
`const getCaretRangeFromPoint = (doc, x, y) => doc.caretRangeFromPoint?.(x, y);\n` +
|
||||
//There isn't a process for flagging deliberate use of main document instead of activeDocument
|
||||
//The blanket rule by the eslint-plugin makes sense for many cases, but does not address special case needs
|
||||
// Scanner compatibility shim: deliberate reference to the primary application Document.
|
||||
// activeDocument is intentionally not equivalent here. Excalidraw supports popout windows
|
||||
// and must sometimes distinguish the main application document from a view/element's
|
||||
// ownerDocument or from the document that currently has focus.
|
||||
//
|
||||
// Related upstream work on false-positive `document` detection:
|
||||
// https://github.com/obsidianmd/eslint-plugin/pull/187
|
||||
//
|
||||
// This case is distinct: access to the primary document is intentional rather than an
|
||||
// accidental reference to the wrong document. Remove this shim when deliberate
|
||||
// main-document access can be represented without a finding.
|
||||
`const mainDocument = document;\n` +
|
||||
//Fetch is the only valid approach in case of loading binary data such as fonts to dataURL (i.e. not network related)
|
||||
//I've also had cases in the past where requestUrl failed with certain endpoints, for those cases I have
|
||||
//fetch in the codebase as a fallback from requestUrl.
|
||||
//https://github.com/obsidianmd/eslint-plugin/issues/176
|
||||
// Scanner compatibility shim: intentional Fetch API use.
|
||||
// Obsidian's requestUrl() is preferred for ordinary HTTP requests. Excalidraw also has
|
||||
// browser-native cases where fetch() is the appropriate API, including reading blob/data
|
||||
// resources for binary conversion, plus narrowly scoped fallbacks where requestUrl() cannot
|
||||
// reproduce the required browser/CORS behavior. Call sites use the deliberately named
|
||||
// deliberateFetch() helper so exceptional uses remain explicit and searchable.
|
||||
// Upstream false-positive report:
|
||||
// https://github.com/obsidianmd/eslint-plugin/issues/176
|
||||
// Remove this shim when the scanner distinguishes these valid uses or supports scoped,
|
||||
// justified exceptions.
|
||||
`const deliberateFetch = async (payload, init) => await fetch(payload, init);\n` +
|
||||
`const PLUGIN_VERSION="${manifest.version}";\n` +
|
||||
//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` +
|
||||
//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
|
||||
//adding a style element to an iframe that is used to create an image
|
||||
//I am sorry, but I got fatigued creating issues for all my edge cases with the eslint-plugin...
|
||||
//given the amount of extra time it takes, and the the usual lack of any meaningful timely response
|
||||
//Since I want to continue releasing Excalidraw versions, and not risk getting flagged for failed releases
|
||||
//I see no other meaningful option
|
||||
`const STARTUP_SCRIPT_BASE64="${startupScriptBase64}";\n` +
|
||||
// Scanner compatibility shim: intentional diagnostic logging.
|
||||
// Excalidraw does not use console.log for routine application output. Remaining log calls
|
||||
// are deliberate diagnostic/debug information used for troubleshooting.
|
||||
//
|
||||
// Remove this shim when reviewed diagnostic logging can be acknowledged without producing
|
||||
// a misleading quality finding.
|
||||
`const consoleLog = console["log"].bind(console);\n` +
|
||||
// Scanner compatibility shim: intentional native DOM element creation.
|
||||
// Obsidian DOM helpers and the plugin stylesheet are preferred for ordinary plugin UI.
|
||||
//
|
||||
// Every remaining call site creates a <style> element. Non-iframe cases inject complete
|
||||
// runtime stylesheet rules (selectors, pseudo-elements, at-rules, or arbitrary CSS) that
|
||||
// cannot be represented by per-element style helpers. Iframe cases must additionally create
|
||||
// the element in the iframe's contentDocument, whose realm does not receive Obsidian's DOM
|
||||
// helpers. Detached canvas/image and serialization-only elements use createFragment().
|
||||
//
|
||||
// Upstream discussion:
|
||||
// https://github.com/obsidianmd/eslint-plugin/issues/196
|
||||
//
|
||||
// Call sites use deliberateCreateElement(doc, tagName) so these unresolved stylesheet
|
||||
// exceptions remain explicit and searchable. Do not broaden the shim beyond reviewed style
|
||||
// creation; remove it when upstream provides an accepted document-scoped pattern.
|
||||
`const deliberateCreateElement = (doc, tagName) => doc.createElement(tagName);\n`;
|
||||
|
||||
const BASE_CONFIG = {
|
||||
@@ -196,7 +291,7 @@ const BASE_CONFIG = {
|
||||
'obsidian',
|
||||
'@zsviczian/excalidraw',
|
||||
'react',
|
||||
'react-dom'
|
||||
'react-dom',
|
||||
],
|
||||
};
|
||||
|
||||
@@ -207,14 +302,6 @@ const getRollupPlugins = (tsconfig, ...plugins) => [
|
||||
preventAssignment: true,
|
||||
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
|
||||
}),
|
||||
replace({ //This is a workaround to silence Obsidian codescanner complain about fs module usage in the plugin code. The plugin does not use fs module, but it is used by some dependencies.
|
||||
preventAssignment: true,
|
||||
delimiters: ['', ''],
|
||||
values: {
|
||||
"require('fs')": "null",
|
||||
'require("fs")': "null"
|
||||
}
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve({ browser: true, preferBuiltins: false }),
|
||||
].concat(plugins);
|
||||
|
||||
@@ -4,8 +4,8 @@ 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.
|
||||
* Bundles the official React package entrypoints into one function-evaluable
|
||||
* artifact for the plugin's shared private runtime.
|
||||
*
|
||||
* @param {{ isProduction: boolean }} options Build-mode selection.
|
||||
* @returns {Promise<string>} Generated browser runtime source.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
/**
|
||||
* Browser entry for the private React runtime used by Excalidraw.
|
||||
* Browser entry for the private React runtime shared by all Excalidraw views.
|
||||
*
|
||||
* 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.
|
||||
* 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";
|
||||
|
||||
+9
-632
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
// });
|
||||
// }
|
||||
// };
|
||||
// };
|
||||
@@ -0,0 +1,7 @@
|
||||
declare const STARTUP_SCRIPT_BASE64: string;
|
||||
|
||||
/**
|
||||
* Returns the default startup script embedded from the authoritative Markdown
|
||||
* asset by the Rollup build.
|
||||
*/
|
||||
export const startupScript = (): string => atob(STARTUP_SCRIPT_BASE64);
|
||||
@@ -1,13 +0,0 @@
|
||||
/*
|
||||
f = app.vault.getFileByPath("startuphooks.md");
|
||||
s = await app.vault.read(f);
|
||||
ea = ExcalidrawAutomate;
|
||||
url = await ea.convertStringToDataURL(s);
|
||||
window.navigator.clipboard.writeText(`export const startupScript = () => atob("${url.split("data:text/html;base64,")[1]}");`);
|
||||
console.log("String copied to clipboard");
|
||||
*/
|
||||
|
||||
export const startupScript = () =>
|
||||
atob(
|
||||
"LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIHRoZSB1c2VyIGNsb3NlcyBhbiBFeGNhbGlkcmF3IHZpZXcuCiAqICAgb25WaWV3VW5sb2FkSG9vazogKHZpZXc6IEV4Y2FsaWRyYXdWaWV3KSA9PiB2b2lkID0gbnVsbDsKICovCi8vZWEub25WaWV3VW5sb2FkSG9vayA9ICh2aWV3KSA9PiB7fTsKCi8qKgogKiBJZiBzZXQsIHRoaXMgY2FsbGJhY2sgaXMgdHJpZ2dlcmVkLCB3aGVuIHRoZSB1c2VyIGNoYW5nZXMgdGhlIHZpZXcgbW9kZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIHVzZXIgc3dpdGNoZXMgdG8gdmlldyBtb2RlIGFuZCBiYWNrLgogKiAgIG9uVmlld01vZGVDaGFuZ2VIb29rOiAoaXNWaWV3TW9kZUVuYWJsZWQ6Ym9vbGVhbiwgdmlldzogRXhjYWxpZHJhd1ZpZXcsIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUpID0+IHZvaWQgPSBudWxsOwogKi8KLy9lYS5vblZpZXdNb2RlQ2hhbmdlSG9vayA9IChpc1ZpZXdNb2RlRW5hYmxlZCwgdmlldywgZWEpID0+IHt9OwoKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gdGhlIHVzZXIgaG92ZXJzIGEgbGluayBpbiB0aGUgc2NlbmUuCiAqIFlvdSBjYW4gdXNlIHRoaXMgY2FsbGJhY2sgaW4gY2FzZSB5b3Ugd2FudCB0byBkbyBzb21ldGhpbmcgYWRkaXRpb25hbCB3aGVuIHRoZSBvbkxpbmtIb3ZlciBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25MaW5rSG92ZXIgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkxpbmtIb3ZlciBtYW5hZ2VtZW50IGZsb3cuCiAqICAgb25MaW5rSG92ZXJIb29rOiAoCiAqICAgICBlbGVtZW50OiBOb25EZWxldGVkRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXcsCiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlCiAqICAgKSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25MaW5rSG92ZXJIb29rID0gKGVsZW1lbnQsIGxpbmtUZXh0LCB2aWV3LCBlYSkgPT4ge307CiAgIAovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiB0aGUgdXNlciBjbGlja3MgYSBsaW5rIGluIHRoZSBzY2VuZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIG9uTGlua0NsaWNrIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkxpbmtDbGljayBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLCBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uTGlua0NsaWNrIG1hbmFnZW1lbnQgZmxvdy4KICogICBvbkxpbmtDbGlja0hvb2s6KAogKiAgICAgZWxlbWVudDogRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgZXZlbnQ6IE1vdXNlRXZlbnQsCiAqICAgICB2aWV3OiBFeGNhbGlkcmF3VmlldywKICogICAgIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUKICogICApID0+IGJvb2xlYW4gPSBudWxsOwogKi8KLy9lYS5vbkxpbmtDbGlja0hvb2sgPSAoZWxlbWVudCxsaW5rVGV4dCxldmVudCwgdmlldywgZWEpID0+IHt9OwogICAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvbkRyb3AgZXZlbnQuIAogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUgb25Ecm9wIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkRyb3AgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkRyb3AgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uRHJvcEhvb2s6IChkYXRhOiB7CiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlOwogKiAgICAgZXZlbnQ6IFJlYWN0LkRyYWdFdmVudDxIVE1MRGl2RWxlbWVudD47CiAqICAgICBkcmFnZ2FibGU6IGFueTsgLy9PYnNpZGlhbiBkcmFnZ2FibGUgb2JqZWN0CiAqICAgICB0eXBlOiAiZmlsZSIgfCAidGV4dCIgfCAidW5rbm93biI7CiAqICAgICBwYXlsb2FkOiB7CiAqICAgICAgIGZpbGVzOiBURmlsZVtdOyAvL1RGaWxlW10gYXJyYXkgb2YgZHJvcHBlZCBmaWxlcwogKiAgICAgICB0ZXh0OiBzdHJpbmc7IC8vc3RyaW5nCiAqICAgICB9OwogKiAgICAgZXhjYWxpZHJhd0ZpbGU6IFRGaWxlOyAvL3RoZSBmaWxlIHJlY2VpdmluZyB0aGUgZHJvcCBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIGRyb3AKICogICAgIHBvaW50ZXJQb3NpdGlvbjogeyB4OiBudW1iZXI7IHk6IG51bWJlciB9OyAvL3RoZSBwb2ludGVyIHBvc2l0aW9uIG9uIGNhbnZhcyBhdCB0aGUgdGltZSBvZiBkcm9wCiAqICAgfSkgPT4gYm9vbGVhbiA9IG51bGw7CiAqLwovL2VhLm9uRHJvcEhvb2sgPSAoZGF0YSkgPT4ge307CiAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvblBhc3RlIGV2ZW50LgogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUKICogb25QYXN0ZSBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25QYXN0ZSBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLAogKiBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uUGFzdGUgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uUGFzdGVIb29rOiAoZGF0YTogewogKiAgICAgZWE6IEV4Y2FsaWRyYXdBdXRvbWF0ZTsKICogICAgIHBheWxvYWQ6IENsaXBib2FyZERhdGE7CiAqICAgICBldmVudDogQ2xpcGJvYXJkRXZlbnQ7CiAqICAgICBleGNhbGlkcmF3RmlsZTogVEZpbGU7IC8vdGhlIGZpbGUgcmVjZWl2aW5nIHRoZSBwYXN0ZSBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIHBhc3RlCiAqICAgICBwb2ludGVyUG9zaXRpb246IHsgeDogbnVtYmVyOyB5OiBudW1iZXIgfTsgLy90aGUgcG9pbnRlciBwb3NpdGlvbiBvbiBjYW52YXMKICogICB9KSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25QYXN0ZUhvb2sgPSAoZGF0YSkgPT4ge307CgovKioKICogaWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiBhbiBFeGNhbGlkcmF3IGZpbGUgaXLine truncated
|
||||
);
|
||||
+89
-41
@@ -46,7 +46,6 @@ import {
|
||||
getNewUniqueFilepath,
|
||||
} from "../utils/fileUtils";
|
||||
import {
|
||||
errorlog,
|
||||
isVersionNewerThanOther,
|
||||
versionUpdateCheckTimer,
|
||||
calculateUIModeValue,
|
||||
@@ -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;
|
||||
@@ -158,6 +167,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
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;
|
||||
@@ -201,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,
|
||||
{
|
||||
@@ -221,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);
|
||||
@@ -606,16 +620,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
await this.fontManager.initializeFonts();
|
||||
}
|
||||
|
||||
/** Adds or replaces a plugin-owned font stylesheet. */
|
||||
public async addFonts(
|
||||
declarations: string[],
|
||||
ownerDocument?: Document,
|
||||
styleId?: string,
|
||||
): Promise<void> {
|
||||
await this.fontManager.addFonts(declarations, ownerDocument, styleId);
|
||||
}
|
||||
|
||||
/** Removes plugin-owned font stylesheets from all open documents. */
|
||||
/** Removes plugin-owned runtime fonts from all open documents. */
|
||||
public removeFonts(): void {
|
||||
this.fontManager.removeFonts();
|
||||
}
|
||||
@@ -660,17 +665,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"));
|
||||
@@ -678,12 +682,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();
|
||||
@@ -751,6 +749,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");
|
||||
@@ -760,11 +761,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 =
|
||||
@@ -811,18 +818,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}`);
|
||||
}
|
||||
@@ -977,6 +986,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
//PLUGIN_VERSION = null;
|
||||
delete window.PolyBool;
|
||||
this.packageManager.destroy();
|
||||
this.viewMigrationHandoffManager.destroy();
|
||||
this.viewMigrationPersistenceHandoffManager.destroy();
|
||||
this.commandManager?.destroy();
|
||||
this.eventManager.destroy();
|
||||
terminateCompressionWorker();
|
||||
@@ -1224,8 +1235,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() {
|
||||
@@ -1249,6 +1260,43 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -349,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();
|
||||
@@ -402,7 +402,6 @@ export class EventManager {
|
||||
changedDependencyFileIDs,
|
||||
false,
|
||||
true,
|
||||
"active-leaf-change",
|
||||
);
|
||||
}
|
||||
}, 2000);
|
||||
|
||||
@@ -50,10 +50,6 @@ import { errorlog, getExportTheme } from "src/utils/utils";
|
||||
import { getImageCache } from "src/shared/ImageCache";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
import { t } from "src/lang/helpers";
|
||||
import {
|
||||
performanceDiagnosticIncrement,
|
||||
performanceDiagnosticLog,
|
||||
} from "src/utils/performanceDiagnostics";
|
||||
|
||||
export class PluginFileManager {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
@@ -105,14 +101,7 @@ export class PluginFileManager {
|
||||
return !!frontmatter[FRONTMATTER_KEYS.plugin.name];
|
||||
}
|
||||
|
||||
const retainedClassification = this.excalidrawFiles.has(f);
|
||||
if (retainedClassification) {
|
||||
performanceDiagnosticIncrement("knownExcalidrawFileFallback");
|
||||
performanceDiagnosticLog("file.classificationFallback", {
|
||||
extension: f.extension,
|
||||
});
|
||||
}
|
||||
return retainedClassification;
|
||||
return this.excalidrawFiles.has(f);
|
||||
}
|
||||
|
||||
//managing my own list of Excalidraw files because in the onDelete event handler
|
||||
@@ -559,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 ---------------------
|
||||
// -------------------------------------------------------
|
||||
@@ -644,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 (
|
||||
@@ -702,10 +728,22 @@ export class PluginFileManager {
|
||||
return;
|
||||
}
|
||||
const inData = new ExcalidrawData(this.plugin);
|
||||
const data = await this.app.vault.read(file);
|
||||
await inData.loadData(data, file, getTextMode(data));
|
||||
await excalidrawView.synchronizeWithData(inData);
|
||||
inData.destroy();
|
||||
try {
|
||||
const data = await this.app.vault.read(file);
|
||||
await inData.loadData(data, file, getTextMode(data));
|
||||
await excalidrawView.synchronizeWithData(inData);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "FileManager.modifyEventHandler",
|
||||
fn: "load synchronized drawing data",
|
||||
message: `Rejected incoming drawing data for ${file.path}`,
|
||||
error,
|
||||
});
|
||||
new Notice(t("DRAWING_RELOAD_FAILED"), 60000);
|
||||
return;
|
||||
} finally {
|
||||
inData.destroy();
|
||||
}
|
||||
if (excalidrawView?.isDirty()) {
|
||||
if (
|
||||
excalidrawView.autosaveTimer &&
|
||||
|
||||
@@ -6,31 +6,37 @@ import {
|
||||
FONTS_STYLE_ID,
|
||||
} from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { getCJKDataURLs } from "src/utils/CJKLoader";
|
||||
import { getCJKFontFaceData } from "src/utils/CJKLoader";
|
||||
import { getFontDataURL } from "src/utils/utils";
|
||||
import { getFontMetrics } from "src/utils/fontMetrics";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
declare const deliberateCreateElement: (
|
||||
document: Document,
|
||||
tagName: string,
|
||||
) => HTMLStyleElement;
|
||||
|
||||
type PackageMapProvider = () => Map<Window, Packages>;
|
||||
type RuntimePackageProvider = () => Packages;
|
||||
|
||||
interface RuntimeFontFaceDefinition {
|
||||
family: string;
|
||||
source: string | ArrayBuffer;
|
||||
descriptors?: FontFaceDescriptors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns CJK and custom-font discovery, registration, document stylesheets, and
|
||||
* Owns CJK and custom-font discovery, document registration, and
|
||||
* readiness state while preserving the plugin's existing public font facade.
|
||||
*/
|
||||
export class FontManager {
|
||||
private isLocalCJKFontAvailabe: boolean = undefined;
|
||||
// Intentionally true to preserve the existing startup race behavior.
|
||||
private fontsReady = true;
|
||||
private readonly registeredFontFaces = new WeakMap<
|
||||
Document,
|
||||
Map<string, FontFace[]>
|
||||
>();
|
||||
|
||||
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,24 +82,35 @@ 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);
|
||||
if (typeof cjkFontDataURLs === "boolean" && !cjkFontDataURLs) {
|
||||
const cjkFontFaceData = await getCJKFontFaceData(this.plugin);
|
||||
if (cjkFontFaceData === false) {
|
||||
new Notice(
|
||||
t("FONTS_LOAD_ERROR") + this.plugin.settings.fontAssetsPath,
|
||||
6000,
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof cjkFontDataURLs === "object") {
|
||||
const fontDeclarations = cjkFontDataURLs.map(
|
||||
(dataURL) =>
|
||||
`@font-face { font-family: 'Xiaolai'; src: url("${dataURL}"); font-display: swap; font-weight: 400; }`,
|
||||
if (cjkFontFaceData) {
|
||||
const fontDefinitions: RuntimeFontFaceDefinition[] = cjkFontFaceData.map(
|
||||
({ dataURL, descriptors }) => ({
|
||||
family: "Xiaolai",
|
||||
source: `url(${JSON.stringify(dataURL)})`,
|
||||
descriptors: {
|
||||
...descriptors,
|
||||
display: "swap",
|
||||
weight: "400",
|
||||
},
|
||||
}),
|
||||
);
|
||||
for (const ownerDocument of this.getOpenObsidianDocuments()) {
|
||||
await this.addFonts(fontDeclarations, ownerDocument, CJK_STYLE_ID);
|
||||
await this.registerFontFaces(
|
||||
fontDefinitions,
|
||||
ownerDocument,
|
||||
CJK_STYLE_ID,
|
||||
);
|
||||
}
|
||||
new Notice(t("FONTS_LOADED"));
|
||||
}
|
||||
@@ -128,21 +145,28 @@ 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(
|
||||
await this.registerFontFaces(
|
||||
[
|
||||
`@font-face{font-family:'Local Font';src:url("${fourthFontDataURL}");font-display: swap;font-weight: 400;`,
|
||||
{
|
||||
family: "Local Font",
|
||||
source: `url(${JSON.stringify(fourthFontDataURL)})`,
|
||||
descriptors: {
|
||||
display: "swap",
|
||||
weight: "400",
|
||||
},
|
||||
},
|
||||
],
|
||||
ownerDocument,
|
||||
FONTS_STYLE_ID,
|
||||
true,
|
||||
);
|
||||
}
|
||||
if (!this.plugin.fourthFontLoaded) {
|
||||
@@ -153,26 +177,50 @@ export class FontManager {
|
||||
this.fontsReady = true;
|
||||
}
|
||||
|
||||
/** Replaces a plugin-owned font stylesheet and waits for the font to load. */
|
||||
public async addFonts(
|
||||
declarations: string[],
|
||||
ownerDocument: Document = mainDocument,
|
||||
styleId: string = FONTS_STYLE_ID,
|
||||
private async registerFontFaces(
|
||||
definitions: RuntimeFontFaceDefinition[],
|
||||
ownerDocument: Document,
|
||||
registrationId: string,
|
||||
preload = false,
|
||||
): Promise<void> {
|
||||
const newStylesheet = deliberateCreateElement(ownerDocument, "style");
|
||||
newStylesheet.id = styleId;
|
||||
newStylesheet.textContent = declarations.join("");
|
||||
const oldStylesheet = ownerDocument.getElementById(styleId);
|
||||
ownerDocument.head.appendChild(newStylesheet);
|
||||
if (oldStylesheet) {
|
||||
ownerDocument.head.removeChild(oldStylesheet);
|
||||
const ownerWindow = ownerDocument.defaultView;
|
||||
const FontFaceConstructor: typeof FontFace | undefined = ownerWindow
|
||||
? Reflect.get(ownerWindow, "FontFace")
|
||||
: undefined;
|
||||
if (!FontFaceConstructor) {
|
||||
throw new Error("FontFace is unavailable in the target document.");
|
||||
}
|
||||
await ownerDocument.fonts.load("20px Local Font");
|
||||
|
||||
const newFaces = definitions.map(
|
||||
({ family, source, descriptors }) =>
|
||||
new FontFaceConstructor(family, source, descriptors),
|
||||
);
|
||||
if (preload) {
|
||||
await Promise.all(newFaces.map((face) => face.load()));
|
||||
}
|
||||
|
||||
let registrations = this.registeredFontFaces.get(ownerDocument);
|
||||
if (!registrations) {
|
||||
registrations = new Map<string, FontFace[]>();
|
||||
this.registeredFontFaces.set(ownerDocument, registrations);
|
||||
}
|
||||
const oldFaces = registrations.get(registrationId) ?? [];
|
||||
newFaces.forEach((face) => ownerDocument.fonts.add(face));
|
||||
oldFaces.forEach((face) => ownerDocument.fonts.delete(face));
|
||||
registrations.set(registrationId, newFaces);
|
||||
|
||||
// Remove a stylesheet left by an earlier in-session implementation.
|
||||
ownerDocument.getElementById(registrationId)?.remove();
|
||||
}
|
||||
|
||||
/** Removes custom and CJK font stylesheets from all open documents. */
|
||||
/** Removes custom and CJK font registrations from all open documents. */
|
||||
public removeFonts(): void {
|
||||
this.getOpenObsidianDocuments().forEach((ownerDocument) => {
|
||||
const registrations = this.registeredFontFaces.get(ownerDocument);
|
||||
registrations?.forEach((faces) => {
|
||||
faces.forEach((face) => ownerDocument.fonts.delete(face));
|
||||
});
|
||||
this.registeredFontFaces.delete(ownerDocument);
|
||||
const oldCustomFontStylesheet =
|
||||
ownerDocument.getElementById(FONTS_STYLE_ID);
|
||||
if (oldCustomFontStylesheet) {
|
||||
|
||||
@@ -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,16 +283,19 @@ 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;
|
||||
}
|
||||
@@ -285,36 +304,49 @@ export class ObserverManager {
|
||||
//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 ||
|
||||
!isInstanceOfElement(m[0].addedNodes[0]) ||
|
||||
!m[0].addedNodes[0].matches(".modal-container") ||
|
||||
!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,
|
||||
});
|
||||
}
|
||||
@@ -324,8 +356,9 @@ export class ObserverManager {
|
||||
return;
|
||||
}
|
||||
this.modalContainerObserver.disconnect();
|
||||
this.activeViewDoc = null;
|
||||
this.modalContainerObserver = null;
|
||||
this.modalObservedView = null;
|
||||
this.activeViewDoc = null;
|
||||
}
|
||||
|
||||
private addWorkspaceDrawerObserver() {
|
||||
|
||||
@@ -8,17 +8,9 @@ import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import { createObsidianCommonHostAdapter } from "./obsidianCommonHostAdapter";
|
||||
import { createObsidianExcalidrawHostAdapter } from "./obsidianExcalidrawHostAdapter";
|
||||
import {
|
||||
performanceDiagnosticIncrement,
|
||||
performanceDiagnosticLog,
|
||||
performanceDiagnosticNow,
|
||||
performanceDiagnosticRecordDuration,
|
||||
performanceDiagnosticsEnabled,
|
||||
} from "../../utils/performanceDiagnostics";
|
||||
|
||||
declare let REACT_PACKAGES: string;
|
||||
declare let react: typeof React;
|
||||
declare let reactDOM: typeof ReactDOM;
|
||||
declare let reactDOM: typeof ReactDOM & typeof import("react-dom");
|
||||
declare let excalidrawLib: typeof ExcalidrawLib;
|
||||
declare let ReactJSXRuntime: unknown;
|
||||
declare let ReactJSXDevRuntime: unknown;
|
||||
@@ -29,20 +21,26 @@ const normalizeError = (error: unknown): 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 runtimePackage: Packages | null = null;
|
||||
private packageLeaseCountMap = new Map<Window, number>();
|
||||
private commonHostDisposerMap = new Map<Window, () => void>();
|
||||
private excalidrawHostDisposerMap = new Map<Window, () => void>();
|
||||
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
|
||||
@@ -50,13 +48,13 @@ 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",
|
||||
@@ -81,8 +79,7 @@ export class PackageManager {
|
||||
|
||||
// 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");
|
||||
}
|
||||
@@ -96,6 +93,13 @@ export class PackageManager {
|
||||
10000,
|
||||
);
|
||||
console.error("Error loading the Excalidraw package", e);
|
||||
} finally {
|
||||
// Per-window evaluation has been removed. Release the decompressed source
|
||||
// Excalidraw source after the one shared runtime is initialized. The
|
||||
// bootstrap releases its inflated React source immediately after eval.
|
||||
excalidrawPackage = "";
|
||||
ReactJSXRuntime = null;
|
||||
ReactJSXDevRuntime = null;
|
||||
}
|
||||
|
||||
plugin.logStartupEvent("Excalidraw package unpacked");
|
||||
@@ -127,9 +131,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 (
|
||||
@@ -144,16 +148,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 (
|
||||
@@ -170,71 +171,57 @@ 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);
|
||||
performanceDiagnosticLog("package.set", {
|
||||
packageWindows: this.packageMap.size,
|
||||
window: window === globalThis.window ? "main" : "popout",
|
||||
});
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquires an idempotent lease for the package owned by `win`.
|
||||
* Acquires the shared runtime while retaining the view's actual window.
|
||||
*
|
||||
* @remarks
|
||||
* Popout packages are deleted when their last lease is released. The main
|
||||
* package remains pinned for the plugin lifetime because it is also the
|
||||
* fallback runtime and is initialized as part of plugin startup.
|
||||
* 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 acquirePackage(win: Window): PackageLease {
|
||||
const packages = this.getPackage(win);
|
||||
const leaseCount = (this.packageLeaseCountMap.get(win) ?? 0) + 1;
|
||||
this.packageLeaseCountMap.set(win, leaseCount);
|
||||
performanceDiagnosticLog("package.leaseAcquired", {
|
||||
window: win === window ? "main" : "popout",
|
||||
leases: leaseCount,
|
||||
packageWindows: this.packageMap.size,
|
||||
});
|
||||
|
||||
let released = false;
|
||||
return {
|
||||
@@ -261,144 +248,49 @@ export class PackageManager {
|
||||
if (remainingLeases === 0) {
|
||||
this.packageLeaseCountMap.delete(win);
|
||||
if (win !== window) {
|
||||
this.deletePackage(win);
|
||||
this.removeRuntimeAlias(win);
|
||||
}
|
||||
} else {
|
||||
this.packageLeaseCountMap.set(win, remainingLeases);
|
||||
}
|
||||
|
||||
performanceDiagnosticLog("package.leaseReleased", {
|
||||
window: win === window ? "main" : "popout",
|
||||
leases: remainingLeases,
|
||||
packageWindows: this.packageMap.size,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a package for a window, creating it if necessary
|
||||
* with robust error handling
|
||||
* 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 diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const diagnosticsStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
try {
|
||||
// Return existing package if available
|
||||
if (this.packageMap.has(win)) {
|
||||
const pkg = this.packageMap.get(win);
|
||||
if (this.validatePackage(pkg)) {
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticIncrement("packageCacheHit");
|
||||
performanceDiagnosticRecordDuration(
|
||||
"packageGet",
|
||||
performanceDiagnosticNow() - diagnosticsStart,
|
||||
);
|
||||
}
|
||||
performanceDiagnosticLog("package.get", {
|
||||
source: "cache",
|
||||
window: win === globalThis.window ? "main" : "popout",
|
||||
packageWindows: this.packageMap.size,
|
||||
durationMs: diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - diagnosticsStart
|
||||
: undefined,
|
||||
});
|
||||
return pkg;
|
||||
}
|
||||
// If package exists but is invalid, delete it so we can recreate it
|
||||
this.deletePackage(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);
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticIncrement("packageCreated");
|
||||
performanceDiagnosticRecordDuration(
|
||||
"packageGet",
|
||||
performanceDiagnosticNow() - diagnosticsStart,
|
||||
);
|
||||
}
|
||||
performanceDiagnosticLog("package.get", {
|
||||
source: "created",
|
||||
window: win === globalThis.window ? "main" : "popout",
|
||||
packageWindows: this.packageMap.size,
|
||||
durationMs: diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - diagnosticsStart
|
||||
: undefined,
|
||||
});
|
||||
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");
|
||||
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 {
|
||||
const packageWindowsBefore = this.packageMap.size;
|
||||
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);
|
||||
performanceDiagnosticIncrement("packageDeleted");
|
||||
performanceDiagnosticLog("package.deleted", {
|
||||
window: win === globalThis.window ? "main" : "popout",
|
||||
before: packageWindowsBefore,
|
||||
after: this.packageMap.size,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
errorHandler.handleError(
|
||||
normalizeError(error),
|
||||
@@ -407,24 +299,17 @@ 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.packageLeaseCountMap.clear();
|
||||
this.commonHostDisposerMap.clear();
|
||||
this.excalidrawHostDisposerMap.clear();
|
||||
this.EXCALIDRAW_PACKAGE = "";
|
||||
this.fallbackPackage = null;
|
||||
this.runtimeAliasWindows.clear();
|
||||
this.disposeObsidianHosts();
|
||||
this.runtimePackage = null;
|
||||
|
||||
react = null;
|
||||
reactDOM = null;
|
||||
|
||||
@@ -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()),
|
||||
);
|
||||
}
|
||||
}
|
||||
+216
-16
@@ -35,7 +35,7 @@ import { getImageCache } from "src/shared/ImageCache";
|
||||
import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt";
|
||||
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "src/shared/Dialogs/EmbeddableMDFileCustomDataSettingsComponent";
|
||||
import { AutostartScriptsSettingsComponent } from "src/shared/Dialogs/AutostartScriptsSettingsComponent";
|
||||
import { startupScript } from "src/constants/starutpscript";
|
||||
import { startupScript } from "src/constants/startupScript";
|
||||
import {
|
||||
getModifierKeyCategoryName,
|
||||
MODIFIER_KEY_CATEGORIES,
|
||||
@@ -70,6 +70,11 @@ import { decryptProviderProfiles } from "src/utils/settingsKeyObfuscation";
|
||||
import { getGeminiSupportedSizes } from "src/utils/geminiImageModelUtils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
|
||||
import { errorlog } from "src/utils/coreUtils";
|
||||
import {
|
||||
replaceScriptFileExtension,
|
||||
resolveConfiguredStartupScriptPath,
|
||||
} from "src/utils/scriptFileUtils";
|
||||
import {
|
||||
getMarkdownFontFamilyId,
|
||||
getSelectableFontOptions,
|
||||
@@ -4966,6 +4971,19 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
aliases: ["Excalidraw Automate autocomplete", "EA suggester"],
|
||||
control: { type: "toggle", key: "fieldSuggester" },
|
||||
},
|
||||
{
|
||||
name: t("ALLOW_JS_FILES_NAME"),
|
||||
desc: fragWithHTML(t("ALLOW_JS_FILES_DESC")),
|
||||
aliases: ["JavaScript files", ".js scripts", "sync scripts"],
|
||||
control: {
|
||||
type: "toggle",
|
||||
key: "allowJavaScriptFiles",
|
||||
afterUpdate: async () => {
|
||||
await this.plugin.scriptEngine?.reloadScripts();
|
||||
this.refreshSettingsUI();
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: t("ENABLE_ONLOAD_SCRIPTS_NAME"),
|
||||
desc: fragWithHTML(t("ENABLE_ONLOAD_SCRIPTS_DESC")),
|
||||
@@ -4995,6 +5013,164 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
});
|
||||
}
|
||||
|
||||
private configureScriptFileStorageSetting(setting: Setting): void {
|
||||
setting
|
||||
.setName(t("STORE_SCRIPTS_AS_JS_NAME"))
|
||||
.setDesc(fragWithHTML(t("STORE_SCRIPTS_AS_JS_DESC")))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("md", t("SCRIPT_FILE_EXTENSION_MARKDOWN"))
|
||||
.addOption("js", t("SCRIPT_FILE_EXTENSION_JAVASCRIPT"))
|
||||
.setValue(
|
||||
this.plugin.settings.storeScriptFilesAsJavaScript ? "js" : "md",
|
||||
)
|
||||
.onChange((value) => {
|
||||
this.plugin.settings.storeScriptFilesAsJavaScript = value === "js";
|
||||
this.applySettingsUpdate();
|
||||
this.refreshSettingsUI();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private configureScriptFileMigrationSetting(setting: Setting): void {
|
||||
const targetExtension = this.plugin.settings
|
||||
.storeScriptFilesAsJavaScript
|
||||
? "js"
|
||||
: "md";
|
||||
const plan =
|
||||
this.plugin.scriptEngine.getScriptFileMigrationPlan(targetExtension);
|
||||
const buttonText =
|
||||
targetExtension === "js"
|
||||
? t("MIGRATE_SCRIPTS_TO_JS_BUTTON")
|
||||
: t("MIGRATE_SCRIPTS_TO_MD_BUTTON");
|
||||
const skippedStatus = plan.conflicts.length
|
||||
? t("MIGRATE_SCRIPT_FILES_SKIPPED").replace(
|
||||
"{count}",
|
||||
String(plan.conflicts.length),
|
||||
)
|
||||
: "";
|
||||
const getSkippedDetails = (conflicts: string[]): string =>
|
||||
t("MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS")
|
||||
.replace("{count}", String(conflicts.length))
|
||||
.replace(
|
||||
"{files}",
|
||||
conflicts
|
||||
.map(
|
||||
(sourcePath) =>
|
||||
`${sourcePath} → ${replaceScriptFileExtension(
|
||||
sourcePath,
|
||||
targetExtension,
|
||||
)}`,
|
||||
)
|
||||
.join("\n"),
|
||||
);
|
||||
|
||||
setting
|
||||
.setName(buttonText)
|
||||
.setDesc(
|
||||
t("MIGRATE_SCRIPT_FILES_STATUS")
|
||||
.replace("{eligible}", String(plan.renames.length))
|
||||
.replace("{extension}", `.${targetExtension}`)
|
||||
.replace("{skipped}", skippedStatus),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(buttonText)
|
||||
.setDisabled(plan.renames.length === 0)
|
||||
.onClick(async () => {
|
||||
const currentPlan =
|
||||
this.plugin.scriptEngine.getScriptFileMigrationPlan(
|
||||
targetExtension,
|
||||
);
|
||||
if (currentPlan.renames.length === 0) {
|
||||
const message = currentPlan.conflicts.length
|
||||
? `${t("MIGRATE_SCRIPT_FILES_NONE")}\n\n${getSkippedDetails(
|
||||
currentPlan.conflicts,
|
||||
)}`
|
||||
: t("MIGRATE_SCRIPT_FILES_NONE");
|
||||
new Notice(message, 10000);
|
||||
this.refreshSettingsUI();
|
||||
return;
|
||||
}
|
||||
|
||||
const startupNote = currentPlan.includesStartupScript
|
||||
? t("MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED")
|
||||
: "";
|
||||
const skippedNote = currentPlan.conflicts.length
|
||||
? t("MIGRATE_SCRIPT_FILES_SKIPPED").replace(
|
||||
"{count}",
|
||||
String(currentPlan.conflicts.length),
|
||||
)
|
||||
: "";
|
||||
const confirmation = new MultiOptionConfirmationPrompt<boolean>(
|
||||
this.plugin,
|
||||
t("MIGRATE_SCRIPT_FILES_CONFIRM")
|
||||
.replace("{count}", String(currentPlan.renames.length))
|
||||
.replace("{extension}", `.${targetExtension}`)
|
||||
.replace("{startup}", startupNote)
|
||||
.replace("{skipped}", skippedNote),
|
||||
new Map<string, boolean>([
|
||||
[t("PROMPT_BUTTON_CANCEL"), false],
|
||||
[buttonText, true],
|
||||
]),
|
||||
buttonText,
|
||||
);
|
||||
if (!(await confirmation.waitForClose)) {
|
||||
return;
|
||||
}
|
||||
|
||||
button.setDisabled(true);
|
||||
try {
|
||||
const count =
|
||||
await this.plugin.scriptEngine.migrateScriptFiles(currentPlan);
|
||||
const completeMessage = t("MIGRATE_SCRIPT_FILES_COMPLETE")
|
||||
.replace("{count}", String(count))
|
||||
.replace("{extension}", `.${targetExtension}`);
|
||||
const message = currentPlan.conflicts.length
|
||||
? `${completeMessage}\n\n${getSkippedDetails(
|
||||
currentPlan.conflicts,
|
||||
)}`
|
||||
: completeMessage;
|
||||
new Notice(
|
||||
message,
|
||||
currentPlan.conflicts.length > 0 ? 15000 : undefined,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where:
|
||||
"ExcalidrawSettingTab.configureScriptFileMigrationSetting",
|
||||
error,
|
||||
});
|
||||
new Notice(t("MIGRATE_SCRIPT_FILES_FAILED"));
|
||||
} finally {
|
||||
this.refreshSettingsUI();
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private createScriptFileStorageDefinition(): SettingDefinition<SettingBindingKey> {
|
||||
return this.createCustomSettingDefinition({
|
||||
name: t("STORE_SCRIPTS_AS_JS_NAME"),
|
||||
desc: fragWithHTML(t("STORE_SCRIPTS_AS_JS_DESC")),
|
||||
aliases: ["download scripts as JavaScript", "convert scripts to .js"],
|
||||
visible: () => this.plugin.settings.allowJavaScriptFiles,
|
||||
controlType: "dropdown",
|
||||
configure: (setting) => this.configureScriptFileStorageSetting(setting),
|
||||
});
|
||||
}
|
||||
|
||||
private createScriptFileMigrationDefinition(): SettingDefinition<SettingBindingKey> {
|
||||
return this.createCustomSettingDefinition({
|
||||
name: t("MIGRATE_SCRIPT_FILES_NAME"),
|
||||
aliases: ["rename script files", "convert scripts", ".md", ".js"],
|
||||
visible: () => this.plugin.settings.allowJavaScriptFiles,
|
||||
controlType: "action button",
|
||||
configure: (setting) =>
|
||||
this.configureScriptFileMigrationSetting(setting),
|
||||
});
|
||||
}
|
||||
|
||||
private createStartupScriptDefinition(): SettingDefinition<SettingBindingKey> {
|
||||
return this.createCustomSettingDefinition({
|
||||
name: t("STARTUP_SCRIPT_NAME"),
|
||||
@@ -5018,9 +5194,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}
|
||||
|
||||
private getAutomateDefinitions(): SettingDefinitionItem<SettingBindingKey>[] {
|
||||
const specs = this.getAutomateSpecs();
|
||||
return [
|
||||
this.createAutomateInformationDefinition(),
|
||||
...this.toDeclarativeDefinitions(this.getAutomateSpecs()),
|
||||
...this.toDeclarativeDefinitions(specs.slice(0, 2)),
|
||||
this.createScriptFileStorageDefinition(),
|
||||
this.createScriptFileMigrationDefinition(),
|
||||
...this.toDeclarativeDefinitions(specs.slice(2)),
|
||||
this.createStartupScriptDefinition(),
|
||||
this.createAutostartScriptsDefinition(),
|
||||
];
|
||||
@@ -5029,7 +5209,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
private renderAutomateSettings(container: HTMLElement): void {
|
||||
const description = container.createDiv({ cls: "setting-item-description" });
|
||||
setSanitizedHtml(description, t("EA_DESC"));
|
||||
this.renderSettingSpecs(container, this.getAutomateSpecs());
|
||||
const specs = this.getAutomateSpecs();
|
||||
this.renderSettingSpecs(container, specs.slice(0, 2));
|
||||
if (this.plugin.settings.allowJavaScriptFiles) {
|
||||
this.configureScriptFileStorageSetting(new Setting(container));
|
||||
this.configureScriptFileMigrationSetting(new Setting(container));
|
||||
}
|
||||
this.renderSettingSpecs(container, specs.slice(2));
|
||||
this.configureStartupScriptSetting(new Setting(container));
|
||||
new AutostartScriptsSettingsComponent(
|
||||
container.createDiv(),
|
||||
@@ -5040,13 +5226,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
private configureStartupScriptSetting(setting: Setting): void {
|
||||
let startupScriptPathText: TextComponent;
|
||||
let startupScriptButton: ButtonComponent;
|
||||
const resolveStartupPath = (value: string): string | null => {
|
||||
if (this.plugin.scriptEngine) {
|
||||
return this.plugin.scriptEngine.resolveStartupScriptPath(value);
|
||||
}
|
||||
const path = resolveConfiguredStartupScriptPath(value);
|
||||
if (!path) {
|
||||
return null;
|
||||
}
|
||||
if (path.toLowerCase().endsWith(".js")) {
|
||||
return this.plugin.settings.allowJavaScriptFiles ? path : null;
|
||||
}
|
||||
return path;
|
||||
};
|
||||
const scriptExists = () => {
|
||||
const startupPath = normalizePath(
|
||||
this.plugin.settings.startupScriptPath.endsWith(".md")
|
||||
? this.plugin.settings.startupScriptPath
|
||||
: `${this.plugin.settings.startupScriptPath}.md`,
|
||||
const startupPath = resolveStartupPath(
|
||||
this.plugin.settings.startupScriptPath,
|
||||
);
|
||||
return Boolean(this.app.vault.getAbstractFileByPath(startupPath));
|
||||
return Boolean(startupPath && this.app.vault.getFileByPath(startupPath));
|
||||
};
|
||||
const updateStartupScriptButton = (button: ButtonComponent): void => {
|
||||
const exists = scriptExists();
|
||||
@@ -5072,9 +5269,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
});
|
||||
this.addVaultPathSupport(setting, text, "file", {
|
||||
optional: true,
|
||||
extensions: ["md"],
|
||||
resolvePath: (value) =>
|
||||
value && !value.endsWith(".md") ? `${value}.md` : value,
|
||||
extensions: this.plugin.settings.allowJavaScriptFiles
|
||||
? ["md", "js"]
|
||||
: ["md"],
|
||||
resolvePath: (value) => resolveStartupPath(value) ?? value,
|
||||
});
|
||||
})
|
||||
.addButton((button) => {
|
||||
@@ -5090,12 +5288,14 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
);
|
||||
this.applySettingsUpdate();
|
||||
}
|
||||
const startupPath = normalizePath(
|
||||
this.plugin.settings.startupScriptPath.endsWith(".md")
|
||||
? this.plugin.settings.startupScriptPath
|
||||
: `${this.plugin.settings.startupScriptPath}.md`,
|
||||
const startupPath = resolveStartupPath(
|
||||
this.plugin.settings.startupScriptPath,
|
||||
);
|
||||
let file = this.app.vault.getAbstractFileByPath(startupPath);
|
||||
if (!startupPath) {
|
||||
new Notice(t("STARTUP_SCRIPT_JS_DISABLED"));
|
||||
return;
|
||||
}
|
||||
let file = this.app.vault.getFileByPath(startupPath);
|
||||
if (!file) {
|
||||
file = await createOrOverwriteFile(
|
||||
this.app,
|
||||
|
||||
@@ -12,12 +12,6 @@ import type {
|
||||
SettingDefinitionItem,
|
||||
} from "src/types/obsidianDeclarativeSettings";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
declare const deliberateCreateElement: (
|
||||
document: Document,
|
||||
tagName: string,
|
||||
) => HTMLElement;
|
||||
|
||||
interface MarkdownDefinitionMetadata {
|
||||
controlType?: string;
|
||||
omit?: boolean;
|
||||
@@ -42,9 +36,7 @@ function toMarkdown(value: string | DocumentFragment | undefined): string {
|
||||
return htmlToMarkdown(value).trim();
|
||||
}
|
||||
|
||||
const container = deliberateCreateElement(mainDocument, "div");
|
||||
container.appendChild(value.cloneNode(true));
|
||||
return htmlToMarkdown(container.innerHTML).trim();
|
||||
return htmlToMarkdown(value.cloneNode(true) as DocumentFragment).trim();
|
||||
}
|
||||
|
||||
function normalizeControlType(controlType: string): string {
|
||||
|
||||
@@ -56,6 +56,8 @@ export interface ExcalidrawSettings {
|
||||
embedUseExcalidrawFolder: boolean;
|
||||
templateFilePath: string;
|
||||
scriptFolderPath: string;
|
||||
allowJavaScriptFiles: boolean;
|
||||
storeScriptFilesAsJavaScript: boolean;
|
||||
fontAssetsPath: string;
|
||||
loadChineseFonts: boolean;
|
||||
loadJapaneseFonts: boolean;
|
||||
@@ -501,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,
|
||||
|
||||
+32
-2
@@ -298,6 +298,8 @@ export default {
|
||||
"Error, can't read file path. Importing file instead",
|
||||
NO_SEARCH_RESULT: "Didn't find a matching element in the drawing",
|
||||
FORCE_SAVE_ABORTED: "Force Save aborted because saving is in progress",
|
||||
DRAWING_RELOAD_FAILED:
|
||||
"Excalidraw rejected invalid incoming Drawing data. The drawing currently open on the canvas was preserved. Save or export it before closing this view, and review the synchronized file or its version history.",
|
||||
LINKLIST_SECOND_ORDER_LINK: "Second Order Link",
|
||||
MARKDOWN_EMBED_CUSTOMIZE_LINK_PROMPT_TITLE:
|
||||
"Customize the Embedded File link",
|
||||
@@ -1329,6 +1331,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?",
|
||||
@@ -1361,9 +1390,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",
|
||||
|
||||
+31
-2
@@ -1298,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?",
|
||||
@@ -1331,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:
|
||||
|
||||
+31
-2
@@ -1205,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-скрипты?",
|
||||
@@ -1237,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:
|
||||
|
||||
@@ -1236,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>。是否启用加载期脚本?",
|
||||
@@ -1267,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 文件添加类型标识符(如 ✏️)",
|
||||
|
||||
@@ -1236,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>。是否啟用載入期指令碼?",
|
||||
@@ -1267,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 檔案新增型別識別符號(如 ✏️)",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
type PendingBackup = {
|
||||
data: string;
|
||||
onComplete?: (durationMs: number | undefined) => void;
|
||||
};
|
||||
|
||||
type BackupWriteState = {
|
||||
@@ -12,8 +11,7 @@ type BackupWriteState = {
|
||||
type BackupPersistenceQueueOptions = {
|
||||
ownerWindow: Window;
|
||||
write: (filepath: string, data: string) => Promise<void>;
|
||||
getTimestamp?: () => number | undefined;
|
||||
onError?: (error: unknown, stage: "write" | "onComplete") => void;
|
||||
onError?: (error: unknown, stage: "write") => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -27,14 +25,12 @@ type BackupPersistenceQueueOptions = {
|
||||
export class BackupPersistenceQueue {
|
||||
private readonly ownerWindow: Window;
|
||||
private readonly write: BackupPersistenceQueueOptions["write"];
|
||||
private readonly getTimestamp?: BackupPersistenceQueueOptions["getTimestamp"];
|
||||
private readonly onError?: BackupPersistenceQueueOptions["onError"];
|
||||
private readonly writes = new Map<string, BackupWriteState>();
|
||||
|
||||
constructor(options: BackupPersistenceQueueOptions) {
|
||||
this.ownerWindow = options.ownerWindow;
|
||||
this.write = options.write;
|
||||
this.getTimestamp = options.getTimestamp;
|
||||
this.onError = options.onError;
|
||||
}
|
||||
|
||||
@@ -44,12 +40,7 @@ export class BackupPersistenceQueue {
|
||||
* @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,
|
||||
onComplete?: PendingBackup["onComplete"],
|
||||
): boolean {
|
||||
public schedule(filepath: string, data: string, delayMs: number): boolean {
|
||||
let state = this.writes.get(filepath);
|
||||
if (!state) {
|
||||
state = { timer: null, inFlight: null, pending: null };
|
||||
@@ -57,7 +48,7 @@ export class BackupPersistenceQueue {
|
||||
}
|
||||
|
||||
const coalesced = state.pending !== null || state.inFlight !== null;
|
||||
state.pending = { data, onComplete };
|
||||
state.pending = { data };
|
||||
this.clearTimer(state);
|
||||
if (state.inFlight === null) {
|
||||
this.scheduleDrain(filepath, state, delayMs);
|
||||
@@ -154,21 +145,10 @@ export class BackupPersistenceQueue {
|
||||
|
||||
const pending = state.pending;
|
||||
state.pending = null;
|
||||
const start = this.getTimestamp?.();
|
||||
const write = this.write(filepath, pending.data);
|
||||
state.inFlight = write;
|
||||
try {
|
||||
await write;
|
||||
if (this.writes.get(filepath) === state) {
|
||||
try {
|
||||
const end = start === undefined ? undefined : this.getTimestamp?.();
|
||||
pending.onComplete?.(
|
||||
start !== undefined && end !== undefined ? end - start : undefined,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
this.onError?.(error, "onComplete");
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
this.onError?.(error, "write");
|
||||
} finally {
|
||||
|
||||
@@ -8,8 +8,6 @@ import { svgToBase64 } from "../utils/utils";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { nanoid } from "src/constants/constants";
|
||||
|
||||
declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;
|
||||
declare const mainDocument: Document;
|
||||
/**
|
||||
* Creates a masked image from an Excalidraw scene.
|
||||
*
|
||||
@@ -206,7 +204,7 @@ export class CropImage {
|
||||
const svgData = svg.outerHTML;
|
||||
//const svgData = new XMLSerializer().serializeToString(svg);
|
||||
// canvas should never be attached to the DOM
|
||||
const canvas = deliberateCreateElement(mainDocument, "canvas") as HTMLCanvasElement;
|
||||
const canvas = createFragment().createEl("canvas");
|
||||
const context = canvas.getContext("2d");
|
||||
|
||||
if (!context) {
|
||||
|
||||
@@ -16,12 +16,29 @@ export const RELEASE_NOTES: { [k: string]: string } = {
|
||||
I build this plugin as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}). Want to master Excalidraw? Join [Excalidraw Mastery](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}). If you find it valuable, say "Thank you", and
|
||||
|
||||
<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.2": `
|
||||
## Fixed
|
||||
- Canvas properties (tray and desktop UI modes) and the element properties (tray-mode only) were moved to the top left corner of the Obsidian workspace when changing tabs.
|
||||
- Back of the note cards did not display if the filename included "?" character on MacOS.
|
||||
|
||||
`,
|
||||
"2.27.1": `
|
||||
## Fixed
|
||||
- Small technical hiccup during the deployment of 2.27.0
|
||||
|
||||
## New from Excalidraw.com
|
||||
- This unfortunate hiccup has made it possible to squeeze in one more new feature: Movable arrow labels in Excalidraw!
|
||||
`,
|
||||
"2.27.0": `
|
||||
${getYouTubeDiv("am2HOlbYsxI")}
|
||||
|
||||
## 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.
|
||||
- On Obsidian 1.13 and newer, Excalidraw now uses Obsidian's searchable, multi-page settings organized into clearer sections with breadcrumbs and clickable links between related options.
|
||||
- If you prefer the previous experience you can 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**.
|
||||
- Excalidraw Automate can optionally load and monitor JavaScript (\`.js\`) files in the Scripts folder, use an explicit \`.js\` ExcalidrawStartup 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)
|
||||
@@ -29,30 +46,38 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
- 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
|
||||
- Opening inline link suggestions while editing text no longer triggers a save that can end text editing, including after duplicating a LaTeX formula.
|
||||
- Downloading very large SVG or PNG exports now avoids base64 conversion, substantially reducing peak memory use and preventing Electron renderer crashes on image-heavy drawings.
|
||||
- Moving a dirty drawing out of a popout window now safely transfers and persists its latest edits from the replacement main-window view.
|
||||
- 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.
|
||||
- This is one of the Plugin's largest internal maintenance releases ever. The settings system, persistence pipeline, plugin lifecycle, runtime packaging, and several major managers were reorganized into clearer, independently maintained components. On the surface the plugin works as before, 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.
|
||||
- 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
|
||||
- Added area-bounded view exports for image-heavy scenes. \`createViewSVG()\` and the new \`createViewPNG()\` accept \`exportArea: {x, y, width, height}\`, filter out off-area elements and unused image payloads, retain required bound elements, and crop to the requested viewport. Both methods also support a complete \`elementsOverride\` export set.
|
||||
- Added \`getElementsIntersectionArea()\` for explicitly selecting elements whose rendered bounds intersect an area. The existing \`getElementsInArea()\` method remains available as a backward-compatible alias.
|
||||
- \`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 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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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[], exportArea?: ViewExportArea}): Promise<SVGSVGElement>",
|
||||
desc:
|
||||
"Creates an SVG representation of the current view with specified options.\n" +
|
||||
"\n" +
|
||||
@@ -299,6 +299,8 @@ 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" +
|
||||
"@param {ViewExportArea} [options.exportArea] - Filters elements to an exact scene rectangle and anchors the SVG to that viewport.\n" +
|
||||
"@returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} FrameRenderingOptions\n" +
|
||||
@@ -315,6 +317,21 @@ 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" +
|
||||
" // exportArea: { x: 0, y: 0, width: 1920, height: 1080 },\n" +
|
||||
"});",
|
||||
},
|
||||
{
|
||||
field: "createViewPNG",
|
||||
code: "async createViewPNG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, embedScene?: boolean, elementsOverride?: readonly ExcalidrawElement[], exportArea?: ViewExportArea, scale?: number}): Promise<Blob>",
|
||||
desc:
|
||||
"Creates a PNG from the currently active Excalidraw view without using or modifying the EA workbench.\n" +
|
||||
"elementsOverride is a complete replacement for the view elements. exportArea filters that candidate set and anchors the image to an exact scene rectangle. The optional scale controls raster resolution.",
|
||||
after:
|
||||
"({\n" +
|
||||
" withBackground: true,\n" +
|
||||
" exportArea: { x: 0, y: 0, width: 1920, height: 1080 },\n" +
|
||||
" scale: 0.5,\n" +
|
||||
"});",
|
||||
},
|
||||
{
|
||||
@@ -506,24 +523,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);',
|
||||
},
|
||||
{
|
||||
@@ -687,8 +705,14 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "getElementsInArea",
|
||||
code: "getElementsInArea(elements: ExcalidrawElement[], area: {x: number, y: number, width: number, height: number}): ExcalidrawElement[];",
|
||||
desc: "Filter the elements and returns only those within the specific area.",
|
||||
code: "getElementsInArea(elements: readonly ExcalidrawElement[], area: {x: number, y: number, width: number, height: number, id?: string}, options?: {margin?: number, includeMarkerFrames?: boolean, includeBoundElements?: boolean}): ExcalidrawElement[];",
|
||||
desc: "Returns elements whose rendered bounds intersect the area, preserving source stacking order. Marker frames remain excluded by default for backward compatibility. Optional binding expansion includes containers, bound elements, and arrow binding targets.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getElementsIntersectionArea",
|
||||
code: "getElementsIntersectionArea(elements: readonly ExcalidrawElement[], area: {x: number, y: number, width: number, height: number, id?: string}, options?: {margin?: number, includeMarkerFrames?: boolean, includeBoundElements?: boolean}): ExcalidrawElement[];",
|
||||
desc: "Preferred explicit name for selecting elements whose rendered bounds intersect an area. It shares the implementation and behavior of the backward-compatible getElementsInArea() API.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -996,6 +1020,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 +1037,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 +1045,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 +1449,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[] = [
|
||||
|
||||
@@ -85,13 +85,6 @@ import {
|
||||
} from "src/types/markdownImageTypes";
|
||||
import { resolveMarkdownImageRenderSettings } from "src/utils/markdownImageUtils";
|
||||
import { addAppendUpdateCustomData } from "src/utils/elementCustomDataUtils";
|
||||
import {
|
||||
performanceDiagnosticIncrement,
|
||||
performanceDiagnosticLog,
|
||||
performanceDiagnosticNow,
|
||||
performanceDiagnosticRecordDuration,
|
||||
performanceDiagnosticsEnabled,
|
||||
} from "src/utils/performanceDiagnostics";
|
||||
|
||||
//declared in rollup.config.mjs
|
||||
declare const deliberateFetch: (
|
||||
@@ -111,6 +104,7 @@ 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"
|
||||
@@ -341,7 +335,7 @@ const ISOLATED_MARKDOWN_RENDER_CSS = `
|
||||
const snapshotRenderedCanvases = (container: HTMLElement): void => {
|
||||
container.querySelectorAll("canvas").forEach((canvas) => {
|
||||
try {
|
||||
const image = deliberateCreateElement(canvas.ownerDocument, "img") as HTMLImageElement;
|
||||
const image = createFragment().createEl("img");
|
||||
image.src = canvas.toDataURL("image/png");
|
||||
image.width = canvas.width;
|
||||
image.height = canvas.height;
|
||||
@@ -867,10 +861,6 @@ export class EmbeddedFilesLoader {
|
||||
|
||||
let cachedSize: Size | undefined;
|
||||
let cachedHasSVGwithBitmap: boolean | undefined;
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const cacheLookupStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
const maybeSVG = shouldUseCache
|
||||
? await getImageCache().getImageFromCache(cacheKey, {
|
||||
skipDependencyCheck: cacheValidation === "stale-first",
|
||||
@@ -889,16 +879,6 @@ export class EmbeddedFilesLoader {
|
||||
},
|
||||
})
|
||||
: undefined;
|
||||
if (diagnosticsEnabled && shouldUseCache) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheLookup",
|
||||
performanceDiagnosticNow() - cacheLookupStart,
|
||||
);
|
||||
performanceDiagnosticIncrement(
|
||||
typeof maybeSVG === "string" ? "imageCacheHit" : "imageCacheMiss",
|
||||
);
|
||||
}
|
||||
|
||||
if (this.terminate) {
|
||||
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
|
||||
}
|
||||
@@ -923,9 +903,6 @@ export class EmbeddedFilesLoader {
|
||||
};
|
||||
}
|
||||
|
||||
const generationStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
const generatedSVG = await createSVG(
|
||||
hasFilenameParts
|
||||
? filenameParts.hasGroupref ||
|
||||
@@ -957,13 +934,6 @@ export class EmbeddedFilesLoader {
|
||||
depth + 1,
|
||||
getExportPadding(this.plugin, file),
|
||||
);
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticIncrement("imageGeneration");
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageGeneration",
|
||||
performanceDiagnosticNow() - generationStart,
|
||||
);
|
||||
}
|
||||
const svg = replaceSVGColors(
|
||||
generatedSVG,
|
||||
inFile instanceof EmbeddedFile ? inFile.colorMap : null,
|
||||
@@ -1065,8 +1035,6 @@ export class EmbeddedFilesLoader {
|
||||
depth: number,
|
||||
options?: LoadImageOptions,
|
||||
): Promise<ImgData> {
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const diagnosticsStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
if (!this.plugin || !inFile) {
|
||||
return null;
|
||||
}
|
||||
@@ -1258,16 +1226,6 @@ export class EmbeddedFilesLoader {
|
||||
const loadedFromCache = isExcalidrawFile
|
||||
? excalidrawLoadedFromCache
|
||||
: pdfLoadedFromCache;
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticIncrement("assetLoad");
|
||||
performanceDiagnosticIncrement(
|
||||
loadedFromCache ? "assetLoadedFromCache" : "assetLoadedWithoutCache",
|
||||
);
|
||||
performanceDiagnosticRecordDuration(
|
||||
"assetLoad",
|
||||
performanceDiagnosticNow() - diagnosticsStart,
|
||||
);
|
||||
}
|
||||
return {
|
||||
mimeType,
|
||||
fileId: generatedFileId,
|
||||
@@ -1310,6 +1268,8 @@ export class EmbeddedFilesLoader {
|
||||
onDeferredValidationCandidates,
|
||||
deferredCacheValidation,
|
||||
sceneElements,
|
||||
waitForRender,
|
||||
prioritizedFileIds,
|
||||
}: {
|
||||
excalidrawData: ExcalidrawData;
|
||||
addFiles: (files: FileData[], isDark: boolean, final?: boolean) => void;
|
||||
@@ -1325,6 +1285,8 @@ export class EmbeddedFilesLoader {
|
||||
) => void;
|
||||
deferredCacheValidation?: ReadonlyMap<FileId, DeferredCacheValidation>;
|
||||
sceneElements?: readonly ExcalidrawElement[];
|
||||
waitForRender?: () => Promise<void>;
|
||||
prioritizedFileIds?: ReadonlySet<FileId>;
|
||||
}) {
|
||||
this.terminalState = "running";
|
||||
if (this.isDark === undefined) {
|
||||
@@ -1346,6 +1308,13 @@ export class EmbeddedFilesLoader {
|
||||
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(
|
||||
@@ -1709,7 +1678,6 @@ export class EmbeddedFilesLoader {
|
||||
const runLoadPool = async (
|
||||
iterator: Generator<Promise<void>>,
|
||||
concurrency: number,
|
||||
phase: "initial" | "deferred-generation",
|
||||
): Promise<boolean> => {
|
||||
let stallTimer: number | null = null;
|
||||
let resolveStall!: () => void;
|
||||
@@ -1742,12 +1710,6 @@ export class EmbeddedFilesLoader {
|
||||
|
||||
this.terminalState = "timed-out";
|
||||
this.terminate = true;
|
||||
performanceDiagnosticIncrement("sceneFileLoaderStalled");
|
||||
performanceDiagnosticLog("sceneFiles.loaderStalled", {
|
||||
loaderId: this.uid,
|
||||
phase,
|
||||
stallTimeoutMs: SCENE_FILE_LOAD_STALL_TIMEOUT_MS,
|
||||
});
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -1769,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);
|
||||
@@ -1777,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,
|
||||
@@ -1791,7 +1814,7 @@ export class EmbeddedFilesLoader {
|
||||
validationConcurrency ?? this.plugin.settings.renderingConcurrency;
|
||||
const iterator = loadIterator(this, entries, true, true);
|
||||
if (!this.terminate) {
|
||||
await runLoadPool(iterator, concurency, "initial");
|
||||
await runLoadPool(iterator, concurency);
|
||||
}
|
||||
|
||||
if (this.terminate) {
|
||||
@@ -1804,6 +1827,7 @@ export class EmbeddedFilesLoader {
|
||||
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,
|
||||
);
|
||||
@@ -1823,11 +1847,7 @@ export class EmbeddedFilesLoader {
|
||||
false,
|
||||
false,
|
||||
);
|
||||
await runLoadPool(
|
||||
deferredIterator,
|
||||
concurency,
|
||||
"deferred-generation",
|
||||
);
|
||||
await runLoadPool(deferredIterator, concurency);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1842,6 +1862,7 @@ 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,
|
||||
|
||||
+290
-107
@@ -62,6 +62,7 @@ import {
|
||||
import {
|
||||
//debug,
|
||||
getImageSize,
|
||||
getPNG,
|
||||
isMaskFile,
|
||||
wrapTextAtCharLength,
|
||||
arrayToMap,
|
||||
@@ -154,10 +155,15 @@ import { log } from "../utils/debugHelper";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
import {
|
||||
AddImageOptions,
|
||||
ElementsInAreaOptions,
|
||||
ImageInfo,
|
||||
KeyBlocker,
|
||||
SceneArea,
|
||||
ScriptSettingValue,
|
||||
SVGColorInfo,
|
||||
ViewImageExportOptions,
|
||||
ViewPNGExportOptions,
|
||||
ViewSVGExportOptions,
|
||||
} from "src/types/excalidrawAutomateTypes";
|
||||
import {
|
||||
_measureText,
|
||||
@@ -205,9 +211,12 @@ import {
|
||||
PDFPageProperties,
|
||||
ExportSettings,
|
||||
} from "src/types/exportUtilTypes";
|
||||
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
|
||||
import {
|
||||
AutoexportConfig,
|
||||
ExcalidrawViewScene,
|
||||
} from "src/types/excalidrawViewTypes";
|
||||
import { FloatingModal } from "./Dialogs/FloatingModal";
|
||||
import { ExcalidrawSidepanelView } from "src/view/sidepanel/Sidepanel";
|
||||
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
|
||||
@@ -219,6 +228,12 @@ import { getPDFCropRect } from "src/utils/PDFUtils";
|
||||
import type { SelectedElementMenuAction } from "src/types/elementActionTypes";
|
||||
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
|
||||
import { URL_REGISTRY, URLs } from "src/constants/safeUrls";
|
||||
import {
|
||||
createExportAreaAnchor,
|
||||
getElementsIntersectionArea as selectElementsIntersectionArea,
|
||||
normalizeSceneArea,
|
||||
} from "src/utils/excalidrawElementUtils";
|
||||
import { cropPNGBlob } from "src/utils/imageExportUtils";
|
||||
|
||||
type ExcalidrawAutomateHelpTarget = ((...args: unknown[]) => unknown) | string;
|
||||
|
||||
@@ -245,10 +260,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 +858,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 +867,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 +937,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();
|
||||
}
|
||||
@@ -1660,79 +1722,162 @@ export class ExcalidrawAutomate {
|
||||
await exportToPDF({ SVG, scale, pageProps, filename });
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an SVG representation of the current view.
|
||||
*
|
||||
* @param {Object} options - The options for creating the SVG.
|
||||
* @param {boolean} [options.withBackground=true] - Whether to include the background in the SVG.
|
||||
* @param {"light" | "dark"} [options.theme] - The theme to use for the SVG.
|
||||
* @param {FrameRenderingOptions} [options.frameRendering={enabled: true, name: true, outline: true, clip: true}] - The frame rendering options.
|
||||
* @param {number} [options.padding] - The padding to apply around the SVG.
|
||||
* @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
|
||||
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
|
||||
*/
|
||||
async createViewSVG({
|
||||
withBackground = true,
|
||||
theme,
|
||||
frameRendering = { enabled: true, name: true, outline: true, clip: true },
|
||||
padding,
|
||||
selectedOnly = false,
|
||||
skipInliningFonts = false,
|
||||
embedScene = false,
|
||||
elementsOverride,
|
||||
}: {
|
||||
withBackground?: boolean;
|
||||
theme?: "light" | "dark";
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
skipInliningFonts?: boolean;
|
||||
embedScene?: boolean;
|
||||
elementsOverride?: ExcalidrawElement[];
|
||||
}): Promise<SVGSVGElement> {
|
||||
private prepareViewImageExport(
|
||||
options: ViewImageExportOptions,
|
||||
): {
|
||||
scene: ExcalidrawViewScene;
|
||||
exportSettings: ExportSettings;
|
||||
padding: number;
|
||||
sourceFile: TFile;
|
||||
ownerDocument: Document;
|
||||
exportArea?: SceneArea;
|
||||
exportBounds?: ReturnType<typeof getCommonBoundingBox>;
|
||||
} | null {
|
||||
if (!this.targetView || !this.targetView.file || !this.targetView._loaded) {
|
||||
log("No view loaded");
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
const view = this.targetView;
|
||||
const scene = this.targetView.getScene(selectedOnly);
|
||||
const scene = this.targetView.getScene(options.selectedOnly ?? false);
|
||||
let elements: readonly ExcalidrawElement[] = scene.elements;
|
||||
let files = scene.files;
|
||||
let exportArea: SceneArea | undefined;
|
||||
let exportBounds: ReturnType<typeof getCommonBoundingBox> | undefined;
|
||||
|
||||
if (elementsOverride) {
|
||||
scene.elements = elementsOverride.filter(
|
||||
(el): el is NonDeletedExcalidrawElement => !el.isDeleted,
|
||||
if (options.elementsOverride) {
|
||||
elements = options.elementsOverride;
|
||||
}
|
||||
elements = elements.filter(
|
||||
(el): el is NonDeletedExcalidrawElement => !el.isDeleted,
|
||||
);
|
||||
|
||||
if (options.exportArea) {
|
||||
exportArea = normalizeSceneArea(
|
||||
options.exportArea,
|
||||
options.exportArea.margin,
|
||||
);
|
||||
elements = selectElementsIntersectionArea(elements, exportArea, {
|
||||
includeMarkerFrames: options.exportArea.includeMarkerFrames,
|
||||
includeBoundElements:
|
||||
options.exportArea.includeBoundElements ?? true,
|
||||
});
|
||||
const referencedFileIds = new Set(
|
||||
elements
|
||||
.filter(
|
||||
(element): element is ExcalidrawImageElement =>
|
||||
element.type === "image" && Boolean(element.fileId),
|
||||
)
|
||||
.map((element) => element.fileId),
|
||||
);
|
||||
files = Object.fromEntries(
|
||||
Object.entries(scene.files).filter(([fileId]) =>
|
||||
referencedFileIds.has(fileId as FileId),
|
||||
),
|
||||
);
|
||||
elements = [...elements, createExportAreaAnchor(exportArea)];
|
||||
exportBounds = getCommonBoundingBox(elements);
|
||||
}
|
||||
|
||||
if (!view.getViewExportIncludeInternalLinks()) {
|
||||
scene.elements = sceneRemoveInternalLinks(scene);
|
||||
elements = sceneRemoveInternalLinks({ elements });
|
||||
}
|
||||
|
||||
const exportSettings: ExportSettings = {
|
||||
withBackground: view.getViewExportWithBackground(withBackground),
|
||||
withTheme: true,
|
||||
isMask: isMaskFile(this.plugin, view.file),
|
||||
skipInliningFonts,
|
||||
frameRendering,
|
||||
};
|
||||
|
||||
return await getSVG(
|
||||
{
|
||||
const theme = view.getViewExportTheme(options.theme) as "dark" | "light";
|
||||
return {
|
||||
scene: {
|
||||
...scene,
|
||||
...{
|
||||
appState: {
|
||||
...scene.appState,
|
||||
theme: view.getViewExportTheme(theme) as "dark" | "light",
|
||||
exportEmbedScene: view.getViewExportEmbedScene(embedScene),
|
||||
},
|
||||
elements,
|
||||
files,
|
||||
appState: {
|
||||
...scene.appState,
|
||||
theme,
|
||||
exportEmbedScene: view.getViewExportEmbedScene(options.embedScene),
|
||||
},
|
||||
},
|
||||
exportSettings,
|
||||
view.getViewExportPadding(padding),
|
||||
view.file,
|
||||
exportSettings: {
|
||||
withBackground: view.getViewExportWithBackground(
|
||||
options.withBackground ?? true,
|
||||
),
|
||||
withTheme: true,
|
||||
isMask: isMaskFile(this.plugin, view.file),
|
||||
frameRendering:
|
||||
options.frameRendering ??
|
||||
({ enabled: true, name: true, outline: true, clip: true } as const),
|
||||
},
|
||||
padding: view.getViewExportPadding(options.padding),
|
||||
sourceFile: view.file,
|
||||
ownerDocument: view.ownerDocument,
|
||||
exportArea,
|
||||
exportBounds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an SVG representation of the current view.
|
||||
*
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to the exported SVG, or `undefined` when no
|
||||
* loaded target view is available.
|
||||
*/
|
||||
async createViewSVG(
|
||||
options: ViewSVGExportOptions = {},
|
||||
): Promise<SVGSVGElement> {
|
||||
const prepared = this.prepareViewImageExport(options);
|
||||
if (!prepared) return;
|
||||
prepared.exportSettings.skipInliningFonts =
|
||||
options.skipInliningFonts ?? false;
|
||||
const svg = await getSVG(
|
||||
prepared.scene,
|
||||
prepared.exportSettings,
|
||||
prepared.padding,
|
||||
prepared.sourceFile,
|
||||
);
|
||||
if (svg && prepared.exportArea && prepared.exportBounds) {
|
||||
const originalViewBox = svg.viewBox.baseVal;
|
||||
const exportScale = originalViewBox.width
|
||||
? Number(svg.getAttribute("width")) / originalViewBox.width
|
||||
: 1;
|
||||
const width = prepared.exportArea.width + prepared.padding * 2;
|
||||
const height = prepared.exportArea.height + prepared.padding * 2;
|
||||
svg.setAttribute(
|
||||
"viewBox",
|
||||
`${prepared.exportArea.x - prepared.exportBounds.minX} ${prepared.exportArea.y - prepared.exportBounds.minY} ${width} ${height}`,
|
||||
);
|
||||
svg.setAttribute("width", `${width * exportScale}`);
|
||||
svg.setAttribute("height", `${height * exportScale}`);
|
||||
}
|
||||
return svg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a PNG representation of the current view without using or mutating
|
||||
* the EA workbench.
|
||||
*
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to a PNG blob, or `undefined` when no loaded
|
||||
* target view is available.
|
||||
*/
|
||||
async createViewPNG(options: ViewPNGExportOptions = {}): Promise<Blob> {
|
||||
const prepared = this.prepareViewImageExport(options);
|
||||
if (!prepared) return;
|
||||
const png = await getPNG(
|
||||
prepared.scene,
|
||||
prepared.exportSettings,
|
||||
prepared.padding,
|
||||
options.scale ?? 1,
|
||||
);
|
||||
if (!png || !prepared.exportArea || !prepared.exportBounds) return png;
|
||||
const scale = options.scale ?? 1;
|
||||
return await cropPNGBlob(png, {
|
||||
x: (prepared.exportArea.x - prepared.exportBounds.minX) * scale,
|
||||
y: (prepared.exportArea.y - prepared.exportBounds.minY) * scale,
|
||||
width: (prepared.exportArea.width + prepared.padding * 2) * scale,
|
||||
height: (prepared.exportArea.height + prepared.padding * 2) * scale,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3084,7 +3229,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 +3278,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 +3286,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 +3306,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;
|
||||
@@ -3411,7 +3565,6 @@ export class ExcalidrawAutomate {
|
||||
fileIDWhiteList,
|
||||
resolve,
|
||||
undefined,
|
||||
"excalidraw-automate-svg-color-map",
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -3573,12 +3726,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")) {
|
||||
@@ -3860,7 +4016,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
|
||||
@@ -3930,11 +4088,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()");
|
||||
@@ -3950,13 +4111,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"],
|
||||
@@ -4274,36 +4437,39 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the elements within a specific area.
|
||||
* @param elements - The elements to check.
|
||||
* @param param1 - The area to check against.
|
||||
* @returns The elements within the area.
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsInArea(
|
||||
elements: readonly ExcalidrawElement[],
|
||||
element: ExcalidrawElement,
|
||||
area: SceneArea,
|
||||
options: ElementsInAreaOptions = {},
|
||||
): ExcalidrawElement[] {
|
||||
const { x, y, width, height, id } = element;
|
||||
return elements.filter((el) => {
|
||||
if (el.type === "frame" && el.frameRole === "marker") {
|
||||
return false;
|
||||
}
|
||||
if (el.id === id) {
|
||||
return true;
|
||||
}
|
||||
const { topX, topY, width: w, height: h } = this.getBoundingBox([el]);
|
||||
const elLeft = topX;
|
||||
const elTop = topY;
|
||||
const elRight = topX + w;
|
||||
const elBottom = topY + h;
|
||||
// overlap exists if rectangles intersect
|
||||
return !(
|
||||
elLeft >= x + width ||
|
||||
elRight <= x ||
|
||||
elTop >= y + height ||
|
||||
elBottom <= y
|
||||
);
|
||||
});
|
||||
return this.getElementsIntersectionArea(elements, area, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @remarks
|
||||
* This explicit name is preferred for new code. `getElementsInArea()` remains
|
||||
* available as a backward-compatible alias and uses the same implementation.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsIntersectionArea(
|
||||
elements: readonly ExcalidrawElement[],
|
||||
area: SceneArea,
|
||||
options: ElementsInAreaOptions = {},
|
||||
): ExcalidrawElement[] {
|
||||
return selectElementsIntersectionArea(elements, area, options);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4717,7 +4883,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.
|
||||
*/
|
||||
@@ -5111,9 +5280,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;
|
||||
|
||||
+178
-121
@@ -67,12 +67,6 @@ import { getPDFRect } from "../utils/PDFUtils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { errorlog } from "src/utils/coreUtils";
|
||||
import { log } from "src/utils/debugHelper";
|
||||
import {
|
||||
performanceDiagnosticLog,
|
||||
performanceDiagnosticNow,
|
||||
performanceDiagnosticRecordDuration,
|
||||
performanceDiagnosticsEnabled,
|
||||
} from "src/utils/performanceDiagnostics";
|
||||
import {
|
||||
MARKDOWN_IMAGE_CUSTOM_DATA_KEY,
|
||||
MARKDOWN_IMAGE_EMBEDDED_FILE_TOKEN,
|
||||
@@ -126,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"
|
||||
> & {
|
||||
@@ -257,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;
|
||||
@@ -323,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
|
||||
*/
|
||||
@@ -555,6 +679,42 @@ export class ExcalidrawData {
|
||||
if (!file) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Parse the complete incoming scene before changing the currently loaded
|
||||
// model. A malformed synchronized Drawing section must not leave a valid
|
||||
// open canvas backed by an unloaded or partially cleared ExcalidrawData.
|
||||
// Keep this as the single scene parse so safe reloads do not add CPU work.
|
||||
const sceneJSONandPOS = getJSON(data);
|
||||
if (sceneJSONandPOS.pos === -1) {
|
||||
throw new Error("Excalidraw JSON not found in the file");
|
||||
}
|
||||
let parsedScene: ExcalidrawDataScene | null = null;
|
||||
|
||||
// In compatibility mode if the .excalidraw file was more recently updated than the .md file, then the .excalidraw file
|
||||
// should be loaded as the scene.
|
||||
// This feature is mostly likely only relevant to people who use Obsidian and Logseq on the same vault and edit .excalidraw
|
||||
// drawings in Logseq.
|
||||
if (this.plugin.settings.syncExcalidraw) {
|
||||
const excalfile = `${file.path.substring(
|
||||
0,
|
||||
file.path.lastIndexOf(".md"),
|
||||
)}.excalidraw`;
|
||||
const f = this.app.vault.getAbstractFileByPath(excalfile);
|
||||
if (f && f instanceof TFile && f.stat.mtime > file.stat.mtime) {
|
||||
//the .excalidraw file is newer then the .md file
|
||||
const d = await this.app.vault.read(f);
|
||||
parsedScene = JSON.parse(d) as ExcalidrawDataScene;
|
||||
}
|
||||
}
|
||||
if (!parsedScene) {
|
||||
// Workaround for files merged by sync where one version is still an old
|
||||
// markdown drawing without the fenced code block.
|
||||
parsedScene = JSON_parse(sceneJSONandPOS.scene);
|
||||
}
|
||||
if (!Array.isArray(parsedScene?.elements)) {
|
||||
throw new Error("Invalid Excalidraw scene: elements array is missing");
|
||||
}
|
||||
|
||||
this.loaded = false;
|
||||
this.selectedElementIds = {};
|
||||
this.textElements = new Map<
|
||||
@@ -580,39 +740,9 @@ export class ExcalidrawData {
|
||||
this.setAutoexportPreferences();
|
||||
this.setembeddableThemePreference();
|
||||
|
||||
this.scene = null;
|
||||
|
||||
//In compatibility mode if the .excalidraw file was more recently updated than the .md file, then the .excalidraw file
|
||||
//should be loaded as the scene.
|
||||
//This feature is mostly likely only relevant to people who use Obsidian and Logseq on the same vault and edit .excalidraw
|
||||
//drawings in Logseq.
|
||||
if (this.plugin.settings.syncExcalidraw) {
|
||||
const excalfile = `${file.path.substring(
|
||||
0,
|
||||
file.path.lastIndexOf(".md"),
|
||||
)}.excalidraw`;
|
||||
const f = this.app.vault.getAbstractFileByPath(excalfile);
|
||||
if (f && f instanceof TFile && f.stat.mtime > file.stat.mtime) {
|
||||
//the .excalidraw file is newer then the .md file
|
||||
const d = await this.app.vault.read(f);
|
||||
this.scene = JSON.parse(d) as ExcalidrawDataScene;
|
||||
}
|
||||
}
|
||||
this.scene = parsedScene;
|
||||
|
||||
// https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/396
|
||||
let sceneJSONandPOS = null;
|
||||
const loadJSON = (): { scene: string; pos: number } => {
|
||||
//Load scene: Read the JSON string after "# Drawing"
|
||||
const sceneJSONandPOS = getJSON(data);
|
||||
if (sceneJSONandPOS.pos === -1) {
|
||||
throw new Error("Excalidraw JSON not found in the file");
|
||||
}
|
||||
if (!this.scene) {
|
||||
this.scene = JSON_parse(sceneJSONandPOS.scene); //this is a workaround to address when files are mereged by sync and one version is still an old markdown without the codeblock ```
|
||||
}
|
||||
return sceneJSONandPOS;
|
||||
};
|
||||
sceneJSONandPOS = loadJSON();
|
||||
const parsedMarkdownImages = parseMarkdownImages(data);
|
||||
this.scene.elements.forEach((element: ExcalidrawElement) => {
|
||||
const markdownImageData = element.customData?.[
|
||||
@@ -1405,8 +1535,6 @@ export class ExcalidrawData {
|
||||
*/
|
||||
disableCompression: boolean = false;
|
||||
generateMDBase(deletedElements: ExcalidrawElement[] = []) {
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const metadataStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
const syncTextLinks = this.plugin.settings.syncElementLinkWithText;
|
||||
let outString = this.textElementCommentedOut ? "%%\n" : "";
|
||||
outString += `# Excalidraw Data\n\n## Text Elements\n`;
|
||||
@@ -1491,10 +1619,6 @@ export class ExcalidrawData {
|
||||
}
|
||||
//outString += this.equations.size > 0 || this.files.size > 0 ? "\n" : "";
|
||||
|
||||
const metadataMs = diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - metadataStart
|
||||
: 0;
|
||||
const stringifyStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
const sceneJSONstring = JSON.stringify(
|
||||
{
|
||||
type: this.scene.type,
|
||||
@@ -1507,102 +1631,35 @@ export class ExcalidrawData {
|
||||
null,
|
||||
"\t",
|
||||
);
|
||||
const stringifyMs = diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - stringifyStart
|
||||
: 0;
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration("serializeMetadata", metadataMs);
|
||||
performanceDiagnosticRecordDuration("serializeStringify", stringifyMs);
|
||||
}
|
||||
performanceDiagnosticLog("serialize.generateBase", {
|
||||
viewId: this.view?.id,
|
||||
elements: this.scene.elements.length,
|
||||
deletedElements: deletedElements.length,
|
||||
textElements: this.textElements.size,
|
||||
embeddedFiles: this.files.size,
|
||||
markdownImages: this.markdownImages.size,
|
||||
equations: this.equations.size,
|
||||
mermaids: this.mermaids.size,
|
||||
metadataMs: diagnosticsEnabled ? metadataMs : undefined,
|
||||
stringifyMs: diagnosticsEnabled ? stringifyMs : undefined,
|
||||
metadataBytes: outString.length,
|
||||
sceneJsonBytes: sceneJSONstring.length,
|
||||
});
|
||||
return { outString, sceneJSONstring };
|
||||
}
|
||||
|
||||
async generateMDAsync(
|
||||
deletedElements: ExcalidrawElement[] = [],
|
||||
): Promise<string> {
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const totalStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
const { outString, sceneJSONstring } = this.generateMDBase(deletedElements);
|
||||
const compressionStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
const drawingSection = await getMarkdownDrawingSectionAsync(
|
||||
sceneJSONstring,
|
||||
this.disableCompression ? false : this.plugin.settings.compress,
|
||||
);
|
||||
const compressionMs = diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - compressionStart
|
||||
: 0;
|
||||
const result =
|
||||
return (
|
||||
outString +
|
||||
(this.textElementCommentedOut ? "" : "%%\n") +
|
||||
drawingSection;
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration("serializeCompression", compressionMs);
|
||||
}
|
||||
performanceDiagnosticLog("serialize.compression", {
|
||||
viewId: this.view?.id,
|
||||
mode: "async",
|
||||
compressed:
|
||||
!this.disableCompression && this.plugin.settings.compress,
|
||||
inputBytes: sceneJSONstring.length,
|
||||
drawingSectionBytes: drawingSection.length,
|
||||
compressionMs: diagnosticsEnabled ? compressionMs : undefined,
|
||||
totalMs: diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - totalStart
|
||||
: undefined,
|
||||
});
|
||||
return result;
|
||||
drawingSection
|
||||
);
|
||||
}
|
||||
|
||||
generateMDSync(deletedElements: ExcalidrawElement[] = []): string {
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const totalStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
const { outString, sceneJSONstring } = this.generateMDBase(deletedElements);
|
||||
const compressionStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
const drawingSection = getMarkdownDrawingSection(
|
||||
sceneJSONstring,
|
||||
this.disableCompression ? false : this.plugin.settings.compress,
|
||||
);
|
||||
const compressionMs = diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - compressionStart
|
||||
: 0;
|
||||
const result =
|
||||
return (
|
||||
outString +
|
||||
(this.textElementCommentedOut ? "" : "%%\n") +
|
||||
drawingSection;
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration("serializeCompression", compressionMs);
|
||||
}
|
||||
performanceDiagnosticLog("serialize.compression", {
|
||||
viewId: this.view?.id,
|
||||
mode: "sync",
|
||||
compressed:
|
||||
!this.disableCompression && this.plugin.settings.compress,
|
||||
inputBytes: sceneJSONstring.length,
|
||||
drawingSectionBytes: drawingSection.length,
|
||||
compressionMs: diagnosticsEnabled ? compressionMs : undefined,
|
||||
totalMs: diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - totalStart
|
||||
: undefined,
|
||||
});
|
||||
return result;
|
||||
drawingSection
|
||||
);
|
||||
}
|
||||
|
||||
public async saveDataURLtoVault(
|
||||
|
||||
+8
-148
@@ -9,12 +9,6 @@ import { hasExcalidrawEmbeddedImagesTreeChanged } from "../utils/fileUtils";
|
||||
import { EXCALIDRAW_PLUGIN } from "src/constants/constants";
|
||||
import { blobToDataURL } from "../utils/coreUtils";
|
||||
import { isInstanceOfSVGSVGElement } from "../utils/typechecks";
|
||||
import {
|
||||
performanceDiagnosticIncrement,
|
||||
performanceDiagnosticNow,
|
||||
performanceDiagnosticRecordDuration,
|
||||
performanceDiagnosticsEnabled,
|
||||
} from "../utils/performanceDiagnostics";
|
||||
import { BackupPersistenceQueue } from "./BackupPersistenceQueue";
|
||||
|
||||
type FileCacheData = {
|
||||
@@ -97,8 +91,6 @@ class ImageCache {
|
||||
private backupWrites = new BackupPersistenceQueue({
|
||||
ownerWindow: window,
|
||||
write: (filepath, data) => this.addBAKToCache(filepath, data),
|
||||
getTimestamp: () =>
|
||||
performanceDiagnosticsEnabled() ? performanceDiagnosticNow() : undefined,
|
||||
onError: (error, stage) =>
|
||||
errorlog({
|
||||
where: "ImageCache.backupWrites",
|
||||
@@ -532,38 +524,19 @@ class ImageCache {
|
||||
key_: ImageKey,
|
||||
options?: GetImageFromCacheOptions,
|
||||
): Promise<{ cacheData: FileCacheData; key: string } | undefined> {
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const totalStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
const key = getKey(key_);
|
||||
if (!this.isReady()) {
|
||||
performanceDiagnosticIncrement("imageCacheRejectNotReady");
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const readyStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
await this.ensureCacheStoreReady();
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheReadyWait",
|
||||
performanceDiagnosticNow() - readyStart,
|
||||
);
|
||||
}
|
||||
|
||||
const idbStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
const cachedData = await this.getCacheData(key);
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheIndexedDbRead",
|
||||
performanceDiagnosticNow() - idbStart,
|
||||
);
|
||||
}
|
||||
if (!cachedData) {
|
||||
performanceDiagnosticIncrement("imageCacheRejectMissing");
|
||||
return undefined;
|
||||
}
|
||||
if (!this.isCurrentCacheData(cachedData)) {
|
||||
performanceDiagnosticIncrement("imageCacheRejectInvalidSchema");
|
||||
const transaction = this.db.transaction(
|
||||
[this.cacheStoreName, this.cacheAccessStoreName],
|
||||
"readwrite",
|
||||
@@ -576,34 +549,20 @@ class ImageCache {
|
||||
|
||||
const file = this.app.vault.getFileByPath(key_.filepath.split("#")[0]);
|
||||
if (!file) {
|
||||
performanceDiagnosticIncrement("imageCacheRejectFileMissing");
|
||||
return undefined;
|
||||
}
|
||||
if (cachedData.mtime < file.stat.mtime) {
|
||||
performanceDiagnosticIncrement("imageCacheRejectStaleMtime");
|
||||
return undefined;
|
||||
}
|
||||
if (!options?.skipDependencyCheck) {
|
||||
const dependencyStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
const dependencyChanged = hasExcalidrawEmbeddedImagesTreeChanged(
|
||||
file,
|
||||
cachedData.mtime,
|
||||
this.plugin,
|
||||
);
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheDependencyCheck",
|
||||
performanceDiagnosticNow() - dependencyStart,
|
||||
);
|
||||
}
|
||||
if (dependencyChanged) {
|
||||
performanceDiagnosticIncrement("imageCacheRejectDependencyChanged");
|
||||
return undefined;
|
||||
}
|
||||
} else {
|
||||
performanceDiagnosticIncrement("imageCacheDependencyCheckSkipped");
|
||||
}
|
||||
// Validated reads can require a minimum render scale so lower-resolution PDF
|
||||
// snapshots are upgraded in the background without blocking the first paint.
|
||||
@@ -612,14 +571,12 @@ class ImageCache {
|
||||
options?.minRenderScale &&
|
||||
cachedRenderScale < options.minRenderScale
|
||||
) {
|
||||
performanceDiagnosticIncrement("imageCacheRejectRenderScale");
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
options?.expectedPayloadKind &&
|
||||
cachedData.payloadKind !== options.expectedPayloadKind
|
||||
) {
|
||||
performanceDiagnosticIncrement("imageCacheRejectPayloadKind");
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
@@ -627,7 +584,6 @@ class ImageCache {
|
||||
cachedData.payloadKind === "svg" &&
|
||||
typeof cachedData.hasSVGwithBitmap !== "boolean"
|
||||
) {
|
||||
performanceDiagnosticIncrement("imageCacheRejectSvgMetadata");
|
||||
return undefined;
|
||||
}
|
||||
options?.onCacheHit?.({
|
||||
@@ -638,14 +594,8 @@ class ImageCache {
|
||||
payloadKind: cachedData.payloadKind,
|
||||
});
|
||||
this.touchCacheData(key);
|
||||
performanceDiagnosticIncrement(
|
||||
cachedData.payloadKind === "svg"
|
||||
? "imageCacheResolvedSvg"
|
||||
: "imageCacheResolvedRaster",
|
||||
);
|
||||
return { cacheData: cachedData, key };
|
||||
} catch (error) {
|
||||
performanceDiagnosticIncrement("imageCacheResolveError");
|
||||
console.error(
|
||||
"unexpected error in getResolvedCacheData",
|
||||
"ImageCache.getResolvedCacheData",
|
||||
@@ -653,13 +603,6 @@ class ImageCache {
|
||||
error,
|
||||
);
|
||||
return undefined;
|
||||
} finally {
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheResolveTotal",
|
||||
performanceDiagnosticNow() - totalStart,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -674,104 +617,23 @@ class ImageCache {
|
||||
key_: ImageKey,
|
||||
options?: GetImageFromCacheOptions,
|
||||
): Promise<string | SVGSVGElement | undefined> {
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const totalStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
const resolved = await this.getResolvedCacheData(key_, options);
|
||||
if (!resolved) {
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheGetImageTotal",
|
||||
performanceDiagnosticNow() - totalStart,
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { cacheData, key } = resolved;
|
||||
const materializeStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
if (cacheData.payloadKind === "svg") {
|
||||
if (options?.svgFormat === "data-url") {
|
||||
const convertStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
const dataUrl = await blobToDataURL(cacheData.blob);
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheSvgDataUrl",
|
||||
performanceDiagnosticNow() - convertStart,
|
||||
);
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheMaterialize",
|
||||
performanceDiagnosticNow() - materializeStart,
|
||||
);
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheGetImageTotal",
|
||||
performanceDiagnosticNow() - totalStart,
|
||||
);
|
||||
}
|
||||
return dataUrl;
|
||||
return blobToDataURL(cacheData.blob);
|
||||
}
|
||||
const blobReadStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
const svgText = await cacheData.blob.text();
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheSvgBlobRead",
|
||||
performanceDiagnosticNow() - blobReadStart,
|
||||
);
|
||||
}
|
||||
const parseStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
const svg = convertSVGStringToElement(svgText);
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheSvgParse",
|
||||
performanceDiagnosticNow() - parseStart,
|
||||
);
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheMaterialize",
|
||||
performanceDiagnosticNow() - materializeStart,
|
||||
);
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheGetImageTotal",
|
||||
performanceDiagnosticNow() - totalStart,
|
||||
);
|
||||
}
|
||||
return svg;
|
||||
return convertSVGStringToElement(svgText);
|
||||
}
|
||||
if (this.obsidanURLCache.has(key)) {
|
||||
performanceDiagnosticIncrement("imageCacheRasterUrlMemoryHit");
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheMaterialize",
|
||||
performanceDiagnosticNow() - materializeStart,
|
||||
);
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheGetImageTotal",
|
||||
performanceDiagnosticNow() - totalStart,
|
||||
);
|
||||
}
|
||||
return this.obsidanURLCache.get(key);
|
||||
}
|
||||
const objectUrlStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
const obsidianURL = URL.createObjectURL(cacheData.blob);
|
||||
performanceDiagnosticIncrement("imageCacheRasterUrlCreated");
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheRasterObjectUrl",
|
||||
performanceDiagnosticNow() - objectUrlStart,
|
||||
);
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheMaterialize",
|
||||
performanceDiagnosticNow() - materializeStart,
|
||||
);
|
||||
performanceDiagnosticRecordDuration(
|
||||
"imageCacheGetImageTotal",
|
||||
performanceDiagnosticNow() - totalStart,
|
||||
);
|
||||
}
|
||||
this.obsidanURLCache.set(key, obsidianURL);
|
||||
return obsidianURL;
|
||||
}
|
||||
@@ -824,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(" ", " ")], {
|
||||
type: "image/svg+xml",
|
||||
})
|
||||
: image;
|
||||
const blob = isSVGElement
|
||||
? new Blob([image.outerHTML.replaceAll(" ", " ")], {
|
||||
type: "image/svg+xml",
|
||||
})
|
||||
: image;
|
||||
const now = Date.now();
|
||||
const data: FileCacheData = {
|
||||
schemaVersion: 2,
|
||||
@@ -893,9 +754,8 @@ class ImageCache {
|
||||
filepath: string,
|
||||
data: BackupData,
|
||||
delayMs: number,
|
||||
onComplete?: (durationMs: number | undefined) => void,
|
||||
): boolean {
|
||||
return this.backupWrites.schedule(filepath, data, delayMs, onComplete);
|
||||
return this.backupWrites.schedule(filepath, data, delayMs);
|
||||
}
|
||||
|
||||
/** Flushes any queued backup before a drawing path is renamed. */
|
||||
|
||||
+677
-158
File diff suppressed because it is too large.
Load diff
@@ -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);
|
||||
|
||||
@@ -5,10 +5,6 @@ import { setStyle } from "src/utils/styleUtils";
|
||||
import { isInstanceOfHTMLElement } from "src/utils/typechecks";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
declare const deliberateCreateElement: (
|
||||
document: Document,
|
||||
tagName: string,
|
||||
) => HTMLElement;
|
||||
|
||||
export class ContentSearcher {
|
||||
private contentDiv: HTMLElement;
|
||||
@@ -159,33 +155,35 @@ export class ContentSearcher {
|
||||
);
|
||||
const nodesToExport =
|
||||
startIndex > -1 ? childNodes.slice(startIndex) : childNodes;
|
||||
const htmlContainer = deliberateCreateElement(mainDocument, "div");
|
||||
const fragment = createFragment();
|
||||
|
||||
nodesToExport.forEach((node) => {
|
||||
htmlContainer.appendChild(node.cloneNode(true));
|
||||
fragment.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>`,
|
||||
);
|
||||
};
|
||||
const headingTags = ["h1", "h2", "h3", "h4"] as const;
|
||||
headingTags.forEach((headingTag, index) => {
|
||||
fragment
|
||||
.querySelectorAll(`summary.excalidraw-setting-h${index + 1}`)
|
||||
.forEach((summary) => {
|
||||
if (summary.children.length > 0 || !summary.textContent) {
|
||||
return;
|
||||
}
|
||||
const heading = summary.createEl(headingTag, {
|
||||
text: summary.textContent,
|
||||
});
|
||||
summary.replaceChildren(heading);
|
||||
});
|
||||
});
|
||||
fragment.querySelectorAll("div.setting-item-name").forEach((name) => {
|
||||
if (name.children.length > 0 || !name.textContent) {
|
||||
return;
|
||||
}
|
||||
const heading = fragment.createEl("h5", { text: name.textContent });
|
||||
name.replaceWith(heading);
|
||||
});
|
||||
|
||||
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);
|
||||
const markdown = htmlToMarkdown(fragment);
|
||||
void window.navigator.clipboard.writeText(markdown);
|
||||
new Notice(t("SEARCH_COPIED_TO_CLIPBOARD"));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import {
|
||||
AppState,
|
||||
DataURL,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { TFile } from "obsidian";
|
||||
import { FileId } from "src/core";
|
||||
import type { FrameRenderingOptions } from "./utilTypes";
|
||||
import {
|
||||
ColorMap,
|
||||
PDFPageViewProps,
|
||||
@@ -58,3 +63,61 @@ export interface AddImageOptions {
|
||||
anchor?: boolean;
|
||||
colorMap?: ColorMap;
|
||||
}
|
||||
|
||||
/** A rectangular region in Excalidraw scene coordinates. */
|
||||
export interface SceneArea {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
/** Optional ID of an element representing the area. */
|
||||
id?: string;
|
||||
}
|
||||
|
||||
/** Controls how {@link ExcalidrawAutomate.getElementsInArea} selects elements. */
|
||||
export interface ElementsInAreaOptions {
|
||||
/** Expands the area by this many scene units on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames. Existing behavior excludes them by default. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/** Includes containers, bound elements, and arrow binding targets needed by the result. */
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
|
||||
/** Restricts a view image export to a rectangular scene region. */
|
||||
export interface ViewExportArea extends SceneArea {
|
||||
/** Expands both the selected content and exported viewport on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames in the export candidate set. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/**
|
||||
* Includes containers, bound elements, and arrow binding targets needed to
|
||||
* render intersecting elements. Defaults to `true` for area exports.
|
||||
*/
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
|
||||
/** Options shared by view-based SVG and PNG exports. */
|
||||
export interface ViewImageExportOptions {
|
||||
withBackground?: boolean;
|
||||
theme?: AppState["theme"];
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
embedScene?: boolean;
|
||||
/** Complete replacement for the view elements used by the export. */
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
/** Filters and anchors the export to an exact scene rectangle. */
|
||||
exportArea?: ViewExportArea;
|
||||
}
|
||||
|
||||
/** Options for {@link ExcalidrawAutomate.createViewSVG}. */
|
||||
export interface ViewSVGExportOptions extends ViewImageExportOptions {
|
||||
skipInliningFonts?: boolean;
|
||||
}
|
||||
|
||||
/** Options for {@link ExcalidrawAutomate.createViewPNG}. */
|
||||
export interface ViewPNGExportOptions extends ViewImageExportOptions {
|
||||
/** Raster scale applied to the exported viewport. */
|
||||
scale?: number;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Vendored
+6
-4
@@ -145,16 +145,18 @@ 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 ownership handle for one window-scoped runtime package.
|
||||
* An idempotent handle for the shared runtime acquired by one view.
|
||||
*
|
||||
* @remarks
|
||||
* The captured window remains the package owner even if Obsidian reparents the
|
||||
* consuming view's DOM into another window before view teardown completes.
|
||||
* 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;
|
||||
|
||||
+32
-18
@@ -7,6 +7,12 @@ interface ExcalidrawFontFaceDescriptor {
|
||||
descriptors?: FontFaceDescriptors;
|
||||
}
|
||||
|
||||
/** A locally loaded CJK subset with the descriptors required for font matching. */
|
||||
export interface CJKFontFaceData {
|
||||
dataURL: string;
|
||||
descriptors?: FontFaceDescriptors;
|
||||
}
|
||||
|
||||
const _0 = "Xiaolai-Regular-09850c4077f3fffe707905872e0e2460.woff2";
|
||||
const _1 = "Xiaolai-Regular-7eb9fffd1aa890d07d0f88cc82e6cfe4.woff2";
|
||||
const _2 = "Xiaolai-Regular-60a3089806700d379f11827ee9843b6b.woff2";
|
||||
@@ -1360,51 +1366,59 @@ export function matchesCJKRange(
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the locally configured CJK font subsets selected by plugin settings.
|
||||
*
|
||||
* @param plugin
|
||||
* @returns
|
||||
* - undefined if no CJK ranges are specified
|
||||
* - false if no CJK fonts are found
|
||||
* - array of Data URLs for CJK fonts
|
||||
* @param plugin - Plugin instance used to resolve settings and read font files.
|
||||
* @returns Loaded subsets with their original descriptors, `undefined` when no
|
||||
* CJK range is enabled, or `false` when no matching local font could be loaded.
|
||||
*/
|
||||
export async function getCJKDataURLs(
|
||||
export async function getCJKFontFaceData(
|
||||
plugin: ExcalidrawPlugin,
|
||||
): Promise<string[] | undefined | boolean> {
|
||||
): Promise<CJKFontFaceData[] | undefined | false> {
|
||||
const rangesToLoad = plugin.getCJKFontSettings();
|
||||
if (!(rangesToLoad.c || rangesToLoad.j || rangesToLoad.k)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fontURIs = XiaolaiFontFaces.filter((ff) =>
|
||||
const fontFaces = XiaolaiFontFaces.filter((ff) =>
|
||||
matchesCJKRange(ff, rangesToLoad),
|
||||
).map((ff) => ff.uri);
|
||||
);
|
||||
|
||||
const buffers: ArrayBuffer[] = [];
|
||||
const loadedFaces: Array<{
|
||||
buffer: ArrayBuffer;
|
||||
descriptors?: FontFaceDescriptors;
|
||||
}> = [];
|
||||
|
||||
// Generator to load fonts
|
||||
function* symbolIterator(): Generator<Promise<void>> {
|
||||
for (const uri of fontURIs) {
|
||||
for (const fontFace of fontFaces) {
|
||||
yield promiseTry(async () => {
|
||||
const ab = await plugin.loadFontFromFile(uri);
|
||||
const ab = await plugin.loadFontFromFile(fontFace.uri);
|
||||
if (ab) {
|
||||
buffers.push(ab);
|
||||
loadedFaces.push({
|
||||
buffer: ab,
|
||||
descriptors: fontFace.descriptors,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const concurrency = 5;
|
||||
const iterator = symbolIterator.bind(this)();
|
||||
const iterator = symbolIterator();
|
||||
await new PromisePool(iterator, concurrency).all();
|
||||
|
||||
// Create an array to hold the Data URLs
|
||||
const dataUrls: string[] = [];
|
||||
const result: CJKFontFaceData[] = [];
|
||||
|
||||
for (const buffer of buffers) {
|
||||
for (const { buffer, descriptors } of loadedFaces) {
|
||||
const blob = new Blob([buffer], { type: "font/woff2" });
|
||||
const dataUrl = await blobToBase64(blob);
|
||||
dataUrls.push(`data:font/woff2;base64,${dataUrl}`);
|
||||
result.push({
|
||||
dataURL: `data:font/woff2;base64,${dataUrl}`,
|
||||
descriptors,
|
||||
});
|
||||
}
|
||||
|
||||
return dataUrls.length > 0 ? dataUrls : false; // Return the array of Data URLs
|
||||
return result.length > 0 ? result : false;
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { ExcalidrawEmbeddableElement } from "@zsviczian/excalidraw/types/element
|
||||
import {
|
||||
AUDIO_TYPES,
|
||||
DEVICE,
|
||||
REG_LINKINDEX_INVALIDCHARS,
|
||||
VIDEO_TYPES,
|
||||
} from "src/constants/constants";
|
||||
import {
|
||||
@@ -122,10 +121,9 @@ export const processLinkText = (
|
||||
linkText = linkParts.path;
|
||||
}
|
||||
|
||||
if (linkText.match(REG_LINKINDEX_INVALIDCHARS)) {
|
||||
return { subpath, file: null };
|
||||
}
|
||||
|
||||
// Resolve existing vault files through Obsidian instead of applying a
|
||||
// cross-platform filename blacklist. Characters such as "?" are valid on
|
||||
// some supported operating systems and may legitimately occur in TFile paths.
|
||||
const file = view.app.metadataCache.getFirstLinkpathDest(
|
||||
linkText,
|
||||
view.file.path,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -59,7 +59,10 @@ import { ColorMap, FileData } from "src/types/embeddedFileLoaderTypes";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import type { StrokeWidthKey } from "@zsviczian/excalidraw/types/common/src/constants";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { cloneElement } from "./excalidrawElementUtils";
|
||||
import {
|
||||
cloneElement,
|
||||
getElementsInArea,
|
||||
} from "./excalidrawElementUtils";
|
||||
|
||||
export {
|
||||
cloneElement,
|
||||
@@ -382,9 +385,7 @@ export async function getTemplate(
|
||||
rect.strokeWidth = 0.1;
|
||||
rect.fillStyle = "solid";
|
||||
scene.elements.push(rect);
|
||||
groupElements = plugin.ea
|
||||
.getElementsInArea(scene.elements, rect)
|
||||
.concat(el);
|
||||
groupElements = getElementsInArea(scene.elements, rect).concat(el);
|
||||
} else {
|
||||
groupElements = plugin.ea.getElementsInFrame(
|
||||
el,
|
||||
@@ -409,7 +410,7 @@ export async function getTemplate(
|
||||
width: el.width + 2 * padding,
|
||||
height: el.height + 2 * padding,
|
||||
};
|
||||
groupElements = plugin.ea.getElementsInArea(scene.elements, areaElement);
|
||||
groupElements = getElementsInArea(scene.elements, areaElement);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import type { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { getCommonBoundingBox, restoreElements } from "src/constants/constants";
|
||||
import {
|
||||
getCommonBoundingBox,
|
||||
nanoid,
|
||||
restoreElements,
|
||||
} from "src/constants/constants";
|
||||
import type {
|
||||
ElementsInAreaOptions,
|
||||
SceneArea,
|
||||
} from "src/types/excalidrawAutomateTypes";
|
||||
|
||||
/**
|
||||
* Calculates the axis-aligned bounds shared by a collection of elements.
|
||||
@@ -15,6 +23,159 @@ export function estimateBounds(
|
||||
return [bb.minX, bb.minY, bb.maxX, bb.maxY];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a normalized copy of a scene area, optionally inflated on every side.
|
||||
*
|
||||
* @param area - Scene rectangle to normalize.
|
||||
* @param margin - Scene-unit margin added around the rectangle.
|
||||
*/
|
||||
export function normalizeSceneArea(
|
||||
area: SceneArea,
|
||||
margin: number = 0,
|
||||
): SceneArea {
|
||||
const left = Math.min(area.x, area.x + area.width) - margin;
|
||||
const top = Math.min(area.y, area.y + area.height) - margin;
|
||||
const right = Math.max(area.x, area.x + area.width) + margin;
|
||||
const bottom = Math.max(area.y, area.y + area.height) + margin;
|
||||
return {
|
||||
x: left,
|
||||
y: top,
|
||||
width: right - left,
|
||||
height: bottom - top,
|
||||
...(area.id ? { id: area.id } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function expandBoundElementIds(
|
||||
selectedIds: Set<string>,
|
||||
elements: readonly ExcalidrawElement[],
|
||||
): void {
|
||||
const elementsById = new Map(elements.map((element) => [element.id, element]));
|
||||
const queue = [...selectedIds];
|
||||
while (queue.length > 0) {
|
||||
const id = queue.shift();
|
||||
if (!id) continue;
|
||||
const element = elementsById.get(id);
|
||||
if (!element) continue;
|
||||
const relatedIds: string[] = [];
|
||||
if (element.type === "text" && element.containerId) {
|
||||
relatedIds.push(element.containerId);
|
||||
}
|
||||
for (const boundElement of element.boundElements ?? []) {
|
||||
relatedIds.push(boundElement.id);
|
||||
}
|
||||
if (element.type === "arrow") {
|
||||
if (element.startBinding?.elementId) {
|
||||
relatedIds.push(element.startBinding.elementId);
|
||||
}
|
||||
if (element.endBinding?.elementId) {
|
||||
relatedIds.push(element.endBinding.elementId);
|
||||
}
|
||||
}
|
||||
for (const id of relatedIds) {
|
||||
if (!selectedIds.has(id) && elementsById.has(id)) {
|
||||
selectedIds.add(id);
|
||||
queue.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns elements whose axis-aligned rendered bounds intersect a scene area.
|
||||
*
|
||||
* @remarks
|
||||
* Results preserve the source array's stacking order. Marker frames are
|
||||
* excluded by default to preserve the historical ExcalidrawAutomate behavior.
|
||||
*/
|
||||
export function getElementsIntersectionArea(
|
||||
elements: readonly ExcalidrawElement[],
|
||||
area: SceneArea,
|
||||
options: ElementsInAreaOptions = {},
|
||||
): ExcalidrawElement[] {
|
||||
const normalizedArea = normalizeSceneArea(area, options.margin);
|
||||
const areaRight = normalizedArea.x + normalizedArea.width;
|
||||
const areaBottom = normalizedArea.y + normalizedArea.height;
|
||||
const selectedIds = new Set<string>();
|
||||
|
||||
for (const element of elements) {
|
||||
if (
|
||||
!options.includeMarkerFrames &&
|
||||
element.type === "frame" &&
|
||||
element.frameRole === "marker"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (normalizedArea.id && element.id === normalizedArea.id) {
|
||||
selectedIds.add(element.id);
|
||||
continue;
|
||||
}
|
||||
const bounds = getCommonBoundingBox([element]);
|
||||
if (
|
||||
bounds.minX < areaRight &&
|
||||
bounds.maxX > normalizedArea.x &&
|
||||
bounds.minY < areaBottom &&
|
||||
bounds.maxY > normalizedArea.y
|
||||
) {
|
||||
selectedIds.add(element.id);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.includeBoundElements) {
|
||||
expandBoundElementIds(selectedIds, elements);
|
||||
}
|
||||
return elements.filter((element) => selectedIds.has(element.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compatible name for {@link getElementsIntersectionArea}.
|
||||
*/
|
||||
export function getElementsInArea(
|
||||
elements: readonly ExcalidrawElement[],
|
||||
area: SceneArea,
|
||||
options: ElementsInAreaOptions = {},
|
||||
): ExcalidrawElement[] {
|
||||
return getElementsIntersectionArea(elements, area, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an invisible rectangle that pins an export to an exact scene area.
|
||||
*
|
||||
* @remarks The returned element is detached data and never enters the EA workbench.
|
||||
*/
|
||||
export function createExportAreaAnchor(area: SceneArea): ExcalidrawElement {
|
||||
const normalizedArea = normalizeSceneArea(area);
|
||||
return {
|
||||
id: nanoid(),
|
||||
type: "rectangle",
|
||||
x: normalizedArea.x,
|
||||
y: normalizedArea.y,
|
||||
width: normalizedArea.width,
|
||||
height: normalizedArea.height,
|
||||
angle: 0,
|
||||
strokeColor: "#000000",
|
||||
backgroundColor: "transparent",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 0.01,
|
||||
strokeStyle: "solid",
|
||||
roughness: 0,
|
||||
opacity: 0,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "a0",
|
||||
roundness: null,
|
||||
seed: 1,
|
||||
version: 1,
|
||||
versionNonce: 1,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: Date.now(),
|
||||
link: null,
|
||||
locked: false,
|
||||
hasTextLink: false,
|
||||
} as unknown as ExcalidrawElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves elements so their top-left corner or center is at a scene position.
|
||||
*
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Notice } from "obsidian";
|
||||
import { DEVICE, EXCALIDRAW_PLUGIN } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { download } from "./fileUtils";
|
||||
import { svgToBase64 } from "./embeddedAssetUtils";
|
||||
import { downloadBlob } from "./fileUtils";
|
||||
import {
|
||||
PageDimensions,
|
||||
PageOrientation,
|
||||
@@ -618,14 +617,12 @@ export async function exportPNGToClipboard(png: Blob) {
|
||||
}
|
||||
|
||||
export function exportPNG(png: Blob, filename: string) {
|
||||
const reader = new FileReader();
|
||||
reader.readAsDataURL(png);
|
||||
reader.onloadend = () => {
|
||||
const base64data = reader.result;
|
||||
download(null, base64data, `${filename}.png`);
|
||||
};
|
||||
downloadBlob(png, `${filename}.png`);
|
||||
}
|
||||
|
||||
export function exportSVG(svg: SVGSVGElement, filename: string) {
|
||||
download(null, svgToBase64(svg.outerHTML), `${filename}.svg`);
|
||||
downloadBlob(
|
||||
new Blob([svg.outerHTML], { type: "image/svg+xml;charset=utf-8" }),
|
||||
`${filename}.svg`,
|
||||
);
|
||||
}
|
||||
@@ -57,6 +57,26 @@ export const download = (
|
||||
mainDocument.body.removeChild(element);
|
||||
};
|
||||
|
||||
/**
|
||||
* Downloads a blob without converting it to a base64 data URL.
|
||||
*
|
||||
* @remarks
|
||||
* Object URLs avoid the large temporary strings and 33% base64 expansion that
|
||||
* can otherwise exhaust Electron's renderer process for large SVG or PNG files.
|
||||
*/
|
||||
export const downloadBlob = (blob: Blob, filename: string): void => {
|
||||
const ownerWindow = mainDocument.defaultView;
|
||||
const urlApi = ownerWindow?.URL ?? URL;
|
||||
const objectUrl = urlApi.createObjectURL(blob);
|
||||
const element = mainDocument.body.createEl("a");
|
||||
setElementDisplay(element, "none");
|
||||
element.setAttribute("href", objectUrl);
|
||||
element.setAttribute("download", filename);
|
||||
element.click();
|
||||
mainDocument.body.removeChild(element);
|
||||
(ownerWindow ?? window).setTimeout(() => urlApi.revokeObjectURL(objectUrl), 1000);
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates the image filename based on the excalidraw filename
|
||||
* @param excalidrawPath - Full filepath of ExclidrawFile
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
export interface RasterCropRegion {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Crops a PNG blob without converting it through a base64 data URL. */
|
||||
export async function cropPNGBlob(
|
||||
blob: Blob,
|
||||
crop: RasterCropRegion,
|
||||
): Promise<Blob> {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const fragment = createFragment();
|
||||
const image = fragment.createEl("img");
|
||||
try {
|
||||
image.src = objectUrl;
|
||||
await image.decode();
|
||||
const canvas = fragment.createEl("canvas");
|
||||
canvas.width = Math.max(1, Math.round(crop.width));
|
||||
canvas.height = Math.max(1, Math.round(crop.height));
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) throw new Error("Could not create a 2D export canvas.");
|
||||
context.drawImage(
|
||||
image,
|
||||
crop.x,
|
||||
crop.y,
|
||||
crop.width,
|
||||
crop.height,
|
||||
0,
|
||||
0,
|
||||
canvas.width,
|
||||
canvas.height,
|
||||
);
|
||||
return await new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob((result) => {
|
||||
if (result) resolve(result);
|
||||
else reject(new Error("Could not encode the cropped PNG."));
|
||||
}, "image/png");
|
||||
});
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
import { log } from "./debugHelper";
|
||||
|
||||
/**
|
||||
* Temporary Phase 0 performance diagnostics.
|
||||
*
|
||||
* Enable before loading the plugin with:
|
||||
* localStorage.setItem("excalidraw-performance-diagnostics", "1")
|
||||
*
|
||||
* Every emitted record is deliberately one flat, copyable string. The module
|
||||
* does not log vault contents or file paths and does not change product state.
|
||||
* Remove this module and every EXCALIDRAW_PERF_PHASE0 call before committing.
|
||||
*/
|
||||
export const PERFORMANCE_DIAGNOSTICS_PREFIX = "EXCALIDRAW_PERF_PHASE0";
|
||||
export const PERFORMANCE_DIAGNOSTICS_STORAGE_KEY =
|
||||
"excalidraw-performance-diagnostics";
|
||||
|
||||
const SUMMARY_INTERVAL_MS = 5000;
|
||||
|
||||
type DiagnosticValue = string | number | boolean | null | undefined;
|
||||
type DiagnosticFields = Record<string, DiagnosticValue>;
|
||||
|
||||
type BrowserPerformanceMemory = {
|
||||
usedJSHeapSize?: number;
|
||||
totalJSHeapSize?: number;
|
||||
jsHeapSizeLimit?: number;
|
||||
};
|
||||
|
||||
type PerformanceWithMemory = Performance & {
|
||||
memory?: BrowserPerformanceMemory;
|
||||
};
|
||||
|
||||
type AggregateMetric = {
|
||||
count: number;
|
||||
totalMs: number;
|
||||
maxMs: number;
|
||||
};
|
||||
|
||||
const metrics = new Map<string, AggregateMetric>();
|
||||
const counters = new Map<string, number>();
|
||||
let idCounter = 0;
|
||||
let lastPeriodicSummaryAt = 0;
|
||||
|
||||
const enabled = (() => {
|
||||
try {
|
||||
return (
|
||||
globalThis.localStorage?.getItem(PERFORMANCE_DIAGNOSTICS_STORAGE_KEY) ===
|
||||
"1"
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
|
||||
function formatNumber(value: number): string {
|
||||
if (!Number.isFinite(value)) {
|
||||
return "na";
|
||||
}
|
||||
return Number.isInteger(value) ? value.toString() : value.toFixed(2);
|
||||
}
|
||||
|
||||
function formatValue(value: DiagnosticValue): string {
|
||||
if (value === null || value === undefined) {
|
||||
return "na";
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
return formatNumber(value);
|
||||
}
|
||||
if (typeof value === "boolean") {
|
||||
return value ? "1" : "0";
|
||||
}
|
||||
return String(value).replaceAll(/\s+/g, "_");
|
||||
}
|
||||
|
||||
function getMemoryFields(): DiagnosticFields {
|
||||
const memory = (globalThis.performance as PerformanceWithMemory | undefined)
|
||||
?.memory;
|
||||
if (!memory) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
heapUsedMB:
|
||||
typeof memory.usedJSHeapSize === "number"
|
||||
? memory.usedJSHeapSize / 1024 / 1024
|
||||
: undefined,
|
||||
heapTotalMB:
|
||||
typeof memory.totalJSHeapSize === "number"
|
||||
? memory.totalJSHeapSize / 1024 / 1024
|
||||
: undefined,
|
||||
heapLimitMB:
|
||||
typeof memory.jsHeapSizeLimit === "number"
|
||||
? memory.jsHeapSizeLimit / 1024 / 1024
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function maybeEmitPeriodicSummary(): void {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
const now = performanceDiagnosticNow();
|
||||
if (lastPeriodicSummaryAt === 0) {
|
||||
lastPeriodicSummaryAt = now;
|
||||
return;
|
||||
}
|
||||
if (now - lastPeriodicSummaryAt < SUMMARY_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
lastPeriodicSummaryAt = now;
|
||||
performanceDiagnosticSummary("interval");
|
||||
}
|
||||
|
||||
export function performanceDiagnosticsEnabled(): boolean {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
export function performanceDiagnosticNow(): number {
|
||||
return globalThis.performance?.now?.() ?? Date.now();
|
||||
}
|
||||
|
||||
export function nextPerformanceDiagnosticId(prefix: string): string {
|
||||
idCounter += 1;
|
||||
return `${prefix}-${idCounter}`;
|
||||
}
|
||||
|
||||
export function performanceDiagnosticLog(
|
||||
event: string,
|
||||
fields: DiagnosticFields = {},
|
||||
): void {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
const entries = Object.entries({
|
||||
atMs: performanceDiagnosticNow(),
|
||||
...fields,
|
||||
...getMemoryFields(),
|
||||
})
|
||||
.filter(([, value]) => value !== undefined)
|
||||
.map(([key, value]) => `${key}=${formatValue(value)}`);
|
||||
const suffix = entries.length > 0 ? ` ${entries.join(" ")}` : "";
|
||||
log(`${PERFORMANCE_DIAGNOSTICS_PREFIX} event=${event}${suffix}`);
|
||||
}
|
||||
|
||||
export function performanceDiagnosticRecordDuration(
|
||||
metric: string,
|
||||
durationMs: number,
|
||||
): void {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
const existing = metrics.get(metric) ?? { count: 0, totalMs: 0, maxMs: 0 };
|
||||
existing.count += 1;
|
||||
existing.totalMs += durationMs;
|
||||
existing.maxMs = Math.max(existing.maxMs, durationMs);
|
||||
metrics.set(metric, existing);
|
||||
maybeEmitPeriodicSummary();
|
||||
}
|
||||
|
||||
export function performanceDiagnosticIncrement(
|
||||
counter: string,
|
||||
amount: number = 1,
|
||||
): void {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
counters.set(counter, (counters.get(counter) ?? 0) + amount);
|
||||
maybeEmitPeriodicSummary();
|
||||
}
|
||||
|
||||
export function performanceDiagnosticSummary(
|
||||
reason: string,
|
||||
fields: DiagnosticFields = {},
|
||||
): void {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
const summaryFields: DiagnosticFields = { reason, ...fields };
|
||||
counters.forEach((value, key) => {
|
||||
summaryFields[`${key}.count`] = value;
|
||||
});
|
||||
metrics.forEach((value, key) => {
|
||||
summaryFields[`${key}.count`] = value.count;
|
||||
summaryFields[`${key}.totalMs`] = value.totalMs;
|
||||
summaryFields[`${key}.avgMs`] =
|
||||
value.count > 0 ? value.totalMs / value.count : 0;
|
||||
summaryFields[`${key}.maxMs`] = value.maxMs;
|
||||
});
|
||||
performanceDiagnosticLog("summary", summaryFields);
|
||||
}
|
||||
|
||||
type PerformanceDiagnosticsGlobal = typeof globalThis & {
|
||||
EXCALIDRAW_PERF_PHASE0_CHECKPOINT?: (label?: string) => void;
|
||||
};
|
||||
|
||||
// Manual checkpoints are useful around an explicit DevTools "Collect garbage"
|
||||
// action. Keep this opt-in and text-only like every other Phase 0 record.
|
||||
if (enabled) {
|
||||
(globalThis as PerformanceDiagnosticsGlobal).EXCALIDRAW_PERF_PHASE0_CHECKPOINT =
|
||||
(label: string = "manual") => {
|
||||
performanceDiagnosticSummary(`manual-${label}`);
|
||||
};
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import type { Theme } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { hideElement, setStyle, showElement } from "./styleUtils";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLCanvasElement;
|
||||
export interface ScreenshotOptions {
|
||||
zoom: number;
|
||||
margin: number;
|
||||
@@ -249,7 +248,7 @@ export async function captureScreenshot(
|
||||
setStyle(container, originalStyle);
|
||||
|
||||
// Stitch tiles together using a browser canvas
|
||||
const canvas = deliberateCreateElement(mainDocument, "canvas");
|
||||
const canvas = createFragment().createEl("canvas");
|
||||
canvas.width = adjustedTotalWidth * devicePixelRatio;
|
||||
canvas.height = adjustedTotalHeight * devicePixelRatio;
|
||||
setStyle(canvas, {
|
||||
|
||||
@@ -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`;
|
||||
};
|
||||
@@ -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,
|
||||
|
||||
+22
-14
@@ -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 });
|
||||
}
|
||||
}
|
||||
|
||||
+824
-953
File diff suppressed because it is too large.
Load diff
@@ -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: {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
isObsidianThemeDark,
|
||||
} from "../../utils/obsidianUtils";
|
||||
import { CustomMutationObserver, DEBUGGING } from "../../utils/debugHelper";
|
||||
import { performanceDiagnosticLog } from "../../utils/performanceDiagnostics";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
|
||||
@@ -110,10 +109,6 @@ export class CanvasNodeFactory {
|
||||
node.containerEl.querySelector(".canvas-node-content-blocker")?.remove();
|
||||
containerEl.appendChild(node.containerEl);
|
||||
this.nodes.set(elementId, node);
|
||||
performanceDiagnosticLog("canvasNode.created", {
|
||||
viewId: this.view.id,
|
||||
nodes: this.nodes.size,
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -223,43 +218,29 @@ export class CanvasNodeFactory {
|
||||
if (!this.initialized || !node) {
|
||||
return;
|
||||
}
|
||||
const before = this.nodes.size;
|
||||
let deleted = false;
|
||||
if (elementId && this.nodes.get(elementId) === node) {
|
||||
deleted = this.nodes.delete(elementId);
|
||||
this.nodes.delete(elementId);
|
||||
} else {
|
||||
for (const [registeredElementId, registeredNode] of this.nodes) {
|
||||
if (registeredNode === node) {
|
||||
deleted = this.nodes.delete(registeredElementId);
|
||||
this.nodes.delete(registeredElementId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.canvas.removeNode(node);
|
||||
node.detach();
|
||||
performanceDiagnosticLog("canvasNode.removed", {
|
||||
viewId: this.view.id,
|
||||
before,
|
||||
after: this.nodes.size,
|
||||
mapEntryDeleted: deleted,
|
||||
});
|
||||
}
|
||||
|
||||
public purgeNodes() {
|
||||
if (!this.initialized) {
|
||||
return;
|
||||
}
|
||||
const before = this.nodes.size;
|
||||
this.nodes.forEach((node) => {
|
||||
this.canvas.removeNode(node);
|
||||
node.detach();
|
||||
});
|
||||
this.nodes.clear();
|
||||
performanceDiagnosticLog("canvasNode.purged", {
|
||||
viewId: this.view.id,
|
||||
before,
|
||||
after: this.nodes.size,
|
||||
});
|
||||
}
|
||||
|
||||
destroy() {
|
||||
|
||||
@@ -32,12 +32,6 @@ import {
|
||||
getPageDimensions,
|
||||
} from "../../utils/exportUtils";
|
||||
import type ExcalidrawView from "../ExcalidrawView";
|
||||
import {
|
||||
performanceDiagnosticLog,
|
||||
performanceDiagnosticNow,
|
||||
performanceDiagnosticRecordDuration,
|
||||
performanceDiagnosticsEnabled,
|
||||
} from "../../utils/performanceDiagnostics";
|
||||
|
||||
/** Runtime dependencies supplied by the view's existing import graph. */
|
||||
export interface ViewExportDependencies {
|
||||
@@ -272,10 +266,6 @@ export class ViewExportManager {
|
||||
embedScene?: boolean;
|
||||
autoexportConfig?: AutoexportConfig;
|
||||
}): Promise<void | false> {
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const diagnosticsStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
if (!data) {
|
||||
data = {};
|
||||
}
|
||||
@@ -329,18 +319,6 @@ export class ViewExportManager {
|
||||
autoexportConfig?.theme,
|
||||
);
|
||||
}
|
||||
const durationMs = diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - diagnosticsStart
|
||||
: 0;
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration("autoexportSvg", durationMs);
|
||||
}
|
||||
performanceDiagnosticLog("autoexport.complete", {
|
||||
viewId: this.view.id,
|
||||
kind: "svg",
|
||||
durationMs: diagnosticsEnabled ? durationMs : undefined,
|
||||
elements: scene.elements.length,
|
||||
});
|
||||
}
|
||||
|
||||
/** Downloads an SVG export of the current or selected scene. */
|
||||
@@ -476,10 +454,6 @@ export class ViewExportManager {
|
||||
embedScene?: boolean;
|
||||
autoexportConfig?: AutoexportConfig;
|
||||
}): Promise<void | false> {
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const diagnosticsStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
if (!data) {
|
||||
data = {};
|
||||
}
|
||||
@@ -530,18 +504,6 @@ export class ViewExportManager {
|
||||
autoexportConfig?.theme,
|
||||
);
|
||||
}
|
||||
const durationMs = diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - diagnosticsStart
|
||||
: 0;
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration("autoexportPng", durationMs);
|
||||
}
|
||||
performanceDiagnosticLog("autoexport.complete", {
|
||||
viewId: this.view.id,
|
||||
kind: "png",
|
||||
durationMs: diagnosticsEnabled ? durationMs : undefined,
|
||||
elements: scene.elements.length,
|
||||
});
|
||||
}
|
||||
|
||||
/** Copies a PNG export of the current or selected scene to the clipboard. */
|
||||
|
||||
@@ -565,6 +565,7 @@ export class ViewLinkNavigationManager {
|
||||
keys,
|
||||
view: this.view,
|
||||
sourceElement: el,
|
||||
followObsidianNewNoteLocation: true,
|
||||
}).open();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,546 @@
|
||||
import { Notice } from "obsidian";
|
||||
import type { AppState } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
|
||||
import { t } from "../../lang/helpers";
|
||||
import { errorlog } from "../../utils/coreUtils";
|
||||
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<SaveExecutionResult> | 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<SaveExecutionResult> {
|
||||
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<SaveExecutionResult> {
|
||||
let completedRequest = false;
|
||||
let latestResult: SaveExecutionResult = { status: "skipped" };
|
||||
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);
|
||||
latestResult = result;
|
||||
} finally {
|
||||
this.activeSaveRevision = null;
|
||||
}
|
||||
completedRequest = true;
|
||||
}
|
||||
return latestResult;
|
||||
}
|
||||
|
||||
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;
|
||||
try {
|
||||
const result = await this.enqueueSave({
|
||||
preventReload: false,
|
||||
forcesave: true,
|
||||
overrideEmbeddableIsEditingSelfDebounce: true,
|
||||
sideEffectPolicy: {
|
||||
triggerAutoexport: policy.triggerAutoexport,
|
||||
},
|
||||
revision: this.currentRevision,
|
||||
});
|
||||
if (
|
||||
this.view.semaphores.windowMigrating ||
|
||||
result.status === "failed" ||
|
||||
result.status === "skipped"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.view.plugin.triggerEmbedUpdates();
|
||||
if (policy.refreshSceneFiles) {
|
||||
await this.view.loadSceneFiles();
|
||||
}
|
||||
if (!silent) {
|
||||
new Notice("Save successful", 1000);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "ViewSaveCoordinator.forceSaveWithPolicy",
|
||||
fn: "forceSaveWithPolicy",
|
||||
error,
|
||||
});
|
||||
new Notice(t("WARNING_SERIOUS_ERROR"), 60000);
|
||||
} finally {
|
||||
this.view.semaphores.forceSaving = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
@@ -6,14 +9,6 @@ import type {
|
||||
} from "../../shared/EmbeddedFileLoader";
|
||||
import type { FileData } from "../../types/embeddedFileLoaderTypes";
|
||||
import type ExcalidrawView from "../ExcalidrawView";
|
||||
import {
|
||||
nextPerformanceDiagnosticId,
|
||||
performanceDiagnosticIncrement,
|
||||
performanceDiagnosticLog,
|
||||
performanceDiagnosticNow,
|
||||
performanceDiagnosticRecordDuration,
|
||||
performanceDiagnosticsEnabled,
|
||||
} from "../../utils/performanceDiagnostics";
|
||||
|
||||
/** Runtime dependencies supplied by the composition root to avoid adding a
|
||||
* circular import.
|
||||
@@ -31,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
|
||||
@@ -55,16 +107,11 @@ export class ViewSceneFileManager {
|
||||
private deferredValidationLoader: EmbeddedFilesLoader = null;
|
||||
private deferredValidationTimer: number | null = null;
|
||||
private deferredValidationFilePath: string | null = null;
|
||||
private nextLoaderDiagnosticContext: {
|
||||
requestId: string;
|
||||
reason: string;
|
||||
} | null = null;
|
||||
private queuedLoadSceneFilesRequest: {
|
||||
isThemeChange: boolean;
|
||||
fileIDWhiteList?: Set<FileId>;
|
||||
forceReloadFileIDs?: Set<FileId>;
|
||||
callback?: () => void;
|
||||
diagnosticReason: string;
|
||||
} | null = null;
|
||||
// Cache metadata collected during the stale-first pass. These are the only
|
||||
// files that need validation after the scene is already visible.
|
||||
@@ -78,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 {
|
||||
@@ -92,7 +154,6 @@ export class ViewSceneFileManager {
|
||||
this.nextLoader.emptyPDFDocsMap();
|
||||
this.nextLoader = null;
|
||||
}
|
||||
this.nextLoaderDiagnosticContext = null;
|
||||
}
|
||||
|
||||
private cancelDeferredSceneFileValidation() {
|
||||
@@ -124,14 +185,17 @@ export class ViewSceneFileManager {
|
||||
candidates: Map<FileId, DeferredCacheValidation>,
|
||||
isThemeChange: boolean,
|
||||
emitPolicy: "changed-only" | "all" = "changed-only",
|
||||
diagnosticReason: string = "unspecified",
|
||||
) {
|
||||
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;
|
||||
}
|
||||
@@ -139,32 +203,12 @@ export class ViewSceneFileManager {
|
||||
const fileIDs = new Set(candidates.keys());
|
||||
const currentFile = this.view.file.path;
|
||||
const loader = this.dependencies.createEmbeddedFilesLoader();
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const diagnosticId = diagnosticsEnabled
|
||||
? nextPerformanceDiagnosticId("sceneValidation")
|
||||
: "";
|
||||
performanceDiagnosticIncrement("sceneFileDeferredValidationScheduled");
|
||||
performanceDiagnosticLog("sceneFiles.validationScheduled", {
|
||||
id: diagnosticId,
|
||||
viewId: this.view.id,
|
||||
candidates: fileIDs.size,
|
||||
themeChange: isThemeChange,
|
||||
emitPolicy,
|
||||
reason: diagnosticReason,
|
||||
});
|
||||
this.deferredValidationFilePath = currentFile;
|
||||
this.deferredValidationTimer = window.setTimeout(() => {
|
||||
const validationStart = diagnosticsEnabled
|
||||
? performanceDiagnosticNow()
|
||||
: 0;
|
||||
let emittedFiles = 0;
|
||||
let emittedBatches = 0;
|
||||
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;
|
||||
}
|
||||
@@ -180,20 +224,16 @@ 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;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (files && files.length > 0) {
|
||||
emittedFiles += files.length;
|
||||
emittedBatches += 1;
|
||||
void this.dependencies.addFiles(files, this.view, isDark);
|
||||
}
|
||||
if (!final) {
|
||||
@@ -204,24 +244,6 @@ export class ViewSceneFileManager {
|
||||
this.deferredValidationLoader = null;
|
||||
}
|
||||
this.deferredValidationFilePath = null;
|
||||
const validationMs = diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - validationStart
|
||||
: 0;
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration(
|
||||
"sceneFileDeferredValidation",
|
||||
validationMs,
|
||||
);
|
||||
}
|
||||
performanceDiagnosticLog("sceneFiles.validationComplete", {
|
||||
id: diagnosticId,
|
||||
viewId: this.view.id,
|
||||
candidates: fileIDs.size,
|
||||
emittedFiles,
|
||||
emittedBatches,
|
||||
reason: diagnosticReason,
|
||||
durationMs: diagnosticsEnabled ? validationMs : undefined,
|
||||
});
|
||||
const queuedLoad = this.queuedLoadSceneFilesRequest;
|
||||
this.queuedLoadSceneFilesRequest = null;
|
||||
if (queuedLoad && this.view.file?.path === currentFile) {
|
||||
@@ -230,7 +252,6 @@ export class ViewSceneFileManager {
|
||||
queuedLoad.fileIDWhiteList,
|
||||
queuedLoad.callback,
|
||||
queuedLoad.forceReloadFileIDs,
|
||||
queuedLoad.diagnosticReason,
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -250,9 +271,16 @@ export class ViewSceneFileManager {
|
||||
fileIDs: Set<FileId>,
|
||||
isThemeChange: boolean = false,
|
||||
forceEmitFromCache: boolean = false,
|
||||
diagnosticReason: string = "unspecified",
|
||||
) {
|
||||
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) {
|
||||
@@ -275,7 +303,6 @@ export class ViewSceneFileManager {
|
||||
),
|
||||
isThemeChange,
|
||||
forceEmitFromCache ? "all" : "changed-only",
|
||||
diagnosticReason,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -284,73 +311,20 @@ export class ViewSceneFileManager {
|
||||
fileIDWhiteList?: Set<FileId>,
|
||||
callback?: () => void,
|
||||
forceReloadFileIDs?: Set<FileId>,
|
||||
diagnosticReason: string = "unspecified",
|
||||
) {
|
||||
const diagnosticsEnabled = performanceDiagnosticsEnabled();
|
||||
const requestId = diagnosticsEnabled
|
||||
? nextPerformanceDiagnosticId("sceneLoad")
|
||||
: "";
|
||||
const embeddedFileEntries = diagnosticsEnabled
|
||||
? Array.from(this.view.excalidrawData.files.entries())
|
||||
: [];
|
||||
const apiFileIds = new Set(
|
||||
diagnosticsEnabled && this.view.excalidrawAPI
|
||||
? Object.keys(this.view.excalidrawAPI.getFiles())
|
||||
: [],
|
||||
);
|
||||
const unresolvedEmbeddedFiles = diagnosticsEnabled
|
||||
? embeddedFileEntries.filter(([, embeddedFile]) => !embeddedFile?.file)
|
||||
.length
|
||||
: undefined;
|
||||
const unresolvedVaultFiles = diagnosticsEnabled
|
||||
? embeddedFileEntries.filter(
|
||||
([, embeddedFile]) =>
|
||||
embeddedFile &&
|
||||
!embeddedFile.file &&
|
||||
!embeddedFile.isHyperLink &&
|
||||
!embeddedFile.isLocalLink,
|
||||
).length
|
||||
: undefined;
|
||||
const externalOrLocalFiles = diagnosticsEnabled
|
||||
? embeddedFileEntries.filter(
|
||||
([, embeddedFile]) =>
|
||||
embeddedFile?.isHyperLink || embeddedFile?.isLocalLink,
|
||||
).length
|
||||
: undefined;
|
||||
const missingApiBinaryFiles = diagnosticsEnabled
|
||||
? embeddedFileEntries.filter(([fileId]) => !apiFileIds.has(fileId)).length
|
||||
: undefined;
|
||||
performanceDiagnosticIncrement("loadSceneFilesRequest");
|
||||
performanceDiagnosticIncrement(`loadSceneFilesReason.${diagnosticReason}`);
|
||||
performanceDiagnosticLog("sceneFiles.request", {
|
||||
id: requestId,
|
||||
viewId: this.view.id,
|
||||
reason: diagnosticReason,
|
||||
themeChange: isThemeChange,
|
||||
whitelist: fileIDWhiteList?.size ?? 0,
|
||||
forceReload: forceReloadFileIDs?.size ?? 0,
|
||||
embeddedFiles: this.view.excalidrawData?.getFiles().length ?? 0,
|
||||
apiBinaryFiles: diagnosticsEnabled ? apiFileIds.size : undefined,
|
||||
missingApiBinaryFiles,
|
||||
unresolvedEmbeddedFiles,
|
||||
unresolvedVaultFiles,
|
||||
externalOrLocalFiles,
|
||||
activeLoader: Boolean(this.activeLoader),
|
||||
deferredValidation: Boolean(
|
||||
this.deferredValidationLoader || this.deferredValidationTimer,
|
||||
),
|
||||
});
|
||||
if (!this.view.excalidrawAPI) {
|
||||
performanceDiagnosticLog("sceneFiles.skipped", {
|
||||
id: requestId,
|
||||
viewId: this.view.id,
|
||||
reason: diagnosticReason,
|
||||
skipReason: "api-missing",
|
||||
});
|
||||
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 &&
|
||||
@@ -364,15 +338,7 @@ export class ViewSceneFileManager {
|
||||
fileIDWhiteList,
|
||||
callback,
|
||||
forceReloadFileIDs,
|
||||
diagnosticReason,
|
||||
};
|
||||
performanceDiagnosticIncrement("loadSceneFilesQueued");
|
||||
performanceDiagnosticLog("sceneFiles.queued", {
|
||||
id: requestId,
|
||||
viewId: this.view.id,
|
||||
reason: diagnosticReason,
|
||||
queueReason: "deferred-validation",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -383,33 +349,21 @@ export class ViewSceneFileManager {
|
||||
|
||||
const loader = this.dependencies.createEmbeddedFilesLoader();
|
||||
|
||||
const runLoader = (
|
||||
l: EmbeddedFilesLoader,
|
||||
effectiveRequestId: string = requestId,
|
||||
effectiveReason: string = diagnosticReason,
|
||||
) => {
|
||||
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.nextLoaderDiagnosticContext = null;
|
||||
this.activeLoader = l;
|
||||
const runId = diagnosticsEnabled
|
||||
? nextPerformanceDiagnosticId("sceneLoadRun")
|
||||
: "";
|
||||
const runStart = diagnosticsEnabled ? performanceDiagnosticNow() : 0;
|
||||
let emittedFiles = 0;
|
||||
let emittedBatches = 0;
|
||||
performanceDiagnosticIncrement("loadSceneFilesRun");
|
||||
performanceDiagnosticLog("sceneFiles.runStart", {
|
||||
id: runId,
|
||||
requestId: effectiveRequestId,
|
||||
parameterSourceRequestId: requestId,
|
||||
viewId: this.view.id,
|
||||
reason: effectiveReason,
|
||||
themeChange: isThemeChange,
|
||||
whitelist: fileIDWhiteList?.size ?? 0,
|
||||
forceReload: forceReloadFileIDs?.size ?? 0,
|
||||
sceneElements: this.view.getViewElements().length,
|
||||
embeddedFiles: this.view.excalidrawData.getFiles().length,
|
||||
});
|
||||
const prioritizedFileIds = getVisibleImageFileIds(this.view);
|
||||
void l.loadSceneFiles({
|
||||
excalidrawData: this.view.excalidrawData,
|
||||
sceneElements: this.view.getViewElements(),
|
||||
@@ -418,51 +372,33 @@ 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) {
|
||||
emittedFiles += files.length;
|
||||
emittedBatches += 1;
|
||||
void this.dependencies.addFiles(files, this.view, isDark);
|
||||
}
|
||||
if (!final) {
|
||||
return;
|
||||
}
|
||||
const runMs = diagnosticsEnabled
|
||||
? performanceDiagnosticNow() - runStart
|
||||
: 0;
|
||||
if (diagnosticsEnabled) {
|
||||
performanceDiagnosticRecordDuration("loadSceneFiles", runMs);
|
||||
}
|
||||
performanceDiagnosticLog("sceneFiles.runComplete", {
|
||||
id: runId,
|
||||
requestId: effectiveRequestId,
|
||||
parameterSourceRequestId: requestId,
|
||||
viewId: this.view.id,
|
||||
reason: effectiveReason,
|
||||
emittedFiles,
|
||||
emittedBatches,
|
||||
terminalState: l.terminalState,
|
||||
apiBinaryFiles: Object.keys(this.view.excalidrawAPI.getFiles()).length,
|
||||
deferredCandidates: this.pendingDeferredValidationCandidates.size,
|
||||
durationMs: diagnosticsEnabled ? runMs : undefined,
|
||||
});
|
||||
this.view.lastSceneLoadTime = Date.now();
|
||||
if (this.activeLoader === l) {
|
||||
this.activeLoader = null;
|
||||
}
|
||||
if (this.nextLoader) {
|
||||
const nextLoader = this.nextLoader;
|
||||
const nextDiagnosticContext = this.nextLoaderDiagnosticContext;
|
||||
runLoader(
|
||||
nextLoader,
|
||||
nextDiagnosticContext?.requestId ?? effectiveRequestId,
|
||||
nextDiagnosticContext?.reason ?? effectiveReason,
|
||||
);
|
||||
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.
|
||||
@@ -471,7 +407,6 @@ export class ViewSceneFileManager {
|
||||
new Map(this.pendingDeferredValidationCandidates),
|
||||
isThemeChange,
|
||||
"changed-only",
|
||||
"post-stale-first-load",
|
||||
);
|
||||
this.pendingDeferredValidationCandidates.clear();
|
||||
}
|
||||
@@ -490,23 +425,11 @@ export class ViewSceneFileManager {
|
||||
const retryFileIDs = new Set(
|
||||
retryCandidates.map(([fileId]) => fileId),
|
||||
);
|
||||
const retryCandidate = retryCandidates[0][1];
|
||||
performanceDiagnosticIncrement("sceneFileRetryScheduled");
|
||||
performanceDiagnosticLog("sceneFiles.retryScheduled", {
|
||||
viewId: this.view.id,
|
||||
reason: "unresolved-embedded-file",
|
||||
candidates: diagnosticsEnabled
|
||||
? retryCandidates.length
|
||||
: undefined,
|
||||
attemptCounter: retryCandidate.attemptCounter,
|
||||
delayMs: 2000,
|
||||
});
|
||||
const currentFile = this.view.file.path;
|
||||
let deferredWaitCount = 0;
|
||||
const retryLoadSceneFiles = () => {
|
||||
if (
|
||||
!this ||
|
||||
!this.view.excalidrawAPI ||
|
||||
!requestIsCurrent() ||
|
||||
currentFile !== this.view.file.path
|
||||
) {
|
||||
return;
|
||||
@@ -517,21 +440,14 @@ export class ViewSceneFileManager {
|
||||
this.deferredValidationLoader ||
|
||||
this.deferredValidationTimer
|
||||
) {
|
||||
deferredWaitCount += 1;
|
||||
window.setTimeout(retryLoadSceneFiles, 500);
|
||||
return;
|
||||
}
|
||||
performanceDiagnosticLog("sceneFiles.retryExecuting", {
|
||||
viewId: this.view.id,
|
||||
reason: "unresolved-embedded-file",
|
||||
deferredWaitMs: deferredWaitCount * 500,
|
||||
});
|
||||
void this.loadSceneFiles(
|
||||
false,
|
||||
retryFileIDs,
|
||||
undefined,
|
||||
undefined,
|
||||
"retry-unresolved-embedded-file",
|
||||
);
|
||||
};
|
||||
window.setTimeout(() => {
|
||||
@@ -548,23 +464,15 @@ export class ViewSceneFileManager {
|
||||
onDeferredValidationCandidates: (candidates) => {
|
||||
this.addDeferredValidationCandidates(candidates);
|
||||
},
|
||||
waitForRender: () =>
|
||||
waitForWindowPaint(() => this.view.ownerWindow ?? window),
|
||||
prioritizedFileIds,
|
||||
});
|
||||
};
|
||||
if (!this.activeLoader) {
|
||||
runLoader(loader);
|
||||
} else {
|
||||
this.nextLoader = loader;
|
||||
this.nextLoaderDiagnosticContext = {
|
||||
requestId,
|
||||
reason: diagnosticReason,
|
||||
};
|
||||
performanceDiagnosticIncrement("loadSceneFilesQueued");
|
||||
performanceDiagnosticLog("sceneFiles.queued", {
|
||||
id: requestId,
|
||||
viewId: this.view.id,
|
||||
reason: diagnosticReason,
|
||||
queueReason: "active-loader",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { AppState } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
|
||||
/** App-state values whose changes are meaningful to drawing persistence. */
|
||||
export interface TrackedAppStateSnapshot {
|
||||
theme: AppState["theme"];
|
||||
viewBackgroundColor: AppState["viewBackgroundColor"];
|
||||
gridSize: AppState["gridSize"];
|
||||
gridStep: AppState["gridStep"];
|
||||
gridModeEnabled: AppState["gridModeEnabled"];
|
||||
colorPalette: AppState["colorPalette"];
|
||||
colorTopPicks: AppState["colorTopPicks"];
|
||||
frameRendering: AppState["frameRendering"];
|
||||
objectsSnapModeEnabled: AppState["objectsSnapModeEnabled"];
|
||||
bindingPreference: AppState["bindingPreference"];
|
||||
isMidpointSnappingEnabled: AppState["isMidpointSnappingEnabled"];
|
||||
boxSelectionMode: AppState["boxSelectionMode"];
|
||||
scrollX: AppState["scrollX"];
|
||||
scrollY: AppState["scrollY"];
|
||||
zoom: AppState["zoom"]["value"];
|
||||
}
|
||||
|
||||
/** Captures only app state that can independently require drawing persistence. */
|
||||
export function captureTrackedAppState(
|
||||
appState: AppState,
|
||||
): TrackedAppStateSnapshot {
|
||||
return {
|
||||
theme: appState.theme,
|
||||
viewBackgroundColor: appState.viewBackgroundColor,
|
||||
gridSize: appState.gridSize,
|
||||
gridStep: appState.gridStep,
|
||||
gridModeEnabled: appState.gridModeEnabled,
|
||||
colorPalette: appState.colorPalette,
|
||||
colorTopPicks: appState.colorTopPicks,
|
||||
frameRendering: appState.frameRendering,
|
||||
objectsSnapModeEnabled: appState.objectsSnapModeEnabled,
|
||||
bindingPreference: appState.bindingPreference,
|
||||
isMidpointSnappingEnabled: appState.isMidpointSnappingEnabled,
|
||||
boxSelectionMode: appState.boxSelectionMode,
|
||||
scrollX: appState.scrollX,
|
||||
scrollY: appState.scrollY,
|
||||
zoom: appState.zoom.value,
|
||||
};
|
||||
}
|
||||
|
||||
function areStructuredValuesEqual(left: unknown, right: unknown): boolean {
|
||||
if (Object.is(left, right)) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
left === null ||
|
||||
right === null ||
|
||||
typeof left !== "object" ||
|
||||
typeof right !== "object"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (Array.isArray(left) || Array.isArray(right)) {
|
||||
return (
|
||||
Array.isArray(left) &&
|
||||
Array.isArray(right) &&
|
||||
left.length === right.length &&
|
||||
left.every((value, index) =>
|
||||
areStructuredValuesEqual(value, right[index]),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const leftRecord = left as Record<string, unknown>;
|
||||
const rightRecord = right as Record<string, unknown>;
|
||||
const leftKeys = Object.keys(leftRecord);
|
||||
const rightKeys = Object.keys(rightRecord);
|
||||
return (
|
||||
leftKeys.length === rightKeys.length &&
|
||||
leftKeys.every(
|
||||
(key) =>
|
||||
Object.hasOwn(rightRecord, key) &&
|
||||
areStructuredValuesEqual(leftRecord[key], rightRecord[key]),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether drawing-owned app state changed. Viewport state participates
|
||||
* only when opening the drawing will not replace it with zoom-to-fit.
|
||||
*/
|
||||
export function didTrackedAppStateChange(
|
||||
previous: TrackedAppStateSnapshot,
|
||||
next: TrackedAppStateSnapshot,
|
||||
trackViewport: boolean,
|
||||
): boolean {
|
||||
return (
|
||||
previous.theme !== next.theme ||
|
||||
previous.viewBackgroundColor !== next.viewBackgroundColor ||
|
||||
previous.gridSize !== next.gridSize ||
|
||||
previous.gridStep !== next.gridStep ||
|
||||
previous.gridModeEnabled !== next.gridModeEnabled ||
|
||||
!areStructuredValuesEqual(previous.colorPalette, next.colorPalette) ||
|
||||
!areStructuredValuesEqual(previous.colorTopPicks, next.colorTopPicks) ||
|
||||
!areStructuredValuesEqual(previous.frameRendering, next.frameRendering) ||
|
||||
previous.objectsSnapModeEnabled !== next.objectsSnapModeEnabled ||
|
||||
previous.bindingPreference !== next.bindingPreference ||
|
||||
previous.isMidpointSnappingEnabled !== next.isMidpointSnappingEnabled ||
|
||||
previous.boxSelectionMode !== next.boxSelectionMode ||
|
||||
(trackViewport &&
|
||||
(previous.scrollX !== next.scrollX ||
|
||||
previous.scrollY !== next.scrollY ||
|
||||
previous.zoom !== next.zoom))
|
||||
);
|
||||
}
|
||||
@@ -1096,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;
|
||||
|
||||
Reference in new issue
Block a user