Compare commits

...
304 Commits
Author SHA1 Message Date
zsviczian 2d39586865 implemented toggleViewMode 2026-09-28 19:50:45 +02:00
zsviczian 3f98be4500 Merge pull request #2960 from zsviczian/kplex-support
feat: add view-scoped integration APIs for K-Plex
2026-09-28 12:13:45 +02:00
zsviczian 038384ce2a linkclick hook, zoom to fit view 2026-09-28 12:12:22 +02:00
zsviczian 7f16448595 save fontTopPicks to file 2026-09-26 10:31:31 +02:00
zsviczian 542fcec6ac 2.28.0-beta.4 2026-09-24 22:30:49 +02:00
zsviczian a8182899b7 2.28.0-beta.3 2026-09-20 18:06:08 +02:00
zsviczian 9d5057dba7 updated excalidraw manifest with correct link 2026-09-20 14:36:40 +02:00
zsviczian 718f671109 ExcaliBrain patch compatiblity 2026-09-20 12:27:17 +02:00
zsviczian 6294305dd8 script store optimization, legacy script store removal 2026-09-20 06:38:53 +02:00
zsviczian add50b79d4 updated ea-scripting.md 2026-09-19 17:51:19 +02:00
zsviczian 6197ebe199 2.28.0-beta.2 2026-09-19 17:14:41 +02:00
zsviczian 5c51d057f3 updated skills 2026-09-19 16:47:42 +02:00
zsviczian 593b02cce3 Merge pull request #2944 from zsviczian/reimagine-scriptstore
feat: Reimagine the Community Script Store
2026-09-19 16:41:35 +02:00
zsviczian b255fe49c5 Fix script store file line endings 2026-09-19 16:36:57 +02:00
zsviczian 74d1529dcb Merge remote-tracking branch 'origin/master' into reimagine-scriptstore 2026-09-19 16:21:26 +02:00
zsviczian bd489d7db7 restore index-new.md (2nd attempt) 2026-09-19 16:01:41 +02:00
zsviczian a5ec501be8 remove updating of the legacy index-new.md file 2026-09-19 15:53:31 +02:00
zsviczian 3998139437 reverted index-new.md 2026-09-19 15:47:48 +02:00
zsviczian 1bab2536d6 updated messages 2026-09-19 15:39:35 +02:00
zsviczian 3dd05bca4e dark mode support 2026-09-19 14:07:17 +02:00
zsviczian 287f6a1cc6 manage script groups, open script, fixed script discover to use Excalidraw/Scripts/Downloaded folder, added reinstall, and uninstall 2026-09-19 13:57:16 +02:00
zsviczian b661cb45f5 updated ai skill generator to announce manifest update 2026-09-19 11:34:47 +02:00
zsviczian 6474b18464 updated ai skill generation 2026-09-19 11:29:35 +02:00
zsviczian bf93306fbd restored directory-info.json and updated header 2026-09-19 11:28:42 +02:00
zsviczian 29d647b510 automate anything image 2026-09-19 10:51:44 +02:00
zsviczian abebbc22fd updated AI skill generation 2026-09-19 10:31:23 +02:00
zsviczian f110a7be96 updated directory-info.json 2026-09-19 09:41:46 +02:00
zsviczian 9b11d9e79f initial scriptstore commit 2026-09-19 06:18:14 +02:00
zsviczian 98d0fb193c moved to platform independent repozitory zip / update functions 2026-09-19 06:10:37 +02:00
zsviczian 7e6fd737d6 updated addArrow to fix null error 2026-09-18 21:25:42 +02:00
zsviczian 8ab48bba05 fixed markdown image editing when obsidian default is preview mode 2026-09-17 19:28:11 +02:00
zsviczian e81d90f0e9 edited messages 2026-09-17 17:57:21 +02:00
zsviczian f265b64ca0 Merge pull request #2936 from bluechallenge/fix/hybrid-note-pdf-image-embed-blank
Fix blank sections in Hybrid Note PDF export when Markdown side has an image embed
2026-09-17 17:51:14 +02:00
zsviczian 24287ef627 Merge pull request #2942 from zsviczian/nested-updates
Fix exponential nested dependency traversal
2026-09-17 17:48:06 +02:00
zsviczian a01e337336 Fix exponential nested dependency traversal 2026-09-17 17:44:05 +02:00
bluechallenge ab1131a950 Merge upstream/master to resolve conflict in Messages.ts
# Conflicts:
#	src/shared/Dialogs/Messages.ts
2026-09-17 06:41:41 +04:00
zsviczian b905ff7001 improved messages 2026-09-16 22:29:51 +02:00
zsviczian 63a466afbd 2.28.0-beta.1 - removed Miro style panning setting (it is not built in by default) 2026-09-16 22:20:21 +02:00
zsviczian ba77c36585 fixes #2940 2026-09-16 17:07:14 +02:00
zsviczian c28f989e23 update wheel zoom text in settings 2026-09-16 16:17:46 +02:00
zsviczian 4948e4e347 fix 2929 2026-09-16 09:42:14 +02:00
zsviczian 3c3a26ec3b updated slideshow script 2026-09-15 22:02:18 +02:00
bluechallengeandClaude Sonnet 5 2580ab8495 Fix blank sections in Hybrid Note PDF export when Markdown side has an image embed
Obsidian's Export to PDF renders the document in its own window (often a
popout), but markdownPostProcessor's isPrinting check only ever looked at
mainDocument's body for the .print marker, so it silently stayed false for
these exports. That caused any section containing a real embed (e.g. a
plain image in a hybrid note's markdown side) to hit the "hide non-preview
excalidraw content" branch and render blank, since none of
isPreview/isMarkdownReadingMode/isPrinting were true.

- Detect isPrinting via the print owner document, not always mainDocument.
- Only route a section through tmpObsidianWYSIWYG's frontmatter/area-ref
  handling when it has no real embeds of its own; sections with embeds
  fall through to processReadingMode, same as the non-print path.
- processInternalEmbed/tmpObsidianWYSIWYG now resolve an internal-embed's
  actual link target via getFirstLinkpathDest instead of assuming it's
  always the containing Excalidraw file, so embedding a different drawing
  in a hybrid note's markdown side renders correctly too.

Fixes #2292

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

Adds a throttled drift guard on pointerenter/pointerdown that compares
the container's bounding rect to the cached appState offsets and calls
refreshCanvasOffset() when they disagree by more than 1px, plus a
css-change hook mirroring the existing layout-change refresh.
2026-08-23 03:10:30 -07:00
zsviczian 9f182616a5 Migrate initial settings sections declaratively 2026-08-23 11:21:13 +02:00
zsviczian 148318ec21 Recover corrupted settings safely 2026-08-23 05:47:05 +02:00
zsviczian 0caa6b7d90 Simplify settings persistence safeguards 2026-08-22 00:04:29 +02:00
zsviczian dd30833789 Recover interrupted settings saves 2026-08-21 22:52:10 +02:00
zsviczian f82f4cf5eb Coalesce settings persistence updates 2026-08-21 22:26:58 +02:00
zsviczian 3f8a04d893 Establish declarative settings adapters 2026-08-21 21:17:51 +02:00
zsviczian f6525d72f8 Add declarative settings compatibility types 2026-08-21 20:57:26 +02:00
zsviczian eeffa5749b Document declarative settings migration plan 2026-08-21 20:27:08 +02:00
zsviczian 36a32940ba Merge pull request #2896 from zsviczian/performance-improvement
Improve embedded scene loading performance
2026-08-16 19:30:14 +02:00
zsviczian 6d344ee3d7 perf: accelerate embedded scene loading 2026-08-16 19:19:57 +02:00
zsviczian 479ecaab33 2.27.0-beta.3 2026-08-16 10:55:46 +02:00
zsviczian 044d39badb fix code scanner findings 2026-08-16 10:46:49 +02:00
zsviczian c6ab40470f updated agents.md and contributing.md 2026-08-16 10:23:18 +02:00
zsviczian d68d23a989 Merge pull request #2895 from zsviczian/new-excalidraw-boundary
Register typed Excalidraw host adapters
2026-08-15 22:43:52 +02:00
zsviczian 8025e1ed1a Complete typed Excalidraw host boundary 2026-08-15 22:40:44 +02:00
zsviczian 57dac2e523 Register Excalidraw package settings adapter 2026-08-15 21:26:09 +02:00
zsviczian c3834b3ed3 Record common host-boundary completion 2026-08-15 20:59:31 +02:00
zsviczian 87f3d863b7 Record desktop UI-mode boundary checkpoint 2026-08-15 20:18:52 +02:00
zsviczian a23ccee9ad Record device-info boundary checkpoint 2026-08-15 20:12:44 +02:00
zsviczian 6c413038f9 Register typed Excalidraw host adapter 2026-08-15 19:58:44 +02:00
zsviczian 4f32647d6f Merge pull request #2893 from zsviczian/excalidraw-automate-cleanup
ExcalidrawAutomate and ExcalidrawView Utils cleanup
2026-08-14 19:16:43 +02:00
zsviczian b0d3125c37 0.18.123 2026-08-14 19:14:52 +02:00
zsviczian 9daa9fa936 typefix on excalidrawViewUtils.ts 2026-08-14 19:00:12 +02:00
zsviczianandClaude Sonnet 5 efb00d1d83 Eliminate remaining any-collapse in ExcalidrawAutomate.ts
cloneElement()/cloneElements() both deep-clone via
JSON.parse(JSON.stringify(el)), which is implicitly any; cast to the
already-known shape (Mutable<ExcalidrawElement>, plus a small local
type for the two cross-element-type relationship fields the generic
remap logic probes). Swapped a same-shape-but-looser inline
boundElements callback annotation for the real BoundElement type, and
gave an untyped new Promise((resolve) => ...) its actual
Promise<string | null>.

The two remaining clusters were genuine external boundaries, fixed at
the source rather than cast around:
- addMermaid()'s result.files traced to mermaidToExcalidraw()'s own
  declared return type in the fork (files?: any). Fixed upstream
  (files?: BinaryFiles) and rebuilt; the suppression is now simply
  unnecessary and removed.
- cloneElements()'s JSON.parse(elementsOrClipboard) now uses the real
  envelope shape confirmed against serializeAsClipboardJSON()/
  actionCopy in the fork's clipboard.ts, instead of a suppression.

Zero eslint-disable comments remain in this file. Confirmed via a
git-stash ESLint diff: 229 -> 172 findings repo-wide, zero regressions,
entire delta contained to this one file. Build, lib, and node --check
all pass clean; dist/main.js unchanged from this repo's side (the fork
rebuild's own +19 bytes aside).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 18:40:32 +02:00
zsviczian d5e2467966 2.27.0-beta.2 2026-08-14 15:25:46 +02:00
zsviczian ccb1f975f4 Merge pull request #2892 from zsviczian/excalidraw-type-import-fix
Fix @excalidraw/common type resolution, eliminating a huge any-collapse
2026-08-14 15:24:44 +02:00
zsviczianandClaude Sonnet 5 8d06fe1ee2 Fix @excalidraw/common type resolution, eliminating a huge any-collapse
@zsviczian/excalidraw's bundled .d.ts files import bare-specifier
@excalidraw/common|element|math|utils, packages this plugin never
depends on (confirmed the same gap exists in upstream's own published
@excalidraw/excalidraw, not a fork-specific bug). Every value that
touched one of those unresolvable imports -- Theme, BinaryFileData.id,
most of AppState, large parts of ExcalidrawElement -- silently
collapsed to any.

Fixed via tsconfig.json paths redirecting all four specifiers (bare
and subpath) into @zsviczian/excalidraw's own already-vendored type
copies under node_modules/@zsviczian/excalidraw/types/ -- zero
version-drift risk since it's literally the same files, and no new
dependency needed. (A first attempt using an external @excalidraw/element
devDependency was reverted: its independently-versioned types
structurally disagreed with this package's own bundled ExcalidrawElement,
producing false-positive mismatches.)

Fixed all 117 real, previously-masked compile errors this surfaced
across 18 files, smallest to largest, each verified with a build
before moving on. Two were genuine pre-existing bugs, not type gaps:

- ExcalidrawView.ts addFiles(): isDark was assigned the literal theme
  string instead of a boolean comparison; !!isDark on any non-empty
  string is always true, so every image loaded through that fallback
  path had been treated as dark-themed regardless of actual theme.
- ExcalidrawView.ts getSelectedTextElement(): the grouped-text-element
  branch cast the originally-selected (possibly non-text) element
  instead of the text element the same branch had already found two
  lines above, silently returning undefined text for non-text
  selections.

getViewColorPalette()'s Array.isArray check, initially flagged as
dead code guarding an impossible shape, turned out to be correct:
AppState.colorPalette's declared ColorPaletteCustom type describes
the record-shaped settings input, but the fork flattens it to a color
list by the time it reaches AppState. Fixed as a documented bridge
cast once confirmed against the fork's own type source, not a logic
change.

Confirmed via a git-stash ESLint diff against the prior commit: 411 ->
229 findings (44% fewer), zero files regressing. Build, lib, and
node --check all pass clean with zero remaining diagnostics.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 15:22:52 +02:00
zsviczianandClaude Sonnet 5 b7472cb8ad Fix unannotated iterator result in excalidrawAutomateUtils.ts
Same shape as the ExcalidrawData.ts RegExpMatchIteratorResult fix: a
let parts; with no type annotation, assigned via res.next(), collapsed
to implicit any. Annotated it. Confirmed via git-stash ESLint diff
that this introduces zero new findings anywhere (413 -> 411).

Also documents a much larger, separate structural finding in
RefactorPlan.md: the remaining 8 findings in this file trace to
@zsviczian/excalidraw's bundled .d.ts files importing from
@excalidraw/common, a package this plugin never depends on -
explains BinaryFileData["id"]/AppState["theme"] collapsing to any.
Not fixed here; needs its own investigation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 13:38:23 +02:00
zsviczianandClaude Sonnet 5 eb02975bfc Fix stale-image retry no-op and ExcalidrawDataScene any-collapse
getFiles() called Object.values() on a Map, which always returns [] -
the only caller (ViewSceneFileManager's stale-image retry loop) has
likely never actually retried a failed-to-load file. Fixed with
Array.from(...values()).

ExcalidrawDataScene intersected a base type that already declared
elements/appState, so TypeScript merged rather than overrode them,
collapsing this.scene.elements to `any` on every direct .filter() call
and cascading into dozens of no-unsafe-* findings. Fixed by Omitting
the colliding keys from the base type before intersecting; type-only,
no runtime behavior change. Two previously-invisible narrowing gaps
this uncovered were fixed with the same `as Mutable<ExcalidrawTextElement>[]`
idiom already used elsewhere in the file.

Confirmed via a git-stash ESLint diff that this introduces zero new
findings anywhere in the repo (470 -> 413, with ExcalidrawAutomate.ts
and ExcalidrawView.ts also improving as a side effect). Both fixes
manually tested and confirmed working.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 13:08:05 +02:00
zsviczianandClaude Sonnet 5 6b2b2592e4 Extract Markdown parsing and embedded-data registries from ExcalidrawData
ExcalidrawData.ts had grown to 2,845 lines. Move the module-level
Markdown/frontmatter parsing functions to excalidrawMarkdownParsing.ts,
and the Files/Equations/MarkdownImages/Mermaids registries to
EmbeddedDataRegistries.ts, both as intact code motion behind
re-exports/delegates so no external caller changed. Reduces
ExcalidrawData.ts to 2,285 lines with zero new lint findings and no
change to the circular-dependency baseline.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 12:35:54 +02:00
zsviczian 2ea7cf5513 fixed: #2889 2026-08-14 09:28:32 +02:00
zsviczian 07b16330d6 Merge pull request #2890 from zsviczian/custom-elements-menu
Feat: Custom elements menu
2026-08-14 09:04:39 +02:00
zsviczianandClaude Sonnet 5 d0898f9fb9 Add script autostart permission flow, UI, and duplicate-registration guard
Completes the script-autostart feature: ExcalidrawAutomate.registerAutostart()
lets a script ask to be automatically re-run every time a new Excalidraw view
opens, gated by a user-confirmed Allow/Deny/Ask-every-time prompt whose
decision persists in the new autostartScripts setting. A fresh "allow" also
immediately attaches the script to every other currently-open view, and
tracks per-script autostart failures (autostartScriptFailures) without
saving settings on every successful run.

ScriptEngine.runAutostartScripts() re-runs allow-listed scripts on each new
view open (wired from ExcalidrawRoot.ts's mount effect); renaming or deleting
a script's file purges its stale permission/failure entries.

Adds AutostartScriptsSettingsComponent, rendered as a table (reusing the
existing AI-provider-table styling) directly in the Excalidraw Automate
settings section and in a Command Palette modal ("Autostart scripts"),
letting a script's Autostart / Manual start only / Ask every time decision
be changed at any time - a "Manual start only" choice is not a dead end.

Also fixes a duplicate-registration bug in registerElementActionProvider():
running an already-registered script again in the same view no longer
creates a second action button.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 08:58:14 +02:00
zsviczianandClaude Sonnet 5 dbb9a7dc0b Add ExcalidrawAutomate.registerAutostart() script autostart permission flow
Lets a script ask to be automatically re-run every time a new Excalidraw
view opens. First call prompts the user Allow/Deny/Ask-me-later via the
existing MultiOptionConfirmationPrompt; the decision persists in the new
autostartScripts setting, a sibling of scriptEngineSettings since it is
plugin/user-trusted permission state a script must not silently flip.

Two additions from user testing: a fresh "allow" also immediately re-runs
the script in every other currently-open view (ScriptEngine.
attachAutostartScriptToOpenViews()), not only views opened afterward; and
renaming/deleting a script's file now purges its autostartScripts entry
(ScriptEngine.purgeAutostartPermission(), wired into the existing
delete/rename event handlers) instead of leaving a stale orphaned
permission under the old name.

No autostart-on-view-open execution or settings UI yet - that's next.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 06:33:17 +02:00
zsviczianandClaude Sonnet 5 9390dec8e2 Add ExcalidrawAutomate.registerElementActionProvider() scripting API
Lets scripts register custom buttons in the selected-element context menu
(view.selectedElementActionsMenu), previously only used internally for the
built-in markdown-image edit/convert actions. Delegates to the existing
registerProvider() mechanism, so per-view cleanup on view close was
already free; adds ScriptEngine.trackElementActionProvider() + cleanup in
unloadScript() for the one real gap: a script's file being deleted while a
view using its registered action is still open.

Fixes a bug found during testing: registerProvider() primes the menu to
recompute actions on its next update() call, but nothing triggered
update() immediately, so a button didn't appear until the user deselected
and reselected an already-selected eligible element. Fixed by calling
update() immediately after registering, mirroring the same call
ExcalidrawRoot.ts already makes at view-open time.

Moves SelectedElementMenuAction/SelectedElementMenuProvider from the
view-owned SelectedElementActionsMenu.ts to a new src/types/
elementActionTypes.ts, since they're now referenced from the public
ExcalidrawAutomate.ts API surface too.

Completes the ExcalidrawAutomate Change Checklist: SuggesterInfo.ts entry
and a Messages.ts release note under 2.27.0. No locale changes needed --
this API produces no plugin-authored user-visible strings.

User-tested: multiple independently-registered/cleared menus, and the
immediate-visibility fix, both confirmed working.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 05:57:17 +02:00
zsviczianandClaude Sonnet 5 a8e2b0984a Correct stale RefactorPlan.md note now that the ExcalidrawData.ts fix is committed
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 23:07:03 +02:00
zsviczianandClaude Sonnet 5 c78cfcc1e5 Fix ExcalidrawData.ts no-unsafe-* findings at their root cause
8 `let parts;`/`let res;` declarations (getDecompressedScene, getJSON, the
text-element/element-link parsing loop, and both quickParse/hasTransclusion
link-parsing loops) had no initializer and no type annotation, so
TypeScript inferred implicit `any`, cascading into every downstream
.value/.length/.index access. The correct type, RegExpMatchIteratorResult,
already existed in this file and was already used correctly by half a
dozen other methods, and was already implied by the exact functions these
variables got passed into. Pure type-annotation change, nothing else
touched — reduces this file's no-unsafe-* findings from 108 to 64 (514 to
470 codebase-wide) with zero logic change.

Also updates RefactorPlan.md documenting this fix and why AIUtils.ts's
similar-looking cluster was investigated and deliberately not pursued: its
`any` traces to Obsidian's own RequestUrlResponse.json: any (a genuine
external API boundary across 5 AI providers, with one spot that mutates
the response object), not a local missing annotation, so it doesn't meet
the same low-risk bar. This effort is parked for now.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 23:06:37 +02:00
zsviczianandClaude Sonnet 5 7067336d0d Fully close out the slider control type for the declarative settings dispatch
Extends SliderControl with after/afterUpdate hooks (no before — no
existing slider needed one). Widens SliderSetting.onChange in
sliderUtils.ts from (value: number) => void to (value: number) => void |
Promise<void> since hooks can be async; createSliderWithText's internal
caller now awaits it. ESLint's no-misused-promises/no-floating-promises
caught both sides of this gap at lint time before it shipped.

Converted: long-press duration desktop/mobile, link opacity, rendering
concurrency, image cache retention days, PNG export scale, export padding,
and max image zoom-in (afterUpdate hook). 3 sliders deliberately left as
legacy code (grid opacity, laser decay time/length — nested
gridSettings/laserSettings fields, not a flat NumberSettingKey), documented
in RefactorPlan.md.

All four control types (toggle/text/dropdown/slider) are now fully
converted. RefactorPlan.md's section is updated with a summary of what
remains before this could feed Obsidian's real getSettingDefinitions():
render support, the visible/visibility-gate mechanism, and only then
wiring up the real API behind Path B.

Manually tested with a risk-based check list; user confirmed no issues
found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 22:08:20 +02:00
zsviczianandClaude Sonnet 5 e176d96c97 Fully close out the dropdown control type for the declarative settings dispatch
Extends DropdownControl with before/after/afterUpdate hooks (mirroring
toggle/text) and adds a NumberDropdownControl variant for dropdowns whose
options are numbers stored as DOM strings but bind to a numeric field
(parse: "int" | "float" controls the parseInt/parseFloat conversion back
into the setting). 117 settings are now on the new path.

Converted: dynamicStyling and previewImageType (plain dropdowns with a
before/after flag hook each), plus the four number-dropdowns: autosave
interval desktop/mobile, PDF export scale, and custom pen count.

4 dropdowns deliberately left as legacy code, documented in
RefactorPlan.md: LIBRARY_STORAGE_NAME (branching async migration logic
ending in a full this.display() re-render), the dynamic AI provider/model
dropdown, EMBED_TYPE_NAME (the dropdown the already-excluded SVG/PNG
export toggles mutate — dynamic options, self-correcting migration,
cross-control show/hide), and the dynamic per-script dropdown closure.

Manually tested with a risk-based check list prioritizing the new
NumberDropdownControl mechanism and type-tricky (literal-union/enum)
fields; user confirmed no issues found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 21:48:05 +02:00
zsviczianandClaude Sonnet 5 1df7a47832 Fully close out the text control type for the declarative settings dispatch
Extends TextControl with before/after/afterUpdate hooks (mirroring
ToggleControl), a vaultPath hook that wires the text input into the
existing addVaultPathSupport() (path suggester + existence warning), and a
capture hook exposing the raw TextComponent for callers that need to keep
manipulating it afterward (a sibling toggle disabling it,
configurePasswordTextInput()). 111 settings are now on the new path.

Converted: folder/file settings (drawing folder, library folder/file,
crop/annotate folders, template, script folder, CJK assets, LaTeX
preamble) via vaultPath; TODO/Done prefix fields and the Taskbone API key
via capture (both interact with toggles converted in the previous commit);
the three filename-affix fields combining sanitize + after (shared
sanitizeFilenameSegment helper); plus the remaining plain text settings.

7 text settings deliberately left as legacy code, documented in
RefactorPlan.md: 4 numeric-text-with-validation fields (different control
shape than sanitize's pure string transform), the AI section's
getter/setter-based number closure, STARTUP_SCRIPT_NAME (text + button
chained on one row with a cross-control dependency), and the two dynamic
per-script text closures.

Manually spot-checked; user confirmed no issues found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 21:24:26 +02:00
zsviczianandClaude Sonnet 5 4fcb50b53a Fully close out the toggle control type for the declarative settings dispatch
Converts the remaining side-effect and captured-Setting-reference toggles
using the new before/after/afterUpdate/negate hooks and buildSetting()'s
Setting return value. 89 settings are now on the new path; 7 toggles are
deliberately left as legacy code because they don't fit the control shape
(nested/migration-guarded fields, cross-control dropdown mutation, a
dynamic per-script toggle) — documented in RefactorPlan.md along with why
each was excluded.

Fixed 4 no-unnecessary-type-assertion ESLint findings from non-null
assertions on buildSetting()'s return value — this project doesn't have
strictNullChecks enabled, so they were genuine no-ops.

Manually smoke-tested; user confirmed no issues found.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 20:51:40 +02:00
zsviczianandClaude Sonnet 5 7b25cfca86 Convert all plain toggle settings to the declarative buildSetting() dispatch
Mechanically converts 51 additional plain (assign + applySettingsUpdate
only) addToggle blocks to buildSetting() calls, using a script that
locates each block by precise bracket-matching rather than manual editing,
to guarantee the same name/desc/key/reload semantics are preserved
byte-for-byte. 66 settings are now on the new path.

Deliberately excludes: toggles whose Setting object is captured into a
variable for later use elsewhere (e.g. readingModeEl.nameEl.setAttribute(),
embedComment's later show/hide) since buildSetting() doesn't return the
Setting reference yet, and the ~22 toggles with a genuine side effect
beyond persistence (show/hide wrappers, requestReloadDrawings, view
refreshes, dropdown-option mutation) since ToggleControl has no side-effect
hook yet. Both are left as imperative code for a later step.

Also widens SettingDefinition.name (and the pre-existing SliderSetting.name
in sliderUtils.ts) from string to string | DocumentFragment: Obsidian's
Setting.setName() accepts both, and several existing settings pass
fragWithHTML(...) as the name, not just the description.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 19:51:24 +02:00
zsviczianandClaude Sonnet 5 b1dd56ddfe Add declarative-shaped SettingDefinition dispatch, pilot all four control types
Adds an internal SettingDefinition/buildSetting() interpreter modeled after
Obsidian's declarative settings API (getSettingDefinitions(), requires
1.13+, not called directly yet) so the current imperative display() can
gradually move toward that shape without depending on Obsidian's real
1.13 types or bumping minAppVersion.

Implements and pilots all four control types against a small, individually
verified set of existing settings, smallest-risk slice first:
- toggle: showReleaseNotes, compareManifestToPluginVersion,
  showNewVersionNotification
- text: latexBoilerplate, experimentalFileTag (plain), cropPrefix/
  cropSuffix/annotatePrefix/annotateSuffix (sanitize hook, shared
  sanitizeFilenameSegment helper)
- dropdown: defaultMode (exact string), defaultPenMode (string-literal
  union, needs the setStringSetting correlated-generic write helper since
  TypeScript can't verify a plain indexed write is sound across a union of
  differently-typed keys)
- slider: zoomToFitMaxLevel (1:1), zoomStep/zoomMin/zoomMax (scale hook,
  stored as a 0-1 fraction displayed as a 1-100 percent slider), reusing
  the existing createSliderWithText helper unchanged

Key/value correlation is compiler-enforced via BooleanSettingKey/
StringSettingKey/StringLikeSettingKey/NumberSettingKey mapped types, so a
control can only bind to a setting of the matching type.

render support and the visible/visibility-gate mechanism (for the existing
show/hide-driven conditional settings) are deliberately deferred to later
steps.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 19:35:09 +02:00
zsviczianandClaude Sonnet 5 3c49aba91c Split ExcalidrawSettingTab.display() into 14 per-section methods
display() was a single ~3,640-line method building the entire settings UI,
already visually organized into named sections via comment dividers and
<hr> elements but with none of that structure at the code level. Extracts
each section into its own private renderXSection() method, called in the
original order from a now ~15-line display(). Pure code motion, verified
byte-identical via a reconstruction diff against the original method body
before splicing.

Two sections turned out to nest sub-panels sharing a single DOM container
(Display + Pen/Grid/Laser Pointer) and were kept as one method rather than
split further. One genuine cross-section dependency surfaced during the
build: a filename-sample preview element and its refresh function, defined
in the Saving section but also refreshed by the Compatibility section's
compatibilityMode toggle. Promoted both to a private field
(filenameSampleEl) and method (getFilenameSample()) on the class.

Makes the settings tab navigable at the code level and creates the natural
per-section unit for eventually converting individual settings to
Obsidian's declarative getSettingDefinitions() API.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 15:55:22 +02:00
zsviczianandClaude Sonnet 5 d2fe360c71 Extract settings data model into settingsDefaults.ts
Moves ExcalidrawSettings, DEFAULT_SETTINGS, and the AI provider/model
config constants out of settings.ts into a dedicated settingsDefaults.ts,
decoupling the data model from the ExcalidrawSettingTab UI class. Consumers
that only needed the settings shape (PluginSettingsManager and 6 other
files) now import from the new location directly instead of pulling in the
whole settings-tab UI class and its dialog/component imports; 5 of them are
converted to import type since they only ever used it as a type.

Prep work toward eventually supporting Obsidian's declarative settings API
without bumping minAppVersion past 1.8.7 yet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 15:50:21 +02:00
zsviczianandClaude Sonnet 5 d55826a5ac Park the ExcalidrawView/main.ts RefactorPlan and record circular-dependency learnings
Closes the ViewSceneFileManager validation checkpoint (user-confirmed, no
issues found) and documents the madge-vs-Rollup circular-dependency
investigation, including why the import-type cleanup didn't move the
reported cycle count. Focus is shifting to src/core/settings.ts and
declarative-settings readiness; the plan is left in a resumable state with
an explicit "next steps if resumed" sequence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 14:52:40 +02:00
zsviczianandClaude Sonnet 5 f39db658db Use import type for ExcalidrawView/ExcalidrawPlugin where only used as a type
These 19 files imported ExcalidrawView or ExcalidrawPlugin as values solely
to type a constructor parameter or field; none accessed them at runtime.
Switching to import type removes unnecessary runtime coupling and matches
the convention already used elsewhere (FontManager, MonkeyPatchManager,
StencilLibraryManager, FieldSuggester, and this session's manager
extractions).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 14:42:23 +02:00
zsviczian ca6ddb6de8 Merge pull request #2884 from dimateos/patch-1
stencil library formatted with 2 spaces
2026-08-13 14:19:41 +02:00
zsviczian 077bbca649 Localize the 10 hardcoded strings flagged by sentence-case lint
ObserverManager.ts, InsertPDFModal.ts, PublishOutOfDateFiles.ts,
ImageCache.ts, Taskbone.ts, and carveout.ts had zero existing t() calls
-- these were hardcoded English strings in Notices, a modal title/
description, and button labels, a real gap against the project's own
"no hardcoded strings" policy, not just a lint nit. Moved all 10 to
en.ts and added translations to es/ru/zh-cn/zh-tw (mine, not verified
by a native speaker -- worth a review pass before release; t() falls
back to English for any locale missing a key, so this is strictly no
worse than the previous always-English behavior).

Also fixes two pre-existing typos while relocating the strings, no
logic change: "rescaning" -> "rescanning" (Taskbone.ts), "NewExcalidraw"
-> "New Excalidraw" (carveout.ts).
2026-08-13 10:28:48 +02:00
zsviczian b04d56091a Fix all 25 no-undef findings without suppressing the rule
Each is TypeScript resolving an ambient global that plain-JS no-undef
scope analysis can't see, not a real bug (verified: tsc/rollup-typescript
built clean on every one before this change too):

- Buffer/NodeJS/BufferEncoding (9x): genuine ambient Node types in
  Obsidian's Electron environment. Declared via globals.node plus two
  explicit entries for the TS-only type/namespace names globals.node
  doesn't cover.
- HTMLWebViewElement (3x, ExcalidrawView.ts): declared as a bare
  top-level `interface` in @types/react/global.d.ts (an ambient script,
  not a module) -- a real global type, same category as HTMLDivElement.
  Declared in ESLint's globals with a comment citing the source.
- React (4x, ExcalidrawAutomate.ts + modifierkeyHelper.ts): NOT a
  global -- @types/react uses `export as namespace React`, only
  available once "react" is imported somewhere in the program. Added
  explicit `import type React from "react"` to both files instead of
  declaring it global, since that's factually correct and makes each
  file's own dependency explicit rather than relying on incidental
  cross-file ambient leakage.
- 8 Obsidian type names in types.d.ts (PluginManifest, Hotkey,
  TAbstractFile, MenuItem, Component, EventRef, WorkspaceContainer):
  also not globals -- named exports of the "obsidian" module referenced
  from inside a `declare module "obsidian" { ... }` augmentation block.
  Extended the file's existing `import {...} from "obsidian"`.
2026-08-13 10:28:35 +02:00
zsviczian a397b4a776 svgToExcalidraw: remove dead second SVG-path implementation
Deletes elements/index.ts, elements/path/ (index.ts, utils/bezier.ts,
utils/ellipse.ts, utils/path-to-points.ts), and elements/utils.ts --
an entire second SVG-path-to-points implementation that nothing
reachable from the actual entry point (parser.ts -> walker.ts)
imports; walker.ts uses the external points-on-path package instead.
Verified via repo-wide search that elements/index.ts (the only entry
into this chain) has zero importers.

Also deletes types.ts, whose only remaining exports (RawElement,
ElementBoundaries, PathCommand) were used exclusively by the removed
files, and removes utils.ts's safeNumber, whose only caller was the
removed bezier.ts.
2026-08-12 22:51:36 +02:00
zsviczian bc7b8cee44 svgToExcalidraw: align line/draw elements to real ExcalidrawLineElement
ExcalidrawLine is now Mutable<ExcalidrawLineElement>; ExcalidrawDraw is
removed (it was a byte-for-byte structural duplicate of ExcalidrawLine).
createExLine() takes points up front and converts them to branded
LocalPoint via a local reimplementation of the fork's pointFrom()
(which is just `[x, y] as Point` at runtime -- the plugin never imports
runtime Excalidraw code directly, so reproducing the one-liner avoids
bundling a second copy of fork code). startBinding/endBinding/
startArrowhead/endArrowhead default to null and polygon defaults to
true, since every SVG-converted line/path element is a closed,
fillable shape (the polygon feature didn't exist when this module was
written).

Because the local ExcalidrawGenericElement union is now composed
entirely of real fork types, ExcalidrawAutomate.importSVG() no longer
needs the `res.content as unknown as ExcalidrawElement[]` cast that
was hiding this gap -- it's a plain, compiler-verified assignment now.
2026-08-12 22:51:27 +02:00
zsviczian 40e2120041 svgToExcalidraw: remove dead vendored types, align rect/ellipse to real types
Deletes the empty src/svgToExcalidraw/ folder and the unused "from
Excalidraw codebase" block in types.ts (verified nothing imports any
of it). ExcalidrawElementBase/Rectangle/Ellipse are now derived from
the real @zsviczian/excalidraw element types (Mutable<...>) instead of
a hand-maintained local copy, so createExElement() now sets index/
frameId/boundElements/updated/link/locked using the same defaults as
the fork's own newElement() factory. Line/draw elements are left as a
local shape for now (real ExcalidrawLineElement needs branded
LocalPoint and binding/arrowhead fields -- noted as a separate step).
2026-08-12 22:29:51 +02:00
zsviczian 3a7b23779e Alias pen/stroke-options types to the fork's canonical definitions
src/types/penTypes.ts and ObsidianMenu.tsx's ResetCustomPenState now
alias @zsviczian/excalidraw's ObsidianPenStyle/ObsidianPenOptions/
ObsidianResetCustomPenState instead of maintaining independent copies,
and ExcalidrawViewAppState drops the unknown overrides that were
re-loosening those fields after the base AppState already typed them
precisely.
2026-08-12 22:06:03 +02:00
zsviczian f8f8a4e542 Bump @zsviczian/excalidraw to 0.18.122
Picks up the published customPens/currentStrokeOptions/resetCustomPen
type fix (previously any) and the ObsidianPenStyle/ObsidianPenOptions/
ObsidianResetCustomPenState types now exported from the fork's new
obsidianTypes.ts.
2026-08-12 22:05:58 +02:00
zsviczian fcee1f64ae ViewSceneFileManager carve out 2026-08-12 20:50:06 +02:00
zsviczian bed3b1f26c ImplementedMarkdownImageController 2026-08-12 19:55:13 +02:00
Diego Mateos e6b4b77c98 stencil library formatted with 2 spaces 2026-08-12 13:05:15 +02:00
zsviczian 86e1e67b8d Replace deprecated React.MutableRefObject with RefObject
React 19's types unified MutableRefObject into RefObject (current is
writable on both); MutableRefObject now only exists as a deprecated
alias. Type-only rename across all 9 flagged usages, no behavior change.
2026-08-11 23:06:56 +02:00
zsviczian d736e7018e Extract Excalidraw React root into its own module (RefactorPlan Phase 7)
Moves the excalidrawRootElement() render body verbatim into
src/view/components/ExcalidrawRoot.ts as createExcalidrawRootElement(view,
initdata), a mechanical relocation with no rendering-syntax or behavior
change. Widens the ~30 previously-private ExcalidrawView members the render
tree touches to public, matching the existing pattern for packages/plugin/
excalidrawAPI.
2026-08-11 23:04:17 +02:00
zsviczian 6ef6fb8aa8 2.27.0-beta.1, 0.18.121, stencil library formatted json, color picker top picks, 2026-08-11 20:34:19 +02:00
zsviczian 8fb91655c7 updated AGENTS.md and CONTRIBUTING.md based on Refactor learnings 2026-08-10 11:47:41 +02:00
zsviczian 4b6d8e3a3c Merge pull request #2880 from zsviczian/fix-refactor-issues
2.27.0-beta.0
2026-08-10 08:21:51 +02:00
zsviczian 6362b7d162 2.27.0-beta.0 2026-08-10 08:18:05 +02:00
zsviczian 19a694260d Merge pull request #2878 from zsviczian/fix-refactor-issues
0.18.120, moved to React 19, fixed mermaid text to diagram history po…
2026-08-09 22:26:11 +02:00
zsviczian dbbc7b3f48 0.18.120, moved to React 19, fixed mermaid text to diagram history popout menu 2026-08-09 22:25:25 +02:00
zsviczian 5108dd3397 Merge pull request #2877 from zsviczian/migrate-to-esm-build
Migrate to esm build
2026-08-09 21:23:24 +02:00
zsviczian 133ff8219b 0.18.119 2026-08-09 21:17:22 +02:00
zsviczian 164a37fd88 build: consume Excalidraw ESM runtime 2026-08-09 21:05:16 +02:00
zsviczian 88e7b47c43 Merge pull request #2876 from zsviczian/reduce-size
Refactoring: main.js size reduction
2026-08-09 17:30:15 +02:00
zsviczian 1616a72344 perf: replace opentype.js font metric parsing 2026-08-09 17:27:30 +02:00
zsviczian 47b853b3b3 build: compress per-window React runtime 2026-08-09 15:49:39 +02:00
zsviczian 2da017b5d3 refactor: use Obsidian YAML APIs 2026-08-09 15:43:37 +02:00
zsviczian 39964d4d70 build: use inflate-only pako runtime 2026-08-09 15:27:34 +02:00
zsviczian 04869e821f Merge pull request #2875 from zsviczian/refactor-excalidrawView-1
Refactor: ExcalidrawView
2026-08-09 14:54:40 +02:00
zsviczian b35fea7eb7 refactor: extract Excalidraw extension renderer 2026-08-09 14:15:27 +02:00
zsviczian 3ceed630b7 refactor: remove obsolete drawio integration 2026-08-09 13:21:42 +02:00
zsviczian ee223fa239 refactor: extract view link navigation manager 2026-08-09 12:50:38 +02:00
zsviczian f1e089930b refactor: extract view fullscreen manager 2026-08-09 12:17:21 +02:00
zsviczian da9dd0fa0b removed commented out old code and debug lines 2026-08-09 11:54:31 +02:00
zsviczian 04f38a6455 refactor: extract view export manager 2026-08-09 11:24:56 +02:00
zsviczian 6976d0969c Merge pull request #2874 from zsviczian/refactor-excalidarw-batch-2
Refactor: move supporting logic out of main.ts into dedicated managers
2026-08-09 10:58:14 +02:00
zsviczian b196ac3de6 refactor: remove dead plugin lifecycle code 2026-08-09 10:56:34 +02:00
zsviczian 776b32216d refactor: extract startup timer 2026-08-09 10:46:18 +02:00
zsviczian 5843e88e6f refactor: extract font manager 2026-08-09 10:29:01 +02:00
zsviczian e0c4eecef4 refactor: extract footer safe area manager 2026-08-09 10:16:39 +02:00
zsviczian fd9090562e updated nanoid to patched version 2026-08-09 09:55:29 +02:00
zsviczian 1a78992ef1 refactor: extract settings management 2026-08-09 09:55:01 +02:00
zsviczian 703355f036 Merge pull request #2873 from zsviczian/refactor-excalidraw
Refactoring: Remove duplicate functions
2026-08-09 08:20:03 +02:00
zsviczian 371fa7a254 removing duplicate functions 2026-08-08 22:09:23 +02:00
zsviczian 00a1bed763 de-duplicated getFontDataURL, svgToBase64, and cropCanvas 2026-08-08 21:45:19 +02:00
zsviczian ff2c8536ce PR #2872 2026-08-08 20:24:05 +02:00
zsviczian eee975c44d refactor: consolidate text link and binary helpers 2026-08-08 20:04:06 +02:00
zsviczian 150f5ccbea Merge pull request #2872 from verryp/fix/text-elements-null-crash
fix: guard null match when .excalidraw.md has no Text Elements heading
2026-08-08 19:37:34 +02:00
verryantopaulus 4f5d913004 fix: simplify null fallback per review suggestion
Per @zsviczian's suggestion on #2872 — collapse the two-step
normalMatch/fallbackMatch into a single optional-chained expression.
Same behavior, less code.
2026-08-09 00:36:02 +07:00
verryantopaulus 64be1aee1e fix: fall through instead of early-return when Text Elements heading missing
Per @zsviczian's review on #2872: an early return skips parsing
"## Element Links" and "## Embedded Files", which may still be present
even when "## Text Elements" itself is missing or was deleted (e.g. a
file with embeddable elements whose link/file sections survived but
the Text Elements heading did not).

Instead of returning early, treat the missing heading as matching zero
characters and fall through to the existing parsing below — the same
codepath that already runs for a file with an empty "## Text Elements"
section. Element Links, Embedded Files, and any block-ref text are
still parsed normally; only the (non-existent) text-element block-refs
are skipped, which is correct since there's nothing there to parse.
2026-08-09 00:19:44 +07:00
verryantopaulus acf7b8d642 fix: guard null match when .excalidraw.md has no Text Elements heading
A valid .excalidraw.md file (correct frontmatter, "# Excalidraw Data"
header, valid "## Drawing" JSON) with no "## Text Elements" heading
anywhere in the body crashed with:

  Cannot read properties of null (reading '0')

loadData() finds "# Excalidraw Data" via RE_EXCALIDRAWDATA_NOSECTION_OK,
so `position` is not -1 and execution moves past the earlier
`position === -1` guard. It then searches for a "## Text Elements"
heading specifically; when that heading doesn't exist at all, both
`normalMatch` and the fallback `data.match(...)` return null, and the
unguarded `data.match(...)[0]` on the null fallback throws.

The plugin's own writer (generateMDBase) always emits the heading
unconditionally, so files it creates itself never hit this path — it
only surfaces for hand-authored or externally-generated .excalidraw.md
files that reasonably omit an empty section.

Treats "no Text Elements heading found" as "zero text elements" and
returns gracefully, mirroring the existing guard a few lines above for
the same underlying condition, instead of throwing.

Fixes #2871
2026-08-09 00:08:02 +07:00
zsviczian 95d89f2fed refactor: consolidate duplicate utility helpers 2026-08-08 11:17:32 +02:00
zsviczian c86db2152e refactor: retire legacy AI settings compatibility 2026-08-08 11:03:45 +02:00
zsviczian 7caf768b8f 2.26.4 2026-08-05 21:51:46 +02:00
zsviczian b295723780 fixed markdown image presistance 2026-08-05 21:35:16 +02:00
zsviczian 40e747c3bd 2.26.3 2026-08-04 19:02:32 +02:00
zsviczian dd06b07a12 updated to 0.18.117 2026-08-04 18:11:06 +02:00
zsviczian b4df1d8e5b Detect Markdown-image deletion via onIncrement instead of guessing trigger
Deleting the last local Markdown image via the Excalidraw properties
panel's trash button skipped the keep-or-delete-file prompt, because
detection only watched specific triggers: the Backspace/Delete/Cut keys
and a data-testid selector that only matches the context-menu delete
item, not the panel button (which the fork never gives a testid).

Replace that trigger-guessing with Excalidraw's onIncrement API: durable
store increments expose exactly which elements were soft-deleted
(isDeleted flipped true) in that action, regardless of what triggered
it. This uniformly covers keyboard, Cut, context menu, the panel
button, undo/redo, and scripts, and removes the old capture/timer/
candidate-matching scaffolding entirely.
2026-08-04 15:43:05 +02:00
zsviczian 614f0fbab0 Fix Markdown image edits lost when switching between images
Editing one Markdown image and immediately selecting or opening another
could drop the first image's edits, both in memory and on disk. Two
distinct races caused this: switchElement()'s force-persist could
silently no-op if a concurrent save claimed the saving semaphore between
the idle-wait and the save() call, and openMarkdownImageEditor()'s
handoff to a brand new controller disposed the previous one via a
fire-and-forget flush instead of awaiting it. Both paths now share a
single flushCurrentElement() helper and persistOwnerAfterEditorFlush()
retries instead of silently giving up.
2026-08-04 14:13:50 +02:00
230 changed files with 157882 additions and 22451 deletions

No files matched your search

+3 -1
View File
@@ -25,4 +25,6 @@ yarn.lock
.lock
# Obsidian files
Obsidian
Obsidian
repository.zip
+156 -52
View File
@@ -37,24 +37,16 @@ Use https://github.com/obsidian-typings/obsidian-typings as a reference when dea
Treat build code and runtime code as one system.
## Project overview
## Project Overview And Tooling
- Target: Obsidian Community Plugin (TypeScript → bundled JavaScript).
- Entry point: `src/main.ts` compiled to `main.js` and loaded by Obsidian.
- Required release artifacts: `main.js`, `manifest.json`, and optional `styles.css`.
## Environment & tooling
- Node.js: use current LTS (Node 22+).
- **Package manager: npm** (required for this sample - `package.json` defines npm scripts and dependencies).
- **Bundler: esbuild** (required for this sample - `esbuild.config.mjs` and build scripts depend on it). Alternative bundlers like Rollup or webpack are acceptable for other projects if they bundle all external dependencies into `main.js`.
- Types: `obsidian` type definitions.
## Linting
- ESLint is preconfigured with `eslint-plugin-obsidianmd` for Obsidian-specific rules.
- Run `npm run lint` to lint the project.
- A GitHub Action automatically lints every commit on all branches.
- Runtime entry point: `src/core/main.ts`, compiled by `rollup.config.mjs` to `dist/main.js`.
- Required release artifacts: `main.js`, `manifest.json`, and `styles.css`.
- Node.js: use Node 22 or newer. Check `node --version` before diagnosing build-tool failures; mixed Node/Corepack installations can produce misleading errors.
- Package manager: npm. Use `npm install` and the scripts in this repository's `package.json`.
- Runtime bundler: Rollup. Do not replace this build with a sample-plugin esbuild setup; Rollup also assembles compressed runtime payloads and merged CSS.
- Primary lint command: `npm run code`. `npm run lint` is broader and may expose unrelated repository backlog.
- Types: Obsidian type definitions plus conservative declarations for intentionally used unpublished APIs.
## Security, privacy, and compliance
@@ -80,11 +72,20 @@ 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.
- Use the existing visibility helpers instead of the native `hidden` property or attribute, which is not reliable in Obsidian's styled UI. Choose `hideElement`/`showElement` or `setComponentVisibility` from `src/utils/styleUtils.ts`, or `setElementHidden`/`setElementDisplay` from `src/utils/htmlUtils.ts` when a boolean/display-oriented API is clearer.
- Search `src/utils/styleUtils.ts` and `src/utils/htmlUtils.ts` before introducing new DOM styling helpers or display classes.
- Run Obsidian CodeScanner after CSS changes. Preserve compatibility with the declared minimum Obsidian version and prefer a widely supported property when it provides the same result; for example, a basic underline is preferable to optional underline-thickness/offset styling.
- For a known vault path, use the most specific synchronous lookup: `app.vault.getFolderByPath()` for folders and `app.vault.getFileByPath()` for files. Use `getAbstractFileByPath()` only when either type is intentionally accepted, and avoid adapter-level existence checks when the Vault API already models the target.
- Radix content in the customized Excalidraw package may be rendered through `ObsidianRadixPortal` directly under the owning document's body. A body portal escapes component ancestor selectors and modal stacking contexts. When a trigger is visible but its menu or popover is not, first inspect whether the content mounted behind a modal or lost ancestor-scoped styles. Use a class on the portaled content, a portal-safe selector, and an explicit stacking level when required; validate main-window, popout, click-outside, and Escape behavior.
## Performance
@@ -92,6 +93,16 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- Avoid long-running tasks during `onload`; use lazy initialization.
- Batch disk access and avoid excessive vault scans.
- Debounce/throttle expensive operations in response to file system events.
- For temporary performance diagnostics, use a unique searchable prefix and
emit one copyable string per event rather than logging expandable objects.
Keep timing-only callbacks and state isolated from production behavior.
- Distinguish synchronous API duration, queue completion, browser-task yields,
animation-frame callbacks, and actual paint; none is a substitute for the
others when explaining perceived latency.
- Temporary diagnostics are not product observability. Do not log vault
contents, and include filenames only when the maintainer explicitly needs
per-file attribution. Remove the diagnostics before commit and search both
`src/` and the built `dist/main.js` for their prefix.
## Coding conventions
@@ -108,6 +119,7 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- Don't assume desktop-only behavior unless `isDesktopOnly` is `true`.
- Avoid using desktop only objects and functions such as Node Buffer, SharedArrayBuffer, etc. For the special case when this is required, make proper mobile safe guards.
- Avoid large in-memory structures; be mindful of memory and storage constraints.
- Treat a physical phone or tablet as a separate validation environment for touch targets, synthesized clicks, scrolling gestures, focus, and the mobile WebView. Desktop mobile emulation is useful for responsive layout checks but is not a substitute for real touch testing.
## Agent do/don't
@@ -191,20 +203,98 @@ This project uses a non-trivial Rollup build because startup time, popout-window
The build embeds or injects runtime code for:
- React and ReactDOM
- a JSX runtime shim for compatibility
- the customized `@zsviczian/excalidraw` package
- 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`
- selected compressed locale payloads
These payloads are executed or unpacked at runtime. This is intentional.
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
The customized component lives in the sibling `zsviczian/excalidraw` repository. When both repositories are available locally, it is normally at `../excalidraw`; verify the actual workspace path and branch instead of assuming it.
- The Excalidraw repository uses Yarn and builds the consumer-specific payload from `packages/excalidraw` with `yarn build:obsidian`.
- That build emits four files under `packages/excalidraw/dist/obsidian/`: production and development JavaScript plus production and development CSS.
- This plugin consumes the same four paths from `node_modules/@zsviczian/excalidraw/dist/obsidian/` in `rollup.config.mjs`.
- For a temporary unpublished integration test, build the sibling package and copy only those four generated files into the installed package under `node_modules`. Do not change `package.json` or `package-lock.json` to a local `file:` dependency merely for this handoff. A later `npm install` restores the published package.
- For the durable handoff, publish a new `@zsviczian/excalidraw` version, update this repository's dependency, run `npm install`, and rebuild the plugin.
- A local artifact copy proves integration only. If plugin source consumes a
new fork API, do not describe the plugin handoff as commit- or release-ready
until the published package is installed and the exact dependency and
lockfile contain that API, unless the maintainer explicitly requests a
paired intermediate commit.
- Never hand-edit or commit generated `dist/`, `lib/`, or `node_modules` artifacts as source fixes.
- Treat the repositories as separate Git histories. Check branch, status, diff, build, and commit state independently in each one, and do not commit or publish unless explicitly requested.
### Typed Excalidraw Host Boundary
The customized Excalidraw runtime receives Obsidian capabilities through typed host adapters. Treat this as the only supported plugin-to-fork dependency-inversion boundary.
- Do not expose or recover the plugin through component props, `appState`, `window`, `globalThis`, `app.plugins`, or fork-side `hostPlugin` variables.
- Keep adapters narrow and semantic. They may expose operations such as reading a current limit or running a named action, but never the plugin instance, the complete settings object, or an active view.
- Capabilities used by `@excalidraw/common` or lower layers belong in `ObsidianCommonHostAdapter`. Capabilities used only by the Excalidraw package belong in `ObsidianExcalidrawHostAdapter`.
- View-specific state must remain instance-scoped. Do not put an active view into either window-runtime adapter; expose a semantic plugin-side action when the component genuinely requires such behavior.
- `PackageManager` registers both adapters once with the shared Excalidraw runtime. React components and individual `ExcalidrawView` instances must not configure or dispose them.
- Adapter methods must read live plugin state instead of capturing settings snapshots during registration.
- `PackageManager` owns the complete lifetime: dispose registrations before releasing the shared runtime, make cleanup idempotent, and roll back all registrations if configuring either adapter fails.
A closure that references the plugin is not itself a memory leak. The risk is allowing a registry, listener, or evaluated runtime retaining that closure to outlive its owning `PackageManager` registration.
The fork is the source of truth for host-adapter contracts and protocol constants. Import or derive types from its published declarations where possible. If the evaluated `window.ExcalidrawLib` surface requires an ambient declaration, derive that declaration from the fork types instead of restating property lists or unions locally.
### Coordinated Internal Protocol And Release
The host adapters are an internal protocol between this plugin and its exact `@zsviczian/excalidraw` dependency. They are not a compatibility surface between arbitrary historical plugin and fork versions.
- A breaking adapter change must increment the relevant protocol version and update the fork implementation, fork tests, plugin adapter, and plugin ambient runtime declaration in one coordinated checkpoint.
- Fail fast during package loading when a required boundary is absent or incompatible. Do not retain global-plugin discovery or legacy bridge fallbacks solely to support mismatched plugin and fork versions.
- Preserve the general backwards-compatibility requirements for persisted settings, serialized scenes, scripts, commands, and public APIs; this exception applies only to the paired internal host protocol.
- For a maintainer-coordinated release, build and verify the fork package first, publish it, update the plugin's exact dependency, run `npm install`, and rebuild and smoke-test against the published artifact before committing the plugin handoff.
### Popout Window Support
- `src/core/managers/PackageManager.ts` manages window-scoped React/ReactDOM/Excalidraw packages.
- This is necessary because the plugin must work in Obsidian/Electron popout windows.
- Do not replace this with a naive global singleton approach.
- The bundle bootstrap inflates and indirectly evaluates one compressed private React/ReactDOM payload in the main application realm before module-level React consumers run. `src/core/managers/PackageManager.ts` then evaluates one Excalidraw artifact and leases the combined shared package to every view.
- A lease retains the view's actual acquisition window for migration and persistence decisions; package evaluation ownership must never substitute for that identity.
- Popouts receive only a temporary `window.ExcalidrawLib` compatibility alias. Remove it after the final lease for that window while keeping the shared runtime alive until plugin unload.
- The React runtime is built from official npm entry points, inflated once during bundle bootstrap, and kept in plugin/package lexical scope. Do not assign React or ReactDOM to `window`; only the documented `window.ExcalidrawLib` compatibility surface remains global.
- Every Excalidraw root must receive its stable owning document. Rendering, DOM ownership, events, observers, portals, realm constructors, fonts, timers, and React roots must derive from the owning view document/window where appropriate; do not turn the shared runtime into a mutable "current window" singleton.
- Treat `HTMLElement.onWindowMigrated()` as a destructive runtime boundary. Its callback runs after Obsidian has moved the view container to another document, while the existing React root and Excalidraw API still belong to the source window runtime.
- For a dirty migration, synchronously capture every API-owned value needed for persistence and unmount the source React root **before the first `await`**. Do not move synchronization, compression, Vault/native file access, `closeLeafView()`, or another asynchronous step ahead of that unmount. On macOS/Electron, doing so reproducibly allowed the source popout window to be destroyed before `root.unmount()`, freezing Obsidian and disconnecting DevTools.
- Cancel deferred initialization and scene-file loaders before migration unmount, and require delayed loader callbacks to match the exact API instance and file path that started them. Component-owned image decoding can still outlive a synchronous `addFiles()` call, so the Excalidraw runtime must also stop after an awaited decode when its editor has unmounted; never delay migration unmount to wait for image work.
- The migration callback owns the single persistence flush. Generic `onClose()` and `onUnloadFile()` safeguards must not start duplicate migration saves, and the retired source view must reject blur-save side effects and vault-modify synchronization after its API is unmounted.
- A popout-to-main migration may serialize from a synchronously captured drawing snapshot, but the replacement main-window view must perform the final drawing-file write. Never initiate the final Vault/native write from the source popout callback.
### Main-Window Persistent Storage
Window ownership for rendering is not the same as ownership for persistent plugin data.
- Existing plugin-level IndexedDB and local-storage data belongs to Obsidian's main application window and must remain shared across normal views and popouts.
- Do not change persistent storage to `view.ownerWindow`, create one database per popout, or infer a storage migration from a rendering bug unless the task explicitly requires that behavior.
- Diagnose persistence and presentation separately. For example, a visible history button conditioned on loaded records proves the load path worked even when a portaled history menu is hidden.
- If a new feature is intentionally view-local, document that exception and test window migration and popout teardown explicitly.
### IndexedDB And Cache Schema Changes
- Classify every affected store as disposable derived cache or durable user
data before changing its schema. Image previews may be rebuilt; drawing
backups must not be deleted as cache migration cleanup.
- Create current stores and remove obsolete disposable stores in one IndexedDB
version-change transaction. Prefer lazy cache rebuilding over deserializing
and rewriting a large legacy cache during startup.
- If opening or upgrading fails, close and clear unusable database handles and
readiness promises. A closed legacy connection must never make the cache
report itself as ready.
- Use browser APIs such as `Blob` and `FileReader` for in-memory payload
conversion so the path remains mobile-safe. Vault file access must still use
Obsidian's Vault API.
- Validate cold upgrade, preservation of durable stores, first cold rebuild,
warm reopen, clear, timed purge, plugin reload, and one mobile run. Persistent
plugin data remains owned by the main application window; popouts need a
usage smoke test, not a separate database.
### MathJax Subproject
@@ -244,6 +334,16 @@ These payloads are executed or unpacked at runtime. This is intentional.
- Preserve existing abstractions unless the task clearly requires a redesign.
- Avoid broad refactors unless there is strong evidence they are necessary.
### Incremental Refactoring Protocol
- Use `RefactorPlan.md` as the living architectural record. Update the progress table and append an action-log entry after each completed or reverted checkpoint.
- Make one independently testable behavior change or mechanical extraction at a time. Prefer moving code intact before simplifying it.
- Preserve timers, observers, semaphores, lifecycle ordering, and unpublished-API workarounds unless their purpose has been traced and an equivalent behavior has been verified across affected platforms.
- Do not convert `ExcalidrawView` wholesale into React. It must remain an Obsidian `TextFileView`; React is the child rendering runtime. Extract cohesive view-scoped controllers and components while retaining compatibility delegates on the view.
- For duplicate utilities, compare every implementation and caller before consolidation. Marginal behavior differences must be shown unused or deliberately preserved.
- Do not derive a runtime settings sanitizer from the TypeScript interface. Interfaces do not exist at runtime, settings evolve frequently, and unknown keys may belong to a newer or companion version. Remove obsolete keys only through an explicit, reviewed migration or retirement decision.
- End every checkpoint with risk-based manual test recommendations: identify the highest-probability failure, the affected workflow, and whether main-window, popout, desktop operating systems, and mobile need separate coverage.
## Naming And Placement Conventions
Treat the following as the target convention for all new code and for any future naming-cleanup pass. The current repository contains legacy exceptions. Do not rename files opportunistically inside behavior changes; do naming cleanup in a dedicated, compatibility-aware refactor.
@@ -301,6 +401,7 @@ Backwards compatibility is a strong requirement in this repository.
- If a rename reaches beyond a purely internal import graph, prefer temporary aliases, re-exports, or compatibility wrappers during migration.
- If settings shape or stored values change, update defaults, settings UI, load/save flow, and migration logic together.
- Assume user scripts, vault content, templates, embeds, release-note references, and community documentation may depend on existing names and behavior.
- The paired plugin-to-fork host protocol is the deliberate exception described above: coordinate and version breaking contract changes instead of preserving fallbacks for mismatched package versions.
## User-Facing Change Workflow
@@ -315,10 +416,10 @@ Backwards compatibility is a strong requirement in this repository.
## React Runtime Import Model
React usage in this repository is special because React and ReactDOM are package-managed per window to support Obsidian popout windows and runtime package injection.
React usage in this repository is special because one compressed private React/ReactDOM runtime is package-managed across main-window and popout roots.
- It is fine to import React for types, component definitions, JSX compilation, and nearby established patterns.
- Do not assume a single global React/ReactDOM runtime is safe for rendering, root creation, or view-owned objects.
- It is fine to import React for types, component definitions, JSX compilation, and nearby established patterns. The plugin build resolves those imports through the inflated private runtime; the library build and separately built Excalidraw artifact keep React external.
- The shared runtime is safe only because each root and Excalidraw instance receives stable owner-document state. Never recover view ownership from the runtime's lexical main window.
- For view-bound rendering and roots, follow `src/view/ExcalidrawView.ts` and use `view.packages.react` and `view.packages.reactDOM` through the package-manager flow.
- For view-owned React objects such as refs or runtime-created elements, follow neighboring patterns such as `src/view/components/menu/ToolsPanel.tsx` and `src/view/components/CustomEmbeddable.tsx`, which intentionally use the package-managed React instance.
- Do not introduce a new direct `ReactDOM.createRoot()` path outside the package-manager model unless you have verified popout-window safety.
@@ -334,7 +435,7 @@ Use this routing guide before editing.
- Commands and command registration: `src/core/managers/CommandManager.ts`
- Vault or workspace event handling: `src/core/managers/EventManager.ts` and `src/core/managers/FileManager.ts`
- Markdown rendering or markdown embeds: `src/core/managers/MarkdownPostProcessor.ts`
- Package/runtime loading across windows: `src/core/managers/PackageManager.ts`
- Shared package/runtime loading and per-window leases: `src/core/managers/PackageManager.ts`
- Styling setup and style injection: `src/core/managers/StylesManager.ts`, `styles.css`, `src/utils/dynamicStyling.ts`
- Main canvas/editor behavior: `src/view/ExcalidrawView.ts`
- Sidepanel behavior: `src/view/sidepanel/`
@@ -357,6 +458,21 @@ If a task changes persisted settings, inspect all relevant pieces.
Settings changes are often incomplete if only one of these surfaces is updated.
## Declarative Settings And Persistence
The plugin supports Obsidian 1.8.7 while optionally using the declarative settings API introduced in Obsidian 1.13. Preserve both compatibility paths.
- Do not bump the `obsidian` dependency or `minAppVersion` merely to consume declarative settings. Gate the runtime path with `requireApiVersion("1.13.0")` and keep conservative placeholder declarations for the newer API.
- `getSettingDefinitions()` must return the complete tree only when the runtime supports declarative settings and the restart-applied compatibility preference enables them. Returning an empty array is the intentional fallback to the legacy renderer.
- The settings page model is the canonical hierarchy for declarative rendering, legacy single-page rendering, descriptions, search aliases, breadcrumbs, cross-page navigation, and Markdown export. Do not create separate setting lists or behavior implementations for the two layouts.
- Controls that change each other's options, visibility, or disabled state must share one integrated component or one shared configurator. Apply dependent state during initial render as well as after changes. Scope captured control references to one rendered definition tree; generating an export-only tree must never replace bindings used by the mounted UI.
- On Obsidian 1.13+, do not call `display()` to refresh a declarative page. Update the mounted controls through their binding/configurator path or ask Obsidian to rebuild definitions only when the definition tree itself changed.
- Declarative page navigation uses guarded unpublished Obsidian APIs. Prefer `openPagePath`; retain the checked `findTabById`/`navigateToPage` fallback, derive localized paths from the canonical page model, and degrade to non-navigating text when the API is unavailable.
- Route all settings writes through `PluginSettingsManager` and its serialized stable-snapshot writer. Save when values change; never make plugin shutdown or settings-tab closure the primary persistence boundary because Obsidian may not await asynchronous writes during termination. Avoid competing direct `saveData()` calls.
- Missing and invalid `data.json` states are different. A first installation with no file is valid; a missing file with a recovery snapshot requires a restore-or-defaults choice; invalid startup data should restore a valid device-local snapshot or ask the user how to proceed; invalid data arriving during a running session must be rejected and repaired from the valid in-memory settings.
- The last-known-good recovery snapshot is durable, device-local IndexedDB data owned by the main application window. Refresh it after every valid load or save, do not store large snapshots in `localStorage`, and do not create independent recovery databases for popouts.
- Preserve unknown persisted keys. Do not derive a sanitizer from the TypeScript settings interface or treat unfamiliar keys as corruption.
## Script Engine And Automation Notes
- Excalidraw Automate is a major public surface of this project.
@@ -380,7 +496,7 @@ These areas require extra care:
- `rollup.config.mjs`: payload injection, localization, manifest/versioning, CSS bundling
- `src/core/main.ts`: lifecycle order, settings migration, startup initialization
- `src/view/ExcalidrawView.ts`: very large, stateful, performance-sensitive, and central to user behavior
- `src/core/managers/PackageManager.ts`: cross-window package loading and runtime evaluation
- `src/core/managers/PackageManager.ts`: shared runtime evaluation, host registration, and cross-window lease/alias lifetime
- `src/lang/helpers.ts`: build-token compatibility for compressed locales
- AI/provider settings and persisted credentials handling
- PDF/export code paths and Electron/Obsidian-specific integrations
@@ -412,6 +528,7 @@ npm run doc
Validation guidance:
- After every code modification, run `npm run build` before starting the next checkpoint. Treat new build errors or warnings relative to the recorded baseline as blockers and report relevant existing warnings accurately.
- Treat `eslint.config.cjs` as the quality bar for all new and modified code.
- Use lint results to avoid introducing new violations in touched files, even if repo-wide lint still fails because of unrelated backlog.
- `npm run code` is useful for visibility, but a failing repo-wide run does not by itself mean your change is invalid if the failures are pre-existing and unrelated.
@@ -419,6 +536,12 @@ Validation guidance:
- Run `npm run lib` if you touch the public/library API surface.
- Run `npm run build:mathjax` or `npm run build:all` if you edit `MathjaxToSVG/`.
- Run `npm run madge` after structural import changes or when touching shared architecture.
- Compare Madge and Rollup circular-dependency results only with their own baselines. Madge enumerates overlapping elementary paths and can include type-only imports, while Rollup reports runtime bundle cycles; their raw counts are not directly comparable.
- When the customized Excalidraw source changes, run its `yarn build:obsidian`, refresh the four local package artifacts, and then run this repository's production and relevant development builds. A plugin build against the old installed artifact does not validate the component change.
- For host-boundary changes, run the fork's focused adapter tests without Obsidian, then validate plugin registration and teardown through cold startup, plugin reload, the main window, a new and restored popout, and window removal. Confirm adapter methods observe settings changed after registration.
- After React/package-loading changes, validate cold startup, plugin reload, the main window, new and restored popouts, and moving a leaf between windows. Confirm that no `window.React` or `window.ReactDOM` global was introduced.
- After Radix/portal changes, validate visibility, positioning, stacking, click-outside, and Escape handling in both the main window and a popout; include mobile when viewport collision behavior can differ.
- Record `dist/main.js` byte size after packaging changes and report remaining headroom under the release limit.
- Prefer targeted diagnostics for the files you touched when repo-wide lint noise obscures signal.
- Prefer `npm run build` plus targeted file diagnostics over raw `tsc --noEmit` as the primary gate. Standalone `tsc` can surface large volumes of dependency-typing noise unrelated to touched files.
- Do not treat `dist/` output edits as source fixes.
@@ -433,7 +556,7 @@ Validation guidance:
- Considering both direct and indirect consumers of the changed code or types
- Reviewing all files that may be impacted by a type, interface, or API change
- Never assume a change is local unless you have verified, by search or analysis, that no other code is affected.
- After making a change, always validate that the build passes and that no new errors or warnings are introduced anywhere in the codebase.
- After making a change, validate the relevant build and compare errors and warnings with the recorded baseline. Touched files must not introduce new diagnostics.
- Prefer minimal, local changes when possible, but never at the expense of breaking global correctness or introducing subtle bugs elsewhere.
- Avoid reformatting large files unless necessary.
- Do not edit generated `dist/` or `lib/` outputs by hand.
@@ -442,26 +565,6 @@ Validation guidance:
- When a change looks odd, search for the constraint that explains it before removing it.
- When in doubt, preserve startup performance, popout support, and existing vault compatibility.
### Additional Guidance for Global Impact
- When changing types, interfaces, or exported APIs, always search for all references and usages across the codebase and update them as needed.
- When tightening types (e.g., replacing `any`), ensure all code that accesses the affected values is type-safe and will continue to work as before.
- If a change introduces new type errors elsewhere, you must fix those errors or revert the change.
- Always run `npm run build` after changes, and do not consider a change complete until the build passes with no new errors.
- If a change could affect runtime behavior, validate by running the plugin in Obsidian if possible.
### MANDATORY: Build Validation After Every Change
**Build validation is not optional and must be run immediately after every code change.**
- After you complete any code modification, you **must** immediately run `npm run build` before proceeding to the next task.
- Do not consider a change complete, correct, or ready to return to the user until `npm run build` passes with no new errors or warnings.
- If the build fails, fix all errors in your code and run `npm run build` again.
- Report all build output (including warnings and circular dependency notices) to the user if relevant to your changes.
- Build validation is not a final polish step—it is part of the core work.
- Treat any new build errors as blockers that must be resolved before considering the task done.
- If a type change or code edit introduces new build failures anywhere in the codebase, those are your responsibility to fix.
### Type Consolidation Follow-through
- Treat user requests like "tiny follow-up" or "do this consolidation" as end-to-end tasks: complete extraction, replace all known duplicates, and remove local leftovers in the same pass.
@@ -550,13 +653,14 @@ Before replacing an `any` type:
### Type Files And Responsibilities
- **`src/types/types.d.ts`**: Ambient module declarations and Obsidian unpublished API types. This is the standard location for extending Obsidian's type system and for global type declarations. Use the existing patterns (interfaces extending `obsidian` module interfaces) consistently.
- **`src/types/excalidrawLib.ts`** (or similar): When creating new type files for project-specific types, place them in `src/types/` and use PascalCase for files that export types or interfaces.
- **`src/types/excalidrawLib.d.ts`**: Ambient declarations for the evaluated `window.ExcalidrawLib` runtime. Derive declarations from published fork types where possible, and keep the file lowerCamelCase in line with grouped type-module naming.
- **Type files in subsystem directories**: Files like `src/shared/ExcalidrawAutomate.ts` may carry substantial type definitions and exports alongside implementation. Do not move these without evaluating the impact on the public API surface.
- **Leverage existing type files**: Consult `src/types/excalidrawLib.ts` for the current Excalidraw type model before adding new Excalidraw-derived types.
- **Leverage existing type files**: Consult `src/types/excalidrawLib.d.ts` and the installed fork declarations for the current Excalidraw type model before adding new Excalidraw-derived types.
### Excalidraw Type Integration
- Do not invent wrapper types for Excalidraw entities. Reference the customized `@zsviczian/excalidraw` types directly.
- Before defining a plugin-local union or interface for a fork concept, search the published fork declarations and import or alias the canonical type. Ambient runtime bridges should reuse those types rather than duplicate their structure.
- Build on existing type extensions in the codebase (e.g., `src/types/types.d.ts` may already extend Excalidraw types).
- When a type depends on Excalidraw internals, document the dependency clearly so future changes to the fork are visible.
- Obsidian unpublished API types often interact with Excalidraw components; model these intersections carefully in `src/types/types.d.ts`.
@@ -611,7 +715,7 @@ In some cases, `@typescript-eslint/no-explicit-any` or `@typescript-eslint/no-un
- **Provider-specific dynamic payloads**: AI providers, image APIs, and other external services return schemas that vary by provider. Normalizing these requires accepting `any` properties or using type assertions on the `item` parameter to access provider-specific fields.
- Example: `(item: Record<string, any>) => item.image?.url || item.image?.b64_json` normalizes images from different providers into a common schema.
- **Mutation-path type casts**: When updating scene elements or bound references, Excalidraw type definitions may return readonly or union types, but the mutation path requires the mutable variant. The assertion is necessary and doesn't bypass a real type mismatch.
- Example: `sceneElements.find(...) as unknown as Mutable<ExcalidrawElement>` during ID migration where the lookup guarantees the mutable variant exists.
+110 -9
View File
@@ -1,6 +1,6 @@
# Contributing to Obsidian Excalidraw Plugin
First off, thank you for considering contributing to the Obsidian Excalidraw plugin! This project integrates a heavily customized Excalidraw fork into Obsidian.
First off, thank you for considering contributing to the Obsidian Excalidraw plugin! This project integrates a heavily customized Excalidraw fork into Obsidian.
Because this is not a generic React canvas app, but rather a deeply integrated Obsidian plugin with popout window support, mobile compatibility constraints, and performance optimizations, please read the following guidelines carefully before making any changes.
@@ -11,38 +11,92 @@ Before spending your valuable time writing code for a new feature or significant
## 🚀 Getting Started
1. Fork the repository and clone it locally.
2. Run `npm install` in the root directory to install the main dependencies.
2. Use Node.js 22 or newer and verify it with `node --version`. A shell that mixes a different Node binary with another installation's Corepack can fail before a build starts.
3. Run `npm install` in the root directory to install the main dependencies.
*(Note: The `MathjaxToSVG` sub-component has its own separate dependencies. You do not need to install them manually; the first time you run `npm run build`, it will take care of this automatically).*
3. To test your changes locally, we recommend symlinking your cloned repository folder into a test Obsidian vault's `.obsidian/plugins/obsidian-excalidraw-plugin` directory. (Using a community plugin like [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) will make local development much faster).
4. To test your changes locally, we recommend symlinking your cloned repository folder into a test Obsidian vault's `.obsidian/plugins/obsidian-excalidraw-plugin` directory. (Using a community plugin like [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) will make local development much faster).
## 🛠️ Build and Lint Commands
- **Build the project:** Run `npm run build`
*(Note: Our Rollup build is non-trivial as it merges CSS, handles MathjaxToSVG dependencies, and embeds runtime payloads. Run this command frequently to validate your changes).*
- **Build readable development payloads:** Run `npm run dev`
- **Build the public library API:** Run `npm run lib` when changing exports or ExcalidrawAutomate APIs
- **Run ESLint:** Run `npm run code`
- **Fix ESLint Warnings:** Run `node ./scripts/fix-eslint-warnings.mjs`
The shipped plugin is `dist/main.js`, `dist/styles.css`, and `dist/manifest.json`. Keep `main.js` below the release size limit and report its byte size after dependency or packaging changes.
## Updating the EA script template
`npm run doc` and `npm run skill` both build the public library declarations, then
run full documentation generation. When `../ea-script-template` exists, they also
refresh its local agent references, generated EA declaration graph and provenance,
type dependencies, and template update manifest. The template consumes declarations
only; personal script workspaces no longer need this plugin as a Git dependency.
After generation, run `npm install`, `npm run check`, `npm run build`, and
`npm run test:template` in the template. Review both repositories separately and
publish the template's updated `master` so users can receive the snapshot with
`npm run update-template`. See the template's `.template/README.md` for ownership,
conflict handling, and the one-time adoption procedure for older workspaces.
## 🧪 Testing
At this time, the project **has no automated tests**. As a contributor, you are responsible for testing your changes thoroughly.
At this time, the project **has no comprehensive automated test suite**. As a contributor, you are responsible for testing your changes thoroughly.
Because Obsidian runs across a variety of environments, please manually test your changes on as many of the following platforms as possible to avoid breaking the plugin for other users:
- Desktop: Mac, Windows, Linux
- Mobile: Android, iOS (Test on both Phones and Tablets)
Desktop mobile emulation is useful for checking responsive layout, but it does not reproduce every touch event, synthesized click, focus, scroll gesture, or mobile WebView behavior. If a change affects an interactive mobile control, validate it on at least one physical phone or tablet.
Use a risk-based test plan rather than a generic smoke test. Every change should identify the most likely regression and whether it needs separate coverage in:
- the main Obsidian window
- a newly opened and restored popout window
- plugin reload and cold application startup
- desktop and mobile layouts
- offline mode, when the change affects packaged assets or runtime loading
For UI and CSS changes:
- Use semantic controls and Obsidian's event helpers. Link-like navigation should use a real anchor; custom navigation handlers should use `onClickEvent`.
- Keep accessible names in `aria-label`. If a styled tooltip is already present, omit the HTML `title` attribute to avoid a second native browser tooltip.
- Run Obsidian CodeScanner and resolve compatibility warnings against the supported Obsidian baseline. Prefer simple, broadly supported CSS when advanced styling is only decorative.
Timers, observers, autosave coordination, and undocumented Obsidian API workarounds may exist for platform behavior outside the plugin's control. Trace their purpose before simplifying them.
## 🪵 Logging Requirement
- **Do not use direct `console.log(...)` calls in project code.** Use the shared logging helper exported as `log` from `src/utils/debugHelper.ts`.
- If you are working in a Node script where importing `src/utils/debugHelper.ts` is not practical, define and use a local `log` wrapper instead of calling `console.log(...)` directly.
- Temporary performance diagnostics must use a unique searchable prefix and
produce copyable string lines rather than expandable console objects. Keep
instrumentation separate from functional behavior, avoid vault contents,
and include filenames only when per-file attribution is explicitly needed.
- Remove temporary diagnostics before committing. Search both `src/` and the
built `dist/main.js` for the prefix so timing callbacks and bundled log code
are not left behind.
## 🏗️ Architecture & Sub-components
This project consists of multiple sub-components and non-standard integrations to support Obsidian-specific features.
### 1. React & Package Manager
Because the plugin must support Obsidian's native popout windows, React and Excalidraw cannot be loaded as simple global singletons.
The plugin inflates one private React/ReactDOM runtime and combines it with one evaluated Excalidraw runtime. Every main-window and popout view leases that shared package while supplying its own stable `ownerDocument`.
- References to React and ReactDOM are handled via `PackageManager.ts` (`src/core/managers/PackageManager.ts`).
- They are loaded to Obsidian popout windows separately during runtime. Do not introduce direct `ReactDOM.createRoot()` or similar global React calls outside of this package manager model.
- 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.
Rendering and persistence have different window-ownership rules. DOM, events, portals, and React roots should use the owning view window. Existing plugin-level IndexedDB and local-storage data belongs to the main Obsidian application window and is shared with popouts; do not move it to `view.ownerWindow` without an explicit storage design and migration.
#### Typed Excalidraw host boundary
Obsidian-specific capabilities used inside the customized component must cross the typed host-adapter boundary configured by `PackageManager`. Do not pass the plugin, its settings object, or an active view through Excalidraw props or `appState`, and do not recover them through globals. Adapters should expose small semantic operations, read current plugin state, and remain owned by the evaluated window runtime. View-specific behavior must stay instance-scoped.
The fork is the source of truth for adapter contracts and protocol versions. Reuse its published types instead of defining parallel plugin-local unions or interfaces. The adapters are an internal protocol paired with this plugin's exact Excalidraw dependency: coordinate breaking changes across both repositories and fail fast on a missing or incompatible boundary rather than retaining legacy global bridges.
### 2. MathjaxToSVG
LaTeX support is provided by the `MathjaxToSVG` library, which is packaged as a separate sub-component (located in the `MathjaxToSVG/` folder).
@@ -50,7 +104,7 @@ LaTeX support is provided by the `MathjaxToSVG` library, which is packaged as a
- It is decompressed and executed dynamically during runtime only when needed, maintaining optimal Obsidian startup times.
### 3. Excalidraw Fork Guidelines
This plugin relies on a custom Excalidraw component fork: [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/).
This plugin relies on a custom Excalidraw component fork: [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/).
If you must submit a PR to the Excalidraw fork, **keep changes to the absolute minimum**. Compounding changes to the fork make merging upstream updates from `excalidraw/excalidraw` exponentially harder.
@@ -87,11 +141,58 @@ If you must submit a PR to the Excalidraw fork, **keep changes to the absolute m
private startRightClickPanning(event) { ... }
```
### 4. Working Across Both Repositories
The customized component is maintained in the separate [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/) repository. When both repositories are checked out as siblings, the usual path is `../excalidraw`.
The repositories deliberately use different package managers:
- `obsidian-excalidraw-plugin`: npm
- `zsviczian/excalidraw`: Yarn
From `../excalidraw/packages/excalidraw`, `yarn build:obsidian` produces four consumer-specific files in `dist/obsidian`: development and production JavaScript and CSS. This plugin reads the corresponding four files from `node_modules/@zsviczian/excalidraw/dist/obsidian/`.
For an unpublished integration test, you may temporarily copy those four generated files into the installed package under this repository's ignored `node_modules`. Keep the declared npm dependency unchanged. Running `npm install` restores the published package. The durable workflow is to publish a new component version, update the plugin dependency, run `npm install`, and rebuild.
Keep component commit readiness, local integration readiness, and durable
consumer handoff separate. A copied artifact can validate the pair locally,
but a plugin change that consumes a new fork API is not release-ready until the
published package is installed and `package.json` plus `package-lock.json`
reference that version.
For a maintainer-coordinated host-protocol release, update and test the fork contract first, inspect the package tarball, publish the fork package, then update this repository's exact dependency and lockfile. The final production build and smoke test must use the published package installed by `npm install`, not the temporary copied artifacts. Unit tests in the fork use structural fake adapters and do not require Obsidian; integration testing here must cover startup, reload, the main window, and popout creation and teardown.
The Excalidraw Obsidian artifact has strict runtime constraints:
- one function-evaluable JavaScript file, with no runtime chunks
- React, ReactDOM, and their JSX runtimes remain external and are supplied by this plugin
- Mermaid remains external and is loaded lazily through Excalidraw Extras
- all required assets work offline except deliberately lazy CJK font subsets
- production is minified; development retains debugger-friendly source information
Radix menus and popovers may be portaled to the owning document body by `ObsidianRadixPortal`. Portaled content no longer has its original component ancestors and can sit behind modal stacking contexts. Style portaled content through a class that survives the portal, and test visibility, positioning, click-outside, and Escape behavior in the main window and a popout.
### 5. Incremental Refactoring
Use `RefactorPlan.md` as the living record for ongoing structural work. Refactors should be small enough to build and test independently. Move cohesive code intact before redesigning it, update the progress table and action log, and provide a risk-based test checklist at the end of each step.
`ExcalidrawView` must remain an Obsidian `TextFileView`; it should not be converted wholesale into React. React owns the child UI, while the view remains the Obsidian lifecycle and compatibility boundary. ExcalidrawAutomate, command IDs, settings, serialized data, and existing plugin integrations must remain backwards compatible.
### 6. Settings UI and persistence
The plugin keeps Obsidian 1.8.7 compatibility while using searchable declarative settings on Obsidian 1.13 and newer.
- Do not bump the Obsidian dependency or minimum version just to use the declarative API. Gate it at runtime; returning an empty definition array is the intentional legacy fallback.
- Maintain one canonical settings hierarchy and shared control behavior for both the declarative multi-page and legacy single-page layouts, including descriptions and Markdown export. Do not fork the two experiences into independent implementations.
- Keep interdependent controls together and apply their visibility, options, and disabled state during initial render as well as after changes.
- Persist settings through `PluginSettingsManager`; do not add independent `saveData()` calls or rely on plugin shutdown to finish an asynchronous save.
- Treat a missing `data.json`, invalid/corrupted data, and a valid externally synchronized update as separate cases. Preserve the device-local recovery workflow and unknown forward-compatible setting keys.
## 🌍 Localization & User-Facing Text
- **No hardcoded strings:** There should be no hardcoded English strings directly in the UI components or logic.
- **Language files:** All strings must be added to the localization files located in `src/lang/locale/`.
- **Translations:** At a minimum, you must add your new keys and strings to `en.ts`. However, it is highly appreciated if you can provide translated strings for all of our actively maintained translations (`es.ts`, `ru.ts`, `zh-cn.ts`, `zh-tw.ts`) using a translation tool.
- **Language files:** All strings must be added to the localization files located in `src/lang/locale/`.
- **Translations:** Add every new key and string to `en.ts` and the actively maintained translations (`es.ts`, `ru.ts`, `zh-cn.ts`, `zh-tw.ts`) in the same change.
## 📦 Pull Requests & Versioning
+2435
View File
File diff suppressed because it is too large. Load diff
+231
View File
@@ -0,0 +1,231 @@
# Excalidraw Automate scripting support plan
Status: active as of 2026-08-29.
This plan tracks the modernization of ExcalidrawAutomate AI support material while preserving compatibility with the long-lived training entrypoint.
Scope summary:
- Keep [docs/AITrainingData](docs/AITrainingData) as the canonical output location.
- Keep [docs/AITrainingData/ExcalidrawAutomate full library for LLM training.md](docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md) as a stable entrypoint, but curate it as a router to skill-first references.
- Use one unified generator behind `npm run doc`.
- Keep [ea-scripts/script-store.json](ea-scripts/script-store.json) as the contributor-facing catalog; keep [ea-scripts/index-new.md](ea-scripts/index-new.md) frozen for legacy clients and generate only targeted update metadata in `directory-info.json`.
- Keep skill generation manually triggered by maintainer workflows (no automatic watcher/CI updates in this phase).
- Add strict naming rules for script preview images under [images](images).
## Decisions captured
1. Unified generation command
- `npm run doc` is the single maintainer command for documentation generation.
- If a script-template repository is present in the current VS Code workspace, `npm run doc` should also refresh template-project references/artifacts.
2. Legacy entrypoint behavior
- The legacy training file remains the stable public entrypoint.
- It must warn AI tools that generated code quality may fail if linked skill/reference URLs are inaccessible (for example: URL access disabled in some chat tools).
3. Script library publishing guidance
- [ea-scripts/script-store.json](ea-scripts/script-store.json) is the contributor-facing metadata source.
- Agents should be guided to open a proper PR for publishing scripts in this repository instead of trying to bypass the normal contribution workflow.
- `npm run script-store:build` validates the current catalog and advances `directory-info.json` only for script/icon files that actually changed; it never rewrites `index-new.md`.
- Historical `mtime` values must remain untouched; they are part of the plugin's backward-compatible update-detection contract.
4. Template repository direction
- A separate repository will be created first.
- Proposed name: `ea-script-template`.
- Once added to this workspace, the unified generator can optionally update it.
- Repository availability status: present and accessible at [../ea-script-template](../ea-script-template).
5. Image naming
- Adopt strict naming convention for script preview images, aligned to current patterns but enforceable.
6. Experimental script policy
- Scripts under [ea-scripts](ea-scripts) are treated as validated examples.
- No experimental bucket is introduced in this phase.
- Very large scripts (for example Mindmap Builder) are still valid; they should be tagged as "advanced/large-reference" rather than experimental.
7. Skill generation trigger
- Keep manual generation trigger. No automated regeneration in this phase.
## Progress tracking
Target branch: `improved-scripting-skills`.
| Phase | Status | Current outcome |
| --- | --- | --- |
| Baseline audit and constraints capture | Complete | Existing generators, outputs, and maintainer decisions captured in this plan |
| Create planning artifact in repository | Complete | Added [ScriptSupportPlan.md](ScriptSupportPlan.md) with phases, decisions, and action log |
| Unify generator implementation behind `npm run doc` | Complete | Added shared generator core at [scripts/excalidraw-docs-generator-core.mjs](scripts/excalidraw-docs-generator-core.mjs); both [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs) and [scripts/skill-builder.mjs](scripts/skill-builder.mjs) are thin wrappers over one code path |
| Ensure canonical pen type completeness in generated docs | Complete | Generated references now include canonical Obsidian pen stroke type definitions plus the full public `src/types` and `lib/types` declaration surface |
| Curate legacy training entrypoint warning and routing | Complete | Legacy training entrypoint now warns about inaccessible references, names the master repository, and routes agents to the curated skill/reference set with absolute GitHub URLs |
| Add PR publishing workflow guidance for scripting agents | Complete | Generated skill guidance now directs script publishing through PRs, uses `script-store.json` as catalog metadata, and generates only targeted legacy mtime updates |
| Add strict image naming and validation | Complete | Generator now warns on non-conforming preview filenames and documents the `scripts-{slug}.{ext}` rule in generated publishing guidance |
| Optional template-repo sync from `npm run doc` | Complete | `npm run doc` now refreshes a co-located `ea-script-template` bootstrap under `.ai/excalidraw-automate/` when the sibling repo is present |
## Implementation checkpoints
### Checkpoint 1: Shared generator core and single command
Objective:
- Introduce a shared generator module and keep lightweight wrappers for backward command compatibility.
Planned changes:
- Consolidate duplicated logic currently split between:
- [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs)
- [scripts/skill-builder.mjs](scripts/skill-builder.mjs)
- Keep `npm run doc` as the single entrypoint command for maintainers.
- Keep manual run model. Do not add auto-run hooks in this phase.
Acceptance:
- One command (`npm run doc`) generates both legacy and skill outputs exactly once.
- Output files stay under [docs/AITrainingData](docs/AITrainingData).
### Checkpoint 2: Fix type-definition completeness regression
Objective:
- Ensure generated type references remain concrete after alias migrations.
Problem to solve:
- `lib/types/penTypes.d.ts` now aliases fork-owned types, and top import stripping can hide canonical shapes in generated docs.
Planned changes:
- Include canonical Obsidian type declarations from the fork type surface in generated reference outputs.
- Add a post-generation guard that fails if `ObsidianPenStrokeOptions` shape is missing.
Acceptance:
- Both:
- [docs/AITrainingData/Excalidraw Automate library and related type definitions.md](docs/AITrainingData/Excalidraw%20Automate%20library%20and%20related%20type%20definitions.md)
- [docs/AITrainingData/ExcalidrawAutomate full library for LLM training.md](docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md)
include concrete stroke option structure, not alias-only references.
Status:
- Complete.
- The generator now includes all declaration files under [src/types](src/types) and [lib/types](lib/types), plus the canonical fork-owned `obsidianTypes.d.ts` source for `ObsidianPenStrokeOptions`.
### Checkpoint 3: Curated legacy entrypoint messaging
Objective:
- Keep stable legacy entrypoint while steering agents to curated skill references.
Planned changes:
- Add a prominent warning that script generation can fail if linked references are not accessible.
- Include concrete note about environments requiring explicit URL enablement.
- Add short routing section pointing to curated skill/reference materials.
Acceptance:
- Legacy file remains backward compatible as an entrypoint.
- Warning is clear and placed before the main usage workflow.
Status:
- Complete.
- The generated legacy entrypoint now includes a top-level routing warning, the master repository URL, and direct absolute links to the curated skill and reference files.
### Checkpoint 4: Script publishing workflow guidance for agents
Objective:
- Teach agents to publish scripts through normal repository contribution workflow.
Planned changes:
- Add concise maintainer-approved workflow guidance in skill docs:
- add script to [ea-scripts](ea-scripts)
- add image to [images](images)
- add or update the entry in [ea-scripts/script-store.json](ea-scripts/script-store.json)
- run `npm run script-store:check` and `npm run script-store:build`
- allow the generator to advance only the changed script/icon `mtime` entry in [ea-scripts/directory-info.json](ea-scripts/directory-info.json)
- keep AI training material updates out of script publishing PRs
- open PR with focused diff and validation notes
- Treat `index-new.md` as a frozen backward-compatibility catalog. Routine publishing must not modify it; new scripts are intentionally unavailable to older clients unless a maintainer explicitly updates the legacy catalog separately.
Acceptance:
- Publishing workflow appears in generated skill material.
- Guidance is PR-centric and does not suggest direct pushes.
Status:
- Complete.
- The generated skill file now includes a dedicated publishing workflow section with absolute repository links, PR-only guidance, a frozen legacy catalog, and targeted `directory-info.json` updates.
### Checkpoint 5: Strict image naming convention and validator
Objective:
- Keep existing style while making naming consistent and enforceable.
Proposed naming rule:
- `scripts-{slug}.{ext}` where:
- `slug` = lowercase words joined by hyphen
- only `a-z`, `0-9`, `-`
- extensions allowed: `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.svg`
Examples:
- `scripts-add-link-to-existing-file-and-open.jpg`
- `scripts-boolean-operations-showcase.png`
Planned changes:
- Add validation in generator flow with clear error output.
- Keep compatibility mode for pre-existing files during initial rollout (warn-only first, strict fail in follow-up if desired).
Acceptance:
- New/updated script previews follow the naming contract.
- Validation output is actionable for contributors.
Status:
- Complete.
- The generator now warns on non-conforming preview filenames and surfaces the naming rule in the generated publishing workflow guidance.
### Checkpoint 6: Optional template repository sync
Objective:
- Allow `npm run doc` to refresh a co-located script-template repo if present.
Planned behavior:
- Detect a workspace folder named `ea-script-template` (or configurable path).
- If found, update agreed generated reference artifacts in that repo.
- If absent, continue without failure.
Current status:
- Repository now exists and is readable at [../ea-script-template](../ea-script-template).
- Checkpoint is considered unblocked and ready for scoped implementation once approved.
Design note: AI support files in template repo
- Preferred default: synchronized local snapshot under `.ai/excalidraw-automate/`, copied from canonical generated references in this repository.
- Routing note: keep canonical GitHub links in SKILL content, but ensure local references and script examples are present for environments without URL access.
- Reasoning: local snapshot gives immediate offline usability while preserving canonical source of truth in plugin-generated outputs.
Design note: template usage model
- Recommended model: single `ea-script-template` repository used as a multi-script workspace (one folder per script project) with shared utilities.
- Why: easier maintenance of common helpers, lint/build rules, and shared abstractions across scripts like Mindmap Builder, Slideshow, and Shade Master.
- Alternative supported pattern: per-script clones for strict isolation (useful for publishing independent repos), but this should be optional rather than the default path.
Acceptance:
- `npm run doc` succeeds in both cases:
- template repo present
- template repo absent
Status:
- Complete.
- `npm run doc` now refreshes a full local skill snapshot in the sibling `ea-script-template` workspace under `.ai/excalidraw-automate/` when the repo is available.
## Validation approach
For each implementation checkpoint:
- Run `npm run doc` from repository root.
- Verify generated files changed only in intended outputs.
- For script/reference changes, inspect key generated artifacts manually.
- Keep [ea-scripts/index-new.md](ea-scripts/index-new.md) untouched unless explicitly edited by maintainer.
## Risks and mitigations
Risk: duplicate logic drifts again across scripts.
- Mitigation: one shared generator core and wrapper entrypoints.
Risk: type aliasing hides critical concrete structures again.
- Mitigation: required-symbol guard (`ObsidianPenStrokeOptions`) and explicit canonical-source inclusion.
Risk: stricter image naming breaks existing contributions.
- Mitigation: staged rollout (warn-first) and clear remediation examples.
Risk: template sync introduces hard dependency on external repo.
- Mitigation: optional detection; never fail when repo is absent.
## Action log
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-08-29 | Captured maintainer decisions for scripting support modernization | Decisions documented for unified generator, manual index curation, PR workflow guidance, strict image naming, and optional template sync | Plan file created at [ScriptSupportPlan.md](ScriptSupportPlan.md) |
| 2026-08-29 | Confirmed template repository workspace availability and expanded publishing requirements | Verified [../ea-script-template](../ea-script-template) is present and readable; added mandatory [ea-scripts/directory-info.json](ea-scripts/directory-info.json) update rules to publishing workflow and checkpoint details | Directory listing succeeded for [../ea-script-template](../ea-script-template); plan updated |
| 2026-08-29 | Implemented checkpoint 1 unified generator | Consolidated duplicated generation logic into [scripts/excalidraw-docs-generator-core.mjs](scripts/excalidraw-docs-generator-core.mjs), with wrapper entrypoints preserved at [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs) and [scripts/skill-builder.mjs](scripts/skill-builder.mjs) | `npm run doc` completed successfully and regenerated legacy + skill outputs from one code path |
| 2026-08-29 | Implemented checkpoint 5 image naming validator | Added warning-only preview filename validation and surfaced the `scripts-{slug}.{ext}` rule in generated publishing guidance | `npm run doc` completed successfully and emitted the expected warning for legacy preview names |
| 2026-08-29 | Implemented checkpoint 6 template bootstrap sync | `npm run doc` now refreshes a link-first bootstrap in the sibling `ea-script-template` workspace under `.ai/excalidraw-automate/` | `npm run doc` completed successfully and refreshed the sibling template bootstrap files |
| 2026-08-29 | Hardened checkpoint 6 for offline and advanced script authoring | Template sync now mirrors full generated references and script examples instead of only link stubs | `npm run doc` and `npm run sync-refs` now produce local skill + references + scripts snapshot in `.ai/excalidraw-automate/` |
| 2026-08-29 | Aligned template script extensions and build output | Template-only reference snapshots now use `.js` filenames with rewritten local links; the template build emits executable `.md` scripts with purpose metadata and editable configuration constants before the bundle | `npm run doc` preserves `.js` reference filenames; template `npm run build`, `npm run check`, and package validation pass on Node 22 |
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -9,24 +9,42 @@ Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source E
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
**Routing note:** Prefer the curated skill package and reference set first. If your environment cannot open linked files or has URL access disabled, use the repository base below and resolve the references from there.
- Master repository: https://github.com/zsviczian/obsidian-excalidraw-plugin
- Start with: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/SKILL.md
- Type definitions: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/type-definitions.md
- API usage index: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/api-usage-index.md
- ExcalidrawLib signatures: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/excalidraw-lib-functions.md
- Startup examples: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/startup-scripts.md
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via `ea.getExcalidrawAPI()`. Note: the API is only available if `ea.targetView` is set. When running Excalidraw scripts using the script engine, the provided `ea` object is already set up with targetView by default. Otherwise you need to first run `ea.setView()`.
- The Excalidraw API available via `ea.getExcalidrawAPI()`. Note: the API is only available if `ea.targetView` is set. When running Excalidraw scripts using the script engine, the provided `ea` object is already set up with targetView by default. Otherwise call `ea.setView()` to select a sensible default or `ea.setView(view)` to bind explicitly. Calling `ea.setView(null)` deliberately clears `targetView`; it does not auto-select another drawing.
- `window.ExcalidrawLib` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via `ea` (ExcalidrawAutomate) methods, ALWAYS prefer `ea` over `window.ExcalidrawLib`. `ea` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
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.
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on `ea.obsidian`.
- In a template-based script workspace, `src/types/ea.d.ts` is an upstream-managed projection of the Script Engine API. Never edit it or generated declarations under `.template/types/`. Put repository-specific ambient declarations and type augmentations in `src/types/local.d.ts` instead, so template updates can replace the generated API safely.
- Version checks are distinct: use `ea.verifyMinimumPluginVersion()` for the Excalidraw plugin and `ea.obsidian.requireApiVersion()` only for the Obsidian application version.
- `utils.executionSource` describes why the current top-level invocation happened. Supported values are `"manual"`, `"plugin-startup"`, `"view-autostart"`, `"sidepanel-restore"`, `"sidepanel-reload"`, and `"drawing-onload"`. It does not indicate whether code came from the compilation cache or whether the script has run before.
- `ea.registerAutostart(message?)` requests view-autostart permission. The script is automatically attached once to each ExcalidrawView, while manual toolbar/command/hotkey invocation remains independently repeatable. The optional explanation appears as the second paragraph of the permission prompt; do not imply that the script's main interactive action starts automatically when only its tools/providers do.
- `ea.registerCleanup(cleanup)` registers synchronous cleanup owned by the current EA instance. Use it for external listeners, timers, observers, and subscriptions; the cleanup runs when that EA is destroyed.
- `ea.registerElementActionProvider()` action descriptors take an Obsidian/Lucide icon name such as `"presentation"`, not serialized SVG markup. For buttons a script renders itself, obtain the SVG with `ea.obsidian.getIcon()` and recreate it in the button's owning document when popout support matters.
- When an Excalidraw API method requires an element, pass the known typed scene element. For example, call `api.startLineEditor(line, pointIndices)`; do not re-read selection state when the intended line is already known.
- For persistent workbench mutations, await `ea.addElementsToView()` with saving enabled (the default). Prefer this public EA save path over unpublished methods on `ea.targetView`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (`onOpen`, `onFocus(view)`, `onClose`, `onExcalidrawViewClosed`) and manage their own `ea.targetView` explicitly.
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with `ea.targetView === null`. Scripts must handle this by deferring view-bound work until `onFocus` delivers a view; call `ea.setView(view)` when you decide to bind.
- Persisted sidepanel scripts are restored lazily when the Excalidraw sidepanel initializes (often during startup, but not necessarily) with `ea.targetView === null`. Scripts must handle this by deferring view-bound work until `onFocus` delivers a view; call `ea.setView(view)` when you decide to bind. When `onFocus` supplies `null` or focus moves to a non-Excalidraw view, call `ea.setView(null)` to make the unbound state explicit and prevent later view operations from targeting a stale drawing.
- Each `ea` instance may host a single `sidepanelTab`. This sidepanel tab is stored in `ea.sidepanelTab`. Create the tab with `ea.createSidepanelTab(title, persist=false, reveal=true)`; the returned `ea.sidepanelTab` exposes `contentEl`, `setContent`, `setTitle`, `setDisabled`, `setCloseCallback`, `open/close`, and focus lifecycle hooks. Note auto-reveal during tab creation via `ea.createSidepanelTab()` is disabled during plugin startup. You can reveal a tab with `ea.sidepanelTab?.open()`. You can persist with `ea.persistSidepanelTab()` (tabs are restored and scripts re-run on next startup). Close with `ea.sidepanelTab?.close()`.
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-`ExcalidrawView` relevant, they can call `ea.closeSidepanelTab()` after completing the operation, and/or inside `ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }` to shut down when the user leaves the originating view.
@@ -64,20 +82,40 @@ To keep this training file concise, large external type definitions are not incl
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
* **Central Rule:** Elements returned from the Excalidraw scene are immutable and should never be modified directly. EA owns a stateful, in-memory "workbench" (`elementsDict` and `imagesDict`) where a script stages one coherent persistent or temporary operation independently of the scene.
* **The Workflow:**
1. Get elements from the current view using `ea.getViewElements()` or `ea.getViewSelectedElements()`.
2. Copy these elements into the EA workbench for editing using `ea.copyViewElementsToEAforEditing(elements)`.
3. Modify the properties of the element copies that are now in the EA workbench (e.g., `ea.getElement(id).locked = true;`).
4. Commit the changes back to the scene using `await ea.addElementsToView()`.
1. Start an independent transaction with `ea.clear()`. This clears only the workbench; it does not delete scene elements or reset style.
2. Read existing scene elements using `ea.getViewElements()` or `ea.getViewSelectedElements()`.
3. To work with mutable copies of those same scene elements, copy them into the workbench with `ea.copyViewElementsToEAforEditing(elements)`. Their IDs are preserved.
4. Modify the workbench copies retrieved by their original IDs (e.g., `ea.getElement(id).locked = true;`).
5. For a persistent scene edit, commit once with `await ea.addElementsToView()`; saving is enabled by default. For temporary transformations such as export or preview preparation, pass the workbench elements to the relevant EA operation without committing them to the scene.
6. Call `ea.clear()` after the operation to discard the workbench copies, preferably in a `finally` block when an awaited operation can fail.
* **Temporary workbench example:**
```javascript
ea.clear();
try {
const sceneElements = ea.getViewElements();
ea.copyViewElementsToEAforEditing(sceneElements);
ea.getElement(pathId).opacity = 0;
// elementsOverride replaces the export scene, so pass the complete workbench.
const svg = await ea.createViewSVG({ elementsOverride: ea.getElements() });
// Use svg. The live scene was never changed.
} finally {
ea.clear();
}
```
* **`elementsOverride` is a complete replacement:** In `createViewSVG()` and `createViewPNG()`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the image. When temporarily modifying an existing scene for export, copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
* **Use `exportArea` for bounded view exports:** Both view export methods accept `exportArea: {x, y, width, height}`. EA filters the candidate elements with the same logic exposed as `getElementsIntersectionArea()` (and its backward-compatible `getElementsInArea()` alias), retains required bound elements, and anchors the result to that exact viewport. This prevents a small preview or PDF page from retaining every image in a large scene.
* **Identity is the boundary:** `copyViewElementsToEAforEditing()` is the standard way to obtain mutable, identity-preserving copies of existing scene elements for both persistent edits and temporary EA operations. By contrast, `ea.cloneElement()` and `ea.cloneElements()` deliberately generate new IDs and are only for creating genuine duplicate scene elements. Never use them to obtain editable workbench copies of existing elements.
* **One workbench transaction at a time:** The workbench is shared mutable state on an EA instance. Do not interleave asynchronous preview/export preparation and scene mutation through the same workbench. Await the operation, then clear the workbench before starting another transaction.
* **Deletion:** To delete an element, set its `isDeleted` property to `true` on the workbench copy (`ea.getElement(id).isDeleted = true;`) and then commit with `await ea.addElementsToView()`.
* **Cleanup:** Use `ea.clear()` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
#### **2. User Interaction: Prompts and Dialogs**
* **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`.
@@ -125,11 +163,27 @@ To keep this training file concise, large external type definitions are not incl
* To permanently remove an element from the scene, set `element.isDeleted = true`.
* **Image Handling:** When dealing with image elements, use `ea.getViewFileForImageElement(imageElement)` to get the corresponding `TFile` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **6.1. Tests in a Multi-Script Workspace**
* **Tests are part of implementation:** Add or update focused automated tests for behavior changes. When fixing a regression, reproduce it with a failing test first when practical.
* **Co-locate by ownership:** Put script tests in `src/scripts/{slug}/__tests__/*.test.ts` and shared utility tests in `src/sharedUtils/__tests__/*.test.ts`. Do not maintain a separate root test tree that mirrors dozens of scripts.
* **Never import executable entrypoints:** `main.ts` runs immediately against the globals injected by Obsidian. Keep it as a thin bootstrap and move testable orchestration to `run.ts` or another import-safe module.
* **Use the universal runner:** Use Vitest. Run a focused suite while iterating, then run `npm run check`; the repository gate includes TypeScript, ESLint, and all test suites. Use `npm run test:watch` for continuous feedback.
* **Test behavior, not bundler details:** Prefer pure domain functions and narrow fakes for `ea`, the Excalidraw API, Obsidian globals, timers, and DOM boundaries. Build and perform an Obsidian smoke test for integration behavior automation cannot prove.
#### **6.2. Per-Script Localization**
* **Catalogs belong to the script:** Store strings in `src/scripts/{slug}/lang/`, with one file per locale. Never create one language catalog shared across unrelated scripts.
* **English defines the contract:** `lang/en.ts` is the typed source of truth. Maintain `de.ts`, `es.ts`, `fr.ts`, `ru.ts`, and `zh-cn.ts`; incomplete reviewed catalogs may rely on English fallback.
* **Use the shared helper:** Register catalogs in `lang/index.ts` with `createTranslator`. Resolve the locale with `ea.obsidian.moment.locale()` and pass the translator into import-safe script logic.
* **Interpolate by name:** Use placeholders such as `{count}` instead of string concatenation. Do not use dynamically constructed regular expressions for interpolation.
* **Keep UI copy out of logic:** Add user-visible strings to the script catalog rather than embedding them in controllers, runners, or helpers.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use `await ea.createSVG(null, ...)` or `await ea.createPNG(null, ...)` (passing `null` as the `templatePath`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to `createSVG` or `createPNG` (e.g., `await ea.createSVG(file.path, ...)`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)`. This is specifically for the open view. You can use the `elementsOverride` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)` for vector output or `await ea.createViewPNG(...)` for raster output. Their `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or patch by ID. Use `exportArea` when only a rectangular viewport is needed; it filters out off-area elements and their unused image payloads instead of exporting the full scene and merely changing the SVG viewBox. For temporary changes, copy the complete desired export set into the EA workbench, modify it there, and pass `ea.getElements()`.
#### **8. Custom Pens and Perfect Freehand**
@@ -230,11 +284,23 @@ Example freedraw element carrying `customData.strokeOptions`:
## References
The `references/` directory contains supporting documentation necessary for writing scripts:
- `references/type-definitions.md`: Core type definitions for ExcalidrawAutomate.
- `references/excalidraw-lib-functions.md`: Function signatures for `window.ExcalidrawLib`.
- `references/startup-scripts.md`: ExcalidrawStartup script template and examples.
- `references/api-usage-index.md`: A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
- `references/scripts/`: A folder containing all the raw, real-world example scripts.
- [type-definitions.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/type-definitions.md): Core type definitions for ExcalidrawAutomate.
- [excalidraw-lib-functions.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/excalidraw-lib-functions.md): Function signatures for `window.ExcalidrawLib`.
- [startup-scripts.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/startup-scripts.md): ExcalidrawStartup script template and examples.
- [api-usage-index.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/api-usage-index.md): A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
- [scripts/](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/docs/AITrainingData/excalidraw-automate/references/scripts): A folder containing all the raw, real-world example scripts.
## Publishing Workflow
Use the normal repository contribution flow when publishing or updating scripts.
The AI training material is maintained independently from publishing PRs; do not bundle regenerated training artifacts into the script PR.
- Preview images must follow `scripts-{slug}.{ext}`, where `slug` uses lowercase `a-z`, `0-9`, and hyphens only.
- Add or update the script under [ea-scripts](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts).
- Add or update the preview image under [images](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images).
- Add or update the script's catalog entry in [ea-scripts/script-store.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/script-store.json).
- Run `npm run script-store:check`, then `npm run script-store:build`. The build validates the catalog and advances `directory-info.json` only for script/icon files that actually changed; it does not modify the frozen legacy `index-new.md` catalog.
- Do not hand-edit unrelated `mtime` values in [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json). Historical mtimes are part of the plugin's update-detection contract.
- Keep the PR focused on the script and its generated references.
### How to use the Script Examples
If you need to implement a specific function (e.g., `ea.addElementsToView`), do NOT guess its implementation context. Instead:
@@ -9,61 +9,61 @@ 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 DrawIO file.md](scripts/Create%20DrawIO%20file.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 sizLine 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 DrawIO file.md](scripts/Create%20DrawIO%20file.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)
- **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)
- **addToGroup**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **analyzeAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **attachInlineLinkSuggester**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **canvas**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md)
- **checkAndCreateFolder**: [Capture Note.md](scripts/Capture%20Note.md)
- **checkForActiveSidepanelTabForScript**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
- **clear**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **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)
- **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), [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)
- **generateElementId**: [Capture Note.md](scripts/Capture%20Note.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **generateElementId**: [Capture Note.md](scripts/Capture%20Note.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **getAISettings**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **getAPI**: [Capture Note.md](scripts/Capture%20Note.md)
- **getAttachmentFilepath**: [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [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)
- **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), [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), [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,64 +71,76 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **getPathForImageFileId**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getPolyBool**: [Boolean Operations.md](scripts/Boolean%20Operations.md)
- **getSceneFromFile**: [Palette loader.md](scripts/Palette%20loader.md)
- **getScriptSettings**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
- **getScriptSettings**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Darken background color.md](scripts/Darken%20background%20color.md), [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), [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)
- **measureText**: [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **Modal**: [Image Occlusion.md](scripts/Image%20Occlusion.md)
- **moveViewElementToZIndex**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md)
- **obsidian**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **obsidian**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
- **onLinkClickHook**: [Slideshow.md](scripts/Slideshow.md)
- **onSceneChangeHook**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Shade Master.md](scripts/Shade%20Master.md)
- **openFileInNewOrAdjacentLeaf**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **openFileInNewOrAdjacentLeaf**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **ownerDocument**: [Slideshow.md](scripts/Slideshow.md)
- **parseText**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **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)
- **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)
- **sidepanelTab**: [Icon Library.md](scripts/Icon%20Library.md), [LayerManager.md](scripts/LayerManager.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
- **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)
- **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), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.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)
- **onChange**: [LayerManager.md](scripts/LayerManager.md)
- **setActiveTool**: [Slideshow.md](scripts/Slideshow.md)
- **setToast**: [Slideshow.md](scripts/Slideshow.md)
- **startLineEditor**: [Slideshow.md](scripts/Slideshow.md)
- **updateContainerSize**: [Capture Note.md](scripts/Capture%20Note.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
- **updateScene**: [Custom Zoom.md](scripts/Custom%20Zoom.md), [Palette loader.md](scripts/Palette%20loader.md), [Set Grid.md](scripts/Set%20Grid.md)
- **updateScene**: [Custom Zoom.md](scripts/Custom%20Zoom.md), [LayerManager.md](scripts/LayerManager.md), [Palette loader.md](scripts/Palette%20loader.md), [Set Grid.md](scripts/Set%20Grid.md), [Slideshow.md](scripts/Slideshow.md)
- **zoomToFit**: [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
## ExcalidrawLib
@@ -84,7 +84,7 @@ export declare const getCommonBoundingBox: (elements: readonly ExcalidrawElement
/* ************************************** */
/* @excalidraw/element/groups -> node_modules/@zsviczian/excalidraw/types/element/src/groups.d.ts */
/* ************************************** */
export declare const getMaximumGroups: (elements: ExcalidrawElement[], elementsMap: ElementsMap) => ExcalidrawElement[][];
export declare const getMaximumGroups: <T extends NonDeletedExcalidrawElement | ExcalidrawElement>(elements: T[], elementsMap: ElementsMap) => T[][];
/* ************************************** */
/* @excalidraw/element/textMeasurements -> node_modules/@zsviczian/excalidraw/types/element/src/textMeasurements.d.ts */
@@ -101,7 +101,7 @@ export declare const wrapText: (text: string, font: FontString, maxWidth: number
/* @excalidraw/element/textElement -> node_modules/@zsviczian/excalidraw/types/element/src/textElement.d.ts */
/* ************************************** */
export declare const getBoundTextMaxWidth: (container: ExcalidrawElement, boundTextElement: ExcalidrawTextElement | null) => number;
export declare const getContainerElement: (element: ExcalidrawTextElement | null, elementsMap: ElementsMap) => ExcalidrawTextContainer | null;
export declare const getContainerElement: <T extends ExcalidrawTextElement, R extends ExcalidrawTextContainer>(element: T | null, elementsMap: ElementsMap) => R | null;
/* ************************************** */
/* ./components/TTDDialog/MermaidToExcalidrawLib -> node_modules/@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/MermaidToExcalidrawLib.d.ts */
@@ -223,21 +223,20 @@ export declare const TTDDialog: {
/* ************************************** */
/* ./components/TTDDialog/utils/TTDStreamFetch -> node_modules/@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/utils/TTDStreamFetch.d.ts */
/* ************************************** */
export declare function parseSSEStream(reader: ReadableStreamDefaultReader<Uint8Array>): AsyncGenerator<string, void, unknown>;
export declare function TTDStreamFetch(options: StreamingOptions): Promise<TTTDDialog.OnTextSubmitRetValue>;
/* ************************************** */
/* ./actions/actionCanvas -> node_modules/@zsviczian/excalidraw/types/excalidraw/actions/actionCanvas.d.ts */
/* ./viewport -> node_modules/@zsviczian/excalidraw/types/excalidraw/viewport.d.ts */
/* ************************************** */
export declare const zoomToFitBounds: ({ bounds, appState, canvasOffsets, fitToViewport, viewportZoomFactor, minZoom, maxZoom, }: {
export declare const zoomToFitBounds: ({ bounds, appState, canvasOffsets, fit, minZoom, maxZoom, steppedZoom, }: {
bounds: SceneBounds;
canvasOffsets?: Offsets;
appState: Readonly<AppState>;
/** whether to fit content to viewport (beyond >100%) */
fitToViewport: boolean;
/** zoom content to cover X of the viewport, when fitToViewport=true */
viewportZoomFactor?: number;
fit?: SetViewportOptions["fit"];
minZoom?: number;
maxZoom?: number;
steppedZoom?: boolean;
}) => {
appState: {
scrollX: number;
@@ -254,4 +253,35 @@ export declare const DiagramToCodePlugin: (props: {
/* ************************************** */
export declare const CommandPalette: ((props: CommandPaletteProps) => import("react/jsx-runtime").JSX.Element | null) & {
defaultItems: typeof defaultItems;
/* ************************************** */
/* ./obsidianExcalidrawHost -> node_modules/@zsviczian/excalidraw/types/excalidraw/obsidianExcalidrawHost.d.ts */
/* ************************************** */
export declare const OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION: 2;
/** Keyboard-blocking lifecycle returned by the host's inline suggester. */
export interface ObsidianKeyBlocker {
isBlockingKeys(): boolean;
close(): void;
}
/** Plugin-wide capabilities consumed by the Excalidraw package. */
export interface ObsidianExcalidrawHostAdapter {
readonly protocolVersion: typeof OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION;
isDoubleTapEraserEnabled(): boolean;
getZoomToFitMaxLevel(): number;
isPenModeCrosshairVisible(): boolean;
isSingleFingerPanningEnabled(): boolean;
isDoubleClickTextEditingDisabled(): boolean;
getZoomStep(): number;
getZoomMin(): number;
getZoomMax(): number;
isContextMenuDisabled(): boolean;
shouldSyncElementLinkWithText(): boolean;
loadFontFromFile(filename: string): Promise<ArrayBuffer | undefined>;
getMermaid(): Promise<MermaidToExcalidrawLibProps>;
runAction(action: "anyFile" | "LaTeX" | "card"): void;
getLabel(key: string): string;
attachInlineLinkSuggester(inputEl: HTMLInputElement | HTMLTextAreaElement, widthWrapper?: HTMLElement, container?: HTMLDivElement | null, suppressPlaceholder?: boolean): ObsidianKeyBlocker;
}
/** Idempotent cleanup returned when a package host is configured. */
export type ObsidianExcalidrawHostDisposer = () => void;
```
@@ -1,35 +0,0 @@
/*
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
```js*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const drawIO = app.plugins.plugins["drawio-obsidian"];
if(!drawIO || !drawIO?._loaded) {
new Notice("Can't find the draw.io diagram plugin");
}
filename = await utils.inputPrompt("Diagram name?");
if(!filename) return;
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
const filepath = await ea.getAttachmentFilepath(filename);
if(!filepath) return;
const leaf = app.workspace.getLeaf('tab')
if(!leaf) return;
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="&lt;mxGraphModel&gt;&lt;root&gt;&lt;mxCell id=&quot;0&quot;/&gt;&lt;mxCell id=&quot;1&quot; parent=&quot;0&quot;/&gt;&lt;/root&gt;&lt;/mxGraphModel&gt;"></svg>`);
await ea.addImage(0,0,file);
await ea.addElementsToView(true,true);
leaf.setViewState({
type: "diagram-edit",
state: {
file: filepath
}
});
```
@@ -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
@@ -3378,11 +3378,36 @@ const zoomToFit = (mode) => {
elementID: sel.id,
level: nextLevel
}
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: getZoom(nextLevel),
animate: true
});
const targetZoom = getZoom(nextLevel);
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent([sel], {
fitToViewport: true,
viewportZoomFactor: targetZoom,
animate: true
});
} else {
// For the new API, we calculate a target rect centered on the element
// with dimensions that will force 'fit: "contain"' to reach our target zoom.
const appState = api().getAppState();
const targetW = appState.width / targetZoom;
const targetH = appState.height / targetZoom;
const cx = sel.x + sel.width / 2;
const cy = sel.y + sel.height / 2;
api().setViewport({
target: {
x: cx - targetW / 2,
y: cy - targetH / 2,
width: targetW,
height: targetH
},
fit: "contain",
animation: true
});
}
}
}
@@ -3411,10 +3436,20 @@ const focusSelected = () => {
if (!sel) return;
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
api().scrollToContent(sel, {
fitToContent: false,
animate: true,
});
} else {
// fit: "none" recenters at the current zoom without changing it
api().setViewport({
target: [sel],
fit: "none",
animation: true
});
}
};
const getMindmapOrder = (node) => {
@@ -83,4 +83,24 @@ Open the script you are interested in and save it to your Obsidian Vault includi
|[Transfer TextElements to Excalidraw markdown metadata](Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md)|The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Zoom to Fit Selected Elements](Zoom%20to%20Fit%20Selected%20Elements.md)|Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)||[@zsviczian](https://github.com/zsviczian)|
|[Hardware Eraser Suppoer](Hardware%20Eraser%20Support.md)|Allows the use of pen inversion/hardware erasers on supported pens.|[@threethan](https://github.com/threethan)|
|[Hardware Eraser Suppoer](Auto%20Draw%20for%20Pen.md)|Automatically switched from the Select tool to the Draw tool when a pen is hovered, and then back.|[@threethan](https://github.com/threethan)|
|[Hardware Eraser Suppoer](Auto%20Draw%20for%20Pen.md)|Automatically switched from the Select tool to the Draw tool when a pen is hovered, and then back.|[@threethan](https://github.com/threethan)|
## Publishing a community script
The current Script Store reads metadata from `ea-scripts/script-store.json`. Add or update one catalog entry when publishing a script, plus the script file and its matching SVG icon/preview when applicable.
Run:
```bash
npm run script-store:check
npm run script-store:build
```
`script-store:build` validates `script-store.json` and updates `directory-info.json` only for script or icon files that are actually modified/new in the current Git working tree. It **does not recalculate historical timestamps**, and repeated builds preserve an already-updated value. When the repository was exported without `.git`, all existing mtimes are left untouched.
`index-new.md` is a frozen legacy catalog for older Excalidraw versions. Routine Script Store publishing must not generate or modify it. New scripts added only to `script-store.json` are intentionally unavailable in older plugin versions unless a maintainer explicitly updates the legacy catalog separately.
Do not hand-edit unrelated `mtime` values. The plugin still uses these timestamps for backward-compatible script update detection.
### Beta release compatibility
Released 2.27.x clients fetch `ea-scripts/index-new.md` and `ea-scripts/directory-info.json` directly from the repository `master` branch at runtime. Keep `index-new.md` unchanged during routine 2.28 Script Store work. `directory-info.json` may still advance for scripts/icons that are actually updated, preserving the established update behavior for scripts already present in the legacy catalog.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,227 @@
/*
This script generates a Voronoi diagram from selected elements on the drawing canvas.
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
- Frame width (default: 100)
- Roughness (default: 0)
- Stroke width (default: 2)
- Grouping (default: checked)
Setting parameters could be set back to default values by click on button 'Default'.
Check info button for howto help during applying the script.
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
```js*/
// ExcalidrawAutomate: Voronoi Diagram Generator
ea.clear();
const DEFAULTS = {
frameWidth: 100,
roughness: 0,
strokeWidth: 2,
groupVoronoi: true
};
let config = ea.getScriptSettings() || { ...DEFAULTS };
// --- UI SETTINGS MODAL ---
async function openSettings() {
return new Promise((resolve) => {
const modal = new ea.obsidian.Modal(app);
modal.contentEl.style.padding = "20px";
// Header container with Title and Info Button
const headerContainer = modal.contentEl.createDiv();
headerContainer.style.display = "flex";
headerContainer.style.justifyContent = "space-between";
headerContainer.style.alignItems = "center";
headerContainer.style.marginBottom = "20px";
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
// Info button using Obsidian's native icon
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
btnInfo.setAttribute("aria-label", "Information & Help");
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
// Info modal content on click
btnInfo.onclick = () => {
const infoModal = new ea.obsidian.Modal(app);
infoModal.contentEl.style.padding = "20px";
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
// Native Obsidian Icon as HTML string
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
const p = infoModal.contentEl.createEl("p");
p.innerHTML = `
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
<div line-height: 1.4;">
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
- <b>Frame width:</b> Spacing around the diagram.<br>
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
- <b>Stroke width:</b> Line thickness.<br>
- <b>Grouping:</b> Group generated cells together.<br>
</div>
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
</div><br>
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
</span>
`;
infoModal.open();
};
const inputs = {};
// Helper function to create input rows
const createInput = (label, key, type = "number") => {
const container = modal.contentEl.createDiv();
container.style.marginBottom = "15px";
container.createEl("label", { text: label });
const input = container.createEl("input", { type: type });
input.style.display = "block";
input.style.marginTop = "5px";
input.value = config[key];
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
inputs[key] = input;
};
createInput("Frame width:", "frameWidth");
createInput("Roughness (0-3):", "roughness");
createInput("Stroke width:", "strokeWidth");
const checkContainer = modal.contentEl.createDiv();
checkContainer.style.marginBottom = "25px";
checkContainer.createEl("label", { text: "Grouping: " });
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
inputs.groupVoronoi.checked = config.groupVoronoi;
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
// Button container
const btnContainer = modal.contentEl.createDiv();
btnContainer.style.display = "flex";
btnContainer.style.gap = "10px";
btnContainer.style.justifyContent = "flex-end";
const btnDefault = btnContainer.createEl("button", { text: "Default" });
const btnOk = btnContainer.createEl("button", { text: "OK" });
btnDefault.onclick = () => {
config = { ...DEFAULTS };
inputs.frameWidth.value = config.frameWidth;
inputs.roughness.value = config.roughness;
inputs.strokeWidth.value = config.strokeWidth;
inputs.groupVoronoi.checked = config.groupVoronoi;
new Notice("Settings reset to default");
};
btnOk.onclick = () => {
ea.setScriptSettings(config);
modal.close();
resolve(true);
};
modal.open();
});
}
// Wait for user to configure settings
const proceed = await openSettings();
if (!proceed) return;
// --- ALGORITHM & EXECUTION ---
const els = ea.getViewSelectedElements();
if (els.length < 2) {
new Notice("Please select at least two items!");
return;
}
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
if (seeds.length < 2) {
new Notice("Please select at least two items!");
return;
}
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
const bbox = [
{ x: minX, y: minY },
{ x: maxX, y: minY },
{ x: maxX, y: maxY },
{ x: minX, y: maxY }
];
function clipPolygon(poly, p1, p2) {
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
const intersect = (a, b) => {
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
if (den === 0) return null;
const t = -num / den;
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
};
const result = [];
for (let i = 0; i < poly.length; i++) {
const cur = poly[i];
const prev = poly[(i - 1 + poly.length) % poly.length];
const curIn = isInside(cur);
const prevIn = isInside(prev);
if (curIn !== prevIn) {
const ix = intersect(prev, cur);
if (ix) result.push(ix);
}
if (curIn) result.push(cur);
}
return result;
}
const polygons = seeds.map((s, i) => {
let poly = [...bbox];
seeds.forEach((_, j) => {
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
});
return poly;
});
ea.style.roughness = config.roughness;
ea.style.strokeWidth = config.strokeWidth;
ea.style.backgroundColor = "transparent";
const ids = [];
for (const poly of polygons) {
if (poly.length < 3) continue;
const points = poly.map(p => [p.x, p.y]);
points.push(points[0]);
ids.push(ea.addLine(points));
}
if (config.groupVoronoi && ids.length > 0) {
ea.addToGroup(ids);
}
await ea.addElementsToView(false, false);
// Clear selection so nothing remains selected on the canvas
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
new Notice("Voronoi diagram created!");
```
@@ -1,13 +1,23 @@
# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs once per Excalidraw plugin load using the plugin-global EA and utils.executionSource === 'plugin-startup'. Use ea.registerCleanup() for external listeners, timers, observers, or subscriptions that must be released when Excalidraw unloads. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
### Template
```js
/*
#exclude
```js*/
/**
* Startup scripts receive the plugin-global EA for the plugin lifetime and
* utils.executionSource === "plugin-startup". Register cleanup for resources
* outside EA so plugin reload/unload cannot accumulate them.
*/
// const ref = app.workspace.on("file-open", (file) => {});
// ea.registerCleanup(() => app.workspace.offref(ref));
//
// const interval = window.setInterval(() => {}, 1000);
// ea.registerCleanup(() => window.clearInterval(interval));
/**
* If set, this callback is triggered when the user closes an Excalidraw view.
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
File diff suppressed because it is too large. Load diff
+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
+43 -5
View File
@@ -17,11 +17,49 @@ You will be able to access your scripts from Excalidraw via the Obsidian Command
![image](https://user-images.githubusercontent.com/14358394/145673652-6b1713e2-edc8-4bc8-8246-3f8df8a4b273.png)
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
![image](https://user-images.githubusercontent.com/14358394/145673633-83b6c969-cead-429b-9721-fd047f980279.png)
## Script development
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
![image](https://user-images.githubusercontent.com/14358394/145673633-83b6c969-cead-429b-9721-fd047f980279.png)
## EA script execution lifecycles
`utils.executionSource` describes why the current top-level script invocation
happened. It does not indicate whether the source was compiled previously,
whether the script has run before, or whether runtime state was retained.
| Trigger | `utils.executionSource` | EA received | Approximate lifetime |
| --- | --- | --- | --- |
| Script button, command, or hotkey | `manual` | fresh view EA | existing ordinary script/view lifecycle |
| Plugin startup script | `plugin-startup` | global plugin EA | plugin lifetime |
| `registerAutostart()` attachment | `view-autostart` | fresh view-local EA | view lifetime |
| Persisted sidepanel reconstruction | `sidepanel-restore` | sidepanel host EA | sidepanel tab lifetime |
| Sidepanel script reload | `sidepanel-reload` | reloaded sidepanel host EA | sidepanel tab lifetime |
| `excalidraw-onload-script` | `drawing-onload` | view-local EA | drawing/view lifetime |
Compilation caching is transparent: compiled JavaScript may be shared while
unchanged, but each invocation retains its existing EA ownership and execution
semantics. Manual execution remains repeatable even for a script that also uses
view autostart.
Use `ea.registerCleanup()` for resources that EA does not own directly:
```js
const ref = app.workspace.on("file-open", handler);
ea.registerCleanup(() => app.workspace.offref(ref));
window.addEventListener("resize", handler);
ea.registerCleanup(() => window.removeEventListener("resize", handler));
const interval = window.setInterval(callback, 1000);
ea.registerCleanup(() => window.clearInterval(interval));
```
Cleanup runs when that particular EA instance is destroyed, so its exact
lifetime depends on whether it is the plugin-startup EA, a view-local EA, or a
sidepanel host EA. The function returned by `registerCleanup()` unregisters the
callback without executing it.
## Script development
An Excalidraw script will automatically receive two objects:
- `ea`: The Script Engine will initialize the `ea` object including setting the active view to the View from which the script was called.
- `utils`: I have borrowed functions exposed on utils from [QuickAdd](https://github.com/chhoumann/quickadd/blob/master/docs/QuickAddAPI.md), though currently not all QuickAdd utility functions are implemented in Excalidraw. As of now, these are the available functions. See the example below for details.
@@ -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.
+127
View File
@@ -0,0 +1,127 @@
# Automate anything with Excalidraw
![Automate anything](../images/banner-automate-anything.png)
Excalidraw Automate scripts are small programs that run inside the Obsidian Excalidraw plugin. They can automate repetitive drawing work, build custom tools and interfaces, work with files in your Obsidian vault, and combine several steps of a workflow into a single command.
The useful question is no longer _“does a community script already exist for this?”_ but _“what would I like Excalidraw to do for me?”_
## The easiest way to create your own script
Use the **[ExcalidrawAutomate script workspace](https://github.com/zsviczian/ea-script-template)**. It is a GitHub template designed for developing one or many Excalidraw Automate scripts with modern tooling and AI coding agents.
The repository already contains:
- Excalidraw Automate API types and reference material for AI agents.
- Agent instructions and practical API-usage examples.
- Script scaffolding, linting, type checking, bundling, and preview support.
- A clean source layout for keeping reusable helpers separate from individual scripts.
- An update workflow so your script repository can receive improvements from the template without replacing your own scripts and guidance.
### Quick start
1. Open [zsviczian/ea-script-template](https://github.com/zsviczian/ea-script-template) and choose **Use this template → Create a new repository**.
2. Clone your new repository and install its dependencies with Node 22.13 or newer.
3. Create a script:
```bash
npm install
npm run new-script -- --name "My Script"
```
4. Tell your AI coding agent what you want the script to accomplish. Describe the workflow, the user interaction, and what should happen on the Excalidraw canvas or in the Obsidian vault.
5. Ask the agent to read the repository instructions and the bundled Excalidraw Automate references before implementing the script.
6. Validate and build:
```bash
npm run check
npm run build
```
7. Copy the generated `.md` script and its preview SVG from `build/` into the Script Engine folder configured in Excalidraw settings. Run the script from an Excalidraw drawing.
> **Important:** files under `src/scripts/{slug}/` are development source files. In particular, `src/scripts/{slug}/main.ts` is **not** a script you can copy into Obsidian and run directly. After creating or changing a script, ask your coding agent to run `npm run build`, or run it yourself. The ready-to-run Script Engine artifact is generated under `build/{slug}/`.
The generated `.md` file contains executable JavaScript for the Excalidraw Script Engine; it is not an Obsidian plugin. If `.md` and `.js` versions with the same script name are both present, Excalidraw prefers the `.md` version.
### Keep your script workspace up to date
The template can update its shared tooling, Excalidraw Automate types, agent guidance, and build infrastructure without replacing your scripts. A good update sequence is:
```bash
npm run update-template:check
npm run update-template
npm install
npm run check
npm run build
```
Run `npm install` after `npm run update-template` because a template update may change `package.json` or `package-lock.json`. Then run the checks and rebuild your scripts before testing them in Obsidian.
## Why AI agents work so well for scripting
The workflow demonstrated in **[AI Scripting Superpowers](https://youtu.be/6BjhUyfS4iM)** is still the core idea:
1. Give the AI accurate Excalidraw Automate API context.
2. Describe a concrete problem and the behavior you want.
3. Let the AI build a first version.
4. Run it in Obsidian and report the exact error or behavior that needs improvement.
5. Iterate until the workflow feels natural.
The video builds a Layer Manager as an example: a purpose-built tool that did not already exist in the script library. The current script workspace takes this workflow further. Instead of manually feeding a large training document to an AI chat, the repository carries agent instructions, API references, types, examples, and validation tools alongside your source code.
You do not need to start by knowing the Excalidraw Automate API. Start by knowing what you want to automate.
## What can a script automate?
Practically anything that Excalidraw Automate and Obsidian expose, for example:
- Batch-format or rearrange selected elements.
- Build specialized drawing, layout, connector, annotation, or image tools.
- Create custom modals, controls, and persistent sidepanels.
- Create, rename, link, embed, or update files in your vault.
- Generate dashboards or drawings from vault data.
- Add startup, drawing-load, or long-lived automation where appropriate.
- Export drawings, images, or structured information.
- Combine several repetitive actions into a single command tailored to your workflow.
Browse the Community Script Store for examples and inspiration before starting from scratch.
## A few authoring rules worth knowing
The template's authoring guidance handles the details, but these principles matter:
- Work in `src/scripts/{slug}/`; treat `build/` as generated output. Do not hand-edit the built script as your source of truth.
- Excalidraw scene elements are immutable; edit them through the Excalidraw Automate workbench and commit the result back to the view.
- The Script Engine injects `ea` and `utils`. Runtime Obsidian APIs are available through `ea.obsidian`.
- Scripts with UI or long-lived behavior need deliberate cleanup and lifecycle handling.
- Test cancellation, empty selections, undo/save behavior, view changes, and any mobile-specific UI on a physical mobile device.
- Run `npm run check` and `npm run build` before testing or distributing a changed script.
## Scripts are code
A script can change your drawing and can also work with files in your vault. Treat scripts like any other code you install: use sources you trust, review unfamiliar scripts, keep backups, and test destructive workflows on disposable data first.
## Share a script with the community
Community scripts are maintained in the central [Obsidian Excalidraw repository](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts). Publish the **built** `.md` artifact, not `src/scripts/{slug}/main.ts`, together with its matching SVG icon/preview when applicable and an entry in `ea-scripts/script-store.json`.
The current Script Store workflow is:
```bash
npm run script-store:check
npm run script-store:build
```
`script-store:build` validates the catalog and updates `directory-info.json` only for script or icon files that actually changed. Do not hand-edit unrelated `mtime` values: existing timestamps are part of backward-compatible update detection.
`ea-scripts/index-new.md` is the frozen legacy catalog for older Excalidraw versions. Routine Script Store publishing should not modify it. New scripts are published through `script-store.json` unless a maintainer deliberately updates the legacy catalog separately.
For the repository-specific publishing rules and current compatibility notes, see [ea-scripts/README.md](../ea-scripts/README.md).
## More resources
- [ExcalidrawAutomate script workspace](https://github.com/zsviczian/ea-script-template)
- [AI Scripting Superpowers](https://youtu.be/6BjhUyfS4iM)
- [Excalidraw Script Engine documentation](https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html)
- [Excalidraw Automate API declaration](API/ExcalidrawAutomate.d.ts)
-33
View File
@@ -1,33 +0,0 @@
/*
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
```js*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const drawIO = app.plugins.plugins["drawio-obsidian"];
if(!drawIO || !drawIO?._loaded) {
new Notice("Can't find the draw.io diagram plugin");
}
filename = await utils.inputPrompt("Diagram name?");
if(!filename) return;
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
const filepath = await ea.getAttachmentFilepath(filename);
if(!filepath) return;
const leaf = app.workspace.getLeaf('tab')
if(!leaf) return;
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="&lt;mxGraphModel&gt;&lt;root&gt;&lt;mxCell id=&quot;0&quot;/&gt;&lt;mxCell id=&quot;1&quot; parent=&quot;0&quot;/&gt;&lt;/root&gt;&lt;/mxGraphModel&gt;"></svg>`);
await ea.addImage(0,0,file);
await ea.addElementsToView(true,true);
leaf.setViewState({
type: "diagram-edit",
state: {
file: filepath
}
});
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="24 26 68 68" stroke="#000"><path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3.553" d="m58.069 43.384-17.008 29.01"/><path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3.501" d="m58.068 43.384 17.008 29.01"/><path fill="#000" d="M52.773 77.084a3.564 3.564 0 0 1-3.553 3.553H36.999a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553h12.222a3.564 3.564 0 0 1 3.553 3.553v9.379zM67.762 48.074a3.564 3.564 0 0 1-3.553 3.553H51.988a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553H64.21a3.564 3.564 0 0 1 3.553 3.553v9.379zM82.752 77.084a3.564 3.564 0 0 1-3.553 3.553H66.977a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553h12.222a3.564 3.564 0 0 1 3.553 3.553v9.379z"/></svg>

Before

Width:  |  Height:  |  Size: 830 B

@@ -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

+106 -86
View File
@@ -1,86 +1,106 @@
# Excalidraw Script Engine scripts library
【English | [简体中文](../docs/zh-cn/ea-scripts/README.md)】
Click to watch the intro video:
[![Script Engine](https://user-images.githubusercontent.com/14358394/145684531-8d9c2992-59ac-4ebc-804a-4cce1777ded2.jpg)](https://youtu.be/hePJcObHIso)
> **Warning**
> There is an easier way to install/manage scripts than what is shown in this video
See the [Excalidraw Script Engine](https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html) documentation for more details.
## How to install scripts into your Obsidian Vault
To install one of the built-in scripts:
- Open up an excalidraw drawing in Obsidian
- In the pane dropdown menu select "Install or update Excalidraw Scripts"
- Click on one of the available scripts
- Click on "Install this script" (note if the script is already installed you will instead see an option to update it)
- Restart Obsidian so the script will be picked up
Note: By default this will install the script into your vault in the `Excalidraw/Scripts/Downloaded` folder
<details><summary>Manual installation of scripts</summary>
Open the script you are interested in and save it to your Obsidian Vault including the first line `/*`, or open it in "Raw" and copy the entire contents to Obsidian.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-download-raw.jpg)
</details>
## List of available scripts
|Title|Description|Icon|Contributor|
|----|----|----|----|
|[Add Connector Point](Add%20Connector%20Point.md)|This script will add a small circle to the top left of each text element in the selection and add the text and the "bullet point" into a group.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-bullet-point.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Link to Existing File and Open](Add%20Link%20to%20Existing%20File%20and%20Open.md)|Prompts for a file from the vault. Adds a link to the selected element pointing to the selected file. You can control in settings to open the file in the current active pane or an adjacent pane.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-and-open.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Link to New Page and Open](Add%20Link%20and%20Open%20Page.md)|Prompts for filename. Offers option to create and open a new Markdown or Excalidraw document. Adds link pointing to the new file, to the selected objects in the drawing. You can control in settings to open the file in the current active pane or an adjacent pane.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-to-new-page-and-pen.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Next Step in Process](Add%20Link%20to%20New%20Page%20and%20Open.md)|This script will prompt you for the title of the process step, then will create a stick note with the text. If an element is selected then the script will connect this new step with an arrow to the previous step (the selected element). If no element is selected, then the script assumes this is the first step in the process and will only output the sticky note with the text that was entered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-process-step.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split Ellipse](Boolean%20Operations.md)|With This Script it is possible to make boolean Operations on Shapes.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-boolean-operations-showcase.png)|[@GColoy](https://github.com/GColoy)|
|[Box Each Selected Groups](Box%20Each%20Selected%20Groups.md)|This script will add encapsulating boxes around each of the currently selected groups in Excalidraw.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-each-selected-groups.png)|[@1-2-3](https://github.com/1-2-3)|
|[Box Selected Elements](Box%20Selected%20Elements.md)|This script will add an encapsulating box around the currently selected elements in Excalidraw.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-elements.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Change shape of selected elements](Change%20shape%20of%20selected%20elements.md)|The script allows you to change the shape of selected Rectangles, Diamonds and Ellipses|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-change-shape.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Connect elements](Connect%20elements.md)|This script will connect two objects with an arrow. If either of the objects are a set of grouped elements (e.g. a text element grouped with an encapsulating rectangle), the script will identify these groups, and connect the arrow to the largest object in the group (assuming you want to connect the arrow to the box around the text element).|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-connect-elements.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Convert freedraw to line](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20freedraw%20to%20line.md)|Convert selected freedraw objects into editable lines. This will allow you to adjust your drawings by dragging line points and will also allow you to select shape fill in case of enclosed lines. You can adjust conversion point density in settings|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-convert-freedraw-to-line.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Convert selected text elements to sticky notes](Convert%20selected%20text%20elements%20to%20sticky%20notes.md)|Converts selected plain text elements to sticky notes with transparent background and transparent stroke color. Essentially converts text element into a wrappable format.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-textelement-to-transparent-stickynote.png)|[@zsviczian](https://github.com/zsviczian)|
|[Convert text to link with folder and alias](Convert%20text%20to%20link%20with%20folder%20and%20alias.md)|Converts text elements to links pointing to a file in a selected folder and with the alias set as the original text. The script will prompt the user to select an existing folder from the vault.|`original text` => `[[selected folder/original text\|original text]]`|[@zsviczian](https://github.com/zsviczian)|
|[Copy Selected Element Styles to Global](Copy%20Selected%20Element%20Styles%20to%20Global)|This script will copy styles of any selected element into Excalidraw's global styles.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png)|[@1-2-3](https://github.com/1-2-3)|
|[Create new markdown file and embed into active drawing](Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md)|The script will prompt you for a filename, then create a new markdown document with the file name provided, open the new markdown document in an adjacent pane, and embed the markdown document into the active Excalidraw drawing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-create-and-embed-new-markdown-file.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Darken background color](Darken%20background%20color.md)|This script darkens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect. In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png)|[@1-2-3](https://github.com/1-2-3)|
|[Elbow connectors](Elbow%20connectors.md)|This script converts the selected connectors to elbows.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/elbow-connectors.png)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles horizontally keep text centered](Expand%20rectangles%20horizontally%20keep%20text20%centered.md)|This script expands the width of the selected rectangles until they are all the same width and keep the text centered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles horizontally](Expand%20rectangles%20horizontally.md)|This script expands the width of the selected rectangles until they are all the same width.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles vertically keep text centered](Expand%20rectangles%20vertically%20keep%20text%20centered.md)|This script expands the height of the selected rectangles until they are all the same height and keep the text centered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles vertically](Expand%20rectangles%20vertically.md)|This script expands the height of the selected rectangles until they are all the same height.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed horizontal distance between centers](Fixed%20horizontal%20distance%20between%20centers.md)|This script arranges the selected elements horizontally with a fixed center spacing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-horizontal-distance-between-centers.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed inner distance](Fixed%20inner%20distance.md)|This script arranges selected elements and groups with a fixed inner distance.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-inner-distance.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed spacing](Fixed%20spacing.md)|The script arranges the selected elements horizontally with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fix-space-demo.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed vertical distance between centers](Fixed%20vertical%20distance%20between%20centers.md)|This script arranges the selected elements vertically with a fixed center spacing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance-between-centers.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed vertical distance](Fixed%20vertical%20distance.md)|The script arranges the selected elements vertically with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance.png)|[@1-2-3](https://github.com/1-2-3)|
|[Lighten background color](Lighten%20background%20color.md)|This script lightens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect.In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png)|[@1-2-3](https://github.com/1-2-3)|
|[Mindmap connector](Mindmap%20connector.md)|This script creates mindmap like lines (only right side and down available currently) for selected elements. The line will start according to the creation time of the elements. So you should create the header element first.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/mindmap%20connector.png)|[@xllowl](https://github.com/xllowl)|
|[Modify background color opacity](Modify%20background%20color%20opacity.md)|This script changes the opacity of the background color of the selected boxes. The default background color in Excalidraw is so dark that the text is hard to read. You can lighten the color a bit by setting transparency. And you can tweak the transparency over and over again until you're happy with it. Although excalidraw has the opacity option in its native property Settings, it also changes the transparency of the border. Use this script to change only the opacity of the background color without affecting the border.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-modify-background-color-opacity.png)|[@1-2-3](https://github.com/1-2-3)|
|[Normalize Selected Arrows](Normalize%20Selected%20Arrows.md)|This script will reset the start and end positions of the selected arrows. The arrow will point to the center of the connected box and will have a gap of 8px from the box.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-normalize-selected-arrows.png)|[@1-2-3](https://github.com/1-2-3)|
|[OCR - Optical Character Recognition](OCR%20-%20Optical%20Character%20Recognition.md)|The script will 1) send the selected image file to [taskbone.com](https://taskbone.com) to extract the text from the image, and 2) will add the text to your drawing as a text element.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Organic Line](Organic%20Line.md)|Converts selected freedraw lines such that pencil pressure will decrease from maximum to minimum from the beginning of the line to its end. The resulting line is placed at the back of the layers, under all other items. Helpful when drawing organic mindmaps.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-organic-line.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Repeat Elements](Repeat%20Elements.md)|This script will detect the difference between 2 selected elements, including position, size, angle, stroke and background color, and create several elements that repeat these differences based on the number of repetitions entered by the user.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-repeat-elements.png)|[@1-2-3](https://github.com/1-2-3)|
|[Reset LaTeX Size](Reset%20LaTeX%20Size.md)|Reset the sizes of embedded LaTeX equations to the default sizes or a multiple of the default sizes.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reset-latex.jpg)|[@firai](https://github.com/firai)|
|[Reverse arrows](Reverse%20arrows.md)|Reverse the direction of **arrows** within the scope of selected elements.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reverse-arrow.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Scribble Helper](Scribble%20Helper.md)|iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the creates a text element at pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then opens the input prompt where you can modify this text with scribble.|![]('https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-scribble-helper.jpg')|[@zsviczian](https://github.com/zsviczian)|
|[Select Elements of Type](Select%20Elements%20of%20Type.md)|Prompts you with a list of the different element types in the active image. Only elements of the selected type will be selected on the canvas. If nothing is selected when running the script, then the script will process all the elements on the canvas. If some elements are selected when the script is executed, then the script will only process the selected elements.<br>The script is useful when, for example, you want to bring to front all the arrows, or want to change the color of all the text elements, etc.|![]('https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-select-element-of-type.jpg')|[@zsviczian](https://github.com/zsviczian)|
|[Set background color of unclosed line object by adding a shadow clone](Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md)|Use this script to set the background color of unclosed (i.e. open) line objects by creating a clone of the object. The script will set the stroke color of the clone to transparent and will add a straight line to close the object. Use settings to define the default background color, the fill style, and the strokeWidth of the clone. By default the clone will be grouped with the original object, you can disable this also in settings.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Dimensions](Set%20Dimensions.md)|Currently there is no way to specify the exact location and size of objects in Excalidraw. You can bridge this gap with the following simple script.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Font Family](Set%20Font%20Family.md)|Sets font family of the text block (Virgil, Helvetica, Cascadia). Useful if you want to set a keyboard shortcut for selecting font family.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-font-family.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Grid](Set%20Grid.md)|The default grid size in Excalidraw is 20. Currently there is no way to change the grid size via the user interface. This script offers a way to bridge this gap.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-grid.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Link Alias](Set20%Link20%Alias.md)|Iterates all of the links in the selected TextElements and prompts the user to set or modify the alias for each link found.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-set-link-alias.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set stroke width of selected elements](Set%20Stroke%20Width%20of%20Selected%20Elements.md)|This script will set the stroke width of selected elements. This is helpful, for example, when you scale freedraw sketches and want to reduce or increase their line width.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-stroke-width.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split text by lines](Split%20text%20by%20lines.md)|Split lines of text into separate text elements for easier reorganization|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-split-lines.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Text Alignment](Set%20Text%20Alignment.md)|Sets text alignment of text block (cetner, right, left). Useful if you want to set a keyboard shortcut for selecting text alignment.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-align.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split Ellipse](Split%20Ellipse.md)|This script splits an ellipse at any point where a line intersects it.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-splitEllipse-demo1.png)|[@GColoy](https://github.com/GColoy)|
|[TheBrain-navigation](TheBrain-navigation.md)|An Excalidraw based graph user interface for your Vault. Requires the [Dataview plugin](https://github.com/blacksmithgu/obsidian-dataview). Generates a graph view similar to that of [TheBrain](https://TheBrain.com) plex. Watch introduction to this script on [YouTube](https://youtu.be/plYobK-VufM).|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/TheBrain.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Toggle Fullscreen on Mobile](Toggle%20Fullscreen%20on%20Mobile.md)|Hides Obsidian workspace leaf padding and header (based on option in settings, default is "hide header" = false) which will take Excalidraw to full screen. ⚠ Note that if the header is not visible, it will be very difficult to invoke the command palette to end full screen. Only hide the header if you have a keyboard or you've practiced opening command palette!|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/ea-toggle-fullscreen.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Toggle Grid](Toggle%20Grid.md)|Toggles the grid.||[@GColoy](https://github.com/GColoy)|
|[Transfer TextElements to Excalidraw markdown metadata](Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md)|The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Zoom to Fit Selected Elements](Zoom%20to%20Fit%20Selected%20Elements.md)|Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)||[@zsviczian](https://github.com/zsviczian)|
|[Hardware Eraser Suppoer](Hardware%20Eraser%20Support.md)|Allows the use of pen inversion/hardware erasers on supported pens.|[@threethan](https://github.com/threethan)|
|[Hardware Eraser Suppoer](Auto%20Draw%20for%20Pen.md)|Automatically switched from the Select tool to the Draw tool when a pen is hovered, and then back.|[@threethan](https://github.com/threethan)|
# Excalidraw Script Engine scripts library
【English | [简体中文](../docs/zh-cn/ea-scripts/README.md)】
Click to watch the intro video:
[![Script Engine](https://user-images.githubusercontent.com/14358394/145684531-8d9c2992-59ac-4ebc-804a-4cce1777ded2.jpg)](https://youtu.be/hePJcObHIso)
> **Warning**
> There is an easier way to install/manage scripts than what is shown in this video
See the [Excalidraw Script Engine](https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html) documentation for more details.
## How to install scripts into your Obsidian Vault
To install one of the built-in scripts:
- Open up an excalidraw drawing in Obsidian
- In the pane dropdown menu select "Install or update Excalidraw Scripts"
- Click on one of the available scripts
- Click on "Install this script" (note if the script is already installed you will instead see an option to update it)
- Restart Obsidian so the script will be picked up
Note: By default this will install the script into your vault in the `Excalidraw/Scripts/Downloaded` folder
<details><summary>Manual installation of scripts</summary>
Open the script you are interested in and save it to your Obsidian Vault including the first line `/*`, or open it in "Raw" and copy the entire contents to Obsidian.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-download-raw.jpg)
</details>
## List of available scripts
|Title|Description|Icon|Contributor|
|----|----|----|----|
|[Add Connector Point](Add%20Connector%20Point.md)|This script will add a small circle to the top left of each text element in the selection and add the text and the "bullet point" into a group.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-bullet-point.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Link to Existing File and Open](Add%20Link%20to%20Existing%20File%20and%20Open.md)|Prompts for a file from the vault. Adds a link to the selected element pointing to the selected file. You can control in settings to open the file in the current active pane or an adjacent pane.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-and-open.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Link to New Page and Open](Add%20Link%20and%20Open%20Page.md)|Prompts for filename. Offers option to create and open a new Markdown or Excalidraw document. Adds link pointing to the new file, to the selected objects in the drawing. You can control in settings to open the file in the current active pane or an adjacent pane.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-to-new-page-and-pen.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Add Next Step in Process](Add%20Link%20to%20New%20Page%20and%20Open.md)|This script will prompt you for the title of the process step, then will create a stick note with the text. If an element is selected then the script will connect this new step with an arrow to the previous step (the selected element). If no element is selected, then the script assumes this is the first step in the process and will only output the sticky note with the text that was entered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-process-step.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split Ellipse](Boolean%20Operations.md)|With This Script it is possible to make boolean Operations on Shapes.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-boolean-operations-showcase.png)|[@GColoy](https://github.com/GColoy)|
|[Box Each Selected Groups](Box%20Each%20Selected%20Groups.md)|This script will add encapsulating boxes around each of the currently selected groups in Excalidraw.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-each-selected-groups.png)|[@1-2-3](https://github.com/1-2-3)|
|[Box Selected Elements](Box%20Selected%20Elements.md)|This script will add an encapsulating box around the currently selected elements in Excalidraw.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-elements.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Change shape of selected elements](Change%20shape%20of%20selected%20elements.md)|The script allows you to change the shape of selected Rectangles, Diamonds and Ellipses|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-change-shape.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Connect elements](Connect%20elements.md)|This script will connect two objects with an arrow. If either of the objects are a set of grouped elements (e.g. a text element grouped with an encapsulating rectangle), the script will identify these groups, and connect the arrow to the largest object in the group (assuming you want to connect the arrow to the box around the text element).|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-connect-elements.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Convert freedraw to line](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20freedraw%20to%20line.md)|Convert selected freedraw objects into editable lines. This will allow you to adjust your drawings by dragging line points and will also allow you to select shape fill in case of enclosed lines. You can adjust conversion point density in settings|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-convert-freedraw-to-line.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Convert selected text elements to sticky notes](Convert%20selected%20text%20elements%20to%20sticky%20notes.md)|Converts selected plain text elements to sticky notes with transparent background and transparent stroke color. Essentially converts text element into a wrappable format.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-textelement-to-transparent-stickynote.png)|[@zsviczian](https://github.com/zsviczian)|
|[Convert text to link with folder and alias](Convert%20text%20to%20link%20with%20folder%20and%20alias.md)|Converts text elements to links pointing to a file in a selected folder and with the alias set as the original text. The script will prompt the user to select an existing folder from the vault.|`original text` => `[[selected folder/original text\|original text]]`|[@zsviczian](https://github.com/zsviczian)|
|[Copy Selected Element Styles to Global](Copy%20Selected%20Element%20Styles%20to%20Global)|This script will copy styles of any selected element into Excalidraw's global styles.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png)|[@1-2-3](https://github.com/1-2-3)|
|[Create new markdown file and embed into active drawing](Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md)|The script will prompt you for a filename, then create a new markdown document with the file name provided, open the new markdown document in an adjacent pane, and embed the markdown document into the active Excalidraw drawing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-create-and-embed-new-markdown-file.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Darken background color](Darken%20background%20color.md)|This script darkens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect. In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png)|[@1-2-3](https://github.com/1-2-3)|
|[Elbow connectors](Elbow%20connectors.md)|This script converts the selected connectors to elbows.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/elbow-connectors.png)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles horizontally keep text centered](Expand%20rectangles%20horizontally%20keep%20text20%centered.md)|This script expands the width of the selected rectangles until they are all the same width and keep the text centered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles horizontally](Expand%20rectangles%20horizontally.md)|This script expands the width of the selected rectangles until they are all the same width.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles vertically keep text centered](Expand%20rectangles%20vertically%20keep%20text%20centered.md)|This script expands the height of the selected rectangles until they are all the same height and keep the text centered.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Expand rectangles vertically](Expand%20rectangles%20vertically.md)|This script expands the height of the selected rectangles until they are all the same height.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed horizontal distance between centers](Fixed%20horizontal%20distance%20between%20centers.md)|This script arranges the selected elements horizontally with a fixed center spacing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-horizontal-distance-between-centers.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed inner distance](Fixed%20inner%20distance.md)|This script arranges selected elements and groups with a fixed inner distance.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-inner-distance.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed spacing](Fixed%20spacing.md)|The script arranges the selected elements horizontally with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fix-space-demo.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed vertical distance between centers](Fixed%20vertical%20distance%20between%20centers.md)|This script arranges the selected elements vertically with a fixed center spacing.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance-between-centers.png)|[@1-2-3](https://github.com/1-2-3)|
|[Fixed vertical distance](Fixed%20vertical%20distance.md)|The script arranges the selected elements vertically with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance.png)|[@1-2-3](https://github.com/1-2-3)|
|[Lighten background color](Lighten%20background%20color.md)|This script lightens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect.In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png)|[@1-2-3](https://github.com/1-2-3)|
|[Mindmap connector](Mindmap%20connector.md)|This script creates mindmap like lines (only right side and down available currently) for selected elements. The line will start according to the creation time of the elements. So you should create the header element first.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/mindmap%20connector.png)|[@xllowl](https://github.com/xllowl)|
|[Modify background color opacity](Modify%20background%20color%20opacity.md)|This script changes the opacity of the background color of the selected boxes. The default background color in Excalidraw is so dark that the text is hard to read. You can lighten the color a bit by setting transparency. And you can tweak the transparency over and over again until you're happy with it. Although excalidraw has the opacity option in its native property Settings, it also changes the transparency of the border. Use this script to change only the opacity of the background color without affecting the border.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-modify-background-color-opacity.png)|[@1-2-3](https://github.com/1-2-3)|
|[Normalize Selected Arrows](Normalize%20Selected%20Arrows.md)|This script will reset the start and end positions of the selected arrows. The arrow will point to the center of the connected box and will have a gap of 8px from the box.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-normalize-selected-arrows.png)|[@1-2-3](https://github.com/1-2-3)|
|[OCR - Optical Character Recognition](OCR%20-%20Optical%20Character%20Recognition.md)|The script will 1) send the selected image file to [taskbone.com](https://taskbone.com) to extract the text from the image, and 2) will add the text to your drawing as a text element.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Organic Line](Organic%20Line.md)|Converts selected freedraw lines such that pencil pressure will decrease from maximum to minimum from the beginning of the line to its end. The resulting line is placed at the back of the layers, under all other items. Helpful when drawing organic mindmaps.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-organic-line.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Repeat Elements](Repeat%20Elements.md)|This script will detect the difference between 2 selected elements, including position, size, angle, stroke and background color, and create several elements that repeat these differences based on the number of repetitions entered by the user.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-repeat-elements.png)|[@1-2-3](https://github.com/1-2-3)|
|[Reset LaTeX Size](Reset%20LaTeX%20Size.md)|Reset the sizes of embedded LaTeX equations to the default sizes or a multiple of the default sizes.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reset-latex.jpg)|[@firai](https://github.com/firai)|
|[Reverse arrows](Reverse%20arrows.md)|Reverse the direction of **arrows** within the scope of selected elements.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reverse-arrow.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Scribble Helper](Scribble%20Helper.md)|iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the creates a text element at pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then opens the input prompt where you can modify this text with scribble.|![]('https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-scribble-helper.jpg')|[@zsviczian](https://github.com/zsviczian)|
|[Select Elements of Type](Select%20Elements%20of%20Type.md)|Prompts you with a list of the different element types in the active image. Only elements of the selected type will be selected on the canvas. If nothing is selected when running the script, then the script will process all the elements on the canvas. If some elements are selected when the script is executed, then the script will only process the selected elements.<br>The script is useful when, for example, you want to bring to front all the arrows, or want to change the color of all the text elements, etc.|![]('https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-select-element-of-type.jpg')|[@zsviczian](https://github.com/zsviczian)|
|[Set background color of unclosed line object by adding a shadow clone](Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md)|Use this script to set the background color of unclosed (i.e. open) line objects by creating a clone of the object. The script will set the stroke color of the clone to transparent and will add a straight line to close the object. Use settings to define the default background color, the fill style, and the strokeWidth of the clone. By default the clone will be grouped with the original object, you can disable this also in settings.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Dimensions](Set%20Dimensions.md)|Currently there is no way to specify the exact location and size of objects in Excalidraw. You can bridge this gap with the following simple script.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Font Family](Set%20Font%20Family.md)|Sets font family of the text block (Virgil, Helvetica, Cascadia). Useful if you want to set a keyboard shortcut for selecting font family.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-font-family.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Grid](Set%20Grid.md)|The default grid size in Excalidraw is 20. Currently there is no way to change the grid size via the user interface. This script offers a way to bridge this gap.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-grid.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Link Alias](Set20%Link20%Alias.md)|Iterates all of the links in the selected TextElements and prompts the user to set or modify the alias for each link found.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-set-link-alias.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set stroke width of selected elements](Set%20Stroke%20Width%20of%20Selected%20Elements.md)|This script will set the stroke width of selected elements. This is helpful, for example, when you scale freedraw sketches and want to reduce or increase their line width.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-stroke-width.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split text by lines](Split%20text%20by%20lines.md)|Split lines of text into separate text elements for easier reorganization|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-split-lines.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Set Text Alignment](Set%20Text%20Alignment.md)|Sets text alignment of text block (cetner, right, left). Useful if you want to set a keyboard shortcut for selecting text alignment.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-align.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Split Ellipse](Split%20Ellipse.md)|This script splits an ellipse at any point where a line intersects it.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-splitEllipse-demo1.png)|[@GColoy](https://github.com/GColoy)|
|[TheBrain-navigation](TheBrain-navigation.md)|An Excalidraw based graph user interface for your Vault. Requires the [Dataview plugin](https://github.com/blacksmithgu/obsidian-dataview). Generates a graph view similar to that of [TheBrain](https://TheBrain.com) plex. Watch introduction to this script on [YouTube](https://youtu.be/plYobK-VufM).|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/TheBrain.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Toggle Fullscreen on Mobile](Toggle%20Fullscreen%20on%20Mobile.md)|Hides Obsidian workspace leaf padding and header (based on option in settings, default is "hide header" = false) which will take Excalidraw to full screen. ⚠ Note that if the header is not visible, it will be very difficult to invoke the command palette to end full screen. Only hide the header if you have a keyboard or you've practiced opening command palette!|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/ea-toggle-fullscreen.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Toggle Grid](Toggle%20Grid.md)|Toggles the grid.||[@GColoy](https://github.com/GColoy)|
|[Transfer TextElements to Excalidraw markdown metadata](Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md)|The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Zoom to Fit Selected Elements](Zoom%20to%20Fit%20Selected%20Elements.md)|Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)||[@zsviczian](https://github.com/zsviczian)|
|[Hardware Eraser Suppoer](Hardware%20Eraser%20Support.md)|Allows the use of pen inversion/hardware erasers on supported pens.|[@threethan](https://github.com/threethan)|
|[Hardware Eraser Suppoer](Auto%20Draw%20for%20Pen.md)|Automatically switched from the Select tool to the Draw tool when a pen is hovered, and then back.|[@threethan](https://github.com/threethan)|
## Publishing a community script
The current Script Store reads metadata from `ea-scripts/script-store.json`. Add or update one catalog entry when publishing a script, plus the script file and its matching SVG icon/preview when applicable.
Run:
```bash
npm run script-store:check
npm run script-store:build
```
`script-store:build` validates `script-store.json` and updates `directory-info.json` only for script or icon files that are actually modified/new in the current Git working tree. It **does not recalculate historical timestamps**, and repeated builds preserve an already-updated value. When the repository was exported without `.git`, all existing mtimes are left untouched.
`index-new.md` is a frozen legacy catalog for older Excalidraw versions. Routine Script Store publishing must not generate or modify it. New scripts added only to `script-store.json` are intentionally unavailable in older plugin versions unless a maintainer explicitly updates the legacy catalog separately.
Do not hand-edit unrelated `mtime` values. The plugin still uses these timestamps for backward-compatible script update detection.
### Beta release compatibility
Released 2.27.x clients fetch `ea-scripts/index-new.md` and `ea-scripts/directory-info.json` directly from the repository `master` branch at runtime. Keep `index-new.md` unchanged during routine 2.28 Script Store work. `directory-info.json` may still advance for scripts/icons that are actually updated, preserving the established update behavior for scripts already present in the legacy catalog.
+8998 -926
View File
File diff suppressed because it is too large. Load diff
+3 -11
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": 1789502464420
},
{
"fname": "Slideshow.svg",
@@ -471,14 +471,6 @@
"fname": "Excalidraw Collaboration Frame.svg",
"mtime": 1687881495985
},
{
"fname": "Create DrawIO file.md",
"mtime": 1688243858267
},
{
"fname": "Create DrawIO file.svg",
"mtime": 1688243858267
},
{
"fname": "Ellipse Selected Elements.md",
"mtime": 1690131476331
@@ -711,4 +703,4 @@
"fname": "VoronoiDiagramGenerator.svg",
"mtime": 1785564296587
}
]
]
+1 -8
View File
@@ -164,7 +164,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.svg"/></div>|[[#Create DrawIO file]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
@@ -340,12 +339,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</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/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
## Create DrawIO file
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.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/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="https://www.youtube.com/watch?v=DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Create new markdown file and embed into active drawing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
@@ -689,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
File diff suppressed because it is too large. Load diff
+14
View File
@@ -28,6 +28,20 @@ export default tseslint.config(
languageOptions: {
globals: {
...globals.browser,
// Buffer/NodeJS/BufferEncoding: genuine ambient Node types available
// in Obsidian's Electron environment (used e.g. in DataAdapter.fs
// callbacks in src/types/types.d.ts).
...globals.node,
// @types/react/global.d.ts declares this as a bare top-level
// `interface` (an ambient script, not a module), so it becomes a
// real global type alongside HTMLDivElement etc. -- not something
// that can be imported.
HTMLWebViewElement: 'readonly',
// NodeJS/BufferEncoding: ambient @types/node type/namespace names
// (globals.node above only covers runtime values like `Buffer`,
// not these TS-only type names).
NodeJS: 'readonly',
BufferEncoding: 'readonly',
},
parserOptions: {
projectService: {
Binary file not shown.

After

Width:  |  Height:  |  Size: 260 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

+2 -2
View File
@@ -1,11 +1,11 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.26.2",
"version": "2.28.0-beta.4",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
"authorUrl": "https://excalidraw-obsidian.online",
"authorUrl": "https://community.sketch-your-mind.com/em",
"fundingUrl": "https://ko-fi.com/zsolt",
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
"isDesktopOnly": false
+2 -2
View File
@@ -1,11 +1,11 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.26.2",
"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",
"authorUrl": "https://excalidraw-obsidian.online",
"authorUrl": "https://community.sketch-your-mind.com/em",
"fundingUrl": "https://ko-fi.com/zsolt",
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
"isDesktopOnly": false
Binary file not shown.
+60 -110
View File
@@ -13,22 +13,20 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.116",
"@zsviczian/excalidraw": "0.18.139",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
"gl-matrix": "^3.4.3",
"lz-string": "^1.5.0",
"monkey-around": "^2.3.0",
"nanoid": "^5.1.11",
"opentype.js": "^1.3.4",
"nanoid": "^5.1.16",
"pako": "^2.1.0",
"points-on-path": "^0.2.1",
"polybooljs": "^1.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"roughjs": "^4.5.2",
"yaml": "^2.9.0"
"react": "19.2.8",
"react-dom": "19.2.8",
"roughjs": "^4.5.2"
},
"devDependencies": {
"@babel/core": "^7.22.9",
@@ -52,19 +50,17 @@
"@types/chroma-js": "^3.1.1",
"@types/js-beautify": "^1.14.0",
"@types/node": "^22.19.19",
"@types/opentype.js": "^1.3.8",
"@types/react": "^18.2.45",
"@types/react-dom": "^18.2.18",
"@zsviczian/excalidraw-extras-api": "^0.0.13",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@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",
"jsesc": "^3.0.2",
"obsidian": "1.8.7",
"postcss": "^8.5.25",
"prettier": "^3.0.1",
@@ -2088,31 +2084,31 @@
}
},
"node_modules/@floating-ui/core": {
"version": "1.7.5",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz",
"integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==",
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz",
"integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==",
"license": "MIT",
"dependencies": {
"@floating-ui/utils": "^0.2.11"
"@floating-ui/utils": "^0.2.12"
}
},
"node_modules/@floating-ui/dom": {
"version": "1.7.6",
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz",
"integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==",
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz",
"integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==",
"license": "MIT",
"dependencies": {
"@floating-ui/core": "^1.7.5",
"@floating-ui/utils": "^0.2.11"
"@floating-ui/core": "^1.8.0",
"@floating-ui/utils": "^0.2.12"
}
},
"node_modules/@floating-ui/react-dom": {
"version": "2.1.8",
"resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.8.tgz",
"integrity": "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==",
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz",
"integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==",
"license": "MIT",
"dependencies": {
"@floating-ui/dom": "^1.7.6"
"@floating-ui/dom": "^1.8.0"
},
"peerDependencies": {
"react": ">=16.8.0",
@@ -2120,9 +2116,9 @@
}
},
"node_modules/@floating-ui/utils": {
"version": "0.2.11",
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz",
"integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==",
"version": "0.2.12",
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz",
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT"
},
"node_modules/@humanfs/core": {
@@ -4891,39 +4887,24 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/opentype.js": {
"version": "1.3.10",
"resolved": "https://registry.npmjs.org/@types/opentype.js/-/opentype.js-1.3.10.tgz",
"integrity": "sha512-F67EFyk6j02okHz5JCgata3ZRAcZi9GLnzmkHw/rzJq3OCc8/ZVdoKrxMTYjcQP6IYHGBz2cav1cpzkOkPiPCQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"devOptional": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.31",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
"integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
"version": "19.2.18",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz",
"integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.2.2"
}
},
"node_modules/@types/react-dom": {
"version": "18.3.7",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"version": "19.2.4",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.4.tgz",
"integrity": "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==",
"devOptional": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0"
"@types/react": "^19.2.0"
}
},
"node_modules/@types/resolve": {
@@ -5274,9 +5255,10 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.116",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.116.tgz",
"integrity": "sha512-cq/jChIEDdmWt/B1ZQUauMqi7wj/vNda0TZjqQ89ju9n8mLrvh9J7f3OZJQ+m/BYOesd1RrY8Nm4SZfBj37Ajg==",
"version": "0.18.139",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.139.tgz",
"integrity": "sha512-3d31zicckBIK4VMyldgCLuPON5xCWNTxn0vF1r3FdlVbfLXI+OFdeq6Qog8aYO4IXN2W5XKdIF5Byzk17U4Aqg==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
"@codemirror/commands": "^6.0.0",
@@ -5316,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": {
@@ -7994,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": {
@@ -9652,6 +9634,7 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"dev": true,
"license": "MIT"
},
"node_modules/js-yaml": {
@@ -9988,6 +9971,7 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
@@ -10238,9 +10222,9 @@
}
},
"node_modules/nanoid": {
"version": "5.1.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.11.tgz",
"integrity": "sha512-v+KEsUv2ps74PaSKv0gHTxTCgMXOIfBEbaqa6w6ISIGC7ZsvHN4N9oJ8d4cmf0n5oTzQz2SLmThbQWhjd/8eKg==",
"version": "5.1.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz",
"integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==",
"funding": [
{
"type": "github",
@@ -10481,22 +10465,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/opentype.js": {
"version": "1.3.4",
"resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-1.3.4.tgz",
"integrity": "sha512-d2JE9RP/6uagpQAVtJoF0pJJA/fgai89Cc50Yp0EJHk+eLp6QQ7gBoblsnubRULNY132I0J1QKMJ+JTbMqz4sw==",
"license": "MIT",
"dependencies": {
"string.prototype.codepointat": "^0.2.1",
"tiny-inflate": "^1.0.3"
},
"bin": {
"ot": "bin/ot"
},
"engines": {
"node": ">= 8.0.0"
}
},
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@@ -11409,28 +11377,24 @@
}
},
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"version": "19.2.8",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
"integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"version": "19.2.8",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
"integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
"scheduler": "^0.27.0"
},
"peerDependencies": {
"react": "^18.3.1"
"react": "^19.2.8"
}
},
"node_modules/react-is": {
@@ -12011,13 +11975,10 @@
}
},
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
"license": "MIT"
},
"node_modules/semver": {
"version": "6.3.1",
@@ -12291,12 +12252,6 @@
"node": ">= 0.4"
}
},
"node_modules/string.prototype.codepointat": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz",
"integrity": "sha512-2cBVCj6I4IOvEnjgO/hWqXjqBGsY+zwPmHl12Srk9IXSZ56Jwwmy+66XO5Iut/oQVR7t5ihYdLB0GMa4alEUcg==",
"license": "MIT"
},
"node_modules/string.prototype.matchall": {
"version": "4.0.12",
"resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",
@@ -12574,12 +12529,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/tiny-inflate": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
"license": "MIT"
},
"node_modules/tinyexec": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz",
@@ -13282,6 +13231,7 @@
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
"dev": true,
"license": "ISC",
"bin": {
"yaml": "bin.mjs"
+15 -15
View File
@@ -20,7 +20,11 @@
"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": "node scripts/generate-repository-zip.mjs",
"repo:update": "node scripts/update-repository.mjs",
"script-store:build": "node scripts/build-script-store.mjs",
"script-store:check": "node scripts/build-script-store.mjs --check"
},
"keywords": [],
"author": "",
@@ -30,22 +34,20 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.116",
"@zsviczian/excalidraw": "0.18.139",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
"gl-matrix": "^3.4.3",
"lz-string": "^1.5.0",
"monkey-around": "^2.3.0",
"nanoid": "^5.1.11",
"opentype.js": "^1.3.4",
"nanoid": "^5.1.16",
"pako": "^2.1.0",
"points-on-path": "^0.2.1",
"polybooljs": "^1.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"roughjs": "^4.5.2",
"yaml": "^2.9.0"
"react": "19.2.8",
"react-dom": "19.2.8",
"roughjs": "^4.5.2"
},
"devDependencies": {
"@babel/core": "^7.22.9",
@@ -69,19 +71,17 @@
"@types/chroma-js": "^3.1.1",
"@types/js-beautify": "^1.14.0",
"@types/node": "^22.19.19",
"@types/opentype.js": "^1.3.8",
"@types/react": "^18.2.45",
"@types/react-dom": "^18.2.18",
"@zsviczian/excalidraw-extras-api": "^0.0.13",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@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",
"jsesc": "^3.0.2",
"obsidian": "1.8.7",
"postcss": "^8.5.25",
"prettier": "^3.0.1",
@@ -96,7 +96,7 @@
"lodash": "^4.18.1",
"lodash-es": "^4.18.1",
"serialize-javascript": "^7.0.5",
"nanoid": "^5.1.11",
"nanoid": "^5.1.16",
"dompurify": "^3.4.12",
"fast-uri": "^3.1.4",
"immutable": "^4.3.9",
+209 -73
View File
@@ -1,4 +1,5 @@
import { nodeResolve } from '@rollup/plugin-node-resolve';
import { execFileSync } from 'node:child_process';
import zlib from 'node:zlib';
import visualizer from 'rollup-plugin-visualizer';
import commonjs from '@rollup/plugin-commonjs';
@@ -10,10 +11,10 @@ import fs from 'fs';
import path from 'path';
import postprocess from '@zsviczian/rollup-plugin-postprocess';
import cssnano from 'cssnano';
import jsesc from 'jsesc';
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
@@ -32,28 +33,60 @@ const absolutePath = path.resolve(DIST_FOLDER);
fs.mkdirSync(absolutePath, { recursive: true });
const isProd = (process.env.NODE_ENV === "production");
const isLib = (process.env.NODE_ENV === "lib");
console.log(`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}`);
const DEFAULT_PLUGIN_REPOSITORY = {
owner: "zsviczian",
name: "obsidian-excalidraw-plugin",
ref: "master",
};
const resolvePluginRepositoryContext = () => {
const repository = { ...DEFAULT_PLUGIN_REPOSITORY };
try {
const remoteUrl = execFileSync("git", ["remote", "get-url", "origin"], {
cwd: process.cwd(),
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
const match = remoteUrl.match(
/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/i,
);
if (match) {
repository.owner = match[1];
repository.name = match[2];
}
const branch = execFileSync("git", ["branch", "--show-current"], {
cwd: process.cwd(),
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
if (branch) {
repository.ref = branch;
return repository;
}
const commit = execFileSync("git", ["rev-parse", "HEAD"], {
cwd: process.cwd(),
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
if (commit) {
repository.ref = commit;
}
} catch {
// Source archives do not include .git. Keep canonical release defaults.
}
return repository;
};
const pluginRepository = resolvePluginRepositoryContext();
console.log(
`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}; repository: ${pluginRepository.owner}/${pluginRepository.name}@${pluginRepository.ref}`,
);
// Excalidraw React 19 compatiblity shim
// Create JSX runtime compatibility layer
const jsxRuntimeShim = `
const jsx = (type, props, key) => {
return React.createElement(type, props);
};
const jsxs = (type, props, key) => {
return React.createElement(type, props);
};
const Fragment = React.Fragment;
React.jsx = jsx;
React.jsxs = jsxs;
React.Fragment = Fragment;
React.jsxRuntime = { jsx, jsxs, Fragment };
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ = { jsx, jsxs, Fragment };
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_dev_runtime__ = { jsx, jsxs, Fragment, jsxDEV: jsx };
window['react/jsx-runtime'] = { jsx, jsxs, Fragment };
window['react/jsx-dev-runtime'] = { jsx, jsxs, Fragment, jsxDEV: jsx };
`;
// Add non-English locales here to embed them as compressed payloads in main.js.
// When adding a locale file:
@@ -94,22 +127,34 @@ function compressLanguageFile(lang) {
return compressDeflateBase64(minifyCode(`x = ${content};`));
}
const excalidraw_pkg = isLib ? "" : minifyCode(isProd
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.production.min.js", "utf8")
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.development.js", "utf8"));
const react_pkg = isLib ? "" : minifyCode(isProd
? fs.readFileSync("./node_modules/react/umd/react.production.min.js", "utf8")
: fs.readFileSync("./node_modules/react/umd/react.development.js", "utf8"));
const reactdom_pkg = isLib ? "" : minifyCode(isProd
? fs.readFileSync("./node_modules/react-dom/umd/react-dom.production.min.js", "utf8")
: fs.readFileSync("./node_modules/react-dom/umd/react-dom.development.js", "utf8"));
const pako_pkg = isLib ? "" : fs.readFileSync("./node_modules/pako/dist/pako.min.js", "utf8");
const excalidrawSource = isLib ? "" : fs.readFileSync(
isProd
? "./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.production.min.js"
: "./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.development.js",
"utf8",
);
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");
if (!isLib) {
const excalidraw_styles = isProd
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.production.css", "utf8")
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.development.css", "utf8");
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.production.min.css", "utf8")
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.development.css", "utf8");
const plugin_styles = fs.readFileSync("./styles.css", "utf8");
const styles = excalidraw_styles + plugin_styles;
cssnano()
@@ -127,10 +172,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' +
@@ -140,10 +250,7 @@ const packageString = isLib
' ' + pako_pkg + '\n' +
' return module.exports;\n' +
'})();\n' +
'\nlet REACT_PACKAGES = `' +
jsesc(react_pkg + reactdom_pkg + jsxRuntimeShim, { quotes: 'backtick' }) +
'`;\n' +
// NEW: Fast, mobile-compatible runtime decompression
// Define the dependency-free inflater used by compressed runtime payloads.
'const unpackBase64Deflate = (b64) => {\n' +
' const binStr = atob(b64);\n' +
' const len = binStr.length;\n' +
@@ -152,38 +259,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' +
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
'const evaluateRuntimeInstructions = (win, instruction) => win.eval.call(win, instruction);\n' +
'const reactRuntimeInstructions = `(function() {${REACT_PACKAGES}; return {React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime};})()`;\n' +
'let {React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime} = evaluateRuntimeInstructions(window, reactRuntimeInstructions);\n' +
'REACT_PACKAGES = "";\n' +
'let react = React;\n' +
'let reactDOM = ReactDOM;\n' +
'let excalidrawLib = {};\n' +
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
//These declarations were moved here because Obsidian code scanner incorrectly flags them with a warning,
//but without offering a proper resolution, or a stepout process to remove them from scanner results.
//for context you can read different issues I raised with the Obsidian team about these.
//Once there is a workable resolution I am moving them back to their original locations, since having them here
//is not at all ideal.
//https://github.com/obsidianmd/eslint-plugin/issues/175
// Scanner compatibility shim: deprecated caret API used only as a compatibility fallback.
// Excalidraw uses Document.caretPositionFromPoint() where supported and falls back to
// caretRangeFromPoint() for supported Obsidian/Electron/WebKit runtimes where the newer
// API is unavailable. Removing the fallback would break compatibility without improving
// plugin safety. The upstream false-positive report remains open:
// https://github.com/obsidianmd/eslint-plugin/issues/175
// Remove this shim when the scanner recognizes feature-detected compatibility fallbacks
// or all supported Obsidian runtimes provide caretPositionFromPoint().
`const getCaretRangeFromPoint = (doc, x, y) => doc.caretRangeFromPoint?.(x, y);\n` +
//There isn't a process for flagging deliberate use of main document instead of activeDocument
//The blanket rule by the eslint-plugin makes sense for many cases, but does not address special case needs
// Scanner compatibility shim: deliberate reference to the primary application Document.
// activeDocument is intentionally not equivalent here. Excalidraw supports popout windows
// and must sometimes distinguish the main application document from a view/element's
// ownerDocument or from the document that currently has focus.
//
// Related upstream work on false-positive `document` detection:
// https://github.com/obsidianmd/eslint-plugin/pull/187
//
// This case is distinct: access to the primary document is intentional rather than an
// accidental reference to the wrong document. Remove this shim when deliberate
// main-document access can be represented without a finding.
`const mainDocument = document;\n` +
//Fetch is the only valid approach in case of loading binary data such as fonts to dataURL (i.e. not network related)
//I've also had cases in the past where requestUrl failed with certain endpoints, for those cases I have
//fetch in the codebase as a fallback from requestUrl.
//https://github.com/obsidianmd/eslint-plugin/issues/176
// Scanner compatibility shim: intentional Fetch API use.
// Obsidian's requestUrl() is preferred for ordinary HTTP requests. Excalidraw also has
// browser-native cases where fetch() is the appropriate API, including reading blob/data
// resources for binary conversion, plus narrowly scoped fallbacks where requestUrl() cannot
// reproduce the required browser/CORS behavior. Call sites use the deliberately named
// deliberateFetch() helper so exceptional uses remain explicit and searchable.
// Upstream false-positive report:
// https://github.com/obsidianmd/eslint-plugin/issues/176
// Remove this shim when the scanner distinguishes these valid uses or supports scoped,
// justified exceptions.
`const deliberateFetch = async (payload, init) => await fetch(payload, init);\n` +
`const PLUGIN_VERSION="${manifest.version}";\n` +
//Moved here since the Obsidian code scanner warning to avoid unnecessary logging appears
//to users, creating the impression that there is unnecessary logging. There isn't.
//Errors and debug information is logged. Nothing else.
`const consoleLog = console["log"].bind(console);\n` +
//Obsidian code scanner fails if document.createElement rule is ignored using the eslint-ignore comment
//the code scanner also does not allow creating style elements and guides plugins to use style.css
//the code scanner does not recognize valid cases such as creating canvas elements for image generation
//adding a style element to an iframe that is used to create an image
//I am sorry, but I got fatigued creating issues for all my edge cases with the eslint-plugin...
//given the amount of extra time it takes, and the the usual lack of any meaningful timely response
//Since I want to continue releasing Excalidraw versions, and not risk getting flagged for failed releases
//I see no other meaningful option
`const STARTUP_SCRIPT_BASE64="${startupScriptBase64}";\n` +
// Scanner compatibility shim: intentional diagnostic logging.
// Excalidraw does not use console.log for routine application output. Remaining log calls
// are deliberate diagnostic/debug information used for troubleshooting.
//
// Remove this shim when reviewed diagnostic logging can be acknowledged without producing
// a misleading quality finding.
`const consoleLog = console["log"].bind(console);\n` +
// Scanner compatibility shim: intentional native DOM element creation.
// Obsidian DOM helpers and the plugin stylesheet are preferred for ordinary plugin UI.
//
// Every remaining call site creates a <style> element. Non-iframe cases inject complete
// runtime stylesheet rules (selectors, pseudo-elements, at-rules, or arbitrary CSS) that
// cannot be represented by per-element style helpers. Iframe cases must additionally create
// the element in the iframe's contentDocument, whose realm does not receive Obsidian's DOM
// helpers. Detached canvas/image and serialization-only elements use createFragment().
//
// Upstream discussion:
// https://github.com/obsidianmd/eslint-plugin/issues/196
//
// Call sites use deliberateCreateElement(doc, tagName) so these unresolved stylesheet
// exceptions remain explicit and searchable. Do not broaden the shim beyond reviewed style
// creation; remove it when upstream provides an accepted document-scoped pattern.
`const deliberateCreateElement = (doc, tagName) => doc.createElement(tagName);\n`;
const BASE_CONFIG = {
@@ -203,7 +344,7 @@ const BASE_CONFIG = {
'obsidian',
'@zsviczian/excalidraw',
'react',
'react-dom'
'react-dom',
],
};
@@ -213,14 +354,9 @@ const getRollupPlugins = (tsconfig, ...plugins) => [
replace({
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"
}
__PLUGIN_REPOSITORY_OWNER__: JSON.stringify(pluginRepository.owner),
__PLUGIN_REPOSITORY_NAME__: JSON.stringify(pluginRepository.name),
__PLUGIN_REPOSITORY_REF__: JSON.stringify(pluginRepository.ref),
}),
commonjs(),
nodeResolve({ browser: true, preferBuiltins: false }),
@@ -292,4 +428,4 @@ if (process.env.NODE_ENV === "lib") {
config.push(BUILD_CONFIG);
}
export default config;
export default config;
+195
View File
@@ -0,0 +1,195 @@
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const scriptsDir = path.join(root, "ea-scripts");
const catalogPath = path.join(scriptsDir, "script-store.json");
const directoryInfoPath = path.join(scriptsDir, "directory-info.json");
const checkOnly = process.argv.includes("--check");
const FEATURED_CATEGORY = "Editors Picks";
const fail = (message) => {
throw new Error(`[script-store] ${message}`);
};
const catalog = JSON.parse(fs.readFileSync(catalogPath, "utf8"));
const validateCatalog = () => {
if (catalog.version !== 1) {
fail(`Unsupported catalog version: ${catalog.version}`);
}
if (!Array.isArray(catalog.categories) || !Array.isArray(catalog.scripts)) {
fail("Catalog must contain categories[] and scripts[].");
}
const categories = new Set();
for (const category of catalog.categories) {
if (!category?.name || categories.has(category.name)) {
fail(`Invalid or duplicate category: ${category?.name ?? "<missing>"}`);
}
categories.add(category.name);
}
const names = new Set();
const files = new Set();
for (const script of catalog.scripts) {
if (!script?.name || !script?.file || !script?.installUrl) {
fail(`Script entry is missing name, file, or installUrl: ${JSON.stringify(script)}`);
}
if (names.has(script.name)) {
fail(`Duplicate script name: ${script.name}`);
}
if (files.has(script.file)) {
fail(`Duplicate script file: ${script.file}`);
}
names.add(script.name);
files.add(script.file);
if (!fs.existsSync(path.join(scriptsDir, script.file))) {
fail(`Missing script file: ea-scripts/${script.file}`);
}
for (const category of script.categories ?? []) {
if (!categories.has(category)) {
fail(`Unknown category "${category}" on ${script.name}`);
}
}
if (
script.featuredRank !== undefined &&
!script.categories?.includes(FEATURED_CATEGORY)
) {
fail(`${script.name} has featuredRank but is not in ${FEATURED_CATEGORY}.`);
}
}
};
const getGitOutput = (args) => {
try {
return execFileSync("git", args, {
cwd: root,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
});
} catch {
return null;
}
};
const getHeadDirectoryInfo = () => {
const source = getGitOutput(["show", "HEAD:ea-scripts/directory-info.json"]);
if (!source) {
return null;
}
try {
return JSON.parse(source);
} catch {
return null;
}
};
const getChangedManagedFiles = () => {
const status = getGitOutput([
"status",
"--porcelain=v1",
"--untracked-files=all",
"--",
"ea-scripts",
]);
if (status === null) {
return null;
}
const managed = new Set();
for (const script of catalog.scripts) {
managed.add(script.file);
managed.add(script.file.replace(/\.(?:md|js)$/i, ".svg"));
}
const changed = new Set();
for (const line of status.split(/\r?\n/)) {
if (line.length < 4) {
continue;
}
let filePath = line.slice(3).trim();
const renameSeparator = filePath.lastIndexOf(" -> ");
if (renameSeparator >= 0) {
filePath = filePath.slice(renameSeparator + 4);
}
if (filePath.startsWith('"') && filePath.endsWith('"')) {
filePath = filePath.slice(1, -1);
}
const prefix = "ea-scripts/";
if (!filePath.startsWith(prefix)) {
continue;
}
const filename = filePath.slice(prefix.length);
if (managed.has(filename)) {
changed.add(filename);
}
}
return changed;
};
const updateDirectoryInfoForChangedScripts = () => {
const existing = JSON.parse(fs.readFileSync(directoryInfoPath, "utf8"));
const changed = getChangedManagedFiles();
const headEntries = getHeadDirectoryInfo();
// Exported repository ZIPs do not contain .git. In that environment the
// historical mtimes are intentionally left completely untouched.
if (changed === null || headEntries === null || changed.size === 0) {
return null;
}
const headByName = new Map(headEntries.map((entry) => [entry.fname, entry.mtime]));
const currentByName = new Map(existing.map((entry) => [entry.fname, entry]));
let nextMtime = Date.now();
for (const filename of changed) {
const localPath = path.join(scriptsDir, filename);
if (!fs.existsSync(localPath)) {
continue;
}
const current = currentByName.get(filename);
const headMtime = headByName.get(filename);
// If this PR already changed the mtime, keep it. This makes repeated
// script-store:build runs idempotent and prevents timestamp churn.
if (current && headMtime !== undefined && current.mtime !== headMtime) {
continue;
}
const mtime = Math.max(nextMtime++, (current?.mtime ?? headMtime ?? 0) + 1);
if (current) {
current.mtime = mtime;
} else {
const entry = { fname: filename, mtime };
existing.push(entry);
currentByName.set(filename, entry);
}
}
return existing;
};
validateCatalog();
if (checkOnly) {
console.log(
`[script-store] Catalog OK: ${catalog.scripts.length} scripts in ${catalog.categories.length} categories.`,
);
process.exit(0);
}
const directoryInfo = updateDirectoryInfoForChangedScripts();
if (directoryInfo) {
const directoryInfoSource = `${JSON.stringify(directoryInfo, null, 2)}\n`;
if (directoryInfoSource !== fs.readFileSync(directoryInfoPath, "utf8")) {
fs.writeFileSync(directoryInfoPath, directoryInfoSource);
}
}
console.log(
`[script-store] Validated ${catalog.scripts.length} scripts and updated directory-info.json for changed script/icon files.`,
);
+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");
@@ -0,0 +1,111 @@
import assert from "node:assert/strict";
import { createJiti } from "jiti";
const log = (message) => process.stdout.write(`${message}\n`);
const jiti = createJiti(import.meta.url);
const {
collectReachableDependencyValues,
getMatchingTopLevelDependencyKeys,
hasReachableDependency,
} = await jiti.import("../src/utils/nestedDependencyTraversal.ts");
const graph = (entries) => ({
nodes: new Map(
Object.entries(entries).map(([key, childKeys]) => [
key,
{ value: key, childKeys },
]),
),
});
const diamond = graph({
root: ["left", "right"],
left: ["shared"],
right: ["shared"],
shared: ["leaf"],
leaf: [],
});
assert.deepEqual(
collectReachableDependencyValues(diamond, "root"),
["left", "right", "shared", "leaf"],
"direct dependencies retain metadata order and shared dependencies are returned once",
);
assert.deepEqual(
getMatchingTopLevelDependencyKeys(
diamond,
"root",
new Set(["left", "right"]),
(value) => value === "leaf",
),
new Set(["left", "right"]),
"a changed shared descendant must invalidate every containing top-level dependency",
);
const cyclic = graph({
root: ["a"],
a: ["b"],
b: ["root", "a", "changed"],
changed: [],
});
let cycleVisits = 0;
assert.equal(
hasReachableDependency(cyclic, "root", (value) => {
cycleVisits++;
return value === "changed";
}),
true,
"cycles must terminate and still find reachable changes",
);
assert.ok(cycleVisits <= 3, "a cycle must not cause repeated visits");
assert.deepEqual(
getMatchingTopLevelDependencyKeys(
cyclic,
"root",
new Set(["a"]),
(value) => value === "root",
),
new Set(),
"a back-link to the root must not invalidate a top-level dependency",
);
const layeredEntries = { root: ["top"] };
const layerCount = 22;
for (let layer = 0; layer < layerCount; layer++) {
const left = `left-${layer}`;
const right = `right-${layer}`;
const nextLeft = `left-${layer + 1}`;
const nextRight = `right-${layer + 1}`;
layeredEntries[left] = [nextLeft, nextRight];
layeredEntries[right] = [nextLeft, nextRight];
}
layeredEntries.top = ["left-0", "right-0"];
layeredEntries[`left-${layerCount}`] = [];
layeredEntries[`right-${layerCount}`] = [];
const layered = graph(layeredEntries);
let layeredVisits = 0;
assert.equal(
hasReachableDependency(layered, "root", () => {
layeredVisits++;
return false;
}),
false,
"an unchanged dependency graph must report no change",
);
assert.equal(
layeredVisits,
layered.nodes.size - 1,
"a graph with exponentially many conceptual paths must visit each node once",
);
assert.deepEqual(
getMatchingTopLevelDependencyKeys(
diamond,
"root",
new Set(["left"]),
(value) => value === "right",
),
new Set(),
"only requested direct dependencies may be returned",
);
log("nested dependency traversal checks passed");
+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");
File diff suppressed because it is too large. Load diff
+330
View File
@@ -0,0 +1,330 @@
import {
chmodSync,
copyFileSync,
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
statSync,
utimesSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { basename, join, relative, resolve, sep } from "node:path";
import { spawnSync } from "node:child_process";
const OUTPUT = "repository.zip";
const IGNORE_DIRS = new Set([
".git",
".svn",
".hg",
"node_modules",
"dist",
".next",
".nuxt",
".cache",
".parcel-cache",
".turbo",
".idea",
".vscode",
".tools",
"coverage",
"build",
"out",
"output",
"secrets",
".claude",
"__MACOSX",
]);
const IGNORE_FILENAMES = new Set([
".DS_Store",
"Thumbs.db",
"REPOSITORY_STRUCTURE.md",
"REPOSITORY_CONTENTS.md",
OUTPUT,
]);
const IGNORE_EXTENSIONS = [
// Images
".png",
".jpg",
".jpeg",
".gif",
".webp",
".bmp",
".tif",
".tiff",
".ico",
".icns",
".avif",
".heic",
".heif",
".svgz",
// PDF / ebook / office containers
".pdf",
".epub",
".doc",
".docx",
".xls",
".xlsx",
".ppt",
".pptx",
// Audio
".mp3",
".wav",
".flac",
".aac",
".m4a",
".ogg",
".opus",
".wma",
// Video
".mp4",
".mov",
".mkv",
".avi",
".webm",
".m4v",
".mpeg",
".mpg",
// Fonts
".ttf",
".otf",
".woff",
".woff2",
".eot",
// Archives / compressed files
".zip",
".tar",
".gz",
".tgz",
".bz2",
".xz",
".7z",
".rar",
// Native binaries / executables / compiled objects
".exe",
".dll",
".so",
".dylib",
".bin",
".com",
".app",
".msi",
".o",
".obj",
".a",
".lib",
".class",
".jar",
".war",
".wasm",
".node",
// Binary databases / data formats
".db",
".sqlite",
".sqlite3",
".parquet",
".arrow",
".feather",
];
function isIgnoredExtension(filename) {
const lower = filename.toLowerCase();
return IGNORE_EXTENSIONS.some((extension) => lower.endsWith(extension));
}
function looksBinary(filePath) {
const buffer = readFileSync(filePath);
if (buffer.length === 0) return false;
if (buffer.includes(0)) return true;
try {
new TextDecoder("utf-8", { fatal: true }).decode(buffer);
} catch {
return true;
}
let suspiciousControls = 0;
for (const byte of buffer) {
const allowedControl = byte === 8 || byte === 9 || byte === 10 || byte === 12 || byte === 13;
if ((byte < 32 && !allowedControl) || byte === 127) {
suspiciousControls += 1;
}
}
return suspiciousControls / buffer.length > 0.01;
}
function copyPreservingMetadata(source, destination) {
mkdirSync(resolve(destination, ".."), { recursive: true });
copyFileSync(source, destination);
const stat = statSync(source);
chmodSync(destination, stat.mode);
utimesSync(destination, stat.atime, stat.mtime);
}
function collectFiles(root) {
const files = [];
const stats = {
included: 0,
skippedBinary: 0,
skippedType: 0,
skippedName: 0,
skippedDir: 0,
skippedOther: 0,
};
function walk(directory) {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const fullPath = join(directory, entry.name);
if (entry.isDirectory()) {
if (IGNORE_DIRS.has(entry.name)) {
stats.skippedDir += 1;
continue;
}
walk(fullPath);
continue;
}
// Match the old `find . -type f` behavior: do not include symlinks,
// sockets, devices, or other non-regular filesystem entries.
if (!entry.isFile()) {
stats.skippedOther += 1;
continue;
}
if (IGNORE_FILENAMES.has(entry.name)) {
stats.skippedName += 1;
continue;
}
if (isIgnoredExtension(entry.name)) {
stats.skippedType += 1;
continue;
}
if (looksBinary(fullPath)) {
stats.skippedBinary += 1;
continue;
}
files.push(fullPath);
stats.included += 1;
}
}
walk(root);
return { files, stats };
}
function createZipWithZipCommand(stageDir, outputPath) {
const result = spawnSync("zip", ["-q", "-r", outputPath, "."], {
cwd: stageDir,
stdio: "inherit",
});
if (result.error?.code === "ENOENT") {
throw new Error("'zip' is required on macOS/Linux but was not found in PATH.");
}
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`zip exited with status ${result.status ?? "unknown"}.`);
}
}
function createZipWithPowerShell(stageDir, outputPath) {
const command = [
"Add-Type -AssemblyName System.IO.Compression.FileSystem;",
"[System.IO.Compression.ZipFile]::CreateFromDirectory(",
"$env:REPO_EXPORT_STAGE,",
"$env:REPO_EXPORT_OUTPUT,",
"[System.IO.Compression.CompressionLevel]::Optimal,",
"$false",
")",
].join(" ");
const env = {
...process.env,
REPO_EXPORT_STAGE: stageDir,
REPO_EXPORT_OUTPUT: outputPath,
};
let lastError;
for (const executable of ["powershell.exe", "pwsh.exe"]) {
const result = spawnSync(
executable,
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command],
{ env, stdio: "inherit" },
);
if (result.error?.code === "ENOENT") {
lastError = result.error;
continue;
}
if (result.error) throw result.error;
if (result.status !== 0) {
throw new Error(`${executable} exited with status ${result.status ?? "unknown"}.`);
}
return;
}
throw new Error(
`PowerShell is required on Windows but was not found.${lastError ? ` ${lastError.message}` : ""}`,
);
}
const root = process.cwd();
const outputPath = join(root, OUTPUT);
const stageDir = mkdtempSync(join(tmpdir(), "ea-repo-export-"));
try {
const { files, stats } = collectFiles(root);
if (files.length === 0) {
console.log("No files matched the inclusion rules; no ZIP created.");
process.exitCode = 0;
} else {
for (const source of files) {
const relativePath = relative(root, source);
const destination = join(stageDir, ...relativePath.split(sep));
copyPreservingMetadata(source, destination);
}
rmSync(outputPath, { force: true });
if (process.platform === "win32") {
createZipWithPowerShell(stageDir, outputPath);
} else {
createZipWithZipCommand(stageDir, outputPath);
}
console.log(`Created ${basename(outputPath)}`);
console.log(`Included files: ${stats.included}`);
console.log(`Skipped ignored folders: ${stats.skippedDir}`);
console.log(`Skipped because of ignored filenames: ${stats.skippedName}`);
console.log(`Skipped because of ignored file types: ${stats.skippedType}`);
console.log(`Skipped because binary content was detected: ${stats.skippedBinary}`);
if (stats.skippedOther > 0) {
console.log(`Skipped non-regular filesystem entries: ${stats.skippedOther}`);
}
}
} finally {
if (existsSync(stageDir)) {
rmSync(stageDir, { recursive: true, force: true });
}
}
+9 -667
View File
@@ -1,676 +1,18 @@
/* eslint-disable no-console */
// to run: node generate-script-library.mjs
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Reconstruct __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, '..');
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
const INDEX_NEW = path.join(EA_SCRIPTS_DIR, 'index-new.md');
const OUT_DIR = path.join(path.join(ROOT, 'docs'), 'AITrainingData');
const SCRIPT_LIBRARY_OUT = path.join(OUT_DIR, 'Excalidraw Script Library.md');
const TYPE_DEF_OUT = path.join(OUT_DIR, 'Excalidraw Automate library and related type definitions.md');
const AI_TRAINING_OUT = path.join(OUT_DIR, 'ExcalidrawAutomate full library for LLM training.md');
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source Excalidraw component. Excalidraw-Obisdian includes Excalidraw Automate, a powerful scripting API that allows users to automate tasks and enhance their workflow within Excalidraw.
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via \`ea.getExcalidrawAPI()\`. Note: the API is only available if \`ea.targetView\` is set. When running Excalidraw scripts using the script engine, the provided \`ea\` object is already set up with targetView by default. Otherwise you need to first run \`ea.setView()\`.
- \`window.ExcalidrawLib\` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via \`ea\` (ExcalidrawAutomate) methods, ALWAYS prefer \`ea\` over \`window.ExcalidrawLib\`. \`ea\` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., \`const modal = new ea.FloatingModal(...)\`) and then assigning functions directly to the \`onOpen\` and \`onClose\` properties of that instance.
For a reference, follow the implementation pattern used in the "Printable Layout Wizard.md" script.
- Elements have a \`customData\` property that can be used to store arbitrary data. To ensure the data the script adds to elements use the \`ea.addAppendUpdateCustomData\` function. This function ensures that existing customData is preserved when adding new data.
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on \`ea.obsidian\`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (\`onOpen\`, \`onFocus(view)\`, \`onClose\`, \`onExcalidrawViewClosed\`) and manage their own \`ea.targetView\` explicitly.
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with \`ea.targetView === null\`. Scripts must handle this by deferring view-bound work until \`onFocus\` delivers a view; call \`ea.setView(view)\` when you decide to bind.
- Each \`ea\` instance may host a single \`sidepanelTab\`. This sidepanel tab is stored in \`ea.sidepanelTab\`. Create the tab with \`ea.createSidepanelTab(title, persist=false, reveal=true)\`; the returned \`ea.sidepanelTab\` exposes \`contentEl\`, \`setContent\`, \`setTitle\`, \`setDisabled\`, \`setCloseCallback\`, \`open/close\`, and focus lifecycle hooks. Note auto-reveal during tab creation via \`ea.createSidepanelTab()\` is disabled during plugin startup. You can reveal a tab with \`ea.sidepanelTab?.open()\`. You can persist with \`ea.persistSidepanelTab()\` (tabs are restored and scripts re-run on next startup). Close with \`ea.sidepanelTab?.close()\`.
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-\`ExcalidrawView\` relevant, they can call \`ea.closeSidepanelTab()\` after completing the operation, and/or inside \`ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }\` to shut down when the user leaves the originating view.
- Scripts can detect view change in \`onFocus(view)\` by comparing \`ea.targetView\` to the provided \`view\` parameter.
- Persistence UX: scripts may offer a “Persist tab” control inside \`contentEl\` that calls \`ea.persistSidepanelTab()\`. Once persisted, hide that control; users can later remove the tab via the sidepanel close button (scripts cannot unpersist themselves, but can close themselves via \`ea.sidepanelTab?.close()\`).
- Use \`checkForActiveSidepanelTabForScript\` to avoid creating duplicate tabs for the same script name. This method returns the \`ExcalidrawSidepanelTab\` associated with the supplied \`scriptName\` (or \`ea.activeScript\` when omitted), or \`null\` if none exists. It is intended to let a script detect an existing tab that may be owned by another \`ExcalidrawAutomate\` instance (for example, a persisted tab restored at startup). Typical pattern:
- Before creating a new sidepanel, call \`ea.checkForActiveSidepanelTabForScript()\` to see if a tab already exists.
- If a tab exists and \`tab.getHostEA() === ea\`, reuse it (your script already hosts it).
- If a tab exists but is hosted by a different \`ea\` instance, decide whether to reuse or hand off control — e.g. open the existing tab and exit to avoid duplicates.
- Note: persisted tabs restored on startup may be created with \`ea.targetView === null\` and hosted by a different \`ea\` instance; handle that case by waiting for \`onFocus\` before binding view-specific work.
- Example usage:
\`const sp = ea.checkForActiveSidepanelTabForScript();
if (sp) {
if (sp.getHostEA() === ea) {
// we already own the tab — reuse it
sp.open();
} else {
// another EA instance hosts the tab — open it for the user and exit
sp.open();
return;
}
}
// no existing tab — safe to create a new one
// ea.createSidepanelTab("My Script", false, true);\`
- A dedicated section "sidepanelTabTypes.d.ts" in this document lists the \`ExcalidrawSidepanelTab\` function signatures.
#### **0. External Documentation & Resources**
To keep this training file concise, large external type definitions are not included. If you need to look up Obsidian APIs or Excalidraw internals, refer to the following resources:
- **Obsidian API Type Definitions:** https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
- **Obsidian Developer Docs:** https://docs.obsidian.md/Home (Community site with API and CSS documentation/examples)
- **Obsidian Developer Forum:** https://forum.obsidian.md/c/developers-api/14
- **ExcalidrawAutomate Implementation:** If the provided API documentation is unclear, consult the source directly: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/shared/ExcalidrawAutomate.ts
- **Excalidraw Core Fork:** For doubts regarding core Excalidraw functionality, consult the fork used by the plugin: https://github.com/zsviczian/excalidraw
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
* **The Workflow:**
1. Get elements from the current view using \`ea.getViewElements()\` or \`ea.getViewSelectedElements()\`.
2. Copy these elements into the EA workbench for editing using \`ea.copyViewElementsToEAforEditing(elements)\`.
3. Modify the properties of the element copies that are now in the EA workbench (e.g., \`ea.getElement(id).locked = true;\`).
4. Commit the changes back to the scene using \`await ea.addElementsToView()\`.
* **Deletion:** To delete an element, set its \`isDeleted\` property to \`true\` on the workbench copy (\`ea.getElement(id).isDeleted = true;\`) and then commit with \`await ea.addElementsToView()\`.
* **Cleanup:** Use \`ea.clear()\` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
#### **2. User Interaction: Prompts and Dialogs**
* **Simple Input:** For straightforward user input, use the \`utils\` object provided to the script.
* \`await utils.inputPrompt()\`: To get a string or number from the user.
* \`await utils.suggester()\`: To let the user select from a predefined list of options.
* **Complex Dialogs:** When a more complex UI with multiple controls is needed, create a floating dialog window.
* **Use \`FloatingModal\`:** Always create a new instance: \`const modal = new ea.FloatingModal(ea.plugin.app);\`.
* **Do Not Extend:** Do not use \`class MyModal extends ea.FloatingModal\`.
* **Define Behavior:** Assign functions directly to the \`onOpen\` and \`onClose\` properties of the instance. Inside \`onOpen\`, use the \`modal.contentEl\` property to build your UI.
* **Reference Implementation:** The script "Printable Layout Wizard.md" is the canonical example for this pattern. Use \`ea.obsidian.Setting\` to add controls like toggles and dropdowns within the modal.
#### **3. Element Manipulation and Querying**
* **Finding Elements:** The most common starting point is to get the user's selection with \`ea.getViewSelectedElements()\`. Use standard JavaScript array methods like \`.filter()\` to narrow down the selection (e.g., \`elements.filter(el => el.type === "text")\`).
* **Geometric Calculations:**
* Before performing layout or positioning tasks, use \`ea.getBoundingBox(elements)\` to get the collective dimensions and position of a group of elements.
* Use \`ea.measureText(text)\` to determine the width and height of a string based on the current \`ea.style\` settings before creating a text element or a container for it.
* **Grouping:**
* To create a group, use \`ea.addToGroup([elementId1, elementId2, ...])\`.
* To operate on existing groups within a selection, use \`ea.getMaximumGroups(selectedElements)\` which correctly identifies the top-level groups. Use \`ea.getLargestElement(group)\` to find the primary container within a group (e.g., the box around a text element).
#### **4. Styling: Creation vs. Modification**
* **For New Elements:** Set the properties on the global \`ea.style\` object *before* you call a creation function like \`ea.addText()\` or \`ea.addRect()\`. This acts like setting the active color/style on a paintbrush.
* **For Existing Elements:** To change the style of an existing element, modify the properties directly on the element's copy in the EA workbench (after \`copyViewElementsToEAforEditing\`). For example: \`const myElement = ea.getElement(id); myElement.strokeColor = '#FF0000';\`.
#### **5. Data Persistence and Customization**
* **Storing Custom Data:** Elements have a \`customData\` property for arbitrary data.
* **Always Use \`ea.addAppendUpdateCustomData(id, newData)\`:** This is crucial. It safely adds or updates your key-value pairs without overwriting data that might have been stored by other scripts or the Excalidraw plugin itself.
* **Creating Configurable Scripts:** To make your script's behavior customizable by the user:
* Use \`ea.getScriptSettings()\` to retrieve saved settings.
* scriptSettings are stored with Excalidraw settings in Obsidian data.json. Keep this light. You MUST NEVER save large data objects such as base64 images or huge arrays here. Keep this lean and efficient.
* Check if settings exist, and if not, define the default structure.
* Use \`await ea.setScriptSettings(settings)\` to save any changes. This allows users to configure your script in the Excalidraw plugin settings pane.
#### **6. Best Practices and Advanced Techniques**
* **Script Overview Block (MANDATORY):** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
* **Strictly Modular Architecture (NO LOOSE CODE):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well; if the UI includes sections, tabs, or panels, these should be rendered via sub-functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
* **Evergreen JSDoc Headers and Comments:** Every function must have a proper JSDoc/Javadoc-style header containing parameter names, types, and a clear description of the function's purpose. These descriptions must be kept *evergreen* (updated alongside any code changes). Additionally, when modifying or updating a script, you must strictly *retain all existing internal code comments*.
* **Isolate Constants and User-Facing Strings:** *Do not embed hardcoded magic values, config parameters, or UI strings deep inside the logic.* You must separate all constants and language strings and collect them at the very top of the file. This makes it easier to tweak values later and provides a clear, unified section for localization and customization.
* **Icons:** Obsidian uses https://lucide.dev icons. These icons are available for scripts via \`ea.obsidian.getIcon("Icon Name")\`. For UI components prefer use of lucide.dev icons.
* **Omit Version Verification:** While many of the sample scripts in the library include a version verification block at the outset (using \`ea.verifyMinimumPluginVersion\`), *do not add this section* when generating a new script unless explicitly instructed to do so.
* **Embrace \`await\`:** Many EA functions are asynchronous and return a \`Promise\` (e.g., \`ea.addElementsToView()\`, \`ea.createSVG()\`, \`utils.inputPrompt()\`). **Always** use \`await\` when calling these functions to ensure your script executes in the correct order.
* **Accessing Obsidian API:** The full Obsidian API is available via \`ea.obsidian\`. For example, use \`new ea.obsidian.Notice("message")\` or \`ea.obsidian.normalizePath(filepath)\`.
* **Accessing Excalidraw API:** The full Excalidraw API is available on \`ea.getExcalidrawAPI()\`, these API functions are Scene dependent. Additional support functions are available on \`window.ExcalidrawLib\`.
* **Visibility vs. Deletion:**
* To temporarily hide an element, set \`element.opacity = 0\`. It's good practice to store the original opacity in \`customData\` so it can be restored. It is also recommended to lock hidden elements so they do not get accidentally selected or moved around.
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. You can use the \`elementsOverride\` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
#### **8. Custom Pens and Perfect Freehand**
Excalidraw's freehand tool is powered by the open-source Perfect Freehand library. The plugin exposes “custom pens” that bundle:
- Canvas style for the next strokes (colors, width, fillStyle, roughness).
- Perfect Freehand stroke geometry and behavior (pressure simulation, outline, tapering, easing, etc.).
Key concepts:
- AppState-driven drawing: When \`appState.currentStrokeOptions\` is set, the freedraw tool renders new strokes using those Perfect Freehand options.
- Element-level persistence: If a freedraw element has \`element.customData.strokeOptions\`, it is rendered with those options regardless of the current tool state.
- Types reference: See \`src/types/penTypes.ts\`. The \`PenOptions\` shape is:
\`\`\`ts
interface PenOptions {
highlighter: boolean; // if true the pen is drawn at the lowest layer, behind all other elements
constantPressure: boolean;
hasOutline: boolean;
outlineWidth: number;
options: {
thinning: number;
smoothing: number;
streamline: number;
easing: string; // see supported names below
start: { cap: boolean; taper: number | boolean; easing: string; };
end: { cap: boolean; taper: number | boolean; easing: string; };
};
}
\`\`\`
Using custom pens from scripts:
- Activate a custom pen for drawing:
\`\`\`ts
// obtain the Excalidraw API
const api = ea.getExcalidrawAPI();
// define Perfect Freehand options (example similar to "finetip")
const penOptions = {
highlighter: false,
constantPressure: true,
hasOutline: false,
outlineWidth: 1,
options: {
thinning: -0.5,
smoothing: 0.4,
streamline: 0.4,
easing: "linear",
start: { taper: 5, cap: false, easing: "linear" },
end: { taper: 5, cap: false, easing: "linear" },
},
};
// apply stroke options + canvas style, then switch to freedraw (strokeWidth, color, background, fillStyle are optional)
ea.viewUpdateScene({
appState: {
currentStrokeOptions: penOptions,
currentItemStrokeWidth: 0.5,
currentItemStrokeColor: "#3E6F8D",
currentItemBackgroundColor: "transparent",
currentItemFillStyle: "hachure",
},
});
api.setActiveTool({ type: "freedraw" });
\`\`\`
- Clear custom pen (revert to default freedraw behavior):
\`\`\`ts
ea.viewUpdateScene({ appState: { currentStrokeOptions: null } });
\`\`\`
- Persist custom strokeOptions onto existing freedraw elements:
\`\`\`ts
const selected = ea.getViewSelectedElements().filter(el => el.type === "freedraw");
ea.copyViewElementsToEAforEditing(selected);
for (const el of selected) {
ea.addAppendUpdateCustomData(el.id, { strokeOptions: penOptions });
}
await ea.addElementsToView();
\`\`\`
Notes:
- New strokes respect \`appState.currentStrokeOptions\` at draw time. Existing elements only change if you update their \`customData.strokeOptions\`.
- For pens that should behave like real markers/highlighters, set \`highlighter: true\` and often \`constantPressure: true\` with an \`outlineWidth\` for the edge.
Supported easing names (string values for \`options.easing\`, \`options.start.easing\`, \`options.end.easing\`):
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce.
Example freedraw element carrying \`customData.strokeOptions\`:
\`\`\`json
{"type":"excalidraw/clipboard","elements":[{"id":"...","type":"freedraw","strokeColor":"#3E6F8D","backgroundColor":"transparent","fillStyle":"hachure","strokeWidth":0.5,"roughness":0,"customData":{"strokeOptions":{"highlighter":false,"hasOutline":false,"outlineWidth":0,"constantPressure":true,"options":{"smoothing":0.4,"thinning":-0.5,"streamline":0.4,"easing":"linear","start":{"taper":5,"cap":false,"easing":"linear"},"end":{"taper":5,"cap":false,"easing":"linear"}}}}}],"files":{}}
\`\`\`
#### **9. Text Element**
* There are three text properties.
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
`;
const SCRIPT_INTRO = `# Excalidraw Script Library Examples
This is an automatically generated knowledge base intended for Retrieval Augmented Generation (RAG) and other AI-assisted workflows (e.g. NotebookLM or local embeddings tools).
Its purpose:
- Provide a single, query-friendly corpus of all Excalidraw Automate scripts.
- Serve as a practical pattern and snippet library for developers learning Excalidraw Automate.
- Preserve original source side by side with the higher-level index (index-new.md) to improve semantic recall.
- Enable AI tools to answer questions about how to manipulate the Excalidraw canvas, elements, styling, or integration features by referencing real, working examples.
Content structure:
1. SCRIPT_INTRO (this section)
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: ${new Date().toISOString()}
---
`;
const TYPE_DEF_INTRO = `# ExcalidrawAutomate library and related type definitions
`;
const EXCALIDRAW_STARTUP_MESSAGE = `# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
Two files follow. First the template startup script with documenation comments, then an actual startup script example with implemented functionality.
`;
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
/*const ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING = [
"node_modules/obsidian/obsidian.d.ts",
];*/
const TYPE_DEF_WHITELIST = [
"lib/shared/ExcalidrawAutomate.d.ts",
"lib/types/excalidrawAutomateTypes.d.ts",
"lib/types/sidepanelTabTypes.d.ts",
"lib/types/penTypes.d.ts",
"lib/types/utilTypes.d.ts",
"lib/types/exportUtilTypes.d.ts",
"lib/types/embeddedFileLoaderTypes.d.ts",
"lib/types/AIUtilTypes.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts",
];
/**
* Returns true if content contains at least one line starting with ```
* and has an odd number of fences (unbalanced).
*/
function needsClosingFence(content) {
const fenceCount = (content.match(/^```/gm) || []).length;
return fenceCount > 0 && fenceCount % 2 === 1;
}
// Add: helpers for type-def aggregation
function normalizeEOL(str) {
return str.replace(/\r\n/g, '\n');
}
function stripBOM(str) {
return str.replace(/^\uFEFF/, '');
}
/**
* Remove top-of-file imports/references while preserving initial comments/blank lines.
* Also removes bare "export {}" lines (module markers).
*/
function stripTopImports(content) {
const lines = normalizeEOL(stripBOM(content)).split('\n');
const out = [];
let inTopRegion = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isImport =
/^\s*import\s+type\s+/.test(line) ||
/^\s*import\s+/.test(line) ||
/^\s*import\(/.test(line);
const isTripleRef = /^\s*\/\/\/\s*<reference/.test(line);
const isBareExportModule = /^\s*export\s*\{\s*\};?\s*$/.test(line);
if (inTopRegion) {
if (isImport || isTripleRef) {
// drop
continue;
}
// comments and blanks are kept, top-region continues until first code (non-comment/non-blank/non-import)
const isBlank = /^\s*$/.test(line);
const isLineComment = /^\s*\/\//.test(line);
const isBlockCommentStart = /^\s*\/\*/.test(line);
if (!isBlank && !isLineComment && !isBlockCommentStart) {
inTopRegion = false;
}
if (!isBareExportModule) out.push(line);
continue;
}
if (!isBareExportModule) out.push(line);
}
return out.join('\n').trim() + '\n';
}
/**
* Create a nice section header for the concatenated file.
*/
function makeSectionHeader(relPath) {
const stars = '*'.repeat(Math.max(6, Math.min(38, relPath.length + 6)));
return [
`/* ${stars} */`,
`/* ${relPath} */`,
`/* ${stars} */`,
].join('\n') + '\n';
}
/**
* Build the concatenated types markdown body from the whitelist only.
* - Removes top-of-file imports
* - Adds section headers with relative paths
* - Wraps all in one ```js code fence
*/
function buildTypeDefMarkdown() {
const entries = TYPE_DEF_WHITELIST.map((rel) => ({
rel,
abs: path.join(ROOT, ...rel.split('/')),
}));
let body = '```js\n';
for (const { rel, abs } of entries) {
if (!fs.existsSync(abs)) {
console.warn('[script-library] Whitelist file missing:', rel);
continue;
}
let content = fs.readFileSync(abs, 'utf8');
content = stripTopImports(content);
body += makeSectionHeader(rel);
body += content.trimEnd() + '\n\n';
}
body += '```\n';
return body;
}
// NEW: Resolve module specifiers from types/excalidraw/index.d.ts to absolute .d.ts paths
function resolveExcalModulePath(spec, excalIndexAbs) {
const baseTypesRoot = path.join(ROOT, 'node_modules', '@zsviczian', 'excalidraw', 'types');
if (spec.startsWith('@excalidraw/')) {
const sub = spec.slice('@excalidraw/'.length); // e.g. 'element', 'element/bounds'
const parts = sub.split('/');
const pkg = parts.shift(); // 'element' | 'common' | 'utils'
const rest = parts;
if (!pkg) return null;
const base = path.join(baseTypesRoot, pkg);
if (rest.length === 0) {
return path.join(base, 'src', 'index.d.ts');
}
return path.join(base, 'src', ...rest) + '.d.ts';
}
// relative to the excalidraw index.d.ts
if (spec.startsWith('.')) {
const dir = path.dirname(excalIndexAbs);
return path.resolve(dir, spec) + '.d.ts';
}
// anything else is not expected
return null;
}
// NEW: Extract function signatures for a set of names from a .d.ts file
function extractFunctionSignaturesFromModule(absPath, names) {
const out = {};
if (!absPath || !fs.existsSync(absPath)) {
return out;
}
const content = fs.readFileSync(absPath, 'utf8');
for (const rawName of names) {
const name = rawName.trim();
if (!name) continue;
// Try "export declare function NAME ..."
let m = content.match(new RegExp(`export\\s+declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
// Try "declare function NAME ..." (re-exported later)
m = content.match(new RegExp(`(^|\\n)declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
// Ensure it starts with export for readability
out[name] = m[0].replace(/^\s*declare\s+/, 'export declare ').trim();
continue;
}
// Try "export declare const NAME: (...args) => ...;"
m = content.match(new RegExp(`export\\s+declare\\s+const\\s+${name}\\s*:\\s*[\\s\\S]*?=>[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
// Try "export declare function-type via type alias" (rare) - fallback to any const function shape
m = content.match(new RegExp(`export\\s+declare\\s+(?:var|let|const)\\s+${name}\\s*:\\s*[\\s\\S]*?;`, 'm'));
if (m && /=>/.test(m[0])) {
out[name] = m[0].trim();
continue;
}
}
return out;
}
// NEW: Build "ExcalidrawLib module functions" section from index.d.ts
function buildExcalidrawLibFunctionsSection() {
const excalIndexRel = 'node_modules/@zsviczian/excalidraw/types/excalidraw/index.d.ts';
const excalIndexAbs = path.join(ROOT, ...excalIndexRel.split('/'));
if (!fs.existsSync(excalIndexAbs)) {
console.warn('[script-library] Missing Excalidraw index.d.ts:', excalIndexRel);
return '';
}
const content = fs.readFileSync(excalIndexAbs, 'utf8');
const reExport = /export\s*\{\s*([\s\S]*?)\s*\}\s*from\s*["']([^"']+)["'];/g;
// Collect names by source module
const moduleToNames = new Map();
for (const match of content.matchAll(reExport)) {
const namesChunk = match[1];
const spec = match[2];
// skip if the export list contains only types we know we shouldn't include? We'll filter later by signature detection.
const names = namesChunk
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (!names.length) continue;
const abs = resolveExcalModulePath(spec, excalIndexAbs);
if (!abs) continue;
const key = spec;
const curr = moduleToNames.get(key) || { abs, names: new Set() };
for (const n of names) curr.names.add(n);
moduleToNames.set(key, curr);
}
// Extract signatures
const seen = new Set();
const sections = [];
let functionsFound = 0;
for (const [spec, { abs, names }] of moduleToNames) {
const sigs = extractFunctionSignaturesFromModule(abs, Array.from(names));
const sigEntries = Object.entries(sigs)
.filter(([name]) => {
if (seen.has(name)) return false;
seen.add(name);
return true;
})
.sort(([a], [b]) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
if (!sigEntries.length) continue;
const rel = path.relative(ROOT, abs).replace(/\\/g, '/');
const header = makeSectionHeader(`${spec} -> ${rel}`).replace(/\*\/\n\/\*/g, '*\/\n/*'); // keep style
sections.push(header + sigEntries.map(([, s]) => s).join('\n') + '\n');
functionsFound += sigEntries.length;
}
if (!sections.length) {
console.warn('[script-library] No function signatures found in ExcalidrawLib exports.');
}
const body =
'# ExcalidrawLib module functions\n\n' +
'The following functions are exposed via window.ExcalidrawLib. Signatures are extracted from TypeScript declarations.\n\n' +
'```ts\n' +
sections.join('\n') +
'```\n';
console.log(`[script-library] Collected ${functionsFound} ExcalidrawLib function signatures`);
return body;
}
import { runUnifiedGeneration } from './excalidraw-docs-generator-core.mjs';
function main() {
console.log('[script-library] Generating Excalidraw Script Library...');
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
process.exit(1);
}
if (!fs.existsSync(INDEX_NEW)) {
console.error('index-new.md not found:', INDEX_NEW);
process.exit(1);
}
if (!fs.existsSync(OUT_DIR)) {
fs.mkdirSync(OUT_DIR, { recursive: true });
}
let output = SCRIPT_INTRO;
console.log('[script-library] Adding index-new.md');
const indexNewContent = fs.readFileSync(INDEX_NEW, 'utf8');
output += `<!-- BEGIN index-new.md -->\n${indexNewContent.trim()}\n<!-- END index-new.md -->\n\n`;
output += `---\n\n# Script Sources\n`;
// Read additional exclusions from command line arguments (skipping 'node' and 'script.mjs')
const args = process.argv.slice(2);
const cmdLineExcludes = args.map(arg => arg.toLowerCase());
// Define the default exclusions (all in lower case for comparison)
const defaultExcludes = [
'index-new.md',
'mindmap builder.md',
'color scheme manager.md',
'comic strip director.md'
];
// Combine both into a single Set for easy lookup
const exclusions = new Set([...defaultExcludes, ...cmdLineExcludes]);
// Collect *.md files (non-recursive) excluding our combined list
const files = fs
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
.filter(
(d) =>
d.isFile() &&
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
!exclusions.has(d.name.toLowerCase())
)
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
for (const file of files) {
const full = path.join(EA_SCRIPTS_DIR, file);
let content = fs.readFileSync(full, 'utf8');
output += `\n---\n\n## ${file}\n`;
output += `<!-- Source: ea-scripts/${file} -->\n\n`;
// Normalize line endings
content = content.replace(/\r\n/g, '\n');
output += content.trimEnd() + '\n';
if (needsClosingFence(content)) {
output += '```\n';
console.log(`[script-library] Added missing closing fence to ${file}`);
} else {
console.log(`[script-library] Added ${file} (no fence fix needed)`);
}
}
fs.writeFileSync(SCRIPT_LIBRARY_OUT, output, 'utf8');
console.log('[script-library] Wrote:', SCRIPT_LIBRARY_OUT);
// Generate TYPE_DEF_OUT from whitelist
try {
console.log('[script-library] Generating Type Definition Library...');
const typeDefs = TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown();
fs.writeFileSync(TYPE_DEF_OUT, typeDefs, 'utf8');
console.log('[script-library] Wrote:', TYPE_DEF_OUT);
} catch (e) {
console.error('[script-library] Failed to generate TYPE_DEF_OUT:', e);
}
// NEW: Generate AI_TRAINING_OUT
try {
console.log('[script-library] Generating AI Training bundle...');
const typeDefContent = fs.existsSync(TYPE_DEF_OUT)
? fs.readFileSync(TYPE_DEF_OUT, 'utf8')
: (TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown());
const scriptLibContent = fs.existsSync(SCRIPT_LIBRARY_OUT)
? fs.readFileSync(SCRIPT_LIBRARY_OUT, 'utf8')
: '';
// NEW: load startup template and example
const startupTemplatePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_TEMPLATE.split('/'));
const startupExamplePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_EXAMPLE.split('/'));
const startupTemplate = fs.existsSync(startupTemplatePath)
? fs.readFileSync(startupTemplatePath, 'utf8').replace(/\r\n/g, '\n').trim()
: (console.warn('[script-library] Missing startup template:', EXCALIDRAW_STARTUP_TEMPLATE), '');
const startupExample = fs.existsSync(startupExamplePath)
? fs.readFileSync(startupExamplePath, 'utf8').replace(/\r\n/g, '\n').trim()
: (console.warn('[script-library] Missing startup example:', EXCALIDRAW_STARTUP_EXAMPLE), '');
const startupSection =
'\n---\n\n' +
EXCALIDRAW_STARTUP_MESSAGE +
'\n' +
(startupTemplate
? `<!-- ${EXCALIDRAW_STARTUP_TEMPLATE} -->\n${startupTemplate}\n\n`
: '') +
(startupExample
? `<!-- ${EXCALIDRAW_STARTUP_EXAMPLE} -->\n${startupExample}\n`
: '');
// NEW: Build ExcalidrawLib functions section
const excalidrawLibFunctionsSection = buildExcalidrawLibFunctionsSection();
const combined =
(AI_TRAINING_INTRO +
'\n---\n\n' +
typeDefContent.trim() +
'\n\n---\n\n' +
excalidrawLibFunctionsSection +
'\n---\n\n' +
scriptLibContent.trim() +
startupSection +
'\n')
.replaceAll("https://youtu.be/", "YouTube: ")
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
.replaceAll("https://www.youtube.com/", "YouTube: "); // prevent accidental link triggering
fs.writeFileSync(AI_TRAINING_OUT, combined, 'utf8');
console.log('[script-library] Wrote:', AI_TRAINING_OUT);
} catch (e) {
console.error('[script-library] Failed to generate AI_TRAINING_OUT:', e);
}
console.log('[script-library] Done.');
console.log('[script-library] Running unified documentation generator (full mode)...');
const result = runUnifiedGeneration({
mode: 'full',
args: process.argv.slice(2),
});
console.log('[script-library] Wrote outputs:', result.generated);
console.log('[script-library] Processed scripts:', result.scriptsProcessed);
}
// ESM equivalent of `if (require.main === module)`
if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
main();
@@ -678,4 +20,4 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
console.error('[script-library] Failed:', e);
process.exit(1);
}
}
}
+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 };
+196
View File
@@ -0,0 +1,196 @@
// Project only declarations reachable from the supported script surface.
import fs from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
const hidden = (node) => node.modifiers?.some((m) =>
[ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword].includes(m.kind));
const names = (statement) => ts.isVariableStatement(statement)
? statement.declarationList.declarations.map((item) => item.name.text)
: statement.name ? [statement.name.text] : [];
export function projectScriptApi(root) {
const modules = new Map();
const selected = new Map();
const pending = [];
const external = new Set();
const overrides = new Map([
['core/main', `import type { App } from "obsidian";
/** Compatibility access to the official Obsidian app; plugin internals are not a scripting API. */
export default interface ExcalidrawPlugin { readonly app: App; }`],
['view/ExcalidrawView', `import type { TFile, WorkspaceLeaf } from "obsidian";
/** View identity and UI ownership for EA hooks. Use EA for drawing operations. */
export default interface ExcalidrawView {
readonly file: TFile | null;
readonly leaf: WorkspaceLeaf;
readonly contentEl: HTMLDivElement;
readonly ownerDocument: Document;
readonly ownerWindow: Window;
}`],
['shared/EmbeddedFileLoader', `declare const embeddedFilesLoader: unique symbol;
/** Opaque EA-owned handle. Obtain through ea.getEmbeddedFilesLoader(), then pass back to EA. */
export interface EmbeddedFilesLoader { readonly [embeddedFilesLoader]: never; }`],
['view/managers/CanvasNodeFactory', `declare const canvasNode: unique symbol;
/** Opaque embedded-canvas identity; Obsidian Canvas internals are not a scripting API. */
export interface ObsidianCanvasNode { readonly [canvasNode]: never; }`],
['view/sidepanel/SidepanelTab', `export type { SidepanelTab as ExcalidrawSidepanelTab } from "src/types/sidepanelTabTypes";`],
]);
const outputNames = {
'core/main': 'scriptPlugin', 'view/ExcalidrawView': 'scriptView',
'shared/ExcalidrawAutomate': 'excalidrawAutomate',
'shared/EmbeddedFileLoader': 'embeddedFilesLoader',
'view/managers/CanvasNodeFactory': 'embeddedCanvasNode',
'view/sidepanel/SidepanelTab': 'sidepanelTab',
'shared/Dialogs/FloatingModal': 'floatingModal',
'types/excalidrawLib': 'excalidrawLib',
'scriptUtils': 'scriptUtils',
};
const outputName = (name) => outputNames[name] ?? `support/${name}`;
function input(name) {
const lib = path.join(root, 'lib', `${name}.d.ts`);
return fs.readFileSync(fs.existsSync(lib) ? lib : path.join(root, 'src', `${name}.d.ts`), 'utf8');
}
// Utils are invocation helpers, not the ScriptEngine implementation class.
const scriptFile = ts.createSourceFile('Scripts.d.ts', input('shared/Scripts'), ts.ScriptTarget.Latest, true);
const engine = scriptFile.statements.find((node) => ts.isClassDeclaration(node));
function utility(name, skip) {
const method = engine.members.find((member) => member.name?.text === name);
const typeParameters = method.typeParameters?.length
? `<${method.typeParameters.map((p) => p.getText(scriptFile)).join(', ')}>` : '';
const result = name === 'inputPrompt' ? 'Promise<string | undefined>' : method.type.getText(scriptFile);
return `${name}${typeParameters}(${method.parameters.slice(skip).map((p) => p.getText(scriptFile)).join(', ')}): ${result};`;
}
const executionSource = scriptFile.statements.find((node) => node.name?.text === 'ScriptExecutionSource');
overrides.set('scriptUtils', `import type { TFile, Instruction } from "obsidian";
import type { ButtonDefinition, InputPromptOptions } from "src/types/promptTypes";
${executionSource.getText(scriptFile)}
export interface ScriptUtils {
${utility('inputPrompt', 3)}
inputPrompt(options: InputPromptOptions): Promise<string | undefined>;
${utility('suggester', 1)}
readonly scriptFile: TFile;
readonly executionSource: ScriptExecutionSource;
}`);
function module(name) {
if (modules.has(name)) return modules.get(name);
const file = ts.createSourceFile(`${name}.d.ts`, overrides.get(name) ?? input(name), ts.ScriptTarget.Latest, true);
const imports = new Map();
const declarations = new Map();
const reexports = new Map();
for (const statement of file.statements) {
if (ts.isImportDeclaration(statement)) {
const clause = statement.importClause;
if (clause?.name) imports.set(clause.name.text, { specifier: statement.moduleSpecifier.text, imported: 'default' });
const bindings = clause?.namedBindings;
if (bindings && ts.isNamedImports(bindings)) for (const item of bindings.elements) {
imports.set(item.name.text, { specifier: statement.moduleSpecifier.text, imported: item.propertyName?.text ?? item.name.text });
}
if (bindings && ts.isNamespaceImport(bindings)) imports.set(bindings.name.text, { specifier: statement.moduleSpecifier.text, imported: '*' });
} else if (ts.isExportDeclaration(statement) && statement.moduleSpecifier && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
for (const item of statement.exportClause.elements) reexports.set(item.name.text, { specifier: statement.moduleSpecifier.text, imported: item.propertyName?.text ?? item.name.text });
} else {
for (const key of names(statement)) declarations.set(key, statement);
if (statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) declarations.set('default', statement);
}
}
const result = { file, imports, declarations, reexports, usedImports: new Map(), usedExports: new Map(), emitted: new Set() };
modules.set(name, result);
return result;
}
function resolve(from, specifier) {
if (!specifier.startsWith('.') && !specifier.startsWith('src/')) {
external.add(specifier.startsWith('@') ? specifier.split('/').slice(0, 2).join('/') : specifier.split('/')[0]);
return { specifier, local: false };
}
let target = specifier.startsWith('src/') ? specifier.slice(4) : path.posix.normalize(path.posix.join(path.posix.dirname(from), specifier));
if (target.startsWith('../')) throw new Error(`Type import escapes source: ${specifier}`);
if (fs.existsSync(path.join(root, 'lib', target, 'index.d.ts'))) target += '/index';
let relative = path.posix.relative(path.posix.dirname(outputName(from)), outputName(target));
if (!relative.startsWith('.')) relative = `./${relative}`;
return { specifier: relative, local: true, target };
}
function request(name, symbol) {
if (!selected.has(name)) selected.set(name, new Set());
if (selected.get(name).has(symbol)) return;
selected.get(name).add(symbol);
pending.push([name, symbol]);
}
function follow(from, ref) {
const result = resolve(from, ref.specifier);
if (result.local) {
if (ref.imported === '*') throw new Error(`Unreviewed local namespace import in ${from}`);
request(result.target, ref.imported);
}
return result.specifier;
}
// Strip implementation-only members before traversing dependencies.
function project(name, declaration) {
if (ts.isClassDeclaration(declaration)) {
const members = declaration.members.filter((member) => !hidden(member) &&
!(name === 'shared/ExcalidrawAutomate' && ts.isConstructorDeclaration(member)));
return ts.factory.updateClassDeclaration(declaration, declaration.modifiers, declaration.name,
declaration.typeParameters, declaration.heritageClauses, members);
}
if (name === 'types/excalidrawLib' && ts.isModuleDeclaration(declaration)) {
const internal = /^(Obsidian.*Host.*|configureObsidian.*Host.*|OBSIDIAN_.*_HOST_PROTOCOL_VERSION)$/;
const body = ts.factory.updateModuleBlock(declaration.body, declaration.body.statements.filter((node) =>
!names(node).some((key) => internal.test(key))));
return ts.factory.updateModuleDeclaration(declaration, declaration.modifiers, declaration.name, body);
}
return declaration;
}
for (const [name, symbol] of [['shared/ExcalidrawAutomate', 'ExcalidrawAutomate'], ['types/excalidrawLib', 'ExcalidrawLib'], ['scriptUtils', 'ScriptUtils'], ['scriptUtils', 'ScriptExecutionSource']]) request(name, symbol);
while (pending.length) {
const [name, symbol] = pending.pop();
const current = module(name);
const reexport = current.reexports.get(symbol);
if (reexport) { current.usedExports.set(symbol, { ...reexport, specifier: follow(name, reexport) }); continue; }
const declaration = current.declarations.get(symbol);
if (!declaration) throw new Error(`Unresolved public type ${name}#${symbol}`);
const projected = project(name, declaration);
current.emitted.add(projected);
function visit(node) {
if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
const specifier = node.argument.literal.text;
const result = resolve(name, specifier);
if (result.local) {
if (!node.qualifier || !ts.isIdentifier(node.qualifier)) throw new Error(`Unsupported import type: ${node.getText(current.file)}`);
request(result.target, node.qualifier.text);
}
} else if (ts.isIdentifier(node)) {
const ref = current.imports.get(node.text);
if (ref) current.usedImports.set(node.text, { ...ref, specifier: follow(name, ref) });
else if (current.declarations.has(node.text)) request(name, node.text);
}
ts.forEachChild(node, visit);
}
visit(projected);
}
const files = new Map();
for (const [name, current] of modules) {
const imports = [...current.usedImports].map(([local, ref]) => {
const binding = ref.imported === 'default' ? local : ref.imported === '*' ? `* as ${local}` : `{ ${ref.imported === local ? local : `${ref.imported} as ${local}`} }`;
return `import type ${binding} from ${JSON.stringify(ref.specifier)};`;
});
const exports = [...current.usedExports].map(([local, ref]) => `export type { ${ref.imported === local ? local : `${ref.imported} as ${local}`} } from ${JSON.stringify(ref.specifier)};`);
const declarations = [...current.emitted].map((node) => {
const transformed = ts.transform(node, [(context) => {
const visit = (child) => {
if (ts.isImportTypeNode(child) && ts.isLiteralTypeNode(child.argument)) {
const specifier = resolve(name, child.argument.literal.text).specifier;
return ts.factory.updateImportTypeNode(child, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(specifier)), child.attributes, child.qualifier, child.typeArguments, child.isTypeOf);
}
return ts.visitEachChild(child, visit, context);
};
return (rootNode) => ts.visitNode(rootNode, visit);
}]);
const content = printer.printNode(ts.EmitHint.Unspecified, transformed.transformed[0], current.file);
transformed.dispose();
return content;
});
files.set(`${outputName(name)}.d.ts`, '// Generated scripting API. No plugin implementation declarations.\n' + [...imports, ...exports, ...declarations, 'export {};'].join('\n') + '\n');
}
return { files, external };
}
+9 -632
View File
@@ -1,641 +1,18 @@
/* eslint-disable no-console */
// to run: node skill-builder.mjs
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Reconstruct __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, '..');
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
const OUT_DIR = path.join(ROOT, 'docs', 'AITrainingData');
// Agent Skills Specific Definitions
const SKILL_NAME = 'excalidraw-automate';
const SKILL_DIR = path.join(OUT_DIR, SKILL_NAME);
const SKILL_REFERENCES_DIR = path.join(SKILL_DIR, 'references');
const SKILL_SCRIPTS_DIR = path.join(SKILL_REFERENCES_DIR, 'scripts');
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source Excalidraw component. Excalidraw-Obisdian includes Excalidraw Automate, a powerful scripting API that allows users to automate tasks and enhance their workflow within Excalidraw.
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via \`ea.getExcalidrawAPI()\`. Note: the API is only available if \`ea.targetView\` is set. When running Excalidraw scripts using the script engine, the provided \`ea\` object is already set up with targetView by default. Otherwise you need to first run \`ea.setView()\`.
- \`window.ExcalidrawLib\` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via \`ea\` (ExcalidrawAutomate) methods, ALWAYS prefer \`ea\` over \`window.ExcalidrawLib\`. \`ea\` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., \`const modal = new ea.FloatingModal(...)\`) and then assigning functions directly to the \`onOpen\` and \`onClose\` properties of that instance.
For a reference, follow the implementation pattern used in the "Printable Layout Wizard.md" script.
- Elements have a \`customData\` property that can be used to store arbitrary data. To ensure the data the script adds to elements use the \`ea.addAppendUpdateCustomData\` function. This function ensures that existing customData is preserved when adding new data.
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on \`ea.obsidian\`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (\`onOpen\`, \`onFocus(view)\`, \`onClose\`, \`onExcalidrawViewClosed\`) and manage their own \`ea.targetView\` explicitly.
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with \`ea.targetView === null\`. Scripts must handle this by deferring view-bound work until \`onFocus\` delivers a view; call \`ea.setView(view)\` when you decide to bind.
- Each \`ea\` instance may host a single \`sidepanelTab\`. This sidepanel tab is stored in \`ea.sidepanelTab\`. Create the tab with \`ea.createSidepanelTab(title, persist=false, reveal=true)\`; the returned \`ea.sidepanelTab\` exposes \`contentEl\`, \`setContent\`, \`setTitle\`, \`setDisabled\`, \`setCloseCallback\`, \`open/close\`, and focus lifecycle hooks. Note auto-reveal during tab creation via \`ea.createSidepanelTab()\` is disabled during plugin startup. You can reveal a tab with \`ea.sidepanelTab?.open()\`. You can persist with \`ea.persistSidepanelTab()\` (tabs are restored and scripts re-run on next startup). Close with \`ea.sidepanelTab?.close()\`.
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-\`ExcalidrawView\` relevant, they can call \`ea.closeSidepanelTab()\` after completing the operation, and/or inside \`ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }\` to shut down when the user leaves the originating view.
- Scripts can detect view change in \`onFocus(view)\` by comparing \`ea.targetView\` to the provided \`view\` parameter.
- Persistence UX: scripts may offer a “Persist tab” control inside \`contentEl\` that calls \`ea.persistSidepanelTab()\`. Once persisted, hide that control; users can later remove the tab via the sidepanel close button (scripts cannot unpersist themselves, but can close themselves via \`ea.sidepanelTab?.close()\`).
- Use \`checkForActiveSidepanelTabForScript\` to avoid creating duplicate tabs for the same script name. This method returns the \`ExcalidrawSidepanelTab\` associated with the supplied \`scriptName\` (or \`ea.activeScript\` when omitted), or \`null\` if none exists. It is intended to let a script detect an existing tab that may be owned by another \`ExcalidrawAutomate\` instance (for example, a persisted tab restored at startup). Typical pattern:
- Before creating a new sidepanel, call \`ea.checkForActiveSidepanelTabForScript()\` to see if a tab already exists.
- If a tab exists and \`tab.getHostEA() === ea\`, reuse it (your script already hosts it).
- If a tab exists but is hosted by a different \`ea\` instance, decide whether to reuse or hand off control — e.g. open the existing tab and exit to avoid duplicates.
- Note: persisted tabs restored on startup may be created with \`ea.targetView === null\` and hosted by a different \`ea\` instance; handle that case by waiting for \`onFocus\` before binding view-specific work.
- Example usage:
\`const sp = ea.checkForActiveSidepanelTabForScript();
if (sp) {
if (sp.getHostEA() === ea) {
// we already own the tab — reuse it
sp.open();
} else {
// another EA instance hosts the tab — open it for the user and exit
sp.open();
return;
}
}
// no existing tab — safe to create a new one
// ea.createSidepanelTab("My Script", false, true);\`
- A dedicated section "sidepanelTabTypes.d.ts" in this document lists the \`ExcalidrawSidepanelTab\` function signatures.
#### **0. External Documentation & Resources**
To keep this training file concise, large external type definitions are not included. If you need to look up Obsidian APIs or Excalidraw internals, refer to the following resources:
- **Obsidian API Type Definitions:** https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
- **Obsidian Developer Docs:** https://docs.obsidian.md/Home (Community site with API and CSS documentation/examples)
- **Obsidian Developer Forum:** https://forum.obsidian.md/c/developers-api/14
- **ExcalidrawAutomate Implementation:** If the provided API documentation is unclear, consult the source directly: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/shared/ExcalidrawAutomate.ts
- **Excalidraw Core Fork:** For doubts regarding core Excalidraw functionality, consult the fork used by the plugin: https://github.com/zsviczian/excalidraw
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
* **The Workflow:**
1. Get elements from the current view using \`ea.getViewElements()\` or \`ea.getViewSelectedElements()\`.
2. Copy these elements into the EA workbench for editing using \`ea.copyViewElementsToEAforEditing(elements)\`.
3. Modify the properties of the element copies that are now in the EA workbench (e.g., \`ea.getElement(id).locked = true;\`).
4. Commit the changes back to the scene using \`await ea.addElementsToView()\`.
* **Deletion:** To delete an element, set its \`isDeleted\` property to \`true\` on the workbench copy (\`ea.getElement(id).isDeleted = true;\`) and then commit with \`await ea.addElementsToView()\`.
* **Cleanup:** Use \`ea.clear()\` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
#### **2. User Interaction: Prompts and Dialogs**
* **Simple Input:** For straightforward user input, use the \`utils\` object provided to the script.
* \`await utils.inputPrompt()\`: To get a string or number from the user.
* \`await utils.suggester()\`: To let the user select from a predefined list of options.
* **Complex Dialogs:** When a more complex UI with multiple controls is needed, create a floating dialog window.
* **Use \`FloatingModal\`:** Always create a new instance: \`const modal = new ea.FloatingModal(ea.plugin.app);\`.
* **Do Not Extend:** Do not use \`class MyModal extends ea.FloatingModal\`.
* **Define Behavior:** Assign functions directly to the \`onOpen\` and \`onClose\` properties of the instance. Inside \`onOpen\`, use the \`modal.contentEl\` property to build your UI.
* **Reference Implementation:** The script "Printable Layout Wizard.md" is the canonical example for this pattern. Use \`ea.obsidian.Setting\` to add controls like toggles and dropdowns within the modal.
#### **3. Element Manipulation and Querying**
* **Finding Elements:** The most common starting point is to get the user's selection with \`ea.getViewSelectedElements()\`. Use standard JavaScript array methods like \`.filter()\` to narrow down the selection (e.g., \`elements.filter(el => el.type === "text")\`).
* **Geometric Calculations:**
* Before performing layout or positioning tasks, use \`ea.getBoundingBox(elements)\` to get the collective dimensions and position of a group of elements.
* Use \`ea.measureText(text)\` to determine the width and height of a string based on the current \`ea.style\` settings before creating a text element or a container for it.
* **Grouping:**
* To create a group, use \`ea.addToGroup([elementId1, elementId2, ...])\`.
* To operate on existing groups within a selection, use \`ea.getMaximumGroups(selectedElements)\` which correctly identifies the top-level groups. Use \`ea.getLargestElement(group)\` to find the primary container within a group (e.g., the box around a text element).
#### **4. Styling: Creation vs. Modification**
* **For New Elements:** Set the properties on the global \`ea.style\` object *before* you call a creation function like \`ea.addText()\` or \`ea.addRect()\`. This acts like setting the active color/style on a paintbrush.
* **For Existing Elements:** To change the style of an existing element, modify the properties directly on the element's copy in the EA workbench (after \`copyViewElementsToEAforEditing\`). For example: \`const myElement = ea.getElement(id); myElement.strokeColor = '#FF0000';\`.
#### **5. Data Persistence and Customization**
* **Storing Custom Data:** Elements have a \`customData\` property for arbitrary data.
* **Always Use \`ea.addAppendUpdateCustomData(id, newData)\`:** This is crucial. It safely adds or updates your key-value pairs without overwriting data that might have been stored by other scripts or the Excalidraw plugin itself.
* **Creating Configurable Scripts:** To make your script's behavior customizable by the user:
* Use \`ea.getScriptSettings()\` to retrieve saved settings.
* scriptSettings are stored with Excalidraw settings in Obsidian data.json. Keep this light. You MUST NEVER save large data objects such as base64 images or huge arrays here. Keep this lean and efficient.
* Check if settings exist, and if not, define the default structure.
* Use \`await ea.setScriptSettings(settings)\` to save any changes. This allows users to configure your script in the Excalidraw plugin settings pane.
#### **6. Best Practices and Advanced Techniques**
* **Script Overview Block (MANDATORY):** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
* **Strictly Modular Architecture (NO LOOSE CODE):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well; if the UI includes sections, tabs, or panels, these should be rendered via sub-functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
* **Evergreen JSDoc Headers and Comments:** Every function must have a proper JSDoc/Javadoc-style header containing parameter names, types, and a clear description of the function's purpose. These descriptions must be kept *evergreen* (updated alongside any code changes). Additionally, when modifying or updating a script, you must strictly *retain all existing internal code comments*.
* **Isolate Constants and User-Facing Strings:** *Do not embed hardcoded magic values, config parameters, or UI strings deep inside the logic.* You must separate all constants and language strings and collect them at the very top of the file. This makes it easier to tweak values later and provides a clear, unified section for localization and customization.
* **Icons:** Obsidian uses https://lucide.dev icons. These icons are available for scripts via \`ea.obsidian.getIcon("Icon Name")\`. For UI components prefer use of lucide.dev icons.
* **Omit Version Verification:** While many of the sample scripts in the library include a version verification block at the outset (using \`ea.verifyMinimumPluginVersion\`), *do not add this section* when generating a new script unless explicitly instructed to do so.
* **Embrace \`await\`:** Many EA functions are asynchronous and return a \`Promise\` (e.g., \`ea.addElementsToView()\`, \`ea.createSVG()\`, \`utils.inputPrompt()\`). **Always** use \`await\` when calling these functions to ensure your script executes in the correct order.
* **Accessing Obsidian API:** The full Obsidian API is available via \`ea.obsidian\`. For example, use \`new ea.obsidian.Notice("message")\` or \`ea.obsidian.normalizePath(filepath)\`.
* **Accessing Excalidraw API:** The full Excalidraw API is available on \`ea.getExcalidrawAPI()\`, these API functions are Scene dependent. Additional support functions are available on \`window.ExcalidrawLib\`.
* **Visibility vs. Deletion:**
* To temporarily hide an element, set \`element.opacity = 0\`. It's good practice to store the original opacity in \`customData\` so it can be restored. It is also recommended to lock hidden elements so they do not get accidentally selected or moved around.
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. You can use the \`elementsOverride\` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
#### **8. Custom Pens and Perfect Freehand**
Excalidraw's freehand tool is powered by the open-source Perfect Freehand library. The plugin exposes “custom pens” that bundle:
- Canvas style for the next strokes (colors, width, fillStyle, roughness).
- Perfect Freehand stroke geometry and behavior (pressure simulation, outline, tapering, easing, etc.).
Key concepts:
- AppState-driven drawing: When \`appState.currentStrokeOptions\` is set, the freedraw tool renders new strokes using those Perfect Freehand options.
- Element-level persistence: If a freedraw element has \`element.customData.strokeOptions\`, it is rendered with those options regardless of the current tool state.
- Types reference: See \`src/types/penTypes.ts\`. The \`PenOptions\` shape is:
\`\`\`ts
interface PenOptions {
highlighter: boolean; // if true the pen is drawn at the lowest layer, behind all other elements
constantPressure: boolean;
hasOutline: boolean;
outlineWidth: number;
options: {
thinning: number;
smoothing: number;
streamline: number;
easing: string; // see supported names below
start: { cap: boolean; taper: number | boolean; easing: string; };
end: { cap: boolean; taper: number | boolean; easing: string; };
};
}
\`\`\`
Using custom pens from scripts:
- Activate a custom pen for drawing:
\`\`\`ts
// obtain the Excalidraw API
const api = ea.getExcalidrawAPI();
// define Perfect Freehand options (example similar to "finetip")
const penOptions = {
highlighter: false,
constantPressure: true,
hasOutline: false,
outlineWidth: 1,
options: {
thinning: -0.5,
smoothing: 0.4,
streamline: 0.4,
easing: "linear",
start: { taper: 5, cap: false, easing: "linear" },
end: { taper: 5, cap: false, easing: "linear" },
},
};
// apply stroke options + canvas style, then switch to freedraw (strokeWidth, color, background, fillStyle are optional)
ea.viewUpdateScene({
appState: {
currentStrokeOptions: penOptions,
currentItemStrokeWidth: 0.5,
currentItemStrokeColor: "#3E6F8D",
currentItemBackgroundColor: "transparent",
currentItemFillStyle: "hachure",
},
});
api.setActiveTool({ type: "freedraw" });
\`\`\`
- Clear custom pen (revert to default freedraw behavior):
\`\`\`ts
ea.viewUpdateScene({ appState: { currentStrokeOptions: null } });
\`\`\`
- Persist custom strokeOptions onto existing freedraw elements:
\`\`\`ts
const selected = ea.getViewSelectedElements().filter(el => el.type === "freedraw");
ea.copyViewElementsToEAforEditing(selected);
for (const el of selected) {
ea.addAppendUpdateCustomData(el.id, { strokeOptions: penOptions });
}
await ea.addElementsToView();
\`\`\`
Notes:
- New strokes respect \`appState.currentStrokeOptions\` at draw time. Existing elements only change if you update their \`customData.strokeOptions\`.
- For pens that should behave like real markers/highlighters, set \`highlighter: true\` and often \`constantPressure: true\` with an \`outlineWidth\` for the edge.
Supported easing names (string values for \`options.easing\`, \`options.start.easing\`, \`options.end.easing\`):
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce.
Example freedraw element carrying \`customData.strokeOptions\`:
\`\`\`json
{"type":"excalidraw/clipboard","elements":[{"id":"...","type":"freedraw","strokeColor":"#3E6F8D","backgroundColor":"transparent","fillStyle":"hachure","strokeWidth":0.5,"roughness":0,"customData":{"strokeOptions":{"highlighter":false,"hasOutline":false,"outlineWidth":0,"constantPressure":true,"options":{"smoothing":0.4,"thinning":-0.5,"streamline":0.4,"easing":"linear","start":{"taper":5,"cap":false,"easing":"linear"},"end":{"taper":5,"cap":false,"easing":"linear"}}}}}],"files":{}}
\`\`\`
#### **9. Text Element**
* There are three text properties.
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
`;
const EXCALIDRAW_STARTUP_MESSAGE = `# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
`;
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
const TYPE_DEF_WHITELIST = [
"lib/shared/ExcalidrawAutomate.d.ts",
"lib/types/excalidrawAutomateTypes.d.ts",
"lib/types/sidepanelTabTypes.d.ts",
"lib/types/penTypes.d.ts",
"lib/types/utilTypes.d.ts",
"lib/types/exportUtilTypes.d.ts",
"lib/types/embeddedFileLoaderTypes.d.ts",
"lib/types/AIUtilTypes.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts",
];
/**
* Returns true if content contains at least one line starting with ```
* and has an odd number of fences (unbalanced).
*/
function needsClosingFence(content) {
const fenceCount = (content.match(/^```/gm) || []).length;
return fenceCount > 0 && fenceCount % 2 === 1;
}
function normalizeEOL(str) {
return str.replace(/\r\n/g, '\n');
}
function stripBOM(str) {
return str.replace(/^\uFEFF/, '');
}
/**
* Remove top-of-file imports/references while preserving initial comments/blank lines.
* Also removes bare "export {}" lines (module markers).
*/
function stripTopImports(content) {
const lines = normalizeEOL(stripBOM(content)).split('\n');
const out = [];
let inTopRegion = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isImport =
/^\s*import\s+type\s+/.test(line) ||
/^\s*import\s+/.test(line) ||
/^\s*import\(/.test(line);
const isTripleRef = /^\s*\/\/\/\s*<reference/.test(line);
const isBareExportModule = /^\s*export\s*\{\s*\};?\s*$/.test(line);
if (inTopRegion) {
if (isImport || isTripleRef) {
continue;
}
const isBlank = /^\s*$/.test(line);
const isLineComment = /^\s*\/\//.test(line);
const isBlockCommentStart = /^\s*\/\*/.test(line);
if (!isBlank && !isLineComment && !isBlockCommentStart) {
inTopRegion = false;
}
if (!isBareExportModule) out.push(line);
continue;
}
if (!isBareExportModule) out.push(line);
}
return out.join('\n').trim() + '\n';
}
function makeSectionHeader(relPath) {
const stars = '*'.repeat(Math.max(6, Math.min(38, relPath.length + 6)));
return [
`/* ${stars} */`,
`/* ${relPath} */`,
`/* ${stars} */`,
].join('\n') + '\n';
}
function buildTypeDefMarkdown() {
const entries = TYPE_DEF_WHITELIST.map((rel) => ({
rel,
abs: path.join(ROOT, ...rel.split('/')),
}));
let body = '# ExcalidrawAutomate library and related type definitions\n\n```js\n';
for (const { rel, abs } of entries) {
if (!fs.existsSync(abs)) {
console.warn('[skill-builder] Whitelist file missing:', rel);
continue;
}
let content = fs.readFileSync(abs, 'utf8');
content = stripTopImports(content);
body += makeSectionHeader(rel);
body += content.trimEnd() + '\n\n';
}
body += '```\n';
return body;
}
function resolveExcalModulePath(spec, excalIndexAbs) {
const baseTypesRoot = path.join(ROOT, 'node_modules', '@zsviczian', 'excalidraw', 'types');
if (spec.startsWith('@excalidraw/')) {
const sub = spec.slice('@excalidraw/'.length);
const parts = sub.split('/');
const pkg = parts.shift();
const rest = parts;
if (!pkg) return null;
const base = path.join(baseTypesRoot, pkg);
if (rest.length === 0) {
return path.join(base, 'src', 'index.d.ts');
}
return path.join(base, 'src', ...rest) + '.d.ts';
}
if (spec.startsWith('.')) {
const dir = path.dirname(excalIndexAbs);
return path.resolve(dir, spec) + '.d.ts';
}
return null;
}
function extractFunctionSignaturesFromModule(absPath, names) {
const out = {};
if (!absPath || !fs.existsSync(absPath)) {
return out;
}
const content = fs.readFileSync(absPath, 'utf8');
for (const rawName of names) {
const name = rawName.trim();
if (!name) continue;
let m = content.match(new RegExp(`export\\s+declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
m = content.match(new RegExp(`(^|\\n)declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].replace(/^\s*declare\s+/, 'export declare ').trim();
continue;
}
m = content.match(new RegExp(`export\\s+declare\\s+const\\s+${name}\\s*:\\s*[\\s\\S]*?=>[\\s\\S]*?;`, 'm'));
if (m) {
out[name] = m[0].trim();
continue;
}
m = content.match(new RegExp(`export\\s+declare\\s+(?:var|let|const)\\s+${name}\\s*:\\s*[\\s\\S]*?;`, 'm'));
if (m && /=>/.test(m[0])) {
out[name] = m[0].trim();
continue;
}
}
return out;
}
function buildExcalidrawLibFunctionsSection() {
const excalIndexRel = 'node_modules/@zsviczian/excalidraw/types/excalidraw/index.d.ts';
const excalIndexAbs = path.join(ROOT, ...excalIndexRel.split('/'));
if (!fs.existsSync(excalIndexAbs)) {
console.warn('[skill-builder] Missing Excalidraw index.d.ts:', excalIndexRel);
return '';
}
const content = fs.readFileSync(excalIndexAbs, 'utf8');
const reExport = /export\s*\{\s*([\s\S]*?)\s*\}\s*from\s*["']([^"']+)["'];/g;
const moduleToNames = new Map();
for (const match of content.matchAll(reExport)) {
const namesChunk = match[1];
const spec = match[2];
const names = namesChunk
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (!names.length) continue;
const abs = resolveExcalModulePath(spec, excalIndexAbs);
if (!abs) continue;
const key = spec;
const curr = moduleToNames.get(key) || { abs, names: new Set() };
for (const n of names) curr.names.add(n);
moduleToNames.set(key, curr);
}
const seen = new Set();
const sections = [];
for (const [spec, { abs, names }] of moduleToNames) {
const sigs = extractFunctionSignaturesFromModule(abs, Array.from(names));
const sigEntries = Object.entries(sigs)
.filter(([name]) => {
if (seen.has(name)) return false;
seen.add(name);
return true;
})
.sort(([a], [b]) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
if (!sigEntries.length) continue;
const rel = path.relative(ROOT, abs).replace(/\\/g, '/');
const header = makeSectionHeader(`${spec} -> ${rel}`);
sections.push(header + sigEntries.map(([, s]) => s).join('\n') + '\n');
}
return '# ExcalidrawLib module functions\n\n' +
'The following functions are exposed via window.ExcalidrawLib. Signatures are extracted from TypeScript declarations.\n\n' +
'```ts\n' +
sections.join('\n') +
'```\n';
}
import { runUnifiedGeneration } from './excalidraw-docs-generator-core.mjs';
function main() {
console.log('[skill-builder] Generating Excalidraw Agent Skill...');
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
process.exit(1);
}
// Ensure directories exist
fs.mkdirSync(SKILL_DIR, { recursive: true });
fs.mkdirSync(SKILL_REFERENCES_DIR, { recursive: true });
// Create or clean the scripts directory
if (fs.existsSync(SKILL_SCRIPTS_DIR)) {
fs.rmSync(SKILL_SCRIPTS_DIR, { recursive: true, force: true });
}
fs.mkdirSync(SKILL_SCRIPTS_DIR, { recursive: true });
// Read exclusions
const args = process.argv.slice(2);
const cmdLineExcludes = args.map(arg => arg.toLowerCase());
const defaultExcludes = ['index-new.md', 'mindmap builder.md', 'color scheme manager.md', 'comic strip director.md'];
const exclusions = new Set([...defaultExcludes, ...cmdLineExcludes]);
// Collect scripts
const files = fs
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
.filter(
(d) =>
d.isFile() &&
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
!exclusions.has(d.name.toLowerCase())
)
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
// Prepare API Index Map
const apiIndex = {
ExcalidrawAutomate: {},
ExcalidrawAPI: {},
ExcalidrawLib: {}
};
function addUsage(category, method, scriptName) {
// Filter out obvious noise or generic javascript attributes
const ignoreList = ['length', 'push', 'map', 'filter', 'forEach', 'includes', 'join', 'toString', 'toLowerCase'];
if (ignoreList.includes(method)) return;
if (method.length < 2) return;
if (!apiIndex[category][method]) {
apiIndex[category][method] = new Set();
}
apiIndex[category][method].add(scriptName);
}
console.log('[skill-builder] Processing scripts and building API Index...');
for (const file of files) {
const full = path.join(EA_SCRIPTS_DIR, file);
let content = fs.readFileSync(full, 'utf8').replace(/\r\n/g, '\n');
// Fix missing fences
if (needsClosingFence(content)) {
content += '\n```\n';
}
// Write individual script to references/scripts/
fs.writeFileSync(path.join(SKILL_SCRIPTS_DIR, file), content, 'utf8');
// Parse API Usage
// 1. ExcalidrawAutomate: ea.functionName
const eaMatches = [...content.matchAll(/ea\.([a-zA-Z0-9_]+)/g)];
eaMatches.forEach(m => addUsage('ExcalidrawAutomate', m[1], file));
// 2. ExcalidrawAPI: api.functionName or ea.getExcalidrawAPI().functionName
const apiMatches = [...content.matchAll(/(?:getExcalidrawAPI\(\)|api)\.([a-zA-Z0-9_]+)/g)];
apiMatches.forEach(m => addUsage('ExcalidrawAPI', m[1], file));
// 3. ExcalidrawLib: ExcalidrawLib.functionName or window.ExcalidrawLib.functionName
const libMatches = [...content.matchAll(/(?:window\.)?ExcalidrawLib\.([a-zA-Z0-9_]+)/g)];
libMatches.forEach(m => addUsage('ExcalidrawLib', m[1], file));
}
// Generate API Usage Index Markdown
console.log('[skill-builder] Writing api-usage-index.md...');
let apiIndexContent = `# Excalidraw API Usage Index\n\n`;
apiIndexContent += `This index maps methods and properties from ExcalidrawAutomate (\`ea\`), ExcalidrawAPI, and ExcalidrawLib to the example scripts that use them. Use this to find real-world examples of how to implement specific features.\n\n`;
for (const [category, methods] of Object.entries(apiIndex)) {
apiIndexContent += `## ${category}\n\n`;
const sortedMethods = Object.keys(methods).sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
if (sortedMethods.length === 0) {
apiIndexContent += `*No usages found.*\n\n`;
continue;
}
for (const method of sortedMethods) {
const scriptLinks = Array.from(methods[method])
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }))
.map(script => `[${script}](scripts/${script.replace(/ /g, '%20')})`)
.join(', ');
apiIndexContent += `- **${method}**: ${scriptLinks}\n`;
}
apiIndexContent += `\n`;
}
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'api-usage-index.md'), apiIndexContent, 'utf8');
// Write Type Definitions
console.log('[skill-builder] Writing type-definitions.md...');
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'type-definitions.md'), buildTypeDefMarkdown(), 'utf8');
// Write ExcalidrawLib Functions
console.log('[skill-builder] Writing excalidraw-lib-functions.md...');
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'excalidraw-lib-functions.md'), buildExcalidrawLibFunctionsSection(), 'utf8');
// Write Startup Scripts template
console.log('[skill-builder] Writing startup-scripts.md...');
const startupTemplatePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_TEMPLATE.split('/'));
const startupExamplePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_EXAMPLE.split('/'));
const startupTemplate = fs.existsSync(startupTemplatePath)
? fs.readFileSync(startupTemplatePath, 'utf8').replace(/\r\n/g, '\n').trim()
: '';
const startupExample = fs.existsSync(startupExamplePath)
? fs.readFileSync(startupExamplePath, 'utf8').replace(/\r\n/g, '\n').trim()
: '';
const startupSection = EXCALIDRAW_STARTUP_MESSAGE + '\n\n' +
(startupTemplate ? `### Template\n\`\`\`js\n${startupTemplate}\n\`\`\`\n\n` : '') +
(startupExample ? `### Example\n\`\`\`js\n${startupExample}\n\`\`\`\n` : '');
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'startup-scripts.md'), startupSection, 'utf8');
// Write SKILL.md
console.log('[skill-builder] Writing SKILL.md...');
const skillMdPath = path.join(SKILL_DIR, 'SKILL.md');
const skillFrontmatter = `---
name: ${SKILL_NAME}
description: Write and manipulate ExcalidrawAutomate scripts for Obsidian.md. Use when the user wants to create, modify, or understand an Excalidraw script.
---
`;
let skillIntro = AI_TRAINING_INTRO
.replaceAll("https://youtu.be/", "YouTube: ")
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
.replaceAll("https://www.youtube.com/", "YouTube: ");
skillIntro += `
## References
The \`references/\` directory contains supporting documentation necessary for writing scripts:
- \`references/type-definitions.md\`: Core type definitions for ExcalidrawAutomate.
- \`references/excalidraw-lib-functions.md\`: Function signatures for \`window.ExcalidrawLib\`.
- \`references/startup-scripts.md\`: ExcalidrawStartup script template and examples.
- \`references/api-usage-index.md\`: A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
- \`references/scripts/\`: A folder containing all the raw, real-world example scripts.
### How to use the Script Examples
If you need to implement a specific function (e.g., \`ea.addElementsToView\`), do NOT guess its implementation context. Instead:
1. Open \`references/api-usage-index.md\`.
2. Find the function name.
3. Note the scripts listed next to it.
4. Read the corresponding script inside the \`references/scripts/\` directory to see a complete, working example of how the function is used in context.
`;
fs.writeFileSync(skillMdPath, skillFrontmatter + skillIntro, 'utf8');
console.log('[skill-builder] Done.');
console.log('[skill-builder] Running unified documentation generator (full mode)...');
const result = runUnifiedGeneration({
mode: 'full',
args: process.argv.slice(2),
});
console.log('[skill-builder] Wrote outputs:', result.generated);
console.log('[skill-builder] Processed scripts:', result.scriptsProcessed);
}
// ESM equivalent of `if (require.main === module)`
if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
main();
@@ -643,4 +20,4 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
console.error('[skill-builder] Failed:', e);
process.exit(1);
}
}
}
+69
View File
@@ -0,0 +1,69 @@
// Publishes a restricted scripting API projection, never the plugin implementation graph.
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import ts from 'typescript';
import { projectScriptApi } from './script-api-projection.mjs';
const log = (...args) => console.log(...args);
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
export function syncScriptTemplateTypes(templateRoot = path.resolve(root, '../ea-script-template')) {
if (!fs.existsSync(templateRoot)) return;
const output = path.join(templateRoot, '.template/types');
const { files: projectedFiles, external } = projectScriptApi(root);
const declarations = new Map();
function forkPath(specifier) {
return specifier
.replace(/^@zsviczian\/excalidraw\/types\/excalidraw$/, '@zsviczian/excalidraw')
.replace(/^@zsviczian\/excalidraw\/types\/excalidraw\//, '@zsviczian/excalidraw/')
.replace(/^@zsviczian\/excalidraw\/types\/(common|element|math|utils)\/src(?:\/index)?$/, '@zsviczian/excalidraw/$1/index')
.replace(/^@zsviczian\/excalidraw\/types\/(common|element|math|utils)\/src\//, '@zsviczian/excalidraw/$1/')
.replace(/^@excalidraw\/excalidraw\//, '@zsviczian/excalidraw/')
.replace(/^@excalidraw\/(common|element|math|utils)$/, '@zsviczian/excalidraw/$1/index')
.replace(/^@excalidraw\/(common|element|math|utils)\//, '@zsviczian/excalidraw/$1/');
}
for (const [name, source] of projectedFiles) {
let content = source;
for (const item of ts.preProcessFile(content).importedFiles.toReversed()) {
content = content.slice(0, item.pos + 1) + forkPath(item.fileName) + content.slice(item.end + 1);
}
declarations.set(name, content);
}
const pluginPackage = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const pkgPath = path.join(templateRoot, 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const forkPackage = JSON.parse(fs.readFileSync(path.join(root, 'node_modules/@zsviczian/excalidraw/package.json'), 'utf8'));
const dependencies = { ...forkPackage.devDependencies, ...pluginPackage.dependencies, ...pluginPackage.devDependencies };
external.add('@excalidraw/mermaid-to-excalidraw');
// Retire dependencies added by the old implementation-graph snapshot.
for (const name of ['react-dom', '@zsviczian/excalidraw-extras-api']) delete pkg.devDependencies[name];
for (const name of external) {
if (name === 'react') { pkg.devDependencies['@types/react'] = dependencies['@types/react']; continue; }
if (name === 'polybooljs') continue; // Included ambient declaration, no runtime dependency.
if (!dependencies[name]) throw new Error(`No declared version for type dependency ${name}`);
// Use the template's supported Obsidian baseline; never downgrade it during generation.
if (name === 'obsidian') continue;
pkg.devDependencies[name] = dependencies[name];
}
fs.rmSync(output, { recursive: true, force: true });
for (const [name, content] of declarations) {
const target = path.join(output, name);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, content);
}
fs.copyFileSync(path.join(root, 'src/types/polybooljs.d.ts'), path.join(output, 'polybooljs.d.ts'));
const revision = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim();
const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));
fs.writeFileSync(path.join(templateRoot, '.template/api-source.json'), JSON.stringify({
repository: 'https://github.com/zsviczian/obsidian-excalidraw-plugin', revision,
sourceDirty: Boolean(execFileSync('git', ['status', '--porcelain', '--', 'src', 'package.json', 'manifest.json'], { cwd: root, encoding: 'utf8' }).trim()),
pluginVersion: manifest.version, excalidrawVersion: dependencies['@zsviczian/excalidraw'],
}, null, 2) + '\n');
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
log(`[template-types] Synced ${declarations.size} declaration files from ${revision}`);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) syncScriptTemplateTypes(process.argv[2]);
+49
View File
@@ -0,0 +1,49 @@
import { cpSync, existsSync, lstatSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { join, relative, resolve } from "node:path";
const sourceRoot = resolve(
process.env.REPO_UPDATE_DIR || join(homedir(), "Downloads", "update"),
);
const destinationRoot = process.cwd();
if (!existsSync(sourceRoot) || !lstatSync(sourceRoot).isDirectory()) {
console.error(`Update folder not found: ${sourceRoot}`);
process.exit(1);
}
let copiedFiles = 0;
function countFiles(path) {
const stat = lstatSync(path);
if (stat.isSymbolicLink() || stat.isFile()) return 1;
if (!stat.isDirectory()) return 0;
let count = 0;
for (const entry of readdirSync(path)) {
count += countFiles(join(path, entry));
}
return count;
}
console.log(`Updating repository from: ${sourceRoot}`);
for (const entry of readdirSync(sourceRoot, { withFileTypes: true })) {
const source = join(sourceRoot, entry.name);
const destination = join(destinationRoot, entry.name);
const entryFileCount = countFiles(source);
cpSync(source, destination, {
recursive: true,
force: true,
errorOnExist: false,
dereference: false,
preserveTimestamps: true,
verbatimSymlinks: true,
});
copiedFiles += entryFileCount;
console.log(`Copied ${relative(sourceRoot, source)}`);
}
console.log(`Repository update complete. Copied ${copiedFiles} file${copiedFiles === 1 ? "" : "s"}.`);
+12 -1
View File
@@ -1,6 +1,17 @@
/*
#exclude
```js*/
/**
* Startup scripts receive the plugin-global EA for the plugin lifetime and
* utils.executionSource === "plugin-startup". Register cleanup for resources
* outside EA so plugin reload/unload cannot accumulate them.
*/
// const ref = app.workspace.on("file-open", (file) => {});
// ea.registerCleanup(() => app.workspace.offref(ref));
//
// const interval = window.setInterval(() => {}, 1000);
// ea.registerCleanup(() => window.clearInterval(interval));
/**
* If set, this callback is triggered when the user closes an Excalidraw view.
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
@@ -317,4 +328,4 @@
// elementCount: elements.length
// });
// }
// };
// };
+4 -2
View File
@@ -1,6 +1,6 @@
import { customAlphabet } from "nanoid";
import { ExcalidrawLib } from "../types/excalidrawLib";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { DeviceType } from "src/types/types";
import { errorHandler } from "../utils/ErrorHandler";
import { getLanguage } from "obsidian";
@@ -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") {
@@ -244,7 +247,6 @@ export const ROUNDNESS = {
export const THEME_FILTER = "invert(93%) hue-rotate(180deg) saturate(1.25)";
export const URLFETCHTIMEOUT = 3000;
export const PLUGIN_ID = "obsidian-excalidraw-plugin";
export const SCRIPT_INSTALL_CODEBLOCK = "excalidraw-script-install";
export const SCRIPT_INSTALL_FOLDER = "Downloaded";
export const fileid = customAlphabet("1234567890abcdef", 40);
export const REG_LINKINDEX_INVALIDCHARS = /[<>:"\\|?*#]/g;
+62 -7
View File
@@ -42,6 +42,47 @@ export function buildSafeUrl(
return `https://${domain}${path}`;
}
// Replaced by Rollup from the checked-out Git repository and branch.
declare const __PLUGIN_REPOSITORY_OWNER__: string;
declare const __PLUGIN_REPOSITORY_NAME__: string;
declare const __PLUGIN_REPOSITORY_REF__: string;
export const PLUGIN_REPOSITORY_OWNER = __PLUGIN_REPOSITORY_OWNER__;
export const PLUGIN_REPOSITORY_NAME = __PLUGIN_REPOSITORY_NAME__;
export const PLUGIN_REPOSITORY_REF = __PLUGIN_REPOSITORY_REF__;
const PLUGIN_REPOSITORY_PATH = [
PLUGIN_REPOSITORY_OWNER,
PLUGIN_REPOSITORY_NAME,
] as const;
const pathParts = (value: string): string[] =>
value
.split("/")
.filter(Boolean)
.map((part) => encodeURIComponent(part));
export const getPluginRepositoryRawUrl = (repositoryPath: string): string =>
buildSafeUrl(
["raw", "githubusercontent", "com"],
[
...PLUGIN_REPOSITORY_PATH,
...pathParts(PLUGIN_REPOSITORY_REF),
...pathParts(repositoryPath),
],
);
export const getPluginRepositoryBlobUrl = (repositoryPath: string): string =>
buildSafeUrl(
["github", "com"],
[
...PLUGIN_REPOSITORY_PATH,
"blob",
...pathParts(PLUGIN_REPOSITORY_REF),
...pathParts(repositoryPath),
],
);
// Helper to enforce type structure in the registry
const defineUrl = (url: string, purpose: string) => ({ url, purpose });
@@ -51,7 +92,22 @@ const defineUrl = (url: string, purpose: string) => ({ url, purpose });
export const URL_REGISTRY = {
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON:
defineUrl(
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/directory-info.json",
getPluginRepositoryRawUrl("ea-scripts/directory-info.json"),
UrlPurpose.APP_LOGIC,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_SCRIPT_STORE_JSON:
defineUrl(
getPluginRepositoryRawUrl("ea-scripts/script-store.json"),
UrlPurpose.APP_LOGIC,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPTING_MD:
defineUrl(
getPluginRepositoryBlobUrl("docs/ea-scripting.md"),
UrlPurpose.DOCS,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_IMAGE_BANNER_AUTOMATE_ANYTHING_PNG:
defineUrl(
getPluginRepositoryRawUrl("images/banner-automate-anything.png"),
UrlPurpose.APP_LOGIC,
),
API_GITHUB_COM_REPOS_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES: defineUrl(
@@ -62,6 +118,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",
@@ -103,7 +163,7 @@ export const URL_REGISTRY = {
UrlPurpose.SUPPORT,
),
COMMUNITY_SKETCH_YOUR_MIND_COM_WIKI: defineUrl(
"https://community.sketch-your-mind.com/wiki",
"https://community.sketch-your-mind.com/Wiki",
UrlPurpose.SUPPORT,
),
WWW_YOUTUBE_COM_VISUALPKM: defineUrl(
@@ -269,11 +329,6 @@ export const URL_REGISTRY = {
"https://community.sketch-your-mind.com/vtw",
UrlPurpose.SUPPORT,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD:
defineUrl(
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/index-new.md",
UrlPurpose.APP_LOGIC,
),
WWW_W3SCHOOLS_COM_COLORS_DEFAULT_ASP: defineUrl(
"https://www.w3schools.com/colors/default.asp",
UrlPurpose.DOCS,
+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
);
+7
View File
@@ -2,6 +2,12 @@ import "obsidian";
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { errorlog } from "src/utils/coreUtils";
import type ExcalidrawView from "src/view/ExcalidrawView";
export type {
ExcalidrawAutomate,
ViewLinkClickContext,
ViewLinkClickHook,
} from "src/shared/ExcalidrawAutomate";
export type { ExcalidrawEphemeralState } from "src/types/excalidrawViewTypes";
//import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
//export ExcalidrawAutomate from "./ExcalidrawAutomate";
//export {ExcalidrawAutomate} from "./ExcaildrawAutomate";
@@ -14,6 +20,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);
+284 -904
View File
File diff suppressed because it is too large. Load diff
+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);
}
}
}
+43 -15
View File
@@ -12,7 +12,6 @@ import {
View,
} from "obsidian";
import {
VIEW_TYPE_EXCALIDRAW,
ICON_NAME,
IMAGE_TYPES,
DEVICE,
@@ -23,7 +22,7 @@ import {
import ExcalidrawView from "../../view/ExcalidrawView";
import { TextMode } from "../../shared/TextMode";
import { REGEX_LINK } from "../../shared/ExcalidrawData";
import { ExcalidrawSettings } from "../settings";
import type { ExcalidrawSettings } from "../settingsDefaults";
import {
openDialogAction,
OpenFileDialog,
@@ -66,6 +65,7 @@ import {
FileId,
} from "@zsviczian/excalidraw/types/element/src/types";
import { ReleaseNotes } from "../../shared/Dialogs/ReleaseNotes";
import { AutostartScriptsModal } from "../../shared/Dialogs/AutostartScriptsSettingsComponent";
import { ScriptInstallPrompt } from "../../shared/Dialogs/ScriptInstallPrompt";
import Taskbone from "../../shared/OCR/Taskbone";
import {
@@ -87,7 +87,7 @@ import {
} from "../../utils/carveout";
import { showFrameSettings } from "../../shared/Dialogs/FrameSettings";
import { insertImageToView } from "../../utils/excalidrawViewUtils";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
import { PaneTarget } from "src/types/utilTypes";
import { decompress } from "src/utils/sceneDataUtils";
@@ -485,13 +485,13 @@ export class CommandManager {
id: "excalidraw-disable-autosave",
name: t("TEMPORARY_DISABLE_AUTOSAVE"),
checkCallback: (checking) => {
if (!this.settings.autosave) {
if (!this.plugin.autosaveEnabled) {
return false;
} //already disabled
if (checking) {
return true;
}
this.settings.autosave = false;
this.plugin.autosaveEnabled = false;
return true;
},
});
@@ -500,13 +500,13 @@ export class CommandManager {
id: "excalidraw-enable-autosave",
name: t("TEMPORARY_ENABLE_AUTOSAVE"),
checkCallback: (checking) => {
if (this.settings.autosave) {
if (this.plugin.autosaveEnabled) {
return false;
} //already enabled
if (checking) {
return true;
}
this.settings.autosave = true;
this.plugin.autosaveEnabled = true;
return true;
},
});
@@ -2251,6 +2251,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"),
@@ -2301,6 +2327,14 @@ export class CommandManager {
},
});
this.addCommand({
id: "view-autostart-scripts",
name: t("AUTOSTART_SCRIPTS_HEAD"),
callback: () => {
new AutostartScriptsModal(this.plugin).open();
},
});
this.addCommand({
id: "tray-mode",
name: t("UI_MODE"),
@@ -2473,20 +2507,14 @@ export class CommandManager {
const excalidrawView =
this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (excalidrawView) {
void excalidrawView.openAsMarkdown();
void this.plugin.ea.toggleViewMode(excalidrawView);
return;
}
const markdownView =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView && fileIsExcalidraw) {
void (async () => {
await markdownView.save();
const activeLeaf = markdownView.leaf;
this.plugin.excalidrawFileModes[activeLeaf.id || activeFile.path] =
VIEW_TYPE_EXCALIDRAW;
await setExcalidrawView(activeLeaf);
})();
void this.plugin.ea.toggleViewMode(markdownView);
}
},
});
+10 -4
View File
@@ -20,7 +20,7 @@ import {
isUnwantedLeaf,
setExcalidrawView,
} from "../../utils/obsidianUtils";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import {
FRONTMATTER_KEYS,
@@ -136,6 +136,12 @@ export class EventManager {
),
);
//theme/snippet toggles can change header/toolbar heights and shift the canvas
//without firing layout-change; refresh cached canvas offsets the same way
this.registerEvent(
this.app.workspace.on("css-change", () => this.onLayoutChangeHandler()),
);
//File Save Trigger Handlers
//Save the drawing if the user clicks outside the Excalidraw Canvas
const onClickEventSaveActiveDrawing = (e: PointerEvent) =>
@@ -343,7 +349,7 @@ export class EventManager {
this.previouslyActiveLeaf = leaf;
if (newActiveviewEV) {
this.plugin.addModalContainerObserver();
this.plugin.addModalContainerObserver(newActiveviewEV);
this.plugin.lastActiveExcalidrawFilePath = newActiveviewEV.file?.path;
} else {
this.plugin.removeModalContainerObserver();
@@ -359,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
}
@@ -391,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,
+88 -46
View File
@@ -29,7 +29,7 @@ import {
} from "../../shared/ExcalidrawData";
import ExcalidrawView from "src/view/ExcalidrawView";
import { getTextMode } from "src/shared/TextMode";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import {
checkAndCreateFolder,
createFileAndAwaitMetacacheUpdate,
@@ -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;
@@ -79,6 +83,16 @@ export class PluginFileManager {
});
}
/**
* Returns whether a vault file is an Excalidraw drawing.
*
* Parsed frontmatter is authoritative when available. During a vault write,
* Obsidian can temporarily remove that frontmatter from the metadata cache;
* in that gap, retain the last confirmed classification from
* {@link excalidrawFiles}. The metadata `changed` event updates that set, so
* deliberately removing the Excalidraw frontmatter still declassifies the
* file once the replacement metadata is published.
*/
public isExcalidrawFile(f: TFile): boolean {
if (!f) {
return false;
@@ -86,11 +100,12 @@ export class PluginFileManager {
if (f.extension === "excalidraw") {
return true;
}
const fileCache = f ? this.plugin.app.metadataCache.getFileCache(f) : null;
return (
!!fileCache?.frontmatter &&
!!fileCache.frontmatter[FRONTMATTER_KEYS.plugin.name]
);
const frontmatter = this.plugin.app.metadataCache.getFileCache(f)?.frontmatter;
if (frontmatter) {
return !!frontmatter[FRONTMATTER_KEYS.plugin.name];
}
return this.excalidrawFiles.has(f);
}
//managing my own list of Excalidraw files because in the onDelete event handler
@@ -537,6 +552,40 @@ export class PluginFileManager {
);
}
/**
* Extracts binary files embedded in a converted legacy scene and rewrites
* the Markdown drawing with durable vault attachment links.
*
* The target file must already exist because Obsidian determines its
* attachment folder relative to that file. This method resolves only after
* every embedded file has been persisted.
*/
public async persistLegacySceneFilesInMarkdown(
markdown: string,
file: TFile,
): Promise<string> {
const convertedData = new ExcalidrawData(this.plugin);
try {
const loaded = await convertedData.loadData(
markdown,
file,
getTextMode(markdown),
);
if (!loaded) {
throw new Error(`Failed to load converted drawing: ${file.path}`);
}
convertedData.disableCompression = true;
await convertedData.syncElements(convertedData.scene);
return (
FRONTMATTER +
(await convertedData.generateMDAsync(convertedData.deletedElements))
);
} finally {
convertedData.destroy();
}
}
// -------------------------------------------------------
// ------------------ Event Handlers ---------------------
// -------------------------------------------------------
@@ -619,23 +668,29 @@ export class PluginFileManager {
if (!(file instanceof TFile)) {
return;
}
const excalidrawViews = getExcalidrawViews(this.app);
excalidrawViews.forEach((excalidrawView) => {
void (async () => {
if (excalidrawView.semaphores?.viewunload) {
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;
}
@@ -668,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);
}
@@ -718,12 +759,13 @@ export class PluginFileManager {
return;
}
//this will not work in the short period when Obsidian is starting up, however
//this will only effect a very few files, statistically unlikely to cause
//much/any real user impact.
//a proper queuing feels overkill for this.
//this will only affect very few files, statistically unlikely to cause
//much/any real user impact. Flush the shared queue so a recently scheduled
//backup is moved with the drawing instead of later recreating the old key.
if (!getImageCache().isReady()) {
return;
}
await getImageCache().flushPendingBAK(oldPath);
const backup = await getImageCache().getBAKFromCache(oldPath);
if (backup) {
await getImageCache().addBAKToCache(newPath, `${backup}`);
+249
View File
@@ -0,0 +1,249 @@
import type { Packages } from "src/types/types";
import { Notice, normalizePath, TFile } from "obsidian";
import {
CJK_STYLE_ID,
DEVICE,
FONTS_STYLE_ID,
} from "src/constants/constants";
import { t } from "src/lang/helpers";
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;
type RuntimePackageProvider = () => Packages;
interface RuntimeFontFaceDefinition {
family: string;
source: string | ArrayBuffer;
descriptors?: FontFaceDescriptors;
}
/**
* Owns CJK and custom-font discovery, document registration, and
* readiness state while preserving the plugin's existing public font facade.
*/
export class FontManager {
private isLocalCJKFontAvailabe: boolean = undefined;
// Intentionally true to preserve the existing startup race behavior.
private fontsReady = true;
private readonly registeredFontFaces = new WeakMap<
Document,
Map<string, FontFace[]>
>();
public constructor(
private readonly plugin: ExcalidrawPlugin,
private readonly getRuntimePackage: RuntimePackageProvider,
) {}
/** Whether font initialization permits the plugin readiness wait to finish. */
public get isReady(): boolean {
return this.fontsReady;
}
/** Returns the enabled CJK ranges when local CJK font assets are available. */
public getCJKFontSettings(): { c: boolean; j: boolean; k: boolean } {
const assetsFoler = this.plugin.settings.fontAssetsPath;
if (typeof this.isLocalCJKFontAvailabe === "undefined") {
this.isLocalCJKFontAvailabe = this.plugin.app.vault
.getFiles()
.some((file) => file.path.startsWith(assetsFoler));
}
if (!this.isLocalCJKFontAvailabe) {
return { c: false, j: false, k: false };
}
return {
c: this.plugin.settings.loadChineseFonts,
j: this.plugin.settings.loadJapaneseFonts,
k: this.plugin.settings.loadKoreanFonts,
};
}
/** Reads a configured CJK font asset from the vault. */
public async loadFontFromFile(
fontName: string,
): Promise<ArrayBuffer | undefined> {
const assetsFoler = this.plugin.settings.fontAssetsPath;
if (!this.isLocalCJKFontAvailabe) {
return;
}
const file = this.plugin.app.vault.getFileByPath(
normalizePath(`${assetsFoler}/${fontName}`),
);
if (!file || !(file instanceof TFile)) {
return;
}
return await this.plugin.app.vault.readBinary(file);
}
/**
* Loads configured CJK and custom fonts into every open Obsidian document
* and registers custom font metrics with the shared Excalidraw runtime.
*/
public async initializeFonts(): Promise<void> {
const cjkFontFaceData = await getCJKFontFaceData(this.plugin);
if (cjkFontFaceData === false) {
new Notice(
t("FONTS_LOAD_ERROR") + this.plugin.settings.fontAssetsPath,
6000,
);
}
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.registerFontFaces(
fontDefinitions,
ownerDocument,
CJK_STYLE_ID,
);
}
new Notice(t("FONTS_LOADED"));
}
const font = await getFontDataURL(
this.plugin.app,
this.plugin.settings.experimantalFourthFont,
"",
"Local Font",
);
if (font.dataURL === "") {
this.plugin.fourthFontLoaded = true;
return;
}
const fourthFontDataURL = font.dataURL;
const file = this.plugin.app.metadataCache.getFirstLinkpathDest(
this.plugin.settings.experimantalFourthFont,
"",
);
let fontMetrics = file.extension.startsWith("woff") || !font.arrayBuffer
? undefined
: getFontMetrics(font.arrayBuffer);
if (!fontMetrics) {
fontMetrics = {
unitsPerEm: 1000,
ascender: 750,
descender: -250,
lineHeight: 1.2,
};
}
const { excalidrawLib } = this.getRuntimePackage();
if (fontMetrics) {
excalidrawLib.registerLocalFont(
{ metrics: fontMetrics },
fourthFontDataURL,
);
}
for (const ownerDocument of this.getOpenObsidianDocuments()) {
await this.registerFontFaces(
[
{
family: "Local Font",
source: `url(${JSON.stringify(fourthFontDataURL)})`,
descriptors: {
display: "swap",
weight: "400",
},
},
],
ownerDocument,
FONTS_STYLE_ID,
true,
);
}
if (!this.plugin.fourthFontLoaded) {
window.setTimeout(() => {
this.plugin.fourthFontLoaded = true;
}, 100);
}
this.fontsReady = true;
}
private async registerFontFaces(
definitions: RuntimeFontFaceDefinition[],
ownerDocument: Document,
registrationId: string,
preload = false,
): Promise<void> {
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.");
}
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 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) {
ownerDocument.head.removeChild(oldCustomFontStylesheet);
}
const oldCJKFontStylesheet = ownerDocument.getElementById(CJK_STYLE_ID);
if (oldCJKFontStylesheet) {
ownerDocument.head.removeChild(oldCJKFontStylesheet);
}
});
}
private getOpenObsidianDocuments(): Document[] {
const visitedDocuments = new Set<Document>();
this.plugin.app.workspace.iterateAllLeaves((leaf) => {
const ownerDocument = DEVICE.isMobile
? mainDocument
: leaf.view.containerEl.ownerDocument;
if (!ownerDocument || visitedDocuments.has(ownerDocument)) {
return;
}
visitedDocuments.add(ownerDocument);
});
return Array.from(visitedDocuments);
}
}
@@ -0,0 +1,92 @@
import type { App } from "obsidian";
import { DEVICE } from "src/constants/constants";
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
declare const mainDocument: Document;
declare const deliberateCreateElement: (
document: Document,
tagName: string,
) => HTMLStyleElement;
const FOOTER_SAFE_AREA_STYLE_ID = "excalidraw-phone-footer-safe-area";
const FOOTER_SAFE_AREA_CSS = `
.excalidraw .App-bottom-bar {
padding-bottom: 50px;
}
`;
interface FooterSafeAreaHost {
app: App;
settings: ExcalidrawSettings;
}
/**
* Owns the optional phone and tablet footer-padding stylesheet across Obsidian
* documents, including cleanup when the plugin unloads.
*/
export class FooterSafeAreaManager {
public constructor(private readonly host: FooterSafeAreaHost) {}
/** Applies or removes footer padding according to the current device and settings. */
public updateFooterSafeAreaPadding(): void {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
const shouldEnable =
(DEVICE.isPhone && this.host.settings?.phoneFooterSafeAreaPadding) ||
(DEVICE.isTablet && this.host.settings?.tabletFooterSafeAreaPadding);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
FOOTER_SAFE_AREA_STYLE_ID,
);
if (!shouldEnable) {
if (existingStylesheet) {
ownerDocument.head.removeChild(existingStylesheet);
}
return;
}
if (isInstanceOfHTMLStyleElement(existingStylesheet)) {
existingStylesheet.textContent = FOOTER_SAFE_AREA_CSS;
return;
}
const stylesheet = deliberateCreateElement(ownerDocument, "style");
stylesheet.id = FOOTER_SAFE_AREA_STYLE_ID;
stylesheet.textContent = FOOTER_SAFE_AREA_CSS;
ownerDocument.head.appendChild(stylesheet);
});
}
/** Removes every footer-padding stylesheet owned by the plugin. */
public destroy(): void {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
FOOTER_SAFE_AREA_STYLE_ID,
);
if (existingStylesheet) {
ownerDocument.head.removeChild(existingStylesheet);
}
});
}
private getOpenObsidianDocuments(): Document[] {
const visitedDocuments = new Set<Document>();
this.host.app.workspace.iterateAllLeaves((leaf) => {
const ownerDocument = DEVICE.isMobile
? mainDocument
: leaf.view.containerEl.ownerDocument;
if (!ownerDocument || visitedDocuments.has(ownerDocument)) {
return;
}
visitedDocuments.add(ownerDocument);
});
return Array.from(visitedDocuments);
}
}
+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);
}
});
}
}
}
+49 -8
View File
@@ -13,7 +13,7 @@ import {
} from "../../constants/constants";
import { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader";
import { createPNG, createSVG } from "../../utils/excalidrawAutomateUtils";
import ExcalidrawPlugin from "../main";
import type ExcalidrawPlugin from "../main";
import { getIMGFilename } from "../../utils/fileUtils";
import {
getEmbeddedFilenameParts,
@@ -41,6 +41,7 @@ import { linkPrompt } from "../../shared/Dialogs/Prompt";
import {
isInstanceOfHTMLElement,
isInstanceOfHTMLImageElement,
isInstanceOfSVGSVGElement,
isInstanceOfSVGElement,
} from "../../utils/typechecks";
import { ExportSettings } from "src/types/exportUtilTypes";
@@ -150,7 +151,9 @@ const _getPNG = async ({
};
if (cacheReady) {
const src = await getImageCache().getImageFromCache(cacheKey);
const src = await getImageCache().getImageFromCache(cacheKey, {
expectedPayloadKind: "raster",
});
if (src && typeof src === "string") {
img.src = src;
return img;
@@ -288,7 +291,10 @@ const _getSVGIMG = async ({
};
if (cacheReady) {
const src = await getImageCache().getImageFromCache(cacheKey);
const src = await getImageCache().getImageFromCache(cacheKey, {
expectedPayloadKind: "svg",
svgFormat: "data-url",
});
if (src && typeof src === "string") {
img.setAttribute("src", src);
return img;
@@ -380,11 +386,13 @@ const _getSVGNative = async ({
};
let maybeSVG;
if (cacheReady) {
maybeSVG = await getImageCache().getImageFromCache(cacheKey);
maybeSVG = await getImageCache().getImageFromCache(cacheKey, {
expectedPayloadKind: "svg",
});
}
const svg =
maybeSVG && maybeSVG instanceof SVGSVGElement
maybeSVG && isInstanceOfSVGSVGElement(maybeSVG)
? maybeSVG
: convertSVGStringToElement(
(
@@ -1244,6 +1252,24 @@ const tmpObsidianWYSIWYG = async (
return;
}
//This internal-embed's src may point to a completely different file than the
//Excalidraw file we are currently rendering (e.g. a plain image embedded in the
//markdown side of a hybrid note). Resolve the actual link target and only take
//over rendering when it is genuinely an Excalidraw drawing; otherwise leave the
//embed alone so Obsidian's native renderer can display it.
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2292
const embedSrc = internalEmbedDiv.getAttribute("src")?.split("#")[0];
const embedTargetFile = embedSrc
? metadataCache.getFirstLinkpathDest(embedSrc, ctx.sourcePath)
: null;
if (
!embedTargetFile ||
!(embedTargetFile instanceof TFile) ||
!plugin.isExcalidrawFile(embedTargetFile)
) {
return;
}
el.empty();
if (internalEmbedDiv.hasAttribute("ready")) {
@@ -1258,7 +1284,7 @@ const tmpObsidianWYSIWYG = async (
return;
}
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
const imgDiv = await processInternalEmbed(internalEmbedDiv, embedTargetFile);
if (!imgDiv) {
return;
}
@@ -1331,8 +1357,13 @@ export const markdownPostProcessor = async (
return;
}
await plugin.awaitSettings();
//Obsidian's Export to PDF renders the document in its own window (main window or a
//popout), not necessarily mainDocument, so the print marker must be looked up on the
//document this section actually belongs to rather than always on the main window.
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2292
const printOwnerDocument = el.ownerDocument ?? mainDocument;
const isPrinting = Boolean(
mainDocument.body.querySelectorAll("body > .print").length > 0,
printOwnerDocument.body.querySelectorAll("body > .print").length > 0,
);
//firstElementChild: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1956
const isFrontmatter =
@@ -1365,7 +1396,17 @@ export const markdownPostProcessor = async (
!plugin.settings.renderImageInHoverPreviewForMDNotes;
const embeddedItems = el.querySelectorAll(".internal-embed");
if (isPrinting && plugin.settings.renderImageInMarkdownToPDF) {
//tmpObsidianWYSIWYG only knows how to handle the frontmatter/area-ref section that
//renders this drawing's own preview. When this section contains real embeds of its
//own (e.g. a plain image embedded in the markdown side of a hybrid note), it must be
//routed to processReadingMode below instead, exactly like the non-print case - otherwise
//tmpObsidianWYSIWYG empties and discards the section without rendering anything back.
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2292
if (
isPrinting &&
plugin.settings.renderImageInMarkdownToPDF &&
embeddedItems.length === 0
) {
await tmpObsidianWYSIWYG(
el,
ctx,
+4 -4
View File
@@ -43,6 +43,10 @@ export class MonkeyPatchManager {
T extends View,
>(this: Workspace, type: ViewConstructor<T>): T | null {
const result = old.call(this, type) as T | null;
const stackTrace = new Error().stack ?? "";
if (!MonkeyPatchManager.isCallerFromTemplaterPlugin(stackTrace)) {
return result;
}
const maybeEAView = this.getMostRecentLeaf()?.view;
if (
!maybeEAView ||
@@ -50,10 +54,6 @@ export class MonkeyPatchManager {
) {
return result;
}
const stackTrace = new Error().stack ?? "";
if (!MonkeyPatchManager.isCallerFromTemplaterPlugin(stackTrace)) {
return result;
}
const leafOrNode = (
maybeEAView as ExcalidrawView
).getActiveEmbeddable();
+60 -23
View File
@@ -1,5 +1,6 @@
import { t } from "src/lang/helpers";
import { DEBUGGING } from "src/utils/debugHelper";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { CustomMutationObserver } from "src/utils/debugHelper";
import { DEVICE } from "src/constants/constants";
import {
@@ -11,14 +12,30 @@ import {
isInstanceOfDocumentFragment,
isInstanceOfElement,
} from "src/utils/typechecks";
import type ExcalidrawView from "src/view/ExcalidrawView";
declare const mainDocument: Document;
const MODAL_CONTAINER_SELECTOR = ".modal-container";
/**
* Checks an observed DOM node without relying on cross-window constructors.
*
* Mutation records can contain nodes from an Obsidian popout realm whose
* `instanceof Element` identity is not reliable after window migration.
*/
const isObservedElement = (node: Node): node is Element =>
node.nodeType === 1 && typeof (node as Element).matches === "function";
export class ObserverManager {
private plugin: ExcalidrawPlugin;
private app: App;
private themeObserver: MutationObserver | CustomMutationObserver;
private fileExplorerObserver: MutationObserver | CustomMutationObserver;
private modalContainerObserver: MutationObserver | CustomMutationObserver;
private modalContainerObserver:
| MutationObserver
| CustomMutationObserver
| null = null;
private modalObservedView: ExcalidrawView | null = null;
private workspaceDrawerLeftObserver:
| MutationObserver
| CustomMutationObserver;
@@ -49,7 +66,7 @@ export class ObserverManager {
this.addWorkspaceDrawerObserver();
}
} catch (e) {
new Notice("Error adding ObserverManager", 6000);
new Notice(t("ERROR_ADDING_OBSERVER_MANAGER"), 6000);
console.error("Error adding ObserverManager", e);
}
this.plugin.logStartupEvent("ObserverManager added");
@@ -266,51 +283,70 @@ export class ObserverManager {
}
/**
* Monitors if the user clicks outside the Excalidraw view, and saves the drawing if it's dirty
* @returns
* Saves a dirty drawing when an Obsidian modal opens in its live document.
*
* @param view - The active or same-leaf replacement view to observe.
*/
public addModalContainerObserver() {
if (!this.plugin.activeExcalidrawView) {
public addModalContainerObserver(view = this.plugin.activeExcalidrawView) {
if (!view) {
return;
}
const activeViewDoc = view.containerEl.ownerDocument;
if (this.modalContainerObserver) {
if (
this.activeViewDoc === this.plugin.activeExcalidrawView.ownerDocument
this.activeViewDoc === activeViewDoc &&
this.modalObservedView === view
) {
return;
}
this.removeModalContainerObserver();
}
//The user clicks settings, or "open another vault", or the command palette
//The user clicks settings, or "open another vault", or the command palette.
//Other body portals, including inline suggestions, must not interrupt editing with a save.
const modalContainerObserverFn: MutationCallback = (
m: MutationRecord[],
mutations: MutationRecord[],
) => {
const view = this.plugin.activeExcalidrawView;
const observedView = this.modalObservedView;
const addedNodes = mutations.flatMap((mutation) =>
mutation.type === "childList"
? Array.from(mutation.addedNodes)
: [],
);
const modalOpened = addedNodes.some(
(node) =>
isObservedElement(node) &&
(node.matches(MODAL_CONTAINER_SELECTOR) ||
node.querySelector(MODAL_CONTAINER_SELECTOR) !== null),
);
if (
m.length !== 1 ||
m[0].type !== "childList" ||
m[0].addedNodes.length !== 1 ||
!view ||
view.semaphores?.viewunload ||
!view.isDirty()
!modalOpened ||
!observedView ||
observedView.semaphores?.viewunload ||
!observedView.isDirty() ||
!observedView.excalidrawAPI
) {
return;
}
const { errorMessage } = view.excalidrawAPI.getAppState();
const { errorMessage } = observedView.excalidrawAPI.getAppState();
if (!errorMessage) {
void this.plugin.activeExcalidrawView.save();
void observedView.save();
}
};
this.activeViewDoc = activeViewDoc;
this.modalObservedView = view;
// Keep the observer constructor and target in the same window realm so a
// migrated view never depends on its destroyed source window.
this.modalContainerObserver = DEBUGGING
? new CustomMutationObserver(
modalContainerObserverFn,
"modalContainerObserver",
)
: new MutationObserver(modalContainerObserverFn);
this.activeViewDoc = this.plugin.activeExcalidrawView.ownerDocument;
this.modalContainerObserver.observe(this.activeViewDoc.body, {
: new (activeViewDoc.defaultView?.MutationObserver ?? MutationObserver)(
modalContainerObserverFn,
);
this.modalContainerObserver.observe(activeViewDoc.body, {
childList: true,
});
}
@@ -320,8 +356,9 @@ export class ObserverManager {
return;
}
this.modalContainerObserver.disconnect();
this.activeViewDoc = null;
this.modalContainerObserver = null;
this.modalObservedView = null;
this.activeViewDoc = null;
}
private addWorkspaceDrawerObserver() {
+221 -132
View File
@@ -1,36 +1,71 @@
import { updateExcalidrawLib } from "src/constants/constants";
import { ExcalidrawLib } from "../../types/excalidrawLib";
import { Packages } from "../../types/types";
import { PackageLease, Packages } from "../../types/types";
import { Notice } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { errorHandler } from "../../utils/ErrorHandler";
import React from "react";
import ReactDOM from "react-dom/client";
import { createObsidianCommonHostAdapter } from "./obsidianCommonHostAdapter";
import { createObsidianExcalidrawHostAdapter } from "./obsidianExcalidrawHostAdapter";
declare let REACT_PACKAGES: string;
declare let react: typeof React;
declare let reactDOM: typeof ReactDOM;
declare let reactDOM: typeof ReactDOM & typeof import("react-dom");
declare let excalidrawLib: typeof ExcalidrawLib;
declare let ReactJSXRuntime: unknown;
declare let ReactJSXDevRuntime: unknown;
declare const unpackExcalidraw: () => string;
export class PackageManager {
private packageMap: Map<Window, Packages> = new Map<Window, Packages>();
private EXCALIDRAW_PACKAGE: string;
private plugin: ExcalidrawPlugin;
private fallbackPackage: Packages | null = null;
const normalizeError = (error: unknown): Error =>
error instanceof Error
? error
: new Error(typeof error === "string" ? error : "Unknown error");
constructor(plugin: ExcalidrawPlugin) {
this.plugin = plugin;
/**
* Owns the plugin's single private React/Excalidraw runtime.
*
* Each view receives the same package but retains an idempotent lease keyed by
* its actual window. The window key governs migration persistence and the
* temporary `ExcalidrawLib` compatibility alias only; rendering ownership is
* supplied independently through each Excalidraw instance's `ownerDocument`.
*/
export class PackageManager {
private runtimePackage: Packages | null = null;
private packageLeaseCountMap = new Map<Window, number>();
private commonHostDisposer: (() => void) | null = null;
private excalidrawHostDisposer: (() => void) | null = null;
private runtimeAliasWindows = new Set<Window>();
constructor(private readonly plugin: ExcalidrawPlugin) {
let excalidrawPackage = "";
try {
this.EXCALIDRAW_PACKAGE = unpackExcalidraw();
excalidrawPackage = unpackExcalidraw();
// Use safe evaluation for unpacking the Excalidraw package
excalidrawLib = errorHandler.safeEval(
`(function() {${this.EXCALIDRAW_PACKAGE};return ExcalidrawLib;})()`,
// Evaluate Excalidraw in the main window with the same private React
// instance used by the plugin bundle. The runtime is passed explicitly
// because window.React and window.ReactDOM are deliberately not set.
const loadExcalidraw = errorHandler.safeEval<
(
reactInstance: typeof React,
reactDOMInstance: typeof reactDOM,
jsxRuntime: unknown,
jsxDevRuntime: unknown,
) => typeof ExcalidrawLib
>(
`(function(React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime) {
${excalidrawPackage};
return ExcalidrawLib;
})`,
"PackageManager constructor - excalidrawLib initialization",
window,
);
excalidrawLib = loadExcalidraw(
react,
reactDOM,
ReactJSXRuntime,
ReactJSXDevRuntime,
);
if (!excalidrawLib) {
throw new Error("Failed to initialize excalidrawLib");
@@ -44,18 +79,27 @@ export class PackageManager {
// Validate the package before storing
if (this.validatePackage(initialPackage)) {
this.setPackage(window, initialPackage);
this.fallbackPackage = initialPackage; // Store a valid package as fallback
this.setRuntimePackage(initialPackage);
} else {
throw new Error("Invalid initial package");
}
} catch (e) {
errorHandler.handleError(e, "PackageManager constructor");
} catch (e: unknown) {
errorHandler.handleError(
normalizeError(e),
"PackageManager constructor",
);
new Notice(
"Error loading the Excalidraw package. Some features may not work correctly.",
10000,
);
console.error("Error loading the Excalidraw package", e);
} finally {
// Per-window evaluation has been removed. Release the decompressed source
// Excalidraw source after the one shared runtime is initialized. The
// bootstrap releases its inflated React source immediately after eval.
excalidrawPackage = "";
ReactJSXRuntime = null;
ReactJSXDevRuntime = null;
}
plugin.logStartupEvent("Excalidraw package unpacked");
@@ -85,151 +129,196 @@ export class PackageManager {
}
/**
* Store a package for a specific window
* Registers plugin capabilities with one evaluated Excalidraw runtime.
*/
public setPackage(window: Window, pkg: Packages) {
if (this.validatePackage(pkg)) {
this.packageMap.set(window, pkg);
private configureObsidianCommonHost(pkg: Packages): void {
this.commonHostDisposer?.();
this.commonHostDisposer = null;
// Update fallback if we don't have one
if (!this.fallbackPackage) {
this.fallbackPackage = pkg;
const lib = pkg.excalidrawLib;
if (
!lib ||
typeof lib.configureObsidianCommonHost !== "function" ||
typeof lib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION !== "number"
) {
throw new Error("Excalidraw package is missing the common host boundary");
}
const adapter = createObsidianCommonHostAdapter(
this.plugin,
lib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION,
);
this.commonHostDisposer = lib.configureObsidianCommonHost(adapter);
}
/** Registers plugin-wide settings with one evaluated Excalidraw runtime. */
private configureObsidianExcalidrawHost(pkg: Packages): void {
this.excalidrawHostDisposer?.();
this.excalidrawHostDisposer = null;
const lib = pkg.excalidrawLib;
if (
!lib ||
typeof lib.configureObsidianExcalidrawHost !== "function" ||
typeof lib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION !== "number"
) {
throw new Error(
"Excalidraw package is missing the package host boundary",
);
}
const adapter = createObsidianExcalidrawHostAdapter(
this.plugin,
lib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION,
);
this.excalidrawHostDisposer =
lib.configureObsidianExcalidrawHost(adapter);
}
/** Disposes the plugin capabilities registered with the shared runtime. */
private disposeObsidianHosts(): void {
this.commonHostDisposer?.();
this.commonHostDisposer = null;
this.excalidrawHostDisposer?.();
this.excalidrawHostDisposer = null;
}
/** Stores and configures the plugin's single evaluated runtime package. */
private setRuntimePackage(pkg: Packages): void {
if (this.validatePackage(pkg)) {
try {
this.configureObsidianCommonHost(pkg);
this.configureObsidianExcalidrawHost(pkg);
} catch (error: unknown) {
this.disposeObsidianHosts();
throw normalizeError(error);
}
this.runtimePackage = pkg;
} else {
errorHandler.handleError(
"Attempted to set invalid package",
"PackageManager.setPackage",
"PackageManager.setRuntimePackage",
);
}
}
public getPackageMap() {
return this.packageMap;
/** Returns the one runtime used by every main-window and popout view. */
public getRuntimePackage(): Packages {
if (!this.runtimePackage || !this.validatePackage(this.runtimePackage)) {
throw new Error("Excalidraw runtime package is unavailable");
}
return this.runtimePackage;
}
/**
* Gets a package for a window, creating it if necessary
* with robust error handling
* Acquires the shared runtime while retaining the view's actual window.
*
* @remarks
* Window identity remains view-owned migration/persistence state. Popout
* leases additionally own the temporary `window.ExcalidrawLib` compatibility
* alias and remove it when the final view in that window releases its lease.
*/
public acquirePackage(win: Window): PackageLease {
const packages = this.getPackage(win);
const leaseCount = (this.packageLeaseCountMap.get(win) ?? 0) + 1;
this.packageLeaseCountMap.set(win, leaseCount);
let released = false;
return {
window: win,
packages,
release: () => {
if (released) {
return;
}
released = true;
this.releasePackageLease(win);
},
};
}
/** Releases one view-owned package lease without consulting mutable DOM. */
private releasePackageLease(win: Window): void {
const leaseCount = this.packageLeaseCountMap.get(win);
if (leaseCount === undefined) {
return;
}
const remainingLeases = Math.max(0, leaseCount - 1);
if (remainingLeases === 0) {
this.packageLeaseCountMap.delete(win);
if (win !== window) {
this.removeRuntimeAlias(win);
}
} else {
this.packageLeaseCountMap.set(win, remainingLeases);
}
}
/**
* Returns the shared runtime and exposes its compatibility API in `win`.
*
* @remarks
* The runtime is never evaluated in the supplied window. Rendering ownership
* is provided separately through Excalidraw's stable `ownerDocument` prop.
*/
public getPackage(win: Window): Packages {
try {
// Return existing package if available
if (this.packageMap.has(win)) {
const pkg = this.packageMap.get(win);
if (this.validatePackage(pkg)) {
return pkg;
}
// If package exists but is invalid, delete it so we can recreate it
this.packageMap.delete(win);
}
// Create new package
return errorHandler.wrapWithTryCatch(
() => {
// Use safe evaluation to load packages in the window context
const evalResult = errorHandler.safeEval<{
react: typeof React;
reactDOM: typeof ReactDOM;
excalidrawLib: typeof ExcalidrawLib;
}>(
`(function() {
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
return {react: React, reactDOM: ReactDOM, excalidrawLib: ExcalidrawLib};
})()`,
"PackageManager.getPackage - package evaluation",
win,
);
if (!evalResult || !this.validatePackage(evalResult)) {
throw new Error("Failed to create valid package");
}
const newPackage = {
react: evalResult.react,
reactDOM: evalResult.reactDOM,
excalidrawLib: evalResult.excalidrawLib,
};
this.packageMap.set(win, newPackage);
return newPackage;
},
"PackageManager.getPackage",
this.fallbackPackage,
);
} catch (error) {
errorHandler.handleError(error, "PackageManager.getPackage");
// Return fallback package if available to prevent data loss
if (this.fallbackPackage) {
return this.fallbackPackage;
}
// If no fallback, throw error to prevent undefined behavior
throw new Error("Failed to get package and no fallback available");
const pkg = this.getRuntimePackage();
if (win !== window) {
win.ExcalidrawLib = pkg.excalidrawLib;
this.runtimeAliasWindows.add(win);
}
return pkg;
}
/** Removes only the window-local alias; the shared runtime remains alive. */
private removeRuntimeAlias(win: Window): void {
const packageLib = this.runtimePackage?.excalidrawLib;
errorHandler.wrapWithTryCatch(() => {
if (packageLib && win.ExcalidrawLib === packageLib) {
delete win.ExcalidrawLib;
}
}, "PackageManager.removeRuntimeAlias");
this.runtimeAliasWindows.delete(win);
}
/**
* Compatibility facade retained for callers that explicitly clean a window.
* The plugin-wide runtime and host registrations live until `destroy()`.
*/
public deletePackage(win: Window) {
try {
const pkg = this.packageMap.get(win);
if (!pkg) {
return;
if (win !== window) {
this.removeRuntimeAlias(win);
}
const { react, reactDOM, excalidrawLib } = pkg;
if (win.ExcalidrawLib === excalidrawLib) {
// Safely clean up resources
errorHandler.wrapWithTryCatch(() => {
if (
excalidrawLib &&
typeof excalidrawLib.destroyObsidianUtils === "function"
) {
excalidrawLib.destroyObsidianUtils();
}
delete win.ExcalidrawLib;
}, "PackageManager.deletePackage - cleanup ExcalidrawLib");
}
if (win.React === react) {
errorHandler.wrapWithTryCatch(() => {
delete win.React;
}, "PackageManager.deletePackage - cleanup React");
}
if (win.ReactDOM === reactDOM) {
errorHandler.wrapWithTryCatch(() => {
delete win.ReactDOM;
}, "PackageManager.deletePackage - cleanup ReactDOM");
}
this.packageMap.delete(win);
} catch (error) {
errorHandler.handleError(error, "PackageManager.deletePackage");
} catch (error: unknown) {
errorHandler.handleError(
normalizeError(error),
"PackageManager.deletePackage",
);
}
}
public setExcalidrawPackage(pkg: string) {
this.EXCALIDRAW_PACKAGE = pkg;
}
public destroy() {
try {
REACT_PACKAGES = "";
Array.from(this.packageMap.entries()).forEach(([win, _]) => {
this.deletePackage(win);
Array.from(this.runtimeAliasWindows).forEach((win) => {
this.removeRuntimeAlias(win);
});
this.removeRuntimeAlias(window);
this.packageMap.clear();
this.EXCALIDRAW_PACKAGE = "";
this.fallbackPackage = null;
this.packageLeaseCountMap.clear();
this.runtimeAliasWindows.clear();
this.disposeObsidianHosts();
this.runtimePackage = null;
react = null;
reactDOM = null;
excalidrawLib = null;
} catch (error) {
errorHandler.handleError(error, "PackageManager.destroy");
} catch (error: unknown) {
errorHandler.handleError(
normalizeError(error),
"PackageManager.destroy",
);
}
}
}
+405
View File
@@ -0,0 +1,405 @@
import { Notice, type App, type PluginManifest } from "obsidian";
import { JSON_parse } from "src/constants/constants";
import {
DEFAULT_SETTINGS,
type ExcalidrawSettings,
} from "src/core/settingsDefaults";
import { PreviewImageType } from "src/types/utilTypes";
import {
decryptPersistedAPIKeys,
encryptPersistedAPIKeys,
} from "src/utils/settingsKeyObfuscation";
import { SerializedSettingsWriter } from "src/core/settings/SerializedSettingsWriter";
import { SettingsRecoveryStore } from "src/core/settings/SettingsRecoveryStore";
import {
SettingsRecoveryPrompt,
type SettingsRecoveryChoice,
type SettingsRecoveryPromptMode,
} from "src/shared/Dialogs/SettingsRecoveryPrompt";
import {
classifySettingsDataLoad,
isSettingsDataRecord,
type SettingsDataFileState,
} from "src/core/settings/settingsDataValidation";
import { t } from "src/lang/helpers";
type PersistedExcalidrawSettings = Partial<ExcalidrawSettings> &
Record<string, unknown>;
interface PluginSettingsHost {
app: App;
manifest: PluginManifest;
settings: ExcalidrawSettings;
loadData(): Promise<unknown>;
saveData(data: unknown): Promise<void>;
}
interface SettingsRecoveryStoreLike {
load(): Promise<PersistedExcalidrawSettings | null>;
save(settings: PersistedExcalidrawSettings): Promise<void>;
destroy(): void;
}
type SettingsRecoveryPromptHandler = (
mode: SettingsRecoveryPromptMode,
) => Promise<SettingsRecoveryChoice>;
/**
* Owns plugin settings persistence, default assembly, and compatibility
* migrations while leaving startup readiness and settings UI registration to
* the plugin lifecycle.
*/
export class PluginSettingsManager {
private readonly writer: SerializedSettingsWriter<PersistedExcalidrawSettings>;
private readonly recoveryStore: SettingsRecoveryStoreLike;
private hasCompletedInitialLoad = false;
private persistenceBlockedByInvalidData = false;
private missingRecoveryNoticeShown = false;
private awaitingStartupRecoveryChoice = false;
private readonly promptForRecoveryChoice: SettingsRecoveryPromptHandler;
public constructor(
private readonly host: PluginSettingsHost,
recoveryStore?: SettingsRecoveryStoreLike,
promptForRecoveryChoice?: SettingsRecoveryPromptHandler,
) {
this.recoveryStore =
recoveryStore ??
new SettingsRecoveryStore({
databaseName: `Excalidraw Settings Recovery ${host.app.appId}`,
});
this.promptForRecoveryChoice =
promptForRecoveryChoice ??
((mode) => new SettingsRecoveryPrompt(host.app, mode).start());
this.writer = new SerializedSettingsWriter({
saveData: async (data) => {
await this.saveRecoverySnapshot(data);
await this.host.saveData(data);
},
});
}
/**
* Loads persisted settings, applies defaults and migrations, and decrypts
* protected API-key fields.
*
* @remarks Unknown persisted properties are intentionally retained.
* @returns `false` when the disk payload was invalid. Runtime callers use
* this to suppress cache invalidation for a rejected synchronized payload.
*/
public async loadSettings(): Promise<boolean> {
const dataFileState = await this.getSettingsDataFileState();
let loadedSettings: unknown = null;
let loadFailed = false;
try {
loadedSettings = await this.host.loadData();
} catch {
loadFailed = true;
}
const classification = classifySettingsDataLoad({
value: loadedSettings,
fileState: dataFileState,
loadFailed,
isInitialLoad: !this.hasCompletedInitialLoad,
});
const hasInvalidSettings = classification === "invalid";
const isFirstInstallation = classification === "first-installation";
let persistedSettings: PersistedExcalidrawSettings;
let recoveredInvalidStartup = false;
let shouldPersistStartupChoice = false;
if (hasInvalidSettings) {
if (this.hasCompletedInitialLoad) {
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
new Notice(t("SETTINGS_DATA_REPAIRED_FROM_MEMORY"), 12000);
console.error(
"Excalidraw rejected invalid synchronized settings data and restored the active settings",
);
await this.persistSnapshot(
encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
),
);
return false;
}
const recoveredSettings = await this.loadRecoverySnapshot();
if (recoveredSettings) {
persistedSettings = recoveredSettings;
recoveredInvalidStartup = true;
shouldPersistStartupChoice = true;
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
} else {
this.host.settings = Object.assign({}, DEFAULT_SETTINGS);
const choice = await this.requestStartupRecoveryChoice(
"invalid-without-recovery",
);
persistedSettings = {};
if (choice === "reset-defaults") {
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
shouldPersistStartupChoice = true;
} else {
this.blockPersistenceWhileWaitingForFile();
}
}
} else if (isFirstInstallation) {
const recoveredSettings = await this.loadRecoverySnapshot();
if (recoveredSettings) {
this.host.settings = Object.assign({}, DEFAULT_SETTINGS);
const choice = await this.requestStartupRecoveryChoice(
"missing-with-recovery",
);
persistedSettings =
choice === "reset-defaults" ? {} : recoveredSettings;
} else {
persistedSettings = {};
}
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
shouldPersistStartupChoice = true;
} else {
this.persistenceBlockedByInvalidData = false;
this.missingRecoveryNoticeShown = false;
persistedSettings = isSettingsDataRecord(loadedSettings)
? loadedSettings
: {};
}
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
let didSettingsMigration = false;
this.host.settings = Object.assign(
{},
DEFAULT_SETTINGS,
decryptedSettings,
);
if (typeof decryptedSettings.libraryStorageMode === "undefined") {
const legacyLibrary: unknown =
typeof decryptedSettings.library === "string" &&
decryptedSettings.library !== "" &&
decryptedSettings.library !== "deprecated"
? JSON_parse(decryptedSettings.library)
: decryptedSettings.library2;
const legacyLibraryRecord =
typeof legacyLibrary === "object" && legacyLibrary !== null
? (legacyLibrary as Record<string, unknown>)
: null;
const hasLegacyItems = Boolean(
(Array.isArray(legacyLibraryRecord?.library) &&
legacyLibraryRecord.library.length) ||
(Array.isArray(legacyLibraryRecord?.libraryItems) &&
legacyLibraryRecord.libraryItems.length),
);
this.host.settings.libraryStorageMode = hasLegacyItems
? "data-json"
: "vault";
this.host.settings.libraryMigrationStatus = hasLegacyItems
? "pending"
: "not-required";
didSettingsMigration = true;
}
const savedMarkdownImageSettings = decryptedSettings.markdownImageSettings;
if (!savedMarkdownImageSettings) {
this.host.settings.markdownImageSettings = {
defaults: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
width: this.host.settings.mdSVGwidth,
fontFamily: this.host.settings.mdFont,
fontColor: this.host.settings.mdFontColor ?? "#000000",
border: {
enabled: false,
color: this.host.settings.mdBorderColor,
},
css: "",
transclusion: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
.border,
},
},
},
};
didSettingsMigration = true;
} else {
this.host.settings.markdownImageSettings = {
defaults: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
...savedMarkdownImageSettings.defaults,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.border,
...savedMarkdownImageSettings.defaults?.border,
},
transclusion: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
...savedMarkdownImageSettings.defaults?.transclusion,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
.border,
...savedMarkdownImageSettings.defaults?.transclusion?.border,
},
},
},
};
}
const markdownImageDefaults = this.host.settings.markdownImageSettings
.defaults as unknown as Record<string, unknown>;
if ("theme" in markdownImageDefaults) {
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
>;
if (
typeof settingsRecord.iframelyAllowed === "boolean" &&
typeof this.host.settings.oEmbedAllowed !== "boolean"
) {
this.host.settings.oEmbedAllowed = settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if ("iframelyAllowed" in settingsRecord) {
delete settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if (!this.host.settings.previewImageType) {
// Migration introduced in 1.9.13.
if (typeof this.host.settings.displaySVGInPreview === "undefined") {
this.host.settings.previewImageType = PreviewImageType.SVGIMG;
} else {
this.host.settings.previewImageType = this.host.settings
.displaySVGInPreview
? PreviewImageType.SVGIMG
: PreviewImageType.PNG;
}
}
const encryptedPersistedSettings = encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
);
const shouldPersistEncryptedSettings =
JSON.stringify(encryptedPersistedSettings) !==
JSON.stringify(persistedSettings);
if (shouldPersistStartupChoice) {
await this.persistSnapshot(encryptedPersistedSettings);
if (recoveredInvalidStartup) {
new Notice(t("SETTINGS_DATA_RECOVERED"), 12000);
}
} else if (
!this.persistenceBlockedByInvalidData &&
(didSettingsMigration || shouldPersistEncryptedSettings)
) {
await this.persistSnapshot(encryptedPersistedSettings);
} else if (!this.persistenceBlockedByInvalidData) {
await this.saveRecoverySnapshot(encryptedPersistedSettings);
}
this.hasCompletedInitialLoad = true;
return !hasInvalidSettings;
}
/** Encrypts protected fields and persists the current settings object. */
public saveSettings(): Promise<void> {
if (this.persistenceBlockedByInvalidData) {
this.showMissingRecoveryNotice();
return Promise.resolve();
}
return this.persistSnapshot(
encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
),
);
}
/** Whether plugin startup is intentionally waiting for a recovery choice. */
public get isAwaitingStartupRecoveryChoice(): boolean {
return this.awaitingStartupRecoveryChoice;
}
private persistSnapshot(
settings: PersistedExcalidrawSettings,
): Promise<void> {
return this.writer.persist(settings);
}
/** Closes the device-local recovery database connection. */
public destroy(): void {
this.recoveryStore.destroy();
}
private async getSettingsDataFileState(): Promise<SettingsDataFileState> {
const pluginDirectory = this.host.manifest.dir;
if (!pluginDirectory) {
return "unknown";
}
try {
const stat = await this.host.app.vault.adapter.stat(
`${pluginDirectory}/data.json`,
);
if (!stat) {
return "missing";
}
return stat.size === 0 ? "empty" : "present";
} catch {
return "unknown";
}
}
private blockPersistenceWhileWaitingForFile(): void {
this.persistenceBlockedByInvalidData = true;
this.missingRecoveryNoticeShown = false;
}
private showMissingRecoveryNotice(): void {
if (this.missingRecoveryNoticeShown) {
return;
}
this.missingRecoveryNoticeShown = true;
console.error(
"Excalidraw settings data is empty or unreadable; waiting for a valid replacement file",
);
new Notice(t("SETTINGS_DATA_INVALID"), 12000);
}
private async requestStartupRecoveryChoice(
mode: SettingsRecoveryPromptMode,
): Promise<SettingsRecoveryChoice> {
this.awaitingStartupRecoveryChoice = true;
try {
return await this.promptForRecoveryChoice(mode);
} finally {
this.awaitingStartupRecoveryChoice = false;
}
}
private async loadRecoverySnapshot(): Promise<PersistedExcalidrawSettings | null> {
try {
const recoveredSettings = await this.recoveryStore.load();
return isSettingsDataRecord(recoveredSettings) ? recoveredSettings : null;
} catch (error) {
console.error("Could not load Excalidraw settings recovery", error);
return null;
}
}
private async saveRecoverySnapshot(
settings: PersistedExcalidrawSettings,
): Promise<void> {
try {
await this.recoveryStore.save(settings);
} catch (error) {
console.error("Could not update Excalidraw settings recovery", error);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
import { log } from "src/utils/debugHelper";
/** Stores and formats plugin startup timing events without owning startup order. */
export class StartupTimer {
private readonly events: string[] = [];
private lastLogTimestamp: number;
public constructor(
initialTimestamp: number,
private readonly pluginVersion: string,
) {
this.lastLogTimestamp = initialTimestamp;
}
/**
* Starts a new timing baseline while retaining events recorded before the
* reset, matching the existing constructor-to-layout startup breakdown.
*/
public reset(timestamp: number): void {
this.lastLogTimestamp = timestamp;
}
/** Records one startup event with total and previous-event elapsed times. */
public logEvent(message: string, loadTimestamp: number): void {
const timestamp = Date.now();
this.events.push(
`${message}\nTotal: ${timestamp - loadTimestamp}ms Delta: ${timestamp - this.lastLogTimestamp}ms\n`,
);
this.lastLogTimestamp = timestamp;
}
/** Writes the complete startup timing breakdown to the debug log. */
public printBreakdown(): void {
log(
`Excalidraw ${this.pluginVersion} startup breakdown:\n${this.events.join(
"\n",
)}`,
);
}
}
+45 -12
View File
@@ -38,6 +38,8 @@ export class StencilLibraryManager {
private itemSource = new Map<LibraryItem["id"], string>();
private currentItems: LibraryItems = [];
private loaded = false;
private loadRevision = 0;
private loadPromise: Promise<void> | null = null;
private migrationPrompt: Promise<void> | null = null;
private saveQueue: Promise<void> = Promise.resolve();
private reloadTimer: number | null = null;
@@ -86,6 +88,7 @@ export class StencilLibraryManager {
}
public invalidate(): void {
this.loadRevision++;
this.loaded = false;
this.itemSource.clear();
this.currentItems = [];
@@ -109,7 +112,7 @@ export class StencilLibraryManager {
await this.migrateLegacyLibrary();
}
if (!this.loaded) {
await this.loadFromVault();
await this.ensureLoaded();
}
return this.currentItems;
}
@@ -156,7 +159,7 @@ export class StencilLibraryManager {
}
await this.saveQueue;
this.invalidate();
await this.loadFromVault();
await this.ensureLoaded();
this.isUpdatingOpenViews = true;
try {
for (const view of getExcalidrawViews(this.plugin.app, true)) {
@@ -286,8 +289,39 @@ export class StencilLibraryManager {
}
}
private async loadFromVault(): Promise<void> {
this.itemSource.clear();
/** Coalesces concurrent view initialization into one vault-library load. */
private async ensureLoaded(): Promise<void> {
while (!this.loaded) {
if (this.loadPromise === null) {
const revision = this.loadRevision;
this.loadPromise = this.loadFromVault().then(
({ itemSource, items }) => {
if (revision !== this.loadRevision) {
return;
}
this.itemSource = itemSource;
this.currentItems = items;
this.loaded = true;
},
);
}
const activeLoad: Promise<void> = this.loadPromise;
try {
await activeLoad;
} finally {
if (this.loadPromise === activeLoad) {
this.loadPromise = null;
}
}
}
}
/** Reads a coherent library snapshot without mutating the active cache. */
private async loadFromVault(): Promise<{
itemSource: Map<LibraryItem["id"], string>;
items: LibraryItems;
}> {
const itemSource = new Map<LibraryItem["id"], string>();
const folderPath = this.getFolderPath();
const localPath = this.getLocalLibraryPath();
const files = this.plugin.app.vault
@@ -315,25 +349,24 @@ export class StencilLibraryManager {
isLocalFile ? "unpublished" : "published",
);
for (const item of items) {
if (this.itemSource.has(item.id)) {
if (itemSource.has(item.id)) {
console.warn(
`Duplicate stencil library item id '${item.id}' in ${file.path}; keeping the first occurrence.`,
);
continue;
}
this.itemSource.set(item.id, file.path);
itemSource.set(item.id, file.path);
combined.push(
isLocalFile ? item : { ...item, status: "published" as const },
);
}
}
this.currentItems = combined;
this.loaded = true;
return { itemSource, items: combined };
}
private async persistChanges(nextItems: LibraryItems): Promise<void> {
if (!this.loaded) {
await this.loadFromVault();
await this.ensureLoaded();
}
const previousById = new Map(
this.currentItems.map((item) => [item.id, item]),
@@ -344,7 +377,7 @@ export class StencilLibraryManager {
for (const item of this.currentItems) {
const next = nextById.get(item.id);
if (!next || JSON.stringify(next) !== JSON.stringify(item)) {
if (!next || JSON.stringify(next, null, 2) !== JSON.stringify(item, null, 2)) {
affectedPaths.add(
this.itemSource.get(item.id) ?? this.getLocalLibraryPath(),
);
@@ -389,7 +422,7 @@ export class StencilLibraryManager {
version: 2,
libraryItems: updated,
};
if (JSON.stringify(existingData) !== JSON.stringify(nextData)) {
if (JSON.stringify(existingData, null, 2) !== JSON.stringify(nextData, null, 2)) {
await this.persistLibraryFile(path, nextData);
}
}
@@ -487,7 +520,7 @@ export class StencilLibraryManager {
return;
}
await this.ensureFolder();
const content = JSON.stringify(data);
const content = JSON.stringify(data, null, 2);
if (existing) {
await this.plugin.app.vault.modify(existing, content);
return;
+1 -1
View File
@@ -1,5 +1,5 @@
import { WorkspaceWindow } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { getAllWindowDocuments } from "../../utils/obsidianUtils";
import { setStyleText } from "src/utils/htmlUtils";
@@ -0,0 +1,186 @@
import type {
AppState,
BinaryFiles,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import type { ExcalidrawDataMigrationState } from "../../shared/ExcalidrawData";
import type { TextMode } from "../../shared/TextMode";
import type { ViewSaveMigrationState } from "../../view/managers/ViewSaveCoordinator";
const DEFAULT_HANDOFF_TTL_MS = 15_000;
/** Drawing-owned runtime state that may cross an Obsidian window migration. */
export interface ViewMigrationDrawingState {
elements: readonly ExcalidrawElement[];
appState: AppState;
files: BinaryFiles;
textMode: TextMode;
compatibilityMode: boolean;
excalidrawData: ExcalidrawDataMigrationState;
save: ViewSaveMigrationState;
}
/** Metadata used to register one transient migration handoff. */
export interface ViewMigrationHandoffRegistration {
leafId: string;
filePath: string;
fileMtime: number;
drawing: ViewMigrationDrawingState;
}
/** Identity and freshness checks required to consume a migration handoff. */
export interface ViewMigrationHandoffRequest {
token: string;
leafId: string;
filePath: string;
fileMtime: number;
}
interface ViewMigrationHandoffEntry extends ViewMigrationHandoffRegistration {
token: string;
expiresAt: number;
}
interface ViewMigrationHandoffScheduler {
now: () => number;
setTimeout: (callback: () => void, delay: number) => number;
clearTimeout: (timer: number) => void;
}
interface ViewMigrationHandoffManagerOptions {
ttlMs?: number;
scheduler?: ViewMigrationHandoffScheduler;
}
/**
* Owns bounded, one-shot drawing handoffs between recreated views.
*
* Entries contain drawing state only. They never retain an `ExcalidrawView`,
* React root, DOM node, `Window`, listener, or package lease. Consumption
* removes the entry before validation so stale or mismatched state cannot be
* retried, and a single expiry timer bounds abandoned payload lifetime.
*/
export class ViewMigrationHandoffManager {
private readonly ttlMs: number;
private readonly scheduler: ViewMigrationHandoffScheduler;
private readonly entries = new Map<string, ViewMigrationHandoffEntry>();
private readonly tokensByLeaf = new Map<string, string>();
private cleanupTimer: number | null = null;
private tokenSequence = 0;
public constructor(options: ViewMigrationHandoffManagerOptions = {}) {
this.ttlMs = options.ttlMs ?? DEFAULT_HANDOFF_TTL_MS;
if (!Number.isFinite(this.ttlMs) || this.ttlMs <= 0) {
throw new Error("View migration handoff TTL must be positive");
}
this.scheduler =
options.scheduler ??
{
now: () => Date.now(),
setTimeout: (callback, delay) => window.setTimeout(callback, delay),
clearTimeout: (timer) => window.clearTimeout(timer),
};
}
/** Registers a handoff, replacing any older payload for the same leaf. */
public register(registration: ViewMigrationHandoffRegistration): string {
this.pruneExpired();
const previousToken = this.tokensByLeaf.get(registration.leafId);
if (previousToken) {
this.deleteEntry(previousToken);
}
const now = this.scheduler.now();
const token = `view-migration-${now.toString(36)}-${(++this.tokenSequence).toString(36)}`;
this.entries.set(token, {
...registration,
token,
expiresAt: now + this.ttlMs,
});
this.tokensByLeaf.set(registration.leafId, token);
this.scheduleCleanup();
return token;
}
/**
* Consumes a matching handoff exactly once.
*
* A token mismatch, leaf/path mismatch, file modification, or TTL expiry
* returns `null` and discards the candidate so the caller must use its
* ordinary disk-backed load path.
*/
public consume(
request: ViewMigrationHandoffRequest,
): ViewMigrationDrawingState | null {
this.pruneExpired();
const entry = this.entries.get(request.token);
if (!entry) {
return null;
}
this.deleteEntry(request.token);
this.scheduleCleanup();
if (
entry.leafId !== request.leafId ||
entry.filePath !== request.filePath ||
entry.fileMtime !== request.fileMtime
) {
return null;
}
return entry.drawing;
}
/** Drops all retained drawing state and cancels expiry work. */
public destroy(): void {
if (this.cleanupTimer !== null) {
this.scheduler.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
this.entries.clear();
this.tokensByLeaf.clear();
}
private deleteEntry(token: string): void {
const entry = this.entries.get(token);
if (!entry) {
return;
}
this.entries.delete(token);
if (this.tokensByLeaf.get(entry.leafId) === token) {
this.tokensByLeaf.delete(entry.leafId);
}
}
private pruneExpired(): void {
const now = this.scheduler.now();
for (const [token, entry] of this.entries) {
if (entry.expiresAt <= now) {
this.deleteEntry(token);
}
}
if (this.entries.size === 0 && this.cleanupTimer !== null) {
this.scheduler.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
}
private scheduleCleanup(): void {
if (this.cleanupTimer !== null) {
this.scheduler.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
if (this.entries.size === 0) {
return;
}
let nextExpiry = Number.POSITIVE_INFINITY;
for (const entry of this.entries.values()) {
nextExpiry = Math.min(nextExpiry, entry.expiresAt);
}
this.cleanupTimer = this.scheduler.setTimeout(() => {
this.cleanupTimer = null;
this.pruneExpired();
this.scheduleCleanup();
}, Math.max(0, nextExpiry - this.scheduler.now()));
}
}
+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";
};
@@ -0,0 +1,41 @@
import type ExcalidrawPlugin from "src/core/main";
import { ExcalidrawLib } from "../../types/excalidrawLib";
const DEFAULT_AREA_LIMIT = 16_777_216;
const DEFAULT_WIDTH_HEIGHT_LIMIT = 32_767;
/**
* Creates the narrow, window-runtime host adapter consumed by the Excalidraw
* fork's common and element packages.
*
* @remarks
* Capability methods read current plugin state rather than capturing settings
* values. The package manager owns both this adapter and its disposer, so the
* adapter cannot outlive the corresponding evaluated Excalidraw runtime.
*/
export const createObsidianCommonHostAdapter = (
plugin: ExcalidrawPlugin,
protocolVersion: typeof ExcalidrawLib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION,
): ExcalidrawLib.ObsidianCommonHostAdapter => ({
protocolVersion,
getDeviceInfo: () => plugin.getObsidianDevice(),
getDesktopUIMode: () => plugin.getPreferredUIMode(),
getPreferredUIMode: (formFactor) => {
if (formFactor === "phone") {
return plugin.settings.phoneUIMode;
}
if (formFactor === "tablet") {
return plugin.settings.tabletUIMode;
}
return plugin.settings.desktopUIMode;
},
getCanvasLimits: () => ({
areaLimit: plugin.excalidrawConfig?.areaLimit ?? DEFAULT_AREA_LIMIT,
widthHeightLimit:
plugin.excalidrawConfig?.widthHeightLimit ?? DEFAULT_WIDTH_HEIGHT_LIMIT,
}),
getHighlightColor: (sceneBackgroundColor, opacity) =>
plugin.getHighlightColor(sceneBackgroundColor, opacity),
});
@@ -0,0 +1,47 @@
import type ExcalidrawPlugin from "src/core/main";
import { ExcalidrawLib } from "../../types/excalidrawLib";
/**
* Creates the plugin-wide capability adapter consumed by the evaluated
* Excalidraw package runtime.
*
* @remarks
* Settings methods read current values rather than capturing a stale snapshot.
* The adapter exposes only semantic operations and never the plugin instance,
* settings object, or active-view state.
*/
export const createObsidianExcalidrawHostAdapter = (
plugin: ExcalidrawPlugin,
protocolVersion: typeof ExcalidrawLib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION,
): ExcalidrawLib.ObsidianExcalidrawHostAdapter => ({
protocolVersion,
isDoubleTapEraserEnabled: () => plugin.settings.penModeDoubleTapEraser,
getZoomToFitMaxLevel: () => plugin.settings.zoomToFitMaxLevel,
isPenModeCrosshairVisible: () => plugin.settings.penModeCrosshairVisible,
isSingleFingerPanningEnabled: () =>
plugin.settings.penModeSingleFingerPanning,
isDoubleClickTextEditingDisabled: () =>
plugin.settings.disableDoubleClickTextEditing,
getZoomStep: () => plugin.settings.zoomStep,
getZoomMin: () => plugin.settings.zoomMin,
getZoomMax: () => plugin.settings.zoomMax,
isContextMenuDisabled: () => plugin.settings.disableContextMenu,
shouldSyncElementLinkWithText: () => plugin.settings.syncElementLinkWithText,
loadFontFromFile: (filename) => plugin.loadFontFromFile(filename),
getMermaid: () => plugin.getMermaid(),
runAction: (action) => plugin.runAction(action),
getLabel: (key) =>
plugin.getLabel(key as Parameters<ExcalidrawPlugin["getLabel"]>[0]),
attachInlineLinkSuggester: (
inputEl,
widthWrapper,
container,
suppressPlaceholder,
) =>
plugin.attachInlineLinkSuggester(
inputEl,
widthWrapper,
container ?? undefined,
suppressPlaceholder,
),
});
+4410 -3873
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,149 @@
/**
* Obsidian 1.13 declarative adapter for canonical setting specifications.
*/
import type { SettingBindingRegistry } from "src/core/settings/SettingBindingRegistry";
import type { LegacySettingsAdapter } from "src/core/settings/LegacySettingsAdapter";
import type {
SettingBindingKey,
SettingSpec,
} from "src/core/settings/settingSpecs";
import type {
SettingDefinition,
} from "src/types/obsidianDeclarativeSettings";
import { annotateMarkdownDefinition } from "src/core/settings/declarativeSettingsMarkdown";
/** Converts canonical setting rows into Obsidian 1.13 definitions. */
export class DeclarativeSettingsAdapter {
private readonly bindings: SettingBindingRegistry;
private readonly legacyAdapter: LegacySettingsAdapter;
private registerBindings = true;
constructor(
bindings: SettingBindingRegistry,
legacyAdapter: LegacySettingsAdapter,
) {
this.bindings = bindings;
this.legacyAdapter = legacyAdapter;
}
/** Starts a definition build, optionally replacing the live control bindings. */
beginBuild(registerBindings: boolean = true): void {
this.registerBindings = registerBindings;
if (registerBindings) {
this.bindings.clear();
}
}
/** Converts one canonical row during the current definition build. */
toDefinition(spec: SettingSpec): SettingDefinition<SettingBindingKey> {
if (this.requiresCustomRender(spec)) {
return this.toRenderedDefinition(spec);
}
if (this.registerBindings) {
this.bindings.register(spec);
}
const base = {
name: this.toSearchText(spec.name),
desc: spec.desc,
aliases: spec.aliases,
searchable: spec.searchable,
visible: spec.visible,
};
const control = spec.control;
switch (control.type) {
case "toggle":
return {
...base,
control: {
type: "toggle",
key: control.key,
disabled: control.disabled,
},
};
case "text":
return {
...base,
control: {
type: "text",
key: control.key,
placeholder: control.placeholder,
disabled: control.disabled,
},
};
case "dropdown":
return {
...base,
control: {
type: "dropdown",
key: control.key,
options: Object.fromEntries(
control.options.map(({ value, label }) => [value, label]),
),
disabled: control.disabled,
},
};
case "number-dropdown":
return {
...base,
control: {
type: "dropdown",
key: control.key,
options: Object.fromEntries(
control.options.map(({ value, label }) => [
value.toString(),
label,
]),
),
disabled: control.disabled,
},
};
case "slider":
return {
...base,
control: {
type: "slider",
key: control.key,
min: control.min,
max: control.max,
step: control.step,
disabled: control.disabled,
},
};
}
}
private requiresCustomRender(spec: SettingSpec): boolean {
if (typeof spec.name !== "string") {
return true;
}
const control = spec.control;
return (
(control.type === "text" &&
Boolean(control.capture || control.sanitize || control.vaultPath)) ||
(control.type === "slider" && control.minWidth !== undefined)
);
}
private toRenderedDefinition(
spec: SettingSpec,
): SettingDefinition<SettingBindingKey> {
return annotateMarkdownDefinition(
{
name: this.toSearchText(spec.name),
desc:
spec.desc === undefined ? undefined : this.toSearchText(spec.desc),
aliases: spec.aliases,
searchable: spec.searchable,
visible: spec.visible,
render: (setting) => this.legacyAdapter.configure(setting, spec),
},
{ controlType: spec.control.type },
);
}
private toSearchText(value: string | DocumentFragment): string {
return typeof value === "string" ? value : (value.textContent ?? "");
}
}
+139
View File
@@ -0,0 +1,139 @@
/**
* Imperative renderer for canonical setting-row specifications.
*/
import { Setting, type TextComponent } from "obsidian";
import type { SettingBindingRegistry } from "src/core/settings/SettingBindingRegistry";
import type {
SettingSpec,
TextControl,
} from "src/core/settings/settingSpecs";
import { configureSliderWithText } from "src/utils/sliderUtils";
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" | "file-or-folder",
options: NonNullable<TextControl["vaultPath"]>["options"],
): void;
}
/** Builds or configures imperative Obsidian setting rows from canonical specs. */
export class LegacySettingsAdapter {
constructor(
private readonly bindings: SettingBindingRegistry,
private readonly host: LegacySettingsAdapterHost,
) {}
/**
* Creates one legacy row. Slider return behavior remains `undefined` for
* compatibility with the former in-class interpreter.
*/
render(container: HTMLElement, spec: SettingSpec): Setting | undefined {
const visible =
typeof spec.visible === "function"
? spec.visible()
: (spec.visible ?? true);
if (!visible) {
return undefined;
}
const setting = new Setting(container);
this.configure(setting, spec);
return spec.control.type === "slider" ? undefined : setting;
}
/** Configures a row supplied by either the legacy or declarative host. */
configure(setting: Setting, spec: SettingSpec): void {
const control = spec.control;
const disabled =
typeof control.disabled === "function"
? control.disabled()
: (control.disabled ?? false);
if (control.type === "slider") {
configureSliderWithText(setting, {
name: cloneSettingFragment(spec.name),
desc: cloneSettingFragment(spec.desc),
value: this.bindings.getSpecValue(spec) as number,
min: control.min,
max: control.max,
step: control.step,
minWidth: control.minWidth,
onChange: (value) => this.bindings.setLegacySpecValue(spec, value),
});
setting.setDisabled(disabled);
return;
}
setting.setName(cloneSettingFragment(spec.name));
if (spec.desc) {
setting.setDesc(cloneSettingFragment(spec.desc));
}
switch (control.type) {
case "toggle":
setting.addToggle((toggle) =>
toggle
.setValue(this.bindings.getSpecValue(spec) as boolean)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value),
),
);
break;
case "text":
setting.addText((text) => {
control.capture?.(text);
if (control.placeholder !== undefined) {
text.setPlaceholder(control.placeholder);
}
text
.setValue(this.bindings.getSpecValue(spec) as string)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value, () => {
if (control.sanitize) {
text.setValue(this.bindings.getSpecValue(spec) as string);
}
}),
);
if (control.vaultPath) {
this.host.addVaultPathSupport(
setting,
text,
control.vaultPath.kind,
control.vaultPath.options,
);
}
});
break;
case "dropdown":
setting.addDropdown((dropdown) => {
for (const option of control.options) {
dropdown.addOption(option.value, option.label);
}
dropdown
.setValue(this.bindings.getSpecValue(spec) as string)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value),
);
});
break;
case "number-dropdown":
setting.addDropdown((dropdown) => {
for (const option of control.options) {
dropdown.addOption(option.value.toString(), option.label);
}
dropdown
.setValue(this.bindings.getSpecValue(spec) as string)
.onChange((value) =>
this.bindings.setLegacySpecValue(spec, value),
);
});
}
// Setting#setDisabled only affects controls that already exist. Apply the
// initial predicate after configuring the row so dependent controls start
// in the same state in both legacy and declarative render paths.
setting.setDisabled(disabled);
}
}
@@ -0,0 +1,42 @@
/**
* Serialized stable-snapshot writer for plugin settings.
*/
/** Persistence operation required by the serialized settings writer. */
export interface SerializedSettingsWriterHost<Snapshot> {
saveData(data: Snapshot): Promise<void>;
}
/**
* Serializes complete settings writes so an older save cannot finish after a
* newer one. Each request captures an immutable JSON snapshot before waiting
* for an earlier write.
*/
export class SerializedSettingsWriter<
Snapshot extends Record<string, unknown>,
> {
private persistenceChain: Promise<void> = Promise.resolve();
public constructor(
private readonly host: SerializedSettingsWriterHost<Snapshot>,
) {}
/** Queues one stable snapshot and resolves when that snapshot is saved. */
public persist(settings: Snapshot): Promise<void> {
let snapshot: Snapshot;
try {
snapshot = JSON.parse(JSON.stringify(settings)) as Snapshot;
} catch (error) {
return Promise.reject(
error instanceof Error
? error
: new Error("Could not serialize settings snapshot"),
);
}
const persistence = this.persistenceChain
.catch((): void => undefined)
.then(() => this.host.saveData(snapshot));
this.persistenceChain = persistence;
return persistence;
}
}
Loaded 100 of 230 files, more files were not shown because too many files have changed in this diff. Show more