Compare commits

...
Author SHA1 Message Date
zsviczian 45684d633c instrumentation 2026-09-15 21:31:00 +02:00
zsviczian d491996112 fix: align settings path warnings 2026-09-15 19:48:12 +02:00
zsviczian f5503b950a fix: preserve declarative setting descriptions 2026-09-15 19:35:22 +02:00
zsviczian 6018801df4 edited messages.ts 2026-09-14 20:49:32 +02:00
zsviczian 5f68ed18bc 2.28.0-beta.0 2026-09-14 20:38:25 +02:00
zsviczian 3dd6320b12 updated package json and messages 2026-09-14 20:06:18 +02:00
zsviczian 7f28393251 Merge pull request #2933 from zsviczian/file-persistence-improvements
Refactor file persistence lifecycle
2026-09-14 19:48:07 +02:00
zsviczian e422209667 chore: finalize persistence refactor cleanup 2026-09-14 19:38:29 +02:00
zsviczian b9481c320a refactor: own reload suppression state 2026-09-14 19:08:34 +02:00
zsviczian 96fe982a6c docs: record autoexport frontmatter fix 2026-09-14 18:11:57 +02:00
zsviczian 1354930dff fix: resolve autoexport settings from saved text 2026-09-14 18:11:21 +02:00
zsviczian 91d085fafa docs: record checkpoint 12a acceptance 2026-09-14 17:47:03 +02:00
zsviczian 839f0547a0 refactor: move save state into coordinator 2026-09-14 17:44:43 +02:00
zsviczian 1cf58ce9e5 docs: record checkpoint 11 acceptance 2026-09-14 17:23:26 +02:00
zsviczian 1d1dd36554 refactor: invalidate stale view loads 2026-09-14 17:22:43 +02:00
zsviczian 452107f653 refactor: coordinate prepared autoexports 2026-09-14 13:20:26 +02:00
zsviczian a634ce27f4 refactor: capture normalized save snapshots 2026-09-13 22:17:04 +02:00
zsviczian 25d7e16404 refactor: coordinate same-file editing lifecycle 2026-09-13 21:17:02 +02:00
zsviczian d1bd628ce7 refactor: back up completed persistence writes 2026-09-13 15:15:32 +02:00
zsviczian 69b0596c84 Merge pull request #2925 from tryingET/add-layer-manager-refreshed-2026-09-08
Add LayerManager script and icon with lifecycle and editing fixes
2026-09-13 13:49:43 +02:00
zsviczian 4f6dc6260c updated slideshow script 2026-09-13 13:19:35 +02:00
zsviczian d8defd4c00 upload slideshow v4 logo 2026-09-13 12:58:59 +02:00
zsviczian c033e8b688 refactor: consolidate migration persistence handoff 2026-09-13 12:24:49 +02:00
zsviczian e5ba009cff refactor: serialize drawing writes by path 2026-09-13 06:54:55 +02:00
zsviczian c7c53f5d3e fix: retry autostart after view runtime replacement 2026-09-13 05:53:55 +02:00
zsviczian 178d3178d5 refactor: hand off dirty view unload persistence 2026-09-13 05:41:22 +02:00
zsviczian 3159282986 fix: classify drawing write notifications by content 2026-09-12 22:18:20 +02:00
zsviczian fbf64dc907 docs: record persistence checkpoint acceptance 2026-09-12 14:11:39 +02:00
zsviczian 071e3ef32a refactor: own prepared save snapshots 2026-09-12 14:10:07 +02:00
zsviczian 58d8ea8427 fix: preserve dirty views during file synchronization 2026-09-12 14:07:14 +02:00
zsviczian 45144b52d4 fix: publish synchronized scenes without history capture 2026-09-12 12:48:12 +02:00
zsviczian 3899d05664 fix: deduplicate copied markdown image renders 2026-09-12 10:16:28 +02:00
zsviczian af1cbe744d fix: retain latest external drawing sync 2026-09-12 10:06:41 +02:00
zsviczian a42e9525df refactor: separate save and synchronization state 2026-09-12 06:37:18 +02:00
zsviczian 0e60557cf7 fix: preserve foreground sidepanel activation 2026-09-11 22:25:32 +02:00
zsviczian 3e4ab8c138 refactor: add lifecycle state accessors 2026-09-11 22:16:52 +02:00
zsviczian bcd4089a73 refactor: clarify persistence lifecycle names 2026-09-11 20:49:25 +02:00
zsviczian 8e13a1808b updated file persisitance lifecycle specification 2026-09-11 20:30:52 +02:00
zsviczian d0b2886fda save sticky note stroke color 2026-09-11 20:12:35 +02:00
zsviczian abff7747e3 slide sorter preview caching improvement 2026-09-10 18:59:16 +02:00
zsviczian a601c3f470 updated slidshow script. Added created to new element 2026-09-08 19:56:39 +02:00
zsviczian 9fc77783c6 do not double measure image size for svg images. 2026-09-08 18:34:11 +02:00
tryinget 2d14cb90c5 feat: add LayerManager script with lifecycle and editing fixes 2026-09-08 12:31:33 +02:00
zsviczian 7abf0dfea2 updated AI skill to avoid using native window.confirm and other such dialogs in favor of Modal confirmation prompts. 2026-09-08 08:10:48 +02:00
zsviczian 41b6f52161 Update package-lock for Excalidraw 0.18.135 2026-09-07 12:17:59 +02:00
zsviczian e35ed8ed69 0.18.135 - marker frame fix 2026-09-07 12:13:12 +02:00
zsviczian 01506674c7 Copy markdown image svg without the base64 font and image payload 2026-09-06 19:35:31 +02:00
zsviczian 3c159af7ef 2.27.3 2026-09-06 14:37:17 +02:00
zsviczian c1b6f280e5 bucket fill color palette - 0.18.133 2026-09-06 11:45:44 +02:00
zsviczian d2f331b32e translations 2026-09-06 11:02:10 +02:00
zsviczian 0b52d3f028 Merge pull request #2924 from zsviczian/sidepane-startup-fix
Avoid blocking sidepanel restore during startup
2026-09-06 10:50:26 +02:00
zsviczian 0ac5625752 Fix sidepanel startup restore timeout 2026-09-06 10:46:28 +02:00
zsviczian 2d64102fd8 Merge pull request #2923 from zsviczian/latex-error-handling
Add strict LaTeX error handling to Excalidraw Automate
2026-09-06 10:05:27 +02:00
zsviczian e1300933f3 Excalidraw Automate scripts can now opt into strict LaTeX validation with \{ throwOnError: true }\ in \addLaTex()\ and \tex2dataURL()\, allowing scripts such as ExcaliMath to catch and display MathJax errors. Requires Excalidraw Extras 0.1.0. 2026-09-06 09:55:48 +02:00
zsviczian 6cab6faf8f added repository zipping to package json - convenience solution 2026-09-06 07:42:44 +02:00
zsviczian 136b6d2599 Merge pull request #2922 from zsviczian/debug-markdown-images
Fix Markdown image persistence, conversion, and caching
2026-09-06 06:56:31 +02:00
zsviczian 568a6c62e6 fix markdown image cache refresh 2026-09-06 06:53:58 +02:00
zsviczian 7c562520b4 perf: reuse unchanged markdown image renders 2026-09-06 06:32:34 +02:00
zsviczian d76a405f09 fix markdown image conversion races 2026-09-06 05:58:15 +02:00
zsviczian 2a46de4fb9 fix local markdown image persistence 2026-09-05 21:54:01 +02:00
zsviczian b4f7b3f2d3 convert line and frame into slideshow if presentation is started 2026-09-05 18:43:47 +02:00
zsviczian dd30161150 Merge pull request #2921 from zsviczian/createElement-resolutions
Avoid unnecessary native DOM element creation
2026-09-05 18:32:45 +02:00
zsviczian f9b8093250 refactor: avoid unnecessary native element creation 2026-09-05 18:28:16 +02:00
zsviczian ff728e0023 slideshow update - added proper sorter view 2026-09-05 16:25:51 +02:00
zsviczian 9d26574170 updated comments in rollup.config.mjs 2026-09-05 12:53:48 +02:00
zsviczian f25410e686 chore(build): remove obsolete fs replacement workaround
The Rollup replacement for transitive require("fs") calls is no longer needed.

The original scanner finding was likely caused by opentype.js, which has since been removed and replaced with the focused SFNT font-metrics reader. Production builds generated with and without the replacement are byte-identical, confirming that the transformation no longer affects main.js.

Removing the no-op replacement also avoids silently masking any future dependency that genuinely introduces filesystem access.

Context: https://github.com/obsidianmd/eslint-plugin/issues/168
2026-09-05 11:09:14 +02:00
zsviczian 65ac23d9b3 updated to eslint 0.4.2, added extensive comments to rollup.config.mjs 2026-09-04 23:13:19 +02:00
zsviczian 1c8b10130a 2.27.2 2026-09-04 19:26:06 +02:00
zsviczian 4e7f46993c safer save, radixportal fixes 2026-09-04 18:04:36 +02:00
zsviczian e6f3e59aec fix: prepare 2.27.2 compatibility fixes 2026-09-04 15:41:46 +02:00
zsviczian ed60ee1ddf docs: record hidden-tab portal fix 2026-09-04 08:46:00 +02:00
zsviczian 76bc65f664 cleanup React runtime execution 2026-09-03 22:47:35 +02:00
zsviczian 992f14797a 2.27.1 2026-09-03 21:58:28 +02:00
zsviczian af6824d9ac fixing obsidian code scanner false positive: reacat 19 seen as script injection 2026-09-03 21:45:55 +02:00
zsviczian 402023519f 2.27.0 2026-09-03 20:55:00 +02:00
zsviczian d1e6a73e8b updated messgages 2026-09-03 20:24:03 +02:00
zsviczian ad6b2b8b4d 2.27.0-rc.4 2026-09-02 17:52:22 +02:00
zsviczian fe8a96ee7f fix grid color 2026-09-02 17:51:48 +02:00
zsviczian f1bf213898 Merge pull request #2919 from zsviczian/fix-dirty
Fix false dirty state from selection and modifier keys
2026-09-02 17:14:30 +02:00
zsviczian 9be221a313 fix: track only persisted drawing changes as dirty 2026-09-02 17:12:42 +02:00
zsviczian 58081803a1 2.27.0-rc.3 2026-09-01 22:04:47 +02:00
zsviczian ba0e66888c fix edge case when switching to an excalidraw view that has not been rendered during Obsidian startup but there is an autostart script already waiting to run. 2026-09-01 21:43:50 +02:00
zsviczian 0a92beec06 Merge pull request #2918 from zsviczian/ea-image-export-improvements
Add bounded ExcalidrawAutomate image exports
2026-09-01 21:35:03 +02:00
zsviczian c1d471bb1f feat: add bounded ExcalidrawAutomate image exports 2026-09-01 21:32:39 +02:00
zsviczian 529d584f01 fixed startupScript build 2026-09-01 19:04:37 +02:00
zsviczian 98b8aa2eba Merge pull request #2917 from zsviczian/script-execution-refactor
Refactor EA script execution lifecycles
2026-09-01 18:40:20 +02:00
121 changed files with 61435 additions and 6634 deletions

No files matched your search

+3 -1
View File
@@ -25,4 +25,6 @@ yarn.lock
.lock
# Obsidian files
Obsidian
Obsidian
repository.zip
+12 -6
View File
@@ -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.
@@ -198,6 +203,7 @@ This project uses a non-trivial Rollup build because startup time, popout-window
The build embeds or injects runtime code for:
- React, ReactDOM/client, and the official JSX runtime entry points built from the installed npm packages
- the customized `@zsviczian/excalidraw` Obsidian artifact built from Excalidraw's ESM source graph
- `MathjaxToSVG`
- `lz-string`
@@ -205,7 +211,7 @@ The build embeds or injects runtime code for:
These payloads are executed or unpacked at runtime. This is intentional.
React, ReactDOM, and the official JSX runtime entry points are normal modules in the main Rollup bundle, not separately compressed or evaluated payloads. React must remain external to the separately built Excalidraw artifact: the plugin supplies its one bundled private React runtime to the single evaluated Excalidraw runtime used by every view. Mermaid is also intentionally absent from the artifact and is loaded lazily at runtime through Excalidraw Extras. All other required Excalidraw assets are expected to work offline except the deliberately lazy CJK font subsets.
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
@@ -251,10 +257,10 @@ The host adapters are an internal protocol between this plugin and its exact `@z
### Popout Window Support
- `src/core/managers/PackageManager.ts` combines the plugin bundle's one private React/ReactDOM runtime with one evaluated Excalidraw artifact in the main application realm and leases that package to every view.
- 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.
- React and ReactDOM are bundled normally from their official npm entry points and kept in plugin/package lexical scope. Do not restore a compressed/evaluated React bootstrap or assign React or ReactDOM to `window`; only the documented `window.ExcalidrawLib` compatibility surface remains global.
- 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.
@@ -410,9 +416,9 @@ Backwards compatibility is a strong requirement in this repository.
## React Runtime Import Model
React usage in this repository is special because one normally bundled private React/ReactDOM runtime is package-managed across main-window and popout roots.
React usage in this repository is special because one compressed private React/ReactDOM runtime is package-managed across main-window and popout roots.
- Import React, ReactDOM, and JSX runtime entry points normally. Rollup must bundle them into the main plugin but keep them external in the library build and in the separately built Excalidraw artifact.
- 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.
+2 -2
View File
@@ -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
The plugin bundles one private React/ReactDOM runtime and combines it with one evaluated Excalidraw runtime. Every main-window and popout view leases that shared package while supplying its own stable `ownerDocument`.
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`).
- React and its JSX runtimes are bundled normally from official npm entry points. They must remain external to the separately built Excalidraw artifact and to the plugin's library build so neither path creates a second React copy.
- 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.
+261 -5
View File
@@ -14,6 +14,10 @@ isolation.
## Progress tracking
File-persistence status, 2026-09-14: checkpoints 1–12b are complete. Checkpoint 12b's own-write reload-guard extraction passed its full runtime gate and is committed as `b9481c32`. The persistence implementation sequence is complete; the remaining lifecycle, initial-load, and interaction semaphores are intentionally outside persistence ownership and should move only in separately evidenced refactors. Earlier combined-5b action-log entries preceding the recorded baseline restoration are rejected history, not descriptions of the final implementation.
The detailed execution specification and per-step ledger are in [File Persistence Refactor Implementation Handoff](<docs/File Persistence Refactor Implementation Handoff.md>). It records the preserved baseline, rejected experiments, causal evidence, accepted implementation, and risk gates for checkpoints 5b–12b. Retain it as the implementation record; do not resume an intermediate candidate from its chronological notes without checking the ledger and final checkpoint status first.
Release target: **2.27.0**.
Update this document in every refactor change. A change is not complete until
@@ -26,8 +30,11 @@ validated, and what remains uncertain.
| Retire legacy AI settings and fallbacks | Complete | Removed the retired migration, schema/default fields, GPT reset, and AI runtime fallbacks without filtering unknown persisted keys; manual testing found no issues |
| Extract settings implementation service | Implemented; awaiting manual validation | `PluginSettingsManager` now owns persistence, default assembly, remaining migrations, and API-key obfuscation; plugin methods and startup readiness remain intact, while temporary autosave enablement is now explicit plugin-instance state rather than persisted settings state |
| Migrate the settings tab to declarative settings with legacy fallback | Complete | Checkpoints 4A-4E migrated the full settings surface and passed focused manual validation. Checkpoints 5/6 finalized and activated the complete tree behind the persisted, restart-applied `useDeclarativeSettings` preference. The final checkpoint removed checkpoint-era names, dead adapter/type branches, unused declarations, and tab-lifetime references to controls owned by one rendered tree. Markdown export now rebuilds declarations without replacing the active control bindings. The supported legacy preference and empty-array fallback remain intentional. The final beta.5 production build is 4,798,339 bytes, 73,417 bytes above `master` and 2,450 bytes below the completed checkpoint-6 build; the Obsidian dependency/minimum remains `1.8.7` |
| Keep rich declarative descriptions on repeat navigation (#2935) | Complete | Rich `DocumentFragment` descriptions now remain as templates: definitions provide a fresh clone whenever Obsidian reads `desc`, and shared custom rows clone their name and description before each render. The maintainer confirmed the repeat-search reproduction is resolved; the fix was committed as `f5503b95` and issue #2935 was closed. |
| Align vault-path warnings with accepted setting values (#2934) | Implemented; awaiting manual validation | An empty drawing folder represents the vault root without a warning. The template row accepts existing folders, files, and extensionless link paths, matching template lookup; its suggestions include both folders and supported files. The shared settings hierarchy and warning behavior remain common to declarative and legacy layouts. |
| 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,14 +46,19 @@ 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; superseded by the shared bundled runtime | React, ReactDOM, and the official JSX runtimes were previously inflated before plugin bootstrap for private popout-window package creation. The later shared-runtime architecture removed the need for retained/evaluated React source, and the current build bundles those modules normally |
| 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. 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 |
| Preserve local Markdown images across drawing copy/paste and deletion | Implemented; base copy/paste fix manually validated; follow-up pending | A local Markdown image's element metadata now takes precedence over stale ordinary-image registry entries during scene synchronization. Paste copies available back-of-note bodies into the destination before its delayed save, and loading a damaged drawing no longer erases the plugin-wide source needed by other open drawings. Deletion detection and Markdown-image classification no longer perform restoring lookups as incidental side effects. Incompatible registry cleanup occurs inside an already-authorized save and does not request `loadDrawing()` for unchanged scene files. Clean sidepanel selection changes detach the prior editor without force-saving or reloading every scene image; pending content and appearance changes retain their existing render/persistence path. The confirmation can persist **Keep** or **Delete** for future deletions, with an **Ask every time** reset in both settings UIs |
| Make local Markdown-image/embeddable conversion transactional | Complete; manually validated | Conversion is serialized, reads the current Canvas-node fragment, waits for its automatic Vault persistence only when an active edit differs from disk, and verifies a unique section before changing either the scene or note. Image-to-embeddable conversion unwraps the owned marker block before inserting the section and keeps exactly one empty level-one heading when it is the final visible boundary before commented Excalidraw data. Reverse conversion removes that complete section boundary, rejects reserved markers or over-captured headings, and commits the staged note change only after the element conversion succeeds. The sidepanel tracks the selected Markdown-image identity rather than only the stable element ID, so it clears and refreshes across retyping |
| Validate Markdown-image dependencies and preserve conversion appearance | Implemented; awaiting manual validation | Focus validation now includes directly referenced external Markdown sources even when their runtime `EmbeddedFile.mtime` was never initialized. Nested drawing cache validation uses the existing dependency traversal with non-Excalidraw vault files included, so a Markdown source change invalidates every containing drawing cache. A command forces fresh generation for one selected image or all scene images, bypassing and replacing applicable persistent entries. Markdown-image custom data remains on an intermediate embeddable and supplies the restored appearance during reverse conversion |
| Extract `ViewSceneFileManager` (Phase 6 item 5) | Complete | `src/view/managers/ViewSceneFileManager.ts` now owns the active/next loader pair, the deferred background revalidation pass and its timer, the request-coalescing queue, and the stale-image retry loop (7 state fields, 5 methods). `loadSceneFiles()` and `scheduleSceneFileDeferredValidation()` stay as public delegates on `ExcalidrawView` (external callers: `ExcalidrawAutomate.ts`'s scripting surface and `EventManager.ts`'s leaf-switch handler, neither of which needed edits). The three byte-for-byte-duplicated loader-teardown blocks in `onClose()`, `onunload()`, and `clear()` collapsed to one call each to a new `terminateActiveLoaders()` method. A previously-missed direct external read of `activeLoader` in `EventManager.ts:387` is preserved via a pass-through getter on `ExcalidrawView`. `EmbeddedFilesLoader` and the shared `addFiles()` helper (still `ExcalidrawView`-owned, since it's also used by the unrelated LaTeX-equation-editing flow) are constructor-injected, matching the `ViewExportManager`/`MarkdownImageController` precedent |
| Establish a typed Excalidraw/Obsidian host boundary | Complete | `commonObsidianUtils.ts` and `obsidianUtils.ts` no longer discover, cache, expose, or call the plugin directly. The common and Excalidraw-package adapters now own every live setting and plugin-service capability, are installed transactionally per evaluated main/popout runtime, and are independently disposed on package teardown. Missing adapters use safe defaults for optional UI/settings reads and explicit errors for Mermaid/link-suggester services. Dead active-view/AI helpers were deleted; the sole live active-view layout lookup now uses the owning component's container ref. The registered adapters are the only remaining strong plugin references inside each evaluated runtime, with package-manager-owned lifetimes. Manual validation found no issues |
| Optimize image-cache purge lookups | Implemented; awaiting manual validation | Both IndexedDB purge passes now resolve each known vault path with `Vault.getFileByPath()` instead of scanning `Vault.getFiles()` once or twice per cache entry. Cache validity, mtime, retention, deletion, and object-URL revocation behavior remain unchanged; purge lookup work is now linear in cache entries rather than cache entries multiplied by vault files |
@@ -58,7 +70,7 @@ validated, and what remains uncertain.
| Investigate post-publication image decode/render latency | Pending; profile before changing behavior | The trusted-SVG bypass reduced synchronous `addFiles()` work from 12.76 seconds to 1.43 seconds, but the measured final batch still had roughly 3.2 seconds between publication and the next animation-frame callback. A future checkpoint should separate browser data-URL decoding, Excalidraw image-cache initialization, React/canvas work, and frame scheduling before selecting a fix; an animation-frame callback alone does not prove a completed paint |
| Performance baseline diagnostics (Phase 0) | Complete; instrumentation archived and removed | The runtime captures established the Phase 1A/1B priorities and supplied the acceptance evidence recorded below. The exact final instrumented checkpoint is preserved on the local `performance-refactor-1b-instrumented` branch for the future persistent-main-runtime feasibility spike. All `performanceDiagnostics` imports, counters, console checkpoint hooks, diagnostic-only callback parameters, and the `EXCALIDRAW_PERF_PHASE0` source module have been removed from the delivery branch; the historical findings remain in this plan without shipping temporary observability in the plugin |
| Share the main React/Excalidraw runtime with popouts (batch 2 checkpoint 1) | PackageManager simplification complete and lifecycle-validated | `PackageManager` now owns exactly one main-realm React/ReactDOM/Excalidraw package and one pair of typed host registrations. The strategy switch, per-window package map, fallback package, per-window evaluator, decompressed-source retention, and per-window host-disposer maps are gone. View leases still capture the real acquisition window for migration/persistence decisions and reference-count only the popout's temporary `ExcalidrawLib` alias. Custom font metrics register once with the shared runtime, while font styles remain per document. Upstream's stable `ownerDocument` boundary continues to own rendering, listeners, portals, fonts, timers, and realm constructors. This checkpoint deliberately does not change the destructive `onWindowMigrated` lifecycle, persistence handoff, React-root recreation, scene loading, or image transfer behavior |
| Bundle the shared React runtime normally | Implemented; awaiting focused runtime validation | Removed the nested React-runtime Rollup build, compressed `REACT_PACKAGES` bootstrap, regex postprocessing, and their obsolete source files/dependency. The main plugin now imports and bundles React, legacy/client ReactDOM, and both JSX runtimes once; the production `jsxDEV` fallback is preserved. The library build and separately built Excalidraw artifact still externalize React so no second copy crosses either boundary. `PackageManager` continues to own the shared package, host adapters, leases, and popout aliases; no view, migration, or persistence lifecycle changed. The obsolete `ownerDocument` compatibility cast in `ExcalidrawRoot` was removed because the published component contract now declares the prop directly. This packaging change was implemented in commit `39346559ced5aa349388d22954fa9a73a51f2959`. If the production bundle later approaches the 5 MiB limit, restoring that commit's compressed React packaging is a practical fallback and recovers approximately 114,871 bytes |
| 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 |
@@ -78,7 +90,14 @@ validated, and what remains uncertain.
| Coalesce drawing-backup persistence by vault path (Phase 1B.3a) | Complete | The main-window-owned `ImageCache` now delegates delayed drawing backups to a plugin-global `BackupPersistenceQueue`. Each path retains at most one active IndexedDB transaction and the latest trailing payload; a new queued payload replaces an obsolete one while preserving the existing 50 ms post-save delay. Backup writes now resolve on transaction completion rather than request scheduling. Rename flushes queued data before moving the backup key, deletion and backup-cache clearing cancel queued data after any active transaction settles, and plugin unload drops timers/references without starting new writes. Image-cache clearing remains independent. Save diagnostics distinguish scheduling, coalescing, and completed physical writes. Runtime validation covered popout/main timer ownership, two completed IndexedDB transactions, rename/save/reopen, deletion, and package/loader lifecycle. Timing-sensitive replacement, trailing-write, flush, and pending-cancellation branches are covered by the deterministic queue harness. Autoexport policy and general save-reason semantics remain separate Phase 1B.3 checkpoints |
| Make save side-effect policy explicit (Phase 1B.3b) | Complete | The public `save()` and `forceSave()` facades retain their signatures and behavior while delegating to private policy-aware implementations. A force-save policy now independently states whether to refresh scene files and whether to run save-time autoexport; save diagnostics carry the originating reason and selected autoexport policy through request, export scheduling, and completion. The window-blur path remains persistence-only with respect to scene-file loading, but deliberately retains SVG/PNG/Excalidraw autoexport and `onTriggerAutoexportHook`: repository documentation promises autoexport each time a drawing is saved, so the handoff's contract exception applies. Runtime validation confirmed that blur persisted and autoexported without a scene-file refresh, manual save retained both behaviors, and close/reopen restored all edits |
| Extract view save coordination without changing semantics (Phase 1B.4a) | Complete | Added a view-scoped `ViewSaveCoordinator` that owns the existing public-save and force-save routing, explicit side-effect policies, dirty-state transitions, autosave timer/function, and teardown/navigation force-save orchestration. `ExcalidrawView` retains compatibility delegates and its `TextFileView`-bound serialization/disk-write body; the externally accessed `autosaveTimer` and `autosaveFunction` properties remain available through accessors. The shared save/autosave/dirty semaphores, timer intervals, busy-wait limits, notices, Excalibrain unload exception, blur/manual policies, loader refresh behavior, and close ordering are mechanically unchanged. Runtime validation covered autosave, manual and blur force-save policies, main↔popout migration, teardown persistence, runtime deletion, and durable reopen with all five edits. Revision tracking, in-flight coalescing, and `flush()` remain the separate Phase 1B.4b checkpoint |
| Preserve edits made during persistence with revision/coalescing semantics (Phase 1B.4b) | Complete | `ViewSaveCoordinator` now advances a monotonic current revision from Excalidraw durable store increments and existing explicit dirty calls, records the revision owned by each save request, and advances the saved revision only after persistence, an unchanged terminal result, or the established view-unload scheduled-write handoff. One save loop owns at most one active request and one merged trailing request. Edits during synchronization/compression remain dirty and update that trailing request; an overlapping request already satisfied by the active revision is discarded without reaching the old `save.skipped` path. Manual force-save busy/notice behavior remains compatible. `flush()` waits for the loop and force-persists any revision still dirty before close or migration; the Electron delayed view-unload write remains intact. Runtime validation on SYL exercised a manual save followed by edits during compression, continued editing across successive trailing saves, final convergence to the newest revision, immediate close/reopen, and the inline `[[` regression. Serialization snapshots, side-effect policies, loader behavior, and popout runtime ownership are unchanged |
| 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 |
| Clarify persistence lifecycle names | Complete | Renamed only private state, request fields, parameters, and locals in the persistence/synchronization hot path: save requests now express own-write suppression, forced persistence, and same-file guard bypass; prepared serialization, TextFileView load identity, reload fallback, incoming data, merged elements, metadata application, and reload file IDs have explicit names. `executeSaveRequest()` replaces the ambiguous private save-policy method name. Internal autozoom callers use `suppressAutozoomOnce()`, while the historical public `preventAutozoom()` remains as a compatibility delegate. `ViewSemaphores.preventReload`, every timer, save argument position/default, await boundary, side-effect policy, and branch condition remain unchanged pending the later ownership refactors. Focused manual validation passed |
| Introduce semantic persistence/lifecycle accessors | Complete | `ViewSaveCoordinator` now exposes `isSaveInProgress` and `isBusy` while retaining the existing semaphore-backed definitions. `ExcalidrawView` exposes lifecycle, same-file edit, save-state, and own-write suppression operations. `FileManager`, `EventManager`, and `MarkdownImageEditor` no longer inspect or mutate `ViewSemaphores` directly. Each replacement preserves the former Boolean expression exactly; `EventManager` deliberately uses the narrower `isClosing()` query rather than adding migration rejection, and `isSaveInProgress` remains broad until persistence and synchronization ownership split in the next behavioral checkpoint. Focused manual validation passed |
| Split persistence and synchronization ownership | Complete | `ViewSaveCoordinator` is now the sole internal reader/writer of the compatibility `saving` field and brackets each queued persistence request itself. `synchronizeWithData()` uses a separate view-local `isSynchronizing` state. Existing mutual exclusion, busy checks, reload/unload waiting, and the three-second dropped-sync policy remain in place using the two explicit states. The synchronization-only `setDirty()` rejection is removed, so a merged scene that preserves newer local content can always advance the document revision and remain dirty for autosave/flush. Focused manual validation passed; the pending-latest synchronization improvement remains a separate checkpoint |
| Retain one pending latest external synchronization | Complete | `FileManager` now signals the modified `TFile` to the view and returns instead of reading, parsing, or retaining a waiter for event-time drawing data. Each view owns one active synchronization loop plus one `pendingExternalSyncPath` marker. The loop waits without a three-second loss boundary and only while an individual save or earlier synchronization actively owns the view. Between an active save and any trailing save, `ViewSaveCoordinator` gives the pending latest-state synchronization one turn; any resulting dirty revision folds into that trailing save instead of being starved by continuous local edits. The sync loop resolves the current file and reads/parses the latest Vault text only after acquiring ownership. Modify events received during that work re-arm the same marker, causing one latest-state reread. Same-file editing suspends rather than discards the marker, so synchronization resumes when editing ownership and its grace period end. Modify handling excludes the `ExcalidrawLoading` placeholder, which shares the drawing view type without the initialized view contract. Autosave resumes only after the pending marker is drained; lifecycle invalidation, file navigation, or runtime loss cancels work that no longer belongs to the view. Focused large-scene two-view validation passed |
| Narrow own-write suppression to the actual write | Complete | Large-scene serialization no longer arms `preventReload`. The prior reset timer and Boolean are cleared before `prepareGetViewDataFromSnapshot()`, then suppression is armed immediately before the live `super.save()` write and its cleanup timer is established immediately after that write resolves. A failed write clears suppression. Migration handoff and detached unload branches do not arm a live-view reload guard because they do not perform a live `TextFileView` write. This removes the multi-second compression window while leaving content-aware expected-write matching as the next small stage. Focused sustained alternating-edit validation passed |
| Match own-write echoes by prepared content | 5b.4 observation implemented; runtime evidence pending | The maintainer confirmed that restored 5a works, `CaptureUpdateAction.NEVER` resolves dirty ping-pong, and committed 5b.2/5b.3 routing and save ownership pass their focused gates. Traces prove residual divergence is caused by stale post-save Boolean suppression. The temporary 5b.4 classifier now observes exact successful/accepted/pending/failed/handed-off/different content and newer local revisions, but the Boolean still solely determines behavior. Validate the candidate decisions, then enable them only at the coalesced read boundary in 5b.5. Full convergence remains the final 5b gate |
| Replace same-file editing Boolean with view-local ownership | Implemented; revised force-save validation pending | `SameFileEditGate` tracks idempotent Canvas-element and Markdown-image-controller owners plus independent release grace records using the established two-second duration. Reacquisition and stale callbacks cannot clear newer or unrelated ownership. Blocked drawing modifies retain the existing latest-state synchronization marker. Migration refreshes its Markdown envelope after synchronous unmount when that pending path is invalidated. A same-file save initiator may now reconcile pending Vault state through only its own owner record before force persistence; other owners still block, and an actively edited Markdown-image source is preserved while other incoming elements merge. Accepted synchronization advances the raw source envelope. Markdown-image reload clear/re-arm workarounds are removed; viewport, raw-file, and public no-argument compatibility behavior remain intact |
| 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 |
@@ -200,6 +219,60 @@ final upstream work is merged into the fork and installed in the plugin.
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-09-13 | Revised checkpoint 8 after Markdown-image force-save overtook a pending shape | Reacquiring Markdown-image ownership kept view B's shape pending in view A. **Render now** then deliberately bypassed the same-file save guard and wrote A's stale scene, deleting the shape. Save initiators now reconcile pending disk state through only their own gate record, preserve the actively edited Markdown-image source, resolve the current merged image element, and then persist. Render, close, handoff, post-flush, and Canvas-entry force-save paths share this boundary; accepted sync also advances the raw Markdown envelope | Owner-specific bypass was added to the deterministic gate check. All persistence/classifier/snapshot/routing scripts, focused and unused-symbol lint, production build, bundle syntax, and diff checks pass with established baselines. Revised bundle: 4,917,773 bytes, SHA-256 `55fb6a7a981e17b2445631f00d72438a441ed9c039a0c25d570141d893fbfbab`. First retest the exact Markdown-image A → shape B → reopen/render A sequence and verify both changes in both views and after reopen |
| 2026-09-13 | Revised checkpoint 8 after same-file edit → migration overwrite | Moving a large drawing immediately after exiting a back-of-note editor allowed migration to invalidate the pending synchronization and serialize the captured scene against stale view `data`, later deleting the newer paragraph from disk. The source unmount remains before the first await; affected Markdown migrations now wait only the established same-file grace and reread the Vault envelope before serialization. No claim is made about whether the exposed interleaving predates checkpoint 8 | Focused view lint retains 18 established findings with none in the migration change; unused-symbol lint, gate check, production build, bundle syntax, and diff checks pass with 33 established circular warnings. Revised bundle: 4,915,716 bytes, SHA-256 `a504f2bf5a822f5a361b944b101baaad5f89ba9589321a710cfcfd285be31667`. First retest the exact paragraph-edit, exit, immediate **Move to new window** sequence and require both durable text and no serious-error Notice |
| 2026-09-13 | Implemented checkpoint 8 view-local same-file edit gate | Replaced the shared same-file Boolean/timer with idempotent owner identities and independent grace records. Canvas elements and Markdown-image controllers cannot clear each other; timer callbacks are realm-owned and stale-safe. Canvas entry is request-fenced across its pre-edit save so exit/removal cannot leave a delayed editor or leaked owner. Blocked modifies retain the existing pending latest-state synchronization until final release, and Markdown-image reload no longer needs explicit clear/re-arm gaps | Gate, classifier, snapshot, routing, persistence-queue, and backup-queue checks pass. Focused and unused-symbol lint, production build, bundle syntax, and diff checks pass with established lint/circular-warning baselines. Candidate bundle: 4,915,501 bytes, SHA-256 `6dad62e31c17e2d30ad38e52d59013941415ce3d3249e126aa984e6b176017cc`. Runtime gate: overlapping owners, final modify during grace, Markdown-image switching/close, navigation, both popout workflows, large-scene alternating edits, and physical mobile |
| 2026-09-13 | Committed checkpoint 7 ordered exact-payload BAK | Maintainer-accepted checkpoint 7 and its recovery callback correction were committed before checkpoint 8 began | Commit `d1bd628c` (`refactor: back up completed persistence writes`) |
| 2026-09-13 | Accepted checkpoint 7 ordered exact-payload BAK | The maintainer accepts the revised candidate, including the dead-view recovery callback correction. Small-drawing synchronization/recovery passed. A BAK created after independently closing two already-divergent very large views lacked edits unique to the overwritten snapshot; this is recorded as the existing complete-snapshot non-merge limitation rather than a BAK ordering regression | Candidate is ready to commit at 4,913,587 bytes, SHA-256 `ccd00809e6b87ef4b05bac43bd389f845e66d0a4ffd3212b47c5518b29737e53`. Checkpoint 8 starts only after this boundary is committed |
| 2026-09-13 | Implemented checkpoint 7 ordered exact-payload BAK | Detached and replacement-owned migration writes now schedule BAK only after successful `vault.modify()` using their immutable request text and captured non-empty eligibility. Live and direct-migration BAK scheduling moved inside the shared per-path write lease and uses exact `PreparedSave.text`, preventing an older continuation from scheduling after a newer source completion. Backup failures remain independent and use the existing main-window `ImageCache`/`BackupPersistenceQueue` logging and storage. Recovery validation also found and removed a dead-view `this.app` dereference from the asynchronous restore confirmation; it now uses the already captured plugin owner | Persistence-queue checks cover exact backup order, source failure, empty-scene eligibility, and schedule failure. A new backup-queue check covers delayed coalescing, slow-active/newest-trailing order, backup failure with later progress, and clear/cancel semantics. Focused lint, unused-symbol lint, classifier/snapshot/routing checks, production build, bundle syntax, and diff checks pass with the established 18 view lint findings and 33 circular warnings. Revised candidate bundle: 4,913,587 bytes, SHA-256 `ccd00809e6b87ef4b05bac43bd389f845e66d0a4ffd3212b47c5518b29737e53`. Runtime gate: first-click recovery plus normal, immediate-close, migration, competing-write, empty-scene safeguard, and rename recovery using disposable drawings |
| 2026-09-13 | Accepted checkpoint 6b.2 and completed checkpoint 6 | The general plugin-owned queue now owns serialized popout-to-main handoff storage and ordering while the recreated main-window view retains responsibility for initiating the physical write. The specialized persistence-handoff manager is retired; drawing-runtime handoff remains separate. Work pauses at this accepted boundary before checkpoint 7 | Maintainer reports the complete 6b.2 runtime gate passed successfully, covering the migration and concurrent-write risks documented in the implementation handoff |
| 2026-09-13 | Implemented checkpoint 6b.2 replacement-owned migration persistence | Removed the specialized serialized migration handoff manager and folded its data-only, one-shot storage into `ViewPersistenceQueue`. Source-popout registration reserves per-path order without writing; only a matching recreated main-window view starts the physical write. Mismatch, discard, and 15-second expiry release the reservation; failures remain centrally visible. Drawing-runtime state handoff stays separate, and BAK remains checkpoint 7 | Queue checks cover no-write registration, migration-before-trailing order, mismatch without exposing foreign text, discard, deterministic expiry, and all earlier FIFO/lease/failure cases. Focused lint, unused-symbol lint, classifier/snapshot/routing checks, production build, bundle syntax, and diff checks pass with the established 18 view lint findings and 33 circular warnings. Candidate bundle: 4,913,022 bytes, SHA-256 `aeb201a5cf81a49b99741ea5473b12094d21157c6d6f0a8650210d1162c3f680`. Runtime gate: dirty popout → main migration with a concurrent same-file edit, main → popout, distinct **Open in new window**, last dirty popout close, and one large compressed migration |
| 2026-09-13 | Accepted and committed checkpoint 6b.1 physical per-path write exclusion | The shared live/detached write boundary behaved correctly under the complete recommended runtime gate. This accepts non-overlap and accepted-operation ordering for the tested workflows; popout-to-main replacement handoff consolidation remains the next scoped checkpoint 6 change. Commit `e5ba009c` | Maintainer reports success for large-scene live-save versus dirty-close, two rapid independently dirty closes, both popout workflows, and the no-loss/no-stall/no-ping-pong/no-viewport-jump criteria |
| 2026-09-13 | Implemented checkpoint 6b.1 physical per-path write exclusion | Added a data-only, idempotently released write lease to the plugin-owned persistence queue. Live `super.save()`, ordinary unload handoff acceptance, and direct main-realm migration writes now share that boundary without giving the queue a live-view callback. This prevents overlapping/overtaking physical writes but deliberately does not claim that FIFO order reconciles independently captured stale snapshots. Popout-to-main replacement persistence and manager consolidation remain 6b.2 | Queue checks cover detached-before-live and live-before-detached ordering plus all 6a cases. Focused lint, unused-symbol lint, classifier/snapshot/routing checks, production build, bundle syntax, and diff checks pass with 33 established circular warnings. Candidate bundle: 4,912,110 bytes, SHA-256 `cb41dd492d89456811401685f3b32edb4f39de6a9f00292901dbfdf445823c3c`. Runtime gate: large-scene live-save versus dirty-close, two rapid dirty closes, both popout operations, no lost edit/stall/ping-pong/viewport jump |
| 2026-09-13 | Accepted checkpoint 6a ordinary dirty-unload persistence | Maintainer stress testing found no lost updates or viewport jumps across five simultaneous mixed Markdown/Excalidraw representations, side-by-side views, **Move to new window**, and **Open in new window**. Additional desktop/mobile concurrent editing remained stable under Obsidian Sync latency. A transient malformed drawing payload was surfaced by the existing Notice; after Sync settled, saving preserved the latest valid scene and left the file intact. This accepts only ordinary dirty-unload handoff; live/detached ordering and migration-handoff consolidation remain checkpoint 6b | Runtime coverage included four Excalidraw views plus one Markdown view, two desktop plus one mobile view with parallel Markdown-embeddable edits, and mixed mobile pen/desktop scene/Markdown editing. The one lost Markdown paragraph edit was attributed to known Obsidian editor behavior and is not counted as a persistence-refactor failure |
| 2026-09-12 | Implemented checkpoint 6a plugin-owned ordinary unload persistence | Replaced the view-owned 200 ms fire-and-forget ordinary-unload write with immutable handoff to a plugin-owned per-path FIFO. Requests carry prepared save/target identity, captured file creation time, reason, and future BAK eligibility; execution resolves the `TFile`, refuses missing/recreated targets and empty text, reports failure centrally, and never coalesces independent producer snapshots. The coordinator outcome is now `persistence-handed-off`. Live `super.save()`, migration branches/managers, multi-producer ordering, and BAK remain unchanged | `node scripts/check-view-persistence-queue.mjs` covers FIFO/trailing work, target validation, empty input, failure isolation, later progress, and flush. Focused lint, unused-symbol lint, classifier/snapshot/routing checks, production build, bundle syntax, and `git diff --check` pass with the established 33 circular warnings. Bundle: 4,911,256 bytes, SHA-256 `59b4e3a2c8184a3f77d7eb97d4d857c5b17a5e857c18e4bff7fd40132380c496`. Runtime gate: unsaved immediate tab close/reopen, unsaved switch to Markdown, plugin disable/reload plus full restart, and one large compressed immediate close. No BAK update is expected until checkpoint 7; two independently dirty closers remain a 6b ordering test |
| 2026-09-12 | Accepted the revised clean checkpoint 5b candidate | Maintainer confirms **Open in new window** now works correctly with the explicit active-`setViewData()` completion boundary. This closes the diagnostic-sensitive lifecycle regression; **Move to new window** remained healthy, and the preceding instrumented large-scene, same-file editing, mixed-view, dirty-migration, and unsaved mode-switch coverage remains accepted | Checkpoint 5b is ready to commit. Temporary diagnostics are absent from source and bundle. Original checkpoint 6 starts with ordinary dirty unload as a separate increment; special migration handoff consolidation remains deferred until that queue is proven |
| 2026-09-12 | Rejected the first clean popout candidate and replaced its timer assumption with load completion | The diagnostic-free build regressed **Open in new window**, while **Move to new window** remained healthy. The accepted trace showed the source view's `content-accepted` transition occurring during the 220 ms timer wait; removing diagnostic work let the zero-delay timer win before that active `setViewData()` load settled. Migration now captures the exact per-view load promise before synchronous unmount, awaits it after any required save flush, and then yields one destination task before source replacement. The completion record settles on normal, early-return, and rejected layout-ready paths; it does not alter file identity or add checkpoint 11 generation invalidation | Revised clean bundle: 4,909,585 bytes, SHA-256 `15733871836c02a3dfcd84a3e9c817028ca34d153366b352c40c2c467f7a3982`. Classifier, snapshot, and routing scripts; unused-symbol lint; production build; bundle syntax; trace-prefix search; and `git diff --check` pass. `ExcalidrawView.ts` retains exactly its 18 established lint findings and Rollup retains 33 circular warnings. Retest **Open in new window** first for distinct loaded views and bidirectional sync, then **Move to new window** including a dirty migration; do not infer success from timer elapsed time |
| 2026-09-12 | Accepted the instrumented 5b.5 lifecycle gate and produced the clean candidate | Maintainer testing could no longer break save or synchronization on the approximately 4,400-element drawing. Passing coverage included active back-of-note editing with tab switches, adjacent Markdown/Excalidraw representations, dirty migration without a prior save, unsaved hotkey switching to Markdown mode, and the corrected **Open in popout** path. Removed all temporary anonymous-view, fingerprint, classification-decision, and migration-phase diagnostics while retaining exact-content classification and the one destination-window yield | Classifier, snapshot, and routing scripts; focused lint; unused-symbol lint; production build; bundle syntax; and `git diff --check` pass. `ExcalidrawView.ts` retains exactly its established 18 errors and Rollup retains 33 established circular warnings. Searches find no `EXCALIDRAW_PERSISTENCE_5B4` trace code in `src/` or `dist/main.js`. Clean bundle: 4,909,082 bytes, SHA-256 `a1b49ad6b31e527c291ecc0dfdcf585d20cb272da010f1068aa0859f8faa86a9`. Final gate before commit: deploy this clean bundle and repeat first-edit, sustained alternating large-scene, and bidirectional **Open in popout** convergence without rescue input |
| 2026-09-12 | Distinguished **Open in popout** from **Move to popout** and corrected reentrant replacement | The earlier passing trace covered tab migration only. In the newly supplied **Open in popout** trace, `closeLeafView()` returned with `sourceStillLeaf=1`; replacement returned `sameAsSource=1`; that source later became API-ready while permanently migrating and was excluded from incoming synchronization. This retracts the earlier general popout acceptance. The callback was running inside the new leaf's active view-state transition, so its immediate nested state changes were resolved no-ops | Preserved synchronous snapshot/root unmount and any dirty flush. Added one destination-window main-task yield before source close/reopen, allowing the outer state transition to finish; the lifecycle guard remains intact. Instrumented validation must show `sourceStillLeaf=0`, `sameAsSource=0`, and bidirectional updates for both opening modes. Combined 5b.5/popout bundle passes focused checks and build: 4,913,456 bytes, SHA-256 `b5d3e75b650bfa20c54126710cb15bad3f01ecc730bdeca780cf39761980ecc0` |
| 2026-09-12 | Implemented checkpoint 5b.5 content-aware Markdown notification handling | A Boolean-armed Markdown notification is no longer discarded. It continues through the existing coalesced synchronization loop, whose single owned Vault read skips parsing only for exact successful or accepted bytes. Matching content never acknowledges a newer local revision; different, unknown, pending, failed, or handed-off content follows normal reconciliation. Removed the temporary shadow-read loop. Raw `.excalidraw` suppression and same-file edit ownership remain unchanged. Popout acceptance is tracked separately by opening mode and is not inferred from the passing **Move to popout** trace | Classifier, snapshot, and routing scripts; focused and unused-symbol lint; production build; bundle syntax; and diff checks pass. `ExcalidrawView.ts` retains its exact 18-error baseline and Rollup retains 33 circular warnings. Runtime gate: first validate **Open in popout** replacement, then small first-edit and duplicate-notification cases, sustained alternating edits on the large scene, viewport/undo/layer/deletion/reopen integrity, same-file edit release, both popout opening modes including unsaved migration, and one mobile smoke test. Remove all temporary diagnostic strings and rerun uninstrumented before commit |
| 2026-09-12 | Proved the popout synchronization gap is unresolved migration ownership | The affected anonymous view 3 appears in all 17 modify enumerations with `returnedByType=1`, `loaded=1`, `api=1`, and `fileMatch=1`, but always `closingOrMigrating=1`; it is therefore skipped at the intended lifecycle guard before routing or classification. Its own subsequent edits complete three saves as `window-migration-persisted`, proving `windowMigrating` remains active rather than the view merely missing one notification | No behavior change or guard bypass. Added temporary complete-string phase observation at migration entry, source unmount, flush settlement, source close, and replacement dispatch/settlement. The next small main→popout reproduction must show the last completed phase and whether the leaf still references the source object. Only then correct teardown/replacement ownership and rerun bidirectional main/popout synchronization. Focused and unused-symbol lint, production build, bundle syntax, and diff checks pass; `ExcalidrawView.ts` retains its exact 18-error baseline. Bundle is 4,914,732 bytes, SHA-256 `3c7607fbf2648cf162a4ad32e21f403f7427d068edad324524b3027e8f6f690e` |
| 2026-09-12 | Validated 5b.4 main-window classification and isolated a popout pre-routing gap | In both supplied traces, views 1 and 3 classified their own suppressed notifications as `matches-successful-write`; four notifications suppressed in the other view classified `different-from-known-content`, validating the intended 5b.5 decision. One successful-content match retained `newerLocal=1`. A newly loaded popout view 4 recorded `content-accepted` but no later suppression, route, sync-read, or acceptance event, so this symptom occurs before the currently observed classification boundary | Production behavior remains unchanged. Temporary 5b.4 observation now compares type enumeration with all-workspace-leaf enumeration and emits complete strings for loaded/API/lifecycle/file-match and route state. Reproduce one main→popout write and one popout→main write; use the first missing target record to identify the exact early-return boundary before implementing a correction or enabling 5b.5. Classifier/snapshot/routing checks, focused and unused-symbol lint, production build, bundle syntax, and diff checks pass; bundle is 4,913,594 bytes, SHA-256 `b6bc2226a5bfe097b87371a3f7315496f3ba411b0143f783abde5270e9773506`. The 4,400-element lock/select latency reproduces on Excalidraw.com and is excluded from this persistence checkpoint absent evidence of additional plugin overhead |
| 2026-09-12 | Checkpointed 5b.2/5b.3 cleanly and implemented 5b.4 observation | Committed dirty-receiver routing as `58d8ea84` and minimum immutable save ownership as `071e3ef3`, followed by ledger commit `fbf64dc9`. Removed the broad 5b.1 trace before checkpointing. The new uncommitted 5b.4 layer logs candidate classification but leaves the legacy Boolean as the sole modify decision. Existing sync reads are reused; only Boolean-suppressed Markdown events get one bounded, coalesced, read-only shadow read | Pure classification, snapshot, and routing scripts pass; focused lint and unused-symbol lint pass; production build, bundle syntax, and `git diff --check` pass. Instrumented bundle: 4,912,850 bytes, SHA-256 `62d4a318aec18fc275c6c5fd624d0d53f65309c1a0347b803a9c721c3e0bc731`. Runtime gate: filtered `EXCALIDRAW_PERSISTENCE_5B4` strings must classify ordinary own echoes as successful/accepted redundancy and the known cross-view suppressed write as non-skippable. Keep this instrumentation through candidate validation; remove it after 5b.5 passes instrumented and then uninstrumented convergence tests |
| 2026-09-12 | Accepted minimum immutable save ownership for 5b.3 and removed broad tracing before checkpointing | Added explicit producer, target-generation, operation, requested-revision, and captured-revision identity. Save preparation works from detached scene/nested element/app-state/file/deletion/selection inputs and a captured Markdown envelope; the exact final text is returned as `PreparedSave`. Revision completion acknowledges the actual capture, and only completed physical writes publish successful prepared identity. The maintainer reports all large-scene tests passed, including bound linear elements and other change types. No modify classification or suppression behavior changed | `node scripts/check-save-snapshot.mjs`, focused lint, unused-symbol lint, production/library builds, bundle syntax, and `git diff --check` pass. The build retains 33 established circular warnings and exactly 18 established `ExcalidrawView.ts` lint errors. Clean bundle: 4,905,956 bytes, SHA-256 `46873e0e72d5264b3aa240be88cb395a37d44b72a1f09fe2fc16e07ea05c9de5`. The broad `EXCALIDRAW_PERSISTENCE_5B` trace was removed before commit; 5b.4 should add only candidate-classification observation. Two-view divergence remains expected until 5b.5 |
| 2026-09-12 | Validated dirty-receiver synchronization and isolated the remaining screen divergence | In the new 1,223-line stress trace, no modify took the full-reload route. Dirty receivers repeatedly entered incremental synchronization, and the maintainer reports substantially better dual-edit performance. Views eventually differed on screen, but reopening the missed view loaded the accumulated updates, confirming persistence survived. Seven cross-view events were still consumed by the receiver's stale post-save Boolean; this exactly matches the already assigned 5b.3–5b.5 defect rather than invalidating the routing correction | Scoped 5b.2 manual gate passes; commit remains pending. The trace's cross-suppressions occur at sequences 563, 684, 731, 850, 903, 1012, and 1123. No new routing predicate is indicated. Next implement minimum capture/prepared-text/write-completion ownership in 5b.3, retaining observation-only behavior until 5b.5 enables content-aware classification |
| 2026-09-12 | Routed dirty or busy stale Markdown receivers through synchronization | Extracted the production modify decision into `getDrawingModifyRoute()`. Same-file Markdown views with local dirty state or active persistence work now bypass the five-minute destructive full reload and use the existing pending latest-state synchronization/merge path. Clean idle stale Markdown and raw `.excalidraw` behavior remain unchanged. This addresses Trace A only; the proved cross-view suppression defect remains intentionally unfixed for 5b.3–5b.5 | `node scripts/check-file-modify-routing.mjs` passes six production-helper cases, focused lint of the new helper/FileManager/diagnostic support passes, and the Node 22.22.2 production build passes in 10.7 seconds with the established 33 circular-dependency warnings. Bundle syntax and `git diff --check` pass. Instrumented bundle: 4,915,216 bytes, SHA-256 `16534db42f8f0f1b28d69c123166ef02f5a2c6a056e3544c61fbb9bd876a6327`. Manual risk gate: reproduce the old-file dirty-receiver interleaving; receiver must log incremental sync, retain both non-conflicting edits and viewport, and persist both. Immediate propagation back to the writer remains gated by the separately proved Boolean defect |
| 2026-09-12 | Classified both remaining propagation failures from the 5b.1 runtime traces | Trace A proves a dirty V2 local edit is overwritten when V1's write is routed through the five-minute full-reload branch: the local edit precedes `modify-route-full-reload`, and no pending read/merge occurs before reload clears dirty. Trace B proves the post-save Boolean repeatedly consumes the other view's writes: six cross-view suppressions are present, and the last leaves both views clean and all queues idle with different scene fingerprints. This is dropped work, not a slow or stuck queue | Evidence-only update; no corrective source change. Checkpoint 5b.2 now has two separate regression cases. First correct and test dirty-receiver routing through existing incremental synchronization. Preserve the cross-suppression failure through 5b.3–5b.5 so exact prepared/successful content identity replaces save-owned timing suppression; do not shorten the timeout or remove re-arm as a heuristic. Temporary diagnostics remain uncommitted |
| 2026-09-12 | Committed the accepted remote-history fix and added bounded 5b.1 propagation instrumentation | Commit `45144b52` contains the confirmed `CaptureUpdateAction.NEVER` correction and the three persistence planning documents. The subsequent diagnostic patch remains uncommitted and adds no intended persistence behavior change. It traces anonymous view/revision/queue/suppression/routing/read/parse/merge/publication state with one complete string per event under prefix `EXCALIDRAW_PERSISTENCE_5B`; content is represented only by bounded counts, hashed element IDs, and text/scene fingerprints. A five-second post-activation snapshot captures quiet divergent state | Production build passed in 10.2 seconds with the established 33 circular-dependency warnings; bundle syntax and `git diff --check` passed. The instrumented bundle is 4,914,810 bytes, SHA-256 `91993059ab69fff35ebb4313811d4d76089dd7c29539b3860cff9e5af5de1fe7`. Focused lint reports only the established 18 `ExcalidrawView.ts` findings; the new helper and other three instrumented files are clean. Runtime gate: stop at first divergence without force save/reload/rescue edit, wait at least five seconds, then copy all filtered trace strings in order and identify the missed visible edit |
| 2026-09-12 | Accepted reported dirty-loop improvement and redirected the remaining divergence investigation | Maintainer confirms the isolated `NEVER` change resolves dirty ping-pong, but repeated A/B edits on the 4,400+ element scene still leave divergent live views. Baseline checkpoint 5b.0 is complete as a comparison; retain the narrow change and investigate under 5b.1–5b.5. Updated the handoff to trace the first missed propagation rather than requiring a new dirty loop, prioritize routing and suppression re-arm evidence, distinguish idle divergence from waiting work, and remove a circular gate that would require fixing the Boolean before reaching its planned replacement. Original checkpoints 6–12 remain gated on convergence | Assessment/documentation only; source remains the isolated capture-mode change. Static review confirms Boolean consumption precedes the pending marker, successful saves re-arm suppression, expiry only clears it, and full-reload routing can return early while busy. These establish testable timing paths, not the cause of this incident. Next runtime deliverable is a bounded trace and smallest reproducing interleaving after plan confirmation. Detailed local undo, competing-edit integrity, viewport and platform coverage remain explicit acceptance tests |
| 2026-09-12 | Isolated incoming synchronization from local undo history | After confirming committed 5a still converges, the maintainer observed that a receiving view becomes dirty despite receiving no change beyond view A's synchronized update. Changed only `applyIncomingSynchronization()` publication from `CaptureUpdateAction.IMMEDIATELY` to `NEVER`; the existing merge-owned explicit dirty branch is unchanged. None of the failed experiment's hash matching, viewport injection, dirty predicate, semaphore removal, or embeddable changes was restored | Production build passed in 11.6 seconds with the established 33 circular-dependency warnings; bundle syntax and `git diff --check` passed. The bundle is 4,903,357 bytes, SHA-256 `acfe02c8592ccae73aaea8ffb1ab034b8517358081f1c72360088244ee14adeb`. Focused lint retains the same 18 existing `ExcalidrawView.ts` errors, none on this change. Highest-risk manual test: edit only clean A and confirm B receives it but remains clean and does not gain the incoming update in its local undo history. Then edit B locally, verify normal dirty/undo/save behavior, preserve each view's viewport, and repeat alternating large-scene edits until idle convergence |
| 2026-09-12 | Preserved failed 5b experiment and restored the controlled baseline | Path-scoped stash object `2b158abb204fd9b7e76aeea0a80e12476ce9879e` contains exactly the five failed runtime paths. The three planning documents remained in the working tree. Source is now identical to HEAD `3899d056`, the committed 5a behavior plus the accepted image-loader fix. No failed-experiment hunk was reapplied, no branch was moved, and no behavioral change was added | Node 22.22.2 production build passed in 11.1 seconds with 33 circular-dependency warnings. `node --check` and `git diff --check` passed; focused lint retained 18 existing `ExcalidrawView.ts` errors and one existing `CustomEmbeddable.tsx` error. Baseline `dist/main.js` is 4,903,363 bytes, SHA-256 `cd2f5459151c56cb6ec920bb7ff369eec489be76cc87159292bf4e7dd90dc560`; installed fork is declared/installed `0.18.135` with artifact hashes recorded in the handoff. Manual 5b.0 gate pending: fresh fixture, full restart, one edit in A, switch once to B, then no input until queues should settle |
| 2026-09-12 | Added the detailed persistence implementation handoff | Expanded the maintainer's appended Astra plan into a linked execution specification with safe source-only stashing, exact baseline identities, dependency/artifact controls, six 5b stages, source map, verified hazards, controlled interleavings, ownership/acknowledgement contracts, and original checkpoints 6–12 with risk-based gates. The handoff owns the task ledger; this document retains acceptance and action history | Documentation only. Baseline switch, stash, runtime edits, instrumentation, build, deployment, and commits have not been performed. Verify document links and `git diff --check`; the next implementation action remains preserving the failed experiment and testing committed 5a with the accepted image fix |
| 2026-09-12 | Paused checkpoint 5b and reviewed its assumptions | Maintainer testing still reproduces dirty/save ping-pong after the first edit and leaf switch. Reviewed the working diff against committed 5a and the lifecycle specification; replaced the remaining roadmap with baseline comparison, causal tracing, convergence tests, minimum save ownership from step 9, and staged content classification before detached persistence. Corrected unsupported claims about harmless ordering, passive parsing, globally comparable revisions, and causal event identification by hash. Earlier 5b fix explanations remain historical hypotheses, not established root causes | Documentation-only review; no source changes, rollback, build, or deployment. Static inspection and an isolated execution of the exact unchanged-link parser loop confirm that parsing can increment element versions without a changed link, but do not reproduce the runtime loop. First manual gate: preserve the failed patch and compare `3899d056` (committed 5a plus the validated image fix), optionally exact 5a `af1cbe74`, using identical disposable fixtures and full Obsidian restarts. One edit plus one switch must settle without further input; then test sustained competing edits, reopen integrity, and independent cameras. Subsequent checkpoints have focused main-window, popout, and physical-mobile risk gates in the revised roadmap |
| 2026-09-12 | Replaced aggregate synchronization dirty inference with merge-owned evidence | Continued large-scene testing still produced dirty-state ping-pong after remote capture and viewport preservation. The remaining dirty branch compared `hashElementsVersion(mergedElements)` with the incoming scene. That hash incorporates element order, so per-view ordering/runtime normalization could repeatedly look like locally newer content even when no edit survived. Reconciliation now records persistence ownership directly: a visible local-only element or a matching local element with a higher version requires write-back; incoming-winning, equal, and order-only differences do not. If the view is already dirty, the same surviving state does not manufacture another revision. Element winner rules, insertion/layer behavior, deleted-element handling, and metadata refresh remain unchanged | Node 22.22.2 production and library builds pass with the established 33 circular-dependency warnings. Bundle syntax, focused manager/coordinator/type lint, unused-symbol lint, retired aggregate-comparison/name searches, and `git diff --check` pass. The touched large files retain exactly their established 18 plus one lint findings, none on the reconciliation changes. The production bundle is 4,904,430 bytes, 338,450 bytes below 5 MiB. Highest-risk retest is the exact no-input failure: after one edit has synchronized, stop interacting and verify neither view becomes dirty again, no further saves alternate, and the next edit propagates. Then create simultaneous distinct edits before either sync completes; both must survive, the merged receiver may legitimately remain dirty until its combined state is saved, and both views must then converge cleanly |
| 2026-09-12 | Made incremental synchronization preserve the receiving view's camera | After the dirty-echo correction, side-by-side testing showed that a received scene replacement could move the non-writing view. `applyIncomingSynchronization()` now captures that view's live `scrollX`, `scrollY`, and `zoom` immediately before publication and includes them with the remote element update. This does not read or copy the writing view's persisted app state, add a timer, or alter element reconciliation; it makes the existing per-view viewport invariant explicit at the exact scene-replacement boundary | Node 22.22.2 production and library builds pass with the established 33 circular-dependency warnings. Bundle syntax, focused manager/coordinator/type lint, unused-symbol lint, retired-name search, and `git diff --check` pass. The two touched large files retain exactly their established 18 plus one lint findings, none on the viewport change. The production bundle is 4,904,356 bytes, 338,524 bytes below 5 MiB. Retest with the two views deliberately panned and zoomed to visibly different locations: editing either view must update elements in the other without changing the receiver's camera. Repeat once while the receiver has a local unsaved competing edit; it should stay dirty and preserve both its local element and camera |
| 2026-09-12 | Corrected incoming synchronization dirty echo exposed by content-aware matching | Initial large-scene competing-edit validation quickly reached continuous dirty state in both views, long-lived save occupancy, and force-save aborts. Content-aware matching correctly stopped one view from consuming another view's write, exposing a separate revision-classification defect: `applyIncomingSynchronization()` published the persisted incoming baseline with `CaptureUpdateAction.IMMEDIATELY`, which Excalidraw defines for local undoable updates. Its durable increment therefore advanced the receiving view as though the synchronization itself were a local edit. Publication now uses `CaptureUpdateAction.NEVER`, Excalidraw's remote-update/scene-initialization mode. The existing merged-versus-incoming comparison remains unchanged and is the sole dirty decision: an exact incoming baseline stays clean, while locally newer surviving state advances the revision and is persisted | Node 22.22.2 production and library builds pass with the established 33 circular-dependency warnings. Bundle syntax, unused-symbol lint, and `git diff --check` pass. Focused lint retains exactly the established 18 `ExcalidrawView.ts` and one `CustomEmbeddable.tsx` findings, with none on the changed synchronization line. The production bundle is 4,904,251 bytes, 338,629 bytes below 5 MiB. Highest-risk retest is the exact large-scene alternating-edit sequence: after each incoming update, the receiving view's dirty indicator should remain clear unless it already contains an unsaved competing edit; once interaction stops, both save loops must settle, Ctrl/Cmd+S must not report an in-progress save, and both scenes must converge. Also repeat the older-incoming/newer-local reconciliation case to prove the necessary dirty branch was not suppressed |
| 2026-09-12 | Replaced Boolean own-write suppression with prepared-content matching | Carried the requested save revision into `executeSaveRequest()`, fingerprinted the exact prepared text after serialization, and armed a view-owned `{ filePath, revision, contentHash }` record only for the live `TextFileView` write. `FileManager` now reads and fingerprints the latest Vault text before consuming an event; mismatch or comparison failure is handled as external synchronization. Removed `ViewSemaphores.preventReload`, its timer/accessors, and the two independent same-file embeddable suppression calls. The remaining two-second timer only cleans up an abandoned record. Failed writes, force-save entry, view reset, and teardown clear it; migration and delayed unload persistence do not arm it | Node 22.22.2 production and library builds pass with the established 33 circular-dependency warnings. Bundle syntax, focused manager/coordinator/type lint, unused-symbol lint, retired-name search, and `git diff --check` pass. `ExcalidrawView.ts` retains exactly its established 18 lint errors and `CustomEmbeddable.tsx` retains its one established error. The production bundle is 4,904,257 bytes, 338,623 bytes below 5 MiB. Highest-risk manual validation is sustained alternating edits in two views of the large drawing while saves overlap. Also verify ordinary own saves do not reload, a same-file Markdown embeddable releases and applies pending changes, a forced save still performs its intended reload path, and one popout/mobile save smoke test exercises Web Crypto and Vault comparison |
| 2026-09-12 | Closed pending-latest synchronization and write-window suppression checkpoints | Retained the bounded latest-state marker, save/sync fairness turn, same-file edit deferral, initialized-view filtering, and suppression timing reduction without further source changes | Maintainer confirmed the same-file edit release issue was fixed, sustained alternating edits became materially more reliable after save/sync fairness, and the final single missed-update case no longer reproduced after narrowing suppression to the actual write |
| 2026-09-12 | Narrowed own-write suppression to the Vault write window | Sustained two-view stress testing found one remaining update that appeared only after the next save. The timing matches the still-Boolean reload guard being armed before asynchronous large-scene compression. Serialization now runs with the guard cleared; only the subsequent live `super.save()` arms it, failed writes disarm it, and successful writes start cleanup immediately. The pending-sync fairness correction remains unchanged. Content-aware matching is deliberately a separate follow-up if the reduced window still permits a wrong event to be consumed | Node 22.22.2 production and library builds pass with the established 33 circular-dependency warnings; unused-symbol lint, bundle syntax, focused manager lint, and `git diff --check` pass. The production bundle is 4,903,139 bytes, 339,741 bytes below 5 MiB. Highest-risk manual check is sustained alternating edits in two views of the large drawing, watching specifically for one view to miss a single change until a later save. Also exercise a failed/aborted save followed by an external modification, and one ordinary small-drawing autosave to confirm its own write still does not reload the editor |
| 2026-09-12 | Replaced the three-second dropped-sync path with one latest-state marker | Added a view-owned synchronization drain with one active promise and one pending file path. The drain waits for an active persistence operation, acquires synchronization before resolving/reading/parsing the current Vault file, re-runs once when events arrive during the operation, and schedules reconciliation autosave only after all pending latest-state work is complete. `FileManager` no longer constructs a potentially stale `ExcalidrawData` or retains a promise waiter per modify event. The existing direct `synchronizeWithData()` facade remains available and uses the same unbounded lifecycle-aware acquisition path. Initial stress testing exposed that the modify handler still discarded the event while same-file editing was active; the marker is now armed immediately and waits through editing ownership and its release grace period. Stress testing also exposed that the view-type collection includes an `ExcalidrawLoading` placeholder without drawing-view lifecycle methods; modify handling now requests initialized views. Continued alternating edits on a very large drawing exposed synchronization starvation because acquisition waited for the entire save loop, including continually replaced trailing work. Synchronization now waits only for the active save, and the coordinator yields to the pending latest-state loop before starting a trailing save so the reconciled dirty revision can be included in that save | Node 22.22.2 production and library builds pass with the established 33 circular-dependency warnings; unused-symbol lint, bundle syntax, focused manager lint, and `git diff --check` pass. `ExcalidrawView.ts` retains exactly its established 18 lint errors. The production bundle is 4,903,052 bytes, 339,828 bytes below 5 MiB. Focused manual validation remains: release an edited back-of-note embeddable after another same-file view changes; sustained alternating edits during deliberately slow saves; multiple modifies during synchronization/image reload; navigation or close while pending; clean incoming-newer convergence; local-newer dirty persistence; same-file multi-view viewport retention; and malformed incoming data recovery |
| 2026-09-12 | Closed the persistence/synchronization ownership checkpoint | Retained the implemented save-versus-sync state split and reconciliation dirty correction without further source changes | User confirmed the focused collision, reconciliation, multi-view, and lifecycle behavior works as expected |
| 2026-09-11 | Split save-in-progress ownership from incoming synchronization | Moved all production reads/writes of `ViewSemaphores.saving` into `ViewSaveCoordinator`, introduced independent view-local synchronization state, and retained mutual exclusion at the coordinator/view boundary. Reload, unload, force-save, and Markdown-image busy behavior still consider both operations where the former broad flag did. Removed the deterministic synchronization-time dirty guard; revision coalescing and the existing three-second dropped-sync behavior are otherwise unchanged | Node 22.22.2 production and library builds pass with the established 33 circular-dependency warnings; bundle syntax and `git diff --check` pass. Focused ESLint is clean for the coordinator and types, while `ExcalidrawView.ts` retains exactly its established 18 errors. The production bundle is 4,901,420 bytes. Focused manual validation remains: older incoming element versus newer local element from a clean baseline, ordinary incoming-newer synchronization without an autosave loop, save/sync collision, same-file multi-view viewport retention, and close/migration during synchronization |
| 2026-09-11 | Closed the semantic persistence/lifecycle accessor checkpoint | Retained the implemented accessors and consumer migrations without further source changes | User reported no regressions after the focused manual validation |
| 2026-09-11 | Added semantic accessors ahead of persistence-state extraction | Added coordinator-owned save-state queries and view-owned lifecycle/same-file/own-write operations, then replaced every direct semaphore reference in `FileManager`, `EventManager`, and `MarkdownImageEditor`. Storage, timeout ownership, save queue state, method ordering, and all former conditions remain unchanged. No new manager or persisted state was introduced | Node 22.22.2 production and library builds pass with the established 33 circular-dependency warnings; bundle syntax, unused-symbol lint, direct-semaphore-reference searches in all three migrated consumers, and `git diff --check` pass. Focused ESLint is clean outside `ExcalidrawView.ts`, which retains exactly its established 18 errors. The production bundle is 4,900,225 bytes, 342,655 bytes below 5 MiB. Focused manual validation remains: own-write modify consumption, same-file Markdown-image switching/flush, active-leaf save behavior, and close/migration rejection |
| 2026-09-11 | Closed the naming-only persistence lifecycle checkpoint | Retained the implemented semantic names and compatibility boundary without further source changes | User confirmed all recommended focused manual tests completed successfully |
| 2026-09-11 | Completed the naming-only persistence lifecycle checkpoint | Replaced ambiguous private save/synchronization names with the semantic vocabulary from the validated lifecycle review, without moving storage or changing behavior. `ViewSemaphores.preventReload` deliberately remains until content-aware expected-write suppression replaces it; the public `preventAutozoom()` name remains as a compatibility delegate. Updated the lifecycle design document to match the implemented names. No manager, timer, revision rule, persistence branch, export policy, or release-note entry was added | Node 22.22.2 production and library builds pass with the established 33 circular-dependency warnings; `node --check dist/main.js`, unused-symbol lint, repository searches for every retired private name, and `git diff --check` pass. Focused ESLint is clean for `FileManager.ts` and `ViewSaveCoordinator.ts`; `ExcalidrawView.ts` retains exactly its established 18 errors, and full source lint retains exactly the established 120-error/0-warning backlog. The production bundle is 4,899,704 bytes, 343,176 bytes below 5 MiB. Focused manual validation remains: positional save-policy routing, own-write echo suppression, external synchronization/viewport retention, and main↔popout dirty migration |
| 2026-09-06 | Extended Markdown-image cache validation and conversion metadata retention | Reused the existing nested dependency traversal with non-Excalidraw vault files enabled, removed the stale runtime-mtime gate from direct focus validation, added a selected-or-all scene image refresh command whose forced load bypasses and replaces persistent cache entries, and retained Markdown-image custom data on the intermediate embeddable so reverse conversion restores its appearance. No dependency index or targeted IndexedDB deletion layer was added | Node 22.22.2 production and library builds and bundle syntax pass with the established 33 circular warnings. Focused ESLint, unused-symbol lint, and `git diff --check` pass; full source lint retains its existing 120-error backlog with no finding in touched files. Manual validation should change an external Markdown source while its drawing is inactive, test the same dependency through an embedded drawing after a cold reopen, invoke the refresh command with exactly one image and with zero/multiple selected, and round-trip a styled local and external Markdown image through an embeddable. Main-window coverage is required; repeat dependency refresh in a popout and run one mobile smoke test because cache storage and focus timing differ |
| 2026-09-06 | Added view-local render-input caching for Markdown images | `ViewSceneFileManager` now retains the exact Markdown and one configuration signature containing the source path, resolved appearance, and Markdown-image custom data used for each displayed image. `EmbeddedFilesLoader` skips SVG regeneration only when those inputs still match and the current Excalidraw API still holds the rendered file; content, style/default, width, source, or metadata changes regenerate normally, as do explicit forced refreshes and cache misses after an API scene reset. Successful insert, duplicate, edit, and embeddable-conversion renders seed the same cache, and obsolete entries are pruned against current scene membership. No persistent image cache or file-mtime heuristic was introduced | Node 22.22.2 production build and bundle syntax pass with the established 33 circular warnings. Focused lint and unused-symbol scan pass outside the existing `ExcalidrawView.ts` backlog; final diff checks pass. Manual validation pending: open a drawing with several local and external Markdown images, trigger repeated full scene reloads and convert an embeddable, and confirm only the new/changed image refreshes without flicker. Then change Markdown text, width, each appearance setting, plugin defaults used by a legacy/partial element, and an external source, confirming each affected image updates once. Exercise explicit refresh, a same-tab file switch, main window, popout, and one mobile reload smoke test |
| 2026-09-06 | Made Markdown-image/embeddable conversion transactional after live race diagnostics | The prior conversion compared unrelated whole-file snapshots and then removed a fragment with exact string replacement. Live traces exposed three independent hazards: duplicate conversion requests, Canvas-node edits not yet persisted, and a missing visible heading boundary causing Obsidian to transclude the commented Excalidraw payload recursively. Conversion now runs one-at-a-time, validates the live fragment against a unique persisted range, waits for the Canvas node's automatic Vault write when necessary, rejects managed or over-captured content, unwraps the marker block before reinserting a local section, and preserves exactly one structural `#` only when the final Markdown-image scaffold disappears. The false warning for a valid single level-one heading is gone. The sidepanel now observes Markdown-image identity across same-ID element retyping. After validation, all temporary logging was removed and the production helpers were reduced to one range resolver, one boolean safety predicate, and one shared conversion guard; no generic parser, temporary `ExcalidrawData`, Canvas save override, or additional persistence layer remains | User validated ordinary round trips, multiple images, recovery after correcting an already-malformed boundary, and immediate edit-then-convert behavior. Focused lint, production build, bundle syntax, unused-symbol scan, debug-prefix search, and diff checks pass |
| 2026-09-05 | Hardened local Markdown-image copy/paste and deletion behavior from live diagnostics | The copy payload contained all three Markdown bodies, but `syncFiles()` short-circuited on stale ordinary-file entries and skipped Markdown restoration. Reloading the incomplete destination then deleted the shared Markdown source, poisoning later pastes. Local element metadata is now authoritative, paste hydrates the destination registry before save, and a malformed/incomplete drawing cannot delete another view's shared source. Deletion checks no longer call the restoring lookup, eliminating the repeated-confirmation loop. Follow-up testing exposed selection flicker: a clean editor switch still forced save/reload, while Markdown-image classification first restored a stale ordinary file. Clean switches now only detach; real content/appearance changes retain the guarded persistence path. Added an optional confirmation toggle backed by a validated `ask`/`keep`/`delete` setting, with the exact setting name shown in the dialog, and documented the changes in 2.27.3 release notes. Audit against `4e7f4699` confirms its parse-before-mutation safety boundary remains intact: incoming Drawing JSON is still fully parsed and validated before `loaded`, registries, file identity, or scene are changed; the Markdown master change occurs only after successful parse and removes a cross-drawing side effect. Removed all temporary text diagnostics | Node 22.22.2 production and library builds and `node --check dist/main.js` pass with the established circular warnings; focused ESLint, unused-symbol lint, and `git diff --check` pass. The temporary debug prefix is absent from `src/` and rebuilt `dist/main.js`. Full source lint retains its existing 120-error backlog with no finding in newly changed lines; TypeScript retains only its existing generated-doc, library-output, and dependency declaration failures. The base copy/paste case is manually validated. Follow-up validation pending: switch repeatedly among unchanged local/external Markdown images with the editor open and confirm no whole-scene flicker or disk save; edit Markdown and appearance immediately before switching and confirm render/save still completes; test keyboard and element-panel deletion for keep/delete, remembered batch/future behavior, settings reset, undo/redo, main/popout, and one mobile prompt/settings smoke test |
| 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` |
@@ -1027,7 +1100,7 @@ Suggested clusters:
| Coordinator | Initial fields/behavior |
| --- | --- |
| `ViewPersistenceCoordinator` | `saving`, `autosaving`, `forceSaving`, `dirty`, save wait behavior |
| `ViewReloadGuard` | `preventReload`, `embeddableIsEditingSelf`, their reset timers |
| `ViewReloadGuard` | expected-own-write matching, `embeddableIsEditingSelf`, their cleanup/grace timers |
| `ViewLoadState` | `justLoaded`, `preventAutozoom`, initial `onChange` suppression |
| `ViewLifecycleState` | `viewloaded`, `viewunload`, `popoutUnload`, `scriptsReady` |
| `ViewInteractionThrottle` | `hoverSleep`, `wheelTimeout`, `isEditingText`, imported-image guard |
@@ -1332,6 +1405,14 @@ to resume.
Started 2026-08-13 and promoted to the active refactor on 2026-08-21. This
effort is independent of the parked `ExcalidrawView`/`main.ts` plan above.
### Issue #2935 follow-up action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-09-15 | Prevent repeat page navigation from consuming rich descriptions | The definition tree now supplies fresh clones of rich descriptions at each read, while the shared custom-row adapter clones fragments before handing them to `Setting#setName`/`setDesc`. The original fragments remain available for later navigation and Markdown export; the native declarative and legacy control paths remain intact | Focused lint and production build pass with established Rollup circular warnings. Manual gate: search for “Scripts,” select **Excalidraw Automate script folder**, select another result, then select the folder again; verify all folder descriptions and the embedding toggle description remain visible. Repeat with a different settings page, confirm formatted links still work, export settings to Markdown after navigation, and switch to the legacy layout after restart. Main-window desktop is the highest-risk environment; a popout settings window and one mobile settings-page return need separate smoke checks if available. |
| 2026-09-15 | Closed the repeat-navigation description checkpoint | The maintainer confirmed the reported search navigation no longer removes descriptions; commit `f5503b95` was pushed and issue #2935 was closed | Runtime reproduction passed in the maintainer's Obsidian installation. |
| 2026-09-15 | Corrected incoherent path warnings (#2934) | The drawing-folder specification explicitly permits empty vault-root selection. Template validation now checks the same folder, file, and metadata-cache linkpath cases as `getListOfTemplateFiles()`, and its completion includes folders as well as `.md`/`.excalidraw` files. No locale text or release note changed | Focused lint and production build pass with established Rollup circular warnings. Manual gate: clear **Excalidraw folder** and confirm no warning; select an existing template folder, a full-path template file, and an extensionless `.md` template link and confirm no warning for each. Enter missing paths and confirm the warning remains, then repeat one valid and one missing case in the legacy layout after restart. Main-window desktop carries the primary risk; popout and mobile need one path-input smoke check if available. |
### Objective and fixed compatibility decisions
Migrate `ExcalidrawSettingTab` to Obsidian's declarative settings API while
@@ -2176,3 +2257,178 @@ action reusing the same rendering component (matching how
| 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. |
---
# Updated File persistance refactor plan 2026-09-12 (Astra)
Implementation companion: [File Persistence Refactor Implementation Handoff](<docs/File Persistence Refactor Implementation Handoff.md>). The summary below is retained as the maintainer's architectural record; the companion is the canonical detailed task ledger. Its 5b.0–5b.5 numbering maps directly to the six steps below, with minimum snapshot ownership brought forward from original step 9.
Checkpoint 5b expanded beyond echo suppression, and I presented plausible explanations as established causes. The continuing failure disproves those completion claims. **The ping-pong root cause is still unproven.**
### What the audit establishes
| Earlier assumption | What the code actually supports |
| --- | --- |
| A matching hash identifies our modify event. | It identifies the content read **after** notification. Another write may already have happened. The stored revision cannot establish event origin. |
| Parsed incoming elements faithfully preserve disk versions. | [The parser](/Users/zsviczian/GitHub/obsidian-excalidraw-plugin/src/shared/ExcalidrawData.ts:976) unconditionally increments versions/nonces when applying non-text links—even unchanged links. This also exists in the committed baseline. |
| Order-only differences can safely be ignored. | Order represents layering. Index normalization can also mutate element versions after the synchronization baseline was calculated. |
| `CaptureUpdateAction.NEVER` prevents incoming synchronization from becoming dirty. | It affects history capture, but several independent dirty paths remain. Its complete effect requires tracing actual callbacks. |
| Save snapshots and revisions already provide precise ownership. | Snapshots retain mutable references; revisions are local to each view, not comparable between views. |
| One pending synchronization guarantees eventual convergence. | It bounds pending state within a view. It does not coordinate competing writers or preserve disk content overwritten before either receiver reads it. |
These are concrete weaknesses in the attempted strategy—not a claim that any single one explains your reproduction.
### Revised improvement plan
**1–2. Retain naming and semantic boundaries.**
No further mechanical cleanup now. There is no evidence supporting the previous “old plugin runtime” explanation.
**3–4. Retain separate save/sync ownership and pending synchronization, but revalidate their guarantees.**
The architecture remains useful. What needs proof is that accepting persisted content does not manufacture another edit, genuine local changes remain persistable, and finite edits produce finite synchronization/save work.
**5. Replace the current 5b attempt with gated sub-checkpoints.**
1. **Establish the comparison baseline.** Preserve the failed patch, then test `3899d056`: committed 5a plus the validated image fix. Use `af1cbe74` if an exact 5a comparison is needed. Use the same settings, dependency artifact, and fresh copy of the drawing, restarting Obsidian between builds.
First test: edit view 1, switch to view 2, stop interacting. Both views must settle without another edit or forced save. If the baseline fails, investigate that before reintroducing content matching.
2. **Trace the first incorrect transition.** Add a separate temporary diagnostic change recording anonymous view/operation identities, dirty-call origin, revisions, pending synchronization, write completion, and fingerprints at read/parse/merge/publication/save boundaries. Include delayed image callbacks and the `TextFileView` bridge. No note contents or image payloads.
The objective is one causal chain explaining the **first unexpected dirty transition**, not logs of an already-running loop.
3. **Create a focused reproduction and establish convergence.** Exercise actual parser/merge/coordinator code where practical. Cover unchanged links, text normalization, layer indices, tombstones, images, repeated notifications, and controlled competing writes.
Acceptance: reapplying a settled document creates no new writes, while genuine unpersisted changes remain eligible for saving. Correct only behavior demonstrated faulty; do not redesign merge semantics incidentally.
4. **Bring forward the minimum snapshot ownership from step 9.** Define precisely which captured state and revision a completed save acknowledges. Own mutable inputs across normalization/compression, associate them with exact prepared text, and distinguish successful persistence from a requested save.
Test edits and nested-object mutations during asynchronous preparation. An older save must never acknowledge newer edits.
5. **Observe content classification before enabling it.** Compare proposed classifications against actual write/accepted-state history without changing the validated 5a suppression behavior. Test failed/no-op writes, delayed and duplicate notifications, competing writers, navigation, and replaced records.
6. **Enable matching inside the coalesced latest-read path.** Avoid independent asynchronous read/hash operations ahead of synchronization ownership. Treat notification origin as unknown; skip work only when observed content is already represented by a known successful write or accepted baseline. Preserve newer local edits and notifications arriving during processing.
Remove the Boolean only after its same-file-editor and force-save callers have separately validated equivalents.
**Checkpoint 5 acceptance:** first-edit convergence without further input; sustained competing-edit convergence; no idle dirty/save loop; independent cameras; correct layers/deletions; Markdown and scene integrity after reopening; force-save available when idle.
**6. Introduce detached persistence only after convergence is established.**
Keep the data-only, main-realm queue and normal `super.save()` bridge. Define handed-off, persisted, superseded, and failed outcomes.
Revise “latest trailing payload”: independent view snapshots cannot safely supersede each other merely by arrival time or larger local revision. Define ordering against live writes too.
Tests: delayed unload versus newer live save, two closing views, immediate reopen, failed writes, and last-popout teardown. Preserve early unmount and replacement-owned migration persistence.
**7. Add BAK handling after successful detached writes.**
Back up the exact successful payload with its captured empty-scene safeguard. Failed or merely accepted handoffs must not advance BAK.
Tests: write failure, empty scenes, coalescing, and interleaved live/detached writes. An in-memory queue must not be described as crash-safe.
**8. Replace the same-file Boolean with an ownership gate.**
Inventory existing flush/release behavior first. Support overlapping owners and grace after the final owner releases; resume pending synchronization without losing current Markdown.
Tests: overlapping editors, rapid switching, final trailing Markdown write, close, and physical-mobile editing. Move this step forward only if it is a demonstrated prerequisite for removing suppression callers.
**9. Complete the snapshot model.**
Extend the minimum ownership work into normalized export-ready state. Explicitly document owned copies, shared immutable payloads, deletions, Markdown envelope, and runtime identity.
Tests: raw/parsed text, equations, images, app-state-only edits, migration, and large-scene memory cost.
**10. Fix autoexport fidelity, then ordering.**
First export the prepared scene corresponding to the successful source write. Then serialize exports using defined source-persistence order—not incomparable view revisions.
Tests: edits during export, slow older exports, two source views, themes, and failed source saves.
**11. Add asynchronous load generations.**
Preserve the separate `textFileViewLoadedFile` bridge. Guard continuations by generation and runtime/file identity.
Tests: A→B→A navigation, close during initialization, and main↔popout migration. Bring a narrow generation fix forward only if the trace implicates stale continuations.
**12. Clean up remaining semaphores and timers last.**
Remove state only once its replacement owner is proven. Keep unrelated dependency-refresh and Canvas cleanup outside this effort.
The recommendation above was the 2026-09-12 handoff boundary. It has been completed through checkpoint 12b; use the status and action log below for the final state rather than resuming that historical next action.
## Detailed implementation handoff and completion record
Read [File Persistence Refactor Implementation Handoff](<docs/File Persistence Refactor Implementation Handoff.md>) before changing this subsystem again. It expands this plan without requiring the preceding conversation:
- Section 2: baseline commits, exact path-scoped stash instructions, preserving these documents, dependency/artifact identity, fixture isolation, and first-edit acceptance tests.
- Sections 3–8: source map and verified hazards; first-transition instrumentation; convergence tests and interleavings; immutable capture/acknowledgement; observation-only classification; enabling classification inside the existing latest-read boundary.
- Sections 9–15: original checkpoints 6–12, including cross-view ordering, detached-write outcomes, BAK eligibility, editor ownership scope, normalized export inputs, source-write export order, stale-load invalidation, and remaining timers.
- Sections 1 and 16: the progress ledger, stop rules, and exact evidence the next agent must record before handing off each change.
Current status: checkpoints 5b–12b are accepted and committed. The final checkpoint commits are `31592829` (5b), `c033e8b6` (6), `d1bd628c` (7), `25d7e164` (8), `a634ce27` (9), `452107f6` (10), `1d1dd365` (11), `839f0547` (12a), and `b9481c32` (12b); the checkpoint-10 save-owned frontmatter correction is `1354930d`. The failed combined experiment remains preserved as stash object `2b158abb204fd9b7e76aeea0a80e12476ce9879e` and must not be reapplied as a group. Drawing-runtime migration handoff remains separate. The checkpoint-8 pre-save reconciliation experiment was rejected, preserved in `refs/stash` as object `8e69125349180b35fc4a534801bbbd79b430e688`, and removed. The initial view-owned checkpoint-10a draft was rejected after review demonstrated missing close/migration output, retired-view completion, mutable asset descriptors, unordered writes, and duplicate preparation.
Checkpoint 12 is complete. Checkpoint 12a mechanically moved the save coordinator's four remaining storage fields out of `ViewSemaphores`; checkpoint 12b moved own-write reload suppression and its cleanup timer into one view-owned guard while preserving the public compatibility delegates and accepted Markdown/raw modify routing. All other lifecycle, initial-load, and interaction state remains intentionally unchanged; it is not persistence state and should move only under a separately evidenced refactor with its own risk gates.
Before continuing to 12b, a separate checkpoint-10 corrective increment resolves automatic-export frontmatter from the exact save-owned Markdown envelope instead of the asynchronously updated Obsidian metadata cache. It passed the focused large-scene runtime gate and is committed as `1354930d`.
### Checkpoint 8 diagnostic action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-09-13 | Rejected and removed the owner-specific pre-save reconciliation experiment after it made the Markdown-image/shape failure occur earlier | Preserved the complete tracked experimental state in `refs/stash` as object `8e69125349180b35fc4a534801bbbd79b430e688` (initially `stash@{0}`). Removed owner-specific synchronization bypass, active Markdown-image preservation, accepted raw-text mutation, and the added pre-save reconciliation calls. Retained the independently confirmed migration-envelope correction and core same-file ownership gate | Source search confirms no remaining `isBlockedExcept`, `reconcilePendingExternal`, `flushPendingExternalSynchronizationForSameFileSave`, `applyLatestExternalSynchronization`, or `preservedMarkdownImageFileIds` symbol. No claim is made about the remaining failure's cause |
| 2026-09-13 | Added narrow checkpoint-8 route/merge diagnostics for the simpler deletion | One complete string per event under `EXCALIDRAW_PERSISTENCE_8` records same-file gate transitions, dirty/save revisions, receiver routing, reload decisions, synchronization classification, and local/incoming/merged element counts. The first runtime gate is only: edit Markdown image in A, click B, add one shape, stop when the Markdown update removes it, then copy all filtered strings | Gate check, unused-symbol lint, production build, bundle syntax, and `git diff --check` pass; focused lint retains only the established 18+1 findings. Diagnostics must be removed before commit |
| 2026-09-13 | Interpreted the first checkpoint-8 deletion trace and expanded publication tracing | View B became dirty and held 4,422 elements, selected incremental synchronization, and acquired it with 4,422 elements. No full reload, Vault read completion, merge, or merge publication occurred before the trace ended, while view A completed a 4,421-element write. This rules out the two initially instrumented transitions but does not yet locate deletion. Added string-only tracing at `setViewData()`, `loadDrawing()`, and every wrapper element publication; the next capture must continue at least five seconds after deletion | No behavior change. Production build, bundle syntax, focused diagnostic lint, unused-symbol lint, and `git diff --check` pass with 33 established Rollup warnings. Expanded instrumented bundle: 4,922,920 bytes, SHA-256 `45963ee049b0d092939cc79861f18eb10f3ca16e82f22c2be5d8f4552f31fdae` |
| 2026-09-13 | Located and corrected the Markdown-image handoff deletion from the expanded trace | View B retained its shape through incremental merge, then an editor-owned `reload(false, file)` cleared `textFileViewLoadedFile`. The next base `setViewData()` misclassified the same file as a new load and published 4,420 disk elements over 4,421 live elements. A successful non-full current-file reload now retains the marker, so that duplicate delivery uses the established same-file early return. Full reload, initial/different-file load, settings, compatibility, routing, and merge behavior remain unchanged | `check-text-file-view-reload-policy.mjs`, same-file gate, modify routing, content classification, unused-symbol lint, production build, bundle syntax, and `git diff --check` pass with 33 established Rollup warnings. Corrected instrumented bundle: 4,923,085 bytes, SHA-256 `baadb3c0cec6b52533124737cd3a630915c99d10b4f9d8d196ee6eaaba81eb4a`. Runtime gate: rerun simple handoff/add-shape, then reopen-and-Render-now; both views and reopen must contain both changes without full `setViewData()` replacement |
| 2026-09-13 | Accepted both targeted marker-correction scenarios and removed checkpoint-8 diagnostics | Maintainer reports the simple handoff/add-shape and extended reopen-editor/**Render now** scenarios both complete without issue. Traces show same-file deliveries taking the existing early return, the local shape retained through merge, and the union later reaching the other view. Removed the diagnostic helper and all source calls; retained only production behavior and executable checks | Reload-policy, same-file gate, snapshot, content-classification, modify-routing, detached-persistence, backup-queue, unused-symbol, focused lint, production build, bundle syntax, `git diff --check`, and source/bundle prefix search pass. Clean bundle: 4,915,827 bytes, SHA-256 `555d6a2aeae81d8dbc6644342ecdde95126c311d8fcc16df1038588e11eaddcd`. Broader checkpoint-8 runtime gate remains before commit |
| 2026-09-13 | Added narrow migration-persistence handoff diagnostics after one checkpoint-8 stress warning | Overall same-file editing validation preserved every change, but an immediate Markdown-image edit followed by tab migration produced `Migration persistence handoff expired before replacement` after 15 seconds and a serious-save warning in the other view. This proves a serialized persistence reservation was registered but not consumed; it does not yet distinguish a missing replacement load, a non-main destination excluded by the current consumption guard, or a leaf/target mismatch. Added complete-string tracing only at migration callback, source registration, replacement `setViewData()`, and queue register/consume/expiry boundaries. No timeout, ownership, write, or routing behavior changed | Reload-policy, same-file gate, and persistence-queue checks; focused diagnostic/queue lint; unused-symbol lint; production build; bundle syntax; and `git diff --check` pass. The build retains 33 established circular warnings. Instrumented bundle: 4,919,089 bytes, SHA-256 `d1369924a12c095a9f31cab930347a01e673e13c8c5b81c363980a4136002ce7`. Reproduce the immediate edit-and-migrate case, wait beyond 15 seconds if the warning appears, and copy every `EXCALIDRAW_MIGRATION_HANDOFF` string from before migration through expiry. Diagnostics must be removed before commit |
| 2026-09-13 | Corrected the trace-proven late Markdown-image save during migration | The replacement main-window view entered `setViewData()` and checked an empty queue at 340,808 ms. The retired popout's owner-invalidation force-save registered its handoff 1,444 ms later, after replacement initialization had passed the only consumption point; it then expired normally. Migration now synchronously starts or joins the owning Markdown-image invalidation before snapshot capture, records that ownership in the snapshot decision, unmounts the source root before awaiting, and waits for invalidation before closing/recreating the leaf. Owner invalidation no longer reloads a closing/migrating source view. This establishes register-before-replacement without changing TTL or adding a second write/consumer heuristic | Reload-policy, same-file-gate, and persistence-queue checks pass; changed manager/editor diagnostics lint clean; unused-symbol lint, production build, bundle syntax, and `git diff --check` pass. `ExcalidrawView.ts` retains its established 18 unrelated lint findings and `MarkdownImageEditor.ts` is clean. Instrumented corrected bundle: 4,919,403 bytes, SHA-256 `5e7f731476669c4853b84def675fdd748af17a605684581977cbc80820d0ea57`. Runtime gate: repeat rapid Markdown-image edit plus popout→main migration until the formerly rare branch occurs; the same leaf's `persistence-register` must precede replacement `persistence-consume-match`, with no expiry or serious-save warning |
| 2026-09-13 | Accepted the corrected migration boundary and removed temporary handoff diagnostics | Maintainer stress-tested repeated Markdown-image edits and main↔popout migration and could not reproduce the failure or lose changes. The trace exercises the formerly failing popout→main branch repeatedly: each source registration precedes replacement creation and is consumed by the matching leaf. One intentionally slow replacement consumed after about 11.3 seconds with 2,954 ms remaining, demonstrating that the correction fixes ordering rather than merely relying on the common fast path. No handoff expired | Removed `EXCALIDRAW_MIGRATION_HANDOFF` helper/imports/calls and rebuilt. Reload-policy, same-file-gate, persistence-queue, save-snapshot, content-classification, file-modify-routing, and backup-queue checks pass. Focused lint is clean for queue/editor; unused-symbol lint, production build, bundle syntax, `git diff --check`, and source/bundle diagnostic-prefix search pass with 33 established Rollup warnings. Clean checkpoint-8 candidate: 4,916,026 bytes, SHA-256 `e2851c6b6cddd219d7ff86bb931b38710426350c795cac8daea6acfd6eac3e74`. Await explicit commit direction |
### Checkpoint 9 action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-09-13 | Committed maintainer-accepted checkpoint 8 | Same-file multi-owner ownership, migration-envelope ordering, and loaded-file marker retention now form the accepted baseline for normalized snapshot work | Commit `25d7e164` (`refactor: coordinate same-file editing lifecycle`) |
| 2026-09-13 | Implemented the complete normalized save/export snapshot contract | `PreparedSave` now owns a detached post-normalization scene, binary files captured before normalization clears them, deleted elements, selected IDs, source file creation time, and captured export settings. The coordinator/classifier retain only a lightweight exact-content identity after completion, avoiding indefinite retention of the second large scene. External Markdown/PDF dependencies remain reference-resolved rather than byte-frozen. Automatic exports do not consume this snapshot until checkpoint 10 | Snapshot detachment/normalization checks, content classification, reload policy, same-file gate, persistence queue, modify routing, backup queue, focused lint, unused-symbol lint, production build, bundle syntax, and `git diff --check` pass with 33 established circular warnings. Candidate bundle: 4,917,634 bytes, SHA-256 `d69ccc4e2b9d5350f75c3b005f6c4c661d2b6aca006f78a2738e48a88d31e9cb`. Runtime gate: repeated large-scene save memory, concurrent newer edit, parsed/raw reopen, dirty close/migration, and side-by-side convergence |
| 2026-09-13 | Accepted checkpoint 9 normalized snapshot contract | All requested tests passed, including aggressive side-by-side editing, migration/popout workflows, parsed/raw persistence, and repeated saves of the 4,400-element fixture. Memory returned to its original value after explicit GC | Checkpoint 9 is ready to commit |
### Checkpoint 10 action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-09-13 | Committed maintainer-accepted checkpoint 9 | The detached normalized save/export snapshot and lightweight retained identity form the accepted baseline for autoexport fidelity | Commit `a634ce27` (`refactor: capture normalized save snapshots`) |
| 2026-09-13 | Implemented the initial checkpoint 10a prepared-save autoexport draft | The draft proved prepared-scene rendering but remained view-owned, skipped dirty-close/migration output, shared mutable embedded-file descriptors, repeated alternate-theme preparation, and did not order final writes | Rejected as a commit candidate after maintainer runtime findings and Astra review; superseded by the 2026-09-14 implementation below |
| 2026-09-14 | Implemented the revised complete checkpoint 10 candidate | `PreparedSave` conditionally freezes mutable asset descriptors and render defaults only when SVG/PNG or a trigger hook may require them; raw-only/no-output saves avoid that copy. View-dependent hooks are materialized before retirement. Successful live, detached-close, and migration writes publish data-only render intent to a plugin/main-realm coordinator. One active plus newest trailing request per source, global hook-resolved destination sequence, per-destination final-write lock, source path/creation revalidation, and lightweight no-output barriers prevent stale completion. Theme assets are prepared once per theme and reused by SVG/PNG; manual exports remain live-view operations. Blob/folder/file create-race recovery hardens final Vault writes, and plugin unload invalidates old-runtime output | Detailed invariants, external-dependency limits, hook timing/extension compatibility, and nine risk-based runtime gates are persisted in the handoff's checkpoint-10 section. Automated snapshot, ordering/failure/unload, persistence-callback, classification, reload, edit-gate, routing, backup, focused/unused lint, production build, bundle syntax, diagnostic-prefix search, and `git diff --check` pass with 33 established Rollup circular warnings and no TypeScript warning. Candidate bundle: 4,928,714 bytes, SHA-256 `b8d0959083373fa1a0e86952c074edda283f25e5ed217b7d8967a905f6c787b6`. Runtime fidelity, close/migration, collision, hook, mobile, responsiveness, and memory gates remain pending; do not commit or start checkpoint 11 before maintainer acceptance |
| 2026-09-14 | Incorporated initial checkpoint-10 runtime findings | Close and migration output now represent the persisted scene and repeated large-scene tests returned to baseline after GC. Automatic theme changes were stale because capture consulted a cached `ExportDialog`; automatic capture now reads current settings/frontmatter directly while manual export retains dialog behavior. Migration writes now publish an immediate no-render barrier and hold heavy output until the matching replacement view completes `setViewData()`, with failure/path mismatch discard and bounded abandoned-record cleanup. Automatic renders are globally serialized and yield a browser task between formats; individual Excalidraw renders remain non-preemptible UI-thread work | Focused manager lint, unused-symbol lint, all persistence/snapshot/routing/backup/autoexport checks, production build, bundle syntax, and `git diff --check` pass. `ExcalidrawView.ts` retains 17 established unrelated lint findings outside changed ranges; Rollup retains 33 established circular warnings. Candidate bundle: 4,930,611 bytes, SHA-256 `5f6345299d04205e5bdbe75db1c9d3d578117885a968a22bf6465a71eb3a0426`. The handoff records the three focused live-setting, migration-order, responsiveness/concurrency, and memory gates; checkpoint 10 remains uncommitted pending maintainer acceptance |
| 2026-09-14 | Replaced per-save rendering with an explicit same-source save-batch gate after rapid-save testing | The prior queue did not export every save, but it immediately rendered the first accepted snapshot and retained one newest trailing snapshot. This could waste a full large-scene render during an ongoing burst. More importantly, the last autosave deliberately submitted a no-output barrier, so final drawing persistence could invalidate the earlier render without creating matching final output. View save-loop lifetimes and detached/migration physical writes now register plugin-owned source activity. Persisted snapshots invalidate stale work immediately but retain only the newest render request until every activity ends plus a 500 ms quiet settle. Autosave supplies its final prepared snapshot. The existing global render lock, between-format task yields, and final-write guards remain | Added deterministic batch-gate coverage for simultaneous activities, N/N+1/N+2 replacement, quiet-timer restart, newest-only release, and no-output cancellation; persistence checks now cover complete detached/migration activity lifetimes. Focused lint, unused-symbol lint, all established checks, production build, bundle syntax, and `git diff --check` pass with 33 established Rollup warnings. Candidate bundle: 4,932,865 bytes, SHA-256 `a074d3522e830bac296b46d25ccfede2cde5ffe2926bc4db19f857a1e5ba1a89`. Runtime acceptance requires the reported two-view rapid-save reproduction, including a final autosave, before checkpoint 10 can commit |
| 2026-09-14 | Accepted checkpoint 10 after the final rapid-save batch test | The maintainer confirmed live setting changes, post-migration export start, rapid two-view large-scene coalescing, absence of the obsolete PNG-size failures, and final SVG/PNG fidelity to the settled persisted drawing | Checkpoint 10 is ready to commit; checkpoint 11 asynchronous load generation is the next permitted change |
### Checkpoint 11 action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-09-14 | Committed maintainer-accepted checkpoint 10 | Detached prepared-scene autoexports, successful-write ordering, migration deferral, live settings, global serialization, and save-batch newest-state coalescing form the accepted baseline | Commit `452107f6` (`refactor: coordinate prepared autoexports`) |
| 2026-09-14 | Implemented exact-target asynchronous `setViewData()` ownership | Added monotonic generation plus exact `TFile`/path/creation identity; replacement load, clear, unload, close, and migration invalidate stale continuations. Parsing/font/transclusion, migration persistence, recovery UI, library/React initialization, hooks, final loaded marker, dirty baseline, and migration-export completion revalidate ownership. Existing synchronization generation and scene-loader API/path guards remain separate | New generation check plus all established lifecycle/persistence checks, unused-symbol validation, production build, bundle syntax, and `git diff --check` pass. Changed ranges add no lint finding beyond the established 17 in `ExcalidrawView.ts` and 16 in `ExcalidrawData.ts`; Rollup retains 33 warnings. The post-recovery-fix candidate bundle is 4,934,416 bytes, SHA-256 `3f629a2d7390eb1d7bf0f7ae9bcfc52fac505cc8a4bec615311f5d631a7c637c`. The handoff records five risk-based runtime gates; checkpoint 11 remains uncommitted pending maintainer acceptance |
| 2026-09-14 | Corrected checkpoint-11 backup-recovery ownership | Runtime tests passed load replacement, mode switching, close, and migration, but a corrupted drawing no longer offered its existing BAK. The parse-error path had started recovery and immediately switched to Markdown; unload generation invalidation then canceled that same recovery. Backup lookup and confirmation now remain within the current load, with Markdown fallback only after no backup or a declined restore. Independent navigation still invalidates the prompt action | Re-test a current corrupted drawing with an available BAK, then navigate away while a second recovery prompt is open and confirm it cannot write or reopen the obsolete target. The large-scene PNG `couldn't export to blob` report remains a bounded secondary-output failure from the accepted checkpoint-10 path: drawing persistence succeeded and the user received an export failure notice |
| 2026-09-14 | Accepted checkpoint 11 with a documented stacked-migration limitation | The maintainer confirmed BAK recovery, rapid replacement/mode switching, close during load, and ordinary migration. Restoring the 4,400-element drawing and stacking two migrations before either replacement finishes can reach the existing post-unmount dirty safety stop, leaving a blank tab until reopen; the restored file remains valid and no data is lost | Treat as a non-blocking reentrant-migration UX limitation. Do not weaken early source-root unmount, dirty-write refusal, or exact load invalidation with another timer. If prioritized later, diagnose it as serialized per-leaf migration ownership with a causal trace rather than as part of BAK recovery |
| 2026-09-14 | Committed maintainer-accepted checkpoint 11 | Exact-target asynchronous load ownership, guarded parsing/rendering/recovery continuations, and corrected BAK fallback ordering form the checkpoint-12 baseline | Commit `1d1dd365` (`refactor: invalidate stale view loads`) |
### Checkpoint 12 action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-09-14 | Inventoried remaining semaphore and timer ownership | Classified each remaining semaphore and every retained/manager-owned timer by acquisition, release, callback target, durability relevance, and intended disposition. Anonymous one-shot UI callbacks remain grouped with their owning feature rather than being folded into a generic timer abstraction | Inventory is recorded in the implementation handoff. It preserves accepted plugin/main-realm durability queues, scene-loader API/path guards, load generation, early migration unmount, and interaction-specific timers |
| 2026-09-14 | Implemented and accepted checkpoint 12a persistence-state extraction | Moved save-in-progress, autosave-in-progress, force-save-in-progress, and path-qualified dirty storage into `ViewSaveCoordinator`. The only view-level raw dirty check now uses the existing semantic `isDirty()` accessor. Removed these four fields from `ViewSemaphores`; no timer, condition, save policy, or lifecycle flag changed | New ownership check and all established lifecycle/persistence checks pass. Unused-symbol validation, focused coordinator/type lint, production build, bundle syntax, and `git diff --check` pass; the view retains its 17 established lint findings and Rollup its 33 warnings. Candidate bundle: 4,934,276 bytes, SHA-256 `f0d268ced6b49f2b8e32009d057a18d9c27cf06af29f4a15ce2e15d39dcc782d`. Maintainer runtime tests passed without issue |
| 2026-09-14 | Committed maintainer-accepted checkpoint 12a | Persistence execution/exclusion and dirty-path state now have one storage owner; the full remaining state/timer inventory defines later groups | Commit `839f0547` (`refactor: move save state into coordinator`) |
| 2026-09-14 | Confirmed stale-metadata explanation for intermittent large-scene PNG failure | Automatic snapshot capture obtains PNG scale from `metadataCache.getFileCache(file)` before the write. During rapid writes a temporarily missing/stale cache can ignore the saved `excalidraw-export-pngscale: 0.1` and fall back to the much larger global scale, matching the reported blob failure | Implement only as a separate checkpoint-10 follow-up: resolve automatic-export frontmatter from exact `PreparedSave.text`; keep manual export resolution unchanged. Add a deterministic stale/missing-cache test and repeat rapid large-scene output fidelity testing |
| 2026-09-14 | Implemented save-owned automatic-export frontmatter candidate | Automatic capture now uses plugin settings as defaults and overlays frontmatter parsed from the source envelope, then re-resolves from final `PreparedSave.text`. Detached output owns exact scale, theme, padding, transparency, embedded-scene, internal-link, mask, and SVG/PNG selection. Manual export/dialog behavior and hook ordering are unchanged | New deterministic check covers `0.1` versus fallback `1` without metadata, all supported overrides, both-theme precedence, legacy padding, invalid scale, and absent frontmatter. Focused lint, all established checks, unused-symbol validation, production build, bundle syntax, and `git diff --check` pass. Candidate bundle: 4,935,817 bytes, SHA-256 `25297e75bc6623baa9ed8dc2c414e6500bba567b289b063da46d1c388af8d406`. Runtime gate pending |
| 2026-09-14 | Accepted save-owned automatic-export frontmatter correction | The maintainer confirmed rapid large-scene output at frontmatter scale `0.1`, live frontmatter changes, manual export behavior, and automatic format/theme selection. The intermittent PNG blob failure no longer occurs | Accepted for a separate checkpoint-10 follow-up commit before any checkpoint-12 continuation |
| 2026-09-14 | Committed save-owned automatic-export frontmatter correction | Automatic output now derives its configuration from the exact persisted envelope while manual exports retain live dialog/metadata semantics | Commit `1354930d` (`fix: resolve autoexport settings from saved text`) |
| 2026-09-14 | Implemented checkpoint 12b own-write reload-guard extraction | Removed `preventReload` and its cleanup timer from the generic view semaphore/timer storage. A view-owned `OwnWriteReloadGuard` now owns one-shot write arming, bounded cleanup, consumption, reset, and destruction. Existing public delegates and the accepted Markdown content-classification, raw `.excalidraw`, same-file embeddable, force-save, load, close, and migration routes remain in place. Re-arm and consume now cancel the exact prior timer so an obsolete callback cannot clear a newer arm | New deterministic guard/source-ownership check and all established lifecycle/persistence checks pass. Focused lint and unused-symbol validation, production/library builds, bundle syntax, source search, and `git diff --check` pass; the view retains its 17 established findings and Rollup its 33 warnings. Candidate bundle: 4,936,295 bytes, SHA-256 `a3c40836eed143b6577668d3227c20d2bd550c489781f92fb50f661243e30f5e`. Maintainer runtime gate remains pending; no temporary instrumentation is included and no commit is permitted before acceptance |
| 2026-09-14 | Accepted checkpoint 12b own-write reload-guard extraction | The maintainer confirmed ordinary autosave/Ctrl+S, alternating multi-view editing, forced save, raw `.excalidraw` own-write suppression and external updates, back-of-note release synchronization, migration/close, and the remaining requested smoke tests all completed successfully | Checkpoint 12b is ready to commit. The branch-wide simplification and artifact audit follows as a separate review |
| 2026-09-14 | Committed checkpoint 12b own-write reload-guard extraction | Own-write suppression and its cleanup callback now have one tested view-owned state owner | Commit `b9481c32` (`refactor: own reload suppression state`) |
| 2026-09-14 | Completed the post-checkpoint file-persistence branch sanity review | Confirmed the new boundaries remain purpose-specific: save/revision/content identity, detached write ordering, automatic-output coalescing, same-file ownership, load generation, and raw compatibility suppression have distinct lifetimes and cannot be safely collapsed. Removed the uncalled `ViewSaveCoordinator.getLastSuccessfulPreparedSave()` and the test-only `ViewPersistenceQueue.flush()`, removed two extra end-of-file blank lines, corrected one obsolete checkpoint comment, and updated lifecycle documentation from superseded experimental descriptions to the accepted implementation. No temporary persistence instrumentation, tracked generated output, attachment, or diagnostic runtime log remains. Historical failed-5b rows and stashes remain as rejected evidence rather than executable guidance | All 12 focused persistence/lifecycle checks pass; unused-symbol validation and focused lint pass; production and library builds plus bundle syntax and cumulative `git diff --check` pass. Rollup retains the established 33 circular warnings. Final reproducible bundle: 4,936,617 bytes, SHA-256 `698e47581470b1e9a211c58bad05ed2000d56fd3097b4cb17be55856530fb73e`. `npm run madge` was attempted but its undeclared CLI is not installed in this checkout; this cleanup changes no imports, and the production graph result is unchanged |
@@ -6,7 +6,7 @@
/* ************************************** */
type MutableElementMapEntry = Mutable<ExcalidrawElement> & Record<string, unknown>;
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings } from "src/types/exportUtilTypes";
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
import { PaneTarget } from "src/types/utilTypes";
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
import { FloatingModal } from "./Dialogs/FloatingModal";
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
@@ -611,30 +611,28 @@ export declare class ExcalidrawAutomate {
pageProps?: PDFPageProperties;
filename: string;
}): Promise<void>;
private prepareViewImageExport;
/**
* 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 {readonly ExcalidrawElement[]} [options.elementsOverride] - Optional complete replacement for the view's exported elements. This array is not merged with the current scene or treated as a patch by ID: when supplied, only its non-deleted elements are exported. Include every element that should appear in the SVG.
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
* @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.
*/
createViewSVG({ withBackground, theme, frameRendering, padding, selectedOnly, skipInliningFonts, embedScene, elementsOverride, }: {
withBackground?: boolean;
theme?: "light" | "dark";
frameRendering?: FrameRenderingOptions;
padding?: number;
selectedOnly?: boolean;
skipInliningFonts?: boolean;
embedScene?: boolean;
elementsOverride?: readonly ExcalidrawElement[];
}): Promise<SVGSVGElement>;
createViewSVG(options?: ViewSVGExportOptions): Promise<SVGSVGElement>;
/**
* 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.
*/
createViewPNG(options?: ViewPNGExportOptions): Promise<Blob>;
/**
* Creates an SVG image from the ExcalidrawAutomate elements and the template provided.
* @param {string} [templatePath] - The template path to use for the SVG.
@@ -902,16 +900,19 @@ export declare class ExcalidrawAutomate {
* @param {string} tex - The LaTeX equation string.
* @param {number} [scaleX=1] - The x-scaling factor (post mathjax creation)
* @param {number} [scaleY=1] - The y-scaling factor (post mathjax creation)
* @param {MathJaxRenderOptions} [options] - MathJax rendering options. Set `throwOnError` to propagate invalid LaTeX errors.
* @returns {Promise<string>} Promise resolving to the ID of the added LaTeX image element.
*/
addLaTex(topX: number, topY: number, tex: string, scaleX?: number, scaleY?: number): Promise<string>;
addLaTex(topX: number, topY: number, tex: string, scaleX?: number, scaleY?: number, options?: MathJaxRenderOptions): Promise<string>;
/**
* Returns the base64 dataURL of the LaTeX equation rendered as an SVG.
* @param {string} tex - The LaTeX equation string.
* @param {number} [scale=4] - The scale factor for the image.
* @param {MathJaxRenderOptions} [options] - MathJax rendering options. Set `throwOnError` to propagate invalid LaTeX errors.
* @returns {Promise<{mimeType: MimeType; fileId: FileId; dataURL: DataURL; created: number; size: { height: number; width: number };}>} Promise resolving to the LaTeX image data.
*/
tex2dataURL(tex: string, scale?: number): Promise<{
tex2dataURL(tex: string, scale?: number, // Default scale value, adjust as needed
options?: MathJaxRenderOptions): Promise<{
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
@@ -1454,12 +1455,27 @@ export declare class ExcalidrawAutomate {
*/
getExportSettings(withBackground: boolean, withTheme: boolean, isMask?: boolean): ExportSettings;
/**
* 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): ExcalidrawElement[];
getElementsInArea(elements: readonly ExcalidrawElement[], area: SceneArea, options?: ElementsInAreaOptions): ExcalidrawElement[];
/**
* 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[];
/**
* Gets the bounding box of the specified elements.
* The bounding box is the box encapsulating all of the elements completely.
@@ -1992,6 +2008,58 @@ 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;
}
/* ************************************** */
/* lib/types/excalidrawElementTypes.d.ts */
@@ -2275,6 +2343,8 @@ export declare const MARKDOWN_IMAGE_CUSTOM_DATA_KEY = "markdownImage";
export declare const MARKDOWN_IMAGE_EMBEDDED_FILE_TOKEN = "markdown-image";
export declare const MARKDOWN_IMAGE_SCHEMA_VERSION = 1;
export type MarkdownImageSource = "local" | "external";
/** Persisted behavior for deleting a local Markdown image from the scene. */
export type MarkdownImageDeletionPreference = "ask" | "keep" | "delete";
export type MarkdownImageTransclusionRenderSettings = {
enabled: boolean;
fontFamily: string;
@@ -2311,6 +2381,15 @@ export type MarkdownImageSettings = {
defaults: MarkdownImageRenderSettings;
};
/* ********************************* */
/* lib/types/mathJaxTypes.d.ts */
/* ********************************* */
/** Options for rendering LaTeX through the Excalidraw Extras MathJax service. */
export interface MathJaxRenderOptions {
/** Propagate MathJax conversion errors instead of returning null. */
throwOnError?: boolean;
}
/* ************************************** */
/* lib/types/obsidianDeclarativeSettings.d.ts */
/* ************************************** */
@@ -2946,6 +3025,13 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
lineHeight: number & {
_brand: "unitlessLineHeight";
};
/**
* Position of text bound to a linear element (such as an arrow),
* expressed as a normalized arc-length parameter (0–1) along the
* container's whole path. Independent of how the path is segmented,
* so it survives midpoint insertion and other geometry changes.
* */
labelPosition?: number | null;
}>;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
@@ -3221,6 +3307,7 @@ declare class App extends React.Component<AppProps, AppState> {
wasAddedToSelection: boolean;
hasBeenDuplicated: boolean;
hasHitCommonBoundingBoxOfSelectedElements: boolean;
arrowLabel: boolean;
};
withCmdOrCtrl: boolean;
drag: {
@@ -3283,6 +3370,7 @@ declare class App extends React.Component<AppProps, AppState> {
wasAddedToSelection: boolean;
hasBeenDuplicated: boolean;
hasHitCommonBoundingBoxOfSelectedElements: boolean;
arrowLabel: boolean;
};
withCmdOrCtrl: boolean;
drag: {
@@ -3644,9 +3732,12 @@ declare class App extends React.Component<AppProps, AppState> {
}) & {
preferSelected?: boolean;
}): NonDeleted<ExcalidrawElement> | null;
private getElementsAtPosition;
getElementsAtPosition(x: number, y: number, opts?: {
includeBoundTextElement?: boolean;
includeLockedElements?: boolean;
}): NonDeleted<ExcalidrawElement>[];
getElementHitThreshold(element: ExcalidrawElement): number;
private hitElement;
hitElement(x: number, y: number, element: NonDeletedExcalidrawElement, considerBoundingBox?: boolean): boolean;
getTextBindableContainerAtPosition(x: number, y: number): (Readonly<{
id: string;
x: number;
@@ -3862,6 +3953,10 @@ declare class App extends React.Component<AppProps, AppState> {
private handleCanvasPointerMove;
private handleEraser;
private handleTouchMove;
/**
* Applies the hover affordances of a selected linear element: the cursor,
* plus the hovered-handle state that renders them highlighted.
*/
handleHoverSelectedLinearElement(linearElementEditor: LinearElementEditor, scenePointerX: number, scenePointerY: number): void;
private handleCanvasPointerDown;
private handleCanvasPointerUp;
@@ -5018,6 +5113,7 @@ export type AppClassProperties = {
dismissLinearEditor: App["dismissLinearEditor"];
flowchart: App["flowchart"];
drawShape: App["drawShape"];
arrowText: App["arrowText"];
cursor: App["cursor"];
bucketFill: App["bucketFill"];
isToolLocked: App["isToolLocked"];
@@ -5074,6 +5170,7 @@ export type PointerDownState = Readonly<{
wasAddedToSelection: boolean;
hasBeenDuplicated: boolean;
hasHitCommonBoundingBoxOfSelectedElements: boolean;
arrowLabel: boolean;
};
withCmdOrCtrl: boolean;
drag: {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -26,6 +26,7 @@ In addition to ExcalidrawAutomate, you can also use two other sources of functio
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
- **Never use native browser dialogs in scripts:** Do not use `window.confirm`, `window.alert`, `window.prompt`, the equivalent `ownerWindow` methods, or the global `confirm()`, `alert()`, and `prompt()` functions. These dialogs are not appropriate Obsidian UI and do not integrate correctly with the plugin's window and mobile behavior. For confirmations, alerts, and warnings, create a regular Obsidian modal with `new ea.obsidian.Modal(ea.plugin.app)` (not `FloatingModal`), render the message and buttons in `contentEl`, and resolve the result from the modal's button callbacks or `onClose` handler. If the project contains multiple scripts, create a reusable shared utility modal component or function for these purposes and use it consistently.
- 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.
@@ -102,7 +103,8 @@ To keep this training file concise, large external type definitions are not incl
ea.clear();
}
```
* **`elementsOverride` is a complete replacement:** In `createViewSVG()`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the SVG. When temporarily modifying an existing scene for export, the simplest safe workflow is to copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
* **`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()`.
@@ -112,6 +114,7 @@ To keep this training file concise, large external type definitions are not incl
* **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.
* **Confirmations, Alerts, and Warnings:** Never use native browser dialogs such as `window.confirm()`, `window.alert()`, `window.prompt()`, `ownerWindow.confirm()`, or their global equivalents. Use a regular Obsidian modal instead: `const modal = new ea.obsidian.Modal(ea.plugin.app)`. Render the message and explicit action buttons in `modal.contentEl`, then resolve the user's choice from the button callbacks or `onClose`. Do not use `FloatingModal` for these simple confirmation or alert/warning dialogs. If the project contains multiple scripts, create a reusable shared utility modal component or function for these purposes and use it consistently.
* **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`.
@@ -179,7 +182,7 @@ To keep this training file concise, large external type definitions are not incl
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. Its `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or a patch by ID. If supplied, include every existing or temporary element that should appear in the SVG. For temporary changes to existing elements, copy the complete desired export set into the EA workbench, modify it there, and pass `ea.getElements()`.
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**
@@ -9,40 +9,41 @@ 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), [VoronoiDiagramGenerator.mLine truncated
- **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), [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.md](scripts/VoronoiDiagramGenerator.md)
- **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)
- **addEventListener**: [Slideshow.md](scripts/Slideshow.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)
- **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), [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), [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)
- **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), [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), [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)
- **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), [Slideshow.md](scripts/Slideshow.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)
- **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), [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)
- **connectObjects**: [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Connect elements.md](scripts/Connect%20elements.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **convertStringToDataURL**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **copyViewElementsToEAforEditing**: [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), [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 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), [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), [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), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [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), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.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), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Uniform size.md](scripts/Uniform%20size.md)
- **create**: [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md)
- **createPDF**: [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Slideshow.md](scripts/Slideshow.md)
- **copyViewElementsToEAforEditing**: [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), [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 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), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.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), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [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), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.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), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Uniform size.md](scripts/Uniform%20size.md)
- **createPDF**: [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
- **createPNGBase64**: [ExcaliAI.md](scripts/ExcaliAI.md), [Image Occlusion.md](scripts/Image%20Occlusion.md)
- **createSidepanelTab**: [Capture Note.md](scripts/Capture%20Note.md), [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)
- **createSidepanelTab**: [Capture Note.md](scripts/Capture%20Note.md), [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), [Slideshow.md](scripts/Slideshow.md)
- **createSVG**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **createViewPNG**: [Slideshow.md](scripts/Slideshow.md)
- **createViewSVG**: [Capture Note.md](scripts/Capture%20Note.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Slideshow.md](scripts/Slideshow.md)
- **deleteViewElements**: [Boolean Operations.md](scripts/Boolean%20Operations.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **DEVICE**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Slideshow.md](scripts/Slideshow.md)
- **elementsDict**: [Capture Note.md](scripts/Capture%20Note.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.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), [Split Ellipse.md](scripts/Split%20Ellipse.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)
- **extractCodeBlocks**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **FloatingModal**: [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.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), [Text to Path.md](scripts/Text%20to%20Path.md)
- **FloatingModal**: [ExcaliAI.md](scripts/ExcaliAI.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), [Text to Path.md](scripts/Text%20to%20Path.md)
- **formatAIUsageLabel**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **generateAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **generateAIText**: [ExcaliAI.md](scripts/ExcaliAI.md)
@@ -50,20 +51,19 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **getAISettings**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **getAPI**: [Capture Note.md](scripts/Capture%20Note.md)
- **getAttachmentFilepath**: [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **getBoundingBox**: [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), [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), [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), [ExcaliMath.md](scripts/ExcaliMath.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Slideshow.md](scripts/Slideshow.md)
- **getBoundingBox**: [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), [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), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Slideshow.md](scripts/Slideshow.md)
- **getBoundTextElement**: [Capture Note.md](scripts/Capture%20Note.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getCM**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Text Aura.md](scripts/Text%20Aura.md)
- **getCM6**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **getColorMapForImageElement**: [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md)
- **getElement**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md)
- **getElements**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [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), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
- **getElements**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
- **getElementsInArea**: [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
- **getElementsIntersectionArea**: [Slideshow.md](scripts/Slideshow.md)
- **getElementsInTheSameGroupWithElement**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap format.md](scripts/Mindmap%20format.md)
- **getEmbeddedFilesLoader**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **getExcalidrawAPI**: [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), [Copy Selected Element Styles to Global.md](scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md), [Custom Zoom.md](scripts/Custom%20Zoom.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), [Invert colors.md](scripts/Invert%20colors.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md), [Uniform size.md](scripts/Uniform%20size.md), [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
- **getExcalidrawAPI**: [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), [Copy Selected Element Styles to Global.md](scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md), [Custom Zoom.md](scripts/Custom%20Zoom.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Invert colors.md](scripts/Invert%20colors.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md), [Uniform size.md](scripts/Uniform%20size.md), [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
- **getExportSettings**: [Icon Library.md](scripts/Icon%20Library.md)
- **getLargestElement**: [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Connect elements.md](scripts/Connect%20elements.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Set Dimensions.md](scripts/Set%20Dimensions.md)
- **getListOfTemplateFiles**: [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md)
- **getMathEditorExtensions**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **getMaximumGroups**: [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), [Connect elements.md](scripts/Connect%20elements.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), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md)
- **getOriginalImageSize**: [ExcaliMath.md](scripts/ExcaliMath.md)
@@ -71,19 +71,20 @@ 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), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.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), [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)
- **getSidepanelLeaf**: [Capture Note.md](scripts/Capture%20Note.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Slideshow.md](scripts/Slideshow.md)
- **getSVGColorInfoForImgElement**: [Shade Master.md](scripts/Shade%20Master.md)
- **getViewCenterPosition**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md)
- **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), [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)
- **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), [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), [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)
- **height**: [Slideshow.md](scripts/Slideshow.md)
- **imagesDict**: [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)
- **isExcalidrawFile**: [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), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Shade Master.md](scripts/Shade%20Master.md)
- **isExcalidrawFile**: [Capture Note.md](scripts/Capture%20Note.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Shade Master.md](scripts/Shade%20Master.md)
- **isExcalidrawMaskFile**: [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md)
- **isExcalidrawView**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **maskEditAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
@@ -93,42 +94,51 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **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)
- **openFileInNewOrAdjacentLeaf**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **parseText**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **plugin**: [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Rename Image.md](scripts/Rename%20Image.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **placeholder**: [Slideshow.md](scripts/Slideshow.md)
- **plugin**: [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Rename Image.md](scripts/Rename%20Image.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **refreshTextElementSize**: [Capture Note.md](scripts/Capture%20Note.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Scribble Helper.md](scripts/Scribble%20Helper.md)
- **registerElementActionProvider**: [Slideshow.md](scripts/Slideshow.md)
- **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), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **selectionEnd**: [Slideshow.md](scripts/Slideshow.md)
- **selectionStart**: [Slideshow.md](scripts/Slideshow.md)
- **setRangeText**: [Slideshow.md](scripts/Slideshow.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), [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)
- **setView**: [Capture Note.md](scripts/Capture%20Note.md), [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)
- **setView**: [Capture Note.md](scripts/Capture%20Note.md), [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), [Slideshow.md](scripts/Slideshow.md)
- **setViewModeEnabled**: [Slideshow.md](scripts/Slideshow.md)
- **showAIUsageModal**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **showColorPicker**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md)
- **sidepanelTab**: [Icon Library.md](scripts/Icon%20Library.md), [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), [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)
- **style**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **targetView**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Folder Note Core - Make Current Drawing a Folder.md](scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **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)
- **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), [Slideshow.md](scripts/Slideshow.md)
- **transformAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **updateViewSVGImageColorMap**: [Shade Master.md](scripts/Shade%20Master.md)
- **verifyMinimumPluginVersion**: [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), [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), [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), [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), [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), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.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 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), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **value**: [Slideshow.md](scripts/Slideshow.md)
- **verifyMinimumPluginVersion**: [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), [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), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.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), [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), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.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 Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **viewToggleFullScreen**: [Slideshow.md](scripts/Slideshow.md)
- **viewUpdateScene**: [Invert colors.md](scripts/Invert%20colors.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.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), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **viewZoomToElements**: [Capture Note.md](scripts/Capture%20Note.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
- **width**: [Slideshow.md](scripts/Slideshow.md)
## ExcalidrawAPI
- **features**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **getAppState**: [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Copy Selected Element Styles to Global.md](scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md), [Custom Zoom.md](scripts/Custom%20Zoom.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Invert colors.md](scripts/Invert%20colors.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **getSceneElements**: [Mindmap format.md](scripts/Mindmap%20format.md)
- **history**: [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md)
- **getSceneElements**: [Mindmap format.md](scripts/Mindmap%20format.md), [Slideshow.md](scripts/Slideshow.md)
- **setActiveTool**: [Slideshow.md](scripts/Slideshow.md)
- **setToast**: [Slideshow.md](scripts/Slideshow.md)
- **startLineEditor**: [Slideshow.md](scripts/Slideshow.md)
- **updateContainerSize**: [Capture Note.md](scripts/Capture%20Note.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
- **updateScene**: [Custom Zoom.md](scripts/Custom%20Zoom.md), [Palette loader.md](scripts/Palette%20loader.md), [Set Grid.md](scripts/Set%20Grid.md)
- **updateScene**: [Custom Zoom.md](scripts/Custom%20Zoom.md), [Palette loader.md](scripts/Palette%20loader.md), [Set Grid.md](scripts/Set%20Grid.md), [Slideshow.md](scripts/Slideshow.md)
- **zoomToFit**: [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
## ExcalidrawLib
@@ -1,332 +1,575 @@
/*
# Deconstruct Selected Elements Into New Drawing
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-deconstruct.jpg)
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
![](https://www.youtube.com/watch?v=HRtaaD34Zzg)
![](https://www.youtube.com/watch?v=mvMQcz401yo)
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)
};
}
// 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 */
modal.open();
```
File diff suppressed because it is too large. Load diff
@@ -6,7 +6,7 @@
/* ************************************** */
type MutableElementMapEntry = Mutable<ExcalidrawElement> & Record<string, unknown>;
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings } from "src/types/exportUtilTypes";
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
import { PaneTarget } from "src/types/utilTypes";
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
import { FloatingModal } from "./Dialogs/FloatingModal";
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
@@ -611,30 +611,28 @@ export declare class ExcalidrawAutomate {
pageProps?: PDFPageProperties;
filename: string;
}): Promise<void>;
private prepareViewImageExport;
/**
* 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 {readonly ExcalidrawElement[]} [options.elementsOverride] - Optional complete replacement for the view's exported elements. This array is not merged with the current scene or treated as a patch by ID: when supplied, only its non-deleted elements are exported. Include every element that should appear in the SVG.
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
* @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.
*/
createViewSVG({ withBackground, theme, frameRendering, padding, selectedOnly, skipInliningFonts, embedScene, elementsOverride, }: {
withBackground?: boolean;
theme?: "light" | "dark";
frameRendering?: FrameRenderingOptions;
padding?: number;
selectedOnly?: boolean;
skipInliningFonts?: boolean;
embedScene?: boolean;
elementsOverride?: readonly ExcalidrawElement[];
}): Promise<SVGSVGElement>;
createViewSVG(options?: ViewSVGExportOptions): Promise<SVGSVGElement>;
/**
* 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.
*/
createViewPNG(options?: ViewPNGExportOptions): Promise<Blob>;
/**
* Creates an SVG image from the ExcalidrawAutomate elements and the template provided.
* @param {string} [templatePath] - The template path to use for the SVG.
@@ -902,16 +900,19 @@ export declare class ExcalidrawAutomate {
* @param {string} tex - The LaTeX equation string.
* @param {number} [scaleX=1] - The x-scaling factor (post mathjax creation)
* @param {number} [scaleY=1] - The y-scaling factor (post mathjax creation)
* @param {MathJaxRenderOptions} [options] - MathJax rendering options. Set `throwOnError` to propagate invalid LaTeX errors.
* @returns {Promise<string>} Promise resolving to the ID of the added LaTeX image element.
*/
addLaTex(topX: number, topY: number, tex: string, scaleX?: number, scaleY?: number): Promise<string>;
addLaTex(topX: number, topY: number, tex: string, scaleX?: number, scaleY?: number, options?: MathJaxRenderOptions): Promise<string>;
/**
* Returns the base64 dataURL of the LaTeX equation rendered as an SVG.
* @param {string} tex - The LaTeX equation string.
* @param {number} [scale=4] - The scale factor for the image.
* @param {MathJaxRenderOptions} [options] - MathJax rendering options. Set `throwOnError` to propagate invalid LaTeX errors.
* @returns {Promise<{mimeType: MimeType; fileId: FileId; dataURL: DataURL; created: number; size: { height: number; width: number };}>} Promise resolving to the LaTeX image data.
*/
tex2dataURL(tex: string, scale?: number): Promise<{
tex2dataURL(tex: string, scale?: number, // Default scale value, adjust as needed
options?: MathJaxRenderOptions): Promise<{
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
@@ -1454,12 +1455,27 @@ export declare class ExcalidrawAutomate {
*/
getExportSettings(withBackground: boolean, withTheme: boolean, isMask?: boolean): ExportSettings;
/**
* 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): ExcalidrawElement[];
getElementsInArea(elements: readonly ExcalidrawElement[], area: SceneArea, options?: ElementsInAreaOptions): ExcalidrawElement[];
/**
* 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[];
/**
* Gets the bounding box of the specified elements.
* The bounding box is the box encapsulating all of the elements completely.
@@ -1992,6 +2008,58 @@ 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;
}
/* ************************************** */
/* lib/types/excalidrawElementTypes.d.ts */
@@ -2275,6 +2343,8 @@ export declare const MARKDOWN_IMAGE_CUSTOM_DATA_KEY = "markdownImage";
export declare const MARKDOWN_IMAGE_EMBEDDED_FILE_TOKEN = "markdown-image";
export declare const MARKDOWN_IMAGE_SCHEMA_VERSION = 1;
export type MarkdownImageSource = "local" | "external";
/** Persisted behavior for deleting a local Markdown image from the scene. */
export type MarkdownImageDeletionPreference = "ask" | "keep" | "delete";
export type MarkdownImageTransclusionRenderSettings = {
enabled: boolean;
fontFamily: string;
@@ -2311,6 +2381,15 @@ export type MarkdownImageSettings = {
defaults: MarkdownImageRenderSettings;
};
/* ********************************* */
/* lib/types/mathJaxTypes.d.ts */
/* ********************************* */
/** Options for rendering LaTeX through the Excalidraw Extras MathJax service. */
export interface MathJaxRenderOptions {
/** Propagate MathJax conversion errors instead of returning null. */
throwOnError?: boolean;
}
/* ************************************** */
/* lib/types/obsidianDeclarativeSettings.d.ts */
/* ************************************** */
@@ -2946,6 +3025,13 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
lineHeight: number & {
_brand: "unitlessLineHeight";
};
/**
* Position of text bound to a linear element (such as an arrow),
* expressed as a normalized arc-length parameter (0–1) along the
* container's whole path. Independent of how the path is segmented,
* so it survives midpoint insertion and other geometry changes.
* */
labelPosition?: number | null;
}>;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
@@ -3221,6 +3307,7 @@ declare class App extends React.Component<AppProps, AppState> {
wasAddedToSelection: boolean;
hasBeenDuplicated: boolean;
hasHitCommonBoundingBoxOfSelectedElements: boolean;
arrowLabel: boolean;
};
withCmdOrCtrl: boolean;
drag: {
@@ -3283,6 +3370,7 @@ declare class App extends React.Component<AppProps, AppState> {
wasAddedToSelection: boolean;
hasBeenDuplicated: boolean;
hasHitCommonBoundingBoxOfSelectedElements: boolean;
arrowLabel: boolean;
};
withCmdOrCtrl: boolean;
drag: {
@@ -3644,9 +3732,12 @@ declare class App extends React.Component<AppProps, AppState> {
}) & {
preferSelected?: boolean;
}): NonDeleted<ExcalidrawElement> | null;
private getElementsAtPosition;
getElementsAtPosition(x: number, y: number, opts?: {
includeBoundTextElement?: boolean;
includeLockedElements?: boolean;
}): NonDeleted<ExcalidrawElement>[];
getElementHitThreshold(element: ExcalidrawElement): number;
private hitElement;
hitElement(x: number, y: number, element: NonDeletedExcalidrawElement, considerBoundingBox?: boolean): boolean;
getTextBindableContainerAtPosition(x: number, y: number): (Readonly<{
id: string;
x: number;
@@ -3862,6 +3953,10 @@ declare class App extends React.Component<AppProps, AppState> {
private handleCanvasPointerMove;
private handleEraser;
private handleTouchMove;
/**
* Applies the hover affordances of a selected linear element: the cursor,
* plus the hovered-handle state that renders them highlighted.
*/
handleHoverSelectedLinearElement(linearElementEditor: LinearElementEditor, scenePointerX: number, scenePointerY: number): void;
private handleCanvasPointerDown;
private handleCanvasPointerUp;
@@ -5018,6 +5113,7 @@ export type AppClassProperties = {
dismissLinearEditor: App["dismissLinearEditor"];
flowchart: App["flowchart"];
drawShape: App["drawShape"];
arrowText: App["arrowText"];
cursor: App["cursor"];
bucketFill: App["bucketFill"];
isToolLocked: App["isToolLocked"];
@@ -5074,6 +5170,7 @@ export type PointerDownState = Readonly<{
wasAddedToSelection: boolean;
hasBeenDuplicated: boolean;
hasHitCommonBoundingBoxOfSelectedElements: boolean;
arrowLabel: boolean;
};
withCmdOrCtrl: boolean;
drag: {
+24
View File
@@ -476,6 +476,30 @@ export declare class ExcalidrawAutomate {
* @returns {string} The ID of the added rectangle element.
*/
addRect(topX: number, topY: number, width: number, height: number, id?: string): string;
/**
* Adds a sticky note and its optional fitted label to the ExcalidrawAutomate
* instance. Width and height default to Excalidraw's sticky-note size.
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
* @param {string} text - The sticky-note text. An empty string creates an unlabeled note.
* @param {Object} [formatting] - Sticky-note size and label formatting.
* @param {number} [formatting.width] - The initial width of the note.
* @param {number} [formatting.height] - The initial height of the note.
* @param {number} [formatting.fontSize] - The label's maximum font size.
* @param {number} [formatting.fontFamily] - The label font family.
* @param {"left" | "center" | "right"} [formatting.textAlign] - The label's horizontal alignment.
* @param {"top" | "middle" | "bottom"} [formatting.textVerticalAlign] - The label's vertical alignment.
* @param {string} [id] - The ID of the sticky-note element.
* @returns {string} The ID of the added sticky note.
*/
addStickyNote(topX: number, topY: number, text: string, formatting?: {
width?: number;
height?: number;
fontSize?: number;
fontFamily?: number;
textAlign?: "left" | "center" | "right";
textVerticalAlign?: "top" | "middle" | "bottom";
}, id?: string): string;
/**
* Adds a diamond element to the ExcalidrawAutomate instance.
* @param {number} topX - The x-coordinate of the top-left corner.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,716 @@
# File persistence refactor: implementation handoff
Updated: 2026-09-14. Status: checkpoint 5b is accepted and committed as `31592829`. Checkpoint 6a ordinary dirty-unload handoff is accepted and committed as `178d3178`. Checkpoint 6b.1 physical per-path write exclusion is accepted and committed as `e5ba009c`. Checkpoint 6b.2 replacement-owned migration persistence is accepted and committed as `c033e8b6`; checkpoint 6 is complete. Checkpoint 7 ordered exact-payload BAK and its recovery callback correction are accepted and committed as `d1bd628c`. Checkpoint 8's same-file multi-owner gate and its migration/loaded-file corrections passed the full maintainer stress gate and are committed as `25d7e164`. Checkpoint 9's complete normalized save/export snapshot contract passed its runtime and memory gates and is committed as `a634ce27`. Checkpoint 10's detached snapshot autoexports, successful-write publication, migration deferral, live settings, global serialization, and same-source save-batch coalescing are accepted and committed as `452107f6`. Checkpoint 11's exact-target asynchronous load generation and recovery-ordering correction passed the maintainer runtime gate and is committed as `1d1dd365`. Checkpoint 12a's persistence-state extraction passed the maintainer runtime gate and is committed as `839f0547`. Checkpoint 12b's own-write reload-guard extraction passed its maintainer runtime gate and is committed as `b9481c32`. The planned persistence transformation is complete; remaining semaphore groups are deliberately scoped to lifecycle, initial load, and interaction behavior rather than persistence ownership.
This is the execution specification for checkpoint 5b and original checkpoints 6–12. Read it with [AGENTS.md](../AGENTS.md), [CONTRIBUTING.md](../CONTRIBUTING.md), the opening review in [File Persistence Lifecycle Design](<Excalidraw Plugin File Persistence Lifecycle Design.md>), and the concluding “Updated File persistance refactor plan 2026-09-12 (Astra)” section of [RefactorPlan.md](../RefactorPlan.md). This document owns detailed tasks and acceptance gates; RefactorPlan owns checkpoint summaries, maintainer acceptance, and commit/action history. Do not maintain another independent task list.
The earlier failed 5b experiment produced dirty/save ping-pong. Restoring 5a and applying only `CaptureUpdateAction.NEVER` resolved that symptom, while later traces separately proved a destructive dirty-receiver route and cross-view notifications dropped by timing-only suppression. Those findings led to the staged 5b.2–5b.5 implementation rather than restoration of the failed combined patch. The prior divergence is now resolved in instrumented maintainer testing; retain its causal history here so later work does not regress to heuristic timer changes or explanations involving retained views from an earlier plugin runtime.
## 1. Execution ledger and rules
The six 5b steps below are numbered consecutively for handoff clarity. In the earlier lifecycle review, minimum snapshot ownership was called “9a before 5b.3”; here it is **5b.3 (original 9a)**, observation is **5b.4**, and enabling matching is **5b.5**. They are the same six tasks, not additional checkpoints.
| ID | Deliverable | State | Evidence / acceptance / commit |
| --- | --- | --- | --- |
| 5b.0 | Preserve experiment; establish committed 5a baseline | Comparison completed | Source stash `2b158abb204fd9b7e76aeea0a80e12476ce9879e`; HEAD `3899d056`; baseline bundle SHA-256 `cd2f5459151c56cb6ec920bb7ff369eec489be76cc87159292bf4e7dd90dc560`; maintainer confirmed 5a works. This is a comparison result, not certification of all stress interleavings |
| 5b.0a | Publish incoming synchronization as non-undoable remote state | Dirty-loop correction confirmed and committed | Only `IMMEDIATELY` → `NEVER` restored. Commit `45144b52`; pre-instrumentation bundle SHA-256 `acfe02c8592ccae73aaea8ffb1ab034b8517358081f1c72360088244ee14adeb`. Remaining alternating-edit divergence is tracked under 5b.1–5b.5; detailed undo/viewport coverage is not newly certified by this report |
| 5b.1 | Trace first missed propagation, with dirty-origin tracing if needed | Evidence complete; diagnostics removed | Trace A: dirty V2 was routed through full reload and its edit was cleared. Trace B: six modify events were cross-suppressed by the receiver's stale post-save Boolean; both views finally reported clean/idle with different scene fingerprints. The broad temporary `EXCALIDRAW_PERSISTENCE_5B` instrumentation was never committed and was removed before the clean 5b.2/5b.3 checkpoints |
| 5b.2 | Reproduce failure; implement demonstrated prerequisites | Complete; committed | Production routing sends stale dirty/busy Markdown receivers through pending incremental synchronization; clean idle stale and raw-file routes are unchanged. Executable checks and maintainer stress/reopen validation pass. Commit `58d8ea84`. Cross-view post-save suppression remains a proved failing requirement carried through 5b.3–5b.5 |
| 5b.3 / 9a | Minimum immutable save ownership | Complete; committed | Save intent now carries producer/target-generation/operation/requested-revision identity. Save-owned scene, nested element data, app-state subset, files, deletions, selected IDs, and source envelope are detached before normalization; `PreparedSave` owns the exact final text and actual captured revision. Only physical successful write outcomes publish a successful prepared identity. Focused checks/builds and maintainer large-scene runtime tests pass. Commit `071e3ef3`; suppression behavior is intentionally unchanged |
| 5b.4 | Observe candidate content classification | Complete; diagnostics removed | Exact-byte classifier covers successful/accepted/pending/failed/handed-off/different/unknown states and newer local revisions. Ordinary own echoes matched successful writes while cross-view notifications consumed by the Boolean contained different content. The traces also proved the distinct **Open in new window** reentrant replacement failure. Temporary observation code is removed from source and the rebuilt bundle |
| 5b.5 | Enable matching at the coalesced read boundary | Complete; committed | Boolean-armed Markdown events now continue through the existing pending latest-state synchronization loop. Its single owned Vault read revalidates runtime/target identity and skips parse/publication only for exact successful-write or accepted-content matches; all other classifications process normally. Raw `.excalidraw` suppression and same-file edit ownership remain unchanged. Explicit `setViewData()` completion ownership fixes the diagnostic-sensitive **Open in new window** lifecycle race. Commit `31592829` |
| 6 | Detached persistence ownership and ordering | Complete; 6b.2 accepted | Ordinary dirty unload hands immutable prepared text to a plugin-owned FIFO and reports `persistence-handed-off`; commit `178d3178`. Commit `e5ba009c` adds data-only leases preventing live `super.save()`, direct main-realm migration writes, and ordinary detached requests from physically overlapping or overtaking accepted work. Checkpoint 6b.2 folds serialized popout-to-main handoff storage and ordering into that queue while retaining replacement-owned physical persistence; its runtime gate passed. Drawing-runtime handoff remains separate |
| 7 | BAK after successful detached persistence | Complete; committed | Successful live, detached, and migration writes schedule the exact prepared text while still inside their shared per-path ordering boundary. Failed writes and non-empty-ineligible snapshots do not advance BAK; backup failure remains independent from source persistence. Recovery confirmation no longer depends on a retired view. Commit `d1bd628c` |
| 8 | Same-file multi-owner edit gate | Complete; committed | View-local owner identities replace the shared Boolean. Canvas elements and Markdown-image controllers release independently through the established grace period; blocked modifies retain one latest-state synchronization without requiring another event. The migration-envelope and loaded-file marker corrections passed targeted and broad stress testing. The rejected owner-specific pre-save experiment remains preserved as stash object `8e69125349180b35fc4a534801bbbd79b430e688`. Commit `25d7e164` |
| 9 | Complete normalized save/export snapshot | Complete; committed | `PreparedSave` owns a detached normalized scene, captured binary files, deletions, selection, file creation identity, and export settings in addition to exact text/revision identity. Long-lived coordinator/classifier state retains only `PreparedSaveIdentity`, preventing the completed save from pinning a second large scene. All persistence/migration/convergence tests passed; large-scene memory returned to its original value after explicit GC. Commit `a634ce27` |
| 10 | Snapshot autoexports, then ordered exports | Complete; committed | The reviewed candidate replaces the rejected view-owned 10a draft. Automatic SVG, PNG, and raw `.excalidraw` output is submitted from every successful live, detached-close, and migration persistence route to a plugin-owned coordinator. Inputs are detached, hooks are materialized before view retirement, stale work is rejected before final Vault writes, migration rendering waits for replacement load, and automatic renders are globally serialized with task yields between formats. Same-source save activity holds heavy work and coalesces the batch to its newest persisted snapshot, including autosave. Automatic options read current settings/frontmatter at each save; manual exports remain live-scene/dialog operations. Commit `452107f6` |
| 11 | Async load generation | Complete; committed | Every `setViewData()` owns a monotonic token plus exact `TFile`, path, and creation identity. Replacement loads and clear/unload/close/migration invalidate and settle the old ownership promise. Parsing, fonts, transclusion text, migration persistence, library/React initialization, recovery prompts, hook continuation, final loaded marker, and accepted-content baseline check current ownership. Existing reload/synchronization target generations and scene-loader API/path guards remain separate. Recovery lookup now precedes the error-path Markdown fallback so that fallback cannot invalidate its own BAK prompt. Commit `1d1dd365` |
| 12 | Remaining semaphore/timer cleanup | Complete; committed | Persistence execution, autosave execution, force-save execution, and dirty-path storage moved intact from `ViewSemaphores` into `ViewSaveCoordinator`; commit `839f0547`. Checkpoint 12b moved the remaining own-write Boolean and cleanup timer into one view-owned `OwnWriteReloadGuard`, preserving compatibility delegates and accepted Markdown/raw routing; commit `b9481c32`. Lifecycle, load, hover, text-edit, import, and scene-loader state remain intentionally unchanged pending separate evidence and risk gates |
For each implementation increment:
1. State the invariant, concrete failing evidence, affected callers, and smallest proposed correction. Do not bundle history, viewport, image loading, and dirty policy into an echo-detection change.
2. Update this ledger and RefactorPlan with what is implemented versus manually accepted. A build is not acceptance. Never mark all of 5b complete because one reproduction improves.
3. Run production build and focused diagnostics before handing off a test build. Keep genuine failures/notices visible; hiding a busy notice or rejecting a modify silently is not a fix.
4. Recommend risk-based tests, wait for required maintainer results, and commit only when requested. Remove temporary diagnostics before a production commit. If a correction fails, record that, preserve its comparison patch, and return to its preceding accepted boundary rather than stacking another guessed predicate.
5. Preserve the TextFileView facade, public scripting APIs, existing serialized data, merge behavior outside the demonstrated defect, early migration unmount, viewport ownership, and dependency-refresh fallback. No new protocol, blanket CRDT, version bump, package upgrade, or manager solely to make a diagram cleaner.
## 2. Checkpoint 5b.0 — recover and validate the baseline
### Exact state at handoff
- Branch observed: `file-persistence-improvements`; HEAD `3899d056`, `fix: deduplicate copied markdown image renders`.
- `af1cbe74`, `fix: retain latest external drawing sync`, is the committed checkpoint 4/5a baseline. `3899d056` adds only the separately accepted image-loader fix. Prefer `3899d056` initially so the image waves do not confound the stress test.
- `a42e9525` is the save/synchronization ownership checkpoint. Do not jump back that far unless the 5a comparison supplies a reason.
- Uncommitted experimental runtime paths at review: `src/core/managers/FileManager.ts`, `src/types/excalidrawViewTypes.ts`, `src/view/ExcalidrawView.ts`, `src/view/components/CustomEmbeddable.tsx`, `src/view/managers/ViewSaveCoordinator.ts`.
- Documentation changes include the maintainer's appended plan and this handoff. They remained outside the source-only stash and are still present in the working tree. No branch switch or destructive rollback was performed.
### Safe preservation procedure
1. Read `git status --short`, `git branch --show-current`, `git log -6 --oneline`, `git diff --stat`, and `git diff --cached --stat`. Inspect all overlapping/new changes. Stop if the five paths above now contain unrelated user work; do not assume this inventory is still exact.
2. Record plugin dependency/lockfile identity, installed `@zsviczian/excalidraw` version and hashes of its four `dist/obsidian` artifacts, Node/npm versions, current production bundle hash, and sibling-repository branch/status if its artifacts were copied locally. `node_modules` is ignored and survives stashing: a Git commit alone does not identify the runtime package. At review the declared Excalidraw dependency was `0.18.135`; verify rather than reinstalling blindly.
3. Preserve the known experiment with a **path-scoped stash**, leaving documentation in the working tree. After confirming the inventory and index, use:
```sh
git stash push -m "checkpoint-5b failed experiment before baseline validation" -- \
src/core/managers/FileManager.ts \
src/types/excalidrawViewTypes.ts \
src/view/ExcalidrawView.ts \
src/view/components/CustomEmbeddable.tsx \
src/view/managers/ViewSaveCoordinator.ts
git rev-parse 'stash@{0}'
git stash show --stat 'stash@{0}'
git status --short
git diff 3899d056 -- src
```
Record the resolved stash object ID in the ledger, not only `stash@{0}` (its index can change). Inspect the saved patch and verify the final source diff is empty. If new experiment files are untracked, preserve them explicitly too; the command above does not include them. Never use `git stash -a`, broad cleaning, or a hard reset. Do not include the roadmap in a blanket stash and then lose the instructions needed to resume.
4. At the reviewed HEAD, stashing those paths restores baseline source without moving the branch. If HEAD has advanced, plan a separate baseline worktree after preserving changes rather than overwriting unrelated commits. The exact `af1cbe74` comparison can also use a separate worktree; do not silently remove the accepted image fix from the development branch.
5. Keep the stash until the replacement 5b is accepted. Consult it as evidence with `git stash show -p <recorded-OID>`. Do not automatically `pop` it after a good baseline test: that would reintroduce all the unvalidated predicates together. Restoring any part later is a separately reviewed action.
6. Keep these documentation edits through the comparison. If the maintainer requests a documentation checkpoint, stage only the explicit documentation paths, not the source experiment. This specification does not itself authorize a commit or deployment.
The procedure above was executed on 2026-09-12 for the documented five source paths. It remains here as the recovery/audit procedure; revalidate the inventory before reusing it.
### 5b.0 execution record
- Branch/HEAD after restoration: `file-persistence-improvements` at `3899d056`. `git diff 3899d056 -- src` was empty.
- Failed experiment: stash object `2b158abb204fd9b7e76aeea0a80e12476ce9879e`, message `checkpoint-5b failed experiment before baseline validation`. It contains exactly the five documented source paths, 144 insertions and 61 deletions. Retain this object through 5b acceptance; do not identify it later only as `stash@{0}`.
- The three planning files were excluded from the stash. Their pre-stash SHA-256 values were `7546b8f...ed0` (`RefactorPlan.md`), `e4dd2686...1eb` (lifecycle design), and `e5a0e919...d99` (this handoff). They subsequently changed only to record this execution; they were not rolled back or stashed.
- Toolchain: Node `v22.22.2`, npm `10.9.7`. Declared and installed `@zsviczian/excalidraw` version: `0.18.135`. Sibling fork was on `master` with no reported working-tree changes.
- Installed fork artifact SHA-256 values: production JS `42e36f9e...e2`; development JS `5df27a6a...f61`; production CSS `e371caed...7db`; development CSS `1151ae7f...947`. Preserve the full command output in the conversation record; abbreviations here are for readability.
- Failed-experiment bundle before restoration: 4,904,430 bytes, SHA-256 `003c1de0...e15`. Rebuilt baseline bundle: 4,903,363 bytes, SHA-256 `cd2f5459...560`.
- `npm run build` passed in 11.1 seconds and reported 33 circular-dependency warnings (three shown plus “and 30 more”). `node --check dist/main.js` passed. Focused ESLint across the five restored paths reported the existing 19 errors: 18 in `ExcalidrawView.ts` and one in `CustomEmbeddable.tsx`; the other three files were clean. `git diff --check` passed.
- No deployment destination or private fixture identity was inferred or recorded. No Obsidian runtime test has been performed against this rebuilt baseline yet.
- The maintainer subsequently confirmed that 5a still works. The receiving view nevertheless became dirty after receiving only view A's synchronized input. This is the accepted baseline observation motivating isolated checkpoint 5b.0a.
### Baseline test record
Build baseline with Node 22+, `npm run build`, and `node --check dist/main.js`. Record actual build warnings, touched-file lint baseline, `dist/main.js` size/hash, and deployment destination. Do not assume the historical 33 Rollup circular warnings or earlier lint counts still apply. Use the established maintainer test-vault deployment workflow and only an authorized destination. Do not edit generated artifacts by hand. Verify the deployed bundle is the one just built, then fully restart Obsidian.
Use disposable fixture copies, preserving the original outside the test mutation path. Record compression/text mode, autosave interval/settings, autoexport options, zoom-to-fit setting, Obsidian/Electron/OS versions, open leaves, and whether both views were fully loaded before interaction. Do not log private fixture contents into the repository.
Test first with a minimal drawing, then the reported approximately 4,400-element drawing with 500+ Markdown images (72 distinct images copied repeatedly). Start every comparison from the same fixture bytes; prior experiments may have altered versions/indices even if the drawing looks unchanged.
| Baseline case | Required observation |
| --- | --- |
| One edit in A; switch once to B; no more input | Same intended content; finite save/sync activity; both eventually clean; no rescue edit/save needed |
| A/B deliberately at different pan/zoom; alternate edits | Elements propagate; receiving camera stays local |
| Both edit before the other write is applied | Distinct non-conflicting edits survive; no perpetual dirty cycle after input stops |
| Repeat incoming unchanged contents / reopen unchanged drawing | No endless normalization saves; reopening preserves content and layers |
| Back-of-note editor held active while other view edits, then released | Pending scene update appears after release; Markdown content survives |
| Receiving view has not saved for more than five minutes | Record whether full reload runs; verify local content and viewport, not merely the incremental path |
Wait for initial asset work and at least multiple configured autosave periods after input stops; record actual timings rather than declaring success after the old two-second suppression window. Compare file contents after close/reopen as well as visible canvases. Run image-loading overlap as a separate case, not an accidental variation between builds.
**Gate:** baseline comparison completed. The maintainer confirmed that 5a still works; preserve that observation without extending it to unreported stress/undo/platform cases. Continue from the isolated capture-mode result below.
### Checkpoint 5b.0a — isolated remote history publication
The baseline publishes the merged incoming scene using `CaptureUpdateAction.IMMEDIATELY`. The maintainer observed that a clean receiver becomes dirty after receiving only that synchronized input. Apply only the previously attempted capture-mode correction: publish with `CaptureUpdateAction.NEVER`, documenting that incoming Vault state is not a local undoable edit and that locally retained merge state is handled by the existing explicit dirty branch above publication.
Do not restore the failed experiment's content hash, expected-write record, viewport app-state injection, dirty-predicate replacement, semaphore removal, or `CustomEmbeddable` edits. This checkpoint does not claim to solve checkpoint 5b's echo-classification problem.
**Gate:** with clean A and B, edit only A and let synchronization settle. B must receive the element change without entering dirty state, adding the incoming operation to its local undo history, saving the same state back, or moving its independent viewport. Then make a local edit in B and verify it becomes dirty, can be undone, persists, and synchronizes to A. Finally repeat several alternating edits on the large fixture and stop input; both views must converge cleanly without a force save. If ping-pong returns, record the first unexpected transition under 5b.1 rather than adding another adjacent fix.
Automated validation: `npm run build` passed in 11.6 seconds with the established 33 circular-dependency warnings; `node --check dist/main.js` and `git diff --check` passed. The bundle is 4,903,357 bytes with the SHA-256 recorded in the ledger. Focused `ExcalidrawView.ts` lint reports its same 18 existing errors, none on the changed publication. The maintainer confirms dirty ping-pong is resolved, but reports sustained alternating-edit divergence. Retain this narrow improvement and proceed to 5b.1 for the remaining failure. The broad convergence portion of the gate remains open for overall 5b acceptance; do not keep adding fixes under baseline checkpoint 5b.0a.
### Assessment after 5b.0a — separate progress from convergence
The remaining issue belongs to checkpoint 5b. It should be investigated now in 5b.1 and reproduced in 5b.2; its eventual correction may depend on 5b.3 snapshot ownership or 5b.4/5b.5 content classification. No later checkpoint is guaranteed to fix it. Original checkpoints 6–12 remain gated on live-view convergence. In particular, the detached-write queue does not fix two active `TextFileView` writers by itself.
Keep `3899d056` plus the isolated `NEVER` change as the current diagnostic starting point. The only source diff at this assessment is that capture mode and its two comment lines. The five-file failed experiment remains stashed. Do not repeat baseline restoration or pop the stash. A controlled comparison without `NEVER` is useful only if a trace implicates history/dirty callbacks; record matching fixtures and edit cadence, and restore the accepted change after comparison. Do not infer causation from the order of user reports.
Current source gives these concrete investigation targets, in this order of boundary observation rather than certainty of cause:
| Boundary / verified behavior | What the trace must establish |
| --- | --- |
| `FileManager.modifyEventHandler()` calls `consumeOwnWriteReloadSuppression()` before setting a pending-sync marker. It checks only the Boolean. | Was the first notification needed by the receiver consumed here? A marker cannot preserve a notification that never reaches it |
| `executeSaveRequest()` arms the Boolean before `super.save()`, then calls `setPreventReload()` after success; that method sets it to true again and schedules cleanup. | If the own-write modify already consumed the first arm before the save promise resolved, did completion re-arm it and consume another view's later write? This is a source-permitted timing sequence, not a reproduced explanation of the current incident |
| Suppression timeout only clears the flag; it does not reread or schedule synchronization. | Did both views settle with no pending work despite a suppressed required notification? Waiting for the timeout cannot itself recover that notification |
| Notification routing can choose full reload, including after five minutes since last save; `reload()` can return early while save/sync or same-file editing is active. | Did a routed event get no incremental marker and no applied reload? Log the branch and early-return reason; a returned `true` is not proof content was installed |
| The save loop yields to the whole sync drain; per-view saves do not coordinate cross-view writes. | Is a missing change queued but waiting, or did another write supersede its disk state before read/merge? Distinguish active operation, whole-loop lifetime, trailing request, and dirty revision |
| Live capture and model normalization share mutable inputs; incoming application can catch errors internally. | Did the change reach prepared bytes and successful publication, and did it survive later callbacks? Parse completion or a resolved application promise alone is not proof of publication |
For the re-arm scenario, the conditional timeline is A arms → A's own event clears → A save resolves and arms again → B writes → A consumes B's event with no pending marker. Trace event/write ordering in Obsidian before selecting any correction. Shortening/removing the timer or deleting the second arm still leaves the origin-blind Boolean; neither is a sufficient general solution without the controlled cases.
`NEVER` may eliminate redundant saves that previously happened to emit another modify and retry a missed synchronization. That is a hypothesis to test, not grounds to restore unnecessary dirty revisions. Also check the opposite failure: if real local work is no longer tracked, the first break occurs before source persistence. The desired contract is explicit eventual propagation after finite edits without depending on an accidental follow-up save.
### First diagnostic run for the remaining divergence
Use the current build's settings and a fresh fixture. For the first attribution run, wait for initial image loading and make distinct changes to separate simple elements (or add distinct simple shapes), recording anonymous element/edit identities. Repeat the user's A/B switching cadence; editing different elements separates propagation failure from same-element conflict policy. Add image-loading overlap and same-element competing edits as subsequent cases.
Capture both views' operations on one sequence timeline. Begin with cheap routing, suppression arm/consume/re-arm/expiry, save completion, pending-marker and ownership events. Trace selected edit identity/version through captured/prepared and read/published states. Use the already-owned save text and sync read for payload observation; do not add an asynchronous Vault read for every modify just for diagnostics. Deep raw/parsed/merged field comparisons are the second tier if the event reaches reconciliation but content changes unexpectedly.
At the first visible divergence, stop editing and collect a read-only snapshot of both scenes' relevant edit identities, disk state, current/saved revisions, active/queued save, pending sync/loop, same-file guard, and suppression state. Record elapsed settling time. Avoid force-save, reload, or close until this evidence is captured because those actions alter the state under investigation. No automatic diagnostic writes or repair loop.
Classify the earliest break:
1. **Source edit absent from prepared/successfully written content:** inspect local dirty tracking, capture revision, normalization and acknowledgement (5b.2/5b.3).
2. **Source write present but receiver event consumed/unrouted:** inspect suppression/routing; reproduce the decision and implement its validated replacement (5b.2 then 5b.4/5b.5 as needed).
3. **Receiver work queued but never acquired/completed:** inspect save/sync/gate waits, exceptions and request fairness (5b.2).
4. **Read/merge/publication omits a required change, or subsequent work overwrites it:** inspect actual write order, merge results, publication and callbacks; use 5b.2 or 5b.3 according to the demonstrated boundary.
These are classifications for selecting the correction, not four changes to implement speculatively. The next implementation deliverable is the trace and its smallest reproducible failing case.
## 3. Source map and verified hazards
Use symbol searches; line numbers in older notes drift. The following describes reviewed source and the failed working patch, not guaranteed post-stash behavior.
| Boundary | Inspect these files/symbols | What must be distinguished |
| --- | --- | --- |
| Notification and leaf-switch entry | `src/core/managers/FileManager.ts: modifyEventHandler`; `EventManager.ts: onModifyHandler`, `onActiveLeafChangeHandler` | Same-path Markdown versus raw `.excalidraw`; initialized view versus `ExcalidrawLoading`; split-switch/full-reload/Markdown-view branches |
| Per-view persistence | `src/view/managers/ViewSaveCoordinator.ts: enqueueSave`, `drainSaveQueue`, `performQueuedSave`, `completeSaveRevision`, `setDirty`, `flush`, `forceSaveWithPolicy` | Active write versus queued save-loop lifetime; queued/requested versus captured revision; dirty visuals versus acknowledged state |
| External synchronization | `src/view/ExcalidrawView.ts: requestExternalSynchronization`, `startExternalSyncLoop`, `drainExternalSynchronization`, `acquireSynchronization`, `yieldToPendingExternalSynchronization`, `applyIncomingSynchronization` | Notification marker versus read in progress; parser model versus live merge; same-file guard; cancellation/finally boundaries |
| All dirty sources | Same view: `onExcalidrawIncrement`, `onChange`, `checkSceneVersion`, explicit `setDirty`; tracked-app-state helpers | Durable store increments, tracked persisted app state, ordered version hash, explicit reconciliation, delayed metadata/image mutations |
| Save representations | Same view: `executeSaveRequest`, `getSceneWithAppState`, `prepareGetViewDataFromSnapshot`, `getViewData`, `loadDrawing`, `setViewData`; `src/shared/ExcalidrawData.ts: loadData`, `syncElements` | Raw Markdown buffer; raw parsed JSON; normalized mutable model; live API; exact text passed to TextFileView |
| Image publication | `src/view/managers/ViewSceneFileManager.ts`; `src/shared/EmbeddedFileLoader.ts`; view `addFiles`/`updateScene`; image scaling helpers | Queued loader versus actual callback/decode completion; render-only work versus persisted geometry/customData |
| Fork store/index behavior | Sibling `packages/element/src/index.ts: hashElementsVersion`; `fractionalIndex.ts: syncInvalidIndices`; installed fork `CaptureUpdateAction`, store callbacks, `updateScene` implementation | Real published artifact behavior; ordered nonce hashing; index mutation; synchronous flush versus delayed callback; history capture semantics |
| Detached persistence | View migration callback and unload branches; `src/core/managers/ViewMigrationPersistenceHandoffManager.ts`, `ViewMigrationHandoffManager.ts`; `src/shared/BackupPersistenceQueue.ts` | Drawing-state transfer versus serialized persistence transfer; accepted handoff versus completed source write |
Verified facts to preserve in future reasoning:
- `loadData()` applies remaining non-text `elementLinkMap` entries by setting the link and incrementing `version` and `versionNonce` unconditionally. An isolated execution of that exact loop with an unchanged link demonstrated the increment; the loop also exists at `3899d056`. This is **not** an end-to-end reproduction of ping-pong. Do not remove version increments globally without checking actual link changes and consumers.
- `hashElementsVersion()` is ordered nonce hashing, not a numerical revision sum or complete content comparison. Reordering can be a genuine layer edit. `ExcalidrawView.updateScene()` normalizes indices after synchronization has computed `previousSceneVersion`; the normalization can mutate versions. Trace the actual installed array and callbacks before changing baseline timing.
- The uncommitted `hasLocalStateToPersist && !isDirty()` guard suppresses revision advancement for an already-dirty view. An already-dirty Boolean does not establish whether a waiting/active request includes a newly reconciled change. Conversely, every repeated reconciliation is not automatically a new document change.
- `setDirty()` advances `currentRevision` and updates a trailing request when `saveLoopPromise` exists. The loop can be alive while `activeSaveRevision` is null and it is awaiting external synchronization. Trace whether the trailing request receives the reconciliation revision. `forceSave` refuses several kinds of busy state; the notice does not prove a physical Vault write is hung.
- `yieldToPendingExternalSynchronization()` awaits the **whole** external drain, not one iteration despite its comment. Further events can extend it. Pending state being bounded does not guarantee finite work or fairness.
- Incoming tombstone IDs filter local elements before the live-element version comparison. Do not claim newer-local-versus-older-deletion behavior is version-aware without a separate correction and test.
- `getSceneWithAppState()` retains API elements and nested objects; a shallow files map still shares values. `syncElements()` assigns the provided scene and mutates it across awaits, including clearing `scene.files` after synchronization. `readonly` does not make this an immutable capture.
- `loadDrawing(false, deletedElements)` may run during save normalization. Camera stripping in the reload branch is not automatically exercised by that call. Adding app state to `updateScene()` can change flush behavior as well as values. The observed camera improvement does not prove which mechanism caused it.
- `await loadSceneFiles()` does not await all image publication/decoding. Some image helpers change geometry/customData without a version bump; do not classify all image differences as disposable cache noise.
- Incremental sync does not explicitly adopt the drain's raw Markdown into `this.data`; serialization uses that buffer's envelope. Verify Obsidian's actual TextFileView callback/buffer contract before claiming a stale buffer, or fixing one by blindly overwriting local Markdown. `setViewData()` has a same-file early return after asynchronous initialization.
- Exact prepared-text equality describes observed bytes, not who emitted a Vault event. View revisions are local counters. Even serialized writes in a single JavaScript realm can race across awaits; a per-view coordinator is not a per-path write coordinator.
## 4. Checkpoint 5b.1 — trace the first erroneous transition
Create a temporary, isolated diagnostic patch with prefix such as `EXCALIDRAW_PERSISTENCE_5B`. Use `log` from `src/utils/debugHelper.ts`, not direct console calls. Emit one copyable string per event, with monotonically assigned anonymous view/operation IDs and sequence numbers. Bound captured observations; do not retain views, scenes, or giant payloads in a global debug buffer. Remove diagnostics and search both `src/` and the rebuilt `dist/main.js` before a production commit.
Trace the missing-propagation boundary first as specified above. The following is the available diagnostic inventory; enable deeper per-element comparisons only when routing/write evidence requires them. Dirty-origin tracing remains necessary for source edits and any recurrence of ping-pong, but an unexpected dirty event is no longer required to begin diagnosis.
- Dirty origin and before/after current/saved/active/requested revision; previous/current ordered scene hash; tracked-app-state category; whether a queued request was created/replaced. Do not merely log the final header-icon color.
- Save trigger (autosave, switch/blur, force, flush, teardown), capture start, preparation completion, actual write invocation/completion/failure/no-op, queue yield/resume, and terminal acknowledgement. A resolved whole-loop promise is not an individual write-completion event.
- Modify notification, classification candidate/result, pending marker transitions, sync acquisition/release, exact target/runtime validity, Vault read start/completion, parse start/completion, publication, and full-reload branch.
- At raw, parsed, merged, published, and serialized boundaries: bounded anonymous element transition samples plus counts of changed IDs, versions/nonces, indices/order, links, text dimensions, deletion state, image geometry/customData, and tracked app-state categories. Capture immutable scalar observations immediately; do not inspect a live object later and call it its earlier state.
- Fingerprint raw/prepared text at selected operation boundaries. Do not hash multi-megabyte scenes on every `onChange` or await extra diagnostic work inside behavior-critical paths. If hashing is deferred, label when input was captured versus when the digest completed. Measure diagnostic overhead and confirm the uninstrumented symptom too.
- Observe TextFileView `getViewData`/`setViewData` and its inherited save contract using the supported runtime/debugger or local typings/source where available; use obsidian-typings as the API reference. Do not introduce an unverified TextFileView override merely to collect a trace.
- Separate delayed loader callbacks, scene publication, and store/onChange notification. A queued loader, synchronous API return, frame callback, and actual paint are different milestones.
Start with a single edit/switch to establish normal routing, then reproduce the reported repeated alternating edits. Identify the first required edit that fails to reach the other view; a quiet but divergent pair is as significant as busy queues. If a new dirty loop occurs, identify its first unwarranted dirty transition and follow the resulting write. If normalization produces a required write, check that its result stabilizes on the next cycle.
**Gate:** attach a concise trace interpretation and unresolved questions to the ledger. If the trace changes timing enough to hide the bug, reduce it and use deterministic barriers in the test harness; do not declare resolution. Do not add a new production manager/guard in this diagnostic checkpoint.
### 5b.1 instrumentation execution record
- Commit `45144b52` is the accepted boundary containing `CaptureUpdateAction.NEVER` and the three persistence planning documents. The failed combined experiment remains preserved as stash object `2b158abb204fd9b7e76aeea0a80e12476ce9879e` and was not reapplied.
- The temporary diagnostic patch remains uncommitted. It adds `src/utils/persistenceTrace.ts` and instruments `PluginFileManager`, `EventManager`, `ViewSaveCoordinator`, and `ExcalidrawView`. It does not add a persistence manager, guard, suppression decision, queue transition, or other intended behavior correction.
- Every diagnostic event goes through `log()` as exactly one fully rendered string beginning `EXCALIDRAW_PERSISTENCE_5B`. It assigns anonymous per-runtime view IDs and a global sequence/elapsed time. It never prints a Vault path, Markdown text, element content, or object payload. Large prepared/read text and ordered scenes are represented by synchronous fingerprints and counts; selected local element changes use hashed IDs and bounded metadata for at most eight elements.
- The trace covers local dirty origins and revision transitions; leaf leave/enter and save request completion; save queue creation, coalescing, dequeue, write, acknowledgement, yield, and release; suppression arm/consume/re-arm/expiry; modify routing; pending-sync marker and loop transitions; read/parse/merge/publication; and reload early-return reasons. A five-second delayed read-only snapshot after leaf activation records both the live scene fingerprint and settled save/sync/pending/suppression state, so a quiet divergent pair is observable without rescue input.
- Node 22.22.2 production build passed in 10.2 seconds with the established 33 circular-dependency warnings. `node --check dist/main.js` and `git diff --check` passed. The instrumented bundle is 4,914,810 bytes with SHA-256 `91993059ab69fff35ebb4313811d4d76089dd7c29539b3860cff9e5af5de1fe7`. Focused lint reports only the same 18 established `ExcalidrawView.ts` findings; the new helper and the other three instrumented files are clean.
Runtime capture procedure:
1. Deploy the instrumented bundle and fully restart Obsidian. Open the disposable large fixture in two adjacent fully loaded Excalidraw views and let initial Markdown-image work settle.
2. Open Developer Tools, filter Console output by `EXCALIDRAW_PERSISTENCE_5B`, and optionally clear the filtered console immediately before editing.
3. Make distinct edits to separate elements while alternating A → B → A → B as in the reported reproduction. Continue only until the first visible missed propagation or divergence.
4. At the first divergence, stop all input. Do not force save, reload, close a leaf, or make a rescue edit. Wait at least five seconds so the delayed settled-state snapshot is emitted.
5. Copy all filtered trace lines as plain text and report which view missed which visible edit. Preserve line order. If the trace volume or overhead prevents reproduction, report that rather than extending the test or treating it as a pass.
### 5b.1 trace interpretation
The two maintainer traces reproduce two independent failure boundaries. These are observed event sequences, not inferred plugin-runtime history or timing guesses.
**Trace A — a dirty receiver is destructively full-reloaded.** V2 records a local durable edit at sequences 53–55 while V1 is preparing its save. V1 writes at sequences 56–58. V2 receives that modify while dirty (`modify-match`, sequence 59), but routes it to `modify-route-full-reload` at sequence 61; `reload-enter` at sequence 62 confirms `full=1` and `preserveViewport=0`. The reload later advances/clears V2's dirty baseline at sequences 81–82 and completes at sequence 83. No incremental synchronization marker, read, merge, or publication occurs for V2. Therefore V2's edit is replaced by the disk snapshot written from V1. The five-minute heuristic is unsafe whenever its target has local unpersisted state; this failure is independent of expected-write matching.
**Trace B — post-save suppression consumes another view's write.** Own writes normally consume the suppression armed immediately before `super.save()`, then successful completion arms the same Boolean again for the cleanup window. The re-armed Boolean has no writer or content identity. The trace records six events where the view consuming suppression is not the view whose `textfile-save-begin` caused the modify: sequences 474, 796, 849, 894, 942, and 1054. The first is already conclusive: V2 re-arms after its own save at sequence 416; V1 writes at sequence 471; V2 consumes that event with `cleanupTimer=1` at sequences 472–474, so it creates no pending synchronization. Its timeout at sequence 495 only observes the Boolean already cleared and cannot recover the event.
The final transition proves this is a dropped notification, not work that merely needs more time. V1 finishes a write and re-arms at sequence 1003. V2 subsequently writes different prepared bytes at sequence 1048. V1 is clean, not saving, and not busy at sequence 1052, but consumes V2's event from the stale cleanup-window Boolean at sequences 1053–1054. After timers settle, V1 and V2 both report `dirty=0`, `saving=0`, `synchronizing=0`, `pending=0`, and `syncLoop=0`, yet their live scene summaries differ at sequences 1069 and 1072 (`4432:3:2080337:47643cfd:3c5b39d6` versus `4432:0:2080312:c16304cc:92a2bd45`). No later queue action exists that can reconcile them. Earlier cross-suppressions in both directions explain why the user-visible missing direction can vary during sustained alternation.
The trace does not show a hung save, an exception, an unreleased synchronization flag, or an unprocessed pending marker. It does show expected parse-time/installation version changes, but those are downstream of successfully routed notifications and are not needed to explain either first break. Preserve those normalization concerns for the deterministic convergence suite; do not mix them into the two demonstrated routing corrections.
## 5. Checkpoint 5b.2 — reproduce and establish convergence
There is no established plugin view/model unit-test suite in `package.json`. Do not invent an `npm test` success claim. Establish a small reproducible harness with a documented command using current tooling; prefer actual functions/classes and injected Vault/scheduler boundaries over a copied imitation of the algorithm. A source-loop micro-test proves only that loop. Test helpers may control promise completion order; avoid timing-dependent real sleeps. Pure helpers can be extracted mechanically only when needed and separately reviewed.
Implement and validate the demonstrated boundaries as separate increments:
1. **Dirty-receiver routing.** Reproduce Trace A with a receiver whose `lastSaveTimestamp` is more than five minutes old and which has a local unsaved edit when another view writes. A same-file Markdown modify must not enter destructive full reload while the receiver is dirty or persistence/synchronization-busy. Route it through the existing pending incremental synchronization path so acquisition, latest-file read, version merge, explicit retained-local dirty state, and viewport preservation remain in force. Keep the clean, inactive stale-view refresh policy unchanged unless its own test proves it unsafe. Verify the local edit and incoming non-conflicting edit both survive, the receiver remains dirty only until the merged state is persisted, and reopen contains both. This correction is eligible for its own checkpoint/test before suppression replacement.
2. **Cross-view suppression reproduction.** Encode the Trace B order explicitly: A completes an own write, its immediate own modify consumes the pre-write arm, completion re-arms the Boolean, then B writes before A's cleanup timeout. Assert that current code suppresses B's event and leaves no pending marker. Retain this failing regression through 5b.3–5b.5. Do not “fix” it by merely shortening the timeout or deleting the completion re-arm: Vault notification timing can differ by platform, and either timing-only change recreates a missed-own-echo or external-write window.
The demonstrated durable replacement is the planned content-aware path: 5b.3 must associate exact prepared bytes and actual successful completion with a save operation; 5b.4 must verify the candidate classification against these interleavings without suppressing; 5b.5 must mark same-file Markdown events as pending work before classification, acquire the existing read boundary, and skip only content already represented by a relevant successful/accepted identity. A different view's differing bytes must remain eligible even during the former cleanup window. Equality may establish redundant content, not writer identity. Keep `CustomEmbeddable`'s non-save calls to `setPreventReload()` explicitly inventoried; removing save-owned Boolean suppression does not authorize deleting same-file editor protection before checkpoint 8 supplies an equivalent owner/grace model.
Define three separate comparisons:
1. **Exact bytes:** what the Vault read or actual save contained. Suitable for redundant-content detection, not merge ownership.
2. **Persisted document meaning:** elements including order/deletions/custom fields, persisted app state, and Markdown envelope under existing format rules. Any excluded field requires a concrete reason; do not erase all indices, nonces, camera values, or image dimensions to make tests pass.
3. **View-local runtime state:** camera, selection, render caches, and editor state where the existing policy treats them as local. Some camera/tool settings are serialized under current settings; local runtime ownership does not authorize removing them from the file format.
Required controlled cases:
| Case | Assertion / decision required |
| --- | --- |
| Parse and serialize unchanged non-text links repeatedly | After any explicitly justified normalization, versions and writes reach a fixed point; real link changes still persist |
| Equal elements with different order/invalid fractional indices | Genuine layer changes survive; normalization converges; dirty baseline corresponds to what was actually installed |
| Raw/parsed text, bound text, equations, copied Markdown images | Normalization does not endlessly toggle fields; durable geometry changes are retained |
| Older incoming N, newer local N+1 | Local result remains eligible for persistence even if the receiver was previously clean or already dirty |
| Incoming-only changes to a clean receiver | Accepting the persisted baseline alone does not create a write-back loop |
| Same element changed in both views; deletion versus edit | Record existing tie/deletion policy; preserve it unless a demonstrated correction is explicitly approved; never claim both conflicting values survive |
| Repeated/duplicate notification and notification during sync finalization | Latest work is not lost at marker clear or promise-finally boundaries; unchanged events do not generate writes |
| Pending save waits for sync; reconciliation changes state | Pending request covers the reconciled revision; acknowledgement cannot strand that change |
| Save fails, parse fails, or view changes while awaiting | Flags/promises release; dirty state and existing valid drawing survive; no false success or stale publication |
| Markdown/back-of-note changes while scene save is preparing | Latest accepted envelope is retained or a conflict is explicitly handled; no silent header/tail overwrite |
Control at least these cross-view interleavings: A writes, B reads A, B merges/saves; A and B both prepare before either completes; B writes between A's notification and A's read; A receives another notification while applying the first; old read/hash completes after navigation/record replacement. Test on-demand leaf-switch saves with autosave, not autosave alone.
If two saves can overwrite an unseen non-conflicting edit before any reader observes it, a latest-read marker alone cannot fix that. Produce the failing timeline and decide whether a narrow plugin-owned per-path reconciliation/write boundary is needed. Such coordination must still use `super.save()` for live writes, must reread/reconcile under the relevant boundary, and must preserve main-realm migration rules. Mere FIFO serialization or choosing the last arrival is not conflict resolution. Treat this as an explicit prerequisite checkpoint, not an incidental new queue inside hash detection.
**Gate:** record the earliest failing case and its responsible boundary. For a queue/merge correction implemented here, record its passing reproduction and callback/history effects. If the failure is specifically the Boolean suppression that 5b.4/5b.5 replace, or snapshot ownership addressed in 5b.3, retain the failing regression case and explicitly carry that acceptance requirement to the named step. Do not require 5b.2 to solve the Boolean with an interim heuristic just to reach the designed replacement, and do not claim overall convergence before it is fixed. Independent defects must not be hidden by the pending replacement. Undo/redo must keep local edits undoable without making remote acceptance a spurious user edit. Re-run both first-edit and sustained large-scene cases after each relevant correction.
### 5b.2a dirty-receiver routing execution record
The first demonstrated correction is implemented as an isolated routing change. `getDrawingModifyRoute()` is a pure production helper used by `PluginFileManager.modifyEventHandler()`. For same-file Markdown, a dirty or persistence-busy receiver now selects `incremental-sync` before the five-minute stale-view decision. That route uses the existing latest pending marker, acquisition, Vault read, merge, non-undoable publication, retained-local dirty marking, and autosave. A clean and idle stale Markdown view still uses the existing full reload; raw `.excalidraw` routing is unchanged.
`node scripts/check-file-modify-routing.mjs` imports the production helper and verifies stale+dirty → incremental, stale+busy → incremental, clean+idle+stale → full reload, the existing Markdown-side/recent-switch protection, and both raw-file routes. It passes. Focused lint for the new helper, `FileManager`, and all temporary diagnostic support files passes. The Node 22.22.2 production build passed in 10.7 seconds with the established 33 circular-dependency warnings; bundle syntax and `git diff --check` pass. The bundle is 4,915,216 bytes, SHA-256 `16534db42f8f0f1b28d69c123166ef02f5a2c6a056e3544c61fbb9bd876a6327`.
Manual gate is deliberately scoped to Trace A because Trace B remains unfixed. Start from a full Obsidian restart with the large drawing's file modification time older than five minutes and neither view carrying a prior suppression timer. Open it in adjacent fully loaded views. Edit A, switch immediately to B, and make a distinct edit while A is still preparing/writing. B's matching modify must log `dirty=1` followed by `modify-route-sync`, never `modify-route-full-reload`; B must retain its own edit while accepting A's non-conflicting edit, preserve its viewport, and persist the merged result. After work settles, verify the persisted/reopened drawing contains both. The still-known stale suppression may prevent A from immediately receiving B's merged write, so that symptom alone does not reject 5b.2a; record it under the already proved 5b.3–5b.5 requirement. Any loss of B's local edit, full reload while B is dirty/busy, or failure of the persisted merged result rejects this increment.
Maintainer validation passes this scoped gate. Across 1,223 trace lines there is no `modify-route-full-reload`; every matching event not consumed by the known Boolean enters `modify-route-sync`, including dirty receivers. The alternating dual-edit scenario remained responsive longer and was reported as definitely better. The two live views eventually diverged on screen, but closing and reopening the view that missed updates loaded those updates from persisted content; the reopened V3 settled with 4,435 live elements. This confirms the former dirty full-reload loss is removed and the accumulated result remains reopenable.
The residual divergence is not new evidence against 5b.2a. The same trace contains seven cross-view suppression events (sequences 563, 684, 731, 850, 903, 1012, and 1123), each caused by a receiver's prior post-save cleanup-window Boolean rather than the current writer. For example, V1 writes at sequence 1117 while clean/idle V2 consumes the event at sequences 1121–1123 with `cleanupTimer=1`, creating no pending synchronization. V2 later shows a different live summary, while reopen obtains the later persisted scene. This precisely matches the accepted 5b.3–5b.5 regression and requires no additional routing change in 5b.2.
## 6. Checkpoint 5b.3 — minimum save ownership (original 9a)
Before implementing, write the capture/acknowledgement contract. Conceptual names below describe roles, not a demand for new managers or final public types:
- **Save intent:** trigger, force/guard/side-effect policy, producer identity, and requested revision. A queued intent can predate capture.
- **SaveSnapshot:** file identity/runtime generation, capture revision, owned scene/app-state/deletion/selection inputs, and the Markdown envelope or its explicitly accepted base identity.
- **PreparedSave:** exact final text, normalized state identity, producer/capture revision, and persistence-relevant eligibility/options. Mutable preparation scratch is not exposed as an immutable result.
- **Write completion:** operation identity, actual successful prepared payload identity, and the revision it is safe to acknowledge. Failure/skipping/handoff are not successful disk writes.
Use existing project/fork types; keep view-scoped types local unless shared. Choose the revision-capture point explicitly: forwarding `requestedRevision` is not enough if capture happens later. Either capture that exact revision when requested, or capture current state later and return its actual captured revision. Do not acknowledge revisions that arrived after capture. Preserve public `save(...)`/force-save delegates and policy merging.
Inventory every mutable input used after an await: elements and nested points/bindings/customData, deleted elements, selected IDs, app-state nested objects, file metadata, Markdown envelope/element maps, and normalization outputs. Copy mutable structures needed by preparation; share immutable strings/bytes only under a documented ownership rule. Do not JSON-clone the entire live API/app state (it contains runtime objects), nor duplicate all image data URLs unnecessarily. Dev tests can freeze owned captures, but must not freeze objects still owned by Excalidraw.
`syncElements()` currently installs and mutates the scene in `this.excalidrawData`. Determine which preparation mutations must later be reflected in the live model. Do not solve immutability by simply detaching everything and dropping normalized metadata, or by publishing an old snapshot over newer local edits. Prove that API mutations during compression cannot change prepared text or exported normalized state.
Capture after any intentionally awaited edit/deletion prompt, with target revalidation. For migration, capture all API-owned values synchronously and unmount before the **first await**, as required today; do not move an ordinary save's waits into that pre-unmount path. Keep teardown and replacement file identity checks distinct from source runtime lifetime.
Audit `getViewData()` and `super.save()` so the text fingerprinted is exactly the text the inherited bridge consumes, including headers/frontmatter/back-of-note and compression. Preserve forced no-op save's explicit reload behavior (`reloadIfWriteDidNotEmitModify`); unchanged text can still require a refresh without a modify event. Verify BAK's existing `lastSavedData` source corresponds to this completed write before building on it.
**Gate:** paused compression plus further edits, nested-object mutation, queued revision advancement, failed write, no-op force save, malformed incoming Markdown, navigation, and migration. Older completion cannot clear a newer revision; normalization cannot overwrite newer live work. Measure peak retained data on the large fixture. No export queue yet.
### 5b.3 implementation record
`ViewSaveCoordinator` now assigns each physical attempt a save intent containing the view producer, save-target generation, operation ID, and requested revision. `ExcalidrawView` samples the actual current revision at scene capture, after the existing deletion-prompt await and target checks. A save-target generation advances when `TextFileView` starts loading a different target; this identity is only for persistence records and deliberately does not claim to be the asynchronous load fence planned in checkpoint 11.
`saveSnapshot.ts` creates save-owned copies of the scene envelope, elements and their nested plain data, the persisted app-state subset, binary-file records, deleted elements, selected IDs, and source Markdown envelope. Runtime render caches (`shape` and `canvas`) are excluded, while immutable data-URL strings are shared. Existing `ExcalidrawData.syncElements()` still owns normalization and its metadata maps; after it settles, `generateMDBase()` synchronously materializes those maps and the normalized scene into strings before asynchronous compression. Therefore the resulting `PreparedSave.text` is the exact immutable text passed through `getViewData()` to `TextFileView.save()`. Completing an older capture acknowledges only its captured revision; edits arriving during normalization/compression remain newer and retain/queue dirty work even if their data was conservatively included in the prepared bytes.
The coordinator retains the latest `PreparedSave` only for a completed live `super.save()` or the awaited main-realm migration write. A requested, skipped, failed, delayed-unload, or migration-handed-off operation is not labeled a successful physical write. The current Boolean is still armed and consumed exactly as before; no modify event is classified or skipped using this record in 5b.3.
Automated validation: `node scripts/check-save-snapshot.mjs` proves nested element/deletion/app-state/file detachment, render-cache exclusion, immutable data-URL sharing, exact prepared text identity, target generation, and captured-versus-requested acknowledgement. Focused lint, unused-symbol checks, production and library builds, bundle syntax, and `git diff --check` pass. The Node 22.22.2 production build retains the established 33 circular-dependency warnings; `ExcalidrawView.ts` retains exactly its established 18 lint errors. With the temporary trace removed, the production bundle is 4,905,956 bytes with SHA-256 `46873e0e72d5264b3aa240be88cb395a37d44b72a1f09fe2fc16e07ea05c9de5`.
The maintainer accepted the focused runtime gate on the 4,400+ element scene: edits made around compression persisted, all tested change types passed, bound linear elements did not change the outcome, and no regression was identified. This gate does not require two-view convergence: the known post-save Boolean may still discard the other view's notification until 5b.5.
## 7. Checkpoint 5b.4 — observe classification without changing suppression
Alongside the now-validated baseline behavior, maintain a temporary candidate record and log what a replacement would do. Do not consume notifications based on the candidate yet. Keep candidate calculations bounded and separate from production scheduling; observation can perturb timing, so compare uninstrumented runs as well.
Candidate identity needs a producer/operation ID, target file/runtime identity, captured revision, exact prepared-text fingerprint, and write state. Producer revision is meaningful only for that producer. A newly started write must not be labeled successful; a record from an older operation must not clear its replacement after a delayed promise settles. Track a successfully accepted document baseline separately where needed. Bound retention; do not store an unbounded hash history.
| Observed state | Required interpretation |
| --- | --- |
| Bytes match this target's known successful prepared write, with no newer local edits | Candidate redundant content; not proof the notification originated here |
| Same bytes, but local edits occurred after capture | Do not clear or acknowledge those newer edits; any skipped merge is only an optimization for already represented disk content |
| Bytes match only a pending/failed/abandoned attempt | Not established successful content; defer/classify after outcome or process normally |
| Bytes match the fully accepted current document baseline | Repeated notification may be redundant without a current expected-write record; define this independently of timeout expiry |
| Different or unknown bytes; read/hash failure | Keep external work eligible; report failure through existing paths; do not consume as an own write |
| Target/runtime/record changed during await | Result cannot classify the replacement target; preserve any newer target work |
| Later writer produced identical bytes | Equality can make content redundant, but cannot establish writer identity |
Test record replacement, successful write notification before/after promise completion, no-op write without notification, duplicate/delayed events, failed write, rename, close, A→B→A navigation, and two writers. Observe force-save and same-file editor callers, including the two suppression calls removed in the failed `CustomEmbeddable.tsx` patch.
**Gate:** every skip decision is justified by known accepted/successful content and cannot lose newer local state. Record disagreements with actual outcomes before changing behavior. Timeout is cleanup, never evidence of origin.
### 5b.4 implementation record
The observation patch is intentionally uncommitted. The bounded classifier compares exact retained strings, while console output uses only length/FNV fingerprints. It distinguishes successful writes, accepted input, still-pending attempts, failed attempts, unconfirmed handoffs, differing known content, and missing/stale target identity. A matching successful write or accepted baseline also reports whether a newer local revision exists; observation never clears that revision.
Existing incremental synchronization classifies the Vault text it already read. To inspect events that the legacy Boolean currently drops, a view temporary per-view marker coalesces only those Markdown events into one latest-state shadow read after local save/sync/edit ownership settles. That read neither parses nor publishes data and never marks dirty or schedules persistence. It captures and revalidates the save-target generation before and after awaits. Initial successfully loaded text and successfully applied synchronization text establish the observation-only accepted baseline. Prepared write attempts are recorded before persistence and transition only when the matching producer/target/operation completes; an older completion cannot replace a newer candidate.
All diagnostics use `log()` and emit one complete string prefixed `EXCALIDRAW_PERSISTENCE_5B4`; they contain anonymous view IDs, revisions/states, and bounded fingerprints, never paths, note contents, image data, or expandable objects. `node scripts/check-save-content-classification.mjs` covers successful content with/without newer local work, accepted content, pending/failed/handed-off attempts, different content, target-generation invalidation, and operation replacement. Focused lint, unused-symbol lint, the production build, bundle syntax, and `git diff --check` pass. The instrumented bundle is 4,912,850 bytes with SHA-256 `62d4a318aec18fc275c6c5fd624d0d53f65309c1a0347b803a9c721c3e0bc731`; the build retains 33 established circular warnings and `ExcalidrawView.ts` retains its established 18 lint errors.
Runtime gate: deploy and restart Obsidian, filter the console by `EXCALIDRAW_PERSISTENCE_5B4`, and run the same alternating two-view large-scene test until the first visible missed propagation. Stop input and wait several seconds before copying all filtered strings. For an ordinary own-write echo, the suppressed shadow read should classify `matches-successful-write`. For the proved cross-view defect, the receiving view's legacy Boolean may still consume the event, but its shadow read must classify `different-from-known-content` (or another explicitly non-skippable state), never a successful/accepted redundant match. Also capture one duplicate notification/settled no-op and one edit made during a save; matching content with `newerLocal=1` must not imply that the newer revision can be cleared. Any mismatch between these candidate results and the known event outcome rejects 5b.4 and must be explained before 5b.5.
### 5b.4 runtime evidence and popout follow-up
The two supplied `EXCALIDRAW_PERSISTENCE_5B4` traces validate the candidate distinction for main-window views 1 and 3. Each view's own notification shadow-read repeatedly classified `matches-successful-write`. Four notifications consumed in the other view's post-save Boolean window classified `different-from-known-content` (trace sequences 93–98, 108–113, 132–135, and 147–150). These are exactly the events that 5b.5 must retain as pending work. Sequence 106 also records `matches-successful-write newerLocal=1`, confirming that byte equality must not acknowledge or clear a later local revision.
The three-view extension reveals a separate pre-classification gap. View 4 records `content-accepted` at sequence 152, proving that its runtime loaded the persisted document, but subsequent saves from views 1 and 3 produce no view-4 suppression, route, sync-read, or accepted-content event. That absence does **not** yet prove why the view was skipped: the original 5b.4 logging begins only after `getExcalidrawViews(app, true)` and target checks. Keep production routing unchanged and temporarily record every Excalidraw leaf visible through both `getLeavesOfType()` and `iterateAllLeaves()`, plus `_loaded`, API readiness, closing/migration state, file match, and the selected route. The next reproduction must establish whether the popout is absent from type enumeration, rejected by the initialized-only filter, rejected by lifecycle/file targeting, or routed to ignore. Correct only the demonstrated boundary, then rerun this main/popout case before enabling or accepting 5b.5.
The follow-up trace resolves that routing question. In this session the affected popout is anonymous view 3. Across all 17 observed modifications it is returned by type enumeration, `_loaded=1`, API-ready, and matched to the modified file, but `closingOrMigrating=1`; `PluginFileManager` therefore takes its intentional lifecycle early return. This is not an initialized-view or file-target failure. View 3 also prepares and completes three later writes through `window-migration-persisted` (sequences 66–77, 146–157, and 257–268), proving `windowMigrating` itself remains active while the user continues editing. Do not merely bypass `isClosingOrMigrating()` in `FileManager`: that would let a source-runtime guard fail open.
The phase traces establish two different Obsidian operations. **Move to popout** completes `closeLeafView()` with `sourceStillLeaf=0`, then creates a distinct replacement (`sameAsSource=0`) that becomes API-ready and receives later updates. **Open in popout** invokes the callback while the newly created leaf's own view-state transition is still active: `closeLeafView()` resolves in the same millisecond with `sourceStillLeaf=1`, and replacement setup resolves with `sameAsSource=1`. That source object then becomes API-ready while retaining `windowMigrating`, so it is visible and writable but excluded from incoming synchronization. The correction preserves synchronous capture and pre-await unmount, completes any required save flush, then yields one main task on the destination window before calling `closeLeafView()`. This lets the outer state transition finish before the nested source replacement. The phase trace must now show `sourceStillLeaf=0` and `sameAsSource=0` for both opening modes; if either remains `1`, do not clear the migration flag or bypass the guard.
The reported 4,400-element lock/select latency reproduces on Excalidraw.com. Treat it as an upstream Excalidraw performance investigation unless a separate profile demonstrates additional plugin synchronization overhead; it is not evidence against the current persistence classification. The phase-observation build passes the focused classifier/snapshot/routing scripts, unused-symbol lint, focused lint, production build, bundle syntax, and `git diff --check`. `ExcalidrawView.ts` retains exactly its 18 established lint errors, the build retains the 33 established circular warnings, and the bundle is 4,914,732 bytes with SHA-256 `3c7607fbf2648cf162a4ad32e21f403f7427d068edad324524b3027e8f6f690e`.
## 8. Checkpoint 5b.5 — enable coalesced content matching
Keep the modify callback lightweight: initialized-target validation, existing routing, and marking latest-state work. For the incremental Markdown path, the view's pending-sync operation should own the fresh read and candidate comparison after acquiring the appropriate save/sync/lifecycle boundary. Reuse that read for parsing; do not create a separate per-event read/hash task ahead of it. Preserve raw `.excalidraw`, full-reload, explicit refresh, and same-file branches; either route them through a validated equivalent classification boundary or explicitly retain their safe behavior during staged rollout.
Logical operation (adapt existing code rather than introducing another loop):
1. Mark a current file as needing inspection; notifications while busy retain this demand.
2. Acquire the operation boundary without waiting on a whole save loop that is itself waiting for this sync. Revalidate the exact runtime/file after meaningful awaits; same path alone is insufficient for navigation away and back.
3. Claim the current pending marker before the read, preserving any later notification as trailing demand. Read current Vault text once, compare against valid success/acceptance identity, and parse only if reconciliation is needed.
4. On redundant content, do not alter newer local dirty revisions or manufacture a new save. On changed content, parse/reconcile through the tested pipeline and advance the accepted baseline only after successful application. If an editor acquires the file meanwhile, retain pending demand and wait for release.
5. Release ownership in `finally`; inspect any trailing demand, including one arriving between the last loop check and promise cleanup. Use existing bounded state if sufficient; add a notification epoch only if a proved gap requires it. Parse failure must retain valid live state without starting an endless retry loop on the same malformed bytes.
6. Save genuinely unpersisted reconciled state through the existing coordinator. Prove fairness between finite pending sync and trailing saves; no early return may strand a dirty revision behind a stale request.
Hashing must be browser/mobile-safe. Exact bytes are the write identity; if a fingerprint is used, document collision assumptions and failure behavior. Do not confuse the Excalidraw scene hash with a full-text fingerprint. Revalidate record/runtime after asynchronous digest completion. Timeouts only release abandoned records; expired records must not cause an otherwise unchanged document to start a save cycle.
Before removing `preventReload` storage/accessors, search **all** callers and classify their purpose: ordinary save echo, explicit force/reload request, same-file editor grace, migration, and teardown. Keep the successful 5a rule (no arming before serialization) until its replacement is accepted. Do not carry forward the failed patch's history mode, camera arguments, or dirty predicate simply because they are adjacent in the diff; each needs its own evidence and gate. If the same-file ownership gate is a prerequisite, execute checkpoint 8 explicitly before retiring those calls.
### 5b.5 implementation record
The staged implementation leaves the legacy Boolean storage and all existing callers in place, but it no longer allows that Boolean to discard a Markdown drawing notification. `PluginFileManager` consumes the one-shot flag for compatibility, then continues through the established route. Raw `.excalidraw` notifications still retain their former early return. Same-file embeddable callers still own `embeddableIsEditingSelf`; their Markdown notification becomes pending and waits at `acquireSynchronization()` until ownership releases.
The pending synchronization loop remains the only active read boundary. After acquiring save/sync/edit ownership, it claims the current marker, reads the latest Vault text once, and revalidates both file/runtime identity and target generation. Exact bytes classified as `matches-successful-write` or `matches-accepted-content` do not parse, publish, clear dirty state, or schedule a save. This remains true when a newer local revision exists: the disk content is redundant, while the later local revision remains dirty. Pending, failed, handed-off, different, or unknown identity follows the existing parse/reconciliation/accepted-baseline path. The temporary separate shadow-read loop was removed, so enabling the decision adds no diagnostic Vault read.
Executable checks cover Markdown deferral versus raw suppression and redundant/non-redundant classification, including successful bytes with newer local work. Classifier, snapshot, and route scripts; focused lint; unused-symbol lint; production build; bundle syntax; and `git diff --check` pass. `ExcalidrawView.ts` retains its exact 18-error baseline and the build retains 33 established circular warnings. The accepted instrumented bundle, including the **Open in popout** correction, was 4,913,456 bytes with SHA-256 `b5d3e75b650bfa20c54126710cb15bad3f01ecc730bdeca780cf39761980ecc0`.
The maintainer then accepted the instrumented runtime gate. Sustained work on the approximately 4,400-element drawing did not break save or synchronization. Additional passing cases covered an active back-of-note editor while switching tabs, adjacent Markdown and Excalidraw representations of the same note, dirty migration to a popout without a prior save, and switching an unsaved drawing to Markdown mode by hotkey. **Open in popout** now creates an updating replacement rather than leaving the visible source permanently migrating; **Move to popout** remains healthy. All changes were preserved.
Temporary fingerprints, anonymous-view enumeration, migration-phase logging, and classification-decision logging were then removed. A repository and rebuilt-bundle search finds no `EXCALIDRAW_PERSISTENCE_5B4`, `persistenceClassificationTrace`, or `persistenceClassificationFingerprint`. The first clean production bundle was 4,909,082 bytes with SHA-256 `a1b49ad6b31e527c291ecc0dfdcf585d20cb272da010f1068aa0859f8faa86a9`; it retained the 33 established Rollup circular warnings. The three executable checks, focused lint, unused-symbol lint, bundle syntax, and `git diff --check` passed; `ExcalidrawView.ts` retained exactly its established 18 lint errors.
That first clean build failed the **Open in new window** runtime case while **Move to new window** continued to work, so it is rejected as a checkpoint candidate. The accepted instrumented trace records `content-accepted` for the source view during the supposed timer boundary, before `closeLeafView()` succeeds. Removing fingerprint/logging work allowed the zero-delay destination timer to run before that asynchronous `setViewData()` continuation completed. The corrected invariant is therefore not “one timer has elapsed”; it is “the exact active view-data load has settled, followed by one destination task.” `setViewData()` now owns a bounded completion record, settles it on successful, early-return, and rejected layout-ready continuations, and migration captures the active promise before synchronous unmount. This is completion observation only: it does not invalidate loads, alter file identity, or claim the broader generation work of checkpoint 11.
The revised clean production bundle is 4,909,585 bytes with SHA-256 `15733871836c02a3dfcd84a3e9c817028ca34d153366b352c40c2c467f7a3982`. It contains no temporary trace prefix. The three executable persistence checks, unused-symbol lint, production build, bundle syntax, and `git diff --check` pass; `ExcalidrawView.ts` retains exactly its established 18 lint errors and Rollup retains 33 established circular warnings.
**Final 5b gate:** accepted. The maintainer confirmed the revised clean **Open in new window** path works correctly. The broader instrumented convergence and lifecycle cases listed above also passed, and **Move to new window** remained healthy throughout the clean-build regression comparison. One physical-mobile save/synchronization smoke test remains recommended before release, but checkpoint 6 may begin after the clean 5b commit.
## 9. Original checkpoint 6 — plugin-owned detached persistence
Start with ordinary dirty unload as its own change; migrate the special window-handoff path only after ordinary handoff is proven. Reuse the scheduling/cleanup lessons of `BackupPersistenceQueue`, not its entire policy: that queue currently drops pending work on `destroy()` and uses latest arrival, neither of which automatically provides source-document durability.
Define a data-only immutable request with operation/producer identity, file targeting information, captured revision, exact text, reason, and captured backup eligibility. Never retain view/Window/DOM/React/API/package lease references or callbacks closing over them. The plugin/main realm owns timers and execution and resolves the `TFile` at execution with `getFileByPath()`.
Required decisions before implementation:
- How the request relates to the last accepted source state and to newer live writes. View-local revisions cannot establish a global newest payload. If a successful-write sequence is introduced, define it at the actual ordered write boundary; assigning arrival tickets does not make two stale snapshots causally comparable.
- One active plus one newest trailing payload is safe only when the trailing candidate demonstrably supersedes the previous candidate. For independent producers, reuse any validated per-path reconciliation boundary from 5b.2 or explicitly resolve the conflict. Do not silently discard independent edits to preserve a queue-size target; if no safe bounded policy has been specified, stop and request the design decision.
- Separate `accepted/handed-off`, `persisted`, `superseded`, and `failed`. Replace `view-unload-scheduled` honestly. Decide how the coordinator/migration state represents pending responsibility without claiming Vault completion. Do not mark a handed-off revision as persisted merely to clear the old view's icon.
- Rename/delete/recreate-same-path behavior: resolve at execution but do not write stale text into a different file merely because the path exists again. Define cancellation/retargeting using the repository's lifecycle, not an invented permanent TFile ID.
- Shutdown/failure: define a bounded retained failure/reporting policy and flush opportunity; plugin unload/application exit may not await promises. An in-memory queue survives a view, not process failure. Do not add a hidden retry loop, recreate deleted files, or claim crash durability.
Keep live writes on `super.save()`. Preserve synchronous capture and source unmount before asynchronous migration work; popout-to-main final writing remains replacement/main-realm owned. Keep `ViewMigrationHandoffManager` drawing state separate. Deleting `ViewMigrationPersistenceHandoffManager` is the final proven consolidation, not the first edit.
**Tests:** dirty ordinary close; closing two views with distinct edits; old unload payload versus newer live save; immediate reopen; rename/delete/recreate; injected failure; source popout destroyed; dirty migration both directions; last popout close; plugin shutdown. Confirm no duplicate writes and no source runtime retained. Main-window ordering tests first, then native Electron teardown on available desktop systems and one mobile unload/navigation run.
### Checkpoint 6a implementation record — ordinary dirty unload only
The first increment replaces the view-owned 200 ms fire-and-forget callback only for ordinary `viewunload`. `executeSaveRequest()` hands the exact `PreparedSave` text and its producer, target-generation, operation, requested/captured revision, file path, captured file creation time, non-empty-scene eligibility, and `view-unload` reason to `ViewPersistenceQueue`. The save result is now honestly named `persistence-handed-off`; it transfers responsibility without publishing a successful-write identity. Normal live `super.save()`, both window-migration branches, drawing-state handoff, and migration persistence handoff are unchanged.
`ViewPersistenceQueue` is plugin-owned and contains only immutable request data plus a captured Vault capability. It resolves the current `TFile` immediately before execution and refuses a missing path, an empty payload, or a same-path file whose creation time differs. Requests execute FIFO per path and are never coalesced because independent view revisions do not establish supersession. Failures are contained so later requests still run, and they produce the existing long-lived serious-error notice plus structured error logging without file contents. The queue has no timer or listener and intentionally has no destructive unload cleanup: plugin unload begins asynchronous view conversions before their handoffs arrive, while completed path chains release themselves.
This increment does **not** solve or claim ordering between a detached request and a concurrent live `super.save()`, nor safe consolidation of two independently dirty closing views. Those remain checkpoint 6b design requirements. It also carries `hasNonDeletedElements` forward but does not write a BAK; that remains checkpoint 7. Do not collapse `ViewMigrationPersistenceHandoffManager` yet.
`node scripts/check-view-persistence-queue.mjs` verifies FIFO execution without coalescing, a blocked first write with a trailing request, missing and recreated targets, empty-payload rejection, injected write failure, later progress after failure, and flush settlement. Focused queue/main/coordinator lint, unused-symbol lint, the prior classifier/snapshot/routing checks, production build, bundle syntax, and `git diff --check` pass. Rollup retains 33 established circular warnings. The bundle is 4,911,256 bytes with SHA-256 `59b4e3a2c8184a3f77d7eb97d4d857c5b17a5e857c18e4bff7fd40132380c496`.
**6a runtime gate:** in the main window, edit a drawing and immediately close its tab without manually saving; reopen it only after a short settle and verify the edit is present. Repeat by switching an unsaved Excalidraw view to Markdown mode, and by disabling/reloading the plugin with an unsaved edit, then fully restart Obsidian and verify persisted contents. Repeat the immediate-close case once with the large compressed drawing to exercise serialization followed by retired-view writing. There must be no unhandled rejection or serious-error notice. A BAK update is not expected yet. Do not use two independently dirty closing views as an acceptance claim for 6a; record that separately for the 6b ordering design.
**6a runtime acceptance — 2026-09-13:** the maintainer accepted this increment after aggressive testing with five simultaneous representations of one drawing: one Markdown view, four Excalidraw views, adjacent views, a tab moved to a popout, and an independently opened popout. Persistence and synchronization remained stable and receiving viewports did not jump. A second test combined one mobile and two desktop views with parallel Markdown-embeddable editing. Obsidian Sync temporarily delivered malformed drawing JSON, which the existing Notice surfaced; after Sync settled, an explicit save persisted the latest valid scene and the file remained intact. A third mixed mobile/desktop/Markdown-view test remained stable under Sync latency. These results validate 6a's ordinary handoff in realistic lifecycle stress, but they do not prove the still-unimplemented 6b ordering between concurrent live and detached writers or migration-handoff consolidation.
### Checkpoint 6b.1 implementation record — physical write exclusion
`ViewPersistenceQueue.acquireWriteLease()` reserves the same FIFO path boundary used by immutable detached requests. The lease contains only an idempotent release function; the queue retains a promise gate, never the live `ExcalidrawView`, its callback, DOM, Window, React root, API, or package lease. `ExcalidrawView` invokes `super.save()` itself while holding the lease. The existing direct main-realm migration `vault.modify()` also holds the lease. For ordinary unload, the view acquires the lease, enqueues its immutable request behind that reservation, and releases; physical persistence then continues after the view can retire.
This increment establishes exclusion and accepted-operation order only. It does not reinterpret view-local revisions as a global sequence, coalesce independent producers, or claim that FIFO order merges two snapshots captured before either observed the other. The popout-to-main branch still transfers text through `ViewMigrationPersistenceHandoffManager`, and the replacement's later `vault.modify()` is not yet consolidated into this boundary. Those are explicit 6b.2 decisions, not hidden assumptions in the lease.
The queue check covers both directions: a live lease cannot overtake already accepted detached writes, and a detached request cannot execute while a live lease is held. Release is idempotent. The previous existing FIFO, missing/recreated target, empty request, failure isolation, later progress, and flush checks remain. Focused lint, unused-symbol lint, save-classifier/snapshot/routing checks, production build, bundle syntax, and `git diff --check` pass. Rollup retains the established 33 circular warnings. Candidate bundle: 4,912,110 bytes, SHA-256 `cb41dd492d89456811401685f3b32edb4f39de6a9f00292901dbfdf445823c3c`.
**6b.1 runtime gate:** first repeat ordinary save and immediate dirty close on one drawing. Then use two views with distinct visible edits: begin a large-scene save in one and immediately save or close the other; after settlement, both views and a reopened third view must contain both edits, with no save stall, dirty ping-pong, or viewport jump. Repeat with two dirty views closed in quick succession. These convergence cases are diagnostic as well as acceptance tests: exclusion guarantees non-overlap, but any lost independent edit proves that 6b.2 needs reconciliation before persistence rather than another ordering predicate. Finally smoke-test **Move to new window** in both directions because its direct main-realm write now uses the lease, and verify **Open in new window** remains unchanged. Do not accept migration-handoff consolidation from this increment.
**6b.1 runtime acceptance — 2026-09-13:** the maintainer reports the complete recommended gate passed successfully. This accepts the shared physical-write boundary for the tested large-scene live-save/dirty-close interleavings, rapid independent dirty closes, and both popout workflows. It does not retroactively claim that FIFO is a general merge algorithm; the specialized popout-to-main persistence transfer remains the next scoped change.
### Checkpoint 6b.2 implementation record — replacement-owned migration persistence
The specialized `ViewMigrationPersistenceHandoffManager` has been removed. `ViewPersistenceQueue` now stores the same immutable migration request used by detached persistence, including producer, target-generation, operation, requested/captured revision, file path, captured creation time, exact prepared text, non-empty-scene eligibility, and `window-migration` reason. `ViewMigrationHandoffManager` remains separate because it transfers live drawing-runtime state rather than persistence responsibility.
The source popout preserves the established destructive-boundary sequence: capture API-owned state and unmount synchronously before the first await, complete preparation, then register data only. Registration immediately reserves the shared per-path boundary but starts no Vault operation. The recreated main-window view consumes the matching leaf/path handoff and thereby initiates the queued physical write; it loads the exact handed-off text and waits for confirmed persistence before recording it as saved. Thus a later live or detached operation cannot overtake the migration write, while the source popout never starts the final Vault/native operation.
Consumption is one-shot and validates both leaf and file path. A mismatch releases its reservation, reports `target-changed`, and never exposes the other file's text to the replacement. Physical execution resolves the current `TFile` and validates its captured creation time through the same queue path as ordinary detached persistence. Failed writes remain visible through the plugin-owned serious-error notice/log path and leave the replacement dirty after loading the recoverable handoff text. An unconsumed handoff expires after 15 seconds on a main-window-owned timer, reports `handoff-expired`, and releases its path so later persistence cannot remain blocked. Explicit discard after failed source replacement releases ordering without writing. The queue continues to retain no view, Window, DOM, React root, Excalidraw API, or package lease.
Executable queue checks cover reservation without early writing, migration-before-trailing ordering, one-shot matching consumption, mismatch rejection without exposing text, discard progress, deterministic expiry progress, and all 6a/6b.1 FIFO, target, failure, and lease cases. Focused queue/main lint, unused-symbol lint, classifier/snapshot/routing checks, production build, bundle syntax, and `git diff --check` pass; `ExcalidrawView.ts` retains exactly its established 18 lint findings and Rollup retains 33 established circular warnings. Candidate bundle: 4,913,022 bytes, SHA-256 `aeb201a5cf81a49b99741ea5473b12094d21157c6d6f0a8650210d1162c3f680`. Runtime acceptance remains pending.
**6b.2 runtime gate:** first edit a drawing in a popout and use **Move to new window** to return it to the main workspace without manually saving. Verify the recreated view contains the edit, settles clean, and a reopened view reads it from disk. While that migration is in progress, make a distinct edit in another view of the same drawing; after settlement, both edits must converge without save stall, dirty ping-pong, viewport movement, serious-error notice, or duplicate write symptoms. Repeat main → popout to ensure its existing direct main-realm write remains healthy. Separately repeat **Open in new window**, which must keep both source and new views active and synchronizing; it is not equivalent to migration. Close the last dirty popout and test a large compressed drawing once. A deliberately failed replacement may pause same-path writes only until explicit discard or the bounded expiry; normal migration must not approach that timeout. Checkpoint 7 must not begin until these cases pass.
**6b.2 runtime acceptance — 2026-09-13:** the maintainer reports that the runtime gate passed successfully. This accepts replacement-owned popout-to-main persistence, its shared per-path ordering, and preservation of the two distinct popout workflows for the tested scenarios. Checkpoint 6 is complete. Work stops at this boundary; checkpoint 7 has not started.
## 10. Original checkpoint 7 — detached BAK after successful source write
Schedule BAK only from confirmed Vault completion using that operation's exact text and captured non-empty-scene eligibility. Do not inspect a retired view or a later live scene to decide whether the old write is safe to back up. Preserve the existing safeguard; its current element-count semantics must not silently change with tombstone representation.
Coalesced/superseded attempts that never write produce no BAK. Failed source writes produce no BAK. Integrate scheduling with existing main-window `ImageCache`/`BackupPersistenceQueue` storage rather than creating a second database or per-popout store. Order backups consistently with successful source writes, including live and detached completions. An older delayed callback must not replace a newer successful backup. Define source-write failure and backup-write failure as different results; a backup failure does not undo a source write.
**Tests:** exact payload identity, source failure preserving prior BAK, backup failure, empty scene, trailing supersession, slow older versus newer write, source close immediately after handoff, purge/clear with queued work. Verify durable backups are never treated as disposable preview cache. Keep recovery reporting plugin-owned and privacy-preserving.
### Checkpoint 7 implementation record — ordered exact-payload BAK
Every successful drawing persistence path now schedules recovery data from the immutable text and non-empty-scene eligibility captured by that operation. `ViewPersistenceQueue` schedules BAK only after its detached or replacement-owned migration `vault.modify()` resolves. A source failure, missing/recreated target, discarded or expired migration, and invalid request therefore cannot advance BAK. The queue never consults a retired view or later live scene.
Normal live `super.save()` and the direct main-realm migration write retain their existing persistence mechanisms, but their BAK scheduling now occurs immediately after successful completion and before releasing the shared per-path write lease. This closes an ordering gap in which a newer source write could previously complete and schedule its backup before an older live continuation scheduled afterward. All three paths use exact `PreparedSave.text`; the old live path no longer recaptures `lastSavedData`. The existing 50 ms delay and `hasNonDeletedElements` safeguard are unchanged.
The established main-window `ImageCache` and `BackupPersistenceQueue` remain the only BAK store and scheduler. Because successful source writes schedule while still ordered, its one-active/one-newest-trailing policy cannot allow an older delayed callback to replace a newer successful backup. Backup scheduling or IndexedDB failure is reported through its own `ImageCache` logging path and does not turn a confirmed source write into a source-persistence failure. Existing rename handling flushes pending BAK before moving the key, backup removal cancels pending work for the path, and clearing backups cancels all pending work before clearing the durable store. This remains in-memory scheduling rather than crash durability; no new retry loop, store, view reference, or popout-owned database was introduced.
Recovery validation exposed one stale-view callback independent of BAK generation: after corrupt-data handling called `setMarkdownView()`, the later confirmation callback still referenced `this.app`, although that originating `ExcalidrawView` could already be retired. The callback already captured stable `plugin`, `file`, and `leaf`; the restore write now uses `plugin.app.vault.modify()` as well. This changes no restore target or prompt policy and removes the dead-view dependency that made the first confirmation click reject.
`check-view-persistence-queue.mjs` now proves exact payload/order for detached and migration completions, source failure preserving the prior BAK, ineligible empty-scene persistence preserving it, and independent backup-scheduling failure. `check-backup-persistence-queue.mjs` proves pending latest-payload replacement, a newer trailing payload behind a slow active write, failure isolation with later progress, and cancel-all behavior used by backup clearing. Focused lint, unused-symbol lint, the persistence classifier/snapshot/routing checks, production build, bundle syntax, and `git diff --check` pass. `ExcalidrawView.ts` retains exactly its established 18 lint findings with none in the changed range, and Rollup retains 33 established circular warnings. Revised candidate bundle: 4,913,587 bytes, SHA-256 `ccd00809e6b87ef4b05bac43bd389f845e66d0a4ffd3212b47c5518b29737e53`. Runtime acceptance remains pending.
**Checkpoint 7 runtime gate:** use disposable drawings because recovery is deliberately exercised. First make a non-empty edit, save normally, wait for the short BAK delay, deliberately corrupt only the disposable drawing JSON in Markdown mode, and verify the first confirmation click restores the exact last successfully persisted scene without an unhandled rejection. Repeat after editing and immediately closing an Excalidraw tab, and after a dirty popout → main migration, to cover both detached paths. For ordering, make distinct rapid changes from two open views, let persistence settle, corrupt the source, and verify the recovered BAK matches the final disk state rather than an older completion. A BAK cannot merge edits from views that were already divergent when independently closed; that is a synchronization/convergence limitation, not a backup-order guarantee. Establish a known non-empty backup, then persist an empty scene and verify that later recovery retains the prior non-empty backup. Finally smoke-test saving followed immediately by renaming the drawing and confirm recovery is available at the new path. There must be no save stall, dirty ping-pong, viewport movement, serious source-persistence notice, duplicate backup prompt, or BAK stored under the retired path. Automated injection covers source/backup failures and clear/cancel ordering; do not manufacture an IndexedDB failure in the primary vault.
**Checkpoint 7 runtime acceptance — 2026-09-13:** the maintainer accepts the revised candidate for commit. Small-drawing synchronization and recovery worked. Aggressive testing with two already-divergent very large views produced a BAK containing the final independently persisted snapshot rather than a union of both views; this is the documented non-merge limitation of complete-snapshot persistence and does not contradict BAK payload/order semantics. The asynchronous first-click recovery failure was traced to and corrected as described above. Checkpoint 8 may begin after the checkpoint 7 commit.
## 11. Original checkpoint 8 — same-file edit ownership gate
Read the complete entry/flush/release paths in `CustomEmbeddable.tsx`, `MarkdownImageEditor.ts`, and the view's self-edit guard methods. Identify whether ownership is view-local, per file, or shared between paths before selecting storage scope; changing scope to plugin-global is a behavior change, not an accessor rename.
Specify idempotent `acquire(ownerId)`, `release(ownerId, graceMs)`, `hasActiveOwners`, `isInGracePeriod`, `isBlocked`. Different simultaneous editors need distinct IDs; repeated acquire from one owner must not leak a counter. Final-owner release starts the relevant grace period; reacquire cancels/replaces only the appropriate release state. Old timers must not unblock a new owner or a different file. Distinguish editor flush completion from its UI closing.
Resume pending latest-state synchronization after release/grace without another modify event. Preserve raw Markdown and explicit bypass/force-save semantics. Replace clear/re-arm workarounds only after their original ordering is reproduced by the new gate. Ensure editor teardown releases ownership even on failed saves, without claiming the failed content persisted.
**Tests:** two overlapping owners, switching image editors while the old one flushes, Canvas self-embed plus image editor, reactivation during grace, final Markdown modify during grace, external drawing change held pending, navigation/close/migration, and touch edit/exit on a physical mobile device. Add no new debounce duration without measured need.
### Checkpoint 8 implementation record — view-local multi-owner gate
`ViewSemaphores.embeddableIsEditingSelf` and its single reset timer are replaced by a view-owned `SameFileEditGate`. The gate keeps idempotent active-owner identities and independent per-owner grace records. Reacquiring an owner cancels only that owner's pending release; timer callbacks verify their exact timer identity before deleting state, and each timer is cleared through the `Window` that created it. Destruction cancels every pending release and active owner. The existing 2,000 ms release grace is retained; no new delay or plugin-global lock was added. The no-argument view methods preserve their former compatibility behavior, while new feature-owned callers use explicit identities.
Canvas/back-of-note ownership is keyed by Excalidraw element ID and is released by edit exit, startup failure, node removal, factory purge, or view teardown. Canvas edit entry is fenced by a per-node request identity across its pre-edit force-save: exiting or removing the node during that await invalidates the continuation and releases ownership before `node.startEditing()` can run. The Markdown-image editor assigns one unique controller ID and holds it across render, force-save, and raw-data refresh. Selection without a Markdown image, controller invalidation/handoff, and close release that exact controller. Old and new controllers therefore cannot clear each other's ownership while an editor flush is in flight. The prior Markdown-image clear/re-arm sequence around `reload()` is removed because reload no longer mutates ownership.
When a same-file owner blocks a drawing modify, `reload()` may refresh the raw Markdown envelope but now also arms the existing one-per-view latest-state synchronization marker. Its existing acquisition loop waits through all active owners and grace records, then rereads the latest Vault contents before parsing and reconciliation. No modify event is consumed merely to end a grace period, and no extra event or rescue edit is required after release. Force-save bypass semantics, raw `.excalidraw` routing, incremental merge behavior, viewport protection, and non-undoable incoming publication remain unchanged.
Initial runtime validation exposed one migration boundary not covered by the normal drain. A back-of-note modify could be pending behind the gate when the source was moved to a new window. Migration invalidated that synchronization, captured the drawing, and later serialized it against the source view's older `data` envelope; the delayed migration write could therefore remove Markdown already visible from the Vault. Whether this interleaving predates checkpoint 8 is not inferred, but it fails checkpoint 8's required migration gate. The source still captures and synchronously unmounts before its first await. After unmount, a Markdown migration save now honors the already-established same-file grace when necessary and rereads the current Vault text before serialization, combining the captured scene with the latest Markdown envelope. Compatibility-mode JSON and migrations without evidence of pending same-file synchronization retain their existing path.
The next large-scene runtime test demonstrated a deletion after a Markdown-image editor in view A was reopened while view B had a new shape not yet visible in A. An owner-specific pre-save reconciliation was implemented as an experiment, but its next runtime test failed earlier: after leaving the editor in A and adding the shape in B, the shape was removed as soon as A's Markdown-image update reached B, before the editor was reopened. That result rejects the experiment and does not establish its proposed stale-save explanation. The complete tracked experimental state is preserved in `refs/stash` as object `8e69125349180b35fc4a534801bbbd79b430e688` (recorded as `stash@{0}` when stored); use the object ID because stash indices move, and do not reapply it as a group. The owner-specific bypass, active-image preservation, accepted-text mutation, and added pre-save calls have been removed. The independently confirmed migration-envelope correction and the core gate remain.
Temporary `EXCALIDRAW_PERSISTENCE_8` diagnostics now record one fully rendered console string per event. They cover same-file ownership acquire/release, dirty revisions and scene counts, save start/result, modify routing with receiver dirty/busy state, full reload/defer/completion, synchronization request/read classification, and incoming/local/merged counts. Their sole first gate is the simpler failure: edit a Markdown image in A, click B so the editor clears, add one distinct shape, and stop when the Markdown update removes it. Copy the complete filtered trace from before the handoff through deletion. The decisive first question is whether B took `full-reload` while its local shape was not yet represented as dirty, or entered `incremental-sync` and lost the shape during or after merge. Do not add another reconciliation rule until the trace establishes that transition.
The first supplied trace rejects both branches of that initial diagnostic question. Receiving view `cd0e817d0c5008b2` records its local edit as dirty and increases from 4,421 to 4,422 elements at sequence 128. It then selects `incremental-sync` at sequence 129 and acquires synchronization with all 4,422 elements still present at sequence 133. No `sync-read`, `sync-merge-start`, `sync-scene-updated`, full reload, or reload completion appears before the captured trace ends. Source view `f34f52c2bd1b4522` independently completes a 4,421-element write. Therefore the evidence does not attribute the deletion to routing or the merge; either the deletion occurs after the last captured event or another scene-publication path is responsible. Instrumentation now also covers every view-wrapper element publication plus `setViewData()` and `loadDrawing()` entry/publication, without changing their behavior. The next capture must include at least five seconds after the visible deletion so an already-running Vault read/parse can finish and log its outcome.
The expanded trace establishes the first destructive transition. View B records its local shape as dirty and increases from 4,420 to 4,421 elements at sequence 27. Its incremental synchronization then merges A's 4,420-element file while retaining all 4,421 live elements at sequences 40–44. A later Markdown-image-editor handoff performs `reload(false, file)` in B and completes with 4,421 elements at sequences 70–74. That successful non-full reload nevertheless clears `textFileViewLoadedFile`. Consequently, the next ordinary same-file `TextFileView.setViewData()` reports `sameLoadedFile=false` at sequence 119, enters new-load initialization, and publishes A's 4,420-element disk snapshot over B's 4,421-element live scene at sequence 123. This is the observed deletion; neither the modify route nor incremental merge removed the shape.
The corrective rule is deliberately scoped to that boundary: a successful non-full reload triggered for the current modified file retains `textFileViewLoadedFile === this.file`. Such a reload refreshes the Markdown envelope while intentionally retaining the reconciled live scene, so the following base-class delivery is a duplicate bridge notification and must take `setViewData()`'s existing same-file early return. Full reloads, settings reloads, initial/different-file loads, compatibility behavior, modify routing, and merge policy retain their existing marker behavior. `shouldRetainLoadedFileAfterReload()` makes this two-input decision executable; its check covers the exact case plus full-reload, non-modify, and combined negatives.
The maintainer confirms both targeted scenarios pass: the simple editor-handoff/add-shape case and the extended reopen-editor/**Render now** case. The traces corroborate the outcome: same-file base deliveries report `sameLoadedFile=true` and take the early return, while incremental merges retain 4,421 elements and later propagate that union to the other view. No destructive 4,421 → 4,420 publication recurs.
All temporary `EXCALIDRAW_PERSISTENCE_8` source instrumentation and its helper are removed. Searches of `src/` and the rebuilt bundle contain no prefix. `check-same-file-edit-gate.mjs` covers repeated acquire, overlapping Canvas/Markdown owners, independent grace expiry, reacquisition in a different owning window, stale callback rejection, same-owner release refresh, legacy release cancellation, unknown release, and teardown. Reload-policy, snapshot, content-classification, modify-routing, detached-persistence, and backup-queue checks pass. Focused lint is clean outside the established 18 findings in `ExcalidrawView.ts` and one in `CustomEmbeddable.tsx`; unused-symbol lint, production build, bundle syntax, and `git diff --check` pass with the established 33 Rollup circular warnings. Clean candidate bundle: 4,915,827 bytes, SHA-256 `555d6a2aeae81d8dbc6644342ecdde95126c311d8fcc16df1038588e11eaddcd`. Broader checkpoint-8 runtime acceptance remains pending.
Subsequent broad runtime validation retained all changes, including the previously failing Markdown-image/shape interleavings. One migration boundary remains unresolved: after editing a Markdown image and immediately migrating its tab to a popout, the main-workspace peer displayed the serious-save warning and `ViewPersistenceQueue` reported `Migration persistence handoff expired before replacement`. The expiry proves that a source save registered an immutable persistence handoff and no matching consumer removed it during its 15-second lifetime. It does **not** prove why. Static inspection identifies a contract asymmetry worth measuring but not yet changing: source registration is selected from the source package window, while `setViewData()` attempts persistence consumption only when the replacement reports `isInMainObsidianWorkspace`. A delayed or absent replacement `setViewData()`, an early same-file return, or a target mismatch remain possible.
Temporary `EXCALIDRAW_MIGRATION_HANDOFF` diagnostics therefore cover only the decisive boundaries and emit one complete copyable string without paths or contents: callback source/destination realm and relevant state; save flush and source registration; close/replacement request; replacement `setViewData()` entry/early return and destination realm; and queue register, consume attempt/match/miss/target mismatch, and expiry. They do not alter the 15-second TTL, queue reservation, migration branch, write timing, or warning policy. Reload-policy, same-file-gate, and persistence-queue checks, focused diagnostic/queue lint, unused-symbol lint, production build, bundle syntax, and `git diff --check` pass. The instrumented bundle is 4,919,089 bytes with SHA-256 `d1369924a12c095a9f31cab930347a01e673e13c8c5b81c363980a4136002ce7`; Rollup retains 33 established circular warnings. The next gate is the exact immediate Markdown-image edit → tab migration reproduction. If the warning appears, wait beyond 15 seconds and copy all strings containing the prefix from before migration through expiry. Do not lengthen the timeout or broaden consumption until this trace identifies the missing transition. Remove the diagnostics before checkpoint-8 commit.
The resulting trace proves an ordering failure rather than a timeout or destination-realm failure. For leaf `cd0e817d0c5008b2`, popout→main migration began clean at 340,322 ms, closed and requested its replacement by 340,398 ms, and the replacement checked an empty persistence queue at 340,808 ms. A Markdown-image owner invalidation that had escaped the migration wait then completed its forced save against the retired source: it registered operation 1/revision 39 at 342,252 ms, 1,444 ms after the only consumer check. With no later replacement to consume it, the reservation expired exactly at 357,252 ms. The stack identifies `MarkdownImageEditorController.invalidateOwner()` reached from its view-attachment path. Earlier dirty popout→main migrations in the same trace demonstrate the intended order: registration precedes replacement creation and the matching consumer removes the handoff within tens of milliseconds.
The correction makes Markdown-image invalidation part of the migration boundary. Migration now starts or joins the active controller's invalidation synchronously before capturing API-owned state. The nullable completion reports ownership synchronously, so the migration retains a save snapshot even if the editor flush has not yet advanced dirty state. It then unmounts the source React root before its first `await`, awaits the editor invalidation, and only then proceeds through save flush, source close, and replacement creation. Thus the editor's forced save must either finish/register before replacement `setViewData()` or fail within the awaited owner operation; it cannot register after the consumer has passed. The invalidation path also skips its normal post-save `reload(false, file)` for a closing or migrating source runtime. No queue TTL, persistence-consumption guard, write ordering, or fallback write was changed.
Reload-policy, same-file-gate, and persistence-queue checks pass. Focused lint is clean for the diagnostic, queue, and Markdown-image editor; `ExcalidrawView.ts` retains exactly its established 18 findings. Unused-symbol lint, production build, bundle syntax, and `git diff --check` pass with the established 33 Rollup warnings. The corrected instrumented bundle is 4,919,403 bytes with SHA-256 `5e7f731476669c4853b84def675fdd748af17a605684581977cbc80820d0ea57`. Keep diagnostics for the runtime gate: repeat rapid Markdown-image editing and popout→main migration until the formerly rare branch is exercised. For a source save, the same leaf must show `persistence-register` before replacement `persistence-consume-match`; there must be no `persistence-expired`, serious-save warning, lost content, or source reload. Remove diagnostics before checkpoint-8 commit.
The maintainer then stress-tested repeated Markdown-image edits and main↔popout migration and could not reproduce an error or lose changes. The trace repeatedly exercises the exact popout→main handoff boundary. Source registrations occur before `migration-editor-unload-complete`, save flush, source close, and replacement request; each replacement then consumes the same leaf's pending handoff. Several complete examples include operations/revisions 1/37, 1/40, 3/62, 3/82, and 1/10. The slowest captured replacement did not enter `setViewData()` until approximately 11.3 seconds after registration and consumed with 2,954 ms left on the unchanged TTL, while ordinary cases consumed within roughly 60–130 ms. There is no expiry event. This directly validates the new register-before-replacement invariant under both common and delayed replacement timing.
All temporary `EXCALIDRAW_MIGRATION_HANDOFF` source instrumentation and its helper are removed, and searches of `src/` and the rebuilt bundle contain neither the prefix nor helper symbol. Reload-policy, same-file-gate, persistence-queue, save-snapshot, content-classification, file-modify-routing, and backup-queue checks pass. Focused lint is clean for the queue and Markdown-image editor; unused-symbol lint, production build, bundle syntax, and `git diff --check` pass with the established 33 Rollup warnings. Clean checkpoint-8 candidate: 4,916,026 bytes, SHA-256 `e2851c6b6cddd219d7ff86bb931b38710426350c795cac8daea6acfd6eac3e74`. Checkpoint 8 awaits explicit commit direction; do not restore either temporary diagnostic helper.
**Remaining checkpoint 8 runtime gate:** retain the accepted back-of-note paragraph → immediate **Move to new window** result. Use two small side-by-side views to hold a back-of-note embeddable active in A, edit the scene in B, exit the embeddable, and make no further input; A must receive B's pending scene change after the grace period, remain viewport-stable, and settle clean. Repeat Markdown-image switching, hiding/reopening the sidepanel, and closing it during a save. Then overlap a Canvas self-embed and the Markdown-image editor so releasing either one alone cannot unblock synchronization; release the final owner and verify the newest Vault state appears without another modify or force save. Reactivate an owner during its grace period and verify no early reload, loss, dirty ping-pong, or undo entry. Repeat navigation away/close and the distinct **Open in new window** path. Finally run the alternating-edit large-scene smoke test and one physical-mobile touch edit/exit. The highest-risk remaining failure is an owner leak or premature final-owner release; either would leave synchronization permanently blocked or allow a destructive same-file reload during overlapping editors.
## 12. Original checkpoint 9 — finish the normalized snapshot contract
Extend accepted 9a/5b.3 rather than recapturing the live API after persistence. `PreparedSave` should retain the normalized scene and settings/input identity needed by secondary outputs, as well as exact source text. Normalization may clear runtime file payloads; preserve or resolve the corresponding export assets without reading a later live view's scene.
Specify ownership of embedded-file metadata, Markdown/equation references, deletions, selection, app-state export options, and file path. Reference-based external assets may themselves change while exporting: document whether fidelity means source-scene revision or also frozen dependency contents. Do not promise historical external-asset bytes unless captured; avoid embedding all large image payloads by default. Persisted unknown/custom fields must survive.
**Tests:** full-scene versus selected export, parsed/raw text, equations, Markdown images, PDF crops, app-state-only edits, deleted elements, normalization during concurrent editing, migration, and peak retained memory while one operation plus a trailing operation exists. Releasing a view must not leak a snapshot through callbacks.
### Checkpoint 9 implementation record — detached normalized export input
The save capture now records the source file creation time and the export settings that can affect automatic secondary output: theme, embedded-scene policy, padding, scale, background, internal-link handling, and mask status. Checkpoint 9 initially reused an already-open export dialog when present. Checkpoint 10 supersedes that behavior for automatic output: every save reads current frontmatter/plugin helpers directly, while manual exports retain dialog state. This captures the choices associated with the saved revision without retaining a dialog.
`ExcalidrawData.syncElements()` normalizes the save-owned cloned scene and, in the normal Markdown format, clears `scene.files` after synchronizing assets. `SaveSnapshot` therefore keeps a separate cloned `exportFiles` collection captured before normalization. `createPreparedSave()` runs only after serialization and creates a second detached scene containing the normalized elements/app state plus those captured binary payloads. It also detaches deleted elements, selected IDs, and export options. Later API edits, continued normalization, or mutation of the temporary save snapshot cannot change the prepared scene. Reference-based Markdown/PDF/external dependencies remain references resolved at export time; this checkpoint does not promise historical dependency bytes.
The heavy `PreparedSave` is operation-scoped. `ViewSaveCoordinator` and content classification now retain a separate `PreparedSaveIdentity` containing only operation/revision/path, exact serialized text, and non-empty status. This preserves exact-content echo classification and BAK eligibility without indefinitely retaining a second 4,400-element scene after save completion. Checkpoint 10 may transfer the heavy prepared value into a plugin-owned autoexport request, but must release it after the active/trailing export settles and must not make source persistence await rendering.
Automated validation covers capture-before-normalization file preservation, save-time normalized element changes, detachment of prepared scene/deletions/selection/options, and removal of heavy scene fields from retained identities. Snapshot, content-classification, reload-policy, same-file-gate, persistence-queue, modify-routing, and backup-queue checks pass. Focused lint, unused-symbol lint, production build, bundle syntax, and `git diff --check` pass with the established 33 Rollup warnings. Candidate bundle: 4,917,634 bytes, SHA-256 `d69ccc4e2b9d5350f75c3b005f6c4c661d2b6aca006f78a2738e48a88d31e9cb`.
**Remaining checkpoint 9 runtime gate:** save the 4,400-element/500+-Markdown-image fixture repeatedly and compare peak, settled, and explicit-GC memory across several cycles. A temporary peak is expected because the operation owns both its working snapshot and final detached prepared scene, but settled memory must not rise monotonically. Verify parsed Markdown and compatibility/raw drawings containing a normal image, Markdown image, equation, links/bindings, deleted elements, and selection changes; save while making a newer edit, reopen, and require the newer dirty revision to survive the older completion. Repeat side-by-side alternating edits, dirty close, dirty **Move to new window**, and **Open in new window** as regression smokes. Changing export settings/frontmatter before save must not affect source persistence; matching autoexport output is checkpoint 10's acceptance gate, not checkpoint 9's.
**Checkpoint 9 runtime acceptance — 2026-09-13:** the maintainer reports all requested persistence, side-by-side, migration, raw/parsed, and large-scene tests passed. Memory returned to its original value after explicit garbage collection, confirming that the coordinator's lightweight retained identity does not pin the heavy prepared scene.
## 13. Original checkpoint 10 — autoexport fidelity, then ordering
**10a:** Make automatic `saveSVG`, `savePNG`, and raw `.excalidraw` output consume the successful `PreparedSave`, including normalized scene/options/path. Inspect `ViewExportManager`'s downstream `loadFilesForExport` and option getters: passing only a scene argument is insufficient if they still consult a later live model. Preserve manual exports' live-scene behavior and existing autoexport trigger policy, including blur and forced-save distinctions. Never export a failed/merely handed-off source request as a successful source revision.
**10b:** Add one active export and one newest eligible trailing export per source/format/theme, ordered by the validated source-persistence identity. Per-view revision maximum is invalid. Check resolved output-path collisions across formats/themes/renames too. Serialize or reject obsolete completion before the final output write so a slow old render cannot overwrite a newer export. A queued old autoexport must not write to a renamed/recreated target without an explicit path policy.
Do not make source persistence wait for slow image rendering/export completion. Detached autoside-effect behavior must be specified separately; never retain a retired view merely to finish an export. Raw `.excalidraw` autoexport can participate in existing modify/compatibility routing; test that it does not create another feedback loop.
**Tests:** N saving while N+1 is edited, slow N rendering versus N+1, two source views, light/dark outputs, source failure, export failure with newer trailing success, rename, close, manual export during queued autoexport, and matching exported elements to the saved source scene rather than the latest API scene.
### Checkpoint 10 reviewed action plan and implementation record
The first checkpoint-10 draft is rejected as a commit candidate. Although it rendered the prepared scene, it still completed through the originating `ExcalidrawView`. Dirty close and migration returned before scheduling output, so their persisted drawing revision produced no image exports; a view retired during rendering also made `getHookServer()` dereference cleared plugin/EA state. The draft retained mutable `EmbeddedFile` descriptors, had no cross-save completion order, duplicated alternate-theme asset preparation between SVG and PNG, and left `createOrOverwriteFile()` exposed to a check/create race. Do not restore that view-owned completion model.
Implement and retain the following sequence as one revised checkpoint-10 candidate:
1. **Freeze render inputs at save capture.** `PreparedSave` owns the normalized scene, autoexport policy, export options, and—when SVG/PNG rendering is enabled or a trigger hook may enable it—detached data-only embedded-file states. Raw-only, autosave, and no-output saves do not pay that registry-copy cost. The state includes cached light/dark data URLs, resolved path/link metadata, color map, PDF crop/render scale, Markdown-image source, equation source, Markdown render defaults, and PDF scale. Copy nested mutable records both into `SaveSnapshot` and from snapshot into `PreparedSave`; never share the live `EmbeddedFile` object. Immutable data-URL strings may be shared. External Markdown/PDF/image file bytes remain reference-resolved at execution time and are explicitly not a historical-byte guarantee.
2. **Materialize view-dependent policy before retirement.** While the source view is valid, run `onTriggerAutoexportHook` and `onImageExportPathHook`, capture the final normalized destination paths, and reduce a request with no enabled outputs to a lightweight persistence barrier. Preserve the hook's historical extension values: a one-theme default path remains `.svg`/`.png`, while the hook receives `.light.svg`, `.dark.svg`, `.light.png`, or `.dark.png`; paired outputs use their suffixed paths and extensions. Hook failure must be contained and must fall back to a barrier rather than cancel or reclassify source persistence. `onImageFilePathHook` remains exclusively on the image-import path and is unchanged. For detached close/migration, hook materialization necessarily occurs before the final write, because retaining the hook server would retain view/runtime state; normal live-save hooks still run after the established source-write boundary.
3. **Publish from every successful persistence route.** Normal live `super.save()`, direct main-realm migration writes, replacement-owned migration handoffs, and ordinary detached close all submit the prepared render request only from their established successful-write boundary. `ViewPersistenceQueue` invokes its completion callback after the exact write and BAK scheduling but before releasing per-path order. Completion-callback failure is isolated from the already successful source result. A merely registered handoff, failed write, missing/recreated source, or known no-write force/reload branch submits no render request. Saves for which automatic output is intentionally disabled submit only a lightweight barrier so an older active export cannot later claim to represent the newest persisted source.
4. **Own execution in the plugin/main realm.** `AutoexportCoordinator` retains no view, `Window`, DOM, React root, API, export dialog, package lease, or hook callback. It re-resolves the captured source path and creation time before rendering and again immediately before output writing. A renamed, deleted, or same-path-recreated source cancels the old request; it is never silently retargeted. Heavy work starts on a main-window task after queue order has been assigned, allowing source persistence to release its path lease without synchronously cloning or stringifying the large scene. Plugin unload invalidates scheduled, trailing, and not-yet-writing work so a previous plugin runtime cannot publish later; an already-issued Vault write cannot be canceled.
5. **Bound and order output work.** Source identity is `path + creation time`, and enqueue order comes from the accepted physical source-persistence boundary rather than incomparable per-view revisions. Keep one active whole-request render and one newest trailing request per source; replacing a trailing request releases its destination claims. A global accepted sequence also tracks every hook-resolved destination, covering collisions across source views, source files, formats, and themes. Recheck source freshness and destination freshness inside a per-destination async lock immediately before the final Vault write. Thus an old render may finish computation, but it cannot overwrite a newer accepted destination. If multiple outputs in one request resolve to one path, the last planned output wins without rendering the displaced formats. Rendering or diagnostic failure must not strand the trailing request.
6. **Reuse work and make final writes race-safe.** Raw `.excalidraw`, SVG, and PNG outputs for one source revision execute sequentially, bounding concurrent large-scene memory. Each render receives a fresh scene clone, but the coordinator prepares theme-dependent assets only once per theme and reuses that result across SVG and PNG; the captured source-theme data URLs are reused without reloading. Alternate-theme preparation recreates mutable loader descriptors from detached state and uses captured Markdown/PDF render defaults. `createOrOverwriteFile()` converts `Blob` before inspecting the target, tolerates a concurrently created output folder, and recovers a file-create race by resolving and modifying the file that won creation. Existing manual export commands remain current-live-scene operations and keep their established hook path.
7. **Resolve live settings and prioritize migration/UI work.** Automatic save capture reads export theme, background, padding, scale, embedded-scene, internal-link, and mask policy directly from current plugin settings/frontmatter helpers; it never reads the potentially long-lived `ExportDialog`. Manual commands continue to honor their live dialog state. A successful migration write immediately submits a lightweight source barrier, invalidating older output without starting a render. Its render request is held by leaf identity until the replacement view's existing `setViewData()` load completion reports success for the same file path. Load failure/path mismatch discards the render, and a 60-second main-realm timer only cleans up an abandoned record; it is not used to guess migration completion. All automatic render requests share one global execution lock and yield a browser task before each requested format, allowing input, paint, and lifecycle tasks between raw/SVG/PNG work. One Excalidraw SVG or PNG render remains synchronous main-thread work and cannot be preempted or honestly described as worker/background execution; source persistence and migration completion never await it.
8. **Coalesce the complete save batch before rendering.** First-active/newest-trailing export queuing bounds memory but does not prevent an early snapshot from rendering while a large drawing still has trailing saves. Each view-owned `ViewSaveCoordinator` therefore marks its complete save-loop lifetime against the plugin-owned `path + creation-time` source identity. Detached and replacement-owned physical writes mark the same activity boundary. Every successful persisted snapshot still submits an immediate lightweight barrier, so an older render can never write after the newer source state is accepted, but the detached render request remains only as the newest pending state. Rendering is released after all known activity for that source reaches zero and a 500 ms quiet-settle timer completes; a newer activity or persisted snapshot cancels/restarts that timer. Autosave now captures and publishes its prepared render state instead of a no-output barrier, ensuring a burst whose last physical write is autosave can still produce output matching the final persisted drawing. If a previous batch's non-preemptible renderer was already executing before a genuinely new edit burst began, it may finish computation, but source/destination guards prevent its obsolete write and the new batch renders once it settles.
The ordering unit covers active N, replaced N+1, newest trailing N+2; cross-source destination collision; a newer no-output barrier; render failure followed by trailing success; logger failure containment; and same-destination serialization with independent-destination progress. Snapshot validation mutates live and intermediate embedded-file metadata/defaults and proves that the prepared request remains detached. Detached-persistence validation proves that only successful writes publish completion and that a completion callback cannot change a successful persistence result.
The output still intentionally uses current external dependency bytes at execution time. SVG link conversion and file-derived CSS classes also use current Vault/metadata state. These are presentation/dependency inputs, not the saved drawing scene, and freezing their bytes or the entire metadata cache is outside checkpoint 10. If that distinction becomes user-visible, open a separately scoped design checkpoint rather than retaining a view.
Automated validation passes for save-snapshot detachment, save-content classification, TextFileView reload policy, same-file ownership, detached persistence and completion-callback isolation, file-modify routing, BAK ordering, autoexport coalescing/obsolescence/failure recovery/deferred start/unload invalidation, save-batch activity/coalescing, focused lint, unused-symbol lint, production Rollup build, bundle syntax, diagnostic-prefix search, and `git diff --check`. The save-batch test proves two simultaneous activities hold N/N+1, a new persisted N+2 restarts the settle timer, only N+2 is released, and a final no-output state cancels pending work. The persistence test proves detached and migration activity spans each complete physical write. `ExcalidrawView.ts` retains 17 established unrelated lint findings and none is in either changed range. Rollup reports the established 33 circular-dependency warnings and no TypeScript warning. Candidate `dist/main.js`: 4,932,865 bytes, SHA-256 `a074d3522e830bac296b46d25ccfede2cde5ffe2926bc4db19f857a1e5ba1a89`.
**Revised checkpoint 10 runtime gate:**
1. Enable SVG, PNG, and raw `.excalidraw` autoexport for one theme. Save an identifiable revision N and immediately add an obvious N+1 change while N renders. No N output may contain unsaved live N+1; after N+1 persists, every final output must represent N+1 even if N was slower.
2. Repeat with two views of one drawing and deliberately overlap saves. Test both an already existing destination and first-time creation of missing SVG/PNG files. There must be no `File already exists`, retired-view `getHookServer`, unhandled promise, or serious-save error, and the eventual output must correspond to the last persisted request.
3. With the large fixture, include normal images, nested Excalidraw, Markdown images, equations, PDF crops, back-of-note cards, internal/external links, bindings, and color-mapped SVG. Verify visible content in single-theme and paired light/dark output. Modify a captured embedded link/color map or Markdown/PDF render setting while an older export is delayed; the older render must retain its captured descriptor/default values, while external source-file bytes may legitimately resolve to their latest version.
4. Reproduce the two reported durability gaps: make a dirty edit and immediately close the tab; then repeat with dirty **Move to new window**, **Open in new window**, popout-to-main migration, and switching to Markdown mode. After a short settle, source Markdown and enabled outputs must all exist and represent the persisted scene. Neither source persistence nor migration UI should wait for image rendering to finish. Separately disable/reload the plugin during a slow export: drawing persistence must remain safe and no old-runtime output/error may appear afterward; completion of secondary output is deliberately not promised across plugin unload.
5. Exercise `onTriggerAutoexportHook` enabling/disabling formats and `onImageExportPathHook` routing each format/theme, including two outputs deliberately mapped to the same destination. Confirm the hook receives the source `TFile` and historical extension strings described above; for a same-request destination collision, confirm the last planned output is the one written. Confirm image insertion still invokes `onImageFilePathHook` unchanged. Hook exceptions or invalid paths may suppress that revision's output but must not lose the drawing, suppress BAK, or block a later valid export.
6. Rename, delete, and recreate the source while an export is delayed. The old request must not write after source identity changes; a later save at the new/current identity must export normally. Force an output failure if practical, then make a newer save and require the newer output to complete.
7. Trigger manual SVG, PNG, raw, clipboard, and selected-only exports while an automatic export is queued. Manual exports must continue to use the current live/selected scene and current dialog settings. Concurrent Vault destinations must not throw a create collision; manual and automatic output of the same path is not assigned a new cross-feature winner policy in this checkpoint, so record the observed final writer if testing that exact collision.
8. Repeat several large-scene save/export cycles while recording peak, settled, and explicit-GC memory plus perceived save/close responsiveness. One prepared request, one active render clone, one theme asset set, and at most one trailing source request are expected. Settled memory must not rise monotonically, source save must not await export completion, and SVG/PNG for the same theme must not visibly perform duplicate asset-reload waves.
9. Run a physical-mobile smoke test with one normal image, Markdown image, and equation. Automatic PNG/SVG generation must complete without Node-only assumptions or a retained desktop/popout runtime.
**Focused follow-up gate after initial runtime testing:**
1. Keep one Excalidraw view open, change **Export image with theme**, make another edit/save, and inspect the next SVG/PNG without reopening the drawing. Repeat for the opposite theme and, if used, one file-level frontmatter override. The next save must use the new setting. Then invoke a manual export and verify its open-dialog choices remain independent.
2. Make an identifiable dirty edit and immediately use **Move to new window** in both directions. The drawing write may finish during migration, but SVG/PNG rendering must not start until the replacement view has finished loading. Repeat **Open in new window** to confirm that its two-view synchronization remains intact. A failed/abandoned replacement may omit secondary output after the bounded cleanup, but must not emit stale output or affect drawing persistence.
3. With the large fixture and SVG+PNG enabled, interact with the destination/replacement view during export. Confirm migration itself completes before export work begins and that input/paint can progress between output formats. Individual PNG/SVG rendering may still cause one unavoidable main-thread pause. Rapidly save two different large drawings and verify their automatic renders do not overlap, source saves remain responsive, eventual outputs are current, and settled/GC memory does not rise monotonically.
4. Repeat the reported rapid two-view test on the large drawing. Make identifiable alternating changes faster than persistence completes, then stop and wait without forcing another save. No heavy export should begin while either view still has an active/trailing save loop. After both loops and the quiet-settle period finish, exactly the newest prepared state should render; final SVG and PNG must match the persisted drawing. Intermediate `PNG too large` notices must not recur merely because obsolete save snapshots were rendered. Repeat once where the final physical write is timer-driven autosave rather than Ctrl+S/tab blur.
Do not commit or begin checkpoint 11 until this gate passes or any failure is causally explained and explicitly accepted. Remove any temporary runtime instrumentation before commit; the current candidate adds none.
**Checkpoint 10 runtime acceptance — 2026-09-14:** the maintainer confirmed that export settings take effect immediately without reopening the view, automatic output starts only after migration completes, and the final save-batch correction resolves both rapid-save findings: obsolete large-scene PNG attempts no longer surface and final SVG/PNG match the settled persisted drawing. Checkpoint 10 is accepted for commit and checkpoint 11 may begin.
## 14. Original checkpoint 11 — asynchronous load generation
Add a monotonically increasing view/runtime load generation. Each `setViewData()` entry captures generation and exact target identity before asynchronous initialization. Invalidate on replacement load, clear, close, and migration. Check after meaningful awaits and before mutations of model, raw text, API, React tree, file state, and dirty baselines. File-path equality alone fails A→B→A navigation. Disposal must invalidate work even if the field still points to the same path.
Keep `textFileViewLoadedFile` and its explanatory comment: it suppresses duplicate same-file TextFileView delivery, not obsolete async continuations. Coordinate with the loader's existing API/path checks rather than replacing them with one broad Boolean. Stale tasks may finish private computation and clean up their own resources, but must not clear flags/baselines belonging to the current generation. Do not serialize all loads behind a dying runtime.
If generation checks were required earlier by 5b, document exactly what is already covered and finish only the remaining boundaries here. Check main/popout replacement identity without violating early unmount.
**Tests:** slow A then fast B; A→B→A; repeated same-file `setViewData`; close during fonts/initialization/compression; migration during load; delayed asset callback from retired API; parse failure followed by valid load; physical-mobile rapid navigation. No stale task may dirty or clear the replacement drawing.
### Checkpoint 11 implementation record — exact-target load ownership
`ViewLoadGeneration` issues a monotonically increasing token containing the exact `TFile` reference plus the captured `path + creation-time` identity. A→B→A therefore cannot revive the first A continuation, and deleting/recreating a path cannot match its former target. Starting another `setViewData()` settles the previous view-load ownership promise before registering the new token. Public `clear()`, `onUnloadFile()`, `onClose()`, `onunload()`, and the synchronous beginning of `onWindowMigrated()` invalidate and settle the active token idempotently. The load's internal clear path resets content without invalidating its own token.
`setViewData()` checks ownership after plugin initialization, migration persistence, layout/font readiness waits, legacy/current parsing, BAK lookup and confirmation, library/React initialization, `loadDrawing()`, file-open hooks, onload-script confirmation, and settings persistence. Recovery callbacks capture the exact target file and refuse to write or reopen after invalidation. `ExcalidrawData.loadData()` and `loadLegacyData()` accept an optional current-generation predicate; they check it after compatibility-file reads, iframe confirmation, font loading, each awaited Markdown transclusion parse, and text-mode rendering before further model mutation. `loadDrawing()` rechecks after library acquisition and guarded React initialization. The final `textFileViewLoadedFile`, accepted-content identity, load messages, `isLoaded`, and migration-autoexport success are committed only by the still-current generation. Moving the loaded-file marker to this final boundary is essential: a partial A load can no longer mark A as complete and cause a replacement A delivery to take the duplicate same-file early return.
This generation is intentionally limited to full `setViewData()` ownership. Incremental Vault synchronization already carries `saveTargetGeneration`, path revalidation, and a latest-state acquisition loop; scene-file work already checks exact API and file path. Those mechanisms are not replaced with a broad load Boolean. An `onFileOpenHook` or user onload script is invoked only while current and the host continuation rechecks afterward, but arbitrary extension/script code already executing against a supplied live view is not forcibly canceled by this token.
`check-view-load-generation.mjs` proves A→B, A→B→A, explicit invalidation, exact-reference identity, and same-path recreation behavior. All established save classification, reload policy, same-file gate, modify routing, BAK, persistence, snapshot, and autoexport checks pass. Unused-symbol validation, production build, bundle syntax, and `git diff --check` pass. `ExcalidrawView.ts` retains its 17 and `ExcalidrawData.ts` its 16 established unrelated lint findings; neither has a new finding in changed ranges. Rollup retains 33 established circular warnings. After the recovery-ordering correction, candidate `dist/main.js`: 4,934,416 bytes, SHA-256 `3f629a2d7390eb1d7bf0f7ae9bcfc52fac505cc8a4bec615311f5d631a7c637c`.
**Checkpoint 11 runtime gate:**
1. Use two materially different drawings, with A being the large image/Markdown fixture. Open A, immediately navigate the same leaf to B before A finishes, and require only B to appear and remain clean. Repeat A→B→A quickly; the final A must load fully, and neither an intermediate canvas, late font notice, recovery prompt, dirty icon, nor viewport update may arrive from the first A or B continuation.
2. Rapidly deliver the same file to one leaf by closing/reopening or switching Markdown→Excalidraw while its first load is incomplete. The newer load must finish rather than being suppressed by `textFileViewLoadedFile`. Then repeat a normal fully loaded same-file delivery/reload smoke test to confirm the established duplicate-delivery protection and checkpoint-8 Markdown-image synchronization remain intact.
3. Start loading the large drawing and immediately close the tab; repeat by switching the leaf to Markdown, using **Move to new window** in both directions, and opening a separate popout. No retired load may clear/dirty the replacement, initialize a React root in the old document, emit a serious error, or interfere with migration persistence/autoexport. The synchronous migration unmount must remain before its first await.
4. With disposable files, start a slow/invalid load and then navigate to a valid drawing before parse or backup recovery completes. No stale restore prompt may modify/reopen the old target. Independently open the invalid file and confirm its normal current-generation error/recovery flow still works.
5. If a drawing has an `onFileOpenHook` or onload script, repeat rapid navigation and confirm only a current load starts the hook/script. Finally run one physical-mobile rapid-navigation and close-during-load smoke test because font, WebView, and lifecycle scheduling differ from desktop.
Do not commit or begin checkpoint 12 until this gate passes. The candidate adds no temporary runtime instrumentation.
**Checkpoint 11 runtime finding — recovery ordering:** desktop tests passed rapid A→B→A replacement, repeated Markdown/Excalidraw switching, close during load, and both migration directions. A corrupted drawing exposed one generation-related regression: the parse-error path started backup recovery and immediately called `setMarkdownView()`, whose unload correctly invalidated the same load token and thereby canceled its own BAK lookup/prompt. The candidate now keeps recovery lookup and confirmation inside the current generation and changes to Markdown only when no backup exists or recovery is declined. An independent navigation still invalidates the token, so a stale prompt cannot write or reopen the former target. Re-test both successful BAK restoration and navigation away while the recovery prompt is open before acceptance.
**Checkpoint 11 runtime acceptance — 2026-09-14:** BAK restoration works again, rapid target replacement and same-file mode switching complete without stale updates, close-during-load preserves changes and automatic output, and ordinary migration during load works in both directions. One deliberately extreme sequence—restore a corrupted 4,400-element drawing, migrate it before its canvas appears, then immediately migrate the still-initializing replacement back—can reach the existing post-unmount migration safety stop: `WARNING_SERIOUS_ERROR` is shown and the tab remains blank until closed and reopened. Repeatedly stacking migrations can reach the same state. The attached trace contains only the expected corrupt-JSON parse errors, the restored file remains valid, and reopening loads it correctly. This is recorded as a non-blocking reentrant-migration UX limitation, not evidence for weakening early unmount, dirty-write refusal, or generation invalidation with a timing heuristic.
## 15. Original checkpoint 12 — remaining flags and timers
Inventory every remaining semaphore/timer by owner, acquisition, release, cancellation, callback target, and durability requirement. Use a table in the completion review. Retire one cohesive group per checkpoint; do not rename the entire object while behavior is changing.
- Save ownership belongs to its accepted coordinator; synchronization to its accepted acquisition/drain; content identities to the tested classifier; same-file editor ownership to its gate.
- Keep lifecycle state (closing/migrating/popout teardown), initial-load/autozoom state, and interaction throttles distinct. A single generic `isBusy` is a caller convenience, not an adequate owner model.
- Durability timers belong to the plugin/main realm; scene-file timers to `ViewSceneFileManager`; interaction timers may be view-owned. Never transfer IndexedDB/local-storage ownership to a popout.
- Clear timers/listeners idempotently, protect callback generation, and verify there is no wait cycle between save, sync, gate release, and unload. Use existing Obsidian registration helpers where appropriate.
- Path-scoping residual global embed invalidation and Canvas capability hardening remain lower-priority separate changes. Do not reopen the accepted image-render deduplication fix without new evidence.
**Tests:** main-window close/navigation, restored/new popout, dirty migration, last-popout destruction, mobile navigation, repeated enable/disable, no late callback after release, and the full first-edit/two-view convergence gate once cleanup finishes.
### Checkpoint 12 ownership inventory and staged execution
This inventory is the boundary for checkpoint 12; it prevents a broad semaphore rename from hiding unrelated lifecycle changes. “Durability” means the state can affect whether or when drawing text reaches the Vault, not merely whether a UI callback runs.
| State | Current owner and acquisition | Release/cancellation and callback target | Durability classification / next action |
| --- | --- | --- | --- |
| `saving`, `autosaving`, `forceSaving`, `dirty` | Before 12a these were stored in `ViewSemaphores`, although every production mutation except one dirty read was already in `ViewSaveCoordinator` | Save `finally`, force-save `finally`, autosave completion, revision acknowledgement, clear/adopt baseline; callbacks target the same coordinator/view | Direct durability state. **12a accepted and committed:** moved intact to private `saveInProgress`, `autosaveInProgress`, `forceSaveInProgress`, and `dirtyFilePath`; the view's one raw dirty read now calls `isDirty()` |
| `preventReload` | Before 12b this was a `ViewSemaphores` Boolean armed immediately around applicable live writes and by `setPreventReload()` | Consumed once by modify/reload routing or cleared by its timeout, force save, load, close, and unload | Content-convergence relevant. **12b accepted:** moved with its timer into view-owned `OwnWriteReloadGuard`. Markdown events still reach exact-content classification; raw `.excalidraw` and same-file embeddable compatibility routes are unchanged |
| `viewunload` | Terminal view lifecycle flag set synchronously in `onunload()` | Never reopens for that instance; consumers are save, scene-loader, observer, navigation, and callback guards | Durability/lifetime boundary. Keep view-owned; later extraction may expose a lifecycle object but must preserve synchronous acquisition |
| `windowMigrating` | Migration transaction flag acquired before source-root unmount | Cleared on explicit pre-replacement failure; successful source instance retires. Consumers include persistence policy, scene loaders, API callbacks, and close guards | Durability and realm boundary. Keep separate from `viewunload`; the accepted early-unmount protocol is not a cleanup target |
| `popoutUnload` | Computed during `onunload()` when the last tab leaves a popout | Terminal for the retiring instance; save normalization reads it | Realm-specific durability safeguard. Keep lifecycle-owned until last-popout teardown has a dedicated tested owner |
| `viewloaded` | Set after the view's layout-ready initialization | Terminal false→true for an instance; checked by full-load and UI rendering paths | Initial-load readiness, not durability. Candidate for later load-state extraction with no timing change |
| `scriptsReady` | Set at the end of synchronous `onload()` setup | `instantiateExcalidraw()` waits with the existing bounded loop | Initial runtime readiness. Retain until the bounded wait can be replaced by an already-owned readiness promise without changing startup ordering |
| `justLoaded` | Armed by `loadDrawing()` and by container-size correction | Consumed by the next Excalidraw `onChange()` | One-shot initial-publication guard affecting false dirty detection and autozoom. Keep coupled to load publication; never merge with load generation |
| `preventAutozoom` | Armed by `suppressAutozoomOnce()` | Cleared by its existing one-second callback; read by initial-load/resize paths | Viewport-only one-shot. Later move with `justLoaded` into initial-load state, preserving public `preventAutozoom()` compatibility |
| `isEditingText` | Armed by text edit/focus handling | Cleared by `isEditingTextResetTimer` or unload; read by mobile resize/keyboard behavior | Interaction throttle. Move only with its timer after physical-mobile validation |
| `hoverSleep` | Armed by hover-link handling | Anonymous 500 ms callback clears it; hover paths consume it | Interaction throttle, no durability role. Candidate for a small hover-controller extraction together with `wheelTimeout` |
| `wheelTimeout` | Wheel handler stores the current timeout handle | Replaced on wheel activity and cleared by callback/unload; hover paths check it | Interaction throttle, no durability role. Keep paired with `hoverSleep` |
| `shouldSaveImportedImage` | Image-tool/paste paths arm it | `shouldSaveImportedImageTimer` clears after three seconds; `onChange()` schedules a forced save when qualifying files arrive | Import-to-durability bridge. Retain as its own group; test paste, Image Tool, SVG-with-bitmap, close, and mobile before extraction |
| `warnAboutLinearElementLinkClick` | Reset during view clear; link navigation consumes and disables it | No timer; lifetime resets with loaded content | Navigation UX latch only. Move to `ViewLinkNavigationManager` in a naming/mechanical checkpoint |
| Timer/handle | Owner and acquisition | Cancellation / callback target | Durability requirement / disposition |
| --- | --- | --- | --- |
| `ViewSaveCoordinator.autosaveTimer` | View save coordinator recursively schedules against autosave interval | Reset after saves/first edit; cleared by coordinator `destroy()` | Starts durability but does not own a detached write. Remain coordinator-owned and view-lifetime bounded |
| `OwnWriteReloadGuard.cleanupTimer` (formerly `preventReloadResetTimer`) | The view-owned guard is armed by successful applicable live writes and the two retained back-of-note compatibility calls | Re-arm cancels the previous exact timer; consume, force-save reset, load, close, unload, and `destroy()` cancel it; the current timeout clears only its own suppression generation | Convergence relevant. **12b accepted:** state and callback identity now have one owner; scheduler remains in the plugin main realm, matching the former direct `window` timer |
| `SameFileEditGate` per-owner release timers | Gate records exact owner window and timer identity | Reacquire cancels its owner only; release callback identity-checks; `destroy()` cancels all | Convergence relevant and already correctly owned; no checkpoint-12 change planned |
| `shouldSaveImportedImageTimer` | View import/paste latch | Replaced on new import and cleared on unload; clears import flag | Can trigger persistence indirectly; move only with its flag |
| `isEditingTextResetTimer` | View text-edit handling | Replaced on edit and cleared on unload; clears mobile keyboard guard | Interaction-only; retain pending mobile test |
| `semaphores.wheelTimeout` and anonymous `hoverSleep` timeout | View hover/wheel handling | Wheel handle is replaced/cleared on unload; hover timeout self-clears but has no retained handle | Interaction-only; extract together and add destruction identity before changing behavior |
| `colorChangeTimer`, `resizeBatchTimer`, `excalidrawInitializeTimer` | View canvas-color, mobile resize, and API-initialization paths | Replaced where applicable and cleared on unload; initialization callback also checks exact API plus lifecycle flags | View interaction/load work; already bounded. Later move to their functional controllers, not a generic timer bag |
| `ViewSceneFileManager.deferredValidationTimer` plus local loader fallback/retry timers | View scene-file manager | Manager termination clears the retained validation timer and invalidates callbacks through API/path/lifecycle checks; local timers settle/recheck their operation | Scene-loader-owned by design. Preserve ownership and exact API/path guards |
| `MarkdownImageController` bounded completion timeout | View Markdown-image controller and owning window | Cleared when operation settles; callback resolves only that operation | Same-file editor completion boundary; retain with controller |
| `BackupPersistenceQueue` per-path timers | Plugin/main-realm image cache queue | Reschedule/flush/cancel/cancel-all clear through recorded owner window | Durability-critical and correctly plugin-owned; no move |
| `ViewPersistenceQueue.cleanupTimer` | Plugin/main-realm detached/migration persistence queue | Replaced/canceled by queue lifecycle; expires abandoned migration handoffs | Durability-critical and correctly plugin-owned; no move |
| `ViewMigrationHandoffManager.cleanupTimer` | Plugin/main-realm drawing-state handoff manager | Rescheduled on registry changes and cleared on destroy | Migration-state lifetime; keep separate from persistence handoff |
| `AutoexportCoordinator` deferred-migration timers and `AutoexportSaveBatchGate` quiet timers | Plugin/main-realm automatic-output coordination | Completion/discard/destroy clear exact records; newest source payload replaces older work | Secondary-output durability/order; accepted checkpoint-10 ownership, no move |
| `ImageCache` purge timers | Plugin/main-realm cache owner | Cleared during cache shutdown/reinitialization | Derived-cache/BAK maintenance; never transfer to a popout |
| `EventManager` active-leaf timers and `StencilLibraryManager.reloadTimer` | Plugin-global managers | Replaced on new events and cleared by manager teardown | UI/plugin coordination, not drawing durability; outside the first persistence-state extraction |
| Anonymous view one-shots | Individual focus, tooltip, navigation, resize, menu, and delayed-refresh call sites | Mostly self-settling and guarded by current API/view state; not a shared state machine | Audit only when moving the owning feature. Do not consolidate unrelated callbacks merely to reduce `setTimeout` count |
**Checkpoint 12a invariant:** save execution ownership, autosave/force-save exclusion, and the path-qualified dirty marker have exactly one storage owner: `ViewSaveCoordinator`. Revision comparisons, save queue ordering, timer intervals, notices, visual dirty callbacks, migration decisions, and public view accessors are unchanged. The archived `TheBrain-navigation.md` script directly mutates `semaphores.saving` while explicitly labeling it a non-published API; 12a intentionally removes that unsupported internal override rather than retaining a second writable source of truth.
**Checkpoint 12a risk gate:** repeat ordinary edit/autosave and Ctrl+S; alternate edits between two views until settled; edit during an in-flight large save and verify the trailing revision persists; close a dirty main-window tab; move a dirty tab main→popout and popout→main; test **Open in new window**; confirm the dirty icon clears only after the latest revision is acknowledged. One paste/Image Tool smoke test ensures the untouched import latch still forces persistence. No temporary runtime instrumentation is included.
`check-save-state-ownership.mjs` verifies that the four retired fields are absent from `ViewSemaphores` and all view/coordinator semaphore access, and that their explicit replacements are private coordinator state. This check and all established persistence, reload, gate, routing, BAK, snapshot, autoexport, and load-generation checks pass. Unused-symbol validation, focused coordinator/type lint, production build, bundle syntax, and `git diff --check` pass. `ExcalidrawView.ts` retains exactly its 17 established unrelated lint findings. Rollup retains 33 established circular warnings. Candidate `dist/main.js`: 4,934,276 bytes, SHA-256 `f0d268ced6b49f2b8e32009d057a18d9c27cf06af29f4a15ce2e15d39dcc782d`.
**Checkpoint 12b invariant:** own-write reload suppression and its cleanup callback have exactly one storage owner, `OwnWriteReloadGuard`. Save serialization still clears suppression before its asynchronous preparation and arms it only immediately around the physical live write. Successful save completion retains the established bounded cleanup window; failed writes, force-save entry, scene publication, close, and unload clear the complete guard. `setPreventReload()` and `clearPreventReloadTimer()` remain public compatibility delegates. The accepted modify path is unchanged: a suppressed Markdown notification continues to the exact-content classifier, while a suppressed raw `.excalidraw` notification retains its one-shot early return. Same-file edit ownership remains exclusively in `SameFileEditGate`.
The extraction makes callback identity explicit without extending the suppression interval: re-arming cancels the former timer, consuming suppression cancels its pending cleanup, and a callback checks that it is still the current timer before clearing state. This removes the former possibility that an older uncancelled timeout could clear a later arm. It does not add hashing, file reads, reloads, waits, or another coordination state.
**Checkpoint 12b risk gate:** first verify an ordinary autosave and Ctrl+S neither reload the saving view nor move its viewport. Then alternate edits between two views of the large drawing through overlapping saves, stop, and require both views and a reopen to converge without dirty ping-pong. Exercise a forced save because that path deliberately disables suppression and may invoke its reload fallback. Open/save/reopen one raw `.excalidraw` compatibility drawing; its own write must not reload unexpectedly, while an external edit must still be observed. Finally edit a back-of-note same-file card, release it, and verify pending scene changes apply; repeat one dirty main↔popout migration/close and one physical-mobile save smoke test to catch late callbacks or owner-window assumptions. No temporary runtime instrumentation is included.
`check-own-write-reload-guard.mjs` deterministically covers one-shot consumption, exact-timer replacement, current-timeout expiry, consumption cancellation, explicit false state, destruction, and source ownership assertions that the Boolean/timer no longer exist in `ViewSemaphores` or `ExcalidrawView`. It and all established persistence, reload, gate, routing, BAK, snapshot, autoexport, and load-generation checks pass. Focused owner/coordinator/type lint and unused-symbol validation pass; `ExcalidrawView.ts` retains exactly its 17 established unrelated lint findings. Production and library builds, bundle syntax, source ownership search, and `git diff --check` pass; Rollup retains 33 established circular warnings. Candidate `dist/main.js`: 4,936,295 bytes, SHA-256 `a3c40836eed143b6577668d3227c20d2bd550c489781f92fb50f661243e30f5e`.
**Checkpoint 12b runtime acceptance — 2026-09-14:** ordinary autosave and Ctrl+S, alternating multi-view editing, forced-save behavior, raw `.excalidraw` own-write suppression plus external modification, back-of-note release synchronization, migration/close, and the remaining requested smoke tests all completed successfully. Checkpoint 12b is committed as `b9481c32`.
**Post-completion branch audit — 2026-09-14:** the complete branch was reviewed from merge base `8e13a180`. No temporary persistence/migration instrumentation, tracked build output, pasted attachment, or unintended runtime logging remains. The accepted managers represent separate ownership domains and no safe consolidation was identified. Cleanup removed two unused public methods (`ViewSaveCoordinator.getLastSuccessfulPreparedSave()` and the test-only `ViewPersistenceQueue.flush()`), corrected minor end-of-file whitespace and an obsolete checkpoint comment, and brought the lifecycle overview/current-status text in sync with the accepted implementation. All 12 focused lifecycle checks, unused-symbol validation, focused lint, production/library builds, bundle syntax, and cumulative diff checks pass. Rollup retains 33 established circular warnings. Final reproducible bundle: 4,936,617 bytes, SHA-256 `698e47581470b1e9a211c58bad05ed2000d56fd3097b4cb17be55856530fb73e`. `npm run madge` could not run because the `madge` CLI is not installed or declared in this checkout; the cleanup changes no imports and Rollup's graph result is unchanged.
**Confirmed checkpoint-10 follow-up — save-owned frontmatter:** at diagnosis, `capturePreparedSaveExportOptions()` called `getPNGScale(plugin, file)`, which read `metadataCache.getFileCache(file)` before the source write. During rapid successive writes the metadata cache can temporarily be absent or behind the save-owned Markdown envelope. A drawing whose exact text says `excalidraw-export-pngscale: 0.1` could therefore fall back to the global scale (commonly `1`), plausibly producing the observed `couldn't export to blob` on a 4,400-element scene. The correction is kept as a separate increment after 12a: parse automatic-export overrides from `PreparedSave.text`, apply them to the detached request, and retain metadata/dialog resolution for manual exports. At minimum test scale `0.1` against an intentionally missing/stale metadata cache; preferably resolve all automatic-export frontmatter options from the same saved envelope so theme, padding, transparency, embed-scene, internal-link, mask, and autoexport selection cannot split from the persisted revision.
**Save-owned autoexport-frontmatter correction:** automatic save capture now starts from current plugin settings rather than `MetadataCache`, parses frontmatter from the in-memory source envelope, and re-resolves it from final `PreparedSave.text` after serialization. The detached automatic request therefore owns the scale, theme, padding, transparency, embedded-scene, internal-link, mask, and SVG/PNG selection written with that exact revision. Global “both themes” still takes precedence over a single frontmatter theme, raw `.excalidraw` selection remains a plugin setting, and `onTriggerAutoexportHook` still receives and may replace the resolved automatic configuration. Manual export/dialog methods retain their existing metadata and live-dialog resolution. Malformed or absent save-owned frontmatter falls back to the captured plugin settings without blocking persistence.
`check-prepared-autoexport-frontmatter.mjs` proves that a save-owned `0.1` scale overrides a simulated global scale of `1` without any metadata cache, covers all other supported automatic overrides, preserves both-theme behavior, retains deprecated SVG padding fallback, rejects an invalid scale, and leaves defaults intact when frontmatter is absent. The new helper and export manager lint cleanly; all established persistence checks, unused-symbol validation, production build, bundle syntax, and `git diff --check` pass. Rollup retains 33 established circular warnings. Candidate `dist/main.js`: 4,935,817 bytes, SHA-256 `25297e75bc6623baa9ed8dc2c414e6500bba567b289b063da46d1c388af8d406`.
**Runtime gate:** retain global PNG scale `1` (or another deliberately unsafe large-scene value) and the drawing frontmatter scale `0.1`. Rapidly alternate edits/saves until several source writes coalesce; no PNG blob failure should occur and the final PNG must use the small scale and match the persisted scene. Then change only the frontmatter scale while the drawing remains open and verify the next automatic PNG uses it without waiting for metadata indexing or reopening. Smoke-test one manual export to confirm its dialog scale is unchanged, plus one SVG-only/PNG-only/none frontmatter transition and one both-theme export.
**Runtime acceptance — 2026-09-14:** the maintainer completed the rapid large-scene, live frontmatter change, manual export, and automatic-output selection tests without error. The intermittent PNG blob failure is resolved. This corrective increment is committed as `1354930d`.
## 16. Required handoff record after each step
Update the ledger with: source commit or uncommitted scope; fixture/settings and installed artifact identity; exact automated commands/results; manual cases passed/failed/not run; new invariant and evidence; remaining uncertainties; next permitted action. Record rollback/stash identity if used. Keep private reproduction material outside committed docs unless the maintainer explicitly provides a public fixture.
No further production behavior change without either a deterministic failing case or a causal runtime trace. No proceeding to detached persistence while checkpoint 5 still requires another edit or forced save to settle. This is a sequence of independently reviewable experiments with acceptance gates, not authorization to implement all remaining checkpoints unattended.
@@ -1,331 +1,573 @@
/*
# Deconstruct Selected Elements Into New Drawing
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-deconstruct.jpg)
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
![](https://www.youtube.com/watch?v=HRtaaD34Zzg)
![](https://www.youtube.com/watch?v=mvMQcz401yo)
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 */
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
<!-- SPDX-License-Identifier: MIT -->
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.35" stroke-linecap="round" stroke-linejoin="round" class="svg-icon layer-manager-icon">
<polygon points="12 4.2 17.7 7.1 12 10 6.3 7.1" fill="currentColor" fill-opacity="0.55" />
<polygon points="12 9.7 18.7 13 12 16.3 5.3 13" />
<polygon points="12 15.2 17.7 18.1 12 21 6.3 18.1" />
</svg>

After

Width:  |  Height:  |  Size: 468 B

+8080 -926
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -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": 1789297989767
},
{
"fname": "Slideshow.svg",
@@ -703,4 +703,4 @@
"fname": "VoronoiDiagramGenerator.svg",
"mtime": 1785564296587
}
]
]
+1 -1
View File
@@ -682,7 +682,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Slideshow.md
```
<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/Slideshow.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will convert your drawing into a slideshow presentation.<br><a href="https://www.youtube.com/watch?v=JwgtCrIVeEU" target="_blank"><img src ="https://i.ytimg.com/vi/JwgtCrIVeEU/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
<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/Slideshow.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will convert your drawing into a slideshow presentation.<br><a href="https://www.youtube.com/watch?v=7DDY8rRDzdU" target="_blank"><img src ="https://i.ytimg.com/vi/7DDY8rRDzdU/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Split Ellipse
```excalidraw-script-install
Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.27.0-rc.2",
"version": "2.28.0-beta.0",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.26.4",
"version": "2.27.3",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+41 -12
View File
@@ -13,7 +13,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.130",
"@zsviczian/excalidraw": "0.18.136",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -52,12 +52,13 @@
"@types/node": "^22.19.19",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@zsviczian/excalidraw-extras-api": "^0.0.13",
"@zsviczian/excalidraw-extras-api": "^0.1.1",
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
"cross-env": "^7.0.3",
"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",
"obsidian": "1.8.7",
@@ -5254,9 +5255,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.130",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.130.tgz",
"integrity": "sha512-+qsJ0B/qFWkT8ZZrgPn+FodZPko93NLIRsCrVqLG5fKFAqoEY22/IXcIRc72jion6D0XkN4wbJtBu/l6HtL7GQ==",
"version": "0.18.136",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.136.tgz",
"integrity": "sha512-n43qggEICjK3NbpvOA4lKxtbFSXJp50WpD9iQOVS32PTXGm/eJtWzu1Ui3LYl30BVlPs/gjhCS7qO4tbqmlpBw==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
@@ -5297,9 +5298,9 @@
}
},
"node_modules/@zsviczian/excalidraw-extras-api": {
"version": "0.0.13",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw-extras-api/-/excalidraw-extras-api-0.0.13.tgz",
"integrity": "sha512-rZBkwfq2J5wjgxvaRTdDbGd0jSrDhznNjJ6soPS9FiuErhwDN4aGUQAJSVECaAiV/2Nynh2/iFadEj3RznaslQ==",
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw-extras-api/-/excalidraw-extras-api-0.1.1.tgz",
"integrity": "sha512-q0EoXFWEF63DJTqIHPTxrR/fkF6NxUKJVb4bYwE1IZYV9sAmB0PTcRp+ib9u4v7zuhkNiYaZO/QAgreZ4uh/Pw==",
"dev": true,
"license": "0-BSD",
"dependencies": {
@@ -5341,6 +5342,26 @@
"integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==",
"license": "MIT"
},
"node_modules/@zsviczian/rollup-plugin-postprocess": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@zsviczian/rollup-plugin-postprocess/-/rollup-plugin-postprocess-1.0.3.tgz",
"integrity": "sha512-W3t9TgbjNnZ07h+Vg78qAo0lFkYoovdlp5ojbiSP6aMswDIDdkvwrt4qQataN2kJ9UlkcvKB0pwsd1NWze8bqg==",
"dev": true,
"license": "MIT",
"dependencies": {
"magic-string": "^0.25.7"
}
},
"node_modules/@zsviczian/rollup-plugin-postprocess/node_modules/magic-string": {
"version": "0.25.9",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz",
"integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"sourcemap-codec": "^1.4.8"
}
},
"node_modules/acorn": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
@@ -7955,9 +7976,9 @@
}
},
"node_modules/eslint-plugin-obsidianmd": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-obsidianmd/-/eslint-plugin-obsidianmd-0.4.0.tgz",
"integrity": "sha512-qZsh8ydaeO7bC+XADWHGG9+CEwiKjoL7arZo1I93e0UHdQ863Jzt+xRk5VI0vo97SIJrA4vWwuz9K9/fggO35g==",
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/eslint-plugin-obsidianmd/-/eslint-plugin-obsidianmd-0.4.2.tgz",
"integrity": "sha512-NFp6wsRSvN0TU6EPi03uF2UQ3GuYyVtzjKDl25KyP8Bnz8gM0unX7R/e+VQ2JtMW2/3DC/VwIXjHnzAhB9JQwg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -12184,6 +12205,14 @@
"source-map": "^0.6.0"
}
},
"node_modules/sourcemap-codec": {
"version": "1.4.8",
"resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz",
"integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==",
"deprecated": "Please use @jridgewell/sourcemap-codec instead",
"dev": true,
"license": "MIT"
},
"node_modules/speech-rule-engine": {
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/speech-rule-engine/-/speech-rule-engine-4.1.4.tgz",
+7 -4
View File
@@ -20,7 +20,9 @@
"skill": "npm run lib && node scripts/skill-builder.mjs",
"mindmap": "node scripts/deploy-mindmap-builder.mjs",
"lint": "eslint .",
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx}\" && eslint --max-warnings=0 --ext .ts,.tsx ./src --fix"
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx}\" && eslint --max-warnings=0 --ext .ts,.tsx ./src --fix",
"repo:export": "bash scripts/generate-repository-zip.sh",
"repo:update": "rsync -av --progress ~/Downloads/update/ ./"
},
"keywords": [],
"author": "",
@@ -30,7 +32,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.130",
"@zsviczian/excalidraw": "0.18.136",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -69,12 +71,13 @@
"@types/node": "^22.19.19",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@zsviczian/excalidraw-extras-api": "^0.0.13",
"@zsviczian/excalidraw-extras-api": "^0.1.1",
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
"cross-env": "^7.0.3",
"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",
"obsidian": "1.8.7",
+145 -40
View File
@@ -8,10 +8,12 @@ import copy from "rollup-plugin-copy";
import typescript from "@rollup/plugin-typescript";
import fs from 'fs';
import path from 'path';
import postprocess from '@zsviczian/rollup-plugin-postprocess';
import cssnano from 'cssnano';
import { minify } from 'uglify-js';
import json from '@rollup/plugin-json';
import { parseEnv } from 'node:util';
import { buildReactRuntime } from './scripts/buildReactRuntime.mjs';
function compressDeflateBase64(code) {
// Compress using Node's native zlib at maximum compression
@@ -83,6 +85,15 @@ const excalidraw_pkg = isLib
: isProd
? minifyCode(excalidrawSource)
: `${excalidrawSource}\n//# sourceURL=obsidian-excalidraw-runtime.development.js\n`;
const reactRuntimeSource = isLib
? ""
: await buildReactRuntime({ isProduction: isProd });
const reactRuntime = isLib || !isProd
? reactRuntimeSource
: minifyCode(reactRuntimeSource);
const reactPackagesCompressed = isLib
? ""
: compressDeflateBase64(reactRuntime);
// Runtime payloads are only decompressed; including Pako's deflate implementation
// would add unused code to the size-constrained Obsidian plugin bundle.
const pako_pkg = isLib ? "" : fs.readFileSync("./node_modules/pako/dist/pako_inflate.min.js", "utf8");
@@ -108,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' +
@@ -130,37 +206,72 @@ const packageString = isLib
' return new TextDecoder().decode(pako.inflate(bytes));\n' +
'};\n' +
'window.unpackBase64Deflate = unpackBase64Deflate;\n' +
'let REACT_PACKAGES = unpackBase64Deflate("' + reactPackagesCompressed + '");\n' +
'const unpackExcalidraw = () => unpackBase64Deflate("' + compressDeflateBase64(excalidraw_pkg) + '");\n' +
'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 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` +
//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
// 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 = {
@@ -179,13 +290,8 @@ const BASE_CONFIG = {
'@lezer/lr',
'obsidian',
'@zsviczian/excalidraw',
...(isLib ? [
'react',
'react-dom',
'react-dom/client',
'react/jsx-runtime',
'react/jsx-dev-runtime',
] : []),
'react',
'react-dom',
],
};
@@ -196,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);
@@ -216,7 +314,6 @@ const BUILD_CONFIG = {
format: 'cjs',
exports: 'default',
inlineDynamicImports: true, // Add this line only
banner: packageString,
},
plugins: getRollupPlugins(
{
@@ -231,13 +328,21 @@ const BUILD_CONFIG = {
comments: false, // Remove all comments
},
}),
postprocess([
[
/(var[^;]*?),\s*React\s*=\s*require\(["']react["']\)([^;]*;)/,
(_, g1, g2) => `${g1}${g2}${packageString}`
],
]),
/*visualizer({
filename: 'bundle-analysis.html',
open: true, // Automatically opens in your browser when the build finishes
gzipSize: true,
brotliSize: true,
}),*/
] : []),
] : [
postprocess([[/var React = require\('react'\);/, packageString]]),
]),
copy({
targets: [{ src: 'manifest.json', dest: DIST_FOLDER }],
verbose: true,
+45
View File
@@ -0,0 +1,45 @@
import commonjs from "@rollup/plugin-commonjs";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import replace from "@rollup/plugin-replace";
import { rollup } from "rollup";
/**
* Bundles the official React package entrypoints into one function-evaluable
* artifact for the plugin's shared private runtime.
*
* @param {{ isProduction: boolean }} options Build-mode selection.
* @returns {Promise<string>} Generated browser runtime source.
*/
export const buildReactRuntime = async ({ isProduction }) => {
const mode = isProduction ? "production" : "development";
const bundle = await rollup({
input: "scripts/reactRuntimeEntry.mjs",
treeshake: true,
plugins: [
replace({
preventAssignment: true,
"process.env.NODE_ENV": JSON.stringify(mode),
}),
nodeResolve({ browser: true, preferBuiltins: false }),
commonjs(),
],
});
try {
const { output } = await bundle.generate({
format: "iife",
name: "ObsidianExcalidrawReactRuntime",
inlineDynamicImports: true,
compact: isProduction,
generatedCode: "es2015",
});
const chunk = output.find((item) => item.type === "chunk");
if (!chunk) {
throw new Error("React runtime build did not emit a JavaScript chunk");
}
return `${chunk.code}
var { React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime } = ObsidianExcalidrawReactRuntime;`;
} finally {
await bundle.close();
}
};
+341
View File
@@ -0,0 +1,341 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
const { AutoexportJobQueue } = await jiti.import(
"../src/core/managers/AutoexportJobQueue.ts",
);
const { KeyedAsyncLock } = await jiti.import(
"../src/core/managers/KeyedAsyncLock.ts",
);
const { AutoexportSaveBatchGate } = await jiti.import(
"../src/core/managers/AutoexportSaveBatchGate.ts",
);
const log = (message) => process.stdout.write(`${message}\n`);
const eventually = async (predicate, message) => {
for (let attempt = 0; attempt < 100; attempt += 1) {
if (predicate()) {
return;
}
await new Promise((resolve) => setTimeout(resolve, 0));
}
assert.fail(message);
};
let nextTimer = 1;
const batchTimers = new Map();
const batchInvalidations = [];
const batchReleases = [];
const batchGate = new AutoexportSaveBatchGate({
scheduler: {
setTimeout: (callback) => {
const timer = nextTimer++;
batchTimers.set(timer, callback);
return timer;
},
clearTimeout: (timer) => batchTimers.delete(timer),
},
settleDelayMs: 500,
getSourceKey: (job) => job.source,
shouldRender: (job) => job.render,
invalidate: (job) => batchInvalidations.push(job.id),
release: (job) => batchReleases.push(job.id),
});
const endFirstActivity = batchGate.beginActivity("drawing");
const endSecondActivity = batchGate.beginActivity("drawing");
batchGate.publish({ id: "N", source: "drawing", render: true });
batchGate.publish({ id: "N+1", source: "drawing", render: true });
assert.deepEqual(batchReleases, [], "active saves hold all heavy exports");
endFirstActivity();
assert.equal(batchTimers.size, 0, "all source save loops must become idle");
endSecondActivity();
assert.equal(
batchTimers.size,
1,
"the final save activity starts one settle timer",
);
batchGate.publish({ id: "N+2", source: "drawing", render: true });
assert.equal(
batchTimers.size,
1,
"a newer persisted state resets the quiet timer",
);
const finalBatchTimer = Array.from(batchTimers.values())[0];
batchTimers.clear();
finalBatchTimer();
assert.deepEqual(
batchInvalidations,
["N", "N+1", "N+2"],
"every persisted state invalidates older output immediately",
);
assert.deepEqual(
batchReleases,
["N+2"],
"only the newest persisted state renders after the save batch settles",
);
const endBarrierActivity = batchGate.beginActivity("drawing");
batchGate.publish({ id: "render", source: "drawing", render: true });
batchGate.publish({ id: "no-output", source: "drawing", render: false });
endBarrierActivity();
assert.equal(
batchTimers.size,
0,
"a final no-output state cancels pending render",
);
assert.deepEqual(batchReleases, ["N+2"]);
batchGate.destroy();
const deferredEvents = [];
let scheduledDrain = null;
const deferredQueue = new AutoexportJobQueue({
getSourceKey: (job) => job.source,
getDestinationKeys: (job) => job.destinations,
execute: async (job) => {
deferredEvents.push(job.id);
},
schedule: (callback) => {
scheduledDrain = callback;
},
});
deferredQueue.enqueue({
id: "deferred",
source: "drawing",
destinations: ["drawing.png"],
});
assert.deepEqual(
deferredEvents,
[],
"enqueue assigns order without starting heavy work synchronously",
);
assert.ok(scheduledDrain, "the coordinator scheduler receives the drain");
scheduledDrain();
await eventually(
() => deferredEvents.includes("deferred"),
"the scheduled drain should execute",
);
const started = [];
const written = [];
let releaseFirst;
const firstBlocked = new Promise((resolve) => {
releaseFirst = resolve;
});
const queue = new AutoexportJobQueue({
getSourceKey: (job) => job.source,
getDestinationKeys: (job) => job.destinations,
execute: async (job, guard) => {
started.push(job.id);
if (job.id === "N") {
await firstBlocked;
}
if (
guard.isCurrentSource() &&
job.destinations.every((path) => guard.isCurrentDestination(path))
) {
written.push(job.id);
}
},
});
queue.enqueue({ id: "N", source: "drawing", destinations: ["drawing.png"] });
queue.enqueue({ id: "N+1", source: "drawing", destinations: ["drawing.png"] });
queue.enqueue({ id: "N+2", source: "drawing", destinations: ["drawing.png"] });
releaseFirst();
await eventually(
() => written.includes("N+2"),
"the newest trailing source request should complete",
);
assert.deepEqual(
started,
["N", "N+2"],
"only the newest trailing source request is retained",
);
assert.deepEqual(
written,
["N+2"],
"an obsolete active render cannot write after a newer persisted request",
);
let releaseCollision;
const collisionBlocked = new Promise((resolve) => {
releaseCollision = resolve;
});
const collisionWrites = [];
const collisionQueue = new AutoexportJobQueue({
getSourceKey: (job) => job.source,
getDestinationKeys: (job) => job.destinations,
execute: async (job, guard) => {
if (job.id === "source-A") {
await collisionBlocked;
}
if (guard.isCurrentDestination(job.destinations[0])) {
collisionWrites.push(job.id);
}
},
});
collisionQueue.enqueue({
id: "source-A",
source: "A",
destinations: ["shared.png"],
});
collisionQueue.enqueue({
id: "source-B",
source: "B",
destinations: ["shared.png"],
});
await eventually(
() => collisionWrites.includes("source-B"),
"the newer colliding destination should write",
);
releaseCollision();
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(
collisionWrites,
["source-B"],
"an older job from another source cannot overwrite a newer destination",
);
let releaseBarrier;
const barrierBlocked = new Promise((resolve) => {
releaseBarrier = resolve;
});
const barrierWrites = [];
const barrierQueue = new AutoexportJobQueue({
getSourceKey: (job) => job.source,
getDestinationKeys: (job) => job.destinations,
execute: async (job, guard) => {
if (job.id === "export") {
await barrierBlocked;
}
if (guard.isCurrentSource()) {
barrierWrites.push(job.id);
}
},
});
barrierQueue.enqueue({
id: "export",
source: "drawing",
destinations: ["drawing.svg"],
});
barrierQueue.enqueue({ id: "barrier", source: "drawing", destinations: [] });
releaseBarrier();
await eventually(
() => barrierWrites.includes("barrier"),
"a persistence barrier should settle",
);
assert.deepEqual(
barrierWrites,
["barrier"],
"a newer persisted revision without outputs cancels older rendering",
);
const recoveryStarted = [];
const recoveryWrites = [];
let releaseFailedExport;
const failedExportBlocked = new Promise((resolve) => {
releaseFailedExport = resolve;
});
const recoveryQueue = new AutoexportJobQueue({
getSourceKey: (job) => job.source,
getDestinationKeys: (job) => job.destinations,
execute: async (job, guard) => {
recoveryStarted.push(job.id);
if (job.id === "failed") {
await failedExportBlocked;
throw new Error("injected export failure");
}
if (guard.isCurrentSource()) {
recoveryWrites.push(job.id);
}
},
onFailure: () => {
throw new Error("injected diagnostic failure");
},
});
recoveryQueue.enqueue({
id: "failed",
source: "drawing",
destinations: ["drawing.png"],
});
recoveryQueue.enqueue({
id: "recovery",
source: "drawing",
destinations: ["drawing.png"],
});
releaseFailedExport();
await eventually(
() => recoveryWrites.includes("recovery"),
"a newer trailing export should run after render and diagnostic failures",
);
assert.deepEqual(recoveryStarted, ["failed", "recovery"]);
assert.deepEqual(recoveryWrites, ["recovery"]);
let releaseDestroyed;
const destroyedBlocked = new Promise((resolve) => {
releaseDestroyed = resolve;
});
const destroyedWrites = [];
const destroyedQueue = new AutoexportJobQueue({
getSourceKey: (job) => job.source,
getDestinationKeys: (job) => job.destinations,
execute: async (job, guard) => {
await destroyedBlocked;
if (guard.isCurrentSource()) {
destroyedWrites.push(job.id);
}
},
});
destroyedQueue.enqueue({
id: "old-runtime",
source: "drawing",
destinations: ["drawing.png"],
});
await Promise.resolve();
destroyedQueue.destroy();
destroyedQueue.enqueue({
id: "after-destroy",
source: "drawing",
destinations: ["drawing.png"],
});
releaseDestroyed();
await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(
destroyedWrites,
[],
"an unloaded plugin runtime cannot publish pending or later output",
);
const writeLock = new KeyedAsyncLock();
const lockedEvents = [];
let releaseLockedWrite;
const lockedWrite = new Promise((resolve) => {
releaseLockedWrite = resolve;
});
const firstLocked = writeLock.run("shared.png", async () => {
lockedEvents.push("first-start");
await lockedWrite;
lockedEvents.push("first-end");
});
const secondLocked = writeLock.run("shared.png", async () => {
lockedEvents.push("second");
});
const independent = writeLock.run("other.png", async () => {
lockedEvents.push("independent");
});
await independent;
assert.deepEqual(
lockedEvents,
["first-start", "independent"],
"different destinations remain independent while one output is blocked",
);
releaseLockedWrite();
await Promise.all([firstLocked, secondLocked]);
assert.deepEqual(
lockedEvents,
["first-start", "independent", "first-end", "second"],
"writes to one resolved destination execute in accepted order",
);
log("autoexport job queue checks passed");
@@ -0,0 +1,87 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
const { BackupPersistenceQueue } = await jiti.import(
"../src/shared/BackupPersistenceQueue.ts",
);
const log = (message) => process.stdout.write(`${message}\n`);
const timers = new Map();
let nextTimer = 1;
const ownerWindow = {
setTimeout: (callback) => {
const timer = nextTimer++;
timers.set(timer, callback);
return timer;
},
clearTimeout: (timer) => timers.delete(timer),
};
const runNextTimer = () => {
const entry = timers.entries().next().value;
assert.ok(entry, "a backup drain timer is pending");
const [timer, callback] = entry;
timers.delete(timer);
callback();
};
const writes = [];
const errors = [];
let releaseSlowWrite;
const slowWrite = new Promise((resolve) => {
releaseSlowWrite = resolve;
});
const queue = new BackupPersistenceQueue({
ownerWindow,
write: async (filepath, data) => {
if (data === "slow") {
await slowWrite;
}
if (data === "fail") {
throw new Error("injected backup failure");
}
writes.push(`${filepath}:${data}`);
},
onError: (error, stage) => errors.push(`${stage}:${error.message}`),
});
assert.equal(queue.schedule("Drawing.md", "old", 50), false);
assert.equal(queue.schedule("Drawing.md", "new", 50), true);
assert.equal(timers.size, 1, "only the newest delayed payload remains queued");
runNextTimer();
await queue.flush("Drawing.md");
assert.deepEqual(writes, ["Drawing.md:new"]);
queue.schedule("Drawing.md", "slow", 50);
runNextTimer();
await Promise.resolve();
assert.equal(
queue.schedule("Drawing.md", "newest", 50),
true,
"a newer payload is retained behind an active backup write",
);
releaseSlowWrite();
await queue.flush("Drawing.md");
assert.deepEqual(writes, [
"Drawing.md:new",
"Drawing.md:slow",
"Drawing.md:newest",
]);
queue.schedule("Drawing.md", "fail", 50);
runNextTimer();
await queue.flush("Drawing.md");
assert.equal(errors.length, 1, "backup failure is reported independently");
queue.schedule("Drawing.md", "after-failure", 50);
runNextTimer();
await queue.flush("Drawing.md");
assert.equal(writes.at(-1), "Drawing.md:after-failure");
queue.schedule("Drawing.md", "cancelled", 50);
queue.schedule("Other.md", "also-cancelled", 50);
await queue.cancelAll();
assert.equal(timers.size, 0, "clearing backups cancels every pending write");
assert.equal(writes.includes("Drawing.md:cancelled"), false);
assert.equal(writes.includes("Other.md:also-cancelled"), false);
log("backup persistence queue checks passed");
+60
View File
@@ -0,0 +1,60 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const log = (message) => process.stdout.write(`${message}\n`);
const jiti = createJiti(import.meta.url);
const { getDrawingModifyRoute, shouldInspectSuppressedModifyContent } =
await jiti.import("../src/core/managers/fileModifyRouting.ts");
const route = (overrides = {}) =>
getDrawingModifyRoute({
fileExtension: "md",
isEditingMarkdownSideInSplitView: false,
isDirty: false,
isPersistenceBusy: false,
isStale: false,
...overrides,
});
assert.equal(
route({ isDirty: true, isStale: true }),
"incremental-sync",
"a stale dirty Markdown receiver must merge rather than reload",
);
assert.equal(
route({ isPersistenceBusy: true, isStale: true }),
"incremental-sync",
"a stale busy Markdown receiver must queue synchronization",
);
assert.equal(
route({ isStale: true }),
"full-reload",
"the existing clean and idle stale-view policy must remain intact",
);
assert.equal(
route({ isEditingMarkdownSideInSplitView: true, isStale: true }),
"incremental-sync",
"the existing Markdown-side/recent-switch protection must remain intact",
);
assert.equal(
route({ fileExtension: "excalidraw", isDirty: true, isStale: true }),
"full-reload",
"raw Excalidraw files retain the existing stale full-reload route",
);
assert.equal(
route({ fileExtension: "excalidraw" }),
"raw-reload",
"recent raw Excalidraw modifies retain their existing reload route",
);
assert.equal(
shouldInspectSuppressedModifyContent("md"),
true,
"Markdown notifications must reach exact-content inspection even while the legacy Boolean is armed",
);
assert.equal(
shouldInspectSuppressedModifyContent("excalidraw"),
false,
"raw Excalidraw files retain their staged legacy suppression behavior",
);
log("file modify routing checks passed");
+96
View File
@@ -0,0 +1,96 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
const { OwnWriteReloadGuard } = await jiti.import(
"../src/view/managers/OwnWriteReloadGuard.ts",
);
const callbacks = new Map();
const cleared = [];
let nextTimer = 1;
const guard = new OwnWriteReloadGuard(
{
setTimeout: (callback) => {
const timer = nextTimer++;
callbacks.set(timer, () => {
callbacks.delete(timer);
callback();
});
return timer;
},
clearTimeout: (timer) => {
cleared.push(timer);
callbacks.delete(timer);
},
},
2000,
);
guard.setForWrite(true);
assert.equal(guard.consume(), true);
assert.equal(guard.consume(), false, "one notification consumes suppression");
guard.armCleanup();
const firstTimer = nextTimer - 1;
const firstCallback = callbacks.get(firstTimer);
guard.armCleanup();
const secondTimer = nextTimer - 1;
assert.deepEqual(cleared, [firstTimer], "re-arm cancels the older timer");
firstCallback();
assert.equal(
guard.consume(),
true,
"an obsolete callback cannot clear a newer suppression arm",
);
assert.equal(callbacks.has(secondTimer), false);
guard.armCleanup();
const expiryTimer = nextTimer - 1;
callbacks.get(expiryTimer)();
assert.equal(guard.consume(), false, "current cleanup expires suppression");
guard.armCleanup();
const consumedTimer = nextTimer - 1;
assert.equal(guard.consume(), true);
assert.equal(
callbacks.has(consumedTimer),
false,
"consumption cancels its cleanup callback",
);
guard.setForWrite(false);
assert.equal(guard.consume(), false);
guard.armCleanup();
const destroyedTimer = nextTimer - 1;
guard.destroy();
assert.equal(callbacks.has(destroyedTimer), false);
assert.equal(guard.consume(), false);
const semaphoreTypes = await readFile(
new URL("../src/types/excalidrawViewTypes.ts", import.meta.url),
"utf8",
);
const viewSource = await readFile(
new URL("../src/view/ExcalidrawView.ts", import.meta.url),
"utf8",
);
assert.doesNotMatch(
semaphoreTypes,
/\bpreventReload\s*:/,
"reload suppression must not remain in ViewSemaphores",
);
assert.doesNotMatch(
viewSource,
/semaphores\??\.preventReload\b/,
"reload suppression must be owned by OwnWriteReloadGuard",
);
assert.doesNotMatch(
viewSource,
/preventReloadResetTimer/,
"reload cleanup timer must be owned by OwnWriteReloadGuard",
);
process.stdout.write("own-write reload guard checks passed\n");
@@ -0,0 +1,71 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
const { resolvePreparedAutoexportSettings } = await jiti.import(
"../src/view/managers/preparedAutoexportFrontmatter.ts",
);
const defaults = {
exportOptions: {
theme: "light",
embedScene: false,
padding: 10,
scale: 1,
withBackground: true,
includeInternalLinks: true,
isMask: false,
},
autoexportConfig: {
svg: false,
png: false,
excalidraw: true,
theme: "light",
},
};
const resolved = resolvePreparedAutoexportSettings(defaults, {
"excalidraw-autoexport": "both",
"excalidraw-export-pngscale": 0.1,
"excalidraw-export-padding": 24,
"excalidraw-export-dark": true,
"excalidraw-export-embed-scene": true,
"excalidraw-export-transparent": true,
"excalidraw-export-internal-links": false,
"excalidraw-mask": true,
});
assert.equal(resolved.exportOptions.scale, 0.1);
assert.equal(resolved.exportOptions.padding, 24);
assert.equal(resolved.exportOptions.theme, "dark");
assert.equal(resolved.exportOptions.embedScene, true);
assert.equal(resolved.exportOptions.withBackground, false);
assert.equal(resolved.exportOptions.includeInternalLinks, false);
assert.equal(resolved.exportOptions.isMask, true);
assert.equal(resolved.autoexportConfig.svg, true);
assert.equal(resolved.autoexportConfig.png, true);
assert.equal(resolved.autoexportConfig.excalidraw, true);
assert.equal(resolved.autoexportConfig.theme, "dark");
const bothThemes = resolvePreparedAutoexportSettings(
{
...defaults,
autoexportConfig: { ...defaults.autoexportConfig, theme: "both" },
},
{ "excalidraw-export-dark": true },
);
assert.equal(bothThemes.autoexportConfig.theme, "both");
const legacyPadding = resolvePreparedAutoexportSettings(defaults, {
"excalidraw-export-svgpadding": "31",
"excalidraw-export-pngscale": "invalid",
});
assert.equal(legacyPadding.exportOptions.padding, 31);
assert.equal(legacyPadding.exportOptions.scale, 1);
assert.deepEqual(
resolvePreparedAutoexportSettings(defaults, {}),
defaults,
"missing metadata must leave save-time plugin defaults intact",
);
process.stdout.write("prepared autoexport frontmatter checks passed\n");
+93
View File
@@ -0,0 +1,93 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
const { SameFileEditGate } = await jiti.import(
"../src/view/managers/SameFileEditGate.ts",
);
const log = (message) => process.stdout.write(`${message}\n`);
const createFakeWindow = () => {
const timers = new Map();
const cleared = [];
let nextTimer = 1;
return {
timers,
cleared,
setTimeout(callback) {
const timer = nextTimer++;
timers.set(timer, callback);
return timer;
},
clearTimeout(timer) {
cleared.push(timer);
timers.delete(timer);
},
};
};
const runOnlyTimer = (ownerWindow) => {
assert.equal(ownerWindow.timers.size, 1);
const [timer, callback] = ownerWindow.timers.entries().next().value;
ownerWindow.timers.delete(timer);
callback();
};
const firstWindow = createFakeWindow();
const secondWindow = createFakeWindow();
let currentWindow = firstWindow;
const gate = new SameFileEditGate(() => currentWindow);
gate.acquire("canvas:a");
gate.acquire("canvas:a");
gate.acquire("markdown:b");
assert.equal(gate.hasActiveOwners, true);
assert.equal(gate.isInGracePeriod, false);
assert.equal(gate.isBlocked, true);
gate.release("canvas:a", 2000);
assert.equal(gate.hasActiveOwners, true, "the second owner remains active");
assert.equal(gate.isInGracePeriod, true);
runOnlyTimer(firstWindow);
assert.equal(gate.isBlocked, true, "one owner's grace cannot unblock another");
gate.release("markdown:b", 2000);
const staleRelease = firstWindow.timers.values().next().value;
currentWindow = secondWindow;
gate.acquire("markdown:b");
assert.equal(firstWindow.timers.size, 0, "reacquire cancels in the timer's realm");
staleRelease();
assert.equal(gate.isBlocked, true, "a stale callback cannot unblock reacquired ownership");
gate.release("markdown:b", 2000);
assert.equal(secondWindow.timers.size, 1);
gate.release("markdown:b", 2000);
assert.equal(
secondWindow.timers.size,
1,
"repeated release refreshes only the same owner's grace",
);
runOnlyTimer(secondWindow);
assert.equal(gate.hasActiveOwners, false);
assert.equal(gate.isInGracePeriod, false);
assert.equal(gate.isBlocked, false);
gate.acquire("canvas:legacy");
gate.release("canvas:legacy", 2000);
gate.cancelRelease("canvas:legacy");
assert.equal(
gate.hasActiveOwners,
true,
"canceling a legacy release restores active ownership",
);
assert.equal(secondWindow.timers.size, 0);
gate.release("canvas:legacy", 0);
gate.release("unknown", 2000);
assert.equal(gate.isBlocked, false, "unknown release is an idempotent no-op");
gate.acquire("canvas:c");
gate.release("canvas:c", 2000);
gate.destroy();
assert.equal(secondWindow.timers.size, 0);
assert.equal(gate.isBlocked, false);
log("same-file edit gate checks passed");
@@ -0,0 +1,128 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
const {
classifyObservedSaveContent,
isRedundantObservedSaveContent,
isSameSaveOperation,
} = await jiti.import("../src/view/managers/saveContentClassification.ts");
const log = (message) => process.stdout.write(`${message}\n`);
const prepared = (overrides = {}) => ({
producerId: "view-1",
targetGeneration: 2,
operationId: 4,
requestedRevision: 5,
capturedRevision: 6,
filePath: "Drawing.md",
text: "saved",
hasNonDeletedElements: true,
...overrides,
});
const classify = (overrides = {}) =>
classifyObservedSaveContent({
filePath: "Drawing.md",
targetGeneration: 2,
observedText: "saved",
currentRevision: 6,
savedRevision: 6,
successfulWrite: prepared(),
latestAttempt: null,
acceptedContent: null,
...overrides,
});
assert.deepEqual(classify(), {
kind: "matches-successful-write",
hasNewerLocalRevision: false,
});
assert.equal(isRedundantObservedSaveContent(classify()), true);
assert.deepEqual(classify({ currentRevision: 7 }), {
kind: "matches-successful-write",
hasNewerLocalRevision: true,
});
assert.equal(
isRedundantObservedSaveContent(classify({ currentRevision: 7 })),
true,
"matching persisted bytes remain redundant without acknowledging newer local work",
);
assert.equal(
classify({
successfulWrite: null,
acceptedContent: {
filePath: "Drawing.md",
targetGeneration: 2,
text: "saved",
},
}).kind,
"matches-accepted-content",
);
assert.deepEqual(
classify({
currentRevision: 7,
savedRevision: 6,
successfulWrite: null,
acceptedContent: {
filePath: "Drawing.md",
targetGeneration: 2,
text: "saved",
},
}),
{
kind: "matches-accepted-content",
hasNewerLocalRevision: true,
},
);
assert.equal(
classify({
successfulWrite: null,
latestAttempt: { preparedSave: prepared(), state: "prepared" },
}).kind,
"matches-pending-write",
);
assert.equal(
isSameSaveOperation(prepared(), prepared()),
true,
"the same operation may complete its prepared record",
);
assert.equal(
isSameSaveOperation(prepared(), prepared({ operationId: 5 })),
false,
"an older completion must not replace a newer operation",
);
assert.equal(
classify({
successfulWrite: null,
latestAttempt: { preparedSave: prepared(), state: "failed" },
}).kind,
"matches-failed-write",
);
assert.equal(
classify({
successfulWrite: null,
latestAttempt: { preparedSave: prepared(), state: "handed-off" },
}).kind,
"matches-unconfirmed-handoff",
);
assert.equal(
classify({ observedText: "external" }).kind,
"different-from-known-content",
);
assert.equal(
isRedundantObservedSaveContent(classify({ observedText: "external" })),
false,
);
assert.equal(classify({ targetGeneration: 3 }).kind, "unknown");
assert.equal(
classify({
successfulWrite: prepared({ targetGeneration: 1 }),
latestAttempt: {
preparedSave: prepared({ targetGeneration: 1 }),
state: "successful",
},
}).kind,
"unknown",
);
log("save content classification checks passed");
+264
View File
@@ -0,0 +1,264 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url, {
interopDefault: true,
});
const {
createPreparedSave,
createPreparedSaveIdentity,
createSaveSnapshot,
getAcknowledgedSaveRevision,
} = await jiti.import("../src/view/managers/saveSnapshot.ts");
const log = (message) => console.log(`SAVE_SNAPSHOT_CHECK ${message}`);
const sourceElement = {
id: "element-1",
type: "rectangle",
isDeleted: false,
points: [[1, 2]],
startBinding: { elementId: "bound-1", focus: 0, gap: 1 },
customData: { nested: { value: 1 } },
shape: { runtime: true },
};
const sourceDeletedElement = {
...sourceElement,
id: "deleted-1",
isDeleted: true,
};
const sourceScene = {
elements: [sourceElement],
appState: {
selectedElementIds: { "element-1": true },
collaborators: new Map([["user-1", { username: "User" }]]),
},
files: {
"file-1": {
id: "file-1",
dataURL: "data:image/png;base64,immutable",
mimeType: "image/png",
created: 1,
lastRetrieved: 1,
},
},
};
const sourceExportData = {
sourceFilePath: "Drawing.md",
files: new Map([
[
"file-1",
{
filePath: "Image.png",
isSVGwithBitmap: false,
img: "data:image/png;base64,light",
imgInverted: "data:image/png;base64,dark",
mtime: 1,
mimeType: "image/png",
size: { width: 10, height: 20 },
linkParts: { original: "Image.png", path: "Image.png" },
filenameparts: { filepath: "Image.png" },
hostPath: "Drawing.md",
attemptCounter: 0,
isHyperLink: false,
isLocalLink: false,
isMarkdownSection: false,
hyperlink: null,
colorMap: { "#000000": "#ffffff" },
pdfPageViewProps: null,
renderScale: 0,
},
],
]),
markdownImages: new Map([["markdown-1", { markdown: "save-owned" }]]),
equations: new Map([
["equation-1", { latex: "x=1", isLoaded: true }],
]),
markdownImageRenderDefaults: {
width: 500,
paddingBottom: 10,
fontFamily: "Cascadia",
fontColor: "Black",
border: { enabled: false, color: "Black" },
css: "",
transclusion: {
enabled: false,
fontFamily: "Cascadia",
fontColor: "Black",
border: { enabled: false, color: "Black" },
css: "",
},
},
pdfScale: 1,
};
const snapshot = createSaveSnapshot({
operation: {
producerId: "view-1",
targetGeneration: 3,
operationId: 9,
requestedRevision: 4,
},
filePath: "Drawing.md",
sourceFileCtime: 10,
capturedRevision: 6,
sourceText: "source text",
scene: sourceScene,
deletedElements: [sourceDeletedElement],
selectedElementIds: sourceScene.appState.selectedElementIds,
exportOptions: {
theme: "dark",
embedScene: true,
padding: 12,
scale: 2,
withBackground: false,
includeInternalLinks: true,
isMask: false,
},
exportData: sourceExportData,
autoexportConfig: {
svg: true,
png: true,
excalidraw: true,
theme: "both",
},
});
sourceElement.points[0][0] = 100;
sourceElement.startBinding.focus = 1;
sourceElement.customData.nested.value = 2;
sourceDeletedElement.customData.nested.value = 3;
sourceScene.appState.selectedElementIds["element-1"] = false;
sourceScene.files["file-1"].lastRetrieved = 2;
sourceExportData.markdownImages.get("markdown-1").markdown = "live change";
sourceExportData.equations.get("equation-1").latex = "x=2";
sourceExportData.files.get("file-1").linkParts.original = "Changed.png";
sourceExportData.files.get("file-1").colorMap["#000000"] = "#ff0000";
sourceExportData.markdownImageRenderDefaults.border.color = "Red";
assert.equal(snapshot.scene.elements[0].points[0][0], 1);
assert.equal(snapshot.scene.elements[0].startBinding.focus, 0);
assert.equal(snapshot.scene.elements[0].customData.nested.value, 1);
assert.equal(snapshot.deletedElements[0].customData.nested.value, 1);
assert.equal(snapshot.selectedElementIds["element-1"], true);
assert.equal(snapshot.scene.files["file-1"].lastRetrieved, 1);
assert.equal(
snapshot.scene.files["file-1"].dataURL,
"data:image/png;base64,immutable",
);
assert.equal("shape" in snapshot.scene.elements[0], false);
assert.equal(
snapshot.exportData.markdownImages.get("markdown-1").markdown,
"save-owned",
);
assert.equal(
snapshot.exportData.equations.get("equation-1").latex,
"x=1",
);
assert.equal(
snapshot.exportData.files.get("file-1").linkParts.original,
"Image.png",
);
assert.equal(
snapshot.exportData.files.get("file-1").colorMap["#000000"],
"#ffffff",
);
assert.equal(
snapshot.exportData.markdownImageRenderDefaults.border.color,
"Black",
);
snapshot.scene.elements[0].customData.nested.value = 7;
snapshot.scene.files = {};
const prepared = createPreparedSave(snapshot, "exact prepared text");
assert.equal(prepared.producerId, "view-1");
assert.equal(prepared.targetGeneration, 3);
assert.equal(prepared.operationId, 9);
assert.equal(prepared.requestedRevision, 4);
assert.equal(prepared.sourceFileCtime, 10);
assert.equal(prepared.capturedRevision, 6);
assert.equal(prepared.text, "exact prepared text");
assert.equal(prepared.hasNonDeletedElements, true);
assert.equal(
prepared.scene.elements[0].customData.nested.value,
7,
"the prepared scene contains save-time normalization",
);
assert.equal(
prepared.scene.files["file-1"].dataURL,
"data:image/png;base64,immutable",
"captured export files survive normalization clearing scene.files",
);
assert.equal(prepared.deletedElements[0].id, "deleted-1");
assert.equal(prepared.selectedElementIds["element-1"], true);
assert.deepEqual(prepared.exportOptions, {
theme: "dark",
embedScene: true,
padding: 12,
scale: 2,
withBackground: false,
includeInternalLinks: true,
isMask: false,
});
assert.deepEqual(prepared.autoexportConfig, {
svg: true,
png: true,
excalidraw: true,
theme: "both",
});
assert.equal(
prepared.exportData.markdownImages.get("markdown-1").markdown,
"save-owned",
);
assert.equal(
prepared.exportData.equations.get("equation-1").latex,
"x=1",
);
snapshot.scene.elements[0].customData.nested.value = 8;
snapshot.exportFiles["file-1"].lastRetrieved = 9;
snapshot.deletedElements[0].customData.nested.value = 9;
snapshot.selectedElementIds["element-1"] = false;
snapshot.exportOptions.padding = 99;
snapshot.exportData.markdownImages.get("markdown-1").markdown =
"snapshot change";
snapshot.exportData.equations.get("equation-1").latex = "x=3";
snapshot.autoexportConfig.svg = false;
snapshot.exportData.files.get("file-1").linkParts.original = "Snapshot.png";
snapshot.exportData.markdownImageRenderDefaults.transclusion.border.color =
"Blue";
assert.equal(prepared.scene.elements[0].customData.nested.value, 7);
assert.equal(prepared.scene.files["file-1"].lastRetrieved, 1);
assert.equal(prepared.deletedElements[0].customData.nested.value, 1);
assert.equal(prepared.selectedElementIds["element-1"], true);
assert.equal(prepared.exportOptions.padding, 12);
assert.equal(
prepared.exportData.markdownImages.get("markdown-1").markdown,
"save-owned",
);
assert.equal(
prepared.exportData.equations.get("equation-1").latex,
"x=1",
);
assert.equal(prepared.autoexportConfig.svg, true);
assert.equal(
prepared.exportData.files.get("file-1").linkParts.original,
"Image.png",
);
assert.equal(
prepared.exportData.markdownImageRenderDefaults.transclusion.border.color,
"Black",
);
const preparedIdentity = createPreparedSaveIdentity(prepared);
assert.equal(preparedIdentity.text, "exact prepared text");
assert.equal("scene" in preparedIdentity, false);
assert.equal("deletedElements" in preparedIdentity, false);
assert.equal("selectedElementIds" in preparedIdentity, false);
assert.equal("exportData" in preparedIdentity, false);
assert.equal("autoexportConfig" in preparedIdentity, false);
assert.equal(getAcknowledgedSaveRevision(4, prepared), 6);
assert.equal(getAcknowledgedSaveRevision(4), 4);
log("save snapshot ownership checks passed");
+48
View File
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
const semaphoreTypes = await readFile(
new URL("../src/types/excalidrawViewTypes.ts", import.meta.url),
"utf8",
);
const viewSource = await readFile(
new URL("../src/view/ExcalidrawView.ts", import.meta.url),
"utf8",
);
const coordinatorSource = await readFile(
new URL("../src/view/managers/ViewSaveCoordinator.ts", import.meta.url),
"utf8",
);
for (const retiredField of ["saving", "autosaving", "forceSaving", "dirty"]) {
assert.doesNotMatch(
semaphoreTypes,
new RegExp(`\\b${retiredField}\\s*:`),
`${retiredField} must not remain in ViewSemaphores`,
);
assert.doesNotMatch(
viewSource,
new RegExp(`semaphores\\??\\.${retiredField}\\b`),
`${retiredField} must not be read through the view semaphore bag`,
);
assert.doesNotMatch(
coordinatorSource,
new RegExp(`semaphores\\??\\.${retiredField}\\b`),
`${retiredField} must be coordinator-owned`,
);
}
for (const ownedField of [
"saveInProgress",
"autosaveInProgress",
"forceSaveInProgress",
"dirtyFilePath",
]) {
assert.match(
coordinatorSource,
new RegExp(`private ${ownedField}\\b`),
`${ownedField} must be explicit coordinator state`,
);
}
process.stdout.write("save state ownership checks passed\n");
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
const { shouldRetainLoadedFileAfterReload } = await jiti.import(
"../src/view/textFileViewReloadPolicy.ts",
);
assert.equal(
shouldRetainLoadedFileAfterReload(false, true),
true,
"a same-file Markdown-envelope refresh must suppress the duplicate TextFileView delivery",
);
assert.equal(
shouldRetainLoadedFileAfterReload(true, true),
false,
"a full reload retains the established marker-reset policy",
);
assert.equal(
shouldRetainLoadedFileAfterReload(false, false),
false,
"a non-modify reload retains the established marker-reset policy",
);
process.stdout.write("text-file-view reload policy checks passed\n");
+46
View File
@@ -0,0 +1,46 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
const { ViewLoadGeneration } = await jiti.import(
"../src/view/managers/ViewLoadGeneration.ts",
);
const generations = new ViewLoadGeneration();
const fileA = { path: "A.md" };
const fileB = { path: "B.md" };
const firstA = generations.begin(fileA, "A.md\u000010");
assert.equal(generations.isCurrent(firstA, fileA, "A.md\u000010"), true);
const loadB = generations.begin(fileB, "B.md\u000020");
assert.equal(
generations.isCurrent(firstA, fileA, "A.md\u000010"),
false,
"a later B load invalidates A",
);
assert.equal(generations.isCurrent(loadB, fileB, "B.md\u000020"), true);
const secondA = generations.begin(fileA, "A.md\u000010");
assert.equal(
generations.isCurrent(firstA, fileA, "A.md\u000010"),
false,
"returning to the same A identity cannot revive its older continuation",
);
assert.equal(generations.isCurrent(secondA, fileA, "A.md\u000010"), true);
generations.invalidate();
assert.equal(
generations.isCurrent(secondA, fileA, "A.md\u000010"),
false,
"clear, close, unload, or migration invalidates the active load",
);
const recreatedA = { path: "A.md" };
const recreatedToken = generations.begin(recreatedA, "A.md\u000030");
assert.equal(
generations.isCurrent(recreatedToken, fileA, "A.md\u000010"),
false,
"same-path recreation is not the same load target",
);
process.stdout.write("view load generation checks passed\n");
+345
View File
@@ -0,0 +1,345 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url);
const { ViewPersistenceQueue } = await jiti.import(
"../src/core/managers/ViewPersistenceQueue.ts",
);
const log = (message) => process.stdout.write(`${message}\n`);
const files = new Map([
["Drawing.md", { path: "Drawing.md", stat: { ctime: 10 } }],
]);
const writes = [];
const backups = [];
const persistenceEvents = [];
const failures = [];
const backupScheduleFailures = [];
const persistedCallbacks = [];
const persistedCallbackFailures = [];
const persistenceActivities = [];
let releaseFirstWrite;
const firstWriteBlocked = new Promise((resolve) => {
releaseFirstWrite = resolve;
});
let writeCount = 0;
const queue = new ViewPersistenceQueue({
resolveFile: (path) => files.get(path) ?? null,
write: async (file, text) => {
writeCount += 1;
if (writeCount === 1) {
await firstWriteBlocked;
}
if (text === "fail") {
throw new Error("injected write failure");
}
writes.push(`${file.path}:${text}`);
persistenceEvents.push(`write:${text}`);
},
scheduleBackup: (filePath, text) => {
if (text === "backup-schedule-fail") {
throw new Error("injected backup scheduling failure");
}
backups.push(`${filePath}:${text}`);
persistenceEvents.push(`backup:${text}`);
},
now: () => Date.now(),
scheduleCleanup: (callback, delayMs) => setTimeout(callback, delayMs),
cancelCleanup: (timer) => clearTimeout(timer),
onFailure: (result) => failures.push(result.status),
onBackupScheduleFailure: (_error, failedRequest) =>
backupScheduleFailures.push(failedRequest.text),
onPersisted: (persistedRequest) => {
persistedCallbacks.push(persistedRequest.text);
if (persistedRequest.text === "completion-callback-fail") {
throw new Error("injected completion callback failure");
}
},
onPersistedCallbackFailure: (_error, failedRequest) => {
persistedCallbackFailures.push(failedRequest.text);
throw new Error("injected completion diagnostic failure");
},
beginPersistenceActivity: (activeRequest) => {
persistenceActivities.push(`start:${activeRequest.text}`);
return () => persistenceActivities.push(`end:${activeRequest.text}`);
},
});
const request = (text, overrides = {}) => ({
producerId: "view-1",
targetGeneration: 1,
operationId: 1,
requestedRevision: 1,
capturedRevision: 1,
filePath: "Drawing.md",
expectedFileCtime: 10,
text,
hasNonDeletedElements: true,
reason: "view-unload",
...overrides,
});
const first = queue.enqueue(request("first"));
const second = queue.enqueue(request("second", { operationId: 2 }));
let liveLeaseAcquired = false;
const liveLeasePromise = queue.acquireWriteLease("Drawing.md").then((lease) => {
liveLeaseAcquired = true;
return lease;
});
await Promise.resolve();
assert.deepEqual(writes, [], "the first write is still deliberately blocked");
assert.equal(
liveLeaseAcquired,
false,
"a live write cannot overtake detached requests already accepted for the path",
);
releaseFirstWrite();
assert.equal((await first).status, "persisted");
assert.equal((await second).status, "persisted");
assert.deepEqual(
writes,
["Drawing.md:first", "Drawing.md:second"],
"independent requests execute in accepted order without coalescing",
);
const liveLease = await liveLeasePromise;
const behindLiveLease = queue.enqueue(
request("behind-live", { operationId: 3 }),
);
await Promise.resolve();
assert.deepEqual(
writes,
["Drawing.md:first", "Drawing.md:second"],
"a detached write cannot overlap an acquired live write lease",
);
liveLease.release();
liveLease.release();
assert.equal((await behindLiveLease).status, "persisted");
assert.deepEqual(writes, [
"Drawing.md:first",
"Drawing.md:second",
"Drawing.md:behind-live",
]);
queue.registerMigrationHandoff({
leafId: "leaf-1",
request: request("migration", {
producerId: "popout-view",
operationId: 4,
reason: "window-migration",
}),
});
const behindMigration = queue.enqueue(
request("behind-migration", { operationId: 5 }),
);
await Promise.resolve();
assert.deepEqual(
writes,
["Drawing.md:first", "Drawing.md:second", "Drawing.md:behind-live"],
"registering a migration handoff reserves order without starting a write",
);
const migration = queue.consumeMigrationHandoff("leaf-1", "Drawing.md");
assert.ok(migration, "the replacement consumes the matching handoff");
assert.equal(migration.request.text, "migration");
assert.equal((await migration.completion).status, "persisted");
assert.equal((await behindMigration).status, "persisted");
assert.deepEqual(writes, [
"Drawing.md:first",
"Drawing.md:second",
"Drawing.md:behind-live",
"Drawing.md:migration",
"Drawing.md:behind-migration",
]);
assert.deepEqual(
backups,
writes,
"detached and migration backups follow successful source-write order",
);
assert.deepEqual(
persistenceEvents,
[
"write:first",
"backup:first",
"write:second",
"backup:second",
"write:behind-live",
"backup:behind-live",
"write:migration",
"backup:migration",
"write:behind-migration",
"backup:behind-migration",
],
"each backup is scheduled before the next accepted source write starts",
);
assert.deepEqual(
persistenceActivities,
[
"start:first",
"end:first",
"start:second",
"end:second",
"start:behind-live",
"end:behind-live",
"start:migration",
"end:migration",
"start:behind-migration",
"end:behind-migration",
],
"detached and migration writes expose their complete physical activity",
);
queue.registerMigrationHandoff({
leafId: "leaf-discarded",
request: request("discarded-migration", {
operationId: 6,
reason: "window-migration",
}),
});
const behindDiscardedMigration = queue.enqueue(
request("after-discard", { operationId: 7 }),
);
queue.discardMigrationHandoff("leaf-discarded");
assert.equal((await behindDiscardedMigration).status, "persisted");
assert.equal(
writes.includes("Drawing.md:discarded-migration"),
false,
"discarding a failed replacement releases order without writing",
);
queue.registerMigrationHandoff({
leafId: "leaf-mismatch",
request: request("wrong-target-migration", {
operationId: 8,
reason: "window-migration",
}),
});
assert.equal(
queue.consumeMigrationHandoff("leaf-mismatch", "Other.md"),
null,
"a mismatched replacement must not receive another file's text",
);
assert.equal(
(await queue.enqueue(request("missing", { filePath: "Missing.md" }))).status,
"target-missing",
);
assert.equal(
(await queue.enqueue(request("", { operationId: 9 }))).status,
"invalid-request",
);
assert.equal(
(
await queue.enqueue(
request("recreated", { expectedFileCtime: 9, operationId: 10 }),
)
).status,
"target-changed",
);
assert.equal(
(await queue.enqueue(request("fail", { operationId: 11 }))).status,
"failed",
);
assert.equal(
backups.includes("Drawing.md:fail"),
false,
"a failed source write must preserve the prior backup",
);
const backupsBeforeEmptySceneWrite = backups.length;
assert.equal(
(
await queue.enqueue(
request("empty-scene", {
operationId: 12,
hasNonDeletedElements: false,
}),
)
).status,
"persisted",
);
assert.equal(
backups.length,
backupsBeforeEmptySceneWrite,
"a successful empty-scene write preserves the prior backup",
);
assert.equal(
(await queue.enqueue(request("backup-schedule-fail", { operationId: 13 })))
.status,
"persisted",
"backup scheduling failure does not reclassify source persistence",
);
assert.deepEqual(backupScheduleFailures, ["backup-schedule-fail"]);
assert.equal(
(await queue.enqueue(request("after-failure", { operationId: 14 }))).status,
"persisted",
"a failed request does not strand later work",
);
assert.equal(
(
await queue.enqueue(
request("completion-callback-fail", { operationId: 15 }),
)
).status,
"persisted",
"a completion callback failure cannot reclassify a successful source write",
);
assert.deepEqual(
persistedCallbacks,
[
"first",
"second",
"behind-live",
"migration",
"behind-migration",
"after-discard",
"empty-scene",
"backup-schedule-fail",
"after-failure",
"completion-callback-fail",
],
"only successful physical writes publish persistence completion",
);
assert.deepEqual(persistedCallbackFailures, ["completion-callback-fail"]);
assert.deepEqual(failures, [
"target-changed",
"target-missing",
"invalid-request",
"target-changed",
"failed",
]);
let fakeNow = 0;
let cleanupCallback = null;
const expiryWrites = [];
const expiryFailures = [];
const expiryQueue = new ViewPersistenceQueue({
resolveFile: (path) => files.get(path) ?? null,
write: async (file, text) => expiryWrites.push(`${file.path}:${text}`),
scheduleBackup: () => undefined,
now: () => fakeNow,
scheduleCleanup: (callback) => {
cleanupCallback = callback;
return 1;
},
cancelCleanup: () => {
cleanupCallback = null;
},
handoffTtlMs: 10,
onFailure: (result) => expiryFailures.push(result.status),
});
expiryQueue.registerMigrationHandoff({
leafId: "leaf-expired",
request: request("expired-migration", {
operationId: 16,
reason: "window-migration",
}),
});
const behindExpiredMigration = expiryQueue.enqueue(
request("after-expiry", { operationId: 17 }),
);
assert.ok(cleanupCallback, "an abandoned handoff has a bounded cleanup");
fakeNow = 10;
cleanupCallback();
assert.equal((await behindExpiredMigration).status, "persisted");
assert.deepEqual(expiryWrites, ["Drawing.md:after-expiry"]);
assert.deepEqual(expiryFailures, ["handoff-expired"]);
log("view persistence queue checks passed");
+5 -2
View File
@@ -44,6 +44,7 @@ In addition to ExcalidrawAutomate, you can also use two other sources of functio
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
- **Never use native browser dialogs in scripts:** Do not use \`window.confirm\`, \`window.alert\`, \`window.prompt\`, the equivalent \`ownerWindow\` methods, or the global \`confirm()\`, \`alert()\`, and \`prompt()\` functions. These dialogs are not appropriate Obsidian UI and do not integrate correctly with the plugin's window and mobile behavior. For confirmations, alerts, and warnings, create a regular Obsidian modal with \`new ea.obsidian.Modal(ea.plugin.app)\` (not \`FloatingModal\`), render the message and buttons in \`contentEl\`, and resolve the result from the modal's button callbacks or \`onClose\` handler. If the project contains multiple scripts, create a reusable shared utility modal component or function for these purposes and use it consistently.
- 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.
@@ -120,7 +121,8 @@ To keep this training file concise, large external type definitions are not incl
ea.clear();
}
\`\`\`
* **\`elementsOverride\` is a complete replacement:** In \`createViewSVG()\`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the SVG. When temporarily modifying an existing scene for export, the simplest safe workflow is to copy the complete desired export set into EA, modify the workbench copy, and pass \`ea.getElements()\` as the override.
* **\`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()\`.
@@ -130,6 +132,7 @@ To keep this training file concise, large external type definitions are not incl
* **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.
* **Confirmations, Alerts, and Warnings:** Never use native browser dialogs such as \`window.confirm()\`, \`window.alert()\`, \`window.prompt()\`, \`ownerWindow.confirm()\`, or their global equivalents. Use a regular Obsidian modal instead: \`const modal = new ea.obsidian.Modal(ea.plugin.app)\`. Render the message and explicit action buttons in \`modal.contentEl\`, then resolve the user's choice from the button callbacks or \`onClose\`. Do not use \`FloatingModal\` for these simple confirmation or alert/warning dialogs. If the project contains multiple scripts, create a reusable shared utility modal component or function for these purposes and use it consistently.
* **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\`.
@@ -197,7 +200,7 @@ To keep this training file concise, large external type definitions are not incl
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. Its \`elementsOverride\` parameter is a complete replacement for the exported element array, not an additive injection or a patch by ID. If supplied, include every existing or temporary element that should appear in the SVG. For temporary changes to existing elements, copy the complete desired export set into the EA workbench, modify it there, and pass \`ea.getElements()\`.
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**
+21
View File
@@ -0,0 +1,21 @@
/**
* Browser entry for the private React runtime shared by all Excalidraw views.
*
* Keep these exports aligned with the lexical externals configured by the
* Excalidraw `build:obsidian` package target.
*/
import React from "react";
import ReactDOMLegacy from "react-dom";
import * as ReactDOMClient from "react-dom/client";
import * as jsxDevRuntime from "react/jsx-dev-runtime";
import * as jsxRuntime from "react/jsx-runtime";
const ReactDOM = Object.assign({}, ReactDOMLegacy, ReactDOMClient);
const ReactJSXRuntime = jsxRuntime;
const ReactJSXDevRuntime = Object.assign({}, jsxDevRuntime, {
// Keep a callable production fallback for bundles compiled against the
// development JSX runtime entrypoint.
jsxDEV: jsxDevRuntime.jsxDEV || jsxRuntime.jsx,
});
export { React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime };
+3
View File
@@ -119,6 +119,7 @@ export let {
loadMermaid,
syncInvalidIndices,
getDefaultColorPalette,
convertToExcalidrawElements,
} = excalidrawLib;
export function updateExcalidrawLib() {
@@ -138,6 +139,7 @@ export function updateExcalidrawLib() {
"getLineHeight",
"restoreElements",
"restoreLibraryItems",
"convertToExcalidrawElements",
];
for (const fnName of requiredFunctions) {
@@ -178,6 +180,7 @@ export function updateExcalidrawLib() {
loadMermaid,
syncInvalidIndices,
getDefaultColorPalette,
convertToExcalidrawElements,
} = excalidrawLib);
} catch (error) {
if (error instanceof Error || typeof error === "string") {
+4
View File
@@ -62,6 +62,10 @@ export const URL_REGISTRY = {
"https://github.com/zsviczian/obsidian-excalidraw-plugin/issues",
UrlPurpose.DOCS,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_EXTRAS_ISSUES: defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-extras/issues",
UrlPurpose.RELEASE_LOG,
),
API_OPENAI_COM_V1: defineUrl("https://api.openai.com/v1", UrlPurpose.AI_API),
API_ANTHROPIC_COM_V1: defineUrl(
"https://api.anthropic.com/v1",
+7
View File
@@ -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);
-13
View File
@@ -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
);
+1
View File
@@ -14,6 +14,7 @@ export type {
StrokeStyle,
} from "@zsviczian/excalidraw/types/element/src/types";
export type { Point } from "src/types/types";
export type { MathJaxRenderOptions } from "src/types/mathJaxTypes";
export const getEA = (view?: ExcalidrawView): ExcalidrawAutomate | null => {
try {
return window.ExcalidrawAutomate.getAPI(view);
+143 -34
View File
@@ -71,7 +71,10 @@ import {
emulateCTRLClickForLinks,
linkClickModifierType,
} from "../utils/modifierkeyHelper";
import { getImageCache } from "../shared/ImageCache";
import {
getImageCache,
scheduleBAKAfterSuccessfulPersistence,
} from "../shared/ImageCache";
import { StylesManager } from "./managers/StylesManager";
import { CustomMutationObserver, log } from "../utils/debugHelper";
import { ExcalidrawConfig } from "../shared/ExcalidrawConfig";
@@ -111,16 +114,24 @@ 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";
import {
type ViewMigrationPersistenceConsumption,
type ViewMigrationPersistenceHandoff,
ViewPersistenceQueue,
type ViewPersistenceRequest,
type ViewPersistenceWriteLease,
} from "./managers/ViewPersistenceQueue";
import {
AutoexportCoordinator,
type PreparedAutoexportRequest,
} from "./managers/AutoexportCoordinator";
import { errorlog } from "../utils/coreUtils";
declare const PLUGIN_VERSION: string;
declare const INITIAL_TIMESTAMP: number;
@@ -168,13 +179,14 @@ export default class ExcalidrawPlugin extends Plugin {
private fontManager: FontManager;
private startupTimer: StartupTimer;
private viewMigrationHandoffManager: ViewMigrationHandoffManager;
private viewMigrationPersistenceHandoffManager: ViewMigrationPersistenceHandoffManager;
private viewPersistenceQueue: ViewPersistenceQueue;
private autoexportCoordinator: AutoexportCoordinator;
public stencilLibraryManager: StencilLibraryManager;
public eaInstances = new WeakArray<ExcalidrawAutomate>();
public fourthFontLoaded: boolean = false;
public excalidrawConfig: ExcalidrawConfig;
public excalidrawFileModes: { [file: string]: string } = {};
public declare settings: ExcalidrawSettings;
declare public settings: ExcalidrawSettings;
/** Session-scoped autosave gate controlled by the temporary commands. */
public autosaveEnabled: boolean = true;
public activeExcalidrawView: ExcalidrawView = null;
@@ -213,8 +225,65 @@ export default class ExcalidrawPlugin extends Plugin {
this.loadTimestamp = INITIAL_TIMESTAMP;
this.startupTimer = new StartupTimer(this.loadTimestamp, PLUGIN_VERSION);
this.viewMigrationHandoffManager = new ViewMigrationHandoffManager();
this.viewMigrationPersistenceHandoffManager =
new ViewMigrationPersistenceHandoffManager();
const persistenceApp = this.app;
const persistenceWindow = window;
this.autoexportCoordinator = new AutoexportCoordinator(this, {
now: () => Date.now(),
setTimeout: (callback, delayMs) =>
persistenceWindow.setTimeout(callback, delayMs),
clearTimeout: (timer) => persistenceWindow.clearTimeout(timer),
});
this.viewPersistenceQueue = new ViewPersistenceQueue({
resolveFile: (filePath) => persistenceApp.vault.getFileByPath(filePath),
write: (file, text) => persistenceApp.vault.modify(file, text),
scheduleBackup: scheduleBAKAfterSuccessfulPersistence,
now: () => Date.now(),
scheduleCleanup: (callback, delayMs) =>
persistenceWindow.setTimeout(callback, delayMs),
cancelCleanup: (timer) => persistenceWindow.clearTimeout(timer),
onFailure: (result) => {
errorlog({
where: "ViewPersistenceQueue",
fn: result.request.reason,
error: result.error,
});
new Notice(t("WARNING_SERIOUS_ERROR"), 60000);
},
onBackupScheduleFailure: (error) => {
errorlog({
where: "ViewPersistenceQueue",
fn: "scheduleBackup",
error,
});
},
onPersisted: (request) => {
if (request.autoexportRequest) {
if (
request.reason === "window-migration" &&
request.migrationLeafId
) {
this.autoexportCoordinator.deferUntilMigrationComplete(
request.migrationLeafId,
request.autoexportRequest,
);
} else {
this.autoexportCoordinator.enqueue(request.autoexportRequest);
}
}
},
onPersistedCallbackFailure: (error) => {
errorlog({
where: "AutoexportCoordinator",
fn: "onPersisted",
error,
});
},
beginPersistenceActivity: (request) =>
this.autoexportCoordinator.beginSaveActivity(
request.filePath,
request.expectedFileCtime,
),
});
this.filesMaster = new Map<
FileId,
{
@@ -620,16 +689,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();
}
@@ -758,9 +818,10 @@ 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 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");
@@ -772,7 +833,11 @@ export default class ExcalidrawPlugin extends Plugin {
log(fname);
const initialMarkdown =
FRONTMATTER + (await this.fileManager.exportSceneToMD(data, false));
const result = await createOrOverwriteFile(this.app, fname, initialMarkdown);
const result = await createOrOverwriteFile(
this.app,
fname,
initialMarkdown,
);
if (hasEmbeddedFiles) {
const convertedMarkdown =
await this.fileManager.persistLegacySceneFilesInMarkdown(
@@ -933,6 +998,7 @@ export default class ExcalidrawPlugin extends Plugin {
excalidrawViews.forEach(({ leaf }) => {
void this.setMarkdownView(leaf);
});
this.autoexportCoordinator.destroy();
if (versionUpdateCheckTimer) {
window.clearTimeout(versionUpdateCheckTimer);
@@ -996,7 +1062,6 @@ export default class ExcalidrawPlugin extends Plugin {
delete window.PolyBool;
this.packageManager.destroy();
this.viewMigrationHandoffManager.destroy();
this.viewMigrationPersistenceHandoffManager.destroy();
this.commandManager?.destroy();
this.eventManager.destroy();
terminateCompressionWorker();
@@ -1057,9 +1122,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
}
public getStencilLibrary():
| StencilLibraryData
| Promise<StencilLibraryData> {
public getStencilLibrary(): StencilLibraryData | Promise<StencilLibraryData> {
return this.stencilLibraryManager.getLibrary().then((libraryItems) => ({
type: "excalidrawlib" as const,
version: 2,
@@ -1287,23 +1350,69 @@ export default class ExcalidrawPlugin extends Plugin {
public registerViewMigrationPersistenceHandoff(
handoff: ViewMigrationPersistenceHandoff,
): void {
this.viewMigrationPersistenceHandoffManager.register(handoff);
this.viewPersistenceQueue.registerMigrationHandoff(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,
);
): ViewMigrationPersistenceConsumption | null {
return this.viewPersistenceQueue.consumeMigrationHandoff(leafId, filePath);
}
/** Discards a handoff when the old view could not be replaced. */
public discardViewMigrationPersistenceHandoff(leafId: string): void {
this.viewMigrationPersistenceHandoffManager.discard(leafId);
this.viewPersistenceQueue.discardMigrationHandoff(leafId);
}
/** Transfers immutable drawing text out of a retiring view runtime. */
public handoffViewPersistence(request: ViewPersistenceRequest): void {
void this.viewPersistenceQueue.enqueue(request);
}
/** Submits an immutable autoexport after a successful live source write. */
public enqueuePreparedAutoexport(request: PreparedAutoexportRequest): void {
this.autoexportCoordinator.enqueue(request);
}
/** Marks one view save queue active for automatic-export coalescing. */
public beginAutoexportSaveActivity(
sourceFilePath: string,
sourceFileCtime: number,
): () => void {
return this.autoexportCoordinator.beginSaveActivity(
sourceFilePath,
sourceFileCtime,
);
}
/** Holds heavy migration autoexport work until the replacement view loads. */
public deferPreparedAutoexportUntilMigrationComplete(
leafId: string,
request: PreparedAutoexportRequest,
): void {
this.autoexportCoordinator.deferUntilMigrationComplete(leafId, request);
}
/** Releases or discards a migration export after replacement load settles. */
public completeMigrationAutoexport(
leafId: string,
filePath: string,
loadSucceeded: boolean,
): void {
this.autoexportCoordinator.completeMigration(
leafId,
filePath,
loadSucceeded,
);
}
/** Reserves the plugin-owned per-path boundary for a live view write. */
public acquireViewPersistenceWriteLease(
filePath: string,
): Promise<ViewPersistenceWriteLease> {
return this.viewPersistenceQueue.acquireWriteLease(filePath);
}
get taskbone() {
+475
View File
@@ -0,0 +1,475 @@
import type { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import type { BinaryFileData } from "@zsviczian/excalidraw/types/excalidraw/types";
import { normalizePath, type TFile } from "obsidian";
import type ExcalidrawPlugin from "../main";
import {
EmbeddedFile,
EmbeddedFilesLoader,
type EmbeddedFilesDataSource,
} from "../../shared/EmbeddedFileLoader";
import type { FileData } from "../../types/embeddedFileLoaderTypes";
import type { ExportSettings } from "../../types/exportUtilTypes";
import type { ExcalidrawViewScene } from "../../types/excalidrawViewTypes";
import { errorlog } from "../../utils/coreUtils";
import { createOrOverwriteFile } from "../../utils/fileUtils";
import { sceneRemoveInternalLinks } from "../../utils/excalidrawViewUtils";
import { getPNG, getSVG } from "../../utils/utils";
import {
cloneSceneForSave,
type PreparedSaveExportData,
type PreparedSaveExportOptions,
type SaveOperationContext,
} from "../../view/managers/saveSnapshot";
import {
AutoexportJobQueue,
type AutoexportJobGuard,
} from "./AutoexportJobQueue";
import {
AutoexportSaveBatchGate,
type AutoexportSaveBatchScheduler,
} from "./AutoexportSaveBatchGate";
import { KeyedAsyncLock } from "./KeyedAsyncLock";
const MIGRATION_AUTOEXPORT_TTL_MS = 60_000;
const AUTOEXPORT_SAVE_BATCH_SETTLE_MS = 500;
export type AutoexportFormat = "svg" | "png" | "excalidraw";
export type AutoexportTheme = "light" | "dark" | null;
export interface PreparedAutoexportOutput {
readonly format: AutoexportFormat;
readonly theme: AutoexportTheme;
readonly destinationPath: string;
}
interface PreparedAutoexportRequestBase extends SaveOperationContext {
readonly sourceFilePath: string;
readonly sourceFileCtime: number;
readonly capturedRevision: number;
}
/** Lightweight marker preventing an older revision from writing stale output. */
export interface PreparedAutoexportBarrierRequest extends PreparedAutoexportRequestBase {
readonly kind: "barrier";
readonly outputs: readonly [];
}
/** Immutable render intent captured while the originating view is alive. */
export interface PreparedAutoexportRenderRequest extends PreparedAutoexportRequestBase {
readonly kind: "render";
readonly scene: ExcalidrawViewScene;
readonly exportOptions: PreparedSaveExportOptions;
readonly exportData: PreparedSaveExportData | null;
readonly outputs: readonly PreparedAutoexportOutput[];
}
export type PreparedAutoexportRequest =
| PreparedAutoexportBarrierRequest
| PreparedAutoexportRenderRequest;
interface ThemeExportContext {
readonly scene: ExcalidrawViewScene;
readonly overrideFiles: Record<FileId, BinaryFileData> | null;
}
interface AutoexportScheduler extends AutoexportSaveBatchScheduler {
readonly now: () => number;
}
interface DeferredMigrationAutoexport {
readonly request: PreparedAutoexportRenderRequest;
readonly expiresAt: number;
readonly timer: number;
}
/**
* Runs automatic exports after successful source persistence.
*
* One request is active per source identity and only its newest trailing
* request is retained. Heavy rendering is serialized globally and yields
* between formats. Final writes additionally compare the hook-resolved
* destination, preventing an older render from overwriting newer output.
*/
export class AutoexportCoordinator {
private readonly queue: AutoexportJobQueue<PreparedAutoexportRequest>;
private readonly saveBatchGate: AutoexportSaveBatchGate<PreparedAutoexportRequest>;
private readonly renderExecution = new KeyedAsyncLock();
private readonly destinationWrites = new KeyedAsyncLock();
private readonly deferredMigrations = new Map<
string,
DeferredMigrationAutoexport
>();
public constructor(
private readonly plugin: ExcalidrawPlugin,
private readonly scheduler: AutoexportScheduler,
) {
this.queue = new AutoexportJobQueue({
getSourceKey: (request) => this.getSourceKey(request),
getDestinationKeys: (request) =>
request.outputs.map((output) => normalizePath(output.destinationPath)),
execute: (request, guard) =>
this.renderExecution.run("autoexport-render", () =>
this.execute(request, guard),
),
onFailure: (error) => {
errorlog({
where: "AutoexportCoordinator",
fn: "queue",
error,
});
},
schedule: (callback) => {
this.scheduler.setTimeout(callback, 0);
},
});
this.saveBatchGate = new AutoexportSaveBatchGate({
scheduler: this.scheduler,
settleDelayMs: AUTOEXPORT_SAVE_BATCH_SETTLE_MS,
getSourceKey: (request) => this.getSourceKey(request),
shouldRender: (request) => request.kind === "render",
invalidate: (request) => this.queue.enqueue(this.createBarrier(request)),
release: (request) => this.queue.enqueue(request),
});
}
/** Accepts one prepared request in successful source-write order. */
public enqueue(request: PreparedAutoexportRequest): void {
this.saveBatchGate.publish(request);
}
/** Holds automatic rendering while one view drains its save queue. */
public beginSaveActivity(
sourceFilePath: string,
sourceFileCtime: number,
): () => void {
return this.saveBatchGate.beginActivity(
this.getSourceKeyFromIdentity(sourceFilePath, sourceFileCtime),
);
}
/** Defers migration rendering while immediately invalidating older output. */
public deferUntilMigrationComplete(
leafId: string,
request: PreparedAutoexportRequest,
): void {
this.queue.enqueue(this.createBarrier(request));
const previous = this.deferredMigrations.get(leafId);
if (previous) {
this.scheduler.clearTimeout(previous.timer);
this.deferredMigrations.delete(leafId);
}
if (request.kind === "barrier") {
return;
}
const expiresAt = this.scheduler.now() + MIGRATION_AUTOEXPORT_TTL_MS;
const deferred: DeferredMigrationAutoexport = {
request,
expiresAt,
timer: this.scheduler.setTimeout(() => {
if (this.deferredMigrations.get(leafId) === deferred) {
this.deferredMigrations.delete(leafId);
}
}, MIGRATION_AUTOEXPORT_TTL_MS),
};
this.deferredMigrations.set(leafId, deferred);
}
/** Releases or discards the render after the replacement load settles. */
public completeMigration(
leafId: string,
filePath: string,
loadSucceeded: boolean,
): void {
const deferred = this.deferredMigrations.get(leafId);
if (!deferred) {
return;
}
this.deferredMigrations.delete(leafId);
this.scheduler.clearTimeout(deferred.timer);
if (
loadSucceeded &&
deferred.expiresAt > this.scheduler.now() &&
deferred.request.sourceFilePath === filePath
) {
this.enqueue(deferred.request);
}
}
/** Prevents work owned by an unloaded plugin runtime from writing later. */
public destroy(): void {
for (const deferred of this.deferredMigrations.values()) {
this.scheduler.clearTimeout(deferred.timer);
}
this.deferredMigrations.clear();
this.saveBatchGate.destroy();
this.queue.destroy();
}
private createBarrier(
request: PreparedAutoexportRequest,
): PreparedAutoexportBarrierRequest {
return {
kind: "barrier",
producerId: request.producerId,
targetGeneration: request.targetGeneration,
operationId: request.operationId,
requestedRevision: request.requestedRevision,
sourceFilePath: request.sourceFilePath,
sourceFileCtime: request.sourceFileCtime,
capturedRevision: request.capturedRevision,
outputs: [],
};
}
private async execute(
request: PreparedAutoexportRequest,
guard: AutoexportJobGuard,
): Promise<void> {
if (!guard.isCurrentSource()) {
return;
}
const sourceFile = this.resolveSourceFile(request);
if (!sourceFile) {
return;
}
if (request.kind === "barrier") {
return;
}
const themeContexts = new Map<
"light" | "dark",
Promise<ThemeExportContext>
>();
for (const output of request.outputs) {
if (!guard.isCurrentSource()) {
return;
}
// Export rendering is main-thread work. Yield between formats so input,
// paint, and lifecycle tasks can run even when a save requests multiple
// expensive outputs. The render itself is not preemptible.
await this.yieldToMainTask();
if (!guard.isCurrentSource()) {
return;
}
try {
let content: string | Blob;
if (output.format === "excalidraw") {
content = JSON.stringify(request.scene, null, "\t");
} else {
const theme = output.theme ?? request.exportOptions.theme;
let contextPromise = themeContexts.get(theme);
if (contextPromise === undefined) {
contextPromise = this.prepareThemeContext(
request,
sourceFile,
theme,
);
themeContexts.set(theme, contextPromise);
}
const context = await contextPromise;
if (!guard.isCurrentSource()) {
return;
}
content =
output.format === "svg"
? await this.renderSVG(request, sourceFile, theme, context)
: await this.renderPNG(request, theme, context);
}
await this.writeIfCurrent(request, guard, output, content);
} catch (error: unknown) {
errorlog({
where: "AutoexportCoordinator",
fn: `${output.format}:${output.theme ?? "scene"}`,
error,
});
}
}
}
private async prepareThemeContext(
request: PreparedAutoexportRenderRequest,
sourceFile: TFile,
theme: "light" | "dark",
): Promise<ThemeExportContext> {
const scene = request.exportOptions.includeInternalLinks
? request.scene
: {
...request.scene,
elements: sceneRemoveInternalLinks(request.scene),
};
const sourceTheme = scene.appState.theme === "dark" ? "dark" : "light";
if (theme === sourceTheme || !request.exportData) {
return { scene, overrideFiles: null };
}
const dataSource = this.createDataSource(
request.exportData,
sourceFile,
scene,
);
const loader = new EmbeddedFilesLoader(this.plugin, theme === "dark");
const collected: Record<FileId, BinaryFileData> = {};
await new Promise<void>((resolve, reject) => {
void loader
.loadSceneFiles({
excalidrawData: dataSource,
sceneElements: scene.elements,
addFiles: (
files: FileData[],
_isDark: boolean,
final: boolean = true,
) => {
for (const file of files ?? []) {
collected[file.id] = { ...file };
}
if (final) {
resolve();
}
},
depth: 0,
isThemeChange: true,
markdownImageRenderDefaults:
request.exportData.markdownImageRenderDefaults,
pdfScale: request.exportData.pdfScale,
})
.catch(reject);
});
return {
scene,
overrideFiles: Object.keys(collected).length ? collected : null,
};
}
private createDataSource(
exportData: PreparedSaveExportData,
sourceFile: TFile,
scene: ExcalidrawViewScene,
): EmbeddedFilesDataSource {
const files = new Map(
Array.from(exportData.files, ([id, state]) => [
id,
EmbeddedFile.fromPreparedSaveState(this.plugin, state),
]),
);
return {
file: sourceFile,
scene: scene as EmbeddedFilesDataSource["scene"],
getFileEntries: () => files.entries(),
getFile: (fileId) => files.get(fileId),
getMarkdownImage: (fileId) => exportData.markdownImages.get(fileId),
getEquationEntries: () => exportData.equations.entries(),
getEquation: (fileId) => exportData.equations.get(fileId),
};
}
private async renderSVG(
request: PreparedAutoexportRenderRequest,
sourceFile: TFile,
theme: "light" | "dark",
context: ThemeExportContext,
): Promise<string> {
const scene = this.createRenderScene(request, theme, context.scene);
const settings = this.getExportSettings(request, true);
const svg = await getSVG(
scene,
settings,
request.exportOptions.padding,
sourceFile,
context.overrideFiles ?? undefined,
);
if (!svg) {
throw new Error("SVG renderer returned no output");
}
return svg.outerHTML;
}
private async renderPNG(
request: PreparedAutoexportRenderRequest,
theme: "light" | "dark",
context: ThemeExportContext,
): Promise<Blob> {
const png = await getPNG(
this.createRenderScene(request, theme, context.scene),
this.getExportSettings(request, false),
request.exportOptions.padding,
request.exportOptions.scale,
context.overrideFiles ?? undefined,
);
if (!png) {
throw new Error("PNG renderer returned no output");
}
return png;
}
private createRenderScene(
request: PreparedAutoexportRenderRequest,
theme: "light" | "dark",
preparedScene: ExcalidrawViewScene,
): ExcalidrawViewScene {
const scene = cloneSceneForSave(preparedScene);
scene.appState = {
...scene.appState,
theme,
exportEmbedScene: request.exportOptions.embedScene,
};
return scene;
}
private getExportSettings(
request: PreparedAutoexportRenderRequest,
isSVG: boolean,
): ExportSettings {
return {
withBackground: request.exportOptions.withBackground,
withTheme: true,
isMask: request.exportOptions.isMask,
...(isSVG ? { skipInliningFonts: false } : {}),
};
}
private async writeIfCurrent(
request: PreparedAutoexportRequest,
guard: AutoexportJobGuard,
output: PreparedAutoexportOutput,
content: string | Blob,
): Promise<void> {
const destinationPath = normalizePath(output.destinationPath);
await this.destinationWrites.run(destinationPath, async () => {
if (
!guard.isCurrentSource() ||
!guard.isCurrentDestination(destinationPath) ||
!this.resolveSourceFile(request)
) {
return;
}
await createOrOverwriteFile(this.plugin.app, destinationPath, content);
});
}
private resolveSourceFile(request: PreparedAutoexportRequest): TFile | null {
const file = this.plugin.app.vault.getFileByPath(request.sourceFilePath);
return file && file.stat.ctime === request.sourceFileCtime ? file : null;
}
private getSourceKey(request: PreparedAutoexportRequest): string {
return this.getSourceKeyFromIdentity(
request.sourceFilePath,
request.sourceFileCtime,
);
}
private getSourceKeyFromIdentity(
sourceFilePath: string,
sourceFileCtime: number,
): string {
return `${sourceFilePath}\u0000${sourceFileCtime}`;
}
private yieldToMainTask(): Promise<void> {
return new Promise((resolve) => {
this.scheduler.setTimeout(resolve, 0);
});
}
}
+169
View File
@@ -0,0 +1,169 @@
export interface AutoexportJobGuard {
readonly sequence: number;
isCurrentSource(): boolean;
isCurrentDestination(destinationKey: string): boolean;
}
interface AutoexportJobQueueOptions<T> {
readonly getSourceKey: (job: T) => string;
readonly getDestinationKeys: (job: T) => readonly string[];
readonly execute: (job: T, guard: AutoexportJobGuard) => Promise<void>;
readonly onFailure?: (error: unknown) => void;
readonly schedule?: (callback: () => void) => void;
}
interface ScheduledJob<T> {
readonly sequence: number;
readonly destinationKeys: readonly string[];
readonly job: T;
}
interface SourceJobState<T> {
active: boolean;
trailing: ScheduledJob<T> | null;
}
/** One active job and one newest trailing job for each source identity. */
export class AutoexportJobQueue<T> {
private destroyed = false;
private sequence = 0;
private readonly sourceStates = new Map<string, SourceJobState<T>>();
private readonly latestSourceSequence = new Map<string, number>();
private readonly latestDestinationSequence = new Map<string, number>();
private readonly destinationReferences = new Map<string, number>();
public constructor(private readonly options: AutoexportJobQueueOptions<T>) {}
public enqueue(job: T): void {
if (this.destroyed) {
return;
}
const sourceKey = this.options.getSourceKey(job);
const scheduled = {
sequence: ++this.sequence,
destinationKeys: Array.from(
new Set(this.options.getDestinationKeys(job)),
),
job,
} satisfies ScheduledJob<T>;
this.latestSourceSequence.set(sourceKey, scheduled.sequence);
for (const destinationKey of scheduled.destinationKeys) {
this.latestDestinationSequence.set(destinationKey, scheduled.sequence);
this.destinationReferences.set(
destinationKey,
(this.destinationReferences.get(destinationKey) ?? 0) + 1,
);
}
const state = this.sourceStates.get(sourceKey) ?? {
active: false,
trailing: null,
};
this.sourceStates.set(sourceKey, state);
if (state.active) {
if (state.trailing) {
this.releaseDestinations(state.trailing);
}
state.trailing = scheduled;
return;
}
state.active = true;
this.scheduleDrain(sourceKey, state, scheduled);
}
/** Invalidates pending/final-write guards without interrupting source saves. */
public destroy(): void {
if (this.destroyed) {
return;
}
this.destroyed = true;
for (const state of this.sourceStates.values()) {
if (state.trailing) {
this.releaseDestinations(state.trailing);
state.trailing = null;
}
}
this.latestSourceSequence.clear();
this.latestDestinationSequence.clear();
this.destinationReferences.clear();
}
private async drain(
sourceKey: string,
state: SourceJobState<T>,
first: ScheduledJob<T>,
): Promise<void> {
let scheduled: ScheduledJob<T> | null = first;
while (scheduled) {
try {
await this.options.execute(
scheduled.job,
this.createGuard(sourceKey, scheduled),
);
} catch (error: unknown) {
try {
this.options.onFailure?.(error);
} catch {
// Diagnostic failure must not strand the source queue.
}
} finally {
this.releaseDestinations(scheduled);
}
scheduled = state.trailing;
state.trailing = null;
}
state.active = false;
if (state.trailing) {
const trailing = state.trailing;
state.trailing = null;
state.active = true;
this.scheduleDrain(sourceKey, state, trailing);
} else {
this.sourceStates.delete(sourceKey);
this.latestSourceSequence.delete(sourceKey);
}
}
private scheduleDrain(
sourceKey: string,
state: SourceJobState<T>,
scheduled: ScheduledJob<T>,
): void {
const start = () => {
void this.drain(sourceKey, state, scheduled);
};
if (this.options.schedule) {
this.options.schedule(start);
return;
}
queueMicrotask(start);
}
private createGuard(
sourceKey: string,
scheduled: ScheduledJob<T>,
): AutoexportJobGuard {
return {
sequence: scheduled.sequence,
isCurrentSource: () =>
this.latestSourceSequence.get(sourceKey) === scheduled.sequence,
isCurrentDestination: (destinationKey) =>
this.latestDestinationSequence.get(destinationKey) ===
scheduled.sequence,
};
}
private releaseDestinations(scheduled: ScheduledJob<T>): void {
for (const destinationKey of scheduled.destinationKeys) {
const references =
(this.destinationReferences.get(destinationKey) ?? 1) - 1;
if (references > 0) {
this.destinationReferences.set(destinationKey, references);
} else {
this.destinationReferences.delete(destinationKey);
this.latestDestinationSequence.delete(destinationKey);
}
}
}
}
@@ -0,0 +1,134 @@
export interface AutoexportSaveBatchScheduler {
readonly setTimeout: (callback: () => void, delayMs: number) => number;
readonly clearTimeout: (timer: number) => void;
}
interface AutoexportSaveBatchGateOptions<T> {
readonly scheduler: AutoexportSaveBatchScheduler;
readonly settleDelayMs: number;
readonly getSourceKey: (request: T) => string;
readonly shouldRender: (request: T) => boolean;
readonly invalidate: (request: T) => void;
readonly release: (request: T) => void;
}
interface SourceBatchState<T> {
activityCount: number;
pending: T | null;
timer: number | null;
}
/** Coalesces persisted snapshots until every known save loop is idle. */
export class AutoexportSaveBatchGate<T> {
private destroyed = false;
private readonly sourceStates = new Map<string, SourceBatchState<T>>();
public constructor(
private readonly options: AutoexportSaveBatchGateOptions<T>,
) {}
/** Marks one view-owned save loop active for a source identity. */
public beginActivity(sourceKey: string): () => void {
if (this.destroyed) {
return () => undefined;
}
const state = this.getOrCreateState(sourceKey);
state.activityCount += 1;
this.cancelTimer(state);
let released = false;
return () => {
if (released || this.destroyed) {
return;
}
released = true;
state.activityCount = Math.max(0, state.activityCount - 1);
if (state.activityCount === 0) {
this.schedulePending(sourceKey, state);
}
this.deleteIfEmpty(sourceKey, state);
};
}
/** Accepts the newest successfully persisted snapshot for one source. */
public publish(request: T): void {
if (this.destroyed) {
return;
}
const sourceKey = this.options.getSourceKey(request);
const state = this.getOrCreateState(sourceKey);
this.options.invalidate(request);
this.cancelTimer(state);
if (!this.options.shouldRender(request)) {
state.pending = null;
this.deleteIfEmpty(sourceKey, state);
return;
}
state.pending = request;
if (state.activityCount === 0) {
this.schedulePending(sourceKey, state);
}
}
public destroy(): void {
if (this.destroyed) {
return;
}
this.destroyed = true;
for (const state of this.sourceStates.values()) {
this.cancelTimer(state);
state.pending = null;
}
this.sourceStates.clear();
}
private getOrCreateState(sourceKey: string): SourceBatchState<T> {
const existing = this.sourceStates.get(sourceKey);
if (existing) {
return existing;
}
const state: SourceBatchState<T> = {
activityCount: 0,
pending: null,
timer: null,
};
this.sourceStates.set(sourceKey, state);
return state;
}
private schedulePending(sourceKey: string, state: SourceBatchState<T>): void {
if (state.pending === null || state.timer !== null) {
return;
}
state.timer = this.options.scheduler.setTimeout(() => {
state.timer = null;
if (this.destroyed || state.activityCount !== 0) {
return;
}
const pending = state.pending;
state.pending = null;
if (pending !== null) {
this.options.release(pending);
}
this.deleteIfEmpty(sourceKey, state);
}, this.options.settleDelayMs);
}
private cancelTimer(state: SourceBatchState<T>): void {
if (state.timer === null) {
return;
}
this.options.scheduler.clearTimeout(state.timer);
state.timer = null;
}
private deleteIfEmpty(sourceKey: string, state: SourceBatchState<T>): void {
if (
state.activityCount === 0 &&
state.pending === null &&
state.timer === null &&
this.sourceStates.get(sourceKey) === state
) {
this.sourceStates.delete(sourceKey);
}
}
}
+26
View File
@@ -2252,6 +2252,32 @@ export class CommandManager {
},
});
this.addCommand({
id: "refresh-scene-images",
name: t("REFRESH_SCENE_IMAGES"),
checkCallback: (checking: boolean) => {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
const images = view
?.getViewElements()
.filter((element) => element.type === "image");
if (!view?.excalidrawAPI || !images?.length) {
return false;
}
if (!checking) {
const selected = view.getViewSelectedElements();
const targets: ExcalidrawImageElement[] =
selected.length === 1 && selected[0].type === "image"
? [selected[0]]
: images;
const fileIDs = new Set(
targets.map((element) => element.fileId),
);
void view.loadSceneFiles(false, fileIDs, undefined, fileIDs);
}
return true;
},
});
this.addCommand({
id: "insert-image",
name: t("INSERT_IMAGE"),
+2 -2
View File
@@ -365,7 +365,7 @@ export class EventManager {
//avoid double saving
if (
previouslyActiveEV?.isDirty() &&
!previouslyActiveEV.semaphores?.viewunload
!previouslyActiveEV.isClosing()
) {
await previouslyActiveEV.save(true); //this will update transclusions in the drawing
}
@@ -397,7 +397,7 @@ export class EventManager {
getChangedTopLevelDependencyFileIDs(newActiveviewEV);
if (changedDependencyFileIDs.size > 0) {
// Reload only top-level embeds whose own file changed or whose
// dependency tree contains a newer nested Excalidraw file.
// dependency tree contains a newer nested visual source.
newActiveviewEV.scheduleSceneFileDeferredValidation(
changedDependencyFileIDs,
false,
+33 -40
View File
@@ -50,6 +50,10 @@ 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 {
getDrawingModifyRoute,
shouldInspectSuppressedModifyContent,
} from "./fileModifyRouting";
export class PluginFileManager {
private plugin: ExcalidrawPlugin;
@@ -664,26 +668,29 @@ export class PluginFileManager {
if (!(file instanceof TFile)) {
return;
}
const excalidrawViews = getExcalidrawViews(this.app);
excalidrawViews.forEach((excalidrawView) => {
void (async () => {
if (
excalidrawView.semaphores?.viewunload ||
excalidrawView.semaphores?.windowMigrating
) {
return;
}
if (
excalidrawView.file &&
(excalidrawView.file.path === file.path ||
const matchesModifiedDrawing = (view: ExcalidrawView): boolean =>
Boolean(
view.file &&
(view.file.path === file.path ||
(file.extension === "excalidraw" &&
`${file.path.substring(
0,
file.path.lastIndexOf(".excalidraw"),
)}.md` === excalidrawView.file.path))
) {
if (excalidrawView.semaphores?.preventReload) {
excalidrawView.semaphores.preventReload = false;
)}.md` === view.file.path)),
);
const excalidrawViews = getExcalidrawViews(this.app, true);
excalidrawViews.forEach((excalidrawView) => {
void (async () => {
if (excalidrawView.isClosingOrMigrating()) {
return;
}
if (matchesModifiedDrawing(excalidrawView)) {
const suppressionConsumed =
excalidrawView.consumeOwnWriteReloadSuppression();
if (
suppressionConsumed &&
!shouldInspectSuppressedModifyContent(file.extension)
) {
return;
}
@@ -716,33 +723,19 @@ export class PluginFileManager {
(activeView === excalidrawView &&
this.plugin.isRecentSplitViewSwitch());
if (
!isEditingMarkdownSideInSplitView &&
excalidrawView.lastSaveTimestamp + 300000 < Date.now()
) {
const route = getDrawingModifyRoute({
fileExtension: file.extension,
isEditingMarkdownSideInSplitView,
isDirty: excalidrawView.isDirty(),
isPersistenceBusy: excalidrawView.isPersistenceBusy(),
isStale: excalidrawView.lastSaveTimestamp + 300000 < Date.now(),
});
if (route === "full-reload") {
await excalidrawView.reload(true, excalidrawView.file);
return;
}
if (file.extension === "md") {
if (excalidrawView.semaphores?.embeddableIsEditingSelf) {
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();
if (excalidrawView?.isDirty()) {
if (
excalidrawView.autosaveTimer &&
excalidrawView.autosaveFunction
) {
window.clearTimeout(excalidrawView.autosaveTimer);
}
if (excalidrawView.autosaveFunction) {
excalidrawView.autosaveFunction();
}
}
if (route === "incremental-sync") {
excalidrawView.requestExternalSynchronization(file);
} else {
await excalidrawView.reload(true, excalidrawView.file);
}
+79 -29
View File
@@ -6,27 +6,33 @@ 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 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,
@@ -79,21 +85,32 @@ export class FontManager {
* 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"));
}
@@ -136,11 +153,20 @@ export class FontManager {
);
}
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) {
@@ -151,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) {
+27
View File
@@ -0,0 +1,27 @@
/** Serializes asynchronous operations sharing the same key. */
export class KeyedAsyncLock {
private readonly tails = new Map<string, Promise<void>>();
public async run<T>(key: string, operation: () => Promise<T>): Promise<T> {
const previous = this.tails.get(key);
let release: () => void = () => undefined;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const ready =
previous?.catch((): void => undefined) ?? Promise.resolve();
const tail = ready.then(() => gate);
this.tails.set(key, tail);
await ready;
try {
return await operation();
} finally {
release();
void tail.then(() => {
if (this.tails.get(key) === tail) {
this.tails.delete(key);
}
});
}
}
}
+15 -17
View File
@@ -5,23 +5,17 @@ import { Notice } from "obsidian";
import type ExcalidrawPlugin from "src/core/main";
import { errorHandler } from "../../utils/ErrorHandler";
import React from "react";
import * as ReactDOMLegacy from "react-dom";
import * as ReactDOMClient from "react-dom/client";
import * as ReactJSXRuntime from "react/jsx-runtime";
import * as ReactJSXDevRuntime from "react/jsx-dev-runtime";
import ReactDOM from "react-dom/client";
import { createObsidianCommonHostAdapter } from "./obsidianCommonHostAdapter";
import { createObsidianExcalidrawHostAdapter } from "./obsidianExcalidrawHostAdapter";
declare let react: typeof React;
declare let reactDOM: typeof ReactDOM & typeof import("react-dom");
declare let excalidrawLib: typeof ExcalidrawLib;
declare let ReactJSXRuntime: unknown;
declare let ReactJSXDevRuntime: unknown;
declare const unpackExcalidraw: () => string;
const reactDOM = Object.assign({}, ReactDOMLegacy, ReactDOMClient);
const reactJSXDevRuntime = Object.assign({}, ReactJSXDevRuntime, {
// React's production jsx-dev-runtime deliberately leaves jsxDEV undefined,
// while the Excalidraw artifact accepts either external runtime entrypoint.
jsxDEV: ReactJSXDevRuntime.jsxDEV ?? ReactJSXRuntime.jsx,
});
const normalizeError = (error: unknown): Error =>
error instanceof Error
? error
@@ -67,10 +61,10 @@ export class PackageManager {
window,
);
excalidrawLib = loadExcalidraw(
React,
react,
reactDOM,
ReactJSXRuntime,
reactJSXDevRuntime,
ReactJSXDevRuntime,
);
if (!excalidrawLib) {
@@ -81,7 +75,7 @@ export class PackageManager {
updateExcalidrawLib();
// Create a package with the loaded libraries
const initialPackage = { react: React, reactDOM, excalidrawLib };
const initialPackage = { react, reactDOM, excalidrawLib };
// Validate the package before storing
if (this.validatePackage(initialPackage)) {
@@ -100,10 +94,12 @@ export class PackageManager {
);
console.error("Error loading the Excalidraw package", e);
} finally {
// Per-window evaluation has been removed. Release the decompressed
// Excalidraw source after the one runtime is initialized instead of
// retaining it for hypothetical future popouts.
// 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");
@@ -315,6 +311,8 @@ export class PackageManager {
this.disposeObsidianHosts();
this.runtimePackage = null;
react = null;
reactDOM = null;
excalidrawLib = null;
} catch (error: unknown) {
errorHandler.handleError(
@@ -250,6 +250,16 @@ export class PluginSettingsManager {
delete markdownImageDefaults.theme;
didSettingsMigration = true;
}
const markdownImageDeletionPreference =
this.host.settings.markdownImageDeletionPreference;
if (
markdownImageDeletionPreference !== "ask" &&
markdownImageDeletionPreference !== "keep" &&
markdownImageDeletionPreference !== "delete"
) {
this.host.settings.markdownImageDeletionPreference = "ask";
didSettingsMigration = true;
}
const settingsRecord = this.host.settings as unknown as Record<
string,
unknown
@@ -1,95 +0,0 @@
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()),
);
}
}
+345
View File
@@ -0,0 +1,345 @@
import type { TFile } from "obsidian";
import type { PreparedAutoexportRequest } from "./AutoexportCoordinator";
const DEFAULT_HANDOFF_TTL_MS = 15_000;
export type ViewPersistenceReason = "view-unload" | "window-migration";
/** Immutable drawing text accepted from a view that may immediately retire. */
export interface ViewPersistenceRequest {
readonly producerId: string;
readonly targetGeneration: number;
readonly operationId: number;
readonly requestedRevision: number;
readonly capturedRevision: number;
readonly filePath: string;
readonly expectedFileCtime: number;
readonly text: string;
readonly hasNonDeletedElements: boolean;
readonly reason: ViewPersistenceReason;
/** Required by window migration so autoexport waits for its replacement. */
readonly migrationLeafId?: string;
readonly autoexportRequest?: PreparedAutoexportRequest;
}
export type ViewPersistenceResult =
| { readonly status: "persisted"; readonly request: ViewPersistenceRequest }
| {
readonly status:
| "invalid-request"
| "target-missing"
| "target-changed"
| "handoff-expired"
| "failed";
readonly request: ViewPersistenceRequest;
readonly error: unknown;
};
interface ViewPersistenceQueueOptions {
readonly resolveFile: (filePath: string) => TFile | null;
readonly write: (file: TFile, text: string) => Promise<void>;
readonly scheduleBackup: (filePath: string, text: string) => void;
readonly now: () => number;
readonly scheduleCleanup: (callback: () => void, delayMs: number) => number;
readonly cancelCleanup: (timer: number) => void;
readonly handoffTtlMs?: number;
readonly onFailure?: (
result: Exclude<ViewPersistenceResult, { status: "persisted" }>,
) => void;
readonly onBackupScheduleFailure?: (
error: unknown,
request: ViewPersistenceRequest,
) => void;
readonly onPersisted?: (request: ViewPersistenceRequest) => void;
readonly onPersistedCallbackFailure?: (
error: unknown,
request: ViewPersistenceRequest,
) => void;
readonly beginPersistenceActivity?: (
request: ViewPersistenceRequest,
) => () => void;
}
/**
* A data-only reservation for one drawing path. The owner must release it in
* `finally`; the queue never retains the live view performing the write.
*/
export interface ViewPersistenceWriteLease {
release(): void;
}
interface PathReservation {
readonly ready: Promise<void>;
readonly release: () => void;
}
export interface ViewMigrationPersistenceHandoff {
readonly leafId: string;
readonly request: ViewPersistenceRequest;
}
export interface ViewMigrationPersistenceConsumption {
readonly request: ViewPersistenceRequest;
readonly completion: Promise<ViewPersistenceResult>;
}
interface ViewMigrationPersistenceEntry extends ViewMigrationPersistenceHandoff {
readonly reservation: PathReservation;
readonly expiresAt: number;
}
/**
* Persists immutable drawing text after its originating view may be destroyed.
*
* Requests for one path execute in accepted order and are never coalesced:
* independent view revisions do not establish that a later arrival supersedes
* an earlier snapshot. Queue entries contain no view, DOM, Window, React root,
* package lease, or callback closing over those objects. Successful writes
* schedule their exact text for BAK before releasing the path reservation.
*
* There is intentionally no destructive `destroy()`: plugin unload starts
* asynchronous view conversions before their unload handoffs arrive. Each
* path chain releases itself after its final accepted write settles, and the
* plugin-main-window cleanup timer releases abandoned migration reservations.
*/
export class ViewPersistenceQueue {
private readonly pathTails = new Map<string, Promise<void>>();
private readonly migrationHandoffs = new Map<
string,
ViewMigrationPersistenceEntry
>();
private cleanupTimer: number | null = null;
public constructor(private readonly options: ViewPersistenceQueueOptions) {}
/** Accepts responsibility immediately and resolves after the physical write. */
public enqueue(
request: ViewPersistenceRequest,
): Promise<ViewPersistenceResult> {
const reservation = this.reservePath(request.filePath);
return this.executeReservation(request, reservation);
}
/**
* Reserves the same per-path write boundary for a live `TextFileView` save.
* Only the gate is retained here; the caller keeps and invokes its own live
* write after acquisition.
*/
public async acquireWriteLease(
filePath: string,
): Promise<ViewPersistenceWriteLease> {
const reservation = this.reservePath(filePath);
await reservation.ready;
return { release: reservation.release };
}
/**
* Reserves persistence order for immutable text supplied by a source popout.
* No Vault write starts until the replacement view consumes the handoff.
*/
public registerMigrationHandoff(
handoff: ViewMigrationPersistenceHandoff,
): void {
this.pruneExpiredHandoffs();
const reservation = this.reservePath(handoff.request.filePath);
const previous = this.migrationHandoffs.get(handoff.leafId);
this.migrationHandoffs.set(handoff.leafId, {
...handoff,
reservation,
expiresAt:
this.options.now() +
(this.options.handoffTtlMs ?? DEFAULT_HANDOFF_TTL_MS),
});
previous?.reservation.release();
this.scheduleHandoffCleanup();
}
/**
* Transfers execution ownership to the replacement main-window view. The
* returned completion represents the physical Vault write.
*/
public consumeMigrationHandoff(
leafId: string,
filePath: string,
): ViewMigrationPersistenceConsumption | null {
this.pruneExpiredHandoffs();
const entry = this.migrationHandoffs.get(leafId);
if (!entry) {
return null;
}
this.migrationHandoffs.delete(leafId);
this.scheduleHandoffCleanup();
if (entry.request.filePath !== filePath) {
this.rejectMigrationTarget(entry);
return null;
}
const completion = this.executeReservation(
entry.request,
entry.reservation,
);
return { request: entry.request, completion };
}
/** Releases ordering after a failed source-view replacement. */
public discardMigrationHandoff(leafId: string): void {
const entry = this.migrationHandoffs.get(leafId);
if (!entry) {
return;
}
this.migrationHandoffs.delete(leafId);
entry.reservation.release();
this.scheduleHandoffCleanup();
}
private reservePath(filePath: string): PathReservation {
const previous = this.pathTails.get(filePath) ?? Promise.resolve();
let releaseGate: () => void = () => undefined;
const gate = new Promise<void>((resolve) => {
releaseGate = resolve;
});
const tail = previous.then(() => gate);
this.pathTails.set(filePath, tail);
void tail.finally(() => {
if (this.pathTails.get(filePath) === tail) {
this.pathTails.delete(filePath);
}
});
let released = false;
return {
ready: previous,
release: () => {
if (released) {
return;
}
released = true;
releaseGate();
},
};
}
private async executeReservation(
request: ViewPersistenceRequest,
reservation: PathReservation,
): Promise<ViewPersistenceResult> {
await reservation.ready;
const endPersistenceActivity =
this.options.beginPersistenceActivity?.(request) ?? (() => undefined);
try {
return await this.execute(request);
} finally {
endPersistenceActivity();
reservation.release();
}
}
private rejectMigrationTarget(entry: ViewMigrationPersistenceEntry): void {
entry.reservation.release();
this.fail(
"target-changed",
entry.request,
new Error("Migration persistence handoff target no longer matches"),
);
}
private pruneExpiredHandoffs(): void {
const now = this.options.now();
for (const [leafId, entry] of this.migrationHandoffs) {
if (entry.expiresAt > now) {
continue;
}
this.migrationHandoffs.delete(leafId);
entry.reservation.release();
this.fail(
"handoff-expired",
entry.request,
new Error("Migration persistence handoff expired before replacement"),
);
}
}
private scheduleHandoffCleanup(): void {
if (this.cleanupTimer !== null) {
this.options.cancelCleanup(this.cleanupTimer);
this.cleanupTimer = null;
}
if (this.migrationHandoffs.size === 0) {
return;
}
let nextExpiry = Number.POSITIVE_INFINITY;
for (const entry of this.migrationHandoffs.values()) {
nextExpiry = Math.min(nextExpiry, entry.expiresAt);
}
this.cleanupTimer = this.options.scheduleCleanup(
() => {
this.cleanupTimer = null;
this.pruneExpiredHandoffs();
this.scheduleHandoffCleanup();
},
Math.max(0, nextExpiry - this.options.now()),
);
}
private async execute(
request: ViewPersistenceRequest,
): Promise<ViewPersistenceResult> {
if (!request.text) {
return this.fail(
"invalid-request",
request,
new Error("Detached drawing persistence payload is empty"),
);
}
const file = this.options.resolveFile(request.filePath);
if (!file) {
return this.fail(
"target-missing",
request,
new Error("Detached drawing persistence target no longer exists"),
);
}
if (file.stat.ctime !== request.expectedFileCtime) {
return this.fail(
"target-changed",
request,
new Error("Detached drawing persistence target was recreated"),
);
}
try {
await this.options.write(file, request.text);
} catch (error: unknown) {
return this.fail("failed", request, error);
}
if (request.hasNonDeletedElements) {
try {
this.options.scheduleBackup(request.filePath, request.text);
} catch (error: unknown) {
this.options.onBackupScheduleFailure?.(error, request);
}
}
try {
this.options.onPersisted?.(request);
} catch (error: unknown) {
try {
this.options.onPersistedCallbackFailure?.(error, request);
} catch {
// Secondary diagnostics cannot change a completed source write.
}
}
return { status: "persisted", request };
}
private fail(
status:
| "invalid-request"
| "target-missing"
| "target-changed"
| "handoff-expired"
| "failed",
request: ViewPersistenceRequest,
error: unknown,
): ViewPersistenceResult {
const result = { status, request, error } as const;
this.options.onFailure?.(result);
return result;
}
}
+45
View File
@@ -0,0 +1,45 @@
export type DrawingModifyRoute =
| "full-reload"
| "incremental-sync"
| "raw-reload";
/** Whether a suppressed notification must still reach content inspection. */
export const shouldInspectSuppressedModifyContent = (
fileExtension: string,
): boolean => fileExtension === "md";
interface DrawingModifyRouteInput {
fileExtension: string;
isEditingMarkdownSideInSplitView: boolean;
isDirty: boolean;
isPersistenceBusy: boolean;
isStale: boolean;
}
/**
* Selects how an open drawing consumes one matching Vault modify event.
*
* A dirty or busy Markdown view must reconcile rather than replace its live
* scene, even when the existing inactivity heuristic would otherwise request
* a full reload.
*/
export const getDrawingModifyRoute = ({
fileExtension,
isEditingMarkdownSideInSplitView,
isDirty,
isPersistenceBusy,
isStale,
}: DrawingModifyRouteInput): DrawingModifyRoute => {
if (
fileExtension === "md" &&
(isDirty || isPersistenceBusy || isEditingMarkdownSideInSplitView)
) {
return "incremental-sync";
}
if (isStale && !isEditingMarkdownSideInSplitView) {
return "full-reload";
}
return fileExtension === "md" ? "incremental-sync" : "raw-reload";
};
+44 -7
View File
@@ -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,
@@ -91,6 +91,7 @@ import {
import { SettingBindingRegistry } from "src/core/settings/SettingBindingRegistry";
import { LegacySettingsAdapter } from "src/core/settings/LegacySettingsAdapter";
import { DeclarativeSettingsAdapter } from "src/core/settings/DeclarativeSettingsAdapter";
import { makeDescriptionsReusable } from "src/core/settings/reusableSettingFragments";
import { SettingsPersistenceQueue } from "src/core/settings/SettingsPersistenceQueue";
import type {
SettingBindingKey,
@@ -1284,7 +1285,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
): SettingDefinitionItem<SettingBindingKey>[] {
this.declarativePagePathsByTag = null;
this.declarativeSettingsAdapter.beginBuild(registerBindings);
return [
return makeDescriptionsReusable([
this.createDeclarativeUtilitiesDefinition("Root", true),
this.declarativeSettingsAdapter.toDefinition(
this.getSettingsLayoutSpec(),
@@ -1292,7 +1293,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
...this.getSettingsPages().map((page) =>
this.toDeclarativePage(page),
),
];
]);
}
/**
* Returns the complete searchable settings tree when supported and selected.
@@ -1344,7 +1345,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
private addVaultPathSupport(
setting: Setting,
text: TextComponent,
kind: "file" | "folder",
kind: "file" | "folder" | "file-or-folder",
options: {
optional?: boolean;
extensions?: readonly string[];
@@ -1366,7 +1367,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
const exists = path
? kind === "folder"
? Boolean(this.app.vault.getFolderByPath(path))
: Boolean(this.app.vault.getFileByPath(path))
: kind === "file"
? Boolean(this.app.vault.getFileByPath(path))
: Boolean(
this.app.vault.getFolderByPath(path) ||
this.app.vault.getFileByPath(path) ||
this.app.metadataCache.getFirstLinkpathDest(path, ""),
)
: false;
if (createFolderButtonEl) {
setElementHidden(
@@ -1719,7 +1726,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
);
}
},
vaultPath: { kind: "folder" },
vaultPath: { kind: "folder", options: { optional: true } },
},
},
];
@@ -1802,7 +1809,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
key: "templateFilePath",
placeholder: t("TEMPLATE_PLACEHOLDER"),
vaultPath: {
kind: "file",
kind: "file-or-folder",
options: { optional: true, extensions: ["md", "excalidraw"] },
},
},
@@ -4586,6 +4593,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
private getMarkdownImageDefaultDefinitions(): SettingDefinitionItem<SettingBindingKey>[] {
return [
...this.toDeclarativeDefinitions(this.getMarkdownImageDeletionSpecs()),
this.createMarkdownDimensionDefinition({
name: t("MD_TRANSCLUDE_WIDTH_NAME"),
desc: fragWithHTML(t("MD_TRANSCLUDE_WIDTH_DESC")),
@@ -4608,6 +4616,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}
private renderMarkdownImageDefaultSettings(container: HTMLElement): void {
this.renderSettingSpecs(container, this.getMarkdownImageDeletionSpecs());
this.configureIntegerTextSetting(new Setting(container), {
name: t("MD_TRANSCLUDE_WIDTH_NAME"),
desc: fragWithHTML(t("MD_TRANSCLUDE_WIDTH_DESC")),
@@ -4626,6 +4635,34 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.renderSettingSpecs(container, this.getMarkdownImageStyleSpecs());
}
private getMarkdownImageDeletionSpecs(): SettingSpec[] {
return [
{
name: t("MARKDOWN_IMAGE_DELETE_BEHAVIOR_NAME"),
desc: t("MARKDOWN_IMAGE_DELETE_BEHAVIOR_DESC"),
aliases: ["local Markdown image deletion", "back-of-note deletion"],
control: {
type: "dropdown",
key: "markdownImageDeletionPreference",
options: [
{
value: "ask",
label: t("MARKDOWN_IMAGE_DELETE_BEHAVIOR_ASK"),
},
{
value: "keep",
label: t("MARKDOWN_IMAGE_DELETE_BEHAVIOR_KEEP"),
},
{
value: "delete",
label: t("MARKDOWN_IMAGE_DELETE_BEHAVIOR_DELETE"),
},
],
},
},
];
}
private getNonstandardSpecs(): SettingSpec[] {
return [
{
+6 -5
View File
@@ -9,13 +9,14 @@ import type {
TextControl,
} from "src/core/settings/settingSpecs";
import { configureSliderWithText } from "src/utils/sliderUtils";
import { cloneSettingFragment } from "src/core/settings/reusableSettingFragments";
/** Legacy-only services used by custom text controls. */
export interface LegacySettingsAdapterHost {
addVaultPathSupport(
setting: Setting,
text: TextComponent,
kind: "file" | "folder",
kind: "file" | "folder" | "file-or-folder",
options: NonNullable<TextControl["vaultPath"]>["options"],
): void;
}
@@ -53,8 +54,8 @@ export class LegacySettingsAdapter {
: (control.disabled ?? false);
if (control.type === "slider") {
configureSliderWithText(setting, {
name: spec.name,
desc: spec.desc,
name: cloneSettingFragment(spec.name),
desc: cloneSettingFragment(spec.desc),
value: this.bindings.getSpecValue(spec) as number,
min: control.min,
max: control.max,
@@ -66,9 +67,9 @@ export class LegacySettingsAdapter {
return;
}
setting.setName(spec.name);
setting.setName(cloneSettingFragment(spec.name));
if (spec.desc) {
setting.setDesc(spec.desc);
setting.setDesc(cloneSettingFragment(spec.desc));
}
switch (control.type) {
@@ -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 {
@@ -0,0 +1,36 @@
import type { SettingDefinitionItem } from "src/types/obsidianDeclarativeSettings";
/** A setting row may render more than once from the same definition tree. */
export function cloneSettingFragment(
value: string | DocumentFragment,
): string | DocumentFragment;
export function cloneSettingFragment(
value: string | DocumentFragment | undefined,
): string | DocumentFragment | undefined;
export function cloneSettingFragment(
value: string | DocumentFragment | undefined,
): string | DocumentFragment | undefined {
return typeof value === "string" || value === undefined
? value
: (value.cloneNode(true) as DocumentFragment);
}
/** Give Obsidian a fresh fragment each time it reads a rich description. */
export function makeDescriptionsReusable<K extends string>(
items: SettingDefinitionItem<K>[],
): SettingDefinitionItem<K>[] {
for (const item of items) {
const description = item.desc;
if (description && typeof description !== "string") {
Object.defineProperty(item, "desc", {
enumerable: true,
configurable: true,
get: () => cloneSettingFragment(description),
});
}
if ("type" in item && item.items) {
makeDescriptionsReusable(item.items);
}
}
return items;
}
+1 -1
View File
@@ -63,7 +63,7 @@ export type TextControl = SettingControlBase<string, StringSettingKey> & {
placeholder?: string;
sanitize?: (value: string) => string;
vaultPath?: {
kind: "file" | "folder";
kind: "file" | "folder" | "file-or-folder";
options?: {
optional?: boolean;
extensions?: readonly string[];
+6 -1
View File
@@ -15,7 +15,10 @@ import { DynamicStyle, GridSettings } from "src/types/types";
import { PreviewImageType } from "src/types/utilTypes";
import { PENS } from "src/utils/pens";
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
import type { MarkdownImageSettings } from "src/types/markdownImageTypes";
import type {
MarkdownImageDeletionPreference,
MarkdownImageSettings,
} from "src/types/markdownImageTypes";
import { ModifierKeySet, ModifierSetType } from "src/utils/modifierkeyHelper";
import { ANNOTATED_PREFIX, CROPPED_PREFIX } from "src/utils/carveout";
import { Rank } from "src/constants/actionIcons";
@@ -179,6 +182,7 @@ export interface ExcalidrawSettings {
mdBorderColor: string;
mdCSS: string;
markdownImageSettings: MarkdownImageSettings;
markdownImageDeletionPreference: MarkdownImageDeletionPreference;
scriptEngineSettings: {
[key: string]: {
[key: string]: ScriptSettingValue | string | number | boolean;
@@ -650,6 +654,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
},
},
},
markdownImageDeletionPreference: "ask",
scriptEngineSettings: {},
autostartScripts: {},
autostartScriptFailures: {},
+16 -3
View File
@@ -233,6 +233,16 @@ export default {
"Delete the Markdown text stored for this image? The image will be removed from the scene either way.",
MARKDOWN_IMAGE_KEEP_TEXT: "Keep Markdown text",
MARKDOWN_IMAGE_DELETE_TEXT: "Delete Markdown text",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE:
"Use this choice for future deletions",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE_DESC:
'Reset “Local Markdown image deletion” to “Ask every time” in the Excalidraw plugin settings.',
MARKDOWN_IMAGE_DELETE_BEHAVIOR_NAME: "Local Markdown image deletion",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DESC:
"Choose whether deleting a local Markdown image also deletes its back-of-note Markdown text.",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_ASK: "Ask every time",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_KEEP: "Keep text without asking",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DELETE: "Delete text without asking",
INSERT_PDF: "Insert PDF file from vault",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "Insert last active PDF page as image",
UNIVERSAL_ADD_FILE: "Insert ANY file",
@@ -298,6 +308,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",
@@ -1151,14 +1163,15 @@ export default {
"Choose exported-image background and theme behavior and whether previews follow Obsidian's theme.",
EMBED_IMAGE_CACHE_NAME: "Cache images for embedding in markdown",
EMBED_IMAGE_CACHE_DESC:
"Cache images for embedding in markdown. This will speed up the embedding process, but in case you compose images of several sub-component drawings, " +
"the embedded image in Markdown won't update until you open the drawing and save it to trigger an update of the cache.",
"Cache images for embedding in markdown. Cached drawings are refreshed when the drawing or one of its nested vault-file dependencies changes.",
SCENE_IMAGE_CACHE_NAME: "Cache nested Excalidraws in Scene",
SCENE_IMAGE_CACHE_DESC:
"Cache nested Excalidraws in the Scene for faster scene rendering. This will speed up the rendering process, especially if you have deeply nested Excalidraws in your scene. " +
"Excalidraw will try to intelligently identify if any children of a nested Excalidraw have changed and will update the cache accordingly. " +
"Excalidraw will identify changes to nested drawings and their embedded vault-file sources and update the cache accordingly. " +
"You may want to turn this off, in case you are suspecting that the cache is not updating properly.",
EMBED_IMAGE_CACHE_CLEAR: "Purge Cache",
REFRESH_SCENE_IMAGES:
"Refresh selected image or all images in the current drawing",
BACKUP_CACHE_CLEAR: "Purge Backups",
BACKUP_CACHE_CLEAR_CONFIRMATION:
"This action will delete all Excalidraw drawing backups. Backups are used as a safety measure in case your drawing file gets damaged. Each time you open Obsidian the plugin automatically deletes backups for files that no longer exist in your Vault. Are you sure you want to clear all backups?",
+16 -3
View File
@@ -234,6 +234,16 @@ export default {
"¿Eliminar el texto Markdown guardado para esta imagen? La imagen se eliminará de la escena en cualquier caso.",
MARKDOWN_IMAGE_KEEP_TEXT: "Conservar texto Markdown",
MARKDOWN_IMAGE_DELETE_TEXT: "Eliminar texto Markdown",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE:
"Usar esta opción para futuras eliminaciones",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE_DESC:
'Restablece “Eliminación de imágenes Markdown locales” a “Preguntar cada vez” en los ajustes del plugin de Excalidraw.',
MARKDOWN_IMAGE_DELETE_BEHAVIOR_NAME: "Eliminación de imágenes Markdown locales",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DESC:
"Elige si al eliminar una imagen Markdown local también se elimina su texto Markdown del reverso de la nota.",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_ASK: "Preguntar cada vez",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_KEEP: "Conservar el texto sin preguntar",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DELETE: "Eliminar el texto sin preguntar",
INSERT_PDF: "Insertar archivo PDF desde la bóveda",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE:
"Insertar última página PDF activa como imagen",
@@ -286,6 +296,8 @@ export default {
"Error, no se puede leer la ruta del archivo. Insertando el archivo en su lugar",
NO_SEARCH_RESULT: "No se encontró ningún elemento coincidente en el bosquejo",
FORCE_SAVE_ABORTED: "Guardado forzado abortado porque ya se está guardando",
DRAWING_RELOAD_FAILED:
"Excalidraw rechazó los datos de dibujo entrantes no válidos. Se conservó el dibujo actualmente abierto en el lienzo. Guárdalo o expórtalo antes de cerrar esta vista y revisa el archivo sincronizado o su historial de versiones.",
LINKLIST_SECOND_ORDER_LINK: "Enlace de Segundo Orden",
MARKDOWN_EMBED_CUSTOMIZE_LINK_PROMPT_TITLE:
"Personalizar el enlace del archivo incrustado",
@@ -1113,15 +1125,16 @@ export default {
EMBED_IMAGE_CACHE_NAME:
"Guardar imágenes en caché para incrustar en Markdown",
EMBED_IMAGE_CACHE_DESC:
"Guarda imágenes en caché para incrustar en Markdown. Esto acelerará el proceso de incrustación, pero si compones imágenes a partir de varios bosquejos anidados, " +
"la imagen incrustada en Markdown no se actualizará hasta que abras el bosquejo y lo guardes para activar la actualización del caché.",
"Guarda imágenes en caché para incrustarlas en Markdown. Los bosquejos almacenados en caché se actualizan cuando cambia el bosquejo o una de sus dependencias de archivos de la bóveda.",
SCENE_IMAGE_CACHE_NAME:
"Guardar bosquejos anidados de Excalidraw en caché en la escena",
SCENE_IMAGE_CACHE_DESC:
"Guarda los bosquejos anidados en caché para un renderizado más rápido. Esto acelerará el proceso de renderizado, especialmente si tienes muchos bosquejos anidados en tu escena. " +
"Excalidraw intentará identificar de manera inteligente si algún elemento de un bosquejo anidado ha cambiado y actualizará el caché. " +
"Excalidraw identificará los cambios en los bosquejos anidados y en sus fuentes de archivos de la bóveda, y actualizará la caché en consecuencia. " +
"Puede que quieras desactivar esta opción si sospechas que el caché no se está actualizando correctamente.",
EMBED_IMAGE_CACHE_CLEAR: "Vaciar caché de imágenes",
REFRESH_SCENE_IMAGES:
"Actualizar la imagen seleccionada o todas las imágenes del dibujo actual",
BACKUP_CACHE_CLEAR: "Eliminar copias de seguridad",
BACKUP_CACHE_CLEAR_CONFIRMATION:
"Esta acción eliminará todas las copias de seguridad de los bosquejos de Excalidraw. Las copias de seguridad se utilizan como medida de seguridad en caso de que tu archivo de bosquejo se dañe. Cada vez que abres Obsidian, el complemento elimina automáticamente las copias de seguridad de los archivos que ya no existen en tu Bóveda. ¿Estás seguro de que quieres borrar todas las copias de seguridad?",
+16 -3
View File
@@ -226,6 +226,16 @@ export default {
"Удалить текст Markdown, сохранённый для этого изображения? Само изображение будет удалено со сцены в любом случае.",
MARKDOWN_IMAGE_KEEP_TEXT: "Сохранить текст Markdown",
MARKDOWN_IMAGE_DELETE_TEXT: "Удалить текст Markdown",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE:
"Использовать этот выбор при следующих удалениях",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE_DESC:
'Сбросить параметр «Удаление локальных Markdown-изображений» на «Спрашивать каждый раз» в настройках плагина Excalidraw.',
MARKDOWN_IMAGE_DELETE_BEHAVIOR_NAME: "Удаление локальных Markdown-изображений",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DESC:
"Выберите, следует ли при удалении локального Markdown-изображения также удалять Markdown-текст на обратной стороне заметки.",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_ASK: "Спрашивать каждый раз",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_KEEP: "Сохранять текст без запроса",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DELETE: "Удалять текст без запроса",
INSERT_PDF: "Вставить PDF-файл из хранилища",
UNIVERSAL_ADD_FILE: "Вставка ЛЮБОГО файла",
// Compatibility keys consumed by upstream Excalidraw via ExcalidrawPlugin.getLabel().
@@ -285,6 +295,8 @@ export default {
NO_SEARCH_RESULT: "Не удалось найти подходящий элемент на чертеже",
FORCE_SAVE_ABORTED:
"Принудительное сохранение прервано, поскольку идет процесс сохранения",
DRAWING_RELOAD_FAILED:
"Excalidraw отклонил некорректные входящие данные рисунка. Открытый сейчас рисунок на холсте сохранён. Сохраните или экспортируйте его перед закрытием этого представления и проверьте синхронизированный файл или историю его версий.",
LINKLIST_SECOND_ORDER_LINK: "Ссылка второго порядка",
MARKDOWN_EMBED_CUSTOMIZE_LINK_PROMPT_TITLE:
"Настройка ссылки на встроенный файл",
@@ -1026,14 +1038,15 @@ export default {
"Выберите фон и тему экспортируемых изображений, а также следование предпросмотра теме Obsidian.",
EMBED_IMAGE_CACHE_NAME: "Кэширование изображений для вставки в markdown",
EMBED_IMAGE_CACHE_DESC:
"Кэшируйте изображения для вставки в markdown. Это ускорит процесс встраивания, но в случае, если вы составите изображения из нескольких чертежей-субкомпонентов, " +
"встроенное изображение в Markdown не будет обновляться, пока вы не откроете рисунок и не сохраните его, чтобы вызвать обновление кэша.",
"Кэшируйте изображения для вставки в Markdown. Кэшированные рисунки обновляются при изменении рисунка или одного из его вложенных файлов в хранилище.",
SCENE_IMAGE_CACHE_NAME: "Кэширование вложенных Excalidraws в Cцене",
SCENE_IMAGE_CACHE_DESC:
"Кэшируйте вложенные Excalidraws в сцене для ускорения рендеринга сцены. Это ускорит процесс рендеринга, особенно если в сцене есть глубоко вложенные Excalidraw. " +
"Excalidraw попытается интеллектуально определить, изменились ли дочерние элементы вложенного Excalidraw, и соответствующим образом обновит кэш. " +
"Excalidraw будет определять изменения во вложенных рисунках и их источниках-файлах в хранилище и соответственно обновлять кэш. " +
"Вы можете отключить эту функцию, если у вас есть подозрения, что кэш обновляется неправильно.",
EMBED_IMAGE_CACHE_CLEAR: "Очистка кэша",
REFRESH_SCENE_IMAGES:
"Обновить выбранное изображение или все изображения в текущем рисунке",
BACKUP_CACHE_CLEAR: "Очистка резервных копий",
BACKUP_CACHE_CLEAR_CONFIRMATION:
"Это действие удалит все резервные копии чертежей Excalidraw. Резервные копии используются в качестве меры безопасности на случай повреждения файла рисунка. Каждый раз, когда вы открываете Obsidian, плагин автоматически удаляет резервные копии файлов, которые больше не существуют в вашем хранилище. Вы уверены, что хотите удалить все резервные копии?",
+14 -3
View File
@@ -204,6 +204,15 @@ export default {
"是否删除为此图像保存的 Markdown 文本?无论如何,该图像都会从场景中移除。",
MARKDOWN_IMAGE_KEEP_TEXT: "保留 Markdown 文本",
MARKDOWN_IMAGE_DELETE_TEXT: "删除 Markdown 文本",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE: "将此选择用于今后的删除操作",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE_DESC:
'在 Excalidraw 插件设置中,将“本地 Markdown 图像删除”重置为“每次询问”。',
MARKDOWN_IMAGE_DELETE_BEHAVIOR_NAME: "本地 Markdown 图像删除",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DESC:
"选择删除本地 Markdown 图像时是否同时删除其笔记背面的 Markdown 文本。",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_ASK: "每次询问",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_KEEP: "保留文本,不再询问",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DELETE: "删除文本,不再询问",
INSERT_PDF: "以图像形式嵌入 PDF 到当前绘图中",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以图像形式嵌入最后激活的 PDF 页面",
UNIVERSAL_ADD_FILE: "嵌入文件 / Insert ANY file",
@@ -261,6 +270,8 @@ export default {
ERROR_CANT_READ_FILEPATH: "错误,无法读取文件路径。正在改为导入文件",
NO_SEARCH_RESULT: "在绘图中未找到匹配的元素",
FORCE_SAVE_ABORTED: "自动保存被中止,因为文件正在保存中",
DRAWING_RELOAD_FAILED:
"Excalidraw 拒绝了无效的传入绘图数据。当前画布上打开的绘图已保留。请在关闭此视图前保存或导出它,并检查同步文件或其版本历史记录。",
LINKLIST_SECOND_ORDER_LINK: "二级链接",
MARKDOWN_EMBED_CUSTOMIZE_LINK_PROMPT_TITLE: "自定义嵌入文件链接",
MARKDOWN_EMBED_CUSTOMIZE_LINK_PROMPT:
@@ -1060,14 +1071,14 @@ export default {
"选择导出图像的背景和主题,以及预览是否跟随 Obsidian 主题。",
EMBED_IMAGE_CACHE_NAME: "为嵌入到 Markdown 文档中的绘图创建预览图缓存",
EMBED_IMAGE_CACHE_DESC:
"可提高下次嵌入的速度。" +
"但如果绘图包含子绘图,(当子绘图改变时)预览图不会更新,直到您打开绘图并手动保存。",
"缓存用于嵌入 Markdown 的图像。绘图或其嵌套的仓库文件依赖发生变化时,缓存的绘图会刷新。",
SCENE_IMAGE_CACHE_NAME: "缓存场景中嵌套的绘图",
SCENE_IMAGE_CACHE_DESC:
"Excalidraw 将智能地尝试识别嵌套的绘图的子元素是否发生变化,并更新缓存。" +
"Excalidraw 会识别嵌套绘图及其嵌入仓库文件源的变化,并相应更新缓存。" +
"这将加快渲染过程,特别是在您的场景中有深度嵌套的绘图时。<br>" +
"如果您怀疑缓存未能正确更新,您可能需要关闭此功能。",
EMBED_IMAGE_CACHE_CLEAR: "清除缓存",
REFRESH_SCENE_IMAGES: "刷新当前绘图中的选定图像或所有图像",
BACKUP_CACHE_CLEAR: "清除备份",
BACKUP_CACHE_CLEAR_CONFIRMATION:
"该操作将删除所有绘图文件的备份。备份是绘图文件损坏时的一种补救手段。每次您打开 Obsidian 时,本插件会自动清理无用的备份。您确定要现在删除所有备份吗?",
+14 -3
View File
@@ -204,6 +204,15 @@ export default {
"是否刪除為此圖像儲存的 Markdown 文字?無論如何,該圖像都會從場景中移除。",
MARKDOWN_IMAGE_KEEP_TEXT: "保留 Markdown 文字",
MARKDOWN_IMAGE_DELETE_TEXT: "刪除 Markdown 文字",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE: "將此選擇用於今後的刪除操作",
MARKDOWN_IMAGE_REMEMBER_DELETE_CHOICE_DESC:
'在 Excalidraw 外掛設定中,將「本地 Markdown 影像刪除」重設為「每次詢問」。',
MARKDOWN_IMAGE_DELETE_BEHAVIOR_NAME: "本地 Markdown 影像刪除",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DESC:
"選擇刪除本地 Markdown 影像時是否同時刪除其筆記背面的 Markdown 文字。",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_ASK: "每次詢問",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_KEEP: "保留文字,不再詢問",
MARKDOWN_IMAGE_DELETE_BEHAVIOR_DELETE: "刪除文字,不再詢問",
INSERT_PDF: "以影像形式嵌入 PDF 到當前繪圖中",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以影像形式嵌入最後啟用的 PDF 頁面",
UNIVERSAL_ADD_FILE: "嵌入檔案 / Insert ANY file",
@@ -261,6 +270,8 @@ export default {
ERROR_CANT_READ_FILEPATH: "錯誤,無法讀取檔案路徑。正在改為匯入檔案",
NO_SEARCH_RESULT: "在繪圖中未找到匹配的元素",
FORCE_SAVE_ABORTED: "自動儲存被中止,因為檔案正在儲存中",
DRAWING_RELOAD_FAILED:
"Excalidraw 拒絕了無效的傳入繪圖資料。當前畫布上開啟的繪圖已保留。請在關閉此檢視前儲存或匯出它,並檢查同步檔案或其版本歷史記錄。",
LINKLIST_SECOND_ORDER_LINK: "二級連結",
MARKDOWN_EMBED_CUSTOMIZE_LINK_PROMPT_TITLE: "自定義嵌入檔案連結",
MARKDOWN_EMBED_CUSTOMIZE_LINK_PROMPT:
@@ -1060,14 +1071,14 @@ export default {
"選擇匯出影像的背景和主題,以及預覽是否跟隨 Obsidian 主題。",
EMBED_IMAGE_CACHE_NAME: "為嵌入到 Markdown 文件中的繪圖建立預覽圖快取",
EMBED_IMAGE_CACHE_DESC:
"可提高下次嵌入的速度。" +
"但如果繪圖包含子繪圖,(當子繪圖改變時)預覽圖不會更新,直到您開啟繪圖並手動儲存。",
"快取用於嵌入 Markdown 的影像。繪圖或其巢狀的倉庫檔案相依項發生變化時,快取的繪圖會重新整理。",
SCENE_IMAGE_CACHE_NAME: "快取場景中巢狀的繪圖",
SCENE_IMAGE_CACHE_DESC:
"Excalidraw 將智慧地嘗試識別巢狀的繪圖的子元素是否發生變化,並更新快取。" +
"Excalidraw 會識別巢狀繪圖及其嵌入倉庫檔案來源的變化,並相應更新快取。" +
"這將加快渲染過程,特別是在您的場景中有深度巢狀的繪圖時。<br>" +
"如果您懷疑快取未能正確更新,您可能需要關閉此功能。",
EMBED_IMAGE_CACHE_CLEAR: "清除快取",
REFRESH_SCENE_IMAGES: "重新整理目前繪圖中的選取影像或所有影像",
BACKUP_CACHE_CLEAR: "清除備份",
BACKUP_CACHE_CLEAR_CONFIRMATION:
"該操作將刪除所有繪圖檔案的備份。備份是繪圖檔案損壞時的一種補救手段。每次您開啟 Obsidian 時,本外掛會自動清理無用的備份。您確定要現在刪除所有備份嗎?",
+1 -3
View File
@@ -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) {
+65 -12
View File
@@ -17,12 +17,67 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.27.0": `
"2.28.0": `
## New
- On Obsidian 1.13 and newer, Excalidraw now uses Obsidian's searchable, multi-page settings. Settings are organized into clearer sections with breadcrumbs, compact help links, and clickable links between related options.
- Prefer the previous experience? Turn off **Use searchable settings** at the top of Excalidraw settings and restart Obsidian. Older Obsidian versions continue using the legacy single-page layout automatically.
- Settings exposed by installed Excalidraw Automate scripts have moved to **Excalidraw Automate → Settings for installed scripts** and update when a script adds or changes its settings.
- Excalidraw Automate can optionally load and monitor JavaScript (\`.js\`) files in the Scripts folder, use an explicit \`.js\` startup script, and store Script Library downloads as either Markdown or JavaScript. Existing scripts can be moved between the two formats while updating startup and pinned-script paths. [#2901](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2901)
- Copied Markdown image SVGs now replace embedded base64 images and fonts with short placeholders, making them smaller and easier to share with AI agents when developing custom CSS.
## New from Excalidraw.com
- Create sticky notes with the new **Sticky note** tool or the **N** shortcut. Labels automatically fit and grow with their note, with dedicated colors and a creation-date footer. [#12064](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12064)
## New in Excalidraw Automate
- Scripts can create native sticky notes, including automatically fitted labels:
\`\`\`ts
addStickyNote(topX: number, topY: number, text: string, formatting?: {width?: number; height?: number; fontSize?: number; fontFamily?: number; textAlign?: "left" | "center" | "right"; textVerticalAlign?: "top" | "middle" | "bottom";}, id?: string): string;
\`\`\`
## Fixed / Refactored
- Rich descriptions in searchable settings now remain visible when you revisit a settings page from search results. [#2935](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2935)
- Drawing persistence is now more reliable during rapid edits across multiple tabs, popout moves, and immediate closing. Backups and automatic exports now track the exact successfully saved revision. [#2933](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2933)
- Rapidly changing Markdown image appearance, selection, or image/embeddable conversion no longer leaves a rejected image-render promise in the console or lets a superseded render overwrite the newer element state.
`,
"2.27.3": `
## Fixed and updated
- Fixed slow vault startup when the Excalidraw Sidepanel was left open when closing Obsidian.
- Markdown Images
- Local Markdown images copied between drawings now always retain their back-of-note text, render correctly after reopening, and no longer trigger repeated deletion confirmations.
- You can now set the default behavior for back-of-the-note text when deleting a local Markdown image. You can change or reset this choice in plugin settings.
- Converting local Markdown images to embeddables and back:
- Works more reliably during rapid edits. The Markdown image sidepanel also correctly follows the converted element.
- Image appearance settings are now preserved when converting an image to an embeddable and back.
- Unchanged Markdown images now retain their already-rendered image during scene reloads, avoiding flicker and unnecessary rendering.
- External Markdown image sources are now checked when a drawing regains focus and when validating cached nested drawings.
- New command panel action: *"Refresh selected image or all images in the current drawing"*. This invalidates the image cache and regenerates the selected image or all images in the current drawing.
- Bucket fill color palette now matches the custom palette for the element background, if available.
- Excalidraw stroke and element background color top-picks drag and drop did not work in Obsidian popout windows.
## New
- Slideshow script now includes an improved slide sorter, support for setting slide titles, and other UX improvements.
- The Deconstruct selected elements script now checks for invalid characters in file names and allows deconstructed items to be saved directly in the vault root folder.
## New in Excalidraw Automate
- Excalidraw Automate scripts can now opt into strict LaTeX validation with \`{ throwOnError: true }\` in \`addLaTex()\` and \`tex2dataURL()\`. This allows scripts to catch and display MathJax errors. Requires Excalidraw Extras 0.1.0. [#2](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_EXTRAS_ISSUES}/2)
`,
"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 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
@@ -31,25 +86,23 @@ 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
- 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.
- Opening the command palette or another Obsidian modal reliably saves dirty drawings, while inline link suggestions no longer trigger a save that can end text editing.
- Converting a legacy ".excalidraw" drawing now persists its embedded images as vault attachments during conversion, before the source file can be removed. [#2898](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2898)
- Entering text editing no longer scans and sorts the entire vault for link suggestions; file-link candidates are loaded only after typing \`[[\`. [#2907](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2907)
- Settings changes are saved promptly without collapsing sections or interrupting fast typing. Writes are serialized, and Excalidraw keeps a device-local recovery copy so an empty or corrupted synchronized **data.json** cannot silently erase a large settings configuration.
- Interdependent settings now initialize and refresh consistently, including TODO icons, auto-export formats, Taskbone credentials, filename previews, and custom grid colors. Built-in font previews also use the correct typeface in secondary Obsidian windows.
- Applying a rendering-related setting no longer resets the live zoom and scroll position of an open drawing. New configurations use ☑ as the completed-TODO marker.
- Interactive Markdown embed defaults now save filename, properties, locked-reading-mode, and background-source changes reliably.
- The color palette uses the available height, keeps its native picker aligned, remembers customized top picks after reload, and updates popover theming immediately after a canvas background change.
- Text-to-diagram chat history is visible again, so saved chats can be restored or deleted.
- Stencil-library JSON is now tab-indented for cleaner Git diffs. [#2883](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2883)
## Maintenance
- This is one of the Plugin's largest internal maintenance releases. The settings system, persistence pipeline, plugin lifecycle, runtime packaging, and several major managers were reorganized into clearer, independently maintained components. The visible workflow remains familiar, but the foundation is substantially safer for future features and fixes.
- The embedded Excalidraw runtime now uses a modern ESM-source build and React 19 instead of the retired UMD pipeline. Offline use and popout windows remain supported; the Assistant UI font is bundled locally and Mermaid still loads on demand through Excalidraw Extras.
- 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
+23
View File
@@ -8,6 +8,7 @@ import {
normalizePath,
TFile,
Notice,
Setting,
TextAreaComponent,
} from "obsidian";
import ExcalidrawView from "../../view/ExcalidrawView";
@@ -1295,8 +1296,17 @@ export class NewFileActions extends Modal {
}
}
/** Optional toggle shown with a multi-option confirmation prompt. */
export interface ConfirmationPromptToggle {
name: string;
description?: string;
defaultValue?: boolean;
}
export class MultiOptionConfirmationPrompt<T = boolean | null> extends Modal {
public waitForClose: Promise<T>;
/** Current value of the optional toggle. */
public toggleValue: boolean;
private resolvePromise: (value: T) => void;
private rejectPromise: (reason?: string) => void;
private selectedValue: T = null;
@@ -1310,8 +1320,10 @@ export class MultiOptionConfirmationPrompt<T = boolean | null> extends Modal {
message: string,
buttons?: Map<string, T>,
ctaButtonLabel?: string,
private readonly toggle?: ConfirmationPromptToggle,
) {
super(plugin.app);
this.toggleValue = toggle?.defaultValue ?? false;
this.message = message;
if (!buttons || buttons.size === 0) {
buttons = new Map<string, boolean | null>([
@@ -1341,6 +1353,17 @@ export class MultiOptionConfirmationPrompt<T = boolean | null> extends Modal {
messageEl.addClass("excalidraw-multiOptionConfirmationPrompt-message");
setSanitizedHtml(messageEl, this.message);
if (this.toggle) {
new Setting(this.contentEl)
.setName(this.toggle.name)
.setDesc(this.toggle.description ?? "")
.addToggle((component) =>
component.setValue(this.toggleValue).onChange((value) => {
this.toggleValue = value;
}),
);
}
const buttonContainer = this.contentEl.createDiv();
buttonContainer.addClass(
"excalidraw-multiOptionConfirmationPrompt-buttonContainer",
+34 -7
View File
@@ -287,7 +287,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "createViewSVG",
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean, elementsOverride?: readonly ExcalidrawElement[]}): 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" +
@@ -300,6 +300,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"@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" +
@@ -317,6 +318,20 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
" 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" +
"});",
},
{
@@ -374,6 +389,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: null,
after: "",
},
{
field: "addStickyNote",
code: 'addStickyNote(topX: number, topY: number, text: string, formatting?: {width?: number; height?: number; fontSize?: number; fontFamily?: number; textAlign?: "left" | "center" | "right"; textVerticalAlign?: "top" | "middle" | "bottom";}, id?: string): string;',
desc: "Adds a sticky note using the current EA colors and styles. The optional label is fitted automatically, and the function returns the note container ID.",
after: "",
},
{
field: "addDiamond",
code: "addDiamond(topX: number, topY: number, width: number, height: number, id?:string): string;",
@@ -466,14 +487,14 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "addLaTex",
code: "async addLaTex(topX: number, topY: number, tex: string): Promise<string>;",
desc: "This is an async function, you need to avait the results. Adds a LaTex element to the drawing. The tex string is the LaTex code. The function returns the id of the created element.",
code: "async addLaTex(topX: number, topY: number, tex: string, scaleX: number = 1, scaleY: number = 1, options?: {throwOnError?: boolean}): Promise<string>;",
desc: "This is an async function; await the result. Adds a LaTeX element to the drawing and returns its ID. Set options.throwOnError to true to catch invalid LaTeX errors in your script.",
after: "",
},
{
field: "tex2dataURL",
code: "async tex2dataURL(tex: string, scale: number = 4): Promise<{mimeType: MimeType;fileId: FileId;dataURL: DataURL;created: number;size: { height: number; width: number };}> ",
desc: "returns the base64 dataURL of the LaTeX equation rendered as an SVG. tex is the LaTeX equation string",
code: "async tex2dataURL(tex: string, scale: number = 4, options?: {throwOnError?: boolean}): Promise<{mimeType: MimeType;fileId: FileId;dataURL: DataURL;created: number;size: { height: number; width: number };}> ",
desc: "Returns the base64 dataURL of the LaTeX equation rendered as an SVG. Set options.throwOnError to true to catch invalid LaTeX errors in your script.",
after: "",
},
{
@@ -690,8 +711,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: "",
},
{
+259 -53
View File
@@ -83,7 +83,11 @@ import {
type MarkdownImageCustomData,
type MarkdownImageRenderSettings,
} from "src/types/markdownImageTypes";
import { resolveMarkdownImageRenderSettings } from "src/utils/markdownImageUtils";
import {
createMarkdownImageRenderCacheEntry,
resolveMarkdownImageRenderSettings,
type MarkdownImageRenderCacheEntry,
} from "src/utils/markdownImageUtils";
import { addAppendUpdateCustomData } from "src/utils/elementCustomDataUtils";
//declared in rollup.config.mjs
@@ -93,6 +97,39 @@ declare const deliberateFetch: (
) => Promise<Response>;
declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;
declare const mainDocument: Document;
/** Minimal drawing-owned data required to resolve export/scene assets. */
export interface EmbeddedFilesDataSource {
file: ExcalidrawData["file"];
scene: ExcalidrawData["scene"];
getFileEntries: ExcalidrawData["getFileEntries"];
getFile: ExcalidrawData["getFile"];
getMarkdownImage: ExcalidrawData["getMarkdownImage"];
getEquationEntries: ExcalidrawData["getEquationEntries"];
getEquation: ExcalidrawData["getEquation"];
}
/** View-independent state needed to recreate one embedded-file descriptor. */
export interface EmbeddedFileExportState {
readonly filePath: string | null;
readonly isSVGwithBitmap: boolean;
readonly img: string;
readonly imgInverted: string;
readonly mtime: number;
readonly mimeType: MimeType;
readonly size: Size;
readonly linkParts: LinkParts | null;
readonly filenameparts: FILENAMEPARTS | null;
readonly hostPath: string;
readonly attemptCounter: number;
readonly isHyperLink: boolean;
readonly isLocalLink: boolean;
readonly isMarkdownSection: boolean;
readonly hyperlink: DataURL | null;
readonly colorMap: ColorMap | null;
readonly pdfPageViewProps: PDFPageViewProps | null;
readonly renderScale: number;
}
//An ugly workaround for the following situation.
//File A is a markdown file that has an embedded Excalidraw file B
//Later file A is embedded into file B as a Markdown embed
@@ -126,11 +163,13 @@ export type DeferredCacheValidation =
type LoadImageOptions = {
cacheValidation?: CacheValidationMode;
bypassCache?: boolean;
onStaleCacheHit?: (validation: DeferredCacheValidation) => void;
deferUncachedExcalidraw?: boolean;
onExcalidrawGenerationDeferred?: () => void;
markdownTransclusionRender?: MarkdownImageRenderSettings;
fileId?: FileId;
pdfScale?: number;
};
type MarkdownRenderOverrides = {
@@ -335,7 +374,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;
@@ -368,6 +407,14 @@ export type MarkdownSVGRenderResult = {
size: Size;
};
const emptyMarkdownSVGRenderResult = (
width: number,
): MarkdownSVGRenderResult => ({
dataURL: "" as DataURL,
hasSVGwithBitmap: false,
size: { width, height: 0 },
});
const getPDFCacheId = (linkParts: LinkParts, pageNum: number): string => {
// Different crops of the same PDF page must not overwrite each other in cache,
// so the cache key uses the full PDF page/reference fragment when present.
@@ -474,6 +521,66 @@ export class EmbeddedFile {
public pdfPageViewProps: PDFPageViewProps;
public renderScale: number = 0;
/** Captures loader inputs and reusable data URLs without retaining a view. */
public exportPreparedSaveState(): EmbeddedFileExportState {
return {
filePath: this.file?.path ?? null,
isSVGwithBitmap: this.isSVGwithBitmap,
img: this.img,
imgInverted: this.imgInverted,
mtime: this.mtime,
mimeType: this.mimeType,
size: { ...this.size },
linkParts: this.linkParts ? { ...this.linkParts } : null,
filenameparts: this.filenameparts ? { ...this.filenameparts } : null,
hostPath: this.hostPath,
attemptCounter: this.attemptCounter,
isHyperLink: this.isHyperLink,
isLocalLink: this.isLocalLink,
isMarkdownSection: this.isMarkdownSection,
hyperlink: this.hyperlink ?? null,
colorMap: this.colorMap ? { ...this.colorMap } : null,
pdfPageViewProps: this.pdfPageViewProps
? { ...this.pdfPageViewProps }
: null,
renderScale: this.renderScale,
};
}
/** Recreates a mutable loader descriptor from detached prepared-save data. */
public static fromPreparedSaveState(
plugin: ExcalidrawPlugin,
state: EmbeddedFileExportState,
): EmbeddedFile {
const descriptor = Object.create(EmbeddedFile.prototype) as EmbeddedFile;
descriptor.plugin = plugin;
descriptor.file = state.filePath
? plugin.app.vault.getFileByPath(state.filePath)
: null;
descriptor.isSVGwithBitmap = state.isSVGwithBitmap;
descriptor.img = state.img;
descriptor.imgInverted = state.imgInverted;
descriptor.mtime = state.mtime;
descriptor.mimeType = state.mimeType;
descriptor.size = { ...state.size };
descriptor.linkParts = state.linkParts ? { ...state.linkParts } : null;
descriptor.filenameparts = state.filenameparts
? { ...state.filenameparts }
: null;
descriptor.hostPath = state.hostPath;
descriptor.attemptCounter = state.attemptCounter;
descriptor.isHyperLink = state.isHyperLink;
descriptor.isLocalLink = state.isLocalLink;
descriptor.isMarkdownSection = state.isMarkdownSection;
descriptor.hyperlink = state.hyperlink;
descriptor.colorMap = state.colorMap ? { ...state.colorMap } : null;
descriptor.pdfPageViewProps = state.pdfPageViewProps
? { ...state.pdfPageViewProps }
: null;
descriptor.renderScale = state.renderScale;
return descriptor;
}
constructor(
plugin: ExcalidrawPlugin,
hostPath: string,
@@ -624,7 +731,10 @@ export class EmbeddedFile {
}
}
public isLoaded(isDark: boolean): boolean {
public isLoaded(
isDark: boolean,
minimumPdfRenderScale: number = this.plugin.settings.pdfScale,
): boolean {
if (!this.isHyperLink && !this.isLocalLink) {
if (!this.file) {
this.file = this.plugin.app.metadataCache.getFirstLinkpathDest(
@@ -648,7 +758,7 @@ export class EmbeddedFile {
? this.imgInverted !== ""
: this.img !== "";
return (
hasImageForTheme && this.renderScale >= this.plugin.settings.pdfScale
hasImageForTheme && this.renderScale >= minimumPdfRenderScale
);
}
}
@@ -744,12 +854,7 @@ export class EmbeddedFilesLoader {
linkParts,
{ markdown, render, fullHeight: true },
);
return {
...result,
size: result.dataURL
? await getImageSize(result.dataURL)
: { width: render.width, height: 0 },
};
return result;
} finally {
this.emptyPDFDocsMap();
}
@@ -782,6 +887,7 @@ export class EmbeddedFilesLoader {
hasSVGwithBitmap,
elements = [],
cacheValidation = "validated",
bypassCache = false,
onStaleCacheHit,
deferUncachedGeneration = false,
}: {
@@ -792,6 +898,7 @@ export class EmbeddedFilesLoader {
hasSVGwithBitmap: boolean;
elements?: ExcalidrawElement[];
cacheValidation?: CacheValidationMode;
bypassCache?: boolean;
onStaleCacheHit?: (validation: DeferredCacheValidation) => void;
deferUncachedGeneration?: boolean;
}): Promise<{
@@ -822,6 +929,7 @@ export class EmbeddedFilesLoader {
inFile instanceof EmbeddedFile ? inFile.colorMap : null,
);
const shouldUseCache =
!bypassCache &&
!hasColorMap &&
this.plugin.settings.allowImageCacheInScene &&
file &&
@@ -1115,6 +1223,7 @@ export class EmbeddedFilesLoader {
inFile,
hasSVGwithBitmap,
cacheValidation: options?.cacheValidation,
bypassCache: options?.bypassCache,
onStaleCacheHit: options?.onStaleCacheHit,
deferUncachedGeneration: options?.deferUncachedExcalidraw,
});
@@ -1171,6 +1280,7 @@ export class EmbeddedFilesLoader {
: file?.extension === "md"
? null
: await getDataURL(ab, mimeType)));
let renderedMarkdownSize: Size | null = null;
if (this.terminate) {
return null;
}
@@ -1197,9 +1307,11 @@ export class EmbeddedFilesLoader {
isTransclusion: true,
}
: undefined,
options?.pdfScale,
);
dataURL = result.dataURL;
hasSVGwithBitmap = result.hasSVGwithBitmap;
renderedMarkdownSize = result.size;
} finally {
markdownRendererRecursionWatcthdog.delete(file);
}
@@ -1207,7 +1319,9 @@ export class EmbeddedFilesLoader {
const size = isPDF
? pdfSize
: (excalidrawSize ?? (await getImageSize(dataURL)));
: (excalidrawSize ??
renderedMarkdownSize ??
(await getImageSize(dataURL)));
if (this.terminate) {
return null;
@@ -1270,8 +1384,12 @@ export class EmbeddedFilesLoader {
sceneElements,
waitForRender,
prioritizedFileIds,
markdownImageRenderCache,
loadedMarkdownImageFileIds,
markdownImageRenderDefaults,
pdfScale,
}: {
excalidrawData: ExcalidrawData;
excalidrawData: EmbeddedFilesDataSource;
addFiles: (files: FileData[], isDark: boolean, final?: boolean) => void;
depth: number;
isThemeChange?: boolean;
@@ -1287,6 +1405,10 @@ export class EmbeddedFilesLoader {
sceneElements?: readonly ExcalidrawElement[];
waitForRender?: () => Promise<void>;
prioritizedFileIds?: ReadonlySet<FileId>;
markdownImageRenderCache?: Map<FileId, MarkdownImageRenderCacheEntry>;
loadedMarkdownImageFileIds?: ReadonlySet<FileId>;
markdownImageRenderDefaults?: MarkdownImageRenderSettings;
pdfScale?: number;
}) {
this.terminalState = "running";
if (this.isDark === undefined) {
@@ -1325,6 +1447,28 @@ export class EmbeddedFilesLoader {
const markdownImageFileIds = new Set(
markdownImageElements.map((element) => element.fileId),
);
// Ordinary copies of a local Markdown image intentionally share one
// fileId. Render and publish that shared binary once while retaining all
// elements for per-element metadata normalization below.
const markdownImageElementsByFileId = new Map<
FileId,
ExcalidrawImageElement[]
>();
for (const element of markdownImageElements) {
const elements = markdownImageElementsByFileId.get(element.fileId);
if (elements) {
elements.push(element);
} else {
markdownImageElementsByFileId.set(element.fileId, [element]);
}
}
if (markdownImageRenderCache) {
for (const fileId of markdownImageRenderCache.keys()) {
if (!markdownImageFileIds.has(fileId)) {
markdownImageRenderCache.delete(fileId);
}
}
}
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,isDark:this.isDark,sceneTheme:excalidrawData.scene.appState.theme});
let onLoadTaskSettled: (() => void) | null = null;
const createSafeLoadTask = (
@@ -1355,6 +1499,46 @@ export class EmbeddedFilesLoader {
DeferredCacheValidation
>();
const deferredGenerationEntries: typeof entries = [];
const renderedMarkdownImageCacheEntries = new Map<
FileId,
MarkdownImageRenderCacheEntry
>();
const normalizeMarkdownImageElement = (
element: ExcalidrawImageElement,
) => {
const customData = element.customData?.[
MARKDOWN_IMAGE_CUSTOM_DATA_KEY
] as MarkdownImageCustomData | undefined;
if (!customData) {
return null;
}
const render = resolveMarkdownImageRenderSettings(
markdownImageRenderDefaults ??
this.plugin.settings.markdownImageSettings.defaults,
customData.render,
);
const legacyRender = customData.render as MarkdownImageRenderSettings & {
theme?: unknown;
};
if ("theme" in legacyRender) {
const migratedRender = { ...legacyRender };
delete migratedRender.theme;
addAppendUpdateCustomData(element, {
[MARKDOWN_IMAGE_CUSTOM_DATA_KEY]: {
...customData,
render: migratedRender as MarkdownImageRenderSettings,
},
});
}
if (
typeof element.customData?.doNotInvertSVGInDarkMode !== "boolean"
) {
addAppendUpdateCustomData(element, {
doNotInvertSVGInDarkMode: false,
});
}
return { customData, render };
};
function* loadIterator(
loader: EmbeddedFilesLoader,
@@ -1392,17 +1576,22 @@ export class EmbeddedFilesLoader {
file,
deferredValidation.cacheMtime,
loader.plugin,
"deferred-scene-validation",
),
);
if (cacheIsValid) {
return;
}
}
if (shouldForceReload || !embeddedFile.isLoaded(loader.isDark)) {
if (
shouldForceReload ||
!embeddedFile.isLoaded(loader.isDark, pdfScale)
) {
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,status:"embedded Files are not loaded"});
let excalidrawGenerationDeferred = false;
const data = await loader._getObsidianImage(embeddedFile, depth, {
cacheValidation,
bypassCache: shouldForceReload,
fileId: id,
deferUncachedExcalidraw,
onExcalidrawGenerationDeferred: () => {
@@ -1413,6 +1602,7 @@ export class EmbeddedFilesLoader {
? (validation) =>
deferredValidationCandidates.set(id, validation)
: undefined,
pdfScale,
});
if (loader.terminate) {
return null;
@@ -1470,46 +1660,25 @@ export class EmbeddedFilesLoader {
return;
}
for (const element of markdownImageElements) {
const id = element.fileId;
for (const [id, elements] of markdownImageElementsByFileId) {
if (fileIDWhiteList && !fileIDWhiteList.has(id)) {
continue;
}
const element = elements[0];
yield createSafeLoadTask(
async () => {
if (loader.terminate) {
return;
}
const customData = element.customData?.[
MARKDOWN_IMAGE_CUSTOM_DATA_KEY
] as MarkdownImageCustomData | undefined;
if (!customData) {
const normalized = normalizeMarkdownImageElement(element);
if (!normalized) {
return;
}
const render = resolveMarkdownImageRenderSettings(
loader.plugin.settings.markdownImageSettings.defaults,
customData.render,
);
const legacyRender = customData.render as MarkdownImageRenderSettings & {
theme?: unknown;
};
if ("theme" in legacyRender) {
const migratedRender = { ...legacyRender };
delete migratedRender.theme;
addAppendUpdateCustomData(element, {
[MARKDOWN_IMAGE_CUSTOM_DATA_KEY]: {
...customData,
render: migratedRender as MarkdownImageRenderSettings,
},
});
}
if (
typeof element.customData?.doNotInvertSVGInDarkMode !== "boolean"
) {
addAppendUpdateCustomData(
element,
{ doNotInvertSVGInDarkMode: false },
);
const { customData, render } = normalized;
// Copies sharing this fileId need the same legacy metadata
// normalization even though only one SVG is generated.
for (const copy of elements.slice(1)) {
normalizeMarkdownImageElement(copy);
}
let sourceFile = excalidrawData.file;
let markdown: string | undefined;
@@ -1535,6 +1704,27 @@ export class EmbeddedFilesLoader {
if (markdown === undefined) {
return;
}
const currentCustomData = element.customData?.[
MARKDOWN_IMAGE_CUSTOM_DATA_KEY
] as MarkdownImageCustomData | undefined;
if (!currentCustomData) {
return;
}
const cacheEntry = createMarkdownImageRenderCacheEntry(
markdown,
sourceFile.path,
currentCustomData,
render,
);
const cached = markdownImageRenderCache?.get(id);
if (
!forceReloadFileIDs?.has(id) &&
loadedMarkdownImageFileIds?.has(id) &&
cached?.markdown === cacheEntry.markdown &&
cached.configuration === cacheEntry.configuration
) {
return;
}
const rendered = await loader.renderMarkdownToSVG(
sourceFile,
markdown,
@@ -1552,6 +1742,7 @@ export class EmbeddedFilesLoader {
hasSVGwithBitmap: rendered.hasSVGwithBitmap,
shouldScale: true,
});
renderedMarkdownImageCacheEntries.set(id, cacheEntry);
},
{
phase: "markdown-image",
@@ -1726,6 +1917,14 @@ export class EmbeddedFilesLoader {
}
try {
addFiles(batchFiles, this.isDark, final);
if (batchFiles && markdownImageRenderCache) {
for (const file of batchFiles) {
const cacheEntry = renderedMarkdownImageCacheEntries.get(file.id);
if (cacheEntry) {
markdownImageRenderCache.set(file.id, cacheEntry);
}
}
}
} catch (e: unknown) {
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
}
@@ -1910,8 +2109,10 @@ export class EmbeddedFilesLoader {
let width = 0;
let height = 0;
const pageNum = isNaN(linkParts.page) ? 1 : (linkParts.page ?? 1);
const requestedScale = this.plugin.settings.pdfScale;
const requestedScale =
options?.pdfScale ?? this.plugin.settings.pdfScale;
const shouldUseCache =
!options?.bypassCache &&
getImageCache().isReady() &&
(!options || this.plugin.settings.allowImageCacheInScene);
const cacheKey: ImageKey = {
@@ -2172,9 +2373,10 @@ export class EmbeddedFilesLoader {
file: TFile,
linkParts: LinkParts,
overrides?: MarkdownRenderOverrides,
): Promise<{ dataURL: DataURL; hasSVGwithBitmap: boolean }> {
pdfScale?: number,
): Promise<MarkdownSVGRenderResult> {
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
return emptyMarkdownSVGRenderResult(linkParts.width);
}
//1.
//get the markdown text
@@ -2183,7 +2385,7 @@ export class EmbeddedFilesLoader {
? null
: await getTransclusion(linkParts, plugin.app, file);
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
return emptyMarkdownSVGRenderResult(linkParts.width);
}
let text = overrides
? overrides.markdown
@@ -2403,7 +2605,7 @@ export class EmbeddedFilesLoader {
}
appendMarkdownBottomSpacer(mdDIV, markdownImagePaddingBottom);
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
return emptyMarkdownSVGRenderResult(linkParts.width);
}
// MathJax typesetting may complete asynchronously after MarkdownRenderer.render() resolves.
@@ -2441,14 +2643,14 @@ export class EmbeddedFilesLoader {
await replaceBlobWithBase64(mdDIV); //because image cache returns a blob
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
return emptyMarkdownSVGRenderResult(linkParts.width);
}
const internalEmbeds = Array.from(
mdDIV.querySelectorAll<HTMLElement>("span.internal-embed[src]"),
);
for (let i = 0; i < internalEmbeds.length; i++) {
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
return emptyMarkdownSVGRenderResult(linkParts.width);
}
const el = internalEmbeds[i];
const src = el.getAttribute("src");
@@ -2486,11 +2688,14 @@ export class EmbeddedFilesLoader {
markdownTransclusionRender: getTransclusionRenderSettings(
overrides.render,
),
pdfScale,
}
: undefined,
: pdfScale === undefined
? undefined
: { pdfScale },
);
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
return emptyMarkdownSVGRenderResult(linkParts.width);
}
if (!embeddedFile?.dataURL) {
continue;
@@ -2541,7 +2746,7 @@ export class EmbeddedFilesLoader {
}
await replaceBlobWithBase64(mdDIV);
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
return emptyMarkdownSVGRenderResult(linkParts.width);
}
//5.1
@@ -2729,6 +2934,7 @@ export class EmbeddedFilesLoader {
return {
dataURL: svgToBase64(finalSVG) as DataURL,
hasSVGwithBitmap,
size: { width: linkParts.width, height: svgHeight },
};
}
}
+260 -88
View File
@@ -49,6 +49,7 @@ import {
mermaidToExcalidraw,
refreshTextDimensions,
getFontFamilyString,
convertToExcalidrawElements,
} from "src/constants/constants";
import {
blobToBase64,
@@ -62,6 +63,7 @@ import {
import {
//debug,
getImageSize,
getPNG,
isMaskFile,
wrapTextAtCharLength,
arrayToMap,
@@ -88,6 +90,7 @@ import {
} from "@zsviczian/excalidraw/types/excalidraw/types";
import { EmbeddedFile, EmbeddedFilesLoader } from "./EmbeddedFileLoader";
import { tex2dataURL } from "./LaTeX";
import type { MathJaxRenderOptions } from "src/types/mathJaxTypes";
import {
LatexSuitePlugin,
MultiOptionConfirmationPrompt,
@@ -154,10 +157,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 +213,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 +230,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;
@@ -1707,79 +1724,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 {readonly ExcalidrawElement[]} [options.elementsOverride] - Optional complete replacement for the view's exported elements. This array is not merged with the current scene or treated as a patch by ID: when supplied, only its non-deleted elements are exported. Include every element that should appear in the SVG.
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
*/
async createViewSVG({
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?: readonly 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,
});
}
/**
@@ -2023,6 +2123,7 @@ export class ExcalidrawAutomate {
locked: false,
frameId: null as string | null,
hasTextLink: !!(eltype === "text" && link),
created: Date.now(),
...(scale ? { scale } : {}),
} as unknown as Mutable<ExcalidrawElement>;
}
@@ -2233,6 +2334,70 @@ export class ExcalidrawAutomate {
return id;
}
/**
* Adds a sticky note and its optional fitted label to the ExcalidrawAutomate
* instance. Width and height default to Excalidraw's sticky-note size.
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
* @param {string} text - The sticky-note text. An empty string creates an unlabeled note.
* @param {Object} [formatting] - Sticky-note size and label formatting.
* @param {number} [formatting.width] - The initial width of the note.
* @param {number} [formatting.height] - The initial height of the note.
* @param {number} [formatting.fontSize] - The label's maximum font size.
* @param {number} [formatting.fontFamily] - The label font family.
* @param {"left" | "center" | "right"} [formatting.textAlign] - The label's horizontal alignment.
* @param {"top" | "middle" | "bottom"} [formatting.textVerticalAlign] - The label's vertical alignment.
* @param {string} [id] - The ID of the sticky-note element.
* @returns {string} The ID of the added sticky note.
*/
addStickyNote(
topX: number,
topY: number,
text: string,
formatting?: {
width?: number;
height?: number;
fontSize?: number;
fontFamily?: number;
textAlign?: "left" | "center" | "right";
textVerticalAlign?: "top" | "middle" | "bottom";
},
id?: string,
): string {
id = id ?? nanoid();
const elements = convertToExcalidrawElements(
[
{
...this.boxedElement(
id,
"stickynote",
topX,
topY,
formatting?.width ?? 0,
formatting?.height ?? 0,
),
type: "stickynote" as const,
label: text
? {
text,
fontSize: formatting?.fontSize ?? this.style.fontSize,
fontFamily: formatting?.fontFamily ?? this.style.fontFamily,
textAlign:
formatting?.textAlign ?? this.style.textAlign,
verticalAlign:
formatting?.textVerticalAlign ?? this.style.verticalAlign,
}
: undefined,
},
],
{ regenerateIds: false },
);
for (const element of elements) {
this.elementsDict[element.id] = element;
}
return id;
}
/**
* Adds a diamond element to the ExcalidrawAutomate instance.
* @param {number} topX - The x-coordinate of the top-left corner.
@@ -2889,6 +3054,7 @@ export class ExcalidrawAutomate {
* @param {string} tex - The LaTeX equation string.
* @param {number} [scaleX=1] - The x-scaling factor (post mathjax creation)
* @param {number} [scaleY=1] - The y-scaling factor (post mathjax creation)
* @param {MathJaxRenderOptions} [options] - MathJax rendering options. Set `throwOnError` to propagate invalid LaTeX errors.
* @returns {Promise<string>} Promise resolving to the ID of the added LaTeX image element.
*/
async addLaTex(
@@ -2897,12 +3063,13 @@ export class ExcalidrawAutomate {
tex: string,
scaleX: number = 1,
scaleY: number = 1,
options?: MathJaxRenderOptions,
): Promise<string> {
if (!tex || !scaleX || !scaleY) {
return null;
}
const id = nanoid();
const image = await tex2dataURL(tex, 4, this.plugin);
const image = await tex2dataURL(tex, 4, this.plugin, options);
if (!image) {
return null;
}
@@ -2936,11 +3103,13 @@ export class ExcalidrawAutomate {
* Returns the base64 dataURL of the LaTeX equation rendered as an SVG.
* @param {string} tex - The LaTeX equation string.
* @param {number} [scale=4] - The scale factor for the image.
* @param {MathJaxRenderOptions} [options] - MathJax rendering options. Set `throwOnError` to propagate invalid LaTeX errors.
* @returns {Promise<{mimeType: MimeType; fileId: FileId; dataURL: DataURL; created: number; size: { height: number; width: number };}>} Promise resolving to the LaTeX image data.
*/
async tex2dataURL(
tex: string,
scale: number = 4, // Default scale value, adjust as needed
options?: MathJaxRenderOptions,
): Promise<{
mimeType: MimeType;
fileId: FileId;
@@ -2948,7 +3117,7 @@ export class ExcalidrawAutomate {
created: number;
size: { height: number; width: number };
}> {
return await tex2dataURL(tex, scale, this.plugin);
return await tex2dataURL(tex, scale, this.plugin, options);
}
/**
@@ -4339,36 +4508,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);
}
/**
+190 -68
View File
@@ -49,7 +49,10 @@ import {
DataURL,
SceneData,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import { EmbeddedFile } from "./EmbeddedFileLoader";
import {
EmbeddedFile,
type EmbeddedFileExportState,
} from "./EmbeddedFileLoader";
import { EmbeddedDataRegistries } from "./EmbeddedDataRegistries";
import { MimeType } from "src/types/embeddedFileLoaderTypes";
import { MultiOptionConfirmationPrompt } from "./Dialogs/Prompt";
@@ -72,6 +75,7 @@ import {
MARKDOWN_IMAGE_EMBEDDED_FILE_TOKEN,
type MarkdownImageCustomData,
type MarkdownImageData,
type MarkdownImageRenderSettings,
} from "src/types/markdownImageTypes";
import {
changeThemeOfExcalidrawMD,
@@ -138,6 +142,7 @@ export type ExcalidrawDataScene = Omit<
};
type RegExpMatchIteratorResult = IteratorResult<RegExpMatchArray, undefined>;
type LoadGenerationGuard = () => boolean;
type SceneElementIndexes = {
linkedNonTextElementsById: Map<string, ExcalidrawElement>;
@@ -257,6 +262,16 @@ type TextElementData = {
hasTextLink: boolean;
};
/** Drawing-owned registries required to regenerate save-time export assets. */
export interface ExcalidrawDataExportState {
sourceFilePath: string;
files: ReadonlyMap<FileId, EmbeddedFileExportState>;
markdownImages: ReadonlyMap<FileId, MarkdownImageData>;
equations: ReadonlyMap<FileId, EquationItem>;
markdownImageRenderDefaults: MarkdownImageRenderSettings;
pdfScale: number;
}
/** Drawing-owned metadata transferred without retaining an old view. */
export interface ExcalidrawDataMigrationState {
sourceFilePath: string;
@@ -343,6 +358,51 @@ export class ExcalidrawData {
this.selectedElementIds = null;
}
/** Captures only the data registries needed by a prepared save export. */
public exportPreparedSaveData(): ExcalidrawDataExportState | null {
if (
!this.loaded ||
!this.file ||
!this.files ||
!this.markdownImages ||
!this.equations
) {
return null;
}
return {
sourceFilePath: this.file.path,
files: new Map(
Array.from(this.files, ([id, value]) => [
id,
value.exportPreparedSaveState(),
]),
),
markdownImages: new Map(
Array.from(this.markdownImages, ([id, value]) => [
id,
{ ...value },
]),
),
equations: new Map(
Array.from(this.equations, ([id, value]) => [id, { ...value }]),
),
markdownImageRenderDefaults: {
...this.plugin.settings.markdownImageSettings.defaults,
border: {
...this.plugin.settings.markdownImageSettings.defaults.border,
},
transclusion: {
...this.plugin.settings.markdownImageSettings.defaults.transclusion,
border: {
...this.plugin.settings.markdownImageSettings.defaults.transclusion
.border,
},
},
},
pdfScale: this.plugin.settings.pdfScale,
};
}
/**
* Exports drawing-owned state for a one-shot window migration.
*
@@ -675,10 +735,50 @@ export class ExcalidrawData {
data: string,
file: TFile,
textMode: TextMode,
isCurrent: LoadGenerationGuard = () => true,
): Promise<boolean> {
if (!file) {
if (!file || !isCurrent()) {
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);
if (!isCurrent()) {
return false;
}
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<
@@ -704,52 +804,13 @@ 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?.[
MARKDOWN_IMAGE_CUSTOM_DATA_KEY
] as MarkdownImageCustomData | undefined;
if (
element.type === "image" &&
markdownImageData?.source === "local" &&
!parsedMarkdownImages.has(element.fileId)
) {
this.plugin.markdownImagesMaster.delete(element.fileId);
}
});
// A missing block is local to this drawing. Do not delete the shared
// clipboard source: another open drawing may still own valid Markdown for
// the same copied fileId.
parsedMarkdownImages.forEach((value, fileId) =>
this.setMarkdownImage(fileId, value),
);
@@ -782,6 +843,9 @@ export class ExcalidrawData {
);
prompt.contentEl.focus();
const confirmation = await prompt.waitForClose;
if (!isCurrent()) {
return false;
}
if (!confirmation) {
throw new Error(ERROR_IFRAME_CONVERSION_CANCELED);
}
@@ -789,6 +853,9 @@ export class ExcalidrawData {
this.initializeNonInitializedFields();
const timer = window.setTimeout(() => {
if (!isCurrent()) {
return;
}
const notice = new Notice(t("FONT_LOAD_SLOW"), 15000);
notice.messageEl.oncontextmenu = () => {
displayFontMessage(this.app);
@@ -796,6 +863,9 @@ export class ExcalidrawData {
}, 5000);
await loadSceneFonts(nonDeletedSceneElements);
window.clearTimeout(timer);
if (!isCurrent()) {
return false;
}
if (!this.scene.files) {
this.scene.files = {}; //loading legacy scenes that do not yet have the files attribute.
@@ -875,7 +945,9 @@ export class ExcalidrawData {
position = data.search(RE_TEXTELEMENTS_FALLBACK_2);
}
if (position === -1) {
await this.setTextMode(textMode);
if (!(await this.setTextMode(textMode, isCurrent)) || !isCurrent()) {
return false;
}
this.loaded = true;
return true; //Text Elements header does not exist
}
@@ -956,6 +1028,9 @@ export class ExcalidrawData {
elementLinkMap.delete(id);
}
const parseRes = await this.parse(text);
if (!isCurrent()) {
return false;
}
textEl.rawText = text;
this.textElements.set(id, {
raw: text,
@@ -1056,13 +1131,19 @@ export class ExcalidrawData {
//e.g. if the entire text elements section was deleted.
this.findNewTextElementsInScene();
this.findNewElementLinksInScene(); //non-text element links
await this.setTextMode(textMode);
if (!(await this.setTextMode(textMode, isCurrent)) || !isCurrent()) {
return false;
}
this.loaded = true;
return true;
}
public async loadLegacyData(data: string, file: TFile): Promise<boolean> {
if (!file) {
public async loadLegacyData(
data: string,
file: TFile,
isCurrent: LoadGenerationGuard = () => true,
): Promise<boolean> {
if (!file || !isCurrent()) {
return false;
}
this.loaded = false;
@@ -1091,17 +1172,22 @@ export class ExcalidrawData {
this.mermaids.clear();
this.findNewTextElementsInScene();
this.findNewElementLinksInScene();
await this.setTextMode(TextMode.raw); //legacy files are always displayed in raw mode.
if (!(await this.setTextMode(TextMode.raw, isCurrent)) || !isCurrent()) {
return false;
} //legacy files are always displayed in raw mode.
this.loaded = true;
return true;
}
public async setTextMode(textMode: TextMode) {
if (!this.scene) {
return;
public async setTextMode(
textMode: TextMode,
isCurrent: LoadGenerationGuard = () => true,
): Promise<boolean> {
if (!this.scene || !isCurrent()) {
return false;
}
this.textMode = textMode;
await this.updateSceneTextElements();
return await this.updateSceneTextElements(isCurrent);
}
/**
@@ -1110,7 +1196,9 @@ export class ExcalidrawData {
* @param forceupdate : will update text elements even if text contents has not changed, this will
* correct sizing issues
*/
private async updateSceneTextElements() {
private async updateSceneTextElements(
isCurrent: LoadGenerationGuard = () => true,
): Promise<boolean> {
//update text in scene based on textElements Map
//first get scene text elements
const elementsMap = arrayToMap(this.scene.elements) as ElementsMap;
@@ -1120,7 +1208,10 @@ export class ExcalidrawData {
for (const te of texts) {
const container = getContainerElement(te, elementsMap);
const originalText =
(await this.getText(te.id)) ?? te.originalText ?? te.text;
(await this.getText(te.id, isCurrent)) ?? te.originalText ?? te.text;
if (!isCurrent()) {
return false;
}
const { text, x, y, width, height } = refreshTextDimensions(
te,
container,
@@ -1143,9 +1234,13 @@ export class ExcalidrawData {
);
}
}
return true;
}
private async getText(id: string): Promise<string> {
private async getText(
id: string,
isCurrent: LoadGenerationGuard = () => true,
): Promise<string> {
const text = this.textElements.get(id);
if (!text) {
return null;
@@ -1153,6 +1248,9 @@ export class ExcalidrawData {
if (this.textMode === TextMode.parsed) {
if (!text.parsed) {
const parseRes = await this.parse(text.raw);
if (!isCurrent()) {
return null;
}
this.textElements.set(id, {
raw: text.raw,
parsed: parseRes.parsed,
@@ -1768,10 +1866,17 @@ export class ExcalidrawData {
FileId,
Mutable<ExcalidrawImageElement>[]
>();
const localMarkdownFileIds = new Set<FileId>();
for (const element of scene.elements) {
if (element.type !== "image") {
continue;
}
const markdownImageData = element.customData?.[
MARKDOWN_IMAGE_CUSTOM_DATA_KEY
] as MarkdownImageCustomData | undefined;
if (markdownImageData?.source === "local") {
localMarkdownFileIds.add(element.fileId);
}
images.push(element);
fileIds.push(element.fileId);
const imagesForFile = imagesByFileId.get(element.fileId);
@@ -1810,6 +1915,19 @@ export class ExcalidrawData {
}
});
// The element metadata is authoritative for source type. A local Markdown
// image may retain stale per-view entries after changing its source. Clear
// those incompatible entries, but do not restore from the plugin-wide
// clipboard registry here: onPaste owns clipboard import, while an ordinary
// reload must respect Markdown text deliberately removed from the note.
// This is registry bookkeeping within an already-authorized save and does
// not require loadDrawing() to republish the unchanged scene files.
localMarkdownFileIds.forEach((fileId) => {
this.files.delete(fileId);
this.equations.delete(fileId);
this.mermaids.delete(fileId);
});
//check if there are any images that need to be processed in the new scene
if (!scene.files || Object.keys(scene.files).length === 0) {
return dirty;
@@ -1827,6 +1945,9 @@ export class ExcalidrawData {
const processedIds = new Set<string>();
fileIds.forEach((fileId, idx) => {
if (processedIds.has(fileId)) {
if (localMarkdownFileIds.has(fileId)) {
return;
}
const embeddedFile = this.getFile(fileId);
const equation = this.getEquation(fileId);
const mermaid = this.getMermaid(fileId);
@@ -1899,26 +2020,27 @@ export class ExcalidrawData {
});
for (const key of Object.keys(scene.files)) {
const fileId = key as FileId;
const fileData = scene.files[key] as (typeof scene.files)[string] & {
name?: string;
};
const mermaidElements = getMermaidImageElements(
imagesByFileId.get(key as FileId) ?? [],
imagesByFileId.get(fileId) ?? [],
);
if (
!(
this.hasFile(key as FileId) ||
this.hasEquation(key as FileId) ||
this.hasMermaid(key as FileId) ||
this.hasMarkdownImage(key as FileId) ||
mermaidElements.length > 0
)
) {
if (localMarkdownFileIds.has(fileId)) {
continue;
}
const hasKnownSource =
this.hasFile(fileId) ||
this.hasEquation(fileId) ||
this.hasMermaid(fileId) ||
mermaidElements.length > 0;
if (!hasKnownSource) {
dirty = true;
await this.saveDataURLtoVault(
fileData.dataURL,
fileData.mimeType,
key as FileId,
fileId,
fileData.name,
);
}
+25
View File
@@ -29,6 +29,7 @@ type ImageCacheMetadata = Partial<
>;
type BackupData = string;
type BackupKey = string;
const BACKUP_WRITE_DELAY_MS = 50;
export type ImageKey = {
filepath: string;
@@ -559,6 +560,7 @@ class ImageCache {
file,
cachedData.mtime,
this.plugin,
"indexeddb-cache-validation",
);
if (dependencyChanged) {
return undefined;
@@ -855,3 +857,26 @@ export const getImageCache = (): ImageCache => {
}
return imageCache;
};
/**
* Queues the exact text from a completed drawing write for recovery.
* Backup failure is logged independently and never changes source persistence.
*/
export const scheduleBAKAfterSuccessfulPersistence = (
filepath: string,
data: BackupData,
): void => {
try {
getImageCache().scheduleBAKToCache(
filepath,
data,
BACKUP_WRITE_DELAY_MS,
);
} catch (error: unknown) {
errorlog({
where: "ImageCache.scheduleBAKAfterSuccessfulPersistence",
fn: "schedule",
error,
});
}
};
+20 -2
View File
@@ -5,6 +5,14 @@ import { FileData, MimeType } from "src/types/embeddedFileLoaderTypes";
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import ExcalidrawPlugin from "src/core/main";
import type { ExcalidrawExtrasAPI } from "@zsviczian/excalidraw-extras-api";
import type { MathJaxRenderOptions } from "src/types/mathJaxTypes";
type Tex2DataURLWithOptions = (
tex: string,
scale?: number,
preamble?: string | null,
options?: MathJaxRenderOptions,
) => ReturnType<ExcalidrawExtrasAPI["mathjax"]["tex2dataURL"]>;
export const updateEquation = async (
equation: string,
@@ -33,6 +41,7 @@ export async function tex2dataURL(
tex: string,
scale: number = 4,
plugin: ExcalidrawPlugin,
options?: MathJaxRenderOptions,
): Promise<{
mimeType: MimeType;
fileId: FileId;
@@ -59,13 +68,22 @@ export async function tex2dataURL(
}
// 3. Hand the request off to the cleanly isolated Extras plugin
return (await mathjaxAPI.tex2dataURL(tex, scale, preambleStr)) as {
// The runtime component version gate guarantees this additive signature even
// while the separately published API typings remain on the previous version.
const mathjaxAPIWithOptions: { tex2dataURL: Tex2DataURLWithOptions } =
mathjaxAPI;
return (await mathjaxAPIWithOptions.tex2dataURL(
tex,
scale,
preambleStr,
options,
)) as {
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
created: number;
size: { height: number; width: number };
};
} | null;
}
export const clearMathJaxVariables = (plugin: ExcalidrawPlugin) => {
+79 -17
View File
@@ -70,7 +70,7 @@ export function containsReservedMarkdownImageMarker(
/** Reads the feature metadata from an image element without modifying it. */
export function getMarkdownImageCustomData(
element: ExcalidrawImageElement,
element: ExcalidrawElement,
): MarkdownImageCustomData | undefined {
const value: unknown = element.customData?.[MARKDOWN_IMAGE_CUSTOM_DATA_KEY];
return value && typeof value === "object"
@@ -81,7 +81,7 @@ export function getMarkdownImageCustomData(
/** Resolves the element appearance, then the configured defaults. */
export function getMarkdownImageRenderSettings(
plugin: ExcalidrawPlugin,
element?: ExcalidrawImageElement,
element?: ExcalidrawElement,
): MarkdownImageRenderSettings {
const stored = element ? getMarkdownImageCustomData(element)?.render : null;
const fallback = plugin.settings.markdownImageSettings.defaults;
@@ -176,12 +176,16 @@ export function isMarkdownImageElement(
view: ExcalidrawView,
element: ExcalidrawImageElement,
): boolean {
if (
getMarkdownImageCustomData(element) ||
view.excalidrawData.markdownImages.has(element.fileId)
) {
return true;
}
const embeddedFile = view.excalidrawData.getFile(element.fileId);
return Boolean(
getMarkdownImageCustomData(element) ||
view.excalidrawData.hasMarkdownImage(element.fileId) ||
(embeddedFile?.file?.extension.toLowerCase() === "md" &&
!view.plugin.isExcalidrawFile(embeddedFile.file)),
embeddedFile?.file?.extension.toLowerCase() === "md" &&
!view.plugin.isExcalidrawFile(embeddedFile.file),
);
}
@@ -195,6 +199,24 @@ async function renderMarkdown(
return loader.renderMarkdownToSVG(sourceFile, markdown, render);
}
const rememberRenderedMarkdownImage = (
view: ExcalidrawView,
elementId: string,
markdown: string,
sourceFile: TFile,
): ExcalidrawImageElement | null => {
const element = view
.getViewElements()
.find(
(candidate): candidate is ExcalidrawImageElement =>
candidate.id === elementId && candidate.type === "image",
);
if (element) {
view.rememberMarkdownImageRender(element, markdown, sourceFile);
}
return element ?? null;
};
const setRenderedMarkdownImageFile = (
ea: ReturnType<typeof getEA>,
fileId: FileId,
@@ -286,13 +308,14 @@ export async function convertEmbeddableElementToMarkdownImage(
element: ExcalidrawEmbeddableElement,
sourceData: MarkdownImageSourceData,
): Promise<boolean> {
const render = getMarkdownImageRenderSettings(view.plugin);
const render = getMarkdownImageRenderSettings(view.plugin, element);
render.width = Math.max(50, Math.round(element.width));
const sourceFile = sourceData.embeddedFile?.file ?? view.file;
const rendered = await renderMarkdown(
view,
sourceData.markdown,
render,
sourceData.embeddedFile?.file ?? view.file,
sourceFile,
);
if (!rendered.dataURL || rendered.size.height <= 0) {
return false;
@@ -335,6 +358,12 @@ export async function convertEmbeddableElementToMarkdownImage(
if (converted) {
view.excalidrawAPI.selectElements([converted]);
}
rememberRenderedMarkdownImage(
view,
element.id,
sourceData.markdown,
sourceFile,
);
view.setDirty();
return true;
}
@@ -355,7 +384,6 @@ export async function convertMarkdownImageElementToEmbeddable(
delete editable.status;
delete editable.crop;
addAppendUpdateCustomData(editable, {
[MARKDOWN_IMAGE_CUSTOM_DATA_KEY]: undefined,
mdProps: view.plugin.settings.embeddableMarkdownDefaults,
});
if (!(await commitElements(ea))) {
@@ -433,11 +461,12 @@ export async function insertMarkdownImage(
return null;
}
const render = getMarkdownImageRenderSettings(view.plugin);
const sourceFile = sourceData.embeddedFile?.file ?? view.file;
const rendered = await renderMarkdown(
view,
sourceData.markdown,
render,
sourceData.embeddedFile?.file ?? view.file,
sourceFile,
);
if (!rendered.dataURL || rendered.size.height <= 0) {
return null;
@@ -477,6 +506,12 @@ export async function insertMarkdownImage(
}
view.setDirty();
view.excalidrawAPI.selectElements([element]);
rememberRenderedMarkdownImage(
view,
element.id,
sourceData.markdown,
sourceFile,
);
return element;
}
@@ -535,9 +570,12 @@ export async function duplicateLocalMarkdownImageElement(
return null;
}
view.setDirty();
const inserted = view
.getViewElements()
.find((candidate) => candidate.id === duplicate.id);
const inserted = rememberRenderedMarkdownImage(
view,
duplicate.id,
source.markdown,
view.file,
);
if (inserted) {
view.excalidrawAPI.selectElements([inserted]);
}
@@ -551,17 +589,40 @@ export async function updateMarkdownImage(
markdown: string,
render: MarkdownImageRenderSettings,
source: MarkdownImageSource,
sameFileEditOwnerOrShouldApply: string | (() => boolean) = () => true,
shouldApplyAfterOwner: () => boolean = () => true,
): Promise<boolean> {
if (containsReservedMarkdownImageMarker(markdown)) {
return false;
}
view.setMarkdownImageEditorIsEditing();
const sameFileEditOwnerId =
typeof sameFileEditOwnerOrShouldApply === "string"
? sameFileEditOwnerOrShouldApply
: undefined;
const shouldApply =
typeof sameFileEditOwnerOrShouldApply === "function"
? sameFileEditOwnerOrShouldApply
: shouldApplyAfterOwner;
view.setMarkdownImageEditorIsEditing(sameFileEditOwnerId);
const sourceFile =
source === "external"
? (view.excalidrawData.getFile(element.fileId)?.file ?? view.file)
: view.file;
const rendered = await renderMarkdown(view, markdown, render, sourceFile);
if (!rendered.dataURL || rendered.size.height <= 0) {
if (
!rendered.dataURL ||
rendered.size.height <= 0 ||
!shouldApply()
) {
return false;
}
const currentElement = view
.getViewElements()
.find((candidate) => candidate.id === element.id);
if (
currentElement?.type !== "image" ||
currentElement.fileId !== element.fileId
) {
return false;
}
const ea = getEA(view);
@@ -578,6 +639,7 @@ export async function updateMarkdownImage(
if (!(await commitElements(ea))) {
return false;
}
rememberRenderedMarkdownImage(view, element.id, markdown, sourceFile);
view.setDirty();
// Persist right after every successful render instead of only on specific UI events (switching
// elements, closing the sidepanel, etc.). Those events are not reliable signals of "the user is
@@ -585,8 +647,8 @@ export async function updateMarkdownImage(
// is moved out of view, and none of that tells us whether the editor is still visible. Saving
// here ties persistence directly to the one thing we know for certain changed: the element in
// the scene. forceSave's waitIfBusy avoids silently no-oping against a concurrent save, and the
// override bypasses the embeddableIsEditingSelf debounce without touching it, so this does not
// disrupt the ongoing edit the way a reload()-driven refresh would.
// bypass leaves this controller's same-file ownership intact, so it does
// not disrupt the ongoing edit the way a reload-driven refresh would.
await view.forceSave(true, true);
return true;
}
+46 -17
View File
@@ -53,6 +53,15 @@ type CompiledScript = {
executable: ScriptExecutable | null;
};
type ViewAutostartRuntime = NonNullable<
ExcalidrawView["selectedElementActionsMenu"]
>;
type ViewAutostartAttachment = {
runtime: ViewAutostartRuntime;
completion: Promise<void>;
};
export interface ScriptFileRenamePlan {
renames: Array<{
file: TFile;
@@ -85,7 +94,7 @@ export class ScriptEngine {
/** Successful or in-flight automatic attachments, scoped to a view and script path. */
private autostartAttachments = new WeakMap<
ExcalidrawView,
Map<string, Promise<void>>
Map<string, ViewAutostartAttachment>
>();
/** EAs whose top-level script invocation currently has a view-autostart trigger. */
private viewAutostartEAs = new WeakSet<ExcalidrawAutomate>();
@@ -755,6 +764,12 @@ export class ScriptEngine {
view: ExcalidrawView,
where: string,
): Promise<void> {
const runtime = view.selectedElementActionsMenu;
if (!runtime) {
// Hidden workspace leaves may not have mounted their React tree yet.
// Their mount effect will request attachment after creating the menu.
return;
}
let attachments = this.autostartAttachments.get(view);
if (!attachments) {
attachments = new Map();
@@ -762,33 +777,46 @@ export class ScriptEngine {
}
const scriptPath = file.path;
const existing = attachments.get(scriptPath);
if (existing !== undefined) {
await existing;
if (existing?.runtime === runtime) {
await existing.completion;
return;
}
let succeeded = false;
let runtimeWasReplaced = false;
const run = (async (): Promise<void> => {
try {
await this.executeScriptFile(
view,
file,
scriptName,
"view-autostart",
);
const executable = await this.getCompiledScript(file);
if (view.selectedElementActionsMenu !== runtime) {
runtimeWasReplaced = true;
return;
}
if (executable) {
await this.executeExecutable(
view,
executable,
scriptName,
file,
"view-autostart",
);
}
succeeded = true;
} catch (error: unknown) {
errorlog({ where, scriptName, error });
}
if (runtimeWasReplaced) {
return;
}
try {
await this.recordAutostartResult(scriptName, !succeeded);
} catch (error: unknown) {
errorlog({ where: `${where}.recordAutostartResult`, scriptName, error });
}
})();
attachments.set(scriptPath, run);
const attachment = { runtime, completion: run };
attachments.set(scriptPath, attachment);
await run;
if (!succeeded && attachments.get(scriptPath) === run) {
if (!succeeded && attachments.get(scriptPath) === attachment) {
attachments.delete(scriptPath);
}
}
@@ -954,13 +982,14 @@ export class ScriptEngine {
): Promise<unknown> {
//addresses the situation when after paste text element IDs are not updated to 8 characters
//linked to onPaste save issue with the false parameter
//The Excalidraw API can briefly be null while React replaces the canvas
//during a view transition. This legacy save preflight is optional; script
//execution itself must continue so view-autostart can attach to the new view.
const scene = view?.getScene();
if (
view &&
view
.getScene()
.elements.some(
(el) => !el.isDeleted && el.type === "text" && el.id.length > 8,
)
scene?.elements.some(
(el) => !el.isDeleted && el.type === "text" && el.id.length > 8,
)
) {
await view.save(false, true);
}
+13 -13
View File
@@ -2,10 +2,11 @@ import {
AbstractInputSuggest,
App,
TAbstractFile,
TFile,
TFolder,
} from "obsidian";
type VaultPathSuggestionKind = "file" | "folder";
type VaultPathSuggestionKind = "file" | "folder" | "file-or-folder";
/** Adds reusable Vault-aware completion to settings path inputs. */
export class VaultPathSuggest extends AbstractInputSuggest<TAbstractFile> {
@@ -23,18 +24,17 @@ export class VaultPathSuggest extends AbstractInputSuggest<TAbstractFile> {
const normalizedExtensions = extensions?.map((extension) =>
extension.toLowerCase().replace(/^\./, ""),
);
this.candidates =
kind === "folder"
? app.vault
.getAllLoadedFiles()
.filter((file) => file instanceof TFolder)
: app.vault
.getFiles()
.filter(
(file) =>
!normalizedExtensions ||
normalizedExtensions.includes(file.extension.toLowerCase()),
);
this.candidates = app.vault.getAllLoadedFiles().filter((file) => {
if (file instanceof TFolder) {
return kind !== "file";
}
return (
kind !== "folder" &&
file instanceof TFile &&
(!normalizedExtensions ||
normalizedExtensions.includes(file.extension.toLowerCase()))
);
});
this.limit = 30;
}
+24 -26
View File
@@ -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"));
}
+10
View File
@@ -243,6 +243,16 @@ export function syncMarkdownImagesInHeader(
updated.slice(block.bodyEnd);
}
updated = updated
.replace(
/(^# Markdown Images[ \t]*\r?\n)(?:[ \t]*\r?\n)+(?=<!-- excalidraw-markdown-image:)/m,
`$1\n`,
)
.replace(
/(<!-- \/excalidraw-markdown-image:[\w-]+ -->)[ \t]*(?:\r?\n[ \t]*)+(?=<!-- excalidraw-markdown-image:)/g,
`$1\n\n`,
);
const missing = [...markdownImages.entries()].filter(
([fileId]) => !existingIds.has(fileId),
);
@@ -79,6 +79,7 @@ export function createExElement(): ExcalidrawElementBase {
updated: Date.now(),
link: null,
locked: false,
created: Date.now(),
};
}
+64 -1
View File
@@ -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;
}
+1
View File
@@ -303,6 +303,7 @@ declare namespace ExcalidrawLib {
} | undefined>;*/
let hashElementsVersion: typeof import("@zsviczian/excalidraw/types/excalidraw").hashElementsVersion;
let convertToExcalidrawElements: typeof import("@zsviczian/excalidraw").convertToExcalidrawElements;
let Excalidraw: typeof import("@zsviczian/excalidraw").Excalidraw;
let MainMenu: typeof import("@zsviczian/excalidraw").MainMenu;
let WelcomeScreen: typeof import("@zsviczian/excalidraw").WelcomeScreen;
-16
View File
@@ -102,8 +102,6 @@ export type MarkdownBlockCacheEntry = {
export interface ViewSemaphores {
warnAboutLinearElementLinkClick: boolean;
//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.
@@ -121,22 +119,8 @@ export interface ViewSemaphores {
//the preventAutozoomOnLoad flag will prevent the open drawing from autozooming when it is reloaded
preventAutozoom: boolean;
autosaving: boolean; //flags that autosaving is in progress. Autosave is an async timer, the flag prevents collision with force save
forceSaving: boolean; //flags that forcesaving is in progress. The flag prevents collision with autosaving
dirty: string | null; //null if there are no changes to be saved, the path of the file if the drawing has unsaved changes
//reload() is triggered by modifyEventHandler in main.ts. preventReload is a one time flag to abort reloading
//to avoid interrupting the flow of drawing by the user.
preventReload: boolean;
isEditingText: boolean; //https://stackoverflow.com/questions/27132796/is-there-any-javascript-event-fired-when-the-on-screen-keyboard-on-mobile-safari
//Save is triggered by multiple threads when an Excalidraw pane is terminated
//- by the view itself
//- by the activeLeafChangeEventHandler change event handler
//- by monkeypatches on detach(next)
//This semaphore helps avoid collision of saves
saving: boolean;
hoverSleep: boolean; //flag with timer to prevent hover preview from being triggered dozens of times
wheelTimeout: number | null; //used to avoid hover preview while zooming
shouldSaveImportedImage: boolean; //forceSave after image import via the Excalidraw Image Tool or by way of paste
+3
View File
@@ -4,6 +4,9 @@ export const MARKDOWN_IMAGE_SCHEMA_VERSION = 1;
export type MarkdownImageSource = "local" | "external";
/** Persisted behavior for deleting a local Markdown image from the scene. */
export type MarkdownImageDeletionPreference = "ask" | "keep" | "delete";
export type MarkdownImageTransclusionRenderSettings = {
enabled: boolean;
fontFamily: string;
+5
View File
@@ -0,0 +1,5 @@
/** Options for rendering LaTeX through the Excalidraw Extras MathJax service. */
export interface MathJaxRenderOptions {
/** Propagate MathJax conversion errors instead of returning null. */
throwOnError?: boolean;
}
+32 -18
View File
@@ -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;
}
+1 -1
View File
@@ -14,7 +14,7 @@ const REQUIRED_EXTRAS_VERSIONS: Record<
{ min?: string; exact?: string }
> = {
plugin: { min: "0.0.15" },
mathjax: { min: "1.0.0" },
mathjax: { min: "1.1.0" },
mermaid: { exact: "2.2.2" },
pdf: { min: "1.0.0" },
filesystem: { min: "1.0.0" },
+3 -5
View File
@@ -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,
+6 -5
View File
@@ -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);
}
}
+162 -1
View File
@@ -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.
*
+10 -5
View File
@@ -157,7 +157,7 @@ const executeCommandLinkWithConfirmation = async (cmd: string, app: App) => {
/**
* Returns the set of top-level embedded-file IDs that need to be rebuilt on
* leaf switch because either the file itself or any nested Excalidraw dependency
* leaf switch because either the file itself or any nested visual dependency
* was modified since the view last completed a scene load.
*/
export function getChangedTopLevelDependencyFileIDs(
@@ -177,7 +177,7 @@ export function getChangedTopLevelDependencyFileIDs(
for (const [fileId, embeddedFile] of view.excalidrawData.getFileEntries()) {
const embeddedTarget = embeddedFile?.file;
if (!embeddedTarget || embeddedFile.mtime === 0) {
if (!embeddedTarget) {
continue;
}
@@ -186,7 +186,7 @@ export function getChangedTopLevelDependencyFileIDs(
changedFileIDs.add(fileId);
}
// Track Excalidraw embeds so we can walk their nested deps below.
// Track Excalidraw embeds so nested changes can be mapped back to them.
if (plugin.isExcalidrawFile(embeddedTarget)) {
const set =
excalidrawFileIdsByPath.get(embeddedTarget.path) ?? new Set<FileId>();
@@ -199,10 +199,15 @@ export function getChangedTopLevelDependencyFileIDs(
return changedFileIDs;
}
// Walk the full nested dependency tree of the root drawing.
// Walk the full nested visual-dependency tree of the root drawing.
// If any nested file changed since lastLoadTime, mark all top-level embeds
// that include it (identified via path[1]) as needing a rebuild.
const nestedTree = getAllNestedExcalidrawFiles(plugin, view.file, false);
const nestedTree = getAllNestedExcalidrawFiles(
plugin,
view.file,
true,
"leaf-switch",
);
for (const [file, node] of nestedTree.entries()) {
if (file.stat.mtime <= lastLoadTime) {
continue;
+6 -9
View File
@@ -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`,
);
}
+96 -11
View File
@@ -30,6 +30,10 @@ import { IMAGE_MIME_TYPES, MimeType } from "src/types/embeddedFileLoaderTypes";
import type { PdfJsDocumentProxy } from "src/types/pdfJsTypes";
import { setElementDisplay } from "./htmlUtils";
import { NestedFileMap } from "src/types/utilTypes";
import {
nestedDependencyElapsedMs,
recordNestedTreeDiagnostic,
} from "./nestedDependencyDiagnostics";
export { splitFolderAndFilename } from "./pathUtils";
declare const mainDocument: Document;
@@ -57,6 +61,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
@@ -578,13 +602,16 @@ export function getAllNestedExcalidrawFiles(
plugin: ExcalidrawPlugin, // Replace `any` with `ExcalidrawPlugin` type in your actual code
rootFile: TFile,
includeImages = false,
diagnosticCallSite = "unspecified",
): NestedFileMap {
const traversalStartedAt = performance.now();
const app = plugin.app;
// Phase 1: Build the Adjacency List (Directed Acyclic Graph)
// This ensures we only parse the metadata cache for each file exactly once.
const adjacencyList = new Map<TFile, TFile[]>();
const parsedFiles = new Set<string>();
let dependencyEdges = 0;
function parseFile(file: TFile) {
if (parsedFiles.has(file.path)) {
@@ -672,11 +699,13 @@ export function getAllNestedExcalidrawFiles(
}
}
dependencyEdges += uniqueChildren.size;
adjacencyList.set(file, Array.from(uniqueChildren.values()));
}
// Populate the adjacency list
parseFile(rootFile);
const parseElapsedMs = nestedDependencyElapsedMs(traversalStartedAt);
// Phase 2: Generate the paths from the in-memory Adjacency List
const result: NestedFileMap = new Map();
@@ -685,6 +714,8 @@ export function getAllNestedExcalidrawFiles(
const stack: { file: TFile; path: TFile[] }[] = [
{ file: rootFile, path: [rootFile] },
];
let generatedPaths = 0;
let maximumDepth = 0;
while (stack.length > 0) {
const { file, path } = stack.pop();
@@ -705,12 +736,28 @@ export function getAllNestedExcalidrawFiles(
}
node.paths.push(childPath);
generatedPaths++;
maximumDepth = Math.max(maximumDepth, childPath.length - 1);
// Push to stack to continue generating paths for its children
stack.push({ file: child, path: childPath });
}
}
const totalElapsedMs = nestedDependencyElapsedMs(traversalStartedAt);
recordNestedTreeDiagnostic({
callSite: diagnosticCallSite,
includeImages,
uniqueFiles: result.size + 1,
parsedDrawings: parsedFiles.size,
dependencyEdges,
generatedPaths,
maximumDepth,
parseMs: parseElapsedMs,
pathsMs: Math.round((totalElapsedMs - parseElapsedMs) * 10) / 10,
totalMs: totalElapsedMs,
});
return result;
}
@@ -722,7 +769,12 @@ export const getExcalidrawEmbeddedFilesFiletree = (
return [];
}
const result = getAllNestedExcalidrawFiles(plugin, sourceFile, true);
const result = getAllNestedExcalidrawFiles(
plugin,
sourceFile,
true,
"ea-filetree",
);
return Array.from(result.keys());
};
@@ -730,12 +782,20 @@ export const hasExcalidrawEmbeddedImagesTreeChanged = (
sourceFile: TFile,
mtime: number,
plugin: ExcalidrawPlugin,
diagnosticCallSite = "cache-validation",
): boolean => {
if (!sourceFile || !plugin.isExcalidrawFile(sourceFile)) {
return false;
}
const nestedTree = getAllNestedExcalidrawFiles(plugin, sourceFile, false);
// Include ordinary vault files because they may be Markdown-image sources
// nested inside an otherwise unchanged Excalidraw drawing.
const nestedTree = getAllNestedExcalidrawFiles(
plugin,
sourceFile,
true,
diagnosticCallSite,
);
for (const file of nestedTree.keys()) {
if (file.stat.mtime > mtime) {
return true;
@@ -818,27 +878,52 @@ export async function createOrOverwriteFile(
path: string,
content: string | ArrayBuffer | Blob,
): Promise<TFile> {
const { folderpath } = splitFolderAndFilename(path);
if (folderpath) {
await checkAndCreateFolder(folderpath);
}
const file = app.vault.getAbstractFileByPath(normalizePath(path));
path = normalizePath(path);
if (content instanceof Blob) {
content = await content.arrayBuffer();
}
const { folderpath } = splitFolderAndFilename(path);
if (folderpath) {
try {
await checkAndCreateFolder(folderpath);
} catch (error: unknown) {
if (!app.vault.getFolderByPath(folderpath)) {
throw error;
}
}
}
const file = app.vault.getFileByPath(path);
if (content instanceof ArrayBuffer) {
if (file && file instanceof TFile) {
if (file) {
await app.vault.modifyBinary(file, content);
return file;
}
return await app.vault.createBinary(path, content);
try {
return await app.vault.createBinary(path, content);
} catch (error: unknown) {
const racedFile = app.vault.getFileByPath(path);
if (!racedFile) {
throw error;
}
await app.vault.modifyBinary(racedFile, content);
return racedFile;
}
}
if (file && file instanceof TFile) {
if (file) {
await app.vault.modify(file, content);
return file;
}
return await app.vault.create(path, content);
try {
return await app.vault.create(path, content);
} catch (error: unknown) {
const racedFile = app.vault.getFileByPath(path);
if (!racedFile) {
throw error;
}
await app.vault.modify(racedFile, content);
return racedFile;
}
}
export async function createFileAndAwaitMetacacheUpdate(
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff. Show more