Compare commits

...
Author SHA1 Message Date
zsviczian 078f48e28a Support Obsidian CLI testing on Windows and macOS 2026-10-11 13:22:07 +02:00
zsviczian f30b4c5d3d updated messages 2026-10-03 13:16:44 +02:00
zsviczian 593ad99bab Merge PR #2959 with mount lifecycle fixes and 2.29.0 release note 2026-10-03 13:10:05 +02:00
zsviczian f591b7558f Merge pull request #2964 from mnaoumov/save-pasted-images-via-saveAttachment
Save pasted and dropped images through internal `app.saveAttachment()`
2026-09-30 22:54:46 +02:00
Michael Naumov 9cf33817b7 Save pasted and dropped images through app.saveAttachment
When the drawing is the active file and no onImageFilePathHook is set, an
imported image is saved the way Obsidian saves one pasted or dropped into a
markdown note, so attachment-management plugins apply their naming and
location rules to it. A generated paste name follows Obsidian's own
"Pasted image YYYYMMDDHHmmss" in that case. Every other caller keeps the
existing path.
2026-09-29 14:31:31 -06:00
zsviczian 128a9ef47b 2.28.1 2026-09-29 20:52:23 +02:00
zsviczian 96bd2212c2 2.28.0 2026-09-29 19:30:31 +02:00
zsviczian 3d8f312add Obsidian CLI testing framework 2026-09-29 17:26:28 +02:00
zsviczian bd40308a83 2.28.0-rc.0 2026-09-28 23:20:00 +02:00
zsviczian 3e13b61c6d lint fix 2026-09-28 22:00:31 +02:00
askalf 921f679f0b keep the mount plan checks runnable against the factory on master
master now builds the factory's Canvas leaf directly and inserts it into the
detached split, instead of calling workspace.createLeafInParent(). The check
script's stand-in WorkspaceSplit gains insertChild, and the fake workspace
drops the createLeafInParent it no longer needs. All 21 mount plan checks and
the call site checks pass on the merged tree.
2026-09-28 19:47:24 +00:00
askalf c3955cad5f Merge remote-tracking branch 'upstream/master' into fix/back-of-note-embeddable-canvas-node-race
# Conflicts:
#	src/view/managers/CanvasNodeFactory.ts
2026-09-28 19:42:42 +00:00
zsviczian 5da2b452f1 Merge pull request #2962 from zsviczian/toggleViewMode
feat: add ExcalidrawAutomate toggleViewMode API
2026-09-28 19:51:31 +02:00
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
askalf ef9b7cd014 Drop explanatory comments from the embeddable mount change 2026-09-25 18:37:22 +00:00
askalf 0d5a809372 simplify mount check wording 2026-09-25 17:32:29 +00:00
askalf 496d451914 Simplify embeddable mount check wording 2026-09-25 16:55:21 +00:00
askalf f25a7ba08b simplify embeddable mount checks 2026-09-25 16:18:24 +00:00
askalf eb284a1c85 bound the injected poll delay so a wait that never ends fails the block 2026-09-25 05:26:48 +00:00
askalf 6e3c8d7468 fold the factory lifecycle checks into the mount plan script
Events that used to be sequenced with timers now land on a named poll of the
wait, through the injected delay, so each block asserts the poll it ended on
rather than an elapsed time. The one block whose subject is elapsed time, the
slow real factory, still runs against the clock.
2026-09-25 05:23:09 +00:00
askalf 41e578320c describe the mount host selection as it stands 2026-09-25 05:23:09 +00:00
askalf a951d371cb pin the three inputs the mount dispatch forwards to the helper 2026-09-25 03:43:27 +00:00
zsviczian 542fcec6ac 2.28.0-beta.4 2026-09-24 22:30:49 +02:00
askalf d31ac3b62b require the mount effect to reach the factory only through the dispatch
The wiring checks pinned where the dispatch sits and how it cancels, but
not what else the effect does beside it. A readiness read in the effect's
own body (an early return onto the workspace leaf, or a ternary choosing
it) restores the whole-file leaf on a slow start while every existing
check stays green, and so does a direct createNode() or
mountWorkspaceLeaf() call next to the dispatch, which mounts a second
host. Reject both: the effect may not name canvasNodeFactory outside the
closures it hands the helper, and may not call either mount path itself.
2026-09-24 14:48:53 +00:00
askalf f96cbc53ff keep the clock in the two cap blocks whose subject is elapsed time
Counting reads made the cap blocks stop discriminating: the cap is a
wall-clock quantity, so readiness has to land after real elapsed time for
its expiry to be the thing under test. Both are green at base again without
them.
2026-09-22 12:09:04 +00:00
askalf dbc9476202 fold the mount checks into the repository's check-script idiom
The mount-plan checks had grown a case per scenario with narrated assertion
labels, so the three scripts read as a patch history rather than as a
description of the behaviour. Table the cases that share a shape, name each
block for what it pins, and run them through the same per-block runner the
lifecycle checks already use, so an arm that reintroduces one defect reports
every block it breaks instead of stopping at the first.

Sequencing by wall clock goes with it: the hosts now ready, give up or
cancel on a counted read, which is what the poll loop actually observes.
Only the two blocks whose subject is elapsed time still use timers. Drop the
helper JSDoc, the issue numbers the squashed commit will carry anyway, and
the comments arguing the implementation is correct rather than recording the
contract.
2026-09-22 12:05:10 +00:00
askalf 8e08316ba6 scope the cancellation-flag check to the mount effect's own body
The declaration check counted `let effectCancelled = false;` in the whole
file, so moving the sole declaration to module or component scope still
satisfied it while leaving a flag shared by every invocation: one
embeddable's cleanup then cancels the mount that replaced it, which is the
regression the flag exists to prevent. Parse the effect instead and require
the declaration's enclosing function to be the effect itself.

Reading the syntax tree also replaces the text heuristics for the other
wiring rows: the dispatch must be a statement of the effect's body and the
whole of its expression, which rejects an `if` gate and an `&&` operand
directly rather than by inspecting the preceding line.
2026-09-22 11:56:58 +00:00
askalf 1eb1aa9ff0 pin the canvas node factory's lifecycle settle sites
The mount wait's consumer was covered through the injected host interface, but the three sites that settle whenInitialized -- initialize() succeeding, its catch, destroy() -- were only read. Aliasing the two modules the factory imports but does not exercise lets it run under node, so the producer side and the real factory through the real dispatch are executed too.
2026-09-21 03:14:27 +00:00
askalf a18fd81133 pin the lifecycle wait and the per-dispatch cancellation latch
Seven discriminating checks and three controls for the lifecycle wait and
the superseded-mount latch, plus call-site assertions requiring the
dispatch to consult this invocation's own cancellation flag and the
cleanup to raise it before its early returns.
2026-09-21 01:48:41 +00:00
askalf d38510fad7 wait for the canvas node factory's lifecycle instead of a fixed timeout
A subpath embed fell back to a whole-file workspace leaf whenever the
factory took longer than the two second cap to initialize. Startup can
legitimately outlast it: layout ready polls up to 50 x 50 ms before
initialize() is called, and initialize() then awaits the core canvas
plugin's load, so the cap cannot tell a slow start from one that will
never finish. CanvasNodeFactory now exposes whenInitialized, settled on
every terminal path, and the wait uses it; the cap remains only for a
host that reports no lifecycle.

Cancellation also latches per dispatch, so a mount superseded by a link
change cannot mount over its replacement once the shared refs are
repopulated.
2026-09-21 01:42:31 +00:00
zsviczian a8182899b7 2.28.0-beta.3 2026-09-20 18:06:08 +02:00
askalf b48112e4ca pin the mount dispatch against a readiness gate and cover zero/nullish waits
The call-site check accepted a dispatch re-gated on
view.canvasNodeFactory.isInitialized(), which skips the wait inside
mountEmbeddableHost and restores the whole-file workspace leaf while both
check scripts stayed green. Require the dispatch to be reached
unconditionally.

Also pin the boundaries the existing rows only reached by argument: a zero
timeout, an undefined subpath, a null extension, a factory that never
appears or is torn down mid-wait, the synchrony of both fast paths, a
teardown landing as the factory readies, and concurrent embeddables.
2026-09-20 13:34:16 +00:00
askalf 5c5e351258 pin the embeddable mount dispatch at its call site
The mount-plan checks exercise the helper only, so removing the dispatch
from the mount effect and keeping the helper leaves them green while the
back-of-the-note embeddable regresses to a whole-file workspace leaf.
Check the wiring against the source of the effect, which cannot be
imported here because it pulls in the types-only obsidian package.
2026-09-20 13:09:37 +00:00
zsviczian 9d5057dba7 updated excalidraw manifest with correct link 2026-09-20 14:36:40 +02:00
askalf 9e69f245b5 move the mount-plan check to the repository's script convention
The first version of the regression test used node:test inside src/, which
the repository's own lint rejects there: src/ is runtime code that must work
on mobile and in popout windows, so node built-ins and bare timers are
banned. Follow scripts/check-*.mjs instead - jiti-imported TypeScript with
node:assert, outside the linted source tree - and inject the wait primitive
so the module can still default to Obsidian's sleep global.
2026-09-20 11:30:58 +00:00
askalf ac359575f6 fix back-of-the-note embeddable initializing as the full drawing
A subpath embeddable can mount before CanvasNodeFactory has finished its
asynchronous initialization on layout ready. The mount check treated an
uninitialized factory the same as an absent subpath and fell through to a
workspace leaf, which renders the whole file - for a hybrid drawing, the
entire drawing - and cannot be edited. Wait for the factory instead, with a
timeout so the leaf fallback still applies when it never initializes.

[#2931](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2931)
2026-09-20 11:19:18 +00: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
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
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
73 changed files with 66281 additions and 2910 deletions

No files matched your search

+16 -4
View File
@@ -54,6 +54,8 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- Default to local/offline operation. Only make network requests when essential to the feature.
- No hidden telemetry. If you collect optional analytics or call third-party services, require explicit opt-in and document clearly in `README.md` and in settings.
- Keep every external origin and every fully static URL as a literal `https://...` string in source so reviewers and security scanners can identify the destination without executing the code. A dynamic resource path may be appended only to a literal base URL, and each untrusted path segment must be validated or encoded.
- Never conceal a network destination or evade a scanner finding by splitting or joining domain labels, deriving an origin from Git state, environment variables, runtime configuration, or character codes, or by encoding, compressing, encrypting, or otherwise transforming a URL. Do not weaken, suppress, or work around a scanner by making an endpoint less statically visible; fix the underlying behavior or document a genuine false positive transparently.
- Never execute remote code, fetch and eval scripts, or auto-update plugin code outside of normal releases.
- Minimize scope: read/write only what's necessary inside the vault. Do not access files outside the vault.
- Clearly disclose any external services used, data sent, and risks.
@@ -310,11 +312,11 @@ Window ownership for rendering is not the same as ownership for persistent plugi
- `src/lang/helpers.ts` resolves those tokens at runtime.
- If you add new runtime-dependent locale patterns, you must keep `rollup.config.mjs` and `src/lang/helpers.ts` in sync.
### Safe URL Tokenization
### Safe URL Handling
- Safe URLs are centralized in `src/constants/safeUrls.ts`.
- The build tokenizes URL constants and resolves them at runtime.
- If you change safe URL handling, rebuild and verify both token emission and token resolution.
- Preserve literal, statically reviewable origins and complete static URLs. Only repository-relative or resource-relative paths may be constructed dynamically from validated or encoded path segments.
- If you change safe URL handling, rebuild and verify that the intended literal origins remain visible in both source and `dist/main.js`, and search for domain assembly or endpoint-obfuscation patterns before release.
### Versioning Nuance
@@ -505,7 +507,17 @@ If a task touches any of the above, read adjacent code first and validate more c
## Validation Expectations
There is no standard unit-test suite wired into `package.json`.
There is no comprehensive runtime unit-test suite. The CLI harness has focused tests wired into `package.json`.
### Obsidian CLI runtime lane
Follow [Obsidian runtime testing](docs/OBSIDIAN_RUNTIME_TESTING.md) for macOS and Windows setup, and its linked fork guide for feature gates. `npm run test:obsidian:runner` tests the vault guards and platform launchers without Obsidian. `npm run verify:obsidian:plugin` builds this plugin with the installed component package. `npm run verify:obsidian` first builds and copies the sibling fork's four Obsidian artifacts. Both native lanes require the explicitly configured `excalidraw-test` vault, check the CLI-selected vault and config paths before deployment, stage the exact `main.js`/CSS/manifest, and assert a live drawing and clean JavaScript error buffer. Review the report's build mode, source identity, hashes, and cleanup result. A previous local artifact copy into `node_modules` remains in effect for the plugin-only lane until `npm install` restores the published package.
Look for an existing `excalidraw-test` vault in Obsidian's vault registry and confirm its path and enabled plugin. If absent, ask the user to create it and install/enable Excalidraw from Community plugins before deployment. Do not create or download a replacement vault without consent. Complete any first-open trust prompt and reopen the vault before CLI probes. Never choose a personal/default vault when the test vault is unavailable.
Use the test-only `scripts/testing/host/processTools.mjs` for native launches. Windows captures output through `Obsidian.com`; long or multiline Windows evals use an owned temporary UTF-8 script and are cleaned up after each call. npm and Yarn launch through JavaScript entries using the current Node executable, avoiding Windows `.cmd` shims. Run CLI scenarios serially. If a request times out, check for a pending Obsidian error/trust dialog; ask the user to save and restart when necessary rather than force-closing an application with other vaults open. Record Windows and macOS live validation separately.
Use this lane after fork behavior or packaging changes when Obsidian is available, then exercise the affected workflow using the fork's V03–V11 validation gates. A blank-drawing smoke does not validate raw text, clipboard, font/image assets, saved scenes, custom pens, popout migration, offline behavior, or physical mobile touch. Record what was tested, artifact/source identity, and any pending or unavailable gates. Never deploy a local build to a personal/default vault as a substitute for the named test vault. Keep CLI eval access to internal plugin instances and temporary test controllers out of production modules.
Repo-wide ESLint currently reports a large backlog of pre-existing issues, so it is not yet a blocking pass/fail gate for every task.
+23 -1
View File
@@ -14,7 +14,7 @@ Before spending your valuable time writing code for a new feature or significant
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).*
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).
4. Create or locate a dedicated `excalidraw-test` vault, install and enable Excalidraw from **Settings → Community plugins**, and follow [Obsidian runtime testing](docs/OBSIDIAN_RUNTIME_TESTING.md). The CLI runner copies the three built files from `dist/` into this vault; it rejects symlinked plugin targets. For an independent manual development setup, [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) can make reloads faster.
## 🛠️ Build and Lint Commands
@@ -27,10 +27,32 @@ Before spending your valuable time writing code for a new feature or significant
The shipped plugin is `dist/main.js`, `dist/styles.css`, and `dist/manifest.json`. Keep `main.js` below the release size limit and report its byte size after dependency or packaging changes.
## Updating the EA script template
`npm run doc` and `npm run skill` both build the public library declarations, then
run full documentation generation. When `../ea-script-template` exists, they also
refresh its local agent references, generated EA declaration graph and provenance,
type dependencies, and template update manifest. The template consumes declarations
only; personal script workspaces no longer need this plugin as a Git dependency.
After generation, run `npm install`, `npm run check`, `npm run build`, and
`npm run test:template` in the template. Review both repositories separately and
publish the template's updated `master` so users can receive the snapshot with
`npm run update-template`. See the template's `.template/README.md` for ownership,
conflict handling, and the one-time adoption procedure for older workspaces.
## 🧪 Testing
At this time, the project **has no comprehensive automated test suite**. As a contributor, you are responsible for testing your changes thoroughly.
The native CLI lane supports macOS and Windows. Run `npm run test:obsidian:runner`
for the offline harness tests, then `npm run verify:obsidian:plugin` to build and
smoke-test this plugin with its installed Excalidraw package. For changes in the
sibling fork, use `npm run verify:obsidian`, which rebuilds and copies the fork's
four Obsidian artifacts first. Both native commands require explicit test-vault
paths and a running Obsidian with CLI access enabled. See the [setup, platform
commands, reports, and cleanup contract](docs/OBSIDIAN_RUNTIME_TESTING.md).
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)
+10 -10
View File
@@ -8,7 +8,7 @@ Scope summary:
- Keep [docs/AITrainingData](docs/AITrainingData) as the canonical output location.
- Keep [docs/AITrainingData/ExcalidrawAutomate full library for LLM training.md](docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md) as a stable entrypoint, but curate it as a router to skill-first references.
- Use one unified generator behind `npm run doc`.
- Keep [ea-scripts/index-new.md](ea-scripts/index-new.md) manually curated.
- 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).
@@ -23,10 +23,10 @@ Scope summary:
- It must warn AI tools that generated code quality may fail if linked skill/reference URLs are inaccessible (for example: URL access disabled in some chat tools).
3. Script library publishing guidance
- `index-new.md` remains manual.
- [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.
- Every publishing PR (new script or script update) must update [ea-scripts/directory-info.json](ea-scripts/directory-info.json).
- For updates, the `mtime` value for the updated script file must be refreshed so the plugin can detect local update availability.
- `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.
@@ -56,7 +56,7 @@ Target branch: `improved-scripting-skills`.
| Unify generator implementation behind `npm run doc` | Complete | Added shared generator core at [scripts/excalidraw-docs-generator-core.mjs](scripts/excalidraw-docs-generator-core.mjs); both [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs) and [scripts/skill-builder.mjs](scripts/skill-builder.mjs) are thin wrappers over one code path |
| Ensure canonical pen type completeness in generated docs | Complete | Generated references now include canonical Obsidian pen stroke type definitions plus the full public `src/types` and `lib/types` declaration surface |
| Curate legacy training entrypoint warning and routing | Complete | Legacy training entrypoint now warns about inaccessible references, names the master repository, and routes agents to the curated skill/reference set with absolute GitHub URLs |
| Add PR publishing workflow guidance for scripting agents | Complete | Generated skill guidance now directs script publishing through PRs, keeps `index-new.md` manual, and requires `directory-info.json` mtime updates |
| 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 |
@@ -123,12 +123,12 @@ Planned changes:
- Add concise maintainer-approved workflow guidance in skill docs:
- add script to [ea-scripts](ea-scripts)
- add image to [images](images)
- update [ea-scripts/index-new.md](ea-scripts/index-new.md) manually
- update [ea-scripts/directory-info.json](ea-scripts/directory-info.json) in the same PR
- for script updates, refresh the target script `mtime` entry in [ea-scripts/directory-info.json](ea-scripts/directory-info.json)
- 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
- Explicitly avoid automating `index-new.md`.
- 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.
@@ -136,7 +136,7 @@ Acceptance:
Status:
- Complete.
- The generated skill file now includes a dedicated publishing workflow section with absolute repository links, PR-only guidance, manual `index-new.md` curation, and `directory-info.json` update requirements.
- 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:
@@ -770,6 +770,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.
@@ -847,8 +871,8 @@ export declare class ExcalidrawAutomate {
* @param {Object} [formatting] - Formatting options for the arrow element.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.startArrowHead] - The start arrowhead type.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.endArrowHead] - The end arrowhead type.
* @param {string} [formatting.startObjectId] - The ID of the start object.
* @param {string} [formatting.endObjectId] - The ID of the end object.
* @param {string} [formatting.startObjectId] - The ID of the start object. When omitted, the arrow start is unbound.
* @param {string} [formatting.endObjectId] - The ID of the end object. When omitted, the arrow end is unbound.
* BindMode Determines whether the arrow remains outside the shape or is allowed to
* go all the way inside the shape up to the exact fixed point.
* @param {"inside" | "orbit"} [formatting.startBindMode] - The binding mode for the start object.
@@ -1516,6 +1540,13 @@ export declare class ExcalidrawAutomate {
* @returns {string | null} The groupId or null if not found.
*/
getCommonGroupForElements(elements: ExcalidrawElement[]): string;
/**
* This is a convenience method to get the release notes for the plugin.
* @returns {Object} The release notes object.
*/
getReleaseNotes(): {
[k: string]: string;
};
/**
* Gets all the elements from elements[] that share one or more groupIds with the specified element.
* @param {ExcalidrawElement} element - The element to check.
@@ -2139,7 +2170,6 @@ export type MarkdownBlockCacheEntry = {
};
export interface ViewSemaphores {
warnAboutLinearElementLinkClick: boolean;
embeddableIsEditingSelf: boolean;
popoutUnload: boolean;
windowMigrating: boolean;
viewloaded: boolean;
@@ -2147,12 +2177,7 @@ export interface ViewSemaphores {
scriptsReady: boolean;
justLoaded: boolean;
preventAutozoom: boolean;
autosaving: boolean;
forceSaving: boolean;
dirty: string | null;
preventReload: boolean;
isEditingText: boolean;
saving: boolean;
hoverSleep: boolean;
wheelTimeout: number | null;
shouldSaveImportedImage: boolean;
@@ -2329,12 +2354,22 @@ export interface SelectableFontOption {
/* lib/types/githubTypes.d.ts */
/* ******************************** */
/**
* Metadata entry describing a file in the remote EA scripts directory listing.
* Metadata entry describing a file in the legacy remote EA scripts directory listing.
*/
export type RemoteDirectoryInfo = {
fname: string;
mtime: number;
};
/**
* File metadata returned by GitHub's repository contents endpoint.
*/
export type GitHubRepositoryContentFile = {
name: string;
path: string;
sha: string;
type: "file" | "dir" | "symlink" | "submodule";
download_url?: string | null;
};
/* ************************************** */
/* lib/types/markdownImageTypes.d.ts */
@@ -2566,6 +2601,32 @@ export interface InputPromptOptions {
draggable?: boolean;
}
/* ************************************* */
/* lib/types/scriptStoreTypes.d.ts */
/* ************************************* */
export type ScriptStoreCategory = {
name: string;
description: string;
};
export type ScriptStoreEntry = {
name: string;
file: string;
installUrl: string;
iconUrl: string;
author: string;
authorUrl: string;
sourceUrl: string;
descriptionHtml: string;
categories: string[];
featuredRank?: number;
};
export type ScriptStoreCatalog = {
version: number;
categories: ScriptStoreCategory[];
scripts: ScriptStoreEntry[];
};
export type ScriptStoreInstallState = "install" | "update" | "up-to-date" | "error";
/* ************************************** */
/* lib/types/sidepanelTabTypes.d.ts */
/* ************************************** */
@@ -2692,26 +2753,6 @@ export interface FrameRenderingOptions {
clip: boolean;
}
export type PaneTarget = "active-pane" | "new-pane" | "popout-window" | "new-tab" | "md-properties";
export interface NestedFileNode {
file: TFile;
/**
* All distinct dependency paths from the root file down to this embedded file.
* Each path is an ordered array of TFile objects starting with the `rootFile` at index 0.
*
* @example
* If Root -> A -> B2.2 and Root -> B -> B2 -> B2.2
* The paths for B2.2 will be:
* [
* [Root, A, B2.2],
* [Root, B, B2, B2.2]
* ]
*
* Usage: To find which top-level embeds to reload if this file changes,
* you can map over `paths` and collect `path[1]`.
*/
paths: TFile[][];
}
export type NestedFileMap = Map<TFile, NestedFileNode>;
/* ************************************** */
/* node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts */
@@ -2876,6 +2917,11 @@ type _ExcalidrawElementBase = Readonly<{
boundElements: readonly BoundElement[] | null;
/** epoch (ms) timestamp of last element update */
updated: number;
/** Client wall-clock creation time in epoch milliseconds; null if unknown.
Preserved for this element's lifetime, including edits and undo/redo,
and excluded from `ElementUpdate` (mutateElement / newElementWith).
Duplicating an element starts a new lifetime. Not an ordering clock. */
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -2887,6 +2933,14 @@ export type ExcalidrawSelectionElement = _ExcalidrawElementBase & {
export type ExcalidrawRectangleElement = _ExcalidrawElementBase & {
type: "rectangle";
};
export type ExcalidrawStickyNoteElement = _ExcalidrawElementBase & Readonly<{
type: "stickynote";
/**
* The height the user set, from which the layout derives `height`: the
* note grows above it to fit its label and never shrinks below it
*/
baseHeight: number;
}>;
export type ExcalidrawDiamondElement = _ExcalidrawElementBase & {
type: "diamond";
};
@@ -2984,14 +3038,14 @@ export type ExcalidrawFrameLikeElement = ExcalidrawFrameElement | ExcalidrawMagi
* These are elements that don't have any additional properties.
*/
export type ExcalidrawGenericElement = ExcalidrawSelectionElement | ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawFlowchartNodeElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawRectanguloidElement = ExcalidrawRectangleElement | ExcalidrawImageElement | ExcalidrawTextElement | ExcalidrawFreeDrawElement | ExcalidrawIframeLikeElement | ExcalidrawFrameLikeElement | ExcalidrawEmbeddableElement | ExcalidrawSelectionElement;
export type ExcalidrawFlowchartNodeElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawRectanguloidElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawImageElement | ExcalidrawTextElement | ExcalidrawFreeDrawElement | ExcalidrawIframeLikeElement | ExcalidrawFrameLikeElement | ExcalidrawEmbeddableElement | ExcalidrawSelectionElement;
/**
* ExcalidrawElement should be JSON serializable and (eventually) contain
* no computed data. The list of all ExcalidrawElements should be shareable
* between peers and contain no state local to the peer.
*/
export type ExcalidrawElement = ExcalidrawGenericElement | ExcalidrawTextElement | ExcalidrawLinearElement | ExcalidrawArrowElement | ExcalidrawFreeDrawElement | ExcalidrawImageElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement;
export type ExcalidrawElement = ExcalidrawGenericElement | ExcalidrawStickyNoteElement | ExcalidrawTextElement | ExcalidrawLinearElement | ExcalidrawArrowElement | ExcalidrawFreeDrawElement | ExcalidrawImageElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement;
export type ExcalidrawNonSelectionElement = Exclude<ExcalidrawElement, ExcalidrawSelectionElement>;
export type Ordered<TElement extends ExcalidrawElement> = TElement & {
index: FractionalIndex;
@@ -3005,11 +3059,20 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
type: "text";
fontSize: number;
fontFamily: FontFamilyValues;
/**
* The font size the user picked, from which the layout derives `fontSize`.
* Today only sticky note labels have one: the auto-fit shrinks below it
* and never above it (compare `baseHeight`, which the note grows above).
* `null` for every other text. Read it through `getBaseFontSize` —
* generic binding repair can detach a label without clearing this, so
* the container decides its meaning.
*/
baseFontSize: number | null;
text: string;
rawText: string;
textAlign: TextAlign;
verticalAlign: VerticalAlign;
containerId: ExcalidrawGenericElement["id"] | null;
containerId: ExcalidrawTextContainer["id"] | null;
originalText: string;
/**
* If `true` the width will fit the text. If `false`, the text will
@@ -3033,8 +3096,8 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
* */
labelPosition?: number | null;
}>;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
export type ExcalidrawTextElementWithContainer = {
containerId: ExcalidrawTextContainer["id"];
} & ExcalidrawTextElement;
@@ -3213,7 +3276,7 @@ declare class App extends React.Component<AppProps, AppState> {
library: AppClassProperties["library"];
libraryItemsFromStorage: LibraryItems | undefined;
id: string;
private store;
store: Store;
private history;
private shouldRenderAllEmbeddables;
excalidrawContainerValue: {
@@ -3240,14 +3303,24 @@ declare class App extends React.Component<AppProps, AppState> {
private appStateObserver;
onStateChange: OnStateChange;
bucketFill: AppBucketFill;
toolDrag: AppToolDrag;
flowchart: AppFlowchart;
cursor: AppCursor;
arrowText: AppArrowText;
pan: AppPan;
viewport: AppViewport;
wheel: AppWheel;
bindModeHandler: ReturnType<typeof setTimeout> | null;
private textWysiwygSubmitHandler;
hitLinkElement?: NonDeletedExcalidrawElement;
lastPointerDownEvent: React.PointerEvent<HTMLElement> | null;
/**
* the handle of the resize in progress while `state.isResizing` — for UI
* that words itself by handle (a sticky note's corners resize
* proportionally, its edges freely); not app state, so it costs no
* re-render of its own
*/
activeResizeHandle: TransformHandleDirection | null;
lastPointerUpEvent: React.PointerEvent<HTMLElement> | PointerEvent | null;
lastPointerUpIsDoubleClick: boolean;
lastPointerMoveEvent: PointerEvent | null;
@@ -3402,6 +3475,12 @@ declare class App extends React.Component<AppProps, AppState> {
missingPointerEventCleanupEmitter: Emitter<[event: PointerEvent | null]>;
onRemoveEventListenersEmitter: Emitter<[]>;
api: ExcalidrawImperativeAPI;
private elementRenderOverrides;
/** offsets of `elementRenderOverrides`; keeps its identity while they don't change */
private elementRenderOffsets;
private renderOverridesUpdatePending;
private getRenderOverrideConfig;
private getElementRenderState;
private createExcalidrawAPI;
constructor(props: AppProps);
/**
@@ -3532,7 +3611,6 @@ declare class App extends React.Component<AppProps, AppState> {
private onBlur;
private onUnload;
private disableEvent;
private preventBrowserZoomWheel;
private handleNavigationModeKeyDown;
/**
* PageUp/PageDown scroll the canvas by a page — vertically, or
@@ -3670,6 +3748,10 @@ declare class App extends React.Component<AppProps, AppState> {
captureUpdate?: SceneData["captureUpdate"];
forceFlushSync?: boolean;
}) => void;
/**
* see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details
*/
setElementRenderOverrides: (overrides: ElementRenderOverrides | null) => void;
applyDeltas: (deltas: StoreDelta[], options?: ApplyToOptions) => [SceneElementsMap, AppState, boolean];
mutateElement: <TElement extends Mutable<ExcalidrawElement>>(element: TElement, updates: ElementUpdate<TElement>, informMutation?: boolean) => TElement;
triggerRender: (
@@ -3765,6 +3847,7 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3800,6 +3883,44 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
customData?: Record<string, any>;
}> & Readonly<{
type: "stickynote";
baseHeight: number;
}> & {
isDeleted: false;
}) | (Readonly<{
id: string;
x: number;
y: number;
strokeColor: string;
backgroundColor: string;
fillStyle: import("@excalidraw/element/types").FillStyle;
strokeWidth: number;
strokeStyle: import("@excalidraw/element/types").StrokeStyle;
roundness: null | {
type: import("@excalidraw/element/types").RoundnessType;
value?: number;
};
roughness: number;
opacity: number;
width: number;
height: number;
angle: Radians;
seed: number;
version: number;
versionNonce: number;
index: import("@excalidraw/element/types").FractionalIndex | null;
isDeleted: boolean;
groupIds: readonly import("@excalidraw/element/types").GroupId[];
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3835,6 +3956,7 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3870,6 +3992,7 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3899,7 +4022,25 @@ declare class App extends React.Component<AppProps, AppState> {
* so the whole create-and-type lands in a single entry.
*/
private isEditingTextContent;
private startTextEditing;
startTextEditing: ({ sceneX, sceneY, insertAtParentCenter, container, autoEdit, initialCaretSceneCoords, arrowEndpoint, }: {
/** X position to insert text at */
sceneX: number;
/** Y position to insert text at */
sceneY: number;
/** whether to attempt to insert at element center if applicable */
insertAtParentCenter?: boolean;
container?: ExcalidrawTextContainer | null;
autoEdit?: boolean;
initialCaretSceneCoords?: {
x: number;
y: number;
};
/**
* creates the text as a label for this arrow endpoint: the binding then
* dictates the text's position and alignment, overriding (sceneX, sceneY)
*/
arrowEndpoint?: ArrowEndpoint | null;
}) => void;
private debounceDoubleClickTimestamp;
private startImageCropping;
private finishImageCropping;
@@ -3968,8 +4109,6 @@ declare class App extends React.Component<AppProps, AppState> {
* pointerup handlers manually
*/
private maybeCleanupAfterMissingPointerUp;
handleCanvasPanUsingWheelOrSpaceDrag: (event: React.PointerEvent<HTMLElement> | MouseEvent) => boolean;
private startRightClickPanning;
private updateGestureOnPointerDown;
/**
* Tracks the pointer within the ongoing multi-touch gesture and applies
@@ -4000,8 +4139,10 @@ declare class App extends React.Component<AppProps, AppState> {
}) => NonDeleted<ExcalidrawEmbeddableElement> | undefined;
private newImagePlaceholder;
private handleLinearElementOnPointerDown;
private getCurrentItemRoundness;
private getCurrentItemStrokeWidth;
getCurrentItemRoundness(elementType: "selection" | "rectangle" | "stickynote" | "diamond" | "ellipse" | "iframe" | "embeddable"): {
type: 2 | 3;
} | null;
getCurrentItemStrokeWidth(elementType: ExcalidrawElement["type"]): number;
private createGenericElementOnPointerDown;
private createFrameElementOnPointerDown;
private maybeCacheReferenceSnapPoints;
@@ -4037,19 +4178,29 @@ declare class App extends React.Component<AppProps, AppState> {
private handleAppOnDrop;
loadFileToCanvas: (file: File, fileHandle: FileSystemFileHandle | null) => Promise<void>;
private handleCanvasContextMenu;
/** opens the context menu for the element under the pointer, or the canvas */
openContextMenu: (pointer: {
clientX: number;
clientY: number;
button?: number;
pointerType?: string;
}) => void;
private maybeDragNewGenericElement;
private maybeHandleCrop;
private maybeHandleResize;
private getContextMenuItems;
private handleWheel;
getTextWysiwygSnappedToCenterPosition(x: number, y: number, appState: AppState, container?: ExcalidrawTextContainer | null): {
viewportX: number;
viewportY: number;
elementCenterX: number;
elementCenterY: number;
} | undefined;
private savePointer;
private resetShouldCacheIgnoreZoomDebounced;
savePointer: (x: number, y: number, button: "up" | "down") => void;
resetShouldCacheIgnoreZoomDebounced: {
(): void;
flush(): void;
cancel(): void;
};
private updateDOMRect;
refresh: () => void;
private getCanvasOffsets;
@@ -4201,7 +4352,7 @@ export type BinaryFileData = {
};
export type BinaryFileMetadata = Omit<BinaryFileData, "dataURL">;
export type BinaryFiles = Record<ExcalidrawElement["id"], BinaryFileData>;
export type ToolType = "selection" | "lasso" | "rectangle" | "diamond" | "ellipse" | "arrow" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "magicframe" | "embeddable" | "laser" | "mermaid" | "autoshape" | "bucketfill";
export type ToolType = "selection" | "lasso" | "rectangle" | "diamond" | "ellipse" | "arrow" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "magicframe" | "stickynote" | "embeddable" | "laser" | "mermaid" | "autoshape" | "bucketfill";
export type ElementOrToolType = ExcalidrawElementType | ToolType | "custom";
export type ActiveTool = {
type: ToolType;
@@ -4301,6 +4452,11 @@ export type ObservedElementsAppState = {
activeLockedId: AppState["activeLockedId"];
};
export type BoxSelectionMode = "contain" | "overlap";
/**
* The pointing device the wheel mappings are tuned for. `auto` is reserved
* for detecting it from the wheel events; see `resolveInputDevice`.
*/
export type InputDevice = "auto" | "mouse" | "trackpad";
/**
* A box, in scene coordinates, that pan & zoom are constrained to.
*
@@ -4380,6 +4536,14 @@ export interface AppState {
bindingPreference: "enabled" | "disabled";
/** user preference whether arrow snap to midpoints while binding */
isMidpointSnappingEnabled: boolean;
/**
* user preference for what the wheel does: with a `trackpad` a plain wheel
* pans; with a `mouse` a plain wheel zooms. Ctrl/cmd+wheel (how a pinch is
* delivered) zooms with either device. Shift+wheel pans horizontally;
* ctrl/cmd+shift+wheel pans vertically. `auto` resolves to `trackpad` until
* device detection exists — see `resolveInputDevice`
*/
inputDevice: InputDevice;
/**
* The bindable element the UI highlights for the user when an arrow is
* dragged or otherwise its endpoint being close to said element.
@@ -4435,6 +4599,8 @@ export interface AppState {
exportWithDarkMode: boolean;
exportScale: number;
currentItemStrokeColor: string;
currentItemStickynoteStrokeColor: string;
currentItemStickynoteBackgroundColor: string;
currentItemBackgroundColor: string;
currentItemFillStyle: ExcalidrawElement["fillStyle"];
currentItemStrokeWidth: number | undefined;
@@ -4609,6 +4775,9 @@ export interface AppState {
* even though both drive `currentItemBackgroundColor` (its defaults and
* use case differ — no transparent) */
bucketFill: readonly string[] | null;
/** sticky notes are their own color domain (own defaults, own picks) */
stickyNoteStroke: readonly string[] | null;
stickyNoteBackground: readonly string[] | null;
};
}
export type SearchMatch = {
@@ -4801,6 +4970,20 @@ export type UIConfig = {
scrollBackToContent?: boolean;
};
};
/** Supported visual changes. Geometry, content, bindings and styles are not overridable. */
export type ElementRenderOverride = Readonly<{
/** Absolute render opacity (0–100, clamped). Omitted: use element.opacity. */
opacity?: number;
/** Translation in scene units. Bound labels inherit their container's offset and ignore this field. */
offset?: Readonly<{
x: number;
y: number;
}>;
}>;
/** see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details */
export type ElementRenderOverrides = ReadonlyMap<ExcalidrawElement["id"], ElementRenderOverride>;
/** The translation part of a snapshot: only the entries that carry an offset. */
export type ElementRenderOffsets = ReadonlyMap<ExcalidrawElement["id"], NonNullable<ElementRenderOverride["offset"]>>;
export interface ExcalidrawProps {
className?: string;
/**
@@ -5017,7 +5200,8 @@ export interface ExcalidrawProps {
}) => MaybePromise<void> | AsyncGenerator<OnExportProgress, void>;
}
export type SceneData = {
elements?: ImportedDataState["elements"];
/** Expects normalized elements; restore imported data before updating the scene. */
elements?: readonly ExcalidrawElement[] | null;
appState?: ImportedDataState["appState"];
collaborators?: Map<SocketId, Collaborator>;
captureUpdate?: CaptureUpdateActionType;
@@ -5116,6 +5300,8 @@ export type AppClassProperties = {
arrowText: App["arrowText"];
cursor: App["cursor"];
bucketFill: App["bucketFill"];
toolDrag: App["toolDrag"];
activeResizeHandle: App["activeResizeHandle"];
isToolLocked: App["isToolLocked"];
getEffectiveGridSize: App["getEffectiveGridSize"];
setPlugins: App["setPlugins"];
@@ -5236,6 +5422,22 @@ export interface ExcalidrawImperativeAPI {
getName: InstanceType<typeof App>["getName"];
setViewport: InstanceType<typeof App>["viewport"]["setViewport"];
getViewportOffsets: InstanceType<typeof App>["viewport"]["getOffsets"];
/**
* Atomically replaces all transient visual overrides. Values are copied;
* omitted IDs/fields use document values, except for inherited label offsets.
* null clears the snapshot.
* Repaints without document changes, history entries or onChange events;
* an equivalent snapshot may still repaint (clearing an already clear
* snapshot does not), so submit only when something changed.
* Finite opacity is clamped to 0–100; non-finite values reject the snapshot.
* Unknown/deleted IDs are ignored when rendering. Reset/unmount clears it.
* Bound labels inherit their container's offset; offsets targeting them are
* ignored. Label opacity remains independent. Target frame children explicitly.
* Frame opacity still multiplies child opacity. Decorations follow their owner.
* Exports and interactive geometry (hit tests, selection, editing) use document
* values, including while authoring an animation preview in edit mode.
*/
setElementRenderOverrides: InstanceType<typeof App>["setElementRenderOverrides"];
registerAction: (action: Action) => void;
refresh: InstanceType<typeof App>["refresh"];
setToast: InstanceType<typeof App>["setToast"];
@@ -5501,7 +5703,7 @@ type EmbeddedLink =
))
| null;
declare namespace ExcalidrawLib {
export declare namespace ExcalidrawLib {
type ObsidianCommonHostUIMode = "full" | "compact" | "tray" | "mobile";
type ObsidianCommonHostAdapter = Readonly<{
@@ -5534,7 +5736,6 @@ declare namespace ExcalidrawLib {
type ObsidianExcalidrawHostAdapter = Readonly<{
protocolVersion: 2;
isDoubleTapEraserEnabled: () => boolean;
isRightClickPanEnabled: () => boolean;
getZoomToFitMaxLevel: () => number;
isPenModeCrosshairVisible: () => boolean;
isSingleFingerPanningEnabled: () => boolean;
@@ -5723,6 +5924,7 @@ declare namespace ExcalidrawLib {
} | undefined>;*/
let hashElementsVersion: typeof import("@zsviczian/excalidraw/types/excalidraw").hashElementsVersion;
let convertToExcalidrawElements: typeof import("@zsviczian/excalidraw").convertToExcalidrawElements;
let Excalidraw: typeof import("@zsviczian/excalidraw").Excalidraw;
let MainMenu: typeof import("@zsviczian/excalidraw").MainMenu;
let WelcomeScreen: typeof import("@zsviczian/excalidraw").WelcomeScreen;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -33,7 +33,8 @@ For a reference, follow the implementation pattern used in the "Printable Layout
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on `ea.obsidian`.
- Version checks are distinct: use `ea.verifyMinimumPluginVersion()` for the Excalidraw plugin and `ea.verifyMinAppVersion()` only for the Obsidian application version.
- 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.
@@ -296,9 +297,9 @@ The AI training material is maintained independently from publishing PRs; do not
- Add or update the script under [ea-scripts](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts).
- Add or update the preview image under [images](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images).
- Keep [ea-scripts/index-new.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index-new.md) manually curated; do not automate it.
- Update [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) in the same PR.
- For script updates, refresh the matching entry's `mtime` in [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) so the plugin can detect the newer local version.
- 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
@@ -56,7 +56,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **getCM**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Text Aura.md](scripts/Text%20Aura.md)
- **getCM6**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **getElement**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md)
- **getElements**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [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)
@@ -95,6 +95,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **onLinkClickHook**: [Slideshow.md](scripts/Slideshow.md)
- **onSceneChangeHook**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Shade Master.md](scripts/Shade%20Master.md)
- **openFileInNewOrAdjacentLeaf**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **ownerDocument**: [Slideshow.md](scripts/Slideshow.md)
- **parseText**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **placeholder**: [Slideshow.md](scripts/Slideshow.md)
- **plugin**: [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Rename Image.md](scripts/Rename%20Image.md), [Shade Master.md](scripts/Shade%20Master.md), [Text to Path.md](scripts/Text%20to%20Path.md)
@@ -114,7 +115,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **setViewModeEnabled**: [Slideshow.md](scripts/Slideshow.md)
- **showAIUsageModal**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **showColorPicker**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md)
- **sidepanelTab**: [Icon Library.md](scripts/Icon%20Library.md), [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), [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)
@@ -134,11 +135,12 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **features**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **getAppState**: [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Copy Selected Element Styles to Global.md](scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md), [Custom Zoom.md](scripts/Custom%20Zoom.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Invert colors.md](scripts/Invert%20colors.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **getSceneElements**: [Mindmap format.md](scripts/Mindmap%20format.md), [Slideshow.md](scripts/Slideshow.md)
- **onChange**: [LayerManager.md](scripts/LayerManager.md)
- **setActiveTool**: [Slideshow.md](scripts/Slideshow.md)
- **setToast**: [Slideshow.md](scripts/Slideshow.md)
- **startLineEditor**: [Slideshow.md](scripts/Slideshow.md)
- **updateContainerSize**: [Capture Note.md](scripts/Capture%20Note.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
- **updateScene**: [Custom Zoom.md](scripts/Custom%20Zoom.md), [Palette loader.md](scripts/Palette%20loader.md), [Set Grid.md](scripts/Set%20Grid.md), [Slideshow.md](scripts/Slideshow.md)
- **updateScene**: [Custom Zoom.md](scripts/Custom%20Zoom.md), [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
@@ -267,7 +267,6 @@ export interface ObsidianKeyBlocker {
export interface ObsidianExcalidrawHostAdapter {
readonly protocolVersion: typeof OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION;
isDoubleTapEraserEnabled(): boolean;
isRightClickPanEnabled(): boolean;
getZoomToFitMaxLevel(): number;
isPenModeCrosshairVisible(): boolean;
isSingleFingerPanningEnabled(): boolean;
File diff suppressed because it is too large. Load diff
@@ -83,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
@@ -770,6 +770,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.
@@ -847,8 +871,8 @@ export declare class ExcalidrawAutomate {
* @param {Object} [formatting] - Formatting options for the arrow element.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.startArrowHead] - The start arrowhead type.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.endArrowHead] - The end arrowhead type.
* @param {string} [formatting.startObjectId] - The ID of the start object.
* @param {string} [formatting.endObjectId] - The ID of the end object.
* @param {string} [formatting.startObjectId] - The ID of the start object. When omitted, the arrow start is unbound.
* @param {string} [formatting.endObjectId] - The ID of the end object. When omitted, the arrow end is unbound.
* BindMode Determines whether the arrow remains outside the shape or is allowed to
* go all the way inside the shape up to the exact fixed point.
* @param {"inside" | "orbit"} [formatting.startBindMode] - The binding mode for the start object.
@@ -1516,6 +1540,13 @@ export declare class ExcalidrawAutomate {
* @returns {string | null} The groupId or null if not found.
*/
getCommonGroupForElements(elements: ExcalidrawElement[]): string;
/**
* This is a convenience method to get the release notes for the plugin.
* @returns {Object} The release notes object.
*/
getReleaseNotes(): {
[k: string]: string;
};
/**
* Gets all the elements from elements[] that share one or more groupIds with the specified element.
* @param {ExcalidrawElement} element - The element to check.
@@ -2139,7 +2170,6 @@ export type MarkdownBlockCacheEntry = {
};
export interface ViewSemaphores {
warnAboutLinearElementLinkClick: boolean;
embeddableIsEditingSelf: boolean;
popoutUnload: boolean;
windowMigrating: boolean;
viewloaded: boolean;
@@ -2147,12 +2177,7 @@ export interface ViewSemaphores {
scriptsReady: boolean;
justLoaded: boolean;
preventAutozoom: boolean;
autosaving: boolean;
forceSaving: boolean;
dirty: string | null;
preventReload: boolean;
isEditingText: boolean;
saving: boolean;
hoverSleep: boolean;
wheelTimeout: number | null;
shouldSaveImportedImage: boolean;
@@ -2329,12 +2354,22 @@ export interface SelectableFontOption {
/* lib/types/githubTypes.d.ts */
/* ******************************** */
/**
* Metadata entry describing a file in the remote EA scripts directory listing.
* Metadata entry describing a file in the legacy remote EA scripts directory listing.
*/
export type RemoteDirectoryInfo = {
fname: string;
mtime: number;
};
/**
* File metadata returned by GitHub's repository contents endpoint.
*/
export type GitHubRepositoryContentFile = {
name: string;
path: string;
sha: string;
type: "file" | "dir" | "symlink" | "submodule";
download_url?: string | null;
};
/* ************************************** */
/* lib/types/markdownImageTypes.d.ts */
@@ -2566,6 +2601,32 @@ export interface InputPromptOptions {
draggable?: boolean;
}
/* ************************************* */
/* lib/types/scriptStoreTypes.d.ts */
/* ************************************* */
export type ScriptStoreCategory = {
name: string;
description: string;
};
export type ScriptStoreEntry = {
name: string;
file: string;
installUrl: string;
iconUrl: string;
author: string;
authorUrl: string;
sourceUrl: string;
descriptionHtml: string;
categories: string[];
featuredRank?: number;
};
export type ScriptStoreCatalog = {
version: number;
categories: ScriptStoreCategory[];
scripts: ScriptStoreEntry[];
};
export type ScriptStoreInstallState = "install" | "update" | "up-to-date" | "error";
/* ************************************** */
/* lib/types/sidepanelTabTypes.d.ts */
/* ************************************** */
@@ -2692,26 +2753,6 @@ export interface FrameRenderingOptions {
clip: boolean;
}
export type PaneTarget = "active-pane" | "new-pane" | "popout-window" | "new-tab" | "md-properties";
export interface NestedFileNode {
file: TFile;
/**
* All distinct dependency paths from the root file down to this embedded file.
* Each path is an ordered array of TFile objects starting with the `rootFile` at index 0.
*
* @example
* If Root -> A -> B2.2 and Root -> B -> B2 -> B2.2
* The paths for B2.2 will be:
* [
* [Root, A, B2.2],
* [Root, B, B2, B2.2]
* ]
*
* Usage: To find which top-level embeds to reload if this file changes,
* you can map over `paths` and collect `path[1]`.
*/
paths: TFile[][];
}
export type NestedFileMap = Map<TFile, NestedFileNode>;
/* ************************************** */
/* node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts */
@@ -2876,6 +2917,11 @@ type _ExcalidrawElementBase = Readonly<{
boundElements: readonly BoundElement[] | null;
/** epoch (ms) timestamp of last element update */
updated: number;
/** Client wall-clock creation time in epoch milliseconds; null if unknown.
Preserved for this element's lifetime, including edits and undo/redo,
and excluded from `ElementUpdate` (mutateElement / newElementWith).
Duplicating an element starts a new lifetime. Not an ordering clock. */
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -2887,6 +2933,14 @@ export type ExcalidrawSelectionElement = _ExcalidrawElementBase & {
export type ExcalidrawRectangleElement = _ExcalidrawElementBase & {
type: "rectangle";
};
export type ExcalidrawStickyNoteElement = _ExcalidrawElementBase & Readonly<{
type: "stickynote";
/**
* The height the user set, from which the layout derives `height`: the
* note grows above it to fit its label and never shrinks below it
*/
baseHeight: number;
}>;
export type ExcalidrawDiamondElement = _ExcalidrawElementBase & {
type: "diamond";
};
@@ -2984,14 +3038,14 @@ export type ExcalidrawFrameLikeElement = ExcalidrawFrameElement | ExcalidrawMagi
* These are elements that don't have any additional properties.
*/
export type ExcalidrawGenericElement = ExcalidrawSelectionElement | ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawFlowchartNodeElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawRectanguloidElement = ExcalidrawRectangleElement | ExcalidrawImageElement | ExcalidrawTextElement | ExcalidrawFreeDrawElement | ExcalidrawIframeLikeElement | ExcalidrawFrameLikeElement | ExcalidrawEmbeddableElement | ExcalidrawSelectionElement;
export type ExcalidrawFlowchartNodeElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement;
export type ExcalidrawRectanguloidElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawImageElement | ExcalidrawTextElement | ExcalidrawFreeDrawElement | ExcalidrawIframeLikeElement | ExcalidrawFrameLikeElement | ExcalidrawEmbeddableElement | ExcalidrawSelectionElement;
/**
* ExcalidrawElement should be JSON serializable and (eventually) contain
* no computed data. The list of all ExcalidrawElements should be shareable
* between peers and contain no state local to the peer.
*/
export type ExcalidrawElement = ExcalidrawGenericElement | ExcalidrawTextElement | ExcalidrawLinearElement | ExcalidrawArrowElement | ExcalidrawFreeDrawElement | ExcalidrawImageElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement;
export type ExcalidrawElement = ExcalidrawGenericElement | ExcalidrawStickyNoteElement | ExcalidrawTextElement | ExcalidrawLinearElement | ExcalidrawArrowElement | ExcalidrawFreeDrawElement | ExcalidrawImageElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement;
export type ExcalidrawNonSelectionElement = Exclude<ExcalidrawElement, ExcalidrawSelectionElement>;
export type Ordered<TElement extends ExcalidrawElement> = TElement & {
index: FractionalIndex;
@@ -3005,11 +3059,20 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
type: "text";
fontSize: number;
fontFamily: FontFamilyValues;
/**
* The font size the user picked, from which the layout derives `fontSize`.
* Today only sticky note labels have one: the auto-fit shrinks below it
* and never above it (compare `baseHeight`, which the note grows above).
* `null` for every other text. Read it through `getBaseFontSize` —
* generic binding repair can detach a label without clearing this, so
* the container decides its meaning.
*/
baseFontSize: number | null;
text: string;
rawText: string;
textAlign: TextAlign;
verticalAlign: VerticalAlign;
containerId: ExcalidrawGenericElement["id"] | null;
containerId: ExcalidrawTextContainer["id"] | null;
originalText: string;
/**
* If `true` the width will fit the text. If `false`, the text will
@@ -3033,8 +3096,8 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase & Readonly<{
* */
labelPosition?: number | null;
}>;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
export type ExcalidrawBindableElement = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawTextElement | ExcalidrawImageElement | ExcalidrawIframeElement | ExcalidrawEmbeddableElement | ExcalidrawFrameElement | ExcalidrawMagicFrameElement;
export type ExcalidrawTextContainer = ExcalidrawRectangleElement | ExcalidrawStickyNoteElement | ExcalidrawDiamondElement | ExcalidrawEllipseElement | ExcalidrawArrowElement;
export type ExcalidrawTextElementWithContainer = {
containerId: ExcalidrawTextContainer["id"];
} & ExcalidrawTextElement;
@@ -3213,7 +3276,7 @@ declare class App extends React.Component<AppProps, AppState> {
library: AppClassProperties["library"];
libraryItemsFromStorage: LibraryItems | undefined;
id: string;
private store;
store: Store;
private history;
private shouldRenderAllEmbeddables;
excalidrawContainerValue: {
@@ -3240,14 +3303,24 @@ declare class App extends React.Component<AppProps, AppState> {
private appStateObserver;
onStateChange: OnStateChange;
bucketFill: AppBucketFill;
toolDrag: AppToolDrag;
flowchart: AppFlowchart;
cursor: AppCursor;
arrowText: AppArrowText;
pan: AppPan;
viewport: AppViewport;
wheel: AppWheel;
bindModeHandler: ReturnType<typeof setTimeout> | null;
private textWysiwygSubmitHandler;
hitLinkElement?: NonDeletedExcalidrawElement;
lastPointerDownEvent: React.PointerEvent<HTMLElement> | null;
/**
* the handle of the resize in progress while `state.isResizing` — for UI
* that words itself by handle (a sticky note's corners resize
* proportionally, its edges freely); not app state, so it costs no
* re-render of its own
*/
activeResizeHandle: TransformHandleDirection | null;
lastPointerUpEvent: React.PointerEvent<HTMLElement> | PointerEvent | null;
lastPointerUpIsDoubleClick: boolean;
lastPointerMoveEvent: PointerEvent | null;
@@ -3402,6 +3475,12 @@ declare class App extends React.Component<AppProps, AppState> {
missingPointerEventCleanupEmitter: Emitter<[event: PointerEvent | null]>;
onRemoveEventListenersEmitter: Emitter<[]>;
api: ExcalidrawImperativeAPI;
private elementRenderOverrides;
/** offsets of `elementRenderOverrides`; keeps its identity while they don't change */
private elementRenderOffsets;
private renderOverridesUpdatePending;
private getRenderOverrideConfig;
private getElementRenderState;
private createExcalidrawAPI;
constructor(props: AppProps);
/**
@@ -3532,7 +3611,6 @@ declare class App extends React.Component<AppProps, AppState> {
private onBlur;
private onUnload;
private disableEvent;
private preventBrowserZoomWheel;
private handleNavigationModeKeyDown;
/**
* PageUp/PageDown scroll the canvas by a page — vertically, or
@@ -3670,6 +3748,10 @@ declare class App extends React.Component<AppProps, AppState> {
captureUpdate?: SceneData["captureUpdate"];
forceFlushSync?: boolean;
}) => void;
/**
* see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details
*/
setElementRenderOverrides: (overrides: ElementRenderOverrides | null) => void;
applyDeltas: (deltas: StoreDelta[], options?: ApplyToOptions) => [SceneElementsMap, AppState, boolean];
mutateElement: <TElement extends Mutable<ExcalidrawElement>>(element: TElement, updates: ElementUpdate<TElement>, informMutation?: boolean) => TElement;
triggerRender: (
@@ -3765,6 +3847,7 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3800,6 +3883,44 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
customData?: Record<string, any>;
}> & Readonly<{
type: "stickynote";
baseHeight: number;
}> & {
isDeleted: false;
}) | (Readonly<{
id: string;
x: number;
y: number;
strokeColor: string;
backgroundColor: string;
fillStyle: import("@excalidraw/element/types").FillStyle;
strokeWidth: number;
strokeStyle: import("@excalidraw/element/types").StrokeStyle;
roundness: null | {
type: import("@excalidraw/element/types").RoundnessType;
value?: number;
};
roughness: number;
opacity: number;
width: number;
height: number;
angle: Radians;
seed: number;
version: number;
versionNonce: number;
index: import("@excalidraw/element/types").FractionalIndex | null;
isDeleted: boolean;
groupIds: readonly import("@excalidraw/element/types").GroupId[];
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3835,6 +3956,7 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3870,6 +3992,7 @@ declare class App extends React.Component<AppProps, AppState> {
frameId: string | null;
boundElements: readonly import("@excalidraw/element/types").BoundElement[] | null;
updated: number;
created: number | null;
link: string | null;
hasTextLink?: boolean;
locked: boolean;
@@ -3899,7 +4022,25 @@ declare class App extends React.Component<AppProps, AppState> {
* so the whole create-and-type lands in a single entry.
*/
private isEditingTextContent;
private startTextEditing;
startTextEditing: ({ sceneX, sceneY, insertAtParentCenter, container, autoEdit, initialCaretSceneCoords, arrowEndpoint, }: {
/** X position to insert text at */
sceneX: number;
/** Y position to insert text at */
sceneY: number;
/** whether to attempt to insert at element center if applicable */
insertAtParentCenter?: boolean;
container?: ExcalidrawTextContainer | null;
autoEdit?: boolean;
initialCaretSceneCoords?: {
x: number;
y: number;
};
/**
* creates the text as a label for this arrow endpoint: the binding then
* dictates the text's position and alignment, overriding (sceneX, sceneY)
*/
arrowEndpoint?: ArrowEndpoint | null;
}) => void;
private debounceDoubleClickTimestamp;
private startImageCropping;
private finishImageCropping;
@@ -3968,8 +4109,6 @@ declare class App extends React.Component<AppProps, AppState> {
* pointerup handlers manually
*/
private maybeCleanupAfterMissingPointerUp;
handleCanvasPanUsingWheelOrSpaceDrag: (event: React.PointerEvent<HTMLElement> | MouseEvent) => boolean;
private startRightClickPanning;
private updateGestureOnPointerDown;
/**
* Tracks the pointer within the ongoing multi-touch gesture and applies
@@ -4000,8 +4139,10 @@ declare class App extends React.Component<AppProps, AppState> {
}) => NonDeleted<ExcalidrawEmbeddableElement> | undefined;
private newImagePlaceholder;
private handleLinearElementOnPointerDown;
private getCurrentItemRoundness;
private getCurrentItemStrokeWidth;
getCurrentItemRoundness(elementType: "selection" | "rectangle" | "stickynote" | "diamond" | "ellipse" | "iframe" | "embeddable"): {
type: 2 | 3;
} | null;
getCurrentItemStrokeWidth(elementType: ExcalidrawElement["type"]): number;
private createGenericElementOnPointerDown;
private createFrameElementOnPointerDown;
private maybeCacheReferenceSnapPoints;
@@ -4037,19 +4178,29 @@ declare class App extends React.Component<AppProps, AppState> {
private handleAppOnDrop;
loadFileToCanvas: (file: File, fileHandle: FileSystemFileHandle | null) => Promise<void>;
private handleCanvasContextMenu;
/** opens the context menu for the element under the pointer, or the canvas */
openContextMenu: (pointer: {
clientX: number;
clientY: number;
button?: number;
pointerType?: string;
}) => void;
private maybeDragNewGenericElement;
private maybeHandleCrop;
private maybeHandleResize;
private getContextMenuItems;
private handleWheel;
getTextWysiwygSnappedToCenterPosition(x: number, y: number, appState: AppState, container?: ExcalidrawTextContainer | null): {
viewportX: number;
viewportY: number;
elementCenterX: number;
elementCenterY: number;
} | undefined;
private savePointer;
private resetShouldCacheIgnoreZoomDebounced;
savePointer: (x: number, y: number, button: "up" | "down") => void;
resetShouldCacheIgnoreZoomDebounced: {
(): void;
flush(): void;
cancel(): void;
};
private updateDOMRect;
refresh: () => void;
private getCanvasOffsets;
@@ -4201,7 +4352,7 @@ export type BinaryFileData = {
};
export type BinaryFileMetadata = Omit<BinaryFileData, "dataURL">;
export type BinaryFiles = Record<ExcalidrawElement["id"], BinaryFileData>;
export type ToolType = "selection" | "lasso" | "rectangle" | "diamond" | "ellipse" | "arrow" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "magicframe" | "embeddable" | "laser" | "mermaid" | "autoshape" | "bucketfill";
export type ToolType = "selection" | "lasso" | "rectangle" | "diamond" | "ellipse" | "arrow" | "line" | "freedraw" | "text" | "image" | "eraser" | "hand" | "frame" | "magicframe" | "stickynote" | "embeddable" | "laser" | "mermaid" | "autoshape" | "bucketfill";
export type ElementOrToolType = ExcalidrawElementType | ToolType | "custom";
export type ActiveTool = {
type: ToolType;
@@ -4301,6 +4452,11 @@ export type ObservedElementsAppState = {
activeLockedId: AppState["activeLockedId"];
};
export type BoxSelectionMode = "contain" | "overlap";
/**
* The pointing device the wheel mappings are tuned for. `auto` is reserved
* for detecting it from the wheel events; see `resolveInputDevice`.
*/
export type InputDevice = "auto" | "mouse" | "trackpad";
/**
* A box, in scene coordinates, that pan & zoom are constrained to.
*
@@ -4380,6 +4536,14 @@ export interface AppState {
bindingPreference: "enabled" | "disabled";
/** user preference whether arrow snap to midpoints while binding */
isMidpointSnappingEnabled: boolean;
/**
* user preference for what the wheel does: with a `trackpad` a plain wheel
* pans; with a `mouse` a plain wheel zooms. Ctrl/cmd+wheel (how a pinch is
* delivered) zooms with either device. Shift+wheel pans horizontally;
* ctrl/cmd+shift+wheel pans vertically. `auto` resolves to `trackpad` until
* device detection exists — see `resolveInputDevice`
*/
inputDevice: InputDevice;
/**
* The bindable element the UI highlights for the user when an arrow is
* dragged or otherwise its endpoint being close to said element.
@@ -4435,6 +4599,8 @@ export interface AppState {
exportWithDarkMode: boolean;
exportScale: number;
currentItemStrokeColor: string;
currentItemStickynoteStrokeColor: string;
currentItemStickynoteBackgroundColor: string;
currentItemBackgroundColor: string;
currentItemFillStyle: ExcalidrawElement["fillStyle"];
currentItemStrokeWidth: number | undefined;
@@ -4609,6 +4775,9 @@ export interface AppState {
* even though both drive `currentItemBackgroundColor` (its defaults and
* use case differ — no transparent) */
bucketFill: readonly string[] | null;
/** sticky notes are their own color domain (own defaults, own picks) */
stickyNoteStroke: readonly string[] | null;
stickyNoteBackground: readonly string[] | null;
};
}
export type SearchMatch = {
@@ -4801,6 +4970,20 @@ export type UIConfig = {
scrollBackToContent?: boolean;
};
};
/** Supported visual changes. Geometry, content, bindings and styles are not overridable. */
export type ElementRenderOverride = Readonly<{
/** Absolute render opacity (0–100, clamped). Omitted: use element.opacity. */
opacity?: number;
/** Translation in scene units. Bound labels inherit their container's offset and ignore this field. */
offset?: Readonly<{
x: number;
y: number;
}>;
}>;
/** see {@link ExcalidrawImperativeAPI.setElementRenderOverrides} for details */
export type ElementRenderOverrides = ReadonlyMap<ExcalidrawElement["id"], ElementRenderOverride>;
/** The translation part of a snapshot: only the entries that carry an offset. */
export type ElementRenderOffsets = ReadonlyMap<ExcalidrawElement["id"], NonNullable<ElementRenderOverride["offset"]>>;
export interface ExcalidrawProps {
className?: string;
/**
@@ -5017,7 +5200,8 @@ export interface ExcalidrawProps {
}) => MaybePromise<void> | AsyncGenerator<OnExportProgress, void>;
}
export type SceneData = {
elements?: ImportedDataState["elements"];
/** Expects normalized elements; restore imported data before updating the scene. */
elements?: readonly ExcalidrawElement[] | null;
appState?: ImportedDataState["appState"];
collaborators?: Map<SocketId, Collaborator>;
captureUpdate?: CaptureUpdateActionType;
@@ -5116,6 +5300,8 @@ export type AppClassProperties = {
arrowText: App["arrowText"];
cursor: App["cursor"];
bucketFill: App["bucketFill"];
toolDrag: App["toolDrag"];
activeResizeHandle: App["activeResizeHandle"];
isToolLocked: App["isToolLocked"];
getEffectiveGridSize: App["getEffectiveGridSize"];
setPlugins: App["setPlugins"];
@@ -5236,6 +5422,22 @@ export interface ExcalidrawImperativeAPI {
getName: InstanceType<typeof App>["getName"];
setViewport: InstanceType<typeof App>["viewport"]["setViewport"];
getViewportOffsets: InstanceType<typeof App>["viewport"]["getOffsets"];
/**
* Atomically replaces all transient visual overrides. Values are copied;
* omitted IDs/fields use document values, except for inherited label offsets.
* null clears the snapshot.
* Repaints without document changes, history entries or onChange events;
* an equivalent snapshot may still repaint (clearing an already clear
* snapshot does not), so submit only when something changed.
* Finite opacity is clamped to 0–100; non-finite values reject the snapshot.
* Unknown/deleted IDs are ignored when rendering. Reset/unmount clears it.
* Bound labels inherit their container's offset; offsets targeting them are
* ignored. Label opacity remains independent. Target frame children explicitly.
* Frame opacity still multiplies child opacity. Decorations follow their owner.
* Exports and interactive geometry (hit tests, selection, editing) use document
* values, including while authoring an animation preview in edit mode.
*/
setElementRenderOverrides: InstanceType<typeof App>["setElementRenderOverrides"];
registerAction: (action: Action) => void;
refresh: InstanceType<typeof App>["refresh"];
setToast: InstanceType<typeof App>["setToast"];
@@ -5501,7 +5703,7 @@ type EmbeddedLink =
))
| null;
declare namespace ExcalidrawLib {
export declare namespace ExcalidrawLib {
type ObsidianCommonHostUIMode = "full" | "compact" | "tray" | "mobile";
type ObsidianCommonHostAdapter = Readonly<{
@@ -5534,7 +5736,6 @@ declare namespace ExcalidrawLib {
type ObsidianExcalidrawHostAdapter = Readonly<{
protocolVersion: 2;
isDoubleTapEraserEnabled: () => boolean;
isRightClickPanEnabled: () => boolean;
getZoomToFitMaxLevel: () => number;
isPenModeCrosshairVisible: () => boolean;
isSingleFingerPanningEnabled: () => boolean;
@@ -5723,6 +5924,7 @@ declare namespace ExcalidrawLib {
} | undefined>;*/
let hashElementsVersion: typeof import("@zsviczian/excalidraw/types/excalidraw").hashElementsVersion;
let convertToExcalidrawElements: typeof import("@zsviczian/excalidraw").convertToExcalidrawElements;
let Excalidraw: typeof import("@zsviczian/excalidraw").Excalidraw;
let MainMenu: typeof import("@zsviczian/excalidraw").MainMenu;
let WelcomeScreen: typeof import("@zsviczian/excalidraw").WelcomeScreen;
+169
View File
@@ -0,0 +1,169 @@
# Obsidian runtime testing on macOS and Windows
This desktop lane builds the real plugin, deploys its exact artifacts to the named
`excalidraw-test` vault, opens a disposable drawing, and checks that the Excalidraw
API and editor mount in the main application document. It supplements source
tests and change-specific manual checks.
## Prepare the test vault
1. Look for an existing vault named `excalidraw-test` in Obsidian's vault switcher
or registry (`~/Library/Application Support/obsidian/obsidian.json` on macOS;
`%APPDATA%\obsidian\obsidian.json` on Windows). Confirm its absolute path.
2. If it is missing, ask the user to create it and install and enable Excalidraw
through **Settings → Community plugins**. A fresh empty vault is sufficient
for this smoke. Agents need consent to create or download a replacement vault.
3. Open the vault in Obsidian. For a downloaded/copied vault, complete any
first-open trust prompt, then close and reopen that vault. Finish plugin
onboarding before automated testing.
4. Use an Obsidian installer with CLI support and enable **Settings → General →
Command line interface**. Follow its registration prompt; see the official
[CLI installation and troubleshooting guide](https://obsidian.md/help/cli).
5. Keep Obsidian running and select the test vault's main window. Ensure its
Excalidraw drawing template does not open a chooser. Avoid simultaneous edits
or another CLI runner in that vault during testing.
6. Use Node.js 22 or newer and install this repository's dependencies with
`npm install`. Check `node --version` in the same terminal used for testing.
The runner requires all three environment variables below. It accepts only the
name `excalidraw-test`, checks canonical vault and configuration paths against the
running app, requires the initial enabled Community plugin installation, and
rejects symlinked plugin directories/artifacts. There is no default-vault fallback.
Use the actual configuration directory if it differs from `.obsidian`.
## Run on Windows
From this plugin checkout in PowerShell, substitute your actual vault path:
```powershell
$env:EXCALIDRAW_TEST_VAULT_NAME = 'excalidraw-test'
$env:EXCALIDRAW_TEST_VAULT_PATH = 'C:\Obsidian\excalidraw-test'
$env:EXCALIDRAW_TEST_CONFIG_DIR = 'C:\Obsidian\excalidraw-test\.obsidian'
npm.cmd run test:obsidian:runner
npm.cmd run verify:obsidian:plugin
```
The launcher discovers `Obsidian.com` under `%LOCALAPPDATA%\Obsidian`,
`%PROGRAMFILES%\Obsidian`, or `%PROGRAMFILES(X86)%\Obsidian`, then falls back to
`obsidian` on PATH. For another installation, set an executable path:
```powershell
$env:EXCALIDRAW_OBSIDIAN_CLI = 'C:\Program Files\Obsidian\Obsidian.com'
```
Use the console launcher `.com` to capture output. The driver passes argument
arrays directly to native processes. It launches npm/Yarn JavaScript entries
through the current Node binary, avoiding `.cmd` shims and shell quoting.
PowerShell environment assignments apply to the current terminal session. Use
`npm.cmd` in PowerShell if its execution policy blocks `npm.ps1`; no global policy
change is necessary. The same applies to `npm.cmd install` and the fork lane's
`npm.cmd run verify:obsidian`.
For additional eval probes, import `spawnNativeSync` from
`scripts/testing/host/processTools.mjs` in a Node script and pass
`['vault=excalidraw-test', 'eval', 'code=' + code]`. Windows PowerShell can alter
embedded native quotes, and large/multiline inline evals can corrupt Obsidian's
console IPC JSON. The helper moves those payloads to an owned UTF-8 script in the
system temporary directory, sends a short file-reading eval, and removes the
directory after success or failure. This local file bridge exists only in test
tooling; no production plugin feature reads external test scripts.
## Run on macOS
From this plugin checkout in a shell, substitute your actual vault path:
```bash
export EXCALIDRAW_TEST_VAULT_NAME=excalidraw-test
export EXCALIDRAW_TEST_VAULT_PATH="$HOME/Obsidian/excalidraw-test"
export EXCALIDRAW_TEST_CONFIG_DIR="$EXCALIDRAW_TEST_VAULT_PATH/.obsidian"
npm run test:obsidian:runner
npm run verify:obsidian:plugin
```
The launcher discovers `/Applications/Obsidian.app/Contents/MacOS/obsidian-cli`,
then the application binary `/Applications/Obsidian.app/Contents/MacOS/Obsidian`,
then `obsidian` on PATH. Set `EXCALIDRAW_OBSIDIAN_CLI` to an executable path for a
nonstandard installation. Do not include command arguments in the override.
macOS evals use native argument arrays without the Windows temporary-file bridge.
## Choose the build
| Command | Component input | Prerequisites |
| --- | --- | --- |
| `npm run test:obsidian:runner` | Fake host fixtures | Node; no Obsidian required |
| `npm run verify:obsidian:plugin` | Installed `@zsviczian/excalidraw` artifacts | Plugin dependencies and prepared test vault |
| `npm run verify:obsidian` | Fresh sibling fork build | Both repositories' dependencies, Yarn, prepared test vault |
The plugin-only lane checks the installed component version against the exact
declared dependency, hashes its four Obsidian artifacts, and runs the real
production `npm run build`. It does not require the sibling fork checkout. If you
previously copied unpublished fork artifacts into `node_modules`, this lane uses
those bytes; version equality alone does not prove published provenance. Run
`npm install` to restore the published dependency before a release smoke.
For a fork integration check, use `npm run verify:obsidian`. It runs
`yarn build:obsidian` in `../excalidraw/packages/excalidraw`, copies only the four
generated Obsidian JavaScript/CSS files into the ignored installed package,
checks their hashes, then builds the plugin. Set `EXCALIDRAW_FORK_ROOT` to an
absolute checkout path when the fork is elsewhere. This temporary handoff does
not change dependencies or lockfiles and remains in `node_modules` afterward.
Windows resolves Yarn's JavaScript entry from the Node installation, the user's
global npm installation, or Corepack. For a different installation, set
`EXCALIDRAW_YARN_CLI` to the absolute `yarn.js` path. Use the fork's declared Yarn
version. npm must be discoverable through its `npm_execpath` or a standard Node
installation; launching through `npm run` supplies that entry automatically.
## Assertions, deployment and cleanup
After CLI capability and target checks, the runner:
1. Builds the selected inputs and validates the plugin manifest ID.
2. Disables Excalidraw in the test vault, copies `dist/main.js`, `styles.css` and
`manifest.json`, checks deployed SHA-256 hashes, and enables the plugin.
3. Waits for the live plugin instance and stable drawing command registration.
4. Creates a UUID-named `__excalidraw_cli_smoke_*` drawing in the vault root through
the plugin, opens it in a new tab, and waits for an API and editor wrapper with
the correct owning document.
5. Rejects captured JavaScript errors, closes/deletes its own drawing, removes its
temporary controller, and writes `report.json`. Cleanup failure fails the run.
Every CLI call explicitly starts with `vault=excalidraw-test`. A CLI `Error:`
payload is failure even when the process exits zero. Internal plugin access via
CLI eval belongs only in these host scripts, never in production modules.
Deployment replaces the test vault's installed plugin build and leaves it enabled;
it does not restore the Community release afterward. The runner does not overwrite
`data.json`, existing notes, or other plugins. Normal plugin startup/drawing
creation may persist its own settings. Opening the temporary tab can change focus
and workspace history; use a disposable test vault. It clears the test vault's
developer error buffer to attribute errors to this run.
The printed report path is in a unique temporary directory unless you set
`EXCALIDRAW_TEST_REPORT_DIR`. Reports include source revisions/dirty flags, build
mode, component version, Node/platform/Obsidian versions, component and deployed
plugin hashes, bundle size, scenarios, and cleanup. Inspect both `status` and
`cleanup`; keep reports outside the checkout and review local paths before sharing.
## Troubleshooting and further coverage
If CLI access is disabled, enable it in Obsidian first. If the app is running but
the CLI cannot reach it, check host permissions: a sandbox may lack access to the
macOS CLI socket or Windows IPC. Retry with authorized host access instead of
opening a second instance or choosing another vault.
If a call times out, inspect pending trust, onboarding, or native error dialogs.
On Windows, malformed inline eval transport can produce a main-process JSON
parse error dialog that blocks later commands. Dismiss it and retry through the
Node helper. If necessary, ask the user to save work and restart Obsidian; do not
force-close the application while other vaults are open. After interrupted cleanup,
review the report/controller's exact drawing path before removing leftovers; never
delete notes by prefix alone.
This smoke covers one newly created main-window drawing. It does not validate
saved scenes, clipboard, text editing, fonts/images, export, custom pens, popout
migration, offline assets, or physical mobile touch. For affected features, follow
the fork's [native validation procedure](https://github.com/zsviczian/excalidraw/blob/master/dev-docs/Obsidian/OBSIDIAN_RUNTIME_TESTING.md)
and its V03–V11 gates (also available in the sibling checkout). Record macOS and
Windows live results separately, along with artifact identity and unavailable
gates. A test of platform argument construction is not a live macOS smoke.
+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)
+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.
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 260 KiB

+2 -2
View File
@@ -1,11 +1,11 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.28.0-beta.1",
"version": "2.28.1",
"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.27.3",
"version": "2.28.1",
"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.
+4 -4
View File
@@ -13,7 +13,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.137",
"@zsviczian/excalidraw": "0.18.140",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -5255,9 +5255,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.137",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.137.tgz",
"integrity": "sha512-Qua9UpBVxU/jOG3vAj/9hO+ZGejvtjk6grvsdt6z1j7c5rphu5IHZtceTdC11wm2wP+iTuMYTxBAvjvDOE0NIw==",
"version": "0.18.140",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.140.tgz",
"integrity": "sha512-DXdxSFVkyVXYBDIlq63IfoegKRZYp71ECSPErSZASxcssKyKOcbiDjI/EjO4nnsvhampnr8mrlLPBjsQyoRTKQ==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
+10 -5
View File
@@ -9,7 +9,10 @@
],
"scripts": {
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs",
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
"test:obsidian:runner": "node --test scripts/testing/host/runner.test.mjs scripts/testing/host/processTools.test.mjs",
"verify:obsidian": "node scripts/testing/host/verify.mjs",
"verify:obsidian:plugin": "node scripts/testing/host/verify.mjs --plugin-only",
"lib": "cross-env NODE_ENV=lib rollup --config rollup.config.mjs",
"code": "eslint --max-warnings=0 --ext .ts,.tsx ./src",
"code:fix": "eslint --max-warnings=0 --ext .ts,.tsx ./src --fix",
@@ -21,8 +24,10 @@
"mindmap": "node scripts/deploy-mindmap-builder.mjs",
"lint": "eslint .",
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx}\" && eslint --max-warnings=0 --ext .ts,.tsx ./src --fix",
"repo:export": "bash scripts/generate-repository-zip.sh",
"repo:update": "rsync -av --progress ~/Downloads/update/ ./"
"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": "",
@@ -32,7 +37,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.137",
"@zsviczian/excalidraw": "0.18.140",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -109,4 +114,4 @@
"node": ">=22.0.0",
"npm": ">=10.0.0"
}
}
}
+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.`,
);
@@ -0,0 +1,220 @@
// This component imports types that are unavailable to this Node process, so
// these checks inspect its TypeScript syntax. Node identity uses assert.ok because
// serializing a parent-linked AST can exhaust the heap.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import ts from "typescript";
const source = await readFile(
new URL("../src/view/components/CustomEmbeddable.tsx", import.meta.url),
"utf8",
);
const file = ts.createSourceFile(
"CustomEmbeddable.tsx",
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
const log = (message) => process.stdout.write(`${message}\n`);
const collect = (match) => {
const found = [];
const visit = (node) => {
if (match(node)) {
found.push(node);
}
ts.forEachChild(node, visit);
};
visit(file);
return found;
};
const enclosingFunction = (node) => {
for (let parent = node.parent; parent; parent = parent.parent) {
if (ts.isFunctionLike(parent)) {
return parent;
}
}
return undefined;
};
const enclosingStatement = (node) => {
let current = node;
while (current.parent && !ts.isStatement(current)) {
current = current.parent;
}
return current;
};
assert.equal(
collect(
(node) =>
ts.isImportDeclaration(node) &&
node.moduleSpecifier.text === "src/utils/embeddableMountPlan",
).length,
1,
"the component has one embeddable mount-plan import",
);
const dispatches = collect(
(node) =>
ts.isCallExpression(node) &&
ts.isIdentifier(node.expression) &&
node.expression.text === "mountEmbeddableHost",
);
assert.equal(
dispatches.length,
1,
"the component has one mountEmbeddableHost call",
);
const [dispatch] = dispatches;
const effect = enclosingFunction(dispatch);
assert.ok(effect, "mountEmbeddableHost is called by a function");
const [options] = dispatch.arguments;
assert.ok(
options && ts.isObjectLiteralExpression(options),
"mountEmbeddableHost receives an options object",
);
const option = (name) =>
options.properties.find(
(property) =>
property.name &&
ts.isIdentifier(property.name) &&
property.name.text === name,
);
for (const name of [
"subpath",
"fileExtension",
"getHost",
"isCancelled",
"createCanvasNode",
"createWorkspaceLeaf",
]) {
assert.ok(option(name), `the options object has ${name}`);
}
assert.ok(
ts.isShorthandPropertyAssignment(option("subpath")),
"subpath is a shorthand option",
);
assert.equal(
option("fileExtension").initializer?.getText(file),
"file.extension",
"fileExtension is file.extension",
);
const getHost = option("getHost");
assert.ok(
ts.isPropertyAssignment(getHost) &&
ts.isArrowFunction(getHost.initializer) &&
getHost.initializer.body.getText(file) === "view.canvasNodeFactory",
"getHost returns view.canvasNodeFactory",
);
const statement = enclosingStatement(dispatch);
assert.ok(
ts.isExpressionStatement(statement),
"mountEmbeddableHost is an expression statement",
);
assert.ok(
statement.parent === effect.body,
"the expression statement belongs to the function body",
);
const handledDispatch = ts.isVoidExpression(statement.expression)
? statement.expression.expression
: statement.expression;
assert.ok(
ts.isCallExpression(handledDispatch) &&
ts.isPropertyAccessExpression(handledDispatch.expression) &&
handledDispatch.expression.expression === dispatch &&
handledDispatch.expression.name.text === "catch",
"the mount dispatch handles rejected promises",
);
assert.equal(
collect(
(node) =>
ts.isIdentifier(node) &&
node.text === "canvasNodeFactory" &&
enclosingFunction(node) === effect,
).length,
0,
"the caller body has no canvasNodeFactory identifier",
);
for (const name of ["createNode", "mountWorkspaceLeaf"]) {
assert.equal(
collect(
(node) =>
ts.isCallExpression(node) &&
ts.isIdentifier(node.expression) &&
node.expression.text === name &&
enclosingFunction(node) === effect,
).length,
0,
`the caller body has no direct ${name} call`,
);
}
const isCancelled = option("isCancelled");
assert.ok(
ts.isPropertyAssignment(isCancelled) &&
ts.isArrowFunction(isCancelled.initializer),
"isCancelled is an arrow function",
);
let firstOperand = isCancelled.initializer.body;
while (
ts.isBinaryExpression(firstOperand) &&
firstOperand.operatorToken.kind === ts.SyntaxKind.BarBarToken
) {
firstOperand = firstOperand.left;
}
assert.ok(
ts.isIdentifier(firstOperand) && firstOperand.text === "effectCancelled",
"the cancellation expression starts with effectCancelled",
);
const declarations = collect(
(node) =>
ts.isVariableDeclaration(node) &&
ts.isIdentifier(node.name) &&
node.name.text === "effectCancelled",
);
assert.equal(
declarations.length,
1,
"effectCancelled has one declaration",
);
assert.ok(
enclosingFunction(declarations[0]) === effect,
"effectCancelled is declared by the calling function",
);
const cleanup = effect.body.statements.find(ts.isReturnStatement);
assert.ok(
cleanup && ts.isArrowFunction(cleanup.expression),
"the calling function returns an arrow function",
);
const [firstCleanupStatement] = cleanup.expression.body.statements;
assert.equal(
firstCleanupStatement.getText(file),
"effectCancelled = true;",
"the cleanup starts with effectCancelled = true;",
);
assert.equal(
collect(
(node) =>
ts.isVariableDeclaration(node) &&
ts.isIdentifier(node.name) &&
node.name.text === "mountWorkspaceLeaf" &&
enclosingFunction(node) === effect,
).length,
1,
"mountWorkspaceLeaf has one declaration in the calling function",
);
log("embeddable mount call site checks passed");
+730
View File
@@ -0,0 +1,730 @@
// Exercises host selection and CanvasNodeFactory lifecycle behavior. The factory
// dependencies are aliased to the local stub module for this Node process.
import assert from "node:assert/strict";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createJiti } from "jiti";
const here = path.dirname(fileURLToPath(import.meta.url));
const stubs = path.join(here, "check-embeddable-mount-plan.stubs.mjs");
const jiti = createJiti(import.meta.url, {
alias: { obsidian: stubs, "../../utils/obsidianUtils": stubs },
});
//The factory reads this global to tell a main-window split from a popout one.
globalThis.mainDocument = {};
const {
CANVAS_NODE_HOST_WAIT_TIMEOUT_MS,
awaitCanvasNodeHost,
mountEmbeddableHost,
requiresCanvasNodeHost,
} = await jiti.import("../src/utils/embeddableMountPlan.ts");
const { CanvasNodeFactory } = await jiti.import(
"../src/view/managers/CanvasNodeFactory.ts",
);
const log = (message) => process.stdout.write(`${message}\n`);
//The module defaults its wait to Obsidian's `sleep` global, absent here.
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
//The wait's poll delay, with hooks keyed by poll number. A hook runs once that
//poll has been entered, so an event lands at a known point of the wait, and a
//wait that outlives every hook fails the script.
const polling = (hooks = {}, limit = 50) => {
const polls = {
count: 0,
delay: (ms) => {
polls.count += 1;
if (polls.count > limit) {
return Promise.reject(new Error(`still polling after ${limit} polls`));
}
hooks[polls.count]?.();
return delay(ms);
},
};
return polls;
};
//Cancellation is live at setup, cancelled on the cleanup read, then live again
//when the refs are populated.
const cancelledOnRead = (read) => {
let reads = 0;
return () => {
reads += 1;
return reads === read;
};
};
const hostReadyOnRead = (read) => {
const host = {
reads: 0,
isInitialized: () => {
host.reads += 1;
return host.reads >= read;
},
};
return host;
};
const unreadyHost = { isInitialized: () => false };
//A host that reports its lifecycle, as `CanvasNodeFactory` does.
const lifecycleHost = () => {
let settle;
const host = {
initialized: false,
isInitialized: () => host.initialized,
whenInitialized: new Promise((resolve) => {
settle = resolve;
}),
ready: () => {
host.initialized = true;
settle(true);
},
//initialize() threw, or destroy() ran: it will never host a node.
givesUp: () => {
host.initialized = false;
settle(false);
},
};
return host;
};
const neverSettlingHost = () => ({
isInitialized: () => false,
whenInitialized: new Promise(() => {}),
});
const mountRecorder = (overrides = {}) => {
const calls = { canvasNodes: 0, workspaceLeaves: 0 };
return {
calls,
options: {
subpath: "#Section",
fileExtension: "md",
getHost: () => ({ isInitialized: () => true }),
createCanvasNode: () => {
calls.canvasNodes += 1;
},
createWorkspaceLeaf: () => {
calls.workspaceLeaves += 1;
},
timeoutMs: 200,
intervalMs: 1,
delay,
...overrides,
},
};
};
//Minimal `ExcalidrawView` stand-in: the members `initialize()` reaches.
const fakeView = ({ loadMs = 0, loadThrows = false } = {}) => ({
ownerDocument: {},
app: {
internalPlugins: {
plugins: {
canvas: {
_loaded: false,
load: async () => {
await delay(loadMs);
if (loadThrows) {
throw new Error("canvas plugin failed to load");
}
},
views: { canvas: () => ({ canvas: { createFileNode: () => ({}) } }) },
},
},
},
workspace: {
rootSplit: {},
floatingSplit: {},
},
},
});
//Resolves to the promise's value, or to `PENDING` if it has not settled.
const PENDING = Symbol("pending");
const settleWithin = (promise, ms = 50) =>
Promise.race([promise, delay(ms).then(() => PENDING)]);
//Blocks run independently.
const blocks = [];
const block = (name, fn) => blocks.push([name, fn]);
//--------------------------------------------------------------------------------
//requiresCanvasNodeHost: which embeds can only be rendered by a Canvas node
//--------------------------------------------------------------------------------
block("only a markdown subpath embed requires a canvas node host", () => {
for (const [subpath, extension, required] of [
["#Section", "md", true],
["#Section", "MD", true],
["#^blockid", "md", true],
["#", "md", true],
[null, "md", false],
["", "md", false],
[undefined, "md", false],
["#page=2", "pdf", false],
["#Section", undefined, false],
["#Section", null, false],
["#Section", "", false],
]) {
assert.equal(
requiresCanvasNodeHost(subpath, extension),
required,
`subpath ${JSON.stringify(subpath)} on ${JSON.stringify(extension)}`,
);
}
});
//--------------------------------------------------------------------------------
//awaitCanvasNodeHost on a host that reports no lifecycle: the bounded poll
//--------------------------------------------------------------------------------
block(
"a factory is accepted on the read that finds it initialized",
async () => {
for (const readyOnRead of [1, 4]) {
const host = hostReadyOnRead(readyOnRead);
assert.equal(
await awaitCanvasNodeHost(
() => host,
() => false,
1000,
1,
delay,
),
true,
);
assert.equal(host.reads, readyOnRead);
}
},
);
block(
"a factory is re-read on every poll and never dereferenced blindly",
async () => {
for (const [name, sequence, timeoutMs, expected] of [
["absent, then present", [null, null, hostReadyOnRead(1)], 1000, true],
["never present", [null], 20, false],
["present, then torn down", [unreadyHost, unreadyHost, null], 30, false],
["present, never initialized", [unreadyHost], 20, false],
]) {
let reads = 0;
const getHost = () => {
reads += 1;
return sequence[Math.min(reads, sequence.length) - 1];
};
assert.equal(
await awaitCanvasNodeHost(getHost, () => false, timeoutMs, 1, delay),
expected,
name,
);
}
},
);
block("an unmounted embeddable stops the wait", async () => {
const host = hostReadyOnRead(1);
assert.equal(
await awaitCanvasNodeHost(
() => host,
() => true,
1000,
1,
delay,
),
false,
"already unmounted",
);
assert.equal(host.reads, 0, "already unmounted: the factory is never read");
assert.equal(
await awaitCanvasNodeHost(
() => unreadyHost,
cancelledOnRead(3),
5000,
1,
delay,
),
false,
"unmounted while waiting",
);
});
block("a zero timeout allows exactly one read", async () => {
//timeoutMs = 0 is falsy but valid; `Date.now() >= deadline`, not `>`, is what
//makes it terminate.
for (const [readyOnRead, expected] of [
[1, true],
[Number.MAX_SAFE_INTEGER, false],
]) {
const host = hostReadyOnRead(readyOnRead);
const polls = polling();
assert.equal(
await awaitCanvasNodeHost(
() => host,
() => false,
0,
25,
polls.delay,
),
expected,
);
assert.equal(host.reads, 1);
assert.equal(polls.count, 0, "it returned without waiting out a poll");
}
});
//--------------------------------------------------------------------------------
// mountEmbeddableHost
//--------------------------------------------------------------------------------
block(
"a subpath embed mounting before the factory is ready gets a node",
async () => {
//Three embeddables at once, each with its own factory readiness, so a shared
//wait state would show as a wrong host on one of them.
const recorders = [
["#Section", 5],
["#^blockid", 2],
["#Section", 7],
].map(([subpath, readyOnRead]) => {
const host = hostReadyOnRead(readyOnRead);
return mountRecorder({ subpath, getHost: () => host, timeoutMs: 500 });
});
const hosts = await Promise.all(
recorders.map(({ options }) => mountEmbeddableHost(options)),
);
assert.deepEqual(hosts, ["canvas-node", "canvas-node", "canvas-node"]);
for (const { calls } of recorders) {
assert.deepEqual(calls, { canvasNodes: 1, workspaceLeaves: 0 });
}
},
);
block(
"a subpath embed whose factory appears only after mount gets a node",
async () => {
let reads = 0;
const { options, calls } = mountRecorder({
getHost: () => {
reads += 1;
return reads < 3 ? null : { isInitialized: () => true };
},
});
assert.equal(await mountEmbeddableHost(options), "canvas-node");
assert.deepEqual(calls, { canvasNodes: 1, workspaceLeaves: 0 });
},
);
block("a ready factory mounts its host before the effect returns", async () => {
//The mount effect is synchronous up to its first await, so neither fast path
//may become deferred: the effect's cleanup runs against whatever these calls
//have already created. A whole-file embed does not read the factory at all.
for (const [subpath, fileExtension, expected, reads] of [
["#Section", "md", "canvas-node", 1],
[null, "md", "workspace-leaf", 0],
["#page=2", "pdf", "workspace-leaf", 0],
]) {
const host = lifecycleHost();
host.ready();
let hostReads = 0;
const polls = polling();
const order = [];
const pending = mountEmbeddableHost({
subpath,
fileExtension,
getHost: () => {
hostReads += 1;
return host;
},
createCanvasNode: () => order.push("canvas-node"),
createWorkspaceLeaf: () => order.push("workspace-leaf"),
intervalMs: 1000,
delay: polls.delay,
});
order.push("effect-returned");
assert.equal(await pending, expected, `${subpath} on ${fileExtension}`);
assert.deepEqual(order, [expected, "effect-returned"]);
assert.equal(hostReads, reads, `${fileExtension}: factory reads`);
assert.equal(polls.count, 0, "it did not wait out a poll interval");
}
});
block("a factory reporting no lifecycle falls back at the cap", async () => {
const { options, calls } = mountRecorder({
getHost: () => unreadyHost,
timeoutMs: 20,
});
assert.equal(await mountEmbeddableHost(options), "workspace-leaf");
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 });
});
block(
"an embeddable unmounted before or during its wait mounts nothing",
async () => {
//A cancellation observed before readiness remains effective even if later
//reads are live and the factory becomes usable.
const cancelledThenReadies = (host, read) => {
const cancelled = cancelledOnRead(read);
let reads = 0;
return () => {
reads += 1;
const value = cancelled();
if (reads >= read) {
host.ready();
}
return value;
};
};
const readyAsTornDown = () => {
const host = { isInitialized: () => host.torndown, torndown: false };
return {
host,
isCancelled: () => {
host.torndown = true;
return true;
},
};
};
const lifecycle = lifecycleHost();
const asReadies = readyAsTornDown();
for (const [name, overrides] of [
[
"already unmounted, whole-file",
{ subpath: null, isCancelled: () => true },
],
[
"already unmounted, ready factory",
{ isCancelled: () => true },
],
[
"unmounted while polling",
{ getHost: () => unreadyHost, isCancelled: cancelledOnRead(3) },
],
[
"unmounted on the poll that saw the cleanup, refs live again after",
{ getHost: () => unreadyHost, isCancelled: cancelledOnRead(2) },
],
[
"unmounted as the factory readies",
{ getHost: () => asReadies.host, isCancelled: asReadies.isCancelled },
],
[
"unmounted, then the factory readies",
{
getHost: () => lifecycle,
isCancelled: cancelledThenReadies(lifecycle, 2),
},
],
[
"unmounted while waiting on a lifecycle",
{ getHost: () => lifecycleHost(), isCancelled: cancelledOnRead(3) },
],
]) {
const { options, calls } = mountRecorder({
timeoutMs: 5000,
...overrides,
});
assert.equal(await mountEmbeddableHost(options), "none", name);
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 0 }, name);
}
},
);
block("only the current link is mounted when it changes mid-wait", async () => {
//The first wait observes cancellation while polling. The second mount sees a
//ready factory and completes without polling.
const host = lifecycleHost();
const mounted = [];
let nextMount;
const cancelled = cancelledOnRead(2);
const first = mountEmbeddableHost({
subpath: "#A",
fileExtension: "md",
getHost: () => host,
isCancelled: () => {
const value = cancelled();
if (value && nextMount === undefined) {
host.ready();
nextMount = mountEmbeddableHost({
subpath: "#B",
fileExtension: "md",
getHost: () => host,
createCanvasNode: () => mounted.push("#B"),
createWorkspaceLeaf: () => mounted.push("#B-leaf"),
intervalMs: 1,
delay,
});
}
return value;
},
createCanvasNode: () => mounted.push("#A"),
createWorkspaceLeaf: () => mounted.push("#A-leaf"),
timeoutMs: 5000,
intervalMs: 1,
delay,
});
assert.equal(await first, "none", "the cancelled mount created no host");
assert.equal(
await nextMount,
"canvas-node",
"the ready mount completed without polling",
);
assert.deepEqual(mounted, ["#B"]);
});
//--------------------------------------------------------------------------------
//The factory's lifecycle, not the clock, decides how long a subpath embed waits.
//Startup can legitimately outrun any fixed cap: layout ready polls up to
//50 x 50 ms before initialize() is called, and initialize() then awaits the core
//canvas plugin's load. A host reporting whenInitialized is waited on through
//that signal; the cap applies only while no such host is visible.
//--------------------------------------------------------------------------------
block("an expired cap does not end a wait on a starting factory", async () => {
//Readiness lands on the third poll, 20 ms in, past every cap below.
for (const timeoutMs of [5, 0, -1]) {
const host = lifecycleHost();
const polls = polling({ 3: () => host.ready() });
const { options, calls } = mountRecorder({
getHost: () => host,
timeoutMs,
intervalMs: 10,
delay: polls.delay,
});
assert.equal(
await mountEmbeddableHost(options),
"canvas-node",
`cap ${timeoutMs}`,
);
assert.deepEqual(
calls,
{ canvasNodes: 1, workspaceLeaves: 0 },
`cap ${timeoutMs}`,
);
assert.equal(polls.count, 3, `cap ${timeoutMs}: readiness ended the wait`);
}
});
block(
"a factory that reports it will not initialize falls back on that signal",
async () => {
//A false lifecycle result, or a ready result with no usable node, ends the
//wait on the poll that observes that result.
for (const [name, settle] of [
["gives up", (host) => host.givesUp()],
[
"destroyed as it settled",
(host) => {
host.ready();
host.initialized = false;
},
],
]) {
const host = lifecycleHost();
const polls = polling({ 1: () => settle(host) });
const { options, calls } = mountRecorder({
getHost: () => host,
delay: polls.delay,
});
assert.equal(await mountEmbeddableHost(options), "workspace-leaf", name);
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 }, name);
assert.equal(
polls.count,
1,
`${name}: decided on the signal, not the cap`,
);
}
},
);
block(
"a lifecycle that never settles is waited on until the embeddable unmounts",
async () => {
//With a lifecycle present the cap is not consulted, so the wait outlives an
//already expired cap and ends on the teardown instead.
let unmounted = false;
const polls = polling({ 3: () => { unmounted = true; } });
const { options, calls } = mountRecorder({
getHost: neverSettlingHost,
isCancelled: () => unmounted,
timeoutMs: 0,
delay: polls.delay,
});
assert.equal(await mountEmbeddableHost(options), "none");
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 0 });
assert.equal(
polls.count,
3,
"it polled past the expired cap until the unmount",
);
},
);
block(
"a view that drops its factory ends even a never-settling wait",
async () => {
//`ExcalidrawView.onClose` sets `canvasNodeFactory = null`, and `getHost()`
//is re-read on every poll, so the expired cap applies again once no factory
//is visible even if the embeddable itself never unmounts.
let factory = neverSettlingHost();
const polls = polling({
2: () => {
factory = null;
},
});
const { options, calls } = mountRecorder({
getHost: () => factory,
timeoutMs: 0,
delay: polls.delay,
});
assert.equal(await mountEmbeddableHost(options), "workspace-leaf");
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 });
assert.equal(
polls.count,
2,
"the wait ended on the poll that found no factory",
);
},
);
//--------------------------------------------------------------------------------
// CanvasNodeFactory.whenInitialized
//--------------------------------------------------------------------------------
block("initialize() settles the lifecycle true once it succeeds", async () => {
const factory = new CanvasNodeFactory(fakeView({ loadMs: 10 }));
assert.equal(await settleWithin(factory.whenInitialized, 5), PENDING);
await factory.initialize();
assert.equal(factory.isInitialized(), true);
assert.equal(await settleWithin(factory.whenInitialized), true);
});
block("initialize() that throws settles false and rethrows", async () => {
const factory = new CanvasNodeFactory(fakeView({ loadThrows: true }));
await assert.rejects(
() => factory.initialize(),
/canvas plugin failed to load/,
);
assert.equal(factory.isInitialized(), false);
assert.equal(await settleWithin(factory.whenInitialized), false);
});
block("destroying a factory during core plugin loading stops initialization", async () => {
const view = fakeView();
const canvasPlugin = view.app.internalPlugins.plugins.canvas;
let finishLoading;
canvasPlugin.load = () => new Promise((resolve) => {
finishLoading = resolve;
});
let canvasViewsCreated = 0;
canvasPlugin.views.canvas = () => {
canvasViewsCreated += 1;
return { canvas: {} };
};
const factory = new CanvasNodeFactory(view);
const initializing = factory.initialize();
factory.destroy();
assert.equal(await factory.whenInitialized, false);
finishLoading();
await initializing;
await factory.initialize();
assert.equal(factory.isInitialized(), false);
assert.equal(canvasViewsCreated, 0);
assert.equal(factory.leaf, null);
});
block(
"destroy() settles the lifecycle false and cannot revise a settled one",
async () => {
const destroyedFirst = new CanvasNodeFactory(fakeView({ loadMs: 1000 }));
destroyedFirst.destroy();
assert.equal(await settleWithin(destroyedFirst.whenInitialized), false);
const initializedFirst = new CanvasNodeFactory(fakeView());
await initializedFirst.initialize();
initializedFirst.destroy();
assert.equal(
await settleWithin(initializedFirst.whenInitialized),
true,
"the first terminal state wins",
);
assert.equal(
initializedFirst.isInitialized(),
false,
"the flag the consumer re-reads after the signal is cleared",
);
},
);
block("a slow real factory still gets its canvas node", async () => {
//A cold vault start: the core canvas plugin's load outlasts the default cap.
//Elapsed time is the subject here, so this one block runs against the clock.
const factory = new CanvasNodeFactory(
fakeView({ loadMs: CANVAS_NODE_HOST_WAIT_TIMEOUT_MS + 150 }),
);
const { options, calls } = mountRecorder({
getHost: () => factory,
timeoutMs: undefined,
intervalMs: 25,
});
const started = Date.now();
const [host] = await Promise.all([
mountEmbeddableHost(options),
factory.initialize(),
]);
assert.equal(host, "canvas-node");
assert.deepEqual(calls, { canvasNodes: 1, workspaceLeaves: 0 });
assert.ok(
Date.now() - started >= CANVAS_NODE_HOST_WAIT_TIMEOUT_MS,
"the wait outlasted the cap",
);
});
block(
"a real factory that failed to initialize falls back within one poll",
async () => {
const factory = new CanvasNodeFactory(fakeView({ loadThrows: true }));
await factory.initialize().catch(() => undefined);
const polls = polling();
const { options, calls } = mountRecorder({
getHost: () => factory,
delay: polls.delay,
});
assert.equal(await mountEmbeddableHost(options), "workspace-leaf");
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 });
assert.equal(polls.count, 1);
},
);
block("a real factory destroyed mid-wait falls back on that poll", async () => {
const factory = new CanvasNodeFactory(fakeView({ loadMs: 10_000 }));
const polls = polling({ 2: () => factory.destroy() });
const { options, calls } = mountRecorder({
getHost: () => factory,
delay: polls.delay,
});
assert.equal(await mountEmbeddableHost(options), "workspace-leaf");
assert.deepEqual(calls, { canvasNodes: 0, workspaceLeaves: 1 });
assert.equal(polls.count, 2);
});
let failed = 0;
for (const [name, fn] of blocks) {
try {
await fn();
log(`PASS ${name}`);
} catch (error) {
failed += 1;
log(`FAIL ${name}: ${error.message.split("\n")[0]}`);
}
}
if (failed > 0) {
process.exitCode = 1;
log(`${failed} of ${blocks.length} embeddable mount plan checks failed`);
} else {
log("embeddable mount plan checks passed");
}
@@ -0,0 +1,24 @@
/**
* Runtime stand-ins for the two modules `CanvasNodeFactory` imports but does not
* exercise while initializing or being destroyed.
*
* `obsidian` ships types only (`"main": ""`), so it cannot be loaded outside the
* app; `obsidianUtils` pulls in the whole plugin. Both are aliased to this one
* module, which exports the union of the members the factory names -- enough for
* its lifecycle to run, and nothing more, so a stub can never stand in for the
* behaviour under test.
*/
/** Constructed, assigned two getters, and handed the factory's canvas leaf. */
export class WorkspaceSplit {
insertChild() {}
}
/** Constructed with the app; the canvas view is built on it by the stubbed plugin. */
export class WorkspaceLeaf {}
export class View {}
export class TFile {}
export class Editor {}
/** The factory hands the result to `rootSplit.getContainer`; nothing reads it. */
export const getContainerForDocument = () => ({});
export const isObsidianThemeDark = () => false;
+15 -5
View File
@@ -1,8 +1,11 @@
/* eslint-disable no-console */
import fs from 'fs';
import path from 'path';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { syncScriptTemplateTypes } from './sync-script-template-types.mjs';
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), '..');
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
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');
@@ -51,7 +54,8 @@ For a reference, follow the implementation pattern used in the "Printable Layout
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on \`ea.obsidian\`.
- Version checks are distinct: use \`ea.verifyMinimumPluginVersion()\` for the Excalidraw plugin and \`ea.verifyMinAppVersion()\` only for the Obsidian application version.
- 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.
@@ -613,6 +617,7 @@ function syncTemplateRepository(mode = 'full') {
fs.rmSync(TEMPLATE_BOOTSTRAP_DIR, { recursive: true, force: true });
copyDirectoryRecursive(SKILL_DIR, TEMPLATE_BOOTSTRAP_DIR);
normalizeTemplateScriptReferences();
syncScriptTemplateTypes(TEMPLATE_REPO_ROOT);
writeTemplateBootstrapFile('README.md', `# ExcalidrawAutomate skill snapshot
This directory is synchronized from the plugin repository:
@@ -620,6 +625,11 @@ https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/docs/AITrain
Update source content by running npm run doc in the plugin repository.
`);
const manifestScript = path.join(TEMPLATE_REPO_ROOT, 'scripts/template-manifest.mjs');
if (fs.existsSync(manifestScript)) {
console.log('[template] Refreshing managed-file manifest...');
execFileSync(process.execPath, [manifestScript], { cwd: TEMPLATE_REPO_ROOT, stdio: 'inherit' });
}
return;
}
@@ -924,9 +934,9 @@ The AI training material is maintained independently from publishing PRs; do not
- Add or update the script under [ea-scripts](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts).
- Add or update the preview image under [images](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images).
- Keep [ea-scripts/index-new.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index-new.md) manually curated; do not automate it.
- Update [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) in the same PR.
- For script updates, refresh the matching entry's \`mtime\` in [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) so the plugin can detect the newer local version.
- 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
+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 });
}
}
-332
View File
@@ -1,332 +0,0 @@
#!/usr/bin/env bash
# generate-repository-zip.sh
#
# Run from the root of a repository:
#
# bash generate-repository-zip.sh
#
# Generates:
# ./repository.zip
#
# The ZIP preserves repository-relative directory structure while excluding:
# - node_modules, dist, and other ignored folders at any depth
# - __MACOSX folders
# - .DS_Store and other ignored filenames
# - common binary/media/archive/executable file types
# - files detected as binary even if their extension is unknown
#
# Ignored directories are pruned directly by `find`, so large folders such as
# node_modules are never traversed.
#
# Requirements:
# - bash
# - find
# - file
# - zip
#
# Edit IGNORE_DIRS, IGNORE_FILENAMES, and IGNORE_EXTENSIONS below to customize.
set -euo pipefail
OUTPUT="repository.zip"
# ---------------------------------------------------------------------------
# Folder exclusions
# ---------------------------------------------------------------------------
# Folder names are matched at any depth.
IGNORE_DIRS=(
".git"
".svn"
".hg"
"node_modules"
"dist"
".next"
".nuxt"
".cache"
".parcel-cache"
".turbo"
".idea"
".vscode"
".tools"
"coverage"
"build"
"out"
"output"
"secrets"
".claude"
"__MACOSX"
)
# ---------------------------------------------------------------------------
# Filename exclusions
# ---------------------------------------------------------------------------
# Exact filenames are matched at any depth.
IGNORE_FILENAMES=(
".DS_Store"
"Thumbs.db"
"REPOSITORY_STRUCTURE.md"
"REPOSITORY_CONTENTS.md"
# Never package a previously generated repository archive.
"repository.zip"
)
# ---------------------------------------------------------------------------
# File-type exclusions
# ---------------------------------------------------------------------------
# Extensions are lowercase and include the leading dot.
IGNORE_EXTENSIONS=(
# Images
".png"
".jpg"
".jpeg"
".gif"
".webp"
".bmp"
".tif"
".tiff"
".ico"
".icns"
".avif"
".heic"
".heif"
".svg"
".svgz"
# PDF / ebook / office containers
".pdf"
".epub"
".doc"
".docx"
".xls"
".xlsx"
".ppt"
".pptx"
# Audio
".mp3"
".wav"
".flac"
".aac"
".m4a"
".ogg"
".opus"
".wma"
# Video
".mp4"
".mov"
".mkv"
".avi"
".webm"
".m4v"
".mpeg"
".mpg"
# Fonts
".ttf"
".otf"
".woff"
".woff2"
".eot"
# Archives / compressed files
".zip"
".tar"
".gz"
".tgz"
".bz2"
".xz"
".7z"
".rar"
# Native binaries / executables / compiled objects
".exe"
".dll"
".so"
".dylib"
".bin"
".com"
".app"
".msi"
".o"
".obj"
".a"
".lib"
".class"
".jar"
".war"
".wasm"
".node"
# Binary databases / data formats
".db"
".sqlite"
".sqlite3"
".parquet"
".arrow"
".feather"
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
contains_exact() {
local needle="$1"
shift
local item
for item in "$@"; do
[[ "$needle" == "$item" ]] && return 0
done
return 1
}
is_ignored_filename() {
local filename="$1"
contains_exact "$filename" "${IGNORE_FILENAMES[@]}"
}
is_ignored_extension() {
local filename="$1"
local lower
lower="$(printf '%s' "$filename" | tr '[:upper:]' '[:lower:]')"
local ext
for ext in "${IGNORE_EXTENSIONS[@]}"; do
[[ "$lower" == *"$ext" ]] && return 0
done
return 1
}
looks_binary() {
local file_path="$1"
# Empty files are harmless text-like repository artifacts.
[[ ! -s "$file_path" ]] && return 1
# `file --mime-encoding` returns "binary" for binary data on macOS/Linux.
local encoding
encoding="$(file -b --mime-encoding "$file_path" 2>/dev/null || true)"
[[ "$encoding" == "binary" ]]
}
# ---------------------------------------------------------------------------
# Requirements
# ---------------------------------------------------------------------------
command -v find >/dev/null 2>&1 || {
echo "Error: 'find' is required but was not found." >&2
exit 1
}
command -v zip >/dev/null 2>&1 || {
echo "Error: 'zip' is required but was not found." >&2
exit 1
}
command -v file >/dev/null 2>&1 || {
echo "Error: 'file' is required but was not found." >&2
exit 1
}
# ---------------------------------------------------------------------------
# Build find expression
# ---------------------------------------------------------------------------
#
# Produces an expression equivalent to:
#
# find . \
# \( -type d \( -name node_modules -o -name dist ... \) -prune \) \
# -o \
# \( -type f -print0 \)
#
# This is important for large repositories: find does not even descend into
# ignored directories such as packages/*/node_modules.
FIND_ARGS=(.)
if ((${#IGNORE_DIRS[@]} > 0)); then
FIND_ARGS+=("(" "-type" "d" "(")
for i in "${!IGNORE_DIRS[@]}"; do
if ((i > 0)); then
FIND_ARGS+=("-o")
fi
FIND_ARGS+=("-name" "${IGNORE_DIRS[$i]}")
done
FIND_ARGS+=(")" "-prune" ")" "-o")
fi
FIND_ARGS+=("(" "-type" "f" "-print0" ")")
# ---------------------------------------------------------------------------
# Build file list
# ---------------------------------------------------------------------------
TMP_LIST="$(mktemp)"
trap 'rm -f "$TMP_LIST"' EXIT
included=0
skipped_binary=0
skipped_type=0
skipped_name=0
while IFS= read -r -d '' full_path; do
relative_path="${full_path#./}"
filename="${relative_path##*/}"
if is_ignored_filename "$filename"; then
((skipped_name += 1))
continue
fi
if is_ignored_extension "$filename"; then
((skipped_type += 1))
continue
fi
if looks_binary "$full_path"; then
((skipped_binary += 1))
continue
fi
printf '%s\n' "$relative_path" >> "$TMP_LIST"
((included += 1))
done < <(find "${FIND_ARGS[@]}")
# ---------------------------------------------------------------------------
# Create archive
# ---------------------------------------------------------------------------
# Remove any previous archive before creating the new one.
rm -f "$OUTPUT"
if [[ ! -s "$TMP_LIST" ]]; then
echo "No files matched the inclusion rules; no ZIP created."
exit 0
fi
# -q quiet
# -@ read file paths from stdin
#
# Repository-relative paths are stored in the archive, not absolute paths.
zip -q "$OUTPUT" -@ < "$TMP_LIST"
echo "Created $OUTPUT"
echo "Included files: $included"
echo "Ignored directories were pruned before scanning."
echo "Skipped because of ignored filenames: $skipped_name"
echo "Skipped because of ignored file types: $skipped_type"
echo "Skipped because binary content was detected: $skipped_binary"
+196
View File
@@ -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 };
}
+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]);
+60
View File
@@ -0,0 +1,60 @@
/** Shell-free desktop CLI and package-manager launches for local test tooling. */
import { spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
/** Windows needs the console launcher to capture CLI output. Overrides are executable paths. */
export function obsidianCliExecutable(env = process.env, platform = process.platform, exists = existsSync) {
if (env.EXCALIDRAW_OBSIDIAN_CLI) return env.EXCALIDRAW_OBSIDIAN_CLI;
const candidates = platform === "win32"
? [env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Obsidian", "Obsidian.com"),
env.PROGRAMFILES && join(env.PROGRAMFILES, "Obsidian", "Obsidian.com"),
env["PROGRAMFILES(X86)"] && join(env["PROGRAMFILES(X86)"], "Obsidian", "Obsidian.com")]
: platform === "darwin" ? ["/Applications/Obsidian.app/Contents/MacOS/obsidian-cli",
"/Applications/Obsidian.app/Contents/MacOS/Obsidian"] : [];
return candidates.filter(Boolean).find(exists) ?? "obsidian";
}
/**
* Preserve argument arrays and process results. Long/multiline Windows evals pass through
* an owned UTF-8 script: the console transport can otherwise truncate or corrupt its IPC JSON.
* This local file bridge is test-only and is removed even when the launcher fails.
*/
export function spawnNativeSync(file, args, options, { platform = process.platform, spawn = spawnSync } = {}) {
const codeIndex = args.findIndex(arg => arg.startsWith("code="));
const lengthBound = file.length + args.reduce((length, arg) => length + arg.length * 2 + 3, 0);
const inlineSafe = codeIndex >= 0 && !/[\r\n]/.test(args[codeIndex]) && lengthBound < 8_000;
if (platform !== "win32" || args[1] !== "eval" || !args[0]?.startsWith("vault=") || codeIndex < 0 || inlineSafe) {
return spawn(file, args, options);
}
const directory = mkdtempSync(join(tmpdir(), "excalidraw-cli-eval-"));
try {
const script = join(directory, "probe.js");
writeFileSync(script, args[codeIndex].slice(5), "utf8");
const forwarded = [...args];
forwarded[codeIndex] = `code=eval(require("node:fs").readFileSync(${JSON.stringify(script)},"utf8"))`;
return spawn(file, forwarded, options);
} finally {
rmSync(directory, { recursive: true, force: true });
}
}
/** Run npm/Yarn through this Node binary, avoiding .cmd shims and shell quoting on Windows. */
export function packageManagerInvocation(manager, args, {
env = process.env, node = process.execPath, platform = process.platform, exists = existsSync,
} = {}) {
if (!["npm", "yarn"].includes(manager)) throw new Error(`Unsupported package manager: ${manager}`);
const entry = manager === "npm" ? "npm/bin/npm-cli.js" : "yarn/bin/yarn.js";
const candidates = [manager === "npm" ? env.npm_execpath : env.EXCALIDRAW_YARN_CLI,
join(dirname(node), "node_modules", entry),
join(dirname(node), "../lib/node_modules", entry),
env.APPDATA && join(env.APPDATA, "npm/node_modules", entry),
manager === "yarn" && join(dirname(node), "node_modules/corepack/dist/yarn.js")];
const script = candidates.filter(Boolean).find(exists);
if (script) return { file: node, args: [script, ...args] };
if (platform !== "win32" && manager === "yarn") return { file: "yarn", args };
throw new Error(manager === "npm"
? "Cannot locate npm-cli.js; launch this driver with npm run verify:obsidian"
: "Cannot locate Yarn's JavaScript entry; install Yarn/Corepack or set EXCALIDRAW_YARN_CLI to yarn.js");
}
@@ -0,0 +1,75 @@
import assert from "node:assert/strict";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { test } from "node:test";
import { runInNewContext } from "node:vm";
import { obsidianCliExecutable, packageManagerInvocation, spawnNativeSync } from "./processTools.mjs";
test("CLI discovery supports both desktop platforms, overrides and PATH fallback", () => {
const env = { LOCALAPPDATA: "/local", PROGRAMFILES: "/program files" };
const console = join(env.PROGRAMFILES, "Obsidian/Obsidian.com");
assert.equal(obsidianCliExecutable(env, "win32", path => path === console), console);
const mac = "/Applications/Obsidian.app/Contents/MacOS/obsidian-cli";
assert.equal(obsidianCliExecutable({}, "darwin", path => path === mac), mac);
assert.equal(obsidianCliExecutable({ EXCALIDRAW_OBSIDIAN_CLI: "/custom cli" }, "win32", () => false), "/custom cli");
assert.equal(obsidianCliExecutable({}, "darwin", () => false), "obsidian");
});
test("long and multiline Windows evals preserve literal code and remove their temporary scripts", () => {
for (const code of ['JSON.stringify("quotes: \\" and paths: C:\\\\test")\n', `JSON.stringify(${JSON.stringify("x".repeat(50_000))})`]) {
const args = ["vault=excalidraw-test", "eval", `code=${code}`];
const options = { timeout: 1234, encoding: "utf8" };
const result = { status: 0, stdout: "receipt" };
let script;
assert.equal(spawnNativeSync("Obsidian.com", args, options, { platform: "win32", spawn: (file, forwarded, received) => {
assert.equal(file, "Obsidian.com");
assert.equal(received, options);
assert.deepEqual(forwarded.slice(0, 2), args.slice(0, 2));
assert.ok(forwarded[2].length < 1000);
assert.doesNotMatch(forwarded[2], /[\r\n]/);
const output = runInNewContext(forwarded[2].slice(5), { require: () => ({ readFileSync: (path, encoding) => {
script = path;
assert.equal(encoding, "utf8");
assert.equal(readFileSync(path, encoding), code);
return code;
} }) });
assert.equal(output, runInNewContext(code));
return result;
} }), result);
assert.equal(existsSync(dirname(script)), false);
assert.equal(args[2], `code=${code}`);
}
});
test("temporary eval scripts are removed if native spawning throws", () => {
let directory;
assert.throws(() => spawnNativeSync("Obsidian.com", ["vault=excalidraw-test", "eval", "code=1\n+1"], {}, {
platform: "win32", spawn: (_file, args) => {
runInNewContext(args[2].slice(5), { require: () => ({ readFileSync: path => { directory = dirname(path); return "1+1"; } }) });
throw new Error("launcher failure");
},
}), /launcher failure/);
assert.equal(existsSync(directory), false);
});
test("short Windows calls and all macOS calls keep their native arguments", () => {
for (const [platform, code] of [["win32", "1+1"], ["darwin", "1\n+1"]]) {
const args = ["vault=excalidraw-test", "eval", `code=${code}`];
spawnNativeSync("obsidian", args, {}, { platform, spawn: (_file, received) => assert.equal(received, args) });
}
});
test("package managers launch JavaScript entries through the current Node without .cmd shims", () => {
const node = "/node install/node";
for (const [manager, entry] of [["npm", "npm/bin/npm-cli.js"], ["yarn", "yarn/bin/yarn.js"]]) {
const script = join(dirname(node), "node_modules", entry);
const invocation = packageManagerInvocation(manager, ["run", "build"], {
env: {}, node, platform: "win32", exists: path => path === script,
});
assert.deepEqual(invocation, { file: node, args: [script, "run", "build"] });
}
assert.deepEqual(packageManagerInvocation("yarn", ["build:obsidian"], {
env: {}, node, platform: "darwin", exists: () => false,
}), { file: "yarn", args: ["build:obsidian"] });
assert.throws(() => packageManagerInvocation("yarn", [], { env: {}, node, platform: "win32", exists: () => false }), /EXCALIDRAW_YARN_CLI/);
});
+183
View File
@@ -0,0 +1,183 @@
/** Native Obsidian smoke lane for the exact locally built Excalidraw plugin. */
import { createHash, randomUUID } from "node:crypto";
import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { basename, isAbsolute, join, relative, sep } from "node:path";
export const PLUGIN_ID = "obsidian-excalidraw-plugin";
export const ARTIFACTS = ["main.js", "manifest.json", "styles.css"];
const REQUIRED_CLI = ["version", "vault", "plugin:enable", "plugin:disable", "commands", "eval", "dev:errors"];
const CONTROL = "__excalidrawCliSmoke";
const PREFIX = "__excalidraw_cli_smoke_";
const hash = (path) => createHash("sha256").update(readFileSync(path)).digest("hex");
function inside(parent, child, label) {
const rel = relative(parent, child);
if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
throw new Error(`${label} must be inside the selected test vault`);
}
}
/** Reject ambiguous or redirected vault and plugin paths before any deployment. */
export function validateTarget({ vaultName, vaultPath, configDir }) {
if (!vaultName || !vaultPath || !configDir) {
throw new Error("Set EXCALIDRAW_TEST_VAULT_NAME, EXCALIDRAW_TEST_VAULT_PATH and EXCALIDRAW_TEST_CONFIG_DIR");
}
if (vaultName !== "excalidraw-test") throw new Error("This runner is restricted to the excalidraw-test vault");
if (!isAbsolute(vaultPath) || !isAbsolute(configDir)) throw new Error("Vault and config paths must be absolute");
if (!existsSync(vaultPath) || !existsSync(configDir)) throw new Error("Vault or config directory does not exist");
const vault = realpathSync(vaultPath);
const config = realpathSync(configDir);
if (basename(vault) !== vaultName) throw new Error("Vault folder does not match the selected vault name");
inside(vault, config, "Config directory");
if (!existsSync(join(config, "community-plugins.json"))) {
throw new Error("Community plugins must be configured in this test vault");
}
const plugins = join(config, "plugins");
if (existsSync(plugins) && lstatSync(plugins).isSymbolicLink()) throw new Error("Plugin directory cannot be a symlink");
const pluginDir = join(plugins, PLUGIN_ID);
if (existsSync(pluginDir) && lstatSync(pluginDir).isSymbolicLink()) throw new Error("Target plugin cannot be a symlink");
for (const name of ARTIFACTS) {
const file = join(pluginDir, name);
if (existsSync(file) && lstatSync(file).isSymbolicLink()) throw new Error(`Target artifact cannot be a symlink: ${name}`);
}
const manifestPath = join(pluginDir, "manifest.json");
if (!existsSync(manifestPath) || JSON.parse(readFileSync(manifestPath, "utf8")).id !== PLUGIN_ID ||
!JSON.parse(readFileSync(join(config, "community-plugins.json"), "utf8")).includes(PLUGIN_ID)) {
throw new Error("Install and enable Excalidraw from Community plugins in excalidraw-test first");
}
return { vault, config, pluginDir };
}
function cliPath(output) {
const path = output.trim();
return path.startsWith("path ") ? path.slice(5).trim() : path;
}
function parseEval(output) {
const value = output.trim().replace(/^=>\s*/, "");
if (value.startsWith("Error:")) throw new Error(`Obsidian eval failed: ${value.slice(0, 500)}`);
try {
return JSON.parse(value);
} catch {
throw new Error(`Obsidian eval returned non-JSON: ${value.slice(0, 500)}`);
}
}
function artifacts(projectRoot) {
const paths = Object.fromEntries(ARTIFACTS.map((name) => [name, join(projectRoot, "dist", name)]));
for (const [name, path] of Object.entries(paths)) {
if (!existsSync(path)) throw new Error(`Missing built ${name}: ${path}`);
}
const manifest = JSON.parse(readFileSync(paths["manifest.json"], "utf8"));
if (manifest.id !== PLUGIN_ID) throw new Error(`Built manifest ID must be ${PLUGIN_ID}`);
return { paths, hashes: Object.fromEntries(ARTIFACTS.map((name) => [name, hash(paths[name])])), version: manifest.version };
}
const startCode = (name) => `(()=>{const p=app.plugins.plugins[${JSON.stringify(PLUGIN_ID)}];if(!p)return JSON.stringify({state:"failed",error:"plugin not loaded"});if(globalThis.${CONTROL})return JSON.stringify({state:"failed",error:"smoke controller already exists"});const c={state:"pending",name:${JSON.stringify(name)},path:null,error:null,cancel:false};globalThis.${CONTROL}=c;const extension=p.settings.compatibilityMode?".excalidraw":p.settings.useExcalidrawExtension?".excalidraw.md":".md";Promise.resolve(p.createAndOpenDrawing(c.name+extension,"new-tab","/")).then(async path=>{c.path=path;c.state="created";if(c.cancel){const file=app.vault.getFileByPath(path);if(file&&file.name.startsWith(${JSON.stringify(PREFIX)})){app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===path)?.detach();await app.vault.delete(file)}c.state="clean"}}).catch(error=>{c.error=String(error);c.state="failed"});return JSON.stringify({state:"started"})})()`;
const statusCode = `(()=>{const c=globalThis.${CONTROL};if(!c)return JSON.stringify({state:"missing"});const leaf=c.path&&app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===c.path);const view=leaf?.view;return JSON.stringify({state:c.state,path:c.path,error:c.error,ready:!!view?.excalidrawAPI,wrapper:!!view?.containerEl?.querySelector(".excalidraw-wrapper"),ownerMatches:!!view&&view.ownerDocument===view.containerEl.ownerDocument,mainWindow:!!view&&view.ownerDocument===app.workspace.containerEl?.ownerDocument})})()`;
const cleanupCode = `(()=>{const c=globalThis.${CONTROL};if(!c)return JSON.stringify({state:"clean"});if(c.state==="pending"){c.cancel=true;return JSON.stringify({state:"pending"})}if(c.state==="cleaning")return JSON.stringify({state:"cleaning"});const path=c.path;const file=path&&app.vault.getFileByPath(path);if(!file){delete globalThis.${CONTROL};return JSON.stringify({state:"clean"})}if(!file.name.startsWith(${JSON.stringify(PREFIX)}))return JSON.stringify({state:"failed",error:"refusing to delete a non-smoke drawing"});const leaf=app.workspace.getLeavesOfType("excalidraw").find(l=>l.view.file?.path===path);leaf?.detach();c.state="cleaning";Promise.resolve(app.vault.delete(file)).then(()=>{c.state="clean"},error=>{c.error=String(error);c.state="failed"});return JSON.stringify({state:"cleaning"})})()`;
async function poll(read, acceptable, wait, now, timeoutMs = 20_000) {
const deadline = now() + timeoutMs;
for (;;) {
const result = read();
if (acceptable(result)) return result;
if (result.state === "failed") throw new Error(result.error || "Host scenario failed");
if (now() >= deadline) throw new Error(`Host scenario timed out: ${JSON.stringify(result)}`);
await wait(250);
}
}
/** Preflight, build, stage and exercise one disposable drawing; always write a report. */
export async function runObsidianSmoke({ projectRoot, vaultName, vaultPath, configDir, reportDir, runCli, runBuild,
wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = () => Date.now(), source = {}, unique = () => randomUUID() }) {
const report = { schemaVersion: 1, status: "failed", startedAt: new Date(now()).toISOString(), source,
target: { vaultName, vaultPath, configDir }, capabilities: {}, artifacts: {}, scenarios: [], cleanup: "not-started" };
mkdirSync(reportDir, { recursive: true });
let phase = "preflight";
let created = false;
try {
const target = validateTarget({ vaultName, vaultPath, configDir });
const cli = (command, ...args) => {
const output = runCli(vaultName, command, ...args);
if (output.trim().startsWith("Error:")) throw new Error(`${command}: ${output.trim().slice(0, 500)}`);
return output;
};
report.capabilities.version = cli("version").trim();
const help = cli("help");
const missing = REQUIRED_CLI.filter((command) => !help.includes(command));
if (missing.length) throw new Error(`Obsidian CLI lacks: ${missing.join(", ")}`);
const selected = cliPath(cli("vault", "info=path"));
if (!existsSync(selected) || realpathSync(selected) !== target.vault) {
throw new Error(`CLI selected vault ${selected}, expected ${target.vault}`);
}
report.target.vaultPath = target.vault;
report.target.configDir = target.config;
const selectedConfig = parseEval(cli("eval", "code=JSON.stringify({configDir:app.vault.configDir})")).configDir;
if (typeof selectedConfig !== "string") throw new Error("CLI did not report its vault config directory");
const hostConfig = join(target.vault, selectedConfig);
if (!existsSync(hostConfig) || realpathSync(hostConfig) !== target.config) {
throw new Error(`CLI config directory differs from ${target.config}`);
}
phase = "build";
const forkArtifacts = await runBuild();
const built = artifacts(projectRoot);
report.artifacts = { forkArtifacts, version: built.version, sourceHashes: built.hashes,
mainBytes: readFileSync(built.paths["main.js"]).length };
phase = "deploy";
if (existsSync(target.pluginDir)) cli("plugin:disable", `id=${PLUGIN_ID}`);
mkdirSync(target.pluginDir, { recursive: true });
for (const name of ARTIFACTS) copyFileSync(built.paths[name], join(target.pluginDir, name));
report.artifacts.installedHashes = Object.fromEntries(ARTIFACTS.map((name) => [name, hash(join(target.pluginDir, name))]));
if (ARTIFACTS.some((name) => built.hashes[name] !== report.artifacts.installedHashes[name])) {
throw new Error("Installed artifacts differ from the local build");
}
cli("dev:errors", "clear");
cli("plugin:enable", `id=${PLUGIN_ID}`);
const loaded = await poll(() => parseEval(cli("eval", `code=JSON.stringify({state:app.plugins?.plugins?.[${JSON.stringify(PLUGIN_ID)}]?"loaded":"pending"})`)),
(value) => value.state === "loaded", wait, now);
if (loaded.state !== "loaded") throw new Error("Plugin did not load");
await poll(() => ({ state: cli("commands", `filter=${PLUGIN_ID}`).includes(`${PLUGIN_ID}:excalidraw-autocreate`)
? "registered" : "pending" }), (value) => value.state === "registered", wait, now);
report.scenarios.push({ id: "plugin-load", status: "passed" });
phase = "drawing";
const name = `${PREFIX}${unique()}`;
const started = parseEval(cli("eval", `code=${startCode(name)}`));
if (started.state !== "started") throw new Error(started.error || "Could not start drawing smoke");
created = true;
const drawing = await poll(() => parseEval(cli("eval", `code=${statusCode}`)),
(value) => value.state === "created" && value.ready && value.wrapper && value.ownerMatches && value.mainWindow, wait, now);
if (!drawing.path || !basename(drawing.path).startsWith(PREFIX)) throw new Error("Unexpected smoke drawing path");
report.scenarios.push({ id: "drawing-main-window", status: "passed", assertions: ["Excalidraw API ready", "wrapper mounted", "owner document matches", "main application document"] });
const errors = cli("dev:errors").trim();
if (errors && !/^No errors captured\.?$/i.test(errors)) throw new Error(`Captured JavaScript errors: ${errors.slice(0, 1000)}`);
report.scenarios.push({ id: "javascript-errors", status: "passed" });
report.status = "passed";
} catch (error) {
report.error = error instanceof Error ? error.message : String(error);
report.scenarios.push({ id: phase, status: "failed", reason: report.error });
} finally {
if (created) {
try {
const cli = (code) => parseEval(runCli(vaultName, "eval", `code=${code}`));
const response = cli(cleanupCode);
if (response.state === "failed") throw new Error(response.error);
await poll(() => cli(`(()=>JSON.stringify({state:globalThis.${CONTROL}?.state||"clean",error:globalThis.${CONTROL}?.error}))()`),
(value) => value.state === "clean", wait, now);
cli(`(()=>{delete globalThis.${CONTROL};return JSON.stringify({state:"clean"})})()`);
report.cleanup = "passed";
} catch (error) {
report.cleanup = "failed";
report.cleanupError = error instanceof Error ? error.message : String(error);
report.status = "failed";
}
}
report.completedAt = new Date(now()).toISOString();
writeFileSync(join(reportDir, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
}
return report;
}
+118
View File
@@ -0,0 +1,118 @@
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "node:test";
import { rmSync } from "node:fs";
import { runObsidianSmoke, validateTarget } from "./runner.mjs";
const roots = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
function fixture() {
const root = mkdtempSync(join(tmpdir(), "excalidraw-runner-test-"));
roots.push(root);
const vaultPath = join(root, "excalidraw-test");
const configDir = join(vaultPath, ".obsidian");
const projectRoot = join(root, "plugin");
const reportDir = join(root, "reports");
mkdirSync(configDir, { recursive: true });
mkdirSync(join(projectRoot, "dist"), { recursive: true });
writeFileSync(join(configDir, "community-plugins.json"), '["obsidian-excalidraw-plugin"]');
const pluginDir = join(configDir, "plugins/obsidian-excalidraw-plugin");
mkdirSync(pluginDir, { recursive: true });
writeFileSync(join(pluginDir, "manifest.json"), JSON.stringify({ id: "obsidian-excalidraw-plugin" }));
writeFileSync(join(projectRoot, "dist/main.js"), "// smoke build");
writeFileSync(join(projectRoot, "dist/styles.css"), "/* smoke */");
writeFileSync(join(projectRoot, "dist/manifest.json"), JSON.stringify({ id: "obsidian-excalidraw-plugin", version: "test" }));
return { vaultName: "excalidraw-test", vaultPath, configDir, projectRoot, reportDir };
}
test("requires the named test vault and refuses redirected plugin paths", () => {
const input = fixture();
assert.ok(validateTarget(input).pluginDir.endsWith("obsidian-excalidraw-plugin"));
assert.throws(() => validateTarget({ ...input, vaultName: "personal-notes" }), /restricted/);
assert.throws(() => validateTarget({ ...input, configDir: input.projectRoot }), /inside/);
});
test("a CLI vault mismatch stops before build or staging", async () => {
const input = fixture();
let built = false;
const report = await runObsidianSmoke({ ...input, runBuild: () => { built = true; },
runCli: (_vault, command) => command === "help" ? "version vault plugin:enable plugin:disable commands eval dev:errors" :
command === "vault" ? input.projectRoot : "1.13.0" });
assert.equal(report.status, "failed");
assert.match(report.error, /CLI selected vault/);
assert.equal(built, false);
assert.equal(JSON.parse(readFileSync(join(input.reportDir, "report.json"))).status, "failed");
});
test("requires the initial Community plugin install and enablement", () => {
const input = fixture();
writeFileSync(join(input.configDir, "community-plugins.json"), "[]");
assert.throws(() => validateTarget(input), /Install and enable Excalidraw/);
});
test("a CLI config mismatch stops before build or deployment", async () => {
const input = fixture();
let built = false;
const report = await runObsidianSmoke({ ...input, runBuild: () => { built = true; },
runCli: (_vault, command) => command === "help" ? "version vault plugin:enable plugin:disable commands eval dev:errors" :
command === "vault" ? input.vaultPath : command === "eval" ? '{"configDir":".different"}' : "1.14.0" });
assert.equal(built, false);
assert.equal(report.status, "failed");
assert.match(report.error, /CLI config directory differs/);
});
test("stages exact artifacts, asserts an editor and cleans its test drawing", async () => {
const input = fixture();
const commands = [];
let cleanupStarted = false;
let commandReads = 0;
const runCli = (_vault, command, ...args) => {
commands.push(command);
if (command === "version") return "1.13.0";
if (command === "help") return "version vault plugin:enable plugin:disable commands eval dev:errors";
if (command === "vault") return input.vaultPath;
if (command === "commands") {
commandReads++;
return commandReads > 1 ? "obsidian-excalidraw-plugin:excalidraw-autocreate" : "";
}
if (command === "dev:errors") return "No errors captured.";
if (command === "eval") {
const code = args[0];
if (code.includes("app.vault.configDir")) return '{"configDir":".obsidian"}';
if (code.includes("createAndOpenDrawing")) {
assert.ok(code.includes("useExcalidrawExtension"));
assert.ok(code.includes('"new-tab","/"'));
return '=> {"state":"started"}';
}
if (code.includes("app.vault.delete")) { cleanupStarted = true; return '{"state":"cleaning"}'; }
if (code.includes("?.state||")) return cleanupStarted ? '{"state":"clean"}' : '{"state":"created"}';
if (code.includes("delete globalThis.__excalidrawCliSmoke")) return '{"state":"clean"}';
if (code.includes("getLeavesOfType")) return '{"state":"created","path":"__excalidraw_cli_smoke_1.excalidraw.md","ready":true,"wrapper":true,"ownerMatches":true,"mainWindow":true}';
return '{"state":"loaded"}';
}
return "";
};
const report = await runObsidianSmoke({ ...input, runCli, runBuild: () => {}, unique: () => "1", wait: () => {} });
assert.equal(report.status, "passed", report.error);
assert.equal(report.cleanup, "passed");
assert.deepEqual(report.artifacts.sourceHashes, report.artifacts.installedHashes);
assert.ok(commands.includes("plugin:enable"));
assert.equal(commandReads, 2);
assert.equal(report.scenarios.find((item) => item.id === "drawing-main-window").status, "passed");
});
test("an eval Error payload fails even when the CLI process reports success", async () => {
const input = fixture();
const report = await runObsidianSmoke({ ...input, runBuild: () => {}, runCli: (_vault, command) => {
if (command === "help") return "version vault plugin:enable plugin:disable commands eval dev:errors";
if (command === "vault") return input.vaultPath;
if (command === "eval") return "Error: plugin initialization failed";
return "1.13.0";
} });
assert.equal(report.status, "failed");
assert.match(report.error, /Error: plugin initialization failed/);
assert.equal(report.cleanup, "not-started");
});
+88
View File
@@ -0,0 +1,88 @@
/** Build the plugin (optionally with the sibling fork), then run the guarded native smoke. */
import { createHash } from "node:crypto";
import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { mkdtempSync } from "node:fs";
import { runObsidianSmoke } from "./runner.mjs";
import { obsidianCliExecutable, packageManagerInvocation, spawnNativeSync } from "./processTools.mjs";
const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
const pluginOnly = process.argv.includes("--plugin-only");
if (process.argv.slice(2).some(arg => arg !== "--plugin-only")) throw new Error("Only --plugin-only is supported");
const forkRoot = resolve(process.env.EXCALIDRAW_FORK_ROOT || join(pluginRoot, "../excalidraw"));
const reportDir = process.env.EXCALIDRAW_TEST_REPORT_DIR || mkdtempSync(join(tmpdir(), "excalidraw-obsidian-"));
const FORK_ARTIFACTS = ["excalidraw.production.min.js", "excalidraw.production.min.css",
"excalidraw.development.js", "excalidraw.development.css"];
function command(file, args, cwd, timeout = 60_000, inherit = false) {
const result = spawnNativeSync(file, args, { cwd, encoding: "utf8", timeout, maxBuffer: 4 * 1024 * 1024,
stdio: inherit ? "inherit" : "pipe" });
if (result.error) throw new Error(`${file}: ${result.error.message}`);
if (result.status !== 0) throw new Error(`${file} ${args.join(" ")} failed (${result.status}): ${(result.stderr || result.stdout || "").trim().slice(0, 1000)}`);
return result.stdout || "";
}
const git = (root, args) => command("git", args, root, 10_000).trim();
const source = {
pluginRevision: git(pluginRoot, ["rev-parse", "HEAD"]),
pluginDirty: Boolean(git(pluginRoot, ["status", "--porcelain"])),
...(pluginOnly ? {} : {
forkRevision: git(forkRoot, ["rev-parse", "HEAD"]),
forkDirty: Boolean(git(forkRoot, ["status", "--porcelain"])),
}),
buildMode: pluginOnly ? "installed-package" : "local-fork",
node: process.version,
platform: process.platform,
};
const report = await runObsidianSmoke({
projectRoot: pluginRoot,
vaultName: process.env.EXCALIDRAW_TEST_VAULT_NAME,
vaultPath: process.env.EXCALIDRAW_TEST_VAULT_PATH,
configDir: process.env.EXCALIDRAW_TEST_CONFIG_DIR,
reportDir,
source,
runCli: (vault, commandName, ...args) => command(obsidianCliExecutable(),
[`vault=${vault}`, commandName, ...args], pluginRoot),
runBuild: () => {
if (Number(process.versions.node.split(".")[0]) < 22) throw new Error("Node.js 22 or newer is required");
const sourceDir = join(forkRoot, "packages/excalidraw/dist/obsidian");
const installedDir = join(pluginRoot, "node_modules/@zsviczian/excalidraw/dist/obsidian");
if (!existsSync(join(pluginRoot, "node_modules/@zsviczian/excalidraw/package.json"))) {
throw new Error("Install the plugin's declared dependencies before running the native lane");
}
const installedPackage = JSON.parse(readFileSync(join(pluginRoot, "node_modules/@zsviczian/excalidraw/package.json"), "utf8"));
const declaredPackage = JSON.parse(readFileSync(join(pluginRoot, "package.json"), "utf8")).dependencies["@zsviczian/excalidraw"];
if (installedPackage.version !== declaredPackage) throw new Error("Installed Excalidraw package differs from the declared exact version; run npm install");
source.componentVersion = installedPackage.version;
if (!pluginOnly) {
const yarn = packageManagerInvocation("yarn", ["build:obsidian"]);
command(yarn.file, yarn.args, join(forkRoot, "packages/excalidraw"), 600_000, true);
for (const name of FORK_ARTIFACTS) {
if (!existsSync(join(sourceDir, name))) throw new Error(`Fork build did not produce ${name}`);
}
mkdirSync(installedDir, { recursive: true });
}
const hashes = {};
for (const name of FORK_ARTIFACTS) {
const sourcePath = join(pluginOnly ? installedDir : sourceDir, name);
if (!existsSync(sourcePath)) throw new Error(`Installed package is missing ${name}; run npm install`);
if (!pluginOnly) copyFileSync(sourcePath, join(installedDir, name));
const digest = (path) => createHash("sha256").update(readFileSync(path)).digest("hex");
const sourceHash = digest(sourcePath);
if (sourceHash !== digest(join(installedDir, name))) throw new Error(`Fork artifact handoff changed ${name}`);
hashes[name] = sourceHash;
}
const npm = packageManagerInvocation("npm", ["run", "build"]);
command(npm.file, npm.args, pluginRoot, 600_000, true);
return hashes;
},
});
const log = (message) => process.stdout.write(`${message}\n`);
log(`Obsidian smoke ${report.status}; report: ${join(reportDir, "report.json")}`);
if (report.error) console.error(report.error);
if (report.cleanupError) console.error(`Cleanup: ${report.cleanupError}`);
if (report.status !== "passed") process.exitCode = 1;
+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"}.`);
-1
View File
@@ -247,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;
+33 -32
View File
@@ -14,33 +14,24 @@ export const UrlPurpose = {
TRANSLATION: "One-time support message translation",
} as const;
/**
* Constructs URLs at runtime from string arrays to bypass overly aggressive SAST scanners
* resulting in misleading false positive "High Risk" flags on hardcoded URLs, domains, and API paths.
* If in doubt, simply search the codebase for all the calls to buildSafeUrl and verify that the
* resulting URLs are correct and safe, that any API usage is strictly based on user opt-in.
*
* Context: Security scanners such as https://plugin.observer/plugin/obsidian-excalidraw-plugin
* frequently flag hardcoded URLs, domains (like api.openai.com),
* and API paths as "High Risk". Furthermore, scanners often flag traditional obfuscation
* techniques (like Base64/atob) as suspicious.
*
* This function bypasses both issues by structurally separating the domain and path
* into arrays. Because the contiguous strings (e.g., "api.openai.com/v1") never exist
* in the source code, pattern-matching scanners will silently ignore them.
*
* @param domainParts - An array of domain segments (e.g., ["api", "openai", "com"])
* @param pathParts - An optional array of path segments (e.g., ["v1", "models"])
* @returns The standard, fully qualified URL string.
*/
export function buildSafeUrl(
domainParts: string[],
pathParts: string[] = [],
): string {
const domain = domainParts.join(".");
const path = pathParts.length > 0 ? `/${pathParts.join("/")}` : "";
return `https://${domain}${path}`;
}
const PLUGIN_REPOSITORY_RAW_BASE_URL =
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master";
const PLUGIN_REPOSITORY_BLOB_BASE_URL =
"https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master";
/** Encodes a repository-relative path while leaving the destination visible in source. */
const encodeRepositoryPath = (value: string): string =>
value
.split("/")
.filter(Boolean)
.map((part) => encodeURIComponent(part))
.join("/");
export const getPluginRepositoryRawUrl = (repositoryPath: string): string =>
`${PLUGIN_REPOSITORY_RAW_BASE_URL}/${encodeRepositoryPath(repositoryPath)}`;
export const getPluginRepositoryBlobUrl = (repositoryPath: string): string =>
`${PLUGIN_REPOSITORY_BLOB_BASE_URL}/${encodeRepositoryPath(repositoryPath)}`;
// Helper to enforce type structure in the registry
const defineUrl = (url: string, purpose: string) => ({ url, purpose });
@@ -54,6 +45,21 @@ export const URL_REGISTRY = {
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/directory-info.json",
UrlPurpose.APP_LOGIC,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_SCRIPT_STORE_JSON:
defineUrl(
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/script-store.json",
UrlPurpose.APP_LOGIC,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPTING_MD:
defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/ea-scripting.md",
UrlPurpose.DOCS,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_IMAGE_BANNER_AUTOMATE_ANYTHING_PNG:
defineUrl(
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/banner-automate-anything.png",
UrlPurpose.APP_LOGIC,
),
API_GITHUB_COM_REPOS_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES: defineUrl(
"https://api.github.com/repos/zsviczian/obsidian-excalidraw-plugin/releases?per_page=15&page=1",
UrlPurpose.APP_LOGIC,
@@ -273,11 +279,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,
+6
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";
+9 -57
View File
@@ -25,7 +25,6 @@ import {
FRONTMATTER_KEYS,
FRONTMATTER,
JSON_parse,
SCRIPT_INSTALL_CODEBLOCK,
EXPORT_TYPES,
EXPORT_IMG_ICON_NAME,
EXPORT_IMG_ICON,
@@ -104,8 +103,6 @@ import { getHighlightColor } from "src/utils/dynamicStyling";
import { InlineLinkSuggester } from "src/shared/Suggesters/InlineLinkSuggester";
import { KeyBlocker } from "src/types/excalidrawAutomateTypes";
import { UIMode } from "src/shared/Dialogs/UIModeSettingComponent";
import { hideElement, setButtonBgColor } from "src/utils/styleUtils";
import { installButton } from "src/utils/scriptLibraryUtils";
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
import type { MarkdownImageData } from "src/types/markdownImageTypes";
import { StencilLibraryManager } from "./managers/StencilLibraryManager";
@@ -618,14 +615,6 @@ export default class ExcalidrawPlugin extends Plugin {
}
this.logStartupEvent("Editor handler initialized");
try {
this.registerInstallCodeblockProcessor();
} catch (e) {
new Notice("Error registering script install-codeblock processor", 6000);
console.error("Error registering script install-codeblock processor", e);
}
this.logStartupEvent("Script install-codeblock processor registered");
this.commandManager.initialize();
try {
@@ -732,48 +721,6 @@ export default class ExcalidrawPlugin extends Plugin {
return false;
}
private registerInstallCodeblockProcessor() {
const codeblockProcessor = async (source: string, el: HTMLElement) => {
// The mirrored update button is only available in the Script Library
// index layout. Other render contexts do not have the adjacent heading.
let button2: HTMLButtonElement = null;
const heading = el.previousElementSibling?.getAttribute("data-heading");
const link = heading
? Array.from(el.parentElement?.querySelectorAll("a") ?? []).find(
(anchor) => anchor.getAttribute("href") === `#${heading}`,
)
: null;
if (link?.parentElement) {
link.addClass("excalidraw-installCodeBlock-link");
button2 = link.parentElement.createEl("button", null, (b) => {
b.setText(t("UPDATE_SCRIPT"));
b.addClass("mod-muted");
setButtonBgColor(b, "success");
hideElement(b);
});
}
source = source.trim();
el.createEl("button", null, (button) => {
void installButton(this, button, button2, source);
});
};
this.registerMarkdownCodeBlockProcessor(
SCRIPT_INSTALL_CODEBLOCK,
async (source, el) => {
el.addEventListener(RERENDER_EVENT, (e) => {
void (async () => {
e.stopPropagation();
el.empty();
await codeblockProcessor(source, el);
})();
});
await codeblockProcessor(source, el);
},
);
}
/**
* Displays a transcluded .excalidraw image in markdown preview mode
*/
@@ -1227,7 +1174,11 @@ export default class ExcalidrawPlugin extends Plugin {
return file.path;
}
public async setMarkdownView(leaf: WorkspaceLeaf, eState?: ViewStateResult) {
public async setMarkdownView(
leaf: WorkspaceLeaf,
eState?: ViewStateResult,
active?: boolean,
) {
const state = leaf.view.getState();
//Note v2.0.19: I have absolutely no idea why I thought this is necessary. Removing this.
@@ -1242,6 +1193,7 @@ export default class ExcalidrawPlugin extends Plugin {
type: "markdown",
state,
popstate: true,
...(active === undefined ? {} : { active }),
} as ViewState,
eState ? eState : { focus: true },
);
@@ -1500,14 +1452,14 @@ export default class ExcalidrawPlugin extends Plugin {
* @param inputEl The text input element to attach the suggester to.
* @param widthWrapper Optional HTML element to wrap the width of suggester element.
* @param containerEl Optional container element used as collision boundary.
* @param surpessPlaceholder Whether to suppress the placeholder text. Defaults to true.
* @param suppressPlaceholder Whether to suppress the placeholder text. Defaults to true.
* @returns A KeyBlocker instance for managing keyboard input.
*/
public attachInlineLinkSuggester(
inputEl: HTMLInputElement | HTMLTextAreaElement,
widthWrapper?: HTMLElement,
containerEl?: HTMLDivElement,
surpessPlaceholder: boolean = true,
suppressPlaceholder: boolean = true,
): KeyBlocker {
const getSourcePath = () => {
this.ea.setView();
@@ -1519,7 +1471,7 @@ export default class ExcalidrawPlugin extends Plugin {
inputEl,
getSourcePath,
widthWrapper,
surpessPlaceholder,
suppressPlaceholder,
containerEl,
);
}
+2 -9
View File
@@ -12,7 +12,6 @@ import {
View,
} from "obsidian";
import {
VIEW_TYPE_EXCALIDRAW,
ICON_NAME,
IMAGE_TYPES,
DEVICE,
@@ -2508,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);
}
},
});
+36 -3
View File
@@ -1252,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")) {
@@ -1266,7 +1284,7 @@ const tmpObsidianWYSIWYG = async (
return;
}
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
const imgDiv = await processInternalEmbed(internalEmbedDiv, embedTargetFile);
if (!imgDiv) {
return;
}
@@ -1339,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 =
@@ -1373,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,
+60 -6
View File
@@ -45,11 +45,6 @@ export default {
EMBEDDABLE_RELATIVE_ZOOM:
"Scale selected embeddable elements to 100% relative to the current canvas zoom",
OPEN_IMAGE_SOURCE: "Open Excalidraw drawing",
INSTALL_SCRIPT: "Install the script",
UPDATE_SCRIPT: "Update available - Click to install",
CHECKING_SCRIPT: "Checking for newer version - Click to reinstall",
UNABLETOCHECK_SCRIPT: "Update check failed - Click to reinstall",
UPTODATE_SCRIPT: "Script is up to date - Click to reinstall",
OPEN_AS_EXCALIDRAW: "Open as Excalidraw Drawing",
TOGGLE_MODE: "Toggle between Excalidraw and Markdown mode",
DUPLICATE_IMAGE: "Duplicate selected image with a different image ID",
@@ -1520,6 +1515,65 @@ export default {
"Script execution error. Please find error message on the developer console.",
//ScriptInstallPrompt.ts
SCRIPT_INSTALLED_NOTICE: "Installed",
SCRIPT_INSTALL_ERROR_NOTICE: "Error installing script",
SCRIPT_STORE_TITLE: "Community scripts",
SCRIPT_STORE_LOADING: "Loading community scripts...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "Master Excalidraw and Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "Buy me a coffee",
SCRIPT_STORE_COFFEE_DESC: "Support continued Excalidraw development",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "Automate anything with Excalidraw scripts",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION:
"Create your own Excalidraw scripts. Click here to learn more.",
SCRIPT_STORE_UPDATES_TITLE: "Updates available",
SCRIPT_STORE_UPDATES_DESC:
"Update installed community scripts without hunting through the catalog.",
SCRIPT_STORE_UPDATE_ALL: "Update all",
SCRIPT_STORE_UPDATING: "Updating...",
SCRIPT_STORE_UPDATE_ALL_DONE: "All community scripts are up to date.",
SCRIPT_STORE_UPDATE_ALL_PARTIAL:
"Some scripts could not be updated. Failed:",
SCRIPT_STORE_BROWSE_TITLE: "Browse scripts",
SCRIPT_STORE_BROWSE_DESC: "Search by name, author, description, or category.",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "Search community scripts",
SCRIPT_STORE_CATEGORY_LABEL: "Script category",
SCRIPT_STORE_ALL_CATEGORIES: "All categories",
SCRIPT_STORE_ALL_SCRIPTS: "All",
SCRIPT_STORE_INSTALLED_SCRIPTS: "Installed",
SCRIPT_STORE_RESULTS: "scripts",
SCRIPT_STORE_NO_RESULTS: "No scripts found",
SCRIPT_STORE_NO_RESULTS_DESC: "Try a different search or category.",
SCRIPT_STORE_DETAILS: "Script details",
SCRIPT_STORE_FEATURED: "Featured",
SCRIPT_STORE_BY: "By",
SCRIPT_STORE_UPDATE_BADGE: "Update",
SCRIPT_STORE_INSTALLED_BADGE: "Installed",
SCRIPT_STORE_CHECK_FAILED: "Check failed",
SCRIPT_STORE_INSTALL: "Install",
SCRIPT_STORE_UPDATE: "Update",
SCRIPT_STORE_REINSTALL: "Reinstall",
SCRIPT_STORE_BACK: "Back to scripts",
SCRIPT_STORE_VIEW_SOURCE: "View source",
SCRIPT_STORE_LOCAL_TITLE: "Installed script",
SCRIPT_STORE_MULTIPLE_COPIES:
"Multiple managed copies found. Update checks use the first copy below. You can open, move, or uninstall each copy separately.",
SCRIPT_STORE_PRIMARY_COPY: "Used for update checks",
SCRIPT_STORE_ADDITIONAL_COPY: "Additional copy",
SCRIPT_STORE_LOCAL_FILE: "Local file",
SCRIPT_STORE_OPEN_LOCAL: "Open local file",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "Could not open the local script file.",
SCRIPT_STORE_JS_OPEN_NOTE:
"JavaScript files are not editable in Obsidian by default. If no plugin provides a .js editor, opening this file may hand it off to an external app.",
SCRIPT_STORE_UNINSTALL: "Uninstall",
SCRIPT_STORE_UNINSTALLED: "Uninstalled",
SCRIPT_STORE_UNINSTALL_FAILED: "Could not uninstall",
SCRIPT_STORE_GROUP_LABEL: "Script group",
SCRIPT_STORE_GROUP_ROOT: "No group (Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "New group name",
SCRIPT_STORE_MOVE_TO_GROUP: "Move",
SCRIPT_STORE_MOVED_TO_GROUP: "Moved script",
SCRIPT_STORE_MOVE_FAILED: "Could not move script",
SCRIPT_INSTALL_PROMPT_FETCH_ERROR:
"Error opening the Excalidraw Script Store page. " +
"Please double check that you can access the website. " +
@@ -1686,7 +1740,7 @@ export default {
//Utils.ts
UPDATE_AVAILABLE: `A newer version of Excalidraw is available in Community Plugins.\n\nYou are using ${PLUGIN_VERSION}.\nThe latest is`,
SCRIPT_UPDATES_AVAILABLE: `Script updates available - check the script store.\n\n${DEVICE.isDesktop ? `This message is available in console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}If you have organized scripts into subfolders under the script store folder and have multiple copies of the same script, you may need to clean up unused versions to clear this alert. For private copies of scripts that should not be updated, store them outside the script store folder.`,
SCRIPT_UPDATES_AVAILABLE: `Script updates available - check the script store.\n\n${DEVICE.isDesktop ? `This message is available in console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}Only community scripts stored under the Downloaded folder are checked for updates. Copies elsewhere in your script folder are ignored.`,
ERROR_PNG_TOO_LARGE:
"Error exporting PNG - PNG too large, try a smaller resolution",
+57 -7
View File
@@ -44,12 +44,6 @@ export default {
EMBEDDABLE_RELATIVE_ZOOM:
"Escalar Elementos Incrustados seleccionados al 100% con respecto al zoom actual del lienzo",
OPEN_IMAGE_SOURCE: "Abrir bosquejo de Excalidraw",
INSTALL_SCRIPT: "Instalar script",
UPDATE_SCRIPT: "Actualización disponible - Click aquí para instalar",
CHECKING_SCRIPT: "Buscando versión más reciente - Click aquí para reinstalar",
UNABLETOCHECK_SCRIPT:
"Fallo en la verificación de actualización - Click aquí para reinstalar",
UPTODATE_SCRIPT: "Script actualizado - Click aquí para reinstalar",
OPEN_AS_EXCALIDRAW: "Abrir como bosquejo de Excalidraw",
TOGGLE_MODE: "Alternar entre modo Excalidraw y Markdown",
DUPLICATE_IMAGE: "Duplicar imagen seleccionada con un ID de imagen diferente",
@@ -1650,7 +1644,7 @@ export default {
//Utils.ts
UPDATE_AVAILABLE: `Hay una versión más nueva de Excalidraw disponible en los Complementos de la Comunidad.\n\nEstás usando la versión ${PLUGIN_VERSION}.\nLa última versión es `,
SCRIPT_UPDATES_AVAILABLE: `Hay actualizaciones de scripts disponibles; revisa la tienda de scripts.\n\n${DEVICE.isDesktop ? `Este mensaje está disponible en console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}Si has organizado los scripts en subcarpetas dentro de la carpeta de la tienda de scripts y tienes varias copias del mismo script, es posible que necesites limpiar las versiones no utilizadas para borrar esta alerta. Para copias privadas de scripts que no deben actualizarse, guárdalas fuera de la carpeta de la tienda de scripts.`,
SCRIPT_UPDATES_AVAILABLE: `Hay actualizaciones de scripts disponibles; revisa la tienda de scripts.\n\n${DEVICE.isDesktop ? `Este mensaje está disponible en console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}Solo se comprueban las actualizaciones de los scripts de la comunidad guardados bajo la carpeta Downloaded. Las copias situadas en otros lugares de la carpeta de scripts se ignoran.`,
ERROR_PNG_TOO_LARGE:
"Error al exportar PNG: El archivo PNG es demasiado grande, intenta una resolución más pequeña.",
@@ -1867,4 +1861,60 @@ Si quieres ver lo que ya es posible hoy, aquí tienes una presentación de las f
//carveout.ts
NEW_DRAWING_TIMEOUT:
"Archivo no encontrado. El nuevo dibujo de Excalidraw está tardando demasiado en crearse. Inténtelo de nuevo.",
SCRIPT_INSTALLED_NOTICE: "Instalado",
SCRIPT_INSTALL_ERROR_NOTICE: "Error al instalar el script",
SCRIPT_STORE_TITLE: "Scripts de la comunidad",
SCRIPT_STORE_LOADING: "Cargando scripts de la comunidad...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "Domina Excalidraw y Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "Invítame a un café",
SCRIPT_STORE_COFFEE_DESC: "Apoya el desarrollo continuo de Excalidraw",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "Automatiza cualquier cosa con scripts de Excalidraw",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION: "Crea tus propios scripts de Excalidraw. Haz clic aquí para saber más.",
SCRIPT_STORE_UPDATES_TITLE: "Actualizaciones disponibles",
SCRIPT_STORE_UPDATES_DESC: "Actualiza los scripts instalados sin buscarlos por todo el catálogo.",
SCRIPT_STORE_UPDATE_ALL: "Actualizar todo",
SCRIPT_STORE_UPDATING: "Actualizando...",
SCRIPT_STORE_UPDATE_ALL_DONE: "Todos los scripts de la comunidad están actualizados.",
SCRIPT_STORE_UPDATE_ALL_PARTIAL: "No se pudieron actualizar algunos scripts. Fallidos:",
SCRIPT_STORE_BROWSE_TITLE: "Explorar scripts",
SCRIPT_STORE_BROWSE_DESC: "Busca por nombre, autor, descripción o categoría.",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "Buscar scripts de la comunidad",
SCRIPT_STORE_CATEGORY_LABEL: "Categoría del script",
SCRIPT_STORE_ALL_CATEGORIES: "Todas las categorías",
SCRIPT_STORE_ALL_SCRIPTS: "Todos",
SCRIPT_STORE_INSTALLED_SCRIPTS: "Instalados",
SCRIPT_STORE_RESULTS: "scripts",
SCRIPT_STORE_NO_RESULTS: "No se encontraron scripts",
SCRIPT_STORE_NO_RESULTS_DESC: "Prueba otra búsqueda o categoría.",
SCRIPT_STORE_DETAILS: "Detalles del script",
SCRIPT_STORE_FEATURED: "Destacado",
SCRIPT_STORE_BY: "Por",
SCRIPT_STORE_UPDATE_BADGE: "Actualizar",
SCRIPT_STORE_INSTALLED_BADGE: "Instalado",
SCRIPT_STORE_CHECK_FAILED: "Falló la comprobación",
SCRIPT_STORE_INSTALL: "Instalar",
SCRIPT_STORE_UPDATE: "Actualizar",
SCRIPT_STORE_REINSTALL: "Reinstalar",
SCRIPT_STORE_BACK: "Volver a scripts",
SCRIPT_STORE_VIEW_SOURCE: "Ver código fuente",
SCRIPT_STORE_LOCAL_TITLE: "Script instalado",
SCRIPT_STORE_MULTIPLE_COPIES:
"Se encontraron varias copias administradas. Las comprobaciones de actualización usan la primera copia. Puedes abrir, mover o desinstalar cada copia por separado.",
SCRIPT_STORE_PRIMARY_COPY: "Usada para comprobar actualizaciones",
SCRIPT_STORE_ADDITIONAL_COPY: "Copia adicional",
SCRIPT_STORE_LOCAL_FILE: "Archivo local",
SCRIPT_STORE_OPEN_LOCAL: "Abrir archivo local",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "No se pudo abrir el archivo local del script.",
SCRIPT_STORE_JS_OPEN_NOTE:
"Obsidian no permite editar archivos JavaScript de forma predeterminada. Si ningún plugin proporciona un editor .js, el archivo puede abrirse en una aplicación externa.",
SCRIPT_STORE_UNINSTALL: "Desinstalar",
SCRIPT_STORE_UNINSTALLED: "Desinstalado",
SCRIPT_STORE_UNINSTALL_FAILED: "No se pudo desinstalar",
SCRIPT_STORE_GROUP_LABEL: "Grupo de scripts",
SCRIPT_STORE_GROUP_ROOT: "Sin grupo (Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "Nombre del nuevo grupo",
SCRIPT_STORE_MOVE_TO_GROUP: "Mover",
SCRIPT_STORE_MOVED_TO_GROUP: "Script movido",
SCRIPT_STORE_MOVE_FAILED: "No se pudo mover el script",
};
+57 -7
View File
@@ -38,13 +38,6 @@ export default {
EMBEDDABLE_RELATIVE_ZOOM:
"Масштабирование выбранных встраиваемых элементов до 100% относительно текущего масштаба холста",
OPEN_IMAGE_SOURCE: "Открыть чертеж Excalidraw",
INSTALL_SCRIPT: "Установите скрипт",
UPDATE_SCRIPT: "Доступно обновление - нажмите для установки",
CHECKING_SCRIPT:
"Проверка на наличие новой версии - Нажмите для переустановки",
UNABLETOCHECK_SCRIPT:
"Проверка обновления не удалась - Нажмите, чтобы переустановить",
UPTODATE_SCRIPT: "Скрипт обновлен - Нажмите для переустановки",
OPEN_AS_EXCALIDRAW: "Открыть как рисунок Excalidraw",
TOGGLE_MODE: "Переключение между режимами Excalidraw и Markdown",
CONVERT_NOTE_TO_EXCALIDRAW:
@@ -1509,4 +1502,61 @@ export default {
//carveout.ts
NEW_DRAWING_TIMEOUT:
"Файл не найден. Создание нового рисунка Excalidraw занимает слишком много времени. Пожалуйста, попробуйте снова.",
SCRIPT_INSTALLED_NOTICE: "Установлено",
SCRIPT_INSTALL_ERROR_NOTICE: "Ошибка установки скрипта",
SCRIPT_STORE_TITLE: "Скрипты сообщества",
SCRIPT_STORE_LOADING: "Загрузка скриптов сообщества...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "Освойте Excalidraw и Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "Купить мне кофе",
SCRIPT_STORE_COFFEE_DESC: "Поддержать дальнейшую разработку Excalidraw",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "Автоматизируйте что угодно с помощью скриптов Excalidraw",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION: "Создавайте собственные скрипты Excalidraw. Нажмите, чтобы узнать больше.",
SCRIPT_STORE_UPDATES_TITLE: "Доступны обновления",
SCRIPT_STORE_UPDATES_DESC: "Обновляйте установленные скрипты без поиска по каталогу.",
SCRIPT_STORE_UPDATE_ALL: "Обновить все",
SCRIPT_STORE_UPDATING: "Обновление...",
SCRIPT_STORE_UPDATE_ALL_DONE: "Все скрипты сообщества обновлены.",
SCRIPT_STORE_UPDATE_ALL_PARTIAL: "Некоторые скрипты не удалось обновить. Ошибок:",
SCRIPT_STORE_BROWSE_TITLE: "Обзор скриптов",
SCRIPT_STORE_BROWSE_DESC: "Ищите по названию, автору, описанию или категории.",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "Поиск скриптов сообщества",
SCRIPT_STORE_CATEGORY_LABEL: "Категория скрипта",
SCRIPT_STORE_ALL_CATEGORIES: "Все категории",
SCRIPT_STORE_ALL_SCRIPTS: "Все",
SCRIPT_STORE_INSTALLED_SCRIPTS: "Установленные",
SCRIPT_STORE_RESULTS: "скриптов",
SCRIPT_STORE_NO_RESULTS: "Скрипты не найдены",
SCRIPT_STORE_NO_RESULTS_DESC: "Попробуйте другой запрос или категорию.",
SCRIPT_STORE_DETAILS: "Сведения о скрипте",
SCRIPT_STORE_FEATURED: "Избранное",
SCRIPT_STORE_BY: "Автор",
SCRIPT_STORE_UPDATE_BADGE: "Обновление",
SCRIPT_STORE_INSTALLED_BADGE: "Установлен",
SCRIPT_STORE_CHECK_FAILED: "Проверка не удалась",
SCRIPT_STORE_INSTALL: "Установить",
SCRIPT_STORE_UPDATE: "Обновить",
SCRIPT_STORE_REINSTALL: "Переустановить",
SCRIPT_STORE_BACK: "Назад к скриптам",
SCRIPT_STORE_VIEW_SOURCE: "Открыть исходник",
SCRIPT_STORE_LOCAL_TITLE: "Установленный скрипт",
SCRIPT_STORE_MULTIPLE_COPIES:
"Найдено несколько управляемых копий. Для проверки обновлений используется первая копия. Каждую копию можно открыть, переместить или удалить отдельно.",
SCRIPT_STORE_PRIMARY_COPY: "Используется для проверки обновлений",
SCRIPT_STORE_ADDITIONAL_COPY: "Дополнительная копия",
SCRIPT_STORE_LOCAL_FILE: "Локальный файл",
SCRIPT_STORE_OPEN_LOCAL: "Открыть локальный файл",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "Не удалось открыть локальный файл скрипта.",
SCRIPT_STORE_JS_OPEN_NOTE:
"По умолчанию Obsidian не редактирует JavaScript-файлы. Если ни один плагин не предоставляет редактор .js, файл может открыться во внешнем приложении.",
SCRIPT_STORE_UNINSTALL: "Удалить",
SCRIPT_STORE_UNINSTALLED: "Удалено",
SCRIPT_STORE_UNINSTALL_FAILED: "Не удалось удалить",
SCRIPT_STORE_GROUP_LABEL: "Группа скриптов",
SCRIPT_STORE_GROUP_ROOT: "Без группы (Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "Имя новой группы",
SCRIPT_STORE_MOVE_TO_GROUP: "Переместить",
SCRIPT_STORE_MOVED_TO_GROUP: "Скрипт перемещён",
SCRIPT_STORE_MOVE_FAILED: "Не удалось переместить скрипт",
SCRIPT_UPDATES_AVAILABLE: `Доступны обновления скриптов — проверьте магазин скриптов.\n\n${DEVICE.isDesktop ? `Это сообщение доступно в console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}Проверяются только скрипты сообщества, находящиеся в папке Downloaded. Копии в других местах папки скриптов игнорируются.`,
};
+57 -6
View File
@@ -37,11 +37,6 @@ export default {
EMBEDDABLE_PROPERTIES: "Embeddable 元素设置",
EMBEDDABLE_RELATIVE_ZOOM: "使元素的缩放级别等于当前绘图的缩放级别",
OPEN_IMAGE_SOURCE: "打开 Excalidraw 绘图",
INSTALL_SCRIPT: "安装此脚本",
UPDATE_SCRIPT: "有可用更新 - 点击安装",
CHECKING_SCRIPT: "检查更新中 - 点击重新安装",
UNABLETOCHECK_SCRIPT: "检查更新失败 - 点击重新安装",
UPTODATE_SCRIPT: "脚本已是最新 - 点击重新安装",
OPEN_AS_EXCALIDRAW: "打开为 Excalidraw 绘图",
TOGGLE_MODE: "在 Excalidraw 和 Markdown 模式之间切换",
DUPLICATE_IMAGE: "复制所选图像,并分配一个不同的图像 ID",
@@ -1577,7 +1572,7 @@ export default {
//Utils.ts
UPDATE_AVAILABLE: `Excalidraw 的新版本已在社区插件中可用。\n\n您正在使用 ${PLUGIN_VERSION}。\n最新版本是`,
SCRIPT_UPDATES_AVAILABLE: `脚本更新可用 - 请检查脚本存储。\n\n${DEVICE.isDesktop ? `此消息可在控制台日志中查看 (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}如果您已将脚本组织到脚本存储文件夹下的子文件夹中,并且存在同一脚本的多个副本,可能需要清理未使用的版本以消除此警报。对于无需更新的私人脚本副本,请将它们存储在脚本存储文件夹之外。`,
SCRIPT_UPDATES_AVAILABLE: `脚本更新可用 - 请检查脚本存储。\n\n${DEVICE.isDesktop ? `此消息可在控制台日志中查看 (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}只检查 Downloaded 文件夹下的社区脚本更新。脚本文件夹中其他位置的副本会被忽略。`,
ERROR_PNG_TOO_LARGE: "导出 PNG 时出错 - PNG 文件过大,请尝试较小的分辨率",
//modifierkeyHelper.ts
@@ -1820,4 +1815,60 @@ Obsidian 的 Excalidraw 插件远不只是画图工具。由于它与 Obsidian
//carveout.ts
NEW_DRAWING_TIMEOUT: "未找到文件。新建 Excalidraw 绘图耗时过长。请重试。",
SCRIPT_INSTALLED_NOTICE: "已安装",
SCRIPT_INSTALL_ERROR_NOTICE: "脚本安装失败",
SCRIPT_STORE_TITLE: "社区脚本",
SCRIPT_STORE_LOADING: "正在加载社区脚本...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "掌握 Excalidraw 与 Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "请我喝杯咖啡",
SCRIPT_STORE_COFFEE_DESC: "支持 Excalidraw 持续开发",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "用 Excalidraw 脚本自动化任何事情",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION: "创建你自己的 Excalidraw 脚本。点击这里了解更多。",
SCRIPT_STORE_UPDATES_TITLE: "有可用更新",
SCRIPT_STORE_UPDATES_DESC: "无需在目录中逐个查找,即可更新已安装的社区脚本。",
SCRIPT_STORE_UPDATE_ALL: "全部更新",
SCRIPT_STORE_UPDATING: "正在更新...",
SCRIPT_STORE_UPDATE_ALL_DONE: "所有社区脚本均已是最新版本。",
SCRIPT_STORE_UPDATE_ALL_PARTIAL: "部分脚本无法更新。失败数量:",
SCRIPT_STORE_BROWSE_TITLE: "浏览脚本",
SCRIPT_STORE_BROWSE_DESC: "可按名称、作者、描述或分类搜索。",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "搜索社区脚本",
SCRIPT_STORE_CATEGORY_LABEL: "脚本分类",
SCRIPT_STORE_ALL_CATEGORIES: "全部分类",
SCRIPT_STORE_ALL_SCRIPTS: "全部",
SCRIPT_STORE_INSTALLED_SCRIPTS: "已安装",
SCRIPT_STORE_RESULTS: "个脚本",
SCRIPT_STORE_NO_RESULTS: "未找到脚本",
SCRIPT_STORE_NO_RESULTS_DESC: "请尝试其他搜索词或分类。",
SCRIPT_STORE_DETAILS: "脚本详情",
SCRIPT_STORE_FEATURED: "精选",
SCRIPT_STORE_BY: "作者",
SCRIPT_STORE_UPDATE_BADGE: "更新",
SCRIPT_STORE_INSTALLED_BADGE: "已安装",
SCRIPT_STORE_CHECK_FAILED: "检查失败",
SCRIPT_STORE_INSTALL: "安装",
SCRIPT_STORE_UPDATE: "更新",
SCRIPT_STORE_REINSTALL: "重新安装",
SCRIPT_STORE_BACK: "返回脚本列表",
SCRIPT_STORE_VIEW_SOURCE: "查看源代码",
SCRIPT_STORE_LOCAL_TITLE: "已安装脚本",
SCRIPT_STORE_MULTIPLE_COPIES:
"发现多个受管理的副本。更新检查使用下面的第一个副本。你可以分别打开、移动或卸载每个副本。",
SCRIPT_STORE_PRIMARY_COPY: "用于更新检查",
SCRIPT_STORE_ADDITIONAL_COPY: "其他副本",
SCRIPT_STORE_LOCAL_FILE: "本地文件",
SCRIPT_STORE_OPEN_LOCAL: "打开本地文件",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "无法打开本地脚本文件。",
SCRIPT_STORE_JS_OPEN_NOTE:
"Obsidian 默认不支持编辑 JavaScript 文件。如果没有插件提供 .js 编辑器,打开文件时可能会交给外部应用。",
SCRIPT_STORE_UNINSTALL: "卸载",
SCRIPT_STORE_UNINSTALLED: "已卸载",
SCRIPT_STORE_UNINSTALL_FAILED: "无法卸载",
SCRIPT_STORE_GROUP_LABEL: "脚本分组",
SCRIPT_STORE_GROUP_ROOT: "不分组(Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "新分组名称",
SCRIPT_STORE_MOVE_TO_GROUP: "移动",
SCRIPT_STORE_MOVED_TO_GROUP: "脚本已移动",
SCRIPT_STORE_MOVE_FAILED: "无法移动脚本",
};
+57 -6
View File
@@ -37,11 +37,6 @@ export default {
EMBEDDABLE_PROPERTIES: "Embeddable 元素設定",
EMBEDDABLE_RELATIVE_ZOOM: "使元素的縮放級別等於當前繪圖的縮放級別",
OPEN_IMAGE_SOURCE: "開啟 Excalidraw 繪圖",
INSTALL_SCRIPT: "安裝此指令碼",
UPDATE_SCRIPT: "有可用更新 - 點選安裝",
CHECKING_SCRIPT: "檢查更新中 - 點選重新安裝",
UNABLETOCHECK_SCRIPT: "檢查更新失敗 - 點選重新安裝",
UPTODATE_SCRIPT: "指令碼已是最新 - 點選重新安裝",
OPEN_AS_EXCALIDRAW: "開啟為 Excalidraw 繪圖",
TOGGLE_MODE: "在 Excalidraw 和 Markdown 模式之間切換",
DUPLICATE_IMAGE: "複製所選影像,並分配一個不同的影像 ID",
@@ -1577,7 +1572,7 @@ export default {
//Utils.ts
UPDATE_AVAILABLE: `Excalidraw 的新版本已在社群外掛中可用。\n\n您正在使用 ${PLUGIN_VERSION}。\n最新版本是`,
SCRIPT_UPDATES_AVAILABLE: `指令碼更新可用 - 請檢查指令碼儲存。\n\n${DEVICE.isDesktop ? `此訊息可在控制台日誌中檢視 (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}如果您已將指令碼組織到指令碼儲存資料夾下的子資料夾中,並且存在同一指令碼的多個副本,可能需要清理未使用的版本以消除此警報。對於無需更新的私人指令碼副本,請將它們儲存在指令碼儲存資料夾之外。`,
SCRIPT_UPDATES_AVAILABLE: `指令碼更新可用 - 請檢查指令碼儲存。\n\n${DEVICE.isDesktop ? `此訊息可在控制台日誌中檢視 (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}只檢查 Downloaded 資料夾下的社群指令碼更新。指令碼資料夾中其他位置的副本會被忽略。`,
ERROR_PNG_TOO_LARGE: "匯出 PNG 時出錯 - PNG 檔案過大,請嘗試較小的解析度",
//modifierkeyHelper.ts
@@ -1820,4 +1815,60 @@ Obsidian 的 Excalidraw 外掛遠不只是畫圖工具。由於它與 Obsidian
//carveout.ts
NEW_DRAWING_TIMEOUT: "找不到檔案。建立新的 Excalidraw 繪圖耗時過長。請重試。",
SCRIPT_INSTALLED_NOTICE: "已安裝",
SCRIPT_INSTALL_ERROR_NOTICE: "指令碼安裝失敗",
SCRIPT_STORE_TITLE: "社群指令碼",
SCRIPT_STORE_LOADING: "正在載入社群指令碼...",
SCRIPT_STORE_MASTERY_TITLE: "Excalidraw Mastery",
SCRIPT_STORE_MASTERY_DESC: "掌握 Excalidraw 與 Visual PKM",
SCRIPT_STORE_COFFEE_TITLE: "請我喝杯咖啡",
SCRIPT_STORE_COFFEE_DESC: "支持 Excalidraw 持續開發",
SCRIPT_STORE_SCRIPTING_BANNER_ALT: "用 Excalidraw 指令碼自動化任何事情",
SCRIPT_STORE_SCRIPTING_BANNER_CAPTION: "建立你自己的 Excalidraw 指令碼。點擊這裡了解更多。",
SCRIPT_STORE_UPDATES_TITLE: "有可用更新",
SCRIPT_STORE_UPDATES_DESC: "不必逐一翻找目錄,就能更新已安裝的社群指令碼。",
SCRIPT_STORE_UPDATE_ALL: "全部更新",
SCRIPT_STORE_UPDATING: "正在更新...",
SCRIPT_STORE_UPDATE_ALL_DONE: "所有社群指令碼都已是最新版本。",
SCRIPT_STORE_UPDATE_ALL_PARTIAL: "部分指令碼無法更新。失敗數量:",
SCRIPT_STORE_BROWSE_TITLE: "瀏覽指令碼",
SCRIPT_STORE_BROWSE_DESC: "可依名稱、作者、描述或分類搜尋。",
SCRIPT_STORE_SEARCH_PLACEHOLDER: "搜尋社群指令碼",
SCRIPT_STORE_CATEGORY_LABEL: "指令碼分類",
SCRIPT_STORE_ALL_CATEGORIES: "全部分類",
SCRIPT_STORE_ALL_SCRIPTS: "全部",
SCRIPT_STORE_INSTALLED_SCRIPTS: "已安裝",
SCRIPT_STORE_RESULTS: "個指令碼",
SCRIPT_STORE_NO_RESULTS: "找不到指令碼",
SCRIPT_STORE_NO_RESULTS_DESC: "請嘗試其他搜尋詞或分類。",
SCRIPT_STORE_DETAILS: "指令碼詳細資料",
SCRIPT_STORE_FEATURED: "精選",
SCRIPT_STORE_BY: "作者",
SCRIPT_STORE_UPDATE_BADGE: "更新",
SCRIPT_STORE_INSTALLED_BADGE: "已安裝",
SCRIPT_STORE_CHECK_FAILED: "檢查失敗",
SCRIPT_STORE_INSTALL: "安裝",
SCRIPT_STORE_UPDATE: "更新",
SCRIPT_STORE_REINSTALL: "重新安裝",
SCRIPT_STORE_BACK: "返回指令碼列表",
SCRIPT_STORE_VIEW_SOURCE: "檢視原始碼",
SCRIPT_STORE_LOCAL_TITLE: "已安裝指令碼",
SCRIPT_STORE_MULTIPLE_COPIES:
"找到多個受管理的副本。更新檢查使用下方第一個副本。你可以分別開啟、移動或解除安裝每個副本。",
SCRIPT_STORE_PRIMARY_COPY: "用於更新檢查",
SCRIPT_STORE_ADDITIONAL_COPY: "其他副本",
SCRIPT_STORE_LOCAL_FILE: "本機檔案",
SCRIPT_STORE_OPEN_LOCAL: "開啟本機檔案",
SCRIPT_STORE_OPEN_LOCAL_FAILED: "無法開啟本機指令碼檔案。",
SCRIPT_STORE_JS_OPEN_NOTE:
"Obsidian 預設不支援編輯 JavaScript 檔案。如果沒有外掛提供 .js 編輯器,開啟檔案時可能會交給外部應用程式。",
SCRIPT_STORE_UNINSTALL: "解除安裝",
SCRIPT_STORE_UNINSTALLED: "已解除安裝",
SCRIPT_STORE_UNINSTALL_FAILED: "無法解除安裝",
SCRIPT_STORE_GROUP_LABEL: "指令碼群組",
SCRIPT_STORE_GROUP_ROOT: "不分組(Downloaded)",
SCRIPT_STORE_NEW_GROUP_PLACEHOLDER: "新群組名稱",
SCRIPT_STORE_MOVE_TO_GROUP: "移動",
SCRIPT_STORE_MOVED_TO_GROUP: "指令碼已移動",
SCRIPT_STORE_MOVE_FAILED: "無法移動指令碼",
};
+38 -11
View File
@@ -17,27 +17,53 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.29.0": `
## Fixed
- Back-of-the-note embeds now wait for initialization so they display the linked Markdown section instead of the whole drawing. 🙏[askalf](${URLs.GITHUB_COM}/askalf) [#2931](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2931)
`,
"2.28.1": `
Re-released due to a minor deployment hiccup, hopefully fixed now.
`,
"2.28.0": `
**Note to ExcaliBrain users:** Update ExcaliBrain. Excalidraw 2.28.0 breaks compatibility with ExcaliBrain v0.2.18.
## New
- Copied Markdown image SVGs now replace embedded base64 images and fonts with short placeholders, making them smaller and easier to share with AI agents when developing custom CSS.
- A brand new and improved Community Script Store. [#2944](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2944)
- When you copy the Markdown Image SVGs for Image CSS AI prompting, the SVG now replace embedded base64 images and fonts with short placeholders, making them smaller and easier to share with agents.
## New from Excalidraw.com
- Create sticky notes with the new **Sticky note** tool or the **N** shortcut. Labels automatically fit and grow with their note, with dedicated colors and a creation-date footer. [#12064](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12064)
- Right click panning (without enabling a specific "Miro-style" setting) is now supported. [#12110](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12110)
## New in Excalidraw Automate
- Scripts can create native sticky notes, including automatically fitted labels:
\`\`\`ts
addStickyNote(topX: number, topY: number, text: string, formatting?: {width?: number; height?: number; fontSize?: number; fontFamily?: number; textAlign?: "left" | "center" | "right"; textVerticalAlign?: "top" | "middle" | "bottom";}, id?: string): string;
\`\`\`
- Create sticky notes with the new **Sticky note** tool or the **N** shortcut. [#12064](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12064)
- Right click panning. [#12110](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12110)
- Customize font toppicks by drag and drop. To set them as default save your toppick choices as a template. [#12160](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12160)
## Fixed / Refactored
- Lasso tool was not available in the More Tools menu in Tray Mode [#2937](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2937)
- \`.excalidraw\` drawings with embedded binary images now render those images when opened into an already-used Excalidraw tab. [#2929](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2929)
- Descriptions in settings no longer disappear when you revisit a settings page from search results. [#2935](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2935)
- Drawing persistence is now more reliable during rapid edits across multiple tabs, popout moves, and immediate closing. Backups and automatic exports now track the exact successfully saved revision. [#2933](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2933)
- Rapidly changing Markdown image appearance, selection, or image/embeddable conversion no longer leaves a rejected image-render promise in the console or lets a superseded render overwrite the newer element state.
- Improved saving and backupts. [#2933](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2933)
- Fixed a bug where, with *"Render Excalidraw as Image in Obsidian PDF Export"* enabled, exporting a Hybrid Note (an Excalidraw drawing with your own Markdown content alongside it) to PDF could render blank sections wherever a regular image (or other non-Excalidraw) embed appeared on the Markdown side. [#2292](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2292), 🙏[bluechallenge](${URLs.GITHUB_COM}/bluechallenge) [#2936](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2936)
- Selection rectangles in popout windows are no longer positioned incorrectly when displays use different DPI settings. [#2940](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2940)
## New/Fixed in Excalidraw Automate
- Updated the [ea-script-template](${URLs.GITHUB_COM}/zsviczian/ea-script-template). Read [EA Script prompting with AI is magical](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}/t/10977)
- Enhancements to support K-Plex and ExcaliBrain integration.
\`\`\`ts
public async toggleViewMode(view: View): Promise<View | null>;
registerViewLinkClickHook(hook: ViewLinkClickHook): () => void;
viewZoomToFit(): void;
clearViewDirty(): void;
registerThisAsViewEA(): boolean;
deregisterThisAsViewEA(): boolean;
\`\`\`
- Excalidraw view state accepts one-shot \`mode: "view" | "edit"\` and \`zoomToFit: true\` options. This lets host integrations open a drawing in its intended mode without polling the React canvas.
- Link-open callbacks now receive a usable native event even when an upstream synthesized event omitted it.
- Scripts can create native sticky notes, including automatically fitted labels:
\`\`\`ts
addStickyNote(topX: number, topY: number, text: string, formatting?: {width?: number; height?: number; fontSize?: number; fontFamily?: number; textAlign?: "left" | "center" | "right"; textVerticalAlign?: "top" | "middle" | "bottom";}, id?: string): string;
\`\`\`
- Unbound arrows created with Excalidraw Automate's \`addArrow()\` no longer contain incomplete binding data that could cause an error when selected.
`,
"2.27.3": `
## Fixed and updated
@@ -219,6 +245,7 @@ ${getYouTubeDiv("aqt5NJE2sJ8")}
- Fixed the "Customize the Embedded File Link" action. If you change the dimensions of the markdown image or the pdf page reference number, the image immediately updates in the scene. You can also use this feature to swap out images e.g. a png icon to an SVG icon. Default shortcut is CTRL+WIN+Click or CMD+Control+Click on the image element.
- LaTeX and Mermaid did not work on iOS. Released updated Excalidraw Extras and bumped the minimum required version to 0.0.15. [#2825](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2825)
- Malformed "Source" URL in ExcalidrawLib and Excalidraw Data json. [#2826]${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2826)
- Markdown-image editor did not function if Obsidian default for new tabs was set to preview mode.
## New in ExcalidrawAutomate
- Added \`onSceneChangeHook\` to allow scripts and sidepanel tabs to react to scene changes. The hook supports filtering by \`appStateKeys\` and checking for tab visibility to optimize performance.
+919 -49
View File
@@ -1,68 +1,938 @@
import { Component, MarkdownRenderer, Modal, Notice, request } from "obsidian";
import ExcalidrawPlugin from "../../core/main";
import {
Modal,
Notice,
normalizePath,
request,
setIcon,
} from "obsidian";
import { SCRIPT_INSTALL_FOLDER } from "../../constants/constants";
import {
getPluginRepositoryBlobUrl,
getPluginRepositoryRawUrl,
URLs,
} from "../../constants/safeUrls";
import { t } from "../../lang/helpers";
import type {
ScriptStoreCatalog,
ScriptStoreEntry,
ScriptStoreInstallState,
} from "../../types/scriptStoreTypes";
import { sanitizedFragment, setSanitizedHtml } from "../../utils/htmlUtils";
import {
getInstalledScriptFiles,
getInstalledScriptGroups,
getScriptInstallStates,
installScript,
moveInstalledScriptToGroup,
uninstallScript,
type ScriptLibraryPluginContext,
} from "../../utils/scriptLibraryUtils";
import { errorlog } from "../../utils/utils";
import { log } from "src/utils/debugHelper";
import { ContentSearcher } from "../components/ContentSearcher";
import { URLs } from "src/constants/safeUrls";
import { t } from "src/lang/helpers";
const URL =
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD;
const CATALOG_URL =
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_SCRIPT_STORE_JSON;
const FEATURED_CATEGORY = "Editors Picks";
type StoreView = "all" | "installed";
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null;
const isUnknownArray = (value: unknown): value is unknown[] =>
Array.isArray(value);
const isStringArray = (value: unknown): value is string[] =>
isUnknownArray(value) &&
value.every((item: unknown) => typeof item === "string");
const isScriptStoreEntry = (value: unknown): value is ScriptStoreEntry =>
isRecord(value) &&
typeof value.name === "string" &&
typeof value.file === "string" &&
typeof value.installUrl === "string" &&
typeof value.iconUrl === "string" &&
typeof value.author === "string" &&
typeof value.authorUrl === "string" &&
typeof value.sourceUrl === "string" &&
typeof value.descriptionHtml === "string" &&
isStringArray(value.categories) &&
(value.featuredRank === undefined || typeof value.featuredRank === "number");
const isScriptStoreCategory = (
value: unknown,
): value is ScriptStoreCatalog["categories"][number] =>
isRecord(value) &&
typeof value.name === "string" &&
typeof value.description === "string";
const parseScriptStoreCatalog = (source: string): ScriptStoreCatalog => {
const parsed: unknown = JSON.parse(source) as unknown;
if (
!isRecord(parsed) ||
parsed.version !== 1 ||
!isUnknownArray(parsed.scripts) ||
!parsed.scripts.every(isScriptStoreEntry) ||
!isUnknownArray(parsed.categories) ||
!parsed.categories.every(isScriptStoreCategory)
) {
throw new Error("Unsupported script store catalog");
}
return {
version: parsed.version,
scripts: parsed.scripts,
categories: parsed.categories,
};
};
const getScriptInstallUrl = (entry: ScriptStoreEntry): string =>
getPluginRepositoryRawUrl(`ea-scripts/${entry.file}`);
const getScriptIconUrl = (entry: ScriptStoreEntry): string =>
getPluginRepositoryRawUrl(
`ea-scripts/${entry.file.replace(/\.(?:md|js)$/i, ".svg")}`,
);
const getScriptSourceUrl = (entry: ScriptStoreEntry): string =>
getPluginRepositoryBlobUrl(`ea-scripts/${entry.file}`);
export class ScriptInstallPrompt extends Modal {
private contentDiv: HTMLDivElement;
private renderComponent: Component;
private catalog: ScriptStoreCatalog | null = null;
private installStates = new Map<string, ScriptStoreInstallState>();
private descriptionText = new Map<string, string>();
private selectedCategory = "";
private searchQuery = "";
private storeView: StoreView = "all";
constructor(private plugin: ExcalidrawPlugin) {
constructor(private plugin: ScriptLibraryPluginContext) {
super(plugin.app);
// this.titleEl.setText(t("INSTAL_MODAL_TITLE"));
}
onOpen(): void {
this.renderComponent = new Component();
this.renderComponent.load();
this.contentEl.classList.add("excalidraw-scriptengine-install");
this.contentDiv = this.contentEl.createDiv();
this.titleEl.setText(t("SCRIPT_STORE_TITLE"));
this.contentEl.classList.add(
"excalidraw-scriptengine-install",
"excalidraw-script-store",
);
this.containerEl.classList.add(
"excalidraw-scriptengine-install",
"excalidraw-script-store",
);
this.contentDiv = this.contentEl.createDiv({
cls: "excalidraw-script-store__content",
});
this.renderLoading();
void this.loadStore();
}
new ContentSearcher(this.contentDiv);
private renderLoading(): void {
this.contentDiv.replaceChildren();
const loading = this.contentDiv.createDiv({
cls: "excalidraw-script-store__loading",
});
const icon = loading.createSpan({
cls: "excalidraw-script-store__loading-icon",
});
setIcon(icon, "loader-circle");
loading.createSpan({ text: t("SCRIPT_STORE_LOADING") });
}
this.containerEl.classList.add("excalidraw-scriptengine-install");
void (async () => {
private async loadStore(): Promise<void> {
try {
const source = await request({ url: CATALOG_URL });
this.catalog = parseScriptStoreCatalog(source);
await this.refreshInstallStates();
this.renderStore();
} catch (error: unknown) {
errorlog({ where: "ScriptInstallPrompt.loadStore", error });
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
this.close();
}
}
private async refreshInstallStates(): Promise<void> {
if (!this.catalog) {
return;
}
const sources = this.catalog.scripts.map((entry) =>
getScriptInstallUrl(entry),
);
const states = await getScriptInstallStates(this.plugin, sources);
this.installStates = new Map(
this.catalog.scripts.map((entry, index) => [
entry.name,
states.get(sources[index]) ?? "error",
]),
);
}
private renderStore(): void {
if (!this.catalog) {
return;
}
this.contentDiv.replaceChildren();
this.renderSupportBar();
this.renderScriptingBanner();
this.renderUpdates();
this.renderBrowseControls();
this.renderScriptGrid();
}
private renderSupportBar(): void {
const support = this.contentDiv.createDiv({
cls: "excalidraw-script-store__support-bar",
});
const mastery = support.createEl("a", {
href: URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM,
cls: "excalidraw-script-store__support-item",
attr: { target: "_blank", rel: "noopener noreferrer" },
});
mastery.createEl("img", {
cls: "excalidraw-script-store__support-logo",
attr: {
src: URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EM_PNG,
alt: t("SCRIPT_STORE_MASTERY_TITLE"),
loading: "lazy",
},
});
const masteryText = mastery.createDiv({
cls: "excalidraw-script-store__support-text",
});
masteryText.createEl("strong", { text: t("SCRIPT_STORE_MASTERY_TITLE") });
masteryText.createSpan({ text: t("SCRIPT_STORE_MASTERY_DESC") });
const coffee = support.createEl("a", {
href: URLs.KO_FI_COM_ZSOLT,
cls: "excalidraw-script-store__support-item",
attr: { target: "_blank", rel: "noopener noreferrer" },
});
const coffeeIcon = coffee.createSpan({
cls: "excalidraw-script-store__support-icon",
});
setIcon(coffeeIcon, "coffee");
const coffeeText = coffee.createDiv({
cls: "excalidraw-script-store__support-text",
});
coffeeText.createEl("strong", { text: t("SCRIPT_STORE_COFFEE_TITLE") });
coffeeText.createSpan({ text: t("SCRIPT_STORE_COFFEE_DESC") });
}
private renderScriptingBanner(): void {
const section = this.contentDiv.createDiv({
cls: "excalidraw-script-store__scripting-promo",
});
const link = section.createEl("a", {
href: URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPTING_MD,
cls: "excalidraw-script-store__scripting-link",
attr: { target: "_blank", rel: "noopener noreferrer" },
});
link.createEl("img", {
cls: "excalidraw-script-store__scripting-banner",
attr: {
src: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_IMAGE_BANNER_AUTOMATE_ANYTHING_PNG,
alt: t("SCRIPT_STORE_SCRIPTING_BANNER_ALT"),
loading: "lazy",
},
});
link.createDiv({
cls: "excalidraw-script-store__scripting-caption",
text: t("SCRIPT_STORE_SCRIPTING_BANNER_CAPTION"),
});
}
private getUpdates(): ScriptStoreEntry[] {
return (
this.catalog?.scripts.filter(
(entry) => this.installStates.get(entry.name) === "update",
) ?? []
);
}
private renderUpdates(): void {
const updates = this.getUpdates();
if (updates.length === 0) {
return;
}
const section = this.contentDiv.createDiv({
cls: "excalidraw-script-store__updates",
});
const header = section.createDiv({
cls: "excalidraw-script-store__updates-header",
});
const titleWrap = header.createDiv();
const title = titleWrap.createEl("h2", {
text: `${t("SCRIPT_STORE_UPDATES_TITLE")} (${updates.length})`,
});
const icon = title.createSpan({
cls: "excalidraw-script-store__inline-icon",
});
setIcon(icon, "circle-arrow-up");
titleWrap.createEl("p", { text: t("SCRIPT_STORE_UPDATES_DESC") });
const updateAll = header.createEl("button", {
text: t("SCRIPT_STORE_UPDATE_ALL"),
cls: "mod-cta",
type: "button",
});
updateAll.addEventListener("click", () => {
void this.updateAll(updateAll);
});
const list = section.createDiv({
cls: "excalidraw-script-store__update-list",
});
updates.forEach((entry) => {
const button = list.createEl("button", {
text: entry.name,
cls: "excalidraw-script-store__update-chip",
type: "button",
});
button.addEventListener("click", () => this.renderDetail(entry));
});
}
private async updateAll(button: HTMLButtonElement): Promise<void> {
const updates = this.getUpdates();
if (updates.length === 0) {
return;
}
button.disabled = true;
button.setText(t("SCRIPT_STORE_UPDATING"));
let failures = 0;
for (const entry of updates) {
try {
const source = await request({ url: URL });
if (!source) {
new Notice(t("SCRIPT_INSTALL_PROMPT_FETCH_ERROR"), 5000);
log(URL);
this.close();
return;
}
await MarkdownRenderer.render(
this.plugin.app,
source,
this.contentDiv,
"",
this.renderComponent,
);
this.contentDiv
.querySelectorAll(
"h1[data-heading],h2[data-heading],h3[data-heading]",
)
.forEach((el) => {
el.setAttribute("id", el.getAttribute("data-heading"));
});
this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => {
el.removeAttribute("target");
});
} catch (e: unknown) {
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e });
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
this.close();
await installScript(this.plugin, getScriptInstallUrl(entry), false);
this.installStates.set(entry.name, "up-to-date");
} catch {
failures += 1;
this.installStates.set(entry.name, "error");
}
})();
}
new Notice(
failures === 0
? t("SCRIPT_STORE_UPDATE_ALL_DONE")
: `${t("SCRIPT_STORE_UPDATE_ALL_PARTIAL")} ${failures}`,
);
this.renderStore();
}
private renderBrowseControls(): void {
if (!this.catalog) {
return;
}
const browse = this.contentDiv.createDiv({
cls: "excalidraw-script-store__browse-header",
});
const heading = browse.createDiv();
heading.createEl("h2", { text: t("SCRIPT_STORE_BROWSE_TITLE") });
heading.createEl("p", { text: t("SCRIPT_STORE_BROWSE_DESC") });
const controls = browse.createDiv({
cls: "excalidraw-script-store__controls",
});
const searchWrap = controls.createDiv({
cls: "excalidraw-script-store__search",
});
const searchIcon = searchWrap.createSpan();
setIcon(searchIcon, "search");
const search = searchWrap.createEl("input", {
type: "search",
placeholder: t("SCRIPT_STORE_SEARCH_PLACEHOLDER"),
attr: { "aria-label": t("SCRIPT_STORE_SEARCH_PLACEHOLDER") },
});
search.value = this.searchQuery;
search.addEventListener("input", () => {
this.searchQuery = search.value.trim().toLowerCase();
this.renderScriptGrid();
});
const category = controls.createEl("select", {
attr: { "aria-label": t("SCRIPT_STORE_CATEGORY_LABEL") },
});
category.createEl("option", {
text: t("SCRIPT_STORE_ALL_CATEGORIES"),
value: "",
});
this.catalog.categories.forEach((item) => {
category.createEl("option", { text: item.name, value: item.name });
});
category.value = this.selectedCategory;
category.addEventListener("change", () => {
this.selectedCategory = category.value;
this.renderScriptGrid();
});
const viewToggle = controls.createDiv({
cls: "excalidraw-script-store__view-toggle",
});
this.renderViewButton(viewToggle, "all", t("SCRIPT_STORE_ALL_SCRIPTS"));
this.renderViewButton(
viewToggle,
"installed",
t("SCRIPT_STORE_INSTALLED_SCRIPTS"),
);
}
private renderViewButton(
parent: HTMLElement,
view: StoreView,
label: string,
): void {
const button = parent.createEl("button", {
text: label,
cls: this.storeView === view ? "is-active" : undefined,
type: "button",
});
button.addEventListener("click", () => {
this.storeView = view;
parent.querySelectorAll("button").forEach((item) => {
item.classList.toggle("is-active", item === button);
});
this.renderScriptGrid();
});
}
private renderScriptGrid(): void {
if (!this.catalog) {
return;
}
this.contentDiv.querySelector(".excalidraw-script-store__results")?.remove();
const results = this.contentDiv.createDiv({
cls: "excalidraw-script-store__results",
});
const entries = this.getFilteredEntries();
results.createDiv({
cls: "excalidraw-script-store__result-summary",
text: `${entries.length} ${t("SCRIPT_STORE_RESULTS")}`,
});
if (entries.length === 0) {
const empty = results.createDiv({
cls: "excalidraw-script-store__empty",
});
const icon = empty.createSpan();
setIcon(icon, "search-x");
empty.createEl("h3", { text: t("SCRIPT_STORE_NO_RESULTS") });
empty.createEl("p", { text: t("SCRIPT_STORE_NO_RESULTS_DESC") });
return;
}
const grid = results.createDiv({ cls: "excalidraw-script-store__grid" });
entries.forEach((entry) => this.renderScriptCard(grid, entry));
}
private getFilteredEntries(): ScriptStoreEntry[] {
if (!this.catalog) {
return [];
}
const featuredRank = new Map(
this.catalog.scripts
.filter((entry) => entry.categories.includes(FEATURED_CATEGORY))
.map((entry) => [
entry.name,
entry.featuredRank ?? Number.MAX_SAFE_INTEGER,
]),
);
return this.catalog.scripts
.filter((entry) => {
const state = this.installStates.get(entry.name) ?? "error";
if (this.storeView === "installed" && state === "install") {
return false;
}
if (
this.selectedCategory &&
!entry.categories.includes(this.selectedCategory)
) {
return false;
}
if (!this.searchQuery) {
return true;
}
const searchable = [
entry.name,
entry.author,
entry.categories.join(" "),
this.getDescription(entry),
]
.join(" ")
.toLowerCase();
return searchable.includes(this.searchQuery);
})
.sort((a, b) => {
const aRank = featuredRank.get(a.name);
const bRank = featuredRank.get(b.name);
if (aRank !== undefined && bRank !== undefined) {
return aRank - bRank;
}
if (aRank !== undefined) {
return -1;
}
if (bRank !== undefined) {
return 1;
}
return a.name.localeCompare(b.name);
});
}
private renderScriptCard(parent: HTMLElement, entry: ScriptStoreEntry): void {
const state = this.installStates.get(entry.name) ?? "error";
const card = parent.createDiv({ cls: "excalidraw-script-store__card" });
if (state === "update") {
card.classList.add("has-update");
}
const main = card.createEl("button", {
cls: "excalidraw-script-store__card-main",
type: "button",
attr: { "aria-label": `${t("SCRIPT_STORE_DETAILS")}: ${entry.name}` },
});
main.addEventListener("click", () => this.renderDetail(entry));
const iconWrap = main.createDiv({ cls: "excalidraw-script-store__icon" });
const fallback = iconWrap.createSpan({
cls: "excalidraw-script-store__icon-fallback",
});
setIcon(fallback, "scroll-text");
const image = iconWrap.createEl("img", {
attr: { src: getScriptIconUrl(entry), alt: "", loading: "lazy" },
});
image.addEventListener(
"error",
() => {
image.classList.add("is-hidden");
fallback.classList.add("is-visible");
},
{ once: true },
);
const text = main.createDiv({ cls: "excalidraw-script-store__card-text" });
const titleRow = text.createDiv({
cls: "excalidraw-script-store__title-row",
});
titleRow.createEl("h3", { text: entry.name });
this.renderStateBadge(titleRow, state);
if (entry.categories.includes(FEATURED_CATEGORY)) {
const featured = titleRow.createSpan({
cls: "excalidraw-script-store__badge is-featured",
text: t("SCRIPT_STORE_FEATURED"),
});
const icon = featured.createSpan();
setIcon(icon, "sparkles");
}
if (entry.author) {
text.createDiv({
cls: "excalidraw-script-store__author",
text: `${t("SCRIPT_STORE_BY")} ${entry.author}`,
});
}
text.createEl("p", { text: this.getDescription(entry) });
const footer = card.createDiv({
cls: "excalidraw-script-store__card-footer",
});
const categoryText = entry.categories
.filter((name) => name !== FEATURED_CATEGORY)
.slice(0, 2)
.join(" · ");
footer.createSpan({ text: categoryText });
const action = footer.createEl("button", {
text: this.getActionLabel(state),
type: "button",
cls: state === "update" ? "mod-cta" : undefined,
});
action.disabled = state === "up-to-date";
action.addEventListener("click", (event) => {
event.stopPropagation();
void this.installEntry(entry, action);
});
}
private renderStateBadge(
parent: HTMLElement,
state: ScriptStoreInstallState,
): void {
if (state === "install") {
return;
}
const badge = parent.createSpan({
cls: [
"excalidraw-script-store__badge",
state === "update" ? "has-update" : "is-installed",
],
text:
state === "update"
? t("SCRIPT_STORE_UPDATE_BADGE")
: state === "error"
? t("SCRIPT_STORE_CHECK_FAILED")
: t("SCRIPT_STORE_INSTALLED_BADGE"),
});
const icon = badge.createSpan();
setIcon(icon, state === "update" ? "circle-arrow-up" : "check");
}
private getDescription(entry: ScriptStoreEntry): string {
const cached = this.descriptionText.get(entry.file);
if (cached !== undefined) {
return cached;
}
const description = (
sanitizedFragment(entry.descriptionHtml).textContent ?? ""
)
.replace(/\s+/g, " ")
.trim();
this.descriptionText.set(entry.file, description);
return description;
}
private getActionLabel(state: ScriptStoreInstallState): string {
switch (state) {
case "install":
return t("SCRIPT_STORE_INSTALL");
case "update":
return t("SCRIPT_STORE_UPDATE");
case "up-to-date":
return t("SCRIPT_STORE_INSTALLED_BADGE");
case "error":
return t("SCRIPT_STORE_REINSTALL");
}
}
private getDetailActionLabel(state: ScriptStoreInstallState): string {
return state === "up-to-date"
? t("SCRIPT_STORE_REINSTALL")
: this.getActionLabel(state);
}
private async installEntry(
entry: ScriptStoreEntry,
button: HTMLButtonElement,
stayOnDetail = false,
): Promise<void> {
button.disabled = true;
button.setText(t("SCRIPT_STORE_UPDATING"));
try {
await installScript(this.plugin, getScriptInstallUrl(entry), false);
this.installStates.set(entry.name, "up-to-date");
new Notice(`${t("SCRIPT_INSTALLED_NOTICE")}: ${entry.name}`);
if (stayOnDetail) {
this.renderDetail(entry);
} else {
this.renderStore();
}
} catch {
this.installStates.set(entry.name, "error");
new Notice(`${t("SCRIPT_INSTALL_ERROR_NOTICE")}: ${entry.name}`);
button.disabled = false;
button.setText(t("SCRIPT_STORE_REINSTALL"));
}
}
private renderDetail(entry: ScriptStoreEntry): void {
const state = this.installStates.get(entry.name) ?? "error";
this.contentDiv.replaceChildren();
const back = this.contentDiv.createEl("button", {
text: t("SCRIPT_STORE_BACK"),
cls: "excalidraw-script-store__back",
type: "button",
});
const backIcon = back.createSpan();
setIcon(backIcon, "arrow-left");
back.addEventListener("click", () => this.renderStore());
const detail = this.contentDiv.createDiv({
cls: "excalidraw-script-store__detail",
});
const hero = detail.createDiv({
cls: "excalidraw-script-store__detail-hero",
});
const iconWrap = hero.createDiv({
cls: "excalidraw-script-store__detail-icon",
});
const fallback = iconWrap.createSpan({
cls: "excalidraw-script-store__detail-icon-fallback",
});
setIcon(fallback, "scroll-text");
const image = iconWrap.createEl("img", {
attr: { src: getScriptIconUrl(entry), alt: "", loading: "lazy" },
});
image.addEventListener(
"error",
() => {
image.classList.add("is-hidden");
fallback.classList.add("is-visible");
},
{ once: true },
);
const title = hero.createDiv({
cls: "excalidraw-script-store__detail-title",
});
title.createEl("h1", { text: entry.name });
if (entry.author) {
const byline = title.createDiv({
cls: "excalidraw-script-store__detail-byline",
});
byline.append(`${t("SCRIPT_STORE_BY")} `);
if (entry.authorUrl) {
byline.createEl("a", {
text: entry.author,
href: entry.authorUrl,
attr: { target: "_blank", rel: "noopener noreferrer" },
});
} else {
byline.append(entry.author);
}
}
const tags = title.createDiv({
cls: "excalidraw-script-store__detail-tags",
});
entry.categories.forEach((category) =>
tags.createSpan({ text: category, cls: "excalidraw-script-store__tag" }),
);
const actions = title.createDiv({
cls: "excalidraw-script-store__detail-actions",
});
const install = actions.createEl("button", {
text: this.getDetailActionLabel(state),
type: "button",
cls: state === "update" || state === "install" ? "mod-cta" : undefined,
});
install.addEventListener("click", () => {
void this.installEntry(entry, install, true);
});
actions.createEl("a", {
text: t("SCRIPT_STORE_VIEW_SOURCE"),
href: getScriptSourceUrl(entry),
cls: "excalidraw-script-store__source-link",
attr: { target: "_blank", rel: "noopener noreferrer" },
});
if (state !== "install") {
this.renderInstalledScriptManagement(detail, entry);
}
const description = detail.createDiv({
cls: "excalidraw-script-store__detail-description",
});
setSanitizedHtml(description, entry.descriptionHtml);
description.querySelectorAll("a").forEach((link) => {
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener noreferrer");
});
}
private renderInstalledScriptManagement(
parent: HTMLElement,
entry: ScriptStoreEntry,
): void {
const source = getScriptInstallUrl(entry);
const localFiles = getInstalledScriptFiles(this.plugin, source);
if (localFiles.length === 0) {
return;
}
const section = parent.createDiv({
cls: "excalidraw-script-store__local-management",
});
section.createEl("h2", { text: t("SCRIPT_STORE_LOCAL_TITLE") });
if (localFiles.length > 1) {
section.createDiv({
cls: "excalidraw-script-store__local-note",
text: t("SCRIPT_STORE_MULTIPLE_COPIES"),
});
}
if (this.plugin.settings.storeScriptFilesAsJavaScript) {
section.createDiv({
cls: "excalidraw-script-store__local-note",
text: t("SCRIPT_STORE_JS_OPEN_NOTE"),
});
}
const groups = getInstalledScriptGroups(this.plugin);
localFiles.forEach((localFile, index) => {
const copy = section.createDiv({
cls: "excalidraw-script-store__local-copy",
});
if (localFiles.length > 1) {
copy.createDiv({
cls: "excalidraw-script-store__local-copy-label",
text:
index === 0
? t("SCRIPT_STORE_PRIMARY_COPY")
: t("SCRIPT_STORE_ADDITIONAL_COPY"),
});
}
const fileRow = copy.createDiv({
cls: "excalidraw-script-store__local-row",
});
const fileInfo = fileRow.createDiv({
cls: "excalidraw-script-store__local-info",
});
fileInfo.createEl("strong", { text: t("SCRIPT_STORE_LOCAL_FILE") });
fileInfo.createEl("code", { text: localFile.path });
const fileActions = fileRow.createDiv({
cls: "excalidraw-script-store__local-actions",
});
const openButton = fileActions.createEl("button", {
text: t("SCRIPT_STORE_OPEN_LOCAL"),
type: "button",
});
openButton.onClickEvent(() => {
void this.openLocalScript(localFile.path);
});
const uninstallButton = fileActions.createEl("button", {
text: t("SCRIPT_STORE_UNINSTALL"),
type: "button",
cls: "mod-warning",
});
uninstallButton.onClickEvent(() => {
void this.uninstallEntry(entry, uninstallButton, localFile.path);
});
const downloadedRoot = normalizePath(
`${this.plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`,
);
const currentGroup =
localFile.parent?.path === downloadedRoot
? ""
: localFile.parent?.path.slice(downloadedRoot.length + 1) ?? "";
const groupRow = copy.createDiv({
cls: "excalidraw-script-store__group-row",
});
const groupLabel = groupRow.createEl("label", {
text: t("SCRIPT_STORE_GROUP_LABEL"),
});
const groupControls = groupRow.createDiv({
cls: "excalidraw-script-store__group-controls",
});
const groupSelect = groupControls.createEl("select", {
attr: {
id: `excalidraw-script-store-group-${index}`,
"aria-label": t("SCRIPT_STORE_GROUP_LABEL"),
},
});
groupSelect.createEl("option", {
text: t("SCRIPT_STORE_GROUP_ROOT"),
value: "",
});
groups.forEach((group) => {
groupSelect.createEl("option", { text: group, value: group });
});
if (
currentGroup &&
!Array.from(groupSelect.options).some(
(option) => option.value === currentGroup,
)
) {
groupSelect.createEl("option", {
text: currentGroup,
value: currentGroup,
});
}
groupSelect.value = currentGroup;
groupLabel.htmlFor = groupSelect.id;
const newGroup = groupControls.createEl("input", {
type: "text",
placeholder: t("SCRIPT_STORE_NEW_GROUP_PLACEHOLDER"),
attr: { "aria-label": t("SCRIPT_STORE_NEW_GROUP_PLACEHOLDER") },
});
const moveButton = groupControls.createEl("button", {
text: t("SCRIPT_STORE_MOVE_TO_GROUP"),
type: "button",
});
moveButton.onClickEvent(() => {
const targetGroup = newGroup.value.trim() || groupSelect.value;
void this.moveEntryToGroup(
entry,
localFile.path,
targetGroup,
moveButton,
);
});
});
}
private async openLocalScript(localPath: string): Promise<void> {
const localFile = this.plugin.app.vault.getFileByPath(
normalizePath(localPath),
);
if (!localFile) {
return;
}
try {
this.close();
await this.plugin.app.workspace.getLeaf(true).openFile(localFile, {
active: true,
});
} catch (error: unknown) {
errorlog({
where: "ScriptInstallPrompt.openLocalScript",
source: localFile.path,
error,
});
new Notice(t("SCRIPT_STORE_OPEN_LOCAL_FAILED"));
}
}
private async uninstallEntry(
entry: ScriptStoreEntry,
button: HTMLButtonElement,
localPath: string,
): Promise<void> {
button.disabled = true;
try {
const source = getScriptInstallUrl(entry);
await uninstallScript(this.plugin, source, localPath);
if (getInstalledScriptFiles(this.plugin, source).length === 0) {
this.installStates.set(entry.name, "install");
}
new Notice(`${t("SCRIPT_STORE_UNINSTALLED")}: ${entry.name}`);
this.renderDetail(entry);
} catch (error: unknown) {
errorlog({
where: "ScriptInstallPrompt.uninstallEntry",
source: localPath,
error,
});
new Notice(`${t("SCRIPT_STORE_UNINSTALL_FAILED")}: ${entry.name}`);
button.disabled = false;
}
}
private async moveEntryToGroup(
entry: ScriptStoreEntry,
localPath: string,
targetGroup: string,
button: HTMLButtonElement,
): Promise<void> {
button.disabled = true;
try {
const source = getScriptInstallUrl(entry);
await moveInstalledScriptToGroup(
this.plugin,
source,
targetGroup,
localPath,
);
new Notice(`${t("SCRIPT_STORE_MOVED_TO_GROUP")}: ${entry.name}`);
this.renderDetail(entry);
} catch (error: unknown) {
errorlog({
where: "ScriptInstallPrompt.moveEntryToGroup",
source: localPath,
error,
});
new Notice(`${t("SCRIPT_STORE_MOVE_FAILED")}: ${entry.name}`);
button.disabled = false;
}
}
onClose(): void {
this.contentEl.empty();
this.renderComponent.unload();
this.contentEl.replaceChildren();
}
}
+39 -1
View File
@@ -440,7 +440,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc:
"Adds an arrow element.\n" +
'Arrowheads: "arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null.\n' +
'Bindings: "inside" | "outside" Sets startObjectId/endObjectId to bind the arrow ends to shapes. Bind mode: "orbit" (default) or "inside".\n' +
'Set startObjectId/endObjectId to bind the corresponding arrow end to a shape; omit an object ID to leave that end unbound. Bind mode: "orbit" (default) or "inside".\n' +
"Fixed point: [xRatio,yRatio] in 0..1 (percentage of bound element width/height) to bind to a specific point on the element. In case of orbit mode, the orbit will happen around this immaginary point.\n" +
"Elbowed: true will create an elbowed arrow.",
after: "",
@@ -661,6 +661,24 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: null,
after: "",
},
{
field: "clearViewDirty",
code: "clearViewDirty(): void;",
desc: "Clears the target view's current dirty marker without saving. Intended for generated/transient scene integrations that update a view with save=false. Calls racing view teardown are ignored.",
after: "",
},
{
field: "registerThisAsViewEA",
code: "registerThisAsViewEA(): boolean;",
desc: "Registers this EA instance as the hook server for its target view.",
after: "",
},
{
field: "deregisterThisAsViewEA",
code: "deregisterThisAsViewEA(): boolean;",
desc: "Restores the target view's default plugin-global EA hook server. Safe to call during view teardown.",
after: "",
},
{
field: "connectObjectWithViewSelectedElement",
code: "connectObjectWithViewSelectedElement(objectA: string, connectionA: ConnectionPoint, connectionB: ConnectionPoint, formatting?: {numberOfPoints?: number; startArrowHead?: string; endArrowHead?: string; padding?: number;},): boolean;",
@@ -969,6 +987,14 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Returns a new instance of ExcalidrawAutomate.",
after: "",
},
{
field: "toggleViewMode",
code: "public async toggleViewMode(view: View): Promise<View | null>",
desc:
"Toggles the supplied live Excalidraw-backed view between Excalidraw and Markdown without relying on the active workspace leaf. " +
"The input may be an ExcalidrawView or a MarkdownView whose file is an Excalidraw drawing. Returns the replacement view after a successful toggle, or null when the supplied view is not eligible.",
after: "(view);",
},
{
field: "getAttachmentFilepath",
code: "async getAttachmentFilepath(filename: string): Promise<string>",
@@ -1293,6 +1319,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Sets Excalidraw in the targetView to view-mode",
after: "",
},
{
field: "registerViewLinkClickHook",
code: "registerViewLinkClickHook(hook: ViewLinkClickHook): () => void;",
desc: "Registers a link-click hook only for the target view and returns a disposer. The callback receives the resolved pane action, so integrations do not need to inspect Excalidraw settings or reproduce platform modifier rules. Return false to prevent native navigation.",
after: "",
},
{
field: "splitFolderAndFilename",
code: "splitFolderAndFilename(filepath: string): { folderpath: string; filename: string; basename: string; extension: string; }",
@@ -1313,6 +1345,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Zoom tarteView to fit elements provided as input. elements === [] will zoom to fit the entire scene. SelectElements toggles whether the elements should be in a selected state at the end of the operation.",
after: "",
},
{
field: "viewZoomToFit",
code: "viewZoomToFit(): void",
desc: "Zooms the target view to fit its complete scene using Excalidraw's normal maximum zoom and safety checks.",
after: "",
},
{
field: "compressToBase64",
code: "compressToBase64(str: string):string",
+200 -47
View File
@@ -23,6 +23,7 @@ import {
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
import {
Editor,
MarkdownView,
Notice,
OpenViewState,
RequestUrlResponse,
@@ -50,6 +51,7 @@ import {
refreshTextDimensions,
getFontFamilyString,
convertToExcalidrawElements,
VIEW_TYPE_EXCALIDRAW,
} from "src/constants/constants";
import {
blobToBase64,
@@ -79,6 +81,7 @@ import {
isObsidianThemeDark,
mergeMarkdownFiles,
openLeaf,
setExcalidrawView,
} from "src/utils/obsidianUtils";
import { getAttachmentsFolderAndFilePath } from "src/utils/pathUtils";
import {
@@ -240,6 +243,19 @@ import { RELEASE_NOTES } from "./Dialogs/Messages";
type ExcalidrawAutomateHelpTarget = ((...args: unknown[]) => unknown) | string;
/** Details supplied to an integration when a link is activated in one Excalidraw view. */
export interface ViewLinkClickContext {
element: ExcalidrawElement;
linkText: string;
event: MouseEvent | null;
action: PaneTarget;
view: ExcalidrawView;
ea: ExcalidrawAutomate;
}
/** A view-scoped link hook. Return `false` to prevent Excalidraw's default navigation. */
export type ViewLinkClickHook = (context: ViewLinkClickContext) => boolean | void;
extendPlugins([
HarmonyPlugin,
MixPlugin,
@@ -870,6 +886,24 @@ export class ExcalidrawAutomate {
this.targetView = view;
}
/**
* Returns the current target view when it is safe to perform a live-view
* operation. Calls that arrive after EA destruction or while the target view
* is unloading are expected teardown races and are ignored silently. Genuine
* calls without an active target view still report the usual EA API error.
*/
private getReadyTargetView(source: string): ExcalidrawView | null {
const view = this.targetView;
if (this.destroyed || view?.semaphores?.viewunload) {
return null;
}
if (view?._loaded) {
return view;
}
errorMessage("targetView not set", source);
return null;
}
/**
* Registers synchronous cleanup owned by this EA instance. Use this for
* external listeners, observers, timers, and subscriptions that EA cannot
@@ -2729,8 +2763,8 @@ export class ExcalidrawAutomate {
* @param {Object} [formatting] - Formatting options for the arrow element.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.startArrowHead] - The start arrowhead type.
* @param {"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null} [formatting.endArrowHead] - The end arrowhead type.
* @param {string} [formatting.startObjectId] - The ID of the start object.
* @param {string} [formatting.endObjectId] - The ID of the end object.
* @param {string} [formatting.startObjectId] - The ID of the start object. When omitted, the arrow start is unbound.
* @param {string} [formatting.endObjectId] - The ID of the end object. When omitted, the arrow end is unbound.
* BindMode Determines whether the arrow remains outside the shape or is allowed to
* go all the way inside the shape up to the exact fixed point.
* @param {"inside" | "orbit"} [formatting.startBindMode] - The binding mode for the start object.
@@ -2778,20 +2812,32 @@ export class ExcalidrawAutomate {
},
id?: string,
): string {
const startFixedPoint = normalizeFixedPoint(formatting?.startFixedPoint);
const endFixedPoint = normalizeFixedPoint(formatting?.endFixedPoint);
const startMode = normalizeBindMode(formatting?.startBindMode);
const endMode = normalizeBindMode(formatting?.endBindMode);
const box = getLineBox(points);
const elbowed = formatting?.elbowed ?? false;
const startElement = formatting?.startObjectId
const startObjectId = formatting?.startObjectId;
const endObjectId = formatting?.endObjectId;
const startBinding: FixedPointBinding | null = startObjectId
? {
elementId: startObjectId,
mode: normalizeBindMode(formatting?.startBindMode),
fixedPoint: normalizeFixedPoint(formatting?.startFixedPoint),
}
: null;
const endBinding: FixedPointBinding | null = endObjectId
? {
elementId: endObjectId,
mode: normalizeBindMode(formatting?.endBindMode),
fixedPoint: normalizeFixedPoint(formatting?.endFixedPoint),
}
: null;
const startElement = startBinding
? (this.getElement(
formatting.startObjectId,
startBinding.elementId,
) as Mutable<ExcalidrawBindableElement>)
: null;
const endElement = formatting?.endObjectId
const endElement = endBinding
? (this.getElement(
formatting.endObjectId,
endBinding.elementId,
) as Mutable<ExcalidrawBindableElement>)
: null;
id = id ?? nanoid();
@@ -2799,16 +2845,8 @@ export class ExcalidrawAutomate {
points: normalizeLinePoints(points),
elbowed,
lastCommittedPoint: null,
startBinding: {
elementId: formatting?.startObjectId,
mode: startMode,
fixedPoint: startFixedPoint,
},
endBinding: {
elementId: formatting?.endObjectId,
mode: endMode,
fixedPoint: endFixedPoint,
},
startBinding,
endBinding,
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/388
startArrowhead:
typeof formatting?.startArrowHead !== "undefined"
@@ -3864,11 +3902,10 @@ export class ExcalidrawAutomate {
* @param {boolean} [forceViewMode=false] - Whether to force view mode.
*/
viewToggleFullScreen(forceViewMode: boolean = false): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
const view = this.getReadyTargetView("viewToggleFullScreen()");
if (!view) {
return;
}
const view = this.targetView;
const isFullscreen = view.isFullscreen();
if (forceViewMode) {
view.updateScene({
@@ -3878,9 +3915,7 @@ export class ExcalidrawAutomate {
},
captureUpdate: CaptureUpdateAction.NEVER,
});
this.targetView.toolsPanelRef?.current?.setExcalidrawViewMode(
!isFullscreen,
);
view.toolsPanelRef?.current?.setExcalidrawViewMode(!isFullscreen);
}
if (isFullscreen) {
@@ -3895,11 +3930,10 @@ export class ExcalidrawAutomate {
* @param {boolean} enabled - Whether to enable view mode.
*/
setViewModeEnabled(enabled: boolean): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
const view = this.getReadyTargetView("setViewModeEnabled()");
if (!view) {
return;
}
const view = this.targetView;
view.updateScene({
appState: { viewModeEnabled: enabled },
captureUpdate: CaptureUpdateAction.NEVER,
@@ -3907,6 +3941,25 @@ export class ExcalidrawAutomate {
view.toolsPanelRef?.current?.setExcalidrawViewMode(enabled);
}
/**
* Registers a link-click hook on the target view only.
*
* The callback receives Excalidraw's resolved pane action, so integrations do not need to read
* plugin settings or reproduce platform-specific modifier-key rules. The returned disposer must
* be called when the integration unmounts. Returning `false` from the callback prevents native
* link navigation.
*
* @param hook - Callback invoked for links activated in the current target view.
* @returns A disposer that unregisters this callback, or a no-op disposer if no view is ready.
*/
registerViewLinkClickHook(hook: ViewLinkClickHook): () => void {
const view = this.getReadyTargetView("registerViewLinkClickHook()");
if (!view) {
return () => undefined;
}
return view.registerViewLinkClickHook(hook, this);
}
/**
* Updates the scene in the target view.
* @param {Object} scene - The scene to load to Excalidraw.
@@ -3929,15 +3982,15 @@ export class ExcalidrawAutomate {
},
restore: boolean = false,
): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
const view = this.getReadyTargetView("viewUpdateScene()");
if (!view) {
return;
}
if (!scene.storeAction) {
scene.storeAction = scene.commitToHistory ? "capture" : "update";
}
this.targetView.updateScene(
view.updateScene(
{
elements: scene.elements,
appState: scene.appState,
@@ -4012,11 +4065,40 @@ export class ExcalidrawAutomate {
elements: ExcalidrawElement[],
margin: number = 0.05,
): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
const view = this.getReadyTargetView("viewZoomToElements()");
if (!view) {
return;
}
this.targetView.zoomToElements(selectElements, elements, margin);
view.zoomToElements(selectElements, elements, margin);
}
/**
* Zooms the target view to fit its complete scene using Excalidraw's normal safety limits.
*
* This honors the plugin's maximum zoom setting and skips unsafe automatic zoom work while the
* view is closing, editing text, or displaying a modal.
*/
viewZoomToFit(): void {
const view = this.getReadyTargetView("viewZoomToFit()");
if (!view) {
return;
}
view.zoomToFit(false);
}
/**
* Clears the target view's current dirty marker without saving.
*
* This is intended for integrations that deliberately render generated or
* transient scene state with `save=false`. It does not disable future dirty
* tracking or persistence. Calls racing view teardown are ignored.
*/
clearViewDirty(): void {
const view = this.getReadyTargetView("clearViewDirty()");
if (!view) {
return;
}
view.clearDirty();
}
/**
@@ -4034,15 +4116,15 @@ export class ExcalidrawAutomate {
shouldRestoreElements: boolean = false,
captureUpdate: CaptureUpdateActionType = CaptureUpdateAction.IMMEDIATELY,
): Promise<boolean> {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "addElementsToView()");
const view = this.getReadyTargetView("addElementsToView()");
if (!view) {
return false;
}
const elements = this.getElements();
if (elements.some((el) => el.type === "embeddable")) {
patchMobileView(this.targetView);
patchMobileView(view);
}
const result = await this.targetView.addElements({
const result = await view.addElements({
newElements: elements,
repositionToCursor,
save,
@@ -4061,24 +4143,28 @@ export class ExcalidrawAutomate {
* @returns {boolean} True if successful, false otherwise.
*/
registerThisAsViewEA(): boolean {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "addElementsToView()");
const view = this.getReadyTargetView("registerThisAsViewEA()");
if (!view) {
return false;
}
this.targetView.setHookServer(this);
view.setHookServer(this);
return true;
}
/**
* Sets the target view EA to window.ExcalidrawAutomate.
* @returns {boolean} True if successful, false otherwise.
* Restores the target view's default plugin-global EA hook server. This is a
* teardown operation, so it remains valid while the view itself is unloading.
* @returns {boolean} True if a target view was available, false otherwise.
*/
deregisterThisAsViewEA(): boolean {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "addElementsToView()");
const view = this.targetView;
if (!view) {
if (!this.destroyed) {
errorMessage("targetView not set", "deregisterThisAsViewEA()");
}
return false;
}
this.targetView.setHookServer(this);
view.setHookServer();
return true;
}
@@ -4930,6 +5016,65 @@ export class ExcalidrawAutomate {
return view instanceof ExcalidrawView;
}
/**
* Toggles an Excalidraw-backed view between the native Excalidraw and Markdown representations.
*
* The supplied view is the authority for the transition; this method does not depend on the
* workspace's currently active leaf or the command palette. Markdown views are accepted only
* when their file is an Excalidraw file. Excalidraw compatibility-mode views are left unchanged.
*
* @param {View} view - The ExcalidrawView or MarkdownView to toggle.
* @returns {Promise<View | null>} The replacement view after a successful toggle, or null when
* the supplied view is not a live Excalidraw-backed view that can be toggled.
*/
public async toggleViewMode(view: View): Promise<View | null> {
if (view instanceof ExcalidrawView) {
const file = view.file;
const leaf = view.leaf;
if (
!file ||
!leaf ||
leaf.view !== view ||
view.compatibilityMode ||
!this.isExcalidrawFile(file)
) {
return null;
}
const preserveInactive = this.plugin.app.workspace.getMostRecentLeaf() !== leaf;
await view.openAsMarkdown(
preserveInactive ? { focus: false } : undefined,
preserveInactive ? false : undefined,
);
return leaf.view instanceof MarkdownView ? leaf.view : null;
}
if (!(view instanceof MarkdownView)) {
return null;
}
const file = view.file;
const leaf = view.leaf;
if (
!file ||
!leaf ||
leaf.view !== view ||
!this.isExcalidrawFile(file)
) {
return null;
}
await view.save();
this.plugin.excalidrawFileModes[leaf.id || file.path] =
VIEW_TYPE_EXCALIDRAW;
const preserveInactive = this.plugin.app.workspace.getMostRecentLeaf() !== leaf;
await setExcalidrawView(
leaf,
preserveInactive ? { active: false, focus: false } : undefined,
);
return leaf.view instanceof ExcalidrawView ? leaf.view : null;
}
/**
* Sets the selection in the view.
* @param {ExcalidrawElement[] | string[]} elements - Array of elements or element IDs to select.
@@ -5377,6 +5522,14 @@ export class ExcalidrawAutomate {
}
});
this.sidepanelTab?.close();
const targetView = this.targetView;
try {
if (targetView?.getHookServer() === this) {
targetView.setHookServer();
}
} catch {
// The target view may already be past its unload lifecycle.
}
this.targetView = null;
this.plugin = null;
this.elementsDict = {};
+8 -2
View File
@@ -63,7 +63,10 @@ import {
} from "../utils/mermaidUtils";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { updateElementIdsInScene } from "../utils/excalidrawSceneUtils";
import { importFileToVault } from "../utils/fileUtils";
import {
canSaveAsObsidianAttachment,
importFileToVault,
} from "../utils/fileUtils";
import { t } from "../lang/helpers";
import { displayFontMessage } from "../utils/excalidrawViewUtils";
import { getPDFRect } from "../utils/PDFUtils";
@@ -1764,7 +1767,10 @@ export class ExcalidrawData {
let fname = name;
if (!fname) {
fname = `Pasted Image ${window.moment().format("YYYYMMDDHHmmss_SSS")}`;
// Saved through app.saveAttachment, a paste is named the way Obsidian names one pasted into a note.
fname = canSaveAsObsidianAttachment(this.app, this.file, this.view)
? `Pasted image ${window.moment().format("YYYYMMDDHHmmss")}`
: `Pasted Image ${window.moment().format("YYYYMMDDHHmmss_SSS")}`;
switch (mimeType) {
case "image/png":
+123 -6
View File
@@ -378,6 +378,23 @@ export class ScriptEngine {
);
}
/**
* Runs a coordinated script-file mutation without letting the vault event
* handlers trigger full registry reloads for each intermediate file change.
* The caller is responsible for refreshing the affected registry entries.
*/
public async withScriptFileEventsSuspended<T>(
operation: () => Promise<T>,
): Promise<T> {
const wasSuspended = this.scriptFileEventsSuspended;
this.scriptFileEventsSuspended = true;
try {
return await operation();
} finally {
this.scriptFileEventsSuspended = wasSuspended;
}
}
updateScriptPath() {
if (this.scriptPath === this.plugin.settings.scriptFolderPath) {
return;
@@ -429,6 +446,47 @@ export class ScriptEngine {
);
}
/** Refreshes one script after an in-place write without reloading all scripts. */
public async refreshManagedScriptFile(file: TFile): Promise<void> {
this.invalidateCompiledScript(file.path);
if (!this.isInScriptFolder(file.path) || !this.isScriptPath(file.path)) {
return;
}
if (!this.loadedScriptPaths.has(file.path)) {
await this.loadScript(file);
return;
}
await this.addScriptIconToMap(
file.path,
this.getScriptName(file),
this.scriptRegistryGeneration,
);
}
/** Removes one deleted script from the live registry without a full reload. */
public async removeManagedScriptFile(
scriptPath: string,
scriptName: string,
): Promise<void> {
this.invalidateCompiledScript(scriptPath);
this.clearAutostartAttachment(scriptPath);
if (
this.loadedScriptPaths.has(scriptPath) ||
Boolean(this.scriptIconMap?.[scriptPath])
) {
this.unloadScript(scriptName, scriptPath);
}
const hasAutostartState =
scriptName in this.plugin.settings.autostartScripts ||
scriptName in this.plugin.settings.autostartScriptFailures;
if (hasAutostartState && !this.getScriptFileByName(scriptName)) {
await this.purgeAutostartPermission(scriptName);
}
getExcalidrawViews(this.app, true).forEach((view) =>
view.updatePinnedScripts(),
);
}
/**
* Builds a non-destructive plan for moving scripts to the selected local
* extension. A configured startup script outside the Scripts folder is
@@ -589,14 +647,73 @@ export class ScriptEngine {
destinationPath: string,
): Promise<void> {
const sourcePath = file.path;
const startupScriptPath = resolveConfiguredStartupScriptPath(
this.plugin.settings.startupScriptPath,
if (sourcePath === destinationPath) {
return;
}
if (
this.app.vault.getFileByPath(destinationPath) ||
this.app.vault.getFolderByPath(destinationPath)
) {
throw new Error(`Script destination already exists: ${destinationPath}`);
}
const sourceScriptName = this.getScriptName(sourcePath);
const wasLoaded = this.loadedScriptPaths.has(sourcePath);
const originalPinnedScripts = [...this.plugin.settings.pinnedScripts];
const originalStartupScriptPath = this.plugin.settings.startupScriptPath;
const resolvedStartupPath = resolveConfiguredStartupScriptPath(
originalStartupScriptPath,
);
await this.migrateScriptFiles({
renames: [{ file, sourcePath, destinationPath }],
conflicts: [],
includesStartupScript: startupScriptPath === sourcePath,
const pinnedChanged = originalPinnedScripts.includes(sourcePath);
const startupChanged = resolvedStartupPath === sourcePath;
let renamed = false;
await this.withScriptFileEventsSuspended(async () => {
try {
await this.app.fileManager.renameFile(file, destinationPath);
renamed = true;
if (pinnedChanged) {
this.plugin.settings.pinnedScripts = originalPinnedScripts.map((path) =>
path === sourcePath ? destinationPath : path,
);
}
if (startupChanged) {
this.plugin.settings.startupScriptPath = destinationPath;
}
if (pinnedChanged || startupChanged) {
await this.plugin.saveSettings();
}
} catch (error: unknown) {
this.plugin.settings.pinnedScripts = originalPinnedScripts;
this.plugin.settings.startupScriptPath = originalStartupScriptPath;
if (renamed) {
try {
await this.app.fileManager.renameFile(file, sourcePath);
} catch (rollbackError: unknown) {
errorlog({
where: "ScriptEngine.renameManagedScriptFile.rollback",
sourcePath: destinationPath,
error: rollbackError,
});
}
}
throw error;
}
});
this.invalidateCompiledScript(sourcePath);
this.invalidateCompiledScript(file.path);
this.clearAutostartAttachment(sourcePath);
if (wasLoaded) {
this.unloadScript(sourceScriptName, sourcePath);
}
if (this.isInScriptFolder(file.path) && this.isScriptPath(file.path)) {
await this.loadScript(file);
}
getExcalidrawViews(this.app, true).forEach((view) =>
view.updatePinnedScripts(),
);
}
public getScriptName(f: TFile | string): string {
+2 -2
View File
@@ -96,7 +96,7 @@ export class InlineLinkSuggester
inputEl: HTMLInputElement | HTMLTextAreaElement,
getSourcePath: () => string | undefined,
widthWrapper?: HTMLElement,
surpessPlaceholder: boolean = false,
suppressPlaceholder: boolean = false,
collisionBoundary?: HTMLElement,
) {
super(app, inputEl, [], collisionBoundary);
@@ -107,7 +107,7 @@ export class InlineLinkSuggester
this.handleBracketKeyDown = (event: KeyboardEvent) =>
this.onBracketKeyDown(event);
this.limit = 20;
if (!surpessPlaceholder) {
if (!suppressPlaceholder) {
this.setPlaceholder(t("INLINE_HINT"));
}
this.emptyStateText = "No match";
+1 -1
View File
@@ -81,7 +81,7 @@ type EmbeddedLink =
))
| null;
declare namespace ExcalidrawLib {
export declare namespace ExcalidrawLib {
type ObsidianCommonHostUIMode = "full" | "compact" | "tray" | "mobile";
type ObsidianCommonHostAdapter = Readonly<{
+4
View File
@@ -80,6 +80,10 @@ export interface ExcalidrawEphemeralState {
rename?: string;
subpath?: string;
line?: number;
/** One-shot view/edit mode requested by an integration opening this drawing. */
mode?: "view" | "edit";
/** One-shot request to fit the scene after its first complete render. */
zoomToFit?: boolean;
match?: {
content?: string;
matches?: [number, number][];
+12 -1
View File
@@ -1,7 +1,18 @@
/**
* Metadata entry describing a file in the remote EA scripts directory listing.
* Metadata entry describing a file in the legacy remote EA scripts directory listing.
*/
export type RemoteDirectoryInfo = {
fname: string;
mtime: number;
};
/**
* File metadata returned by GitHub's repository contents endpoint.
*/
export type GitHubRepositoryContentFile = {
name: string;
path: string;
sha: string;
type: "file" | "dir" | "symlink" | "submodule";
download_url?: string | null;
};
+29
View File
@@ -0,0 +1,29 @@
export type ScriptStoreCategory = {
name: string;
description: string;
};
export type ScriptStoreEntry = {
name: string;
file: string;
installUrl: string;
iconUrl: string;
author: string;
authorUrl: string;
sourceUrl: string;
descriptionHtml: string;
categories: string[];
featuredRank?: number;
};
export type ScriptStoreCatalog = {
version: number;
categories: ScriptStoreCategory[];
scripts: ScriptStoreEntry[];
};
export type ScriptStoreInstallState =
| "install"
| "update"
| "up-to-date"
| "error";
+11
View File
@@ -202,6 +202,7 @@ export type LocalGraphView = View & {
declare global {
interface Window {
MouseEvent?: typeof MouseEvent;
ExcalidrawAutomate: ExcalidrawAutomate;
ExcalidrawLib: typeof ExcalidrawLib;
pdfjsLib: PdfJsLibrary;
@@ -241,6 +242,16 @@ declare module "obsidian" {
enablePlugin(id: string): Promise<void>;
disablePlugin(id: string): Promise<void>;
};
/**
* Saves an attachment where Obsidian saves an image pasted or dropped into the active note, making the
* path unique. Internal, present with this signature since Obsidian 0.8.5; attachment-management plugins
* patch it to apply their naming and location rules.
*/
saveAttachment(
name: string,
extension: string,
data: ArrayBuffer,
): Promise<TFile>;
hotkeyManager: {
addDefaultHotkeys(commandId: string, hotkeys: Hotkey[]): void;
+175
View File
@@ -0,0 +1,175 @@
/**
* Mount-time host selection for embedded files.
*
* A subpath embed (a back-of-the-note section or a block reference) can only be
* rendered section-scoped by a native Canvas node. A workspace leaf always
* renders the whole file, which for a hybrid drawing is the entire drawing.
* `CanvasNodeFactory` initializes asynchronously on layout ready, so an
* embeddable can mount before the factory is usable; these helpers wait for it.
*/
/** Minimal `CanvasNodeFactory` surface needed to decide when a node can be created. */
export interface CanvasNodeHost {
isInitialized: () => boolean;
/**
* Settles true when the factory finished initializing, false when it can no
* longer do so. Absent on a host that does not report its lifecycle, which
* leaves such a caller on the bounded wait below.
*/
whenInitialized?: Promise<boolean>;
}
export const CANVAS_NODE_HOST_WAIT_INTERVAL_MS = 25;
/**
* Bounds the wait only while no factory is visible at all; a factory that
* reports its lifecycle is waited on through that signal.
*/
export const CANVAS_NODE_HOST_WAIT_TIMEOUT_MS = 2000;
/** Marks a lifecycle race that the poll interval won, i.e. still initializing. */
const STILL_INITIALIZING = Symbol("still-initializing");
/**
* Decides whether an embeddable must be hosted by a native Canvas node.
*
* @param subpath - Section or block reference of the link, null when absent.
* @param fileExtension - Extension of the embedded file.
* @returns True when only a Canvas node can render the requested section.
* @remarks
* Any non-empty subpath counts, including a bare `#`.
*/
export function requiresCanvasNodeHost(
subpath: string | null | undefined,
fileExtension: string | null | undefined,
): boolean {
return Boolean(subpath) && (fileExtension?.toLowerCase?.() ?? "") === "md";
}
/**
* Waits for the Canvas node factory to finish its asynchronous initialization.
*
* @param getHost - Reads the factory on each poll; it may be absent at first
* and may be torn down while waiting, so it is re-read rather than captured.
* @param isCancelled - Signals that the embeddable unmounted; stops the wait.
* @param timeoutMs - Upper bound on the wait while no factory is visible.
* @param intervalMs - Delay between polls.
* @returns True when the factory became usable, false on cancel, on a factory
* that reported it will not initialize, or on the no-factory timeout.
*/
export async function awaitCanvasNodeHost(
getHost: () => CanvasNodeHost | null | undefined,
isCancelled: () => boolean = () => false,
timeoutMs: number = CANVAS_NODE_HOST_WAIT_TIMEOUT_MS,
intervalMs: number = CANVAS_NODE_HOST_WAIT_INTERVAL_MS,
delay: (ms: number) => Promise<void> = sleep,
): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (isCancelled()) {
return false;
}
const host = getHost();
if (host?.isInitialized()) {
return true;
}
const lifecycle = host?.whenInitialized;
if (lifecycle !== undefined) {
//The lifecycle settles on every terminal path (initialized,
//initialization failed, destroyed), so this wait needs no deadline of its
//own; racing the interval keeps cancellation observable meanwhile.
const settled = await Promise.race([
lifecycle,
delay(intervalMs).then(() => STILL_INITIALIZING),
]);
if (settled === STILL_INITIALIZING) {
continue;
}
//One more read decides it: a factory that initialized and was then
//destroyed still reports true here but can no longer host a node.
return settled === true && Boolean(getHost()?.isInitialized());
}
if (Date.now() >= deadline) {
return false;
}
await delay(intervalMs);
}
}
/** Host chosen for an embeddable, or "none" when the embeddable unmounted first. */
export type EmbeddableMountHost = "canvas-node" | "workspace-leaf" | "none";
/** Collaborators the mount dispatch needs; injected so the decision stays testable. */
export interface EmbeddableMountOptions {
subpath: string | null | undefined;
fileExtension: string | null | undefined;
getHost: () => CanvasNodeHost | null | undefined;
isCancelled?: () => boolean;
createCanvasNode: () => void;
createWorkspaceLeaf: () => void;
timeoutMs?: number;
intervalMs?: number;
delay?: (ms: number) => Promise<void>;
}
/**
* Mounts an embeddable into the host that can actually render it.
*
* @param options - Link details and the two mount actions.
* @returns The host that was used, for logging and tests.
* @remarks
* A subpath embed waits for the Canvas node factory; the workspace leaf is the
* fallback when the factory reports it will not initialize.
*/
export async function mountEmbeddableHost(
options: EmbeddableMountOptions,
): Promise<EmbeddableMountHost> {
const {
subpath,
fileExtension,
getHost,
isCancelled = () => false,
createCanvasNode,
createWorkspaceLeaf,
timeoutMs,
intervalMs,
delay,
} = options;
//Latched: once this invocation has read itself cancelled it stays cancelled.
let cancelledOnce = false;
const cancelled = () => {
cancelledOnce ||= isCancelled();
return cancelledOnce;
};
if (cancelled()) {
return "none";
}
if (!requiresCanvasNodeHost(subpath, fileExtension)) {
createWorkspaceLeaf();
return "workspace-leaf";
}
if (getHost()?.isInitialized()) {
createCanvasNode();
return "canvas-node";
}
const ready = await awaitCanvasNodeHost(
getHost,
cancelled,
timeoutMs,
intervalMs,
delay,
);
if (cancelled()) {
return "none";
}
if (ready) {
createCanvasNode();
return "canvas-node";
}
createWorkspaceLeaf();
return "workspace-leaf";
}
+27
View File
@@ -780,6 +780,23 @@ export async function exportImageToFile(
return await createOrOverwriteFile(view.app, path, content);
}
/**
* Whether an image imported into `excalidrawFile` can be saved the way Obsidian saves an image pasted or
* dropped into a markdown note: through `app.saveAttachment`, which places it relative to the active file.
* That holds only while the drawing is the active file, and only when no `onImageFilePathHook` chooses the
* path instead.
*/
export function canSaveAsObsidianAttachment(
app: App,
excalidrawFile: TFile,
view?: ExcalidrawView,
): boolean {
return (
!view?.getHookServer()?.onImageFilePathHook &&
app.workspace.getActiveFile()?.path === excalidrawFile.path
);
}
export async function importFileToVault(
app: App,
fname: string,
@@ -787,6 +804,16 @@ export async function importFileToVault(
excalidrawFile: TFile,
view?: ExcalidrawView,
): Promise<TFile> {
if (
typeof content !== "string" &&
canSaveAsObsidianAttachment(app, excalidrawFile, view)
) {
const { basename, extension } = splitFolderAndFilename(fname);
const data =
content instanceof Blob ? await content.arrayBuffer() : content;
return await app.saveAttachment(basename, extension, data);
}
let hookFilepath: string;
const ea = view?.getHookServer();
if (ea?.onImageFilePathHook) {
+21 -6
View File
@@ -582,12 +582,27 @@ export const foldExcalidrawSection = (view: MarkdownView) => {
}
};
export async function setExcalidrawView(leaf: WorkspaceLeaf) {
await leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state: leaf.view.getState(),
popstate: true,
} as ViewState);
export interface ViewTransitionOptions {
active?: boolean;
focus?: boolean;
}
/** Replace a leaf with an Excalidraw view while honoring explicit activation and focus policy. */
export async function setExcalidrawView(
leaf: WorkspaceLeaf,
options?: ViewTransitionOptions,
) {
await leaf.setViewState(
{
type: VIEW_TYPE_EXCALIDRAW,
state: leaf.view.getState(),
popstate: true,
...(options?.active === undefined ? {} : { active: options.active }),
} as ViewState,
options?.focus === undefined
? undefined
: { focus: options.focus },
);
}
export async function closeLeafView(leaf: WorkspaceLeaf) {
+570 -163
View File
@@ -1,107 +1,515 @@
import { TFile, Notice, request } from "obsidian";
import {
normalizePath,
Notice,
request,
TFile,
TFolder,
type App,
} from "obsidian";
import { SCRIPT_INSTALL_FOLDER } from "src/constants/constants";
import { URLs } from "src/constants/safeUrls";
import { t } from "src/lang/helpers";
import { RemoteDirectoryInfo } from "src/types/githubTypes";
import type { RemoteDirectoryInfo } from "src/types/githubTypes";
import type { ScriptStoreInstallState } from "src/types/scriptStoreTypes";
import { ExcalidrawSidepanelView } from "src/view/sidepanel/Sidepanel";
import { errorlog } from "./coreUtils";
import { getIMGFilename, createOrOverwriteFile } from "./fileUtils";
import { hideElement, setButtonBgColor, showElement } from "./styleUtils";
import type ExcalidrawPlugin from "src/core/main";
import { createOrOverwriteFile, getIMGFilename } from "./fileUtils";
import {
getManagedScriptFileExtension,
getPreferredScriptFiles,
getScriptFileStem,
isScriptFilePath,
} from "./scriptFileUtils";
export const installButton = async (
plugin: ExcalidrawPlugin,
button: HTMLButtonElement,
button2: HTMLButtonElement,
source: string,
) => {
const setButtonText = (
text: "CHECKING" | "INSTALL" | "UPTODATE" | "UPDATE" | "ERROR",
) => {
if (button2) {
hideElement(button2);
}
switch (text) {
case "CHECKING":
button.setText(t("CHECKING_SCRIPT"));
setButtonBgColor(button, "normal");
break;
case "INSTALL":
button.setText(t("INSTALL_SCRIPT"));
setButtonBgColor(button, "accent");
break;
case "UPTODATE":
button.setText(t("UPTODATE_SCRIPT"));
setButtonBgColor(button, "normal");
break;
case "UPDATE":
button.setText(t("UPDATE_SCRIPT"));
setButtonBgColor(button, "success");
if (button2) {
showElement(button2);
}
break;
case "ERROR":
button.setText(t("UNABLETOCHECK_SCRIPT"));
setButtonBgColor(button, "normal");
break;
}
};
type ScriptLibrarySettings = {
scriptFolderPath: string;
allowJavaScriptFiles: boolean;
storeScriptFilesAsJavaScript: boolean;
};
button.addClass("mod-muted");
let decodedURI = source;
type ScriptLibraryScriptEngine = {
getScriptName(file: TFile | string): string;
withScriptFileEventsSuspended<T>(operation: () => Promise<T>): Promise<T>;
refreshManagedScriptFile(file: TFile): Promise<void>;
removeManagedScriptFile(scriptPath: string, scriptName: string): Promise<void>;
renameManagedScriptFile(file: TFile, destinationPath: string): Promise<void>;
};
/** Narrow plugin surface required by the community-script library helpers. */
export type ScriptLibraryPluginContext = {
app: App;
settings: ScriptLibrarySettings;
scriptEngine: ScriptLibraryScriptEngine;
};
const REMOTE_METADATA_CACHE_TTL = 15 * 60 * 1000;
let directoryInfoPromise: Promise<Map<string, number> | null> | null = null;
let directoryInfoFetchedAt = 0;
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null;
const isRemoteDirectoryInfo = (value: unknown): value is RemoteDirectoryInfo =>
isRecord(value) &&
typeof value.fname === "string" &&
typeof value.mtime === "number";
const getDownloadedScriptsFolder = (
plugin: ScriptLibraryPluginContext,
): string =>
normalizePath(
`${plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`,
);
const decodeRemoteFilename = (source: string): string => {
try {
decodedURI = decodeURI(source);
} catch (e: unknown) {
const decodedURI = decodeURI(source);
return decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
} catch (error: unknown) {
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
where: "scriptLibraryUtils.decodeRemoteFilename",
source,
error: e,
error,
});
return source.substring(source.lastIndexOf("/") + 1);
}
};
const sortManagedCopies = (
plugin: ScriptLibraryPluginContext,
files: TFile[],
): TFile[] => {
const root = getDownloadedScriptsFolder(plugin);
return [...files].sort((a, b) => {
const aRelative = a.path.slice(root.length + 1);
const bRelative = b.path.slice(root.length + 1);
const aDepth = aRelative.split("/").length - 1;
const bDepth = bRelative.split("/").length - 1;
return aDepth - bDepth || a.path.localeCompare(b.path);
});
};
const getManagedScriptFilesByStem = (
plugin: ScriptLibraryPluginContext,
): Map<string, TFile[]> => {
const root = plugin.app.vault.getFolderByPath(
getDownloadedScriptsFolder(plugin),
);
if (!root) {
return new Map();
}
const managedFiles: TFile[] = [];
const visit = (folder: TFolder): void => {
folder.children.forEach((child) => {
if (child instanceof TFolder) {
visit(child);
} else if (child instanceof TFile && isScriptFilePath(child.path)) {
managedFiles.push(child);
}
});
};
visit(root);
const filesByStem = new Map<string, TFile[]>();
getPreferredScriptFiles(managedFiles).forEach((file) => {
const stem = getScriptFileStem(file.name);
const files = filesByStem.get(stem) ?? [];
files.push(file);
filesByStem.set(stem, files);
});
filesByStem.forEach((files, stem) => {
filesByStem.set(stem, sortManagedCopies(plugin, files));
});
return filesByStem;
};
const getLocalScriptFiles = (
plugin: ScriptLibraryPluginContext,
remoteFilename: string,
): TFile[] => {
const stem = getScriptFileStem(remoteFilename);
return getManagedScriptFilesByStem(plugin).get(stem) ?? [];
};
const getLocalScriptFile = (
plugin: ScriptLibraryPluginContext,
remoteFilename: string,
): TFile | null => getLocalScriptFiles(plugin, remoteFilename)[0] ?? null;
/** Returns all managed local copies for one community script. */
export const getInstalledScriptFiles = (
plugin: ScriptLibraryPluginContext,
source: string,
): TFile[] => getLocalScriptFiles(plugin, decodeRemoteFilename(source));
/**
* Returns the primary managed local copy for one community script.
* A copy directly under Downloaded wins; otherwise the shallowest grouped copy
* is used. Additional copies are intentionally ignored for update detection.
*/
export const getInstalledScriptFile = (
plugin: ScriptLibraryPluginContext,
source: string,
): TFile | null => getInstalledScriptFiles(plugin, source)[0] ?? null;
/** Returns existing group folders relative to the Downloaded folder. */
export const getInstalledScriptGroups = (
plugin: ScriptLibraryPluginContext,
): string[] => {
const rootPath = getDownloadedScriptsFolder(plugin);
const root = plugin.app.vault.getFolderByPath(rootPath);
if (!root) {
return [];
}
const groups: string[] = [];
const visit = (folder: TFolder): void => {
folder.children.forEach((child) => {
if (!(child instanceof TFolder)) {
return;
}
groups.push(child.path.slice(rootPath.length + 1));
visit(child);
});
};
visit(root);
return groups.sort((a, b) => a.localeCompare(b));
};
const getManagedScriptFile = (
plugin: ScriptLibraryPluginContext,
source: string,
localPath?: string,
): TFile | null => {
const files = getInstalledScriptFiles(plugin, source);
if (!localPath) {
return files[0] ?? null;
}
const normalizedPath = normalizePath(localPath);
return files.find((file) => file.path === normalizedPath) ?? null;
};
const ensureFolderPath = async (
plugin: ScriptLibraryPluginContext,
folderPath: string,
): Promise<void> => {
const normalized = normalizePath(folderPath);
const parts = normalized.split("/").filter(Boolean);
let current = "";
for (const part of parts) {
current = current ? `${current}/${part}` : part;
if (plugin.app.vault.getFolderByPath(current)) {
continue;
}
if (plugin.app.vault.getFileByPath(current)) {
throw new Error(
`Cannot create script group because a file exists at ${current}`,
);
}
await plugin.app.vault.createFolder(current);
}
};
/** Moves an installed script and its optional icon to a relative script group. */
export const moveInstalledScriptToGroup = async (
plugin: ScriptLibraryPluginContext,
source: string,
relativeGroup: string,
localPath?: string,
): Promise<TFile> => {
const scriptFile = getManagedScriptFile(plugin, source, localPath);
if (!scriptFile) {
throw new Error("Script is not installed");
}
const root = getDownloadedScriptsFolder(plugin);
const requestedGroup = relativeGroup.trim();
const group = requestedGroup ? normalizePath(requestedGroup) : "";
const destinationFolder = group ? normalizePath(`${root}/${group}`) : root;
if (destinationFolder !== root && !destinationFolder.startsWith(`${root}/`)) {
throw new Error("Invalid script group");
}
await ensureFolderPath(plugin, destinationFolder);
const destinationPath = normalizePath(
`${destinationFolder}/${scriptFile.name}`,
);
if (destinationPath === scriptFile.path) {
return scriptFile;
}
const destinationStem = getScriptFileStem(scriptFile.name);
const conflictingScript = ["md", "js"]
.map((extension) =>
plugin.app.vault.getFileByPath(
normalizePath(`${destinationFolder}/${destinationStem}.${extension}`),
),
)
.find((file) => file && file.path !== scriptFile.path);
if (conflictingScript) {
throw new Error("A script with this name already exists in that group");
}
const sourceIconPath = getIMGFilename(scriptFile.path, "svg");
const destinationIconPath = getIMGFilename(destinationPath, "svg");
const iconFile = plugin.app.vault.getFileByPath(sourceIconPath);
if (iconFile && plugin.app.vault.getFileByPath(destinationIconPath)) {
throw new Error(
"A script icon with this name already exists in that group",
);
}
let iconMoved = false;
try {
await plugin.scriptEngine.withScriptFileEventsSuspended(async () => {
if (iconFile) {
await plugin.app.fileManager.renameFile(iconFile, destinationIconPath);
iconMoved = true;
}
await plugin.scriptEngine.renameManagedScriptFile(
scriptFile,
destinationPath,
);
});
} catch (error: unknown) {
if (iconMoved) {
const movedIcon = plugin.app.vault.getFileByPath(destinationIconPath);
if (movedIcon) {
try {
await plugin.scriptEngine.withScriptFileEventsSuspended(async () => {
await plugin.app.fileManager.renameFile(movedIcon, sourceIconPath);
});
} catch (rollbackError: unknown) {
errorlog({
where: "scriptLibraryUtils.moveInstalledScriptToGroup.rollback",
source: destinationIconPath,
error: rollbackError,
});
}
}
}
throw error;
}
return plugin.app.vault.getFileByPath(destinationPath) ?? scriptFile;
};
/** Removes an installed community script and its optional local icon. */
export const uninstallScript = async (
plugin: ScriptLibraryPluginContext,
source: string,
localPath?: string,
): Promise<void> => {
const scriptFile = getManagedScriptFile(plugin, source, localPath);
if (!scriptFile) {
return;
}
const iconFile = plugin.app.vault.getFileByPath(
getIMGFilename(scriptFile.path, "svg"),
);
const scriptPath = scriptFile.path;
const scriptName = plugin.scriptEngine.getScriptName(scriptFile);
await plugin.scriptEngine.withScriptFileEventsSuspended(async () => {
await plugin.app.fileManager.trashFile(scriptFile);
if (iconFile) {
try {
await plugin.app.fileManager.trashFile(iconFile);
} catch (error: unknown) {
errorlog({
where: "scriptLibraryUtils.uninstallScript.icon",
source: iconFile.path,
error,
});
}
}
});
await plugin.scriptEngine.removeManagedScriptFile(scriptPath, scriptName);
};
const getDirectoryInfo = async (): Promise<Map<string, number> | null> => {
if (
!directoryInfoPromise ||
Date.now() - directoryInfoFetchedAt > REMOTE_METADATA_CACHE_TTL
) {
directoryInfoFetchedAt = Date.now();
directoryInfoPromise = (async () => {
try {
const parsed: unknown = JSON.parse(
await request({
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
}),
) as unknown;
if (!Array.isArray(parsed)) {
return null;
}
const files = new Map<string, number>();
parsed.forEach((entry: unknown) => {
if (isRemoteDirectoryInfo(entry)) {
files.set(entry.fname, entry.mtime);
}
});
return files.size > 0 ? files : null;
} catch (error: unknown) {
errorlog({
where: "scriptLibraryUtils.getDirectoryInfo",
error,
});
return null;
}
})();
}
return await directoryInfoPromise;
};
const getInstallStateFromDirectoryInfo = (
plugin: ScriptLibraryPluginContext,
scriptFile: TFile,
remoteFilename: string,
files: Map<string, number>,
): ScriptStoreInstallState => {
if (!files.has(remoteFilename)) {
return "error";
}
const scriptMtime = files.get(remoteFilename) ?? 0;
if (scriptMtime > scriptFile.stat.mtime) {
return "update";
}
const iconFilename = getIMGFilename(remoteFilename, "svg");
const iconMtime = files.get(iconFilename);
if (!iconMtime) {
return "up-to-date";
}
const iconFile = plugin.app.vault.getFileByPath(
getIMGFilename(scriptFile.path, "svg"),
);
return !iconFile || iconMtime > iconFile.stat.mtime
? "update"
: "up-to-date";
};
/**
* Resolves one community script's install/update state using the legacy mtime
* contract. directory-info.json is the compatibility source of truth.
*/
export const getScriptInstallStates = async (
plugin: ScriptLibraryPluginContext,
sources: readonly string[],
): Promise<Map<string, ScriptStoreInstallState>> => {
const filesByStem = getManagedScriptFilesByStem(plugin);
const remoteFiles = sources.map((source) => ({
source,
remoteFilename: decodeRemoteFilename(source),
}));
const hasInstalledScripts = remoteFiles.some(({ remoteFilename }) =>
filesByStem.has(getScriptFileStem(remoteFilename)),
);
const states = new Map<string, ScriptStoreInstallState>();
if (!hasInstalledScripts) {
remoteFiles.forEach(({ source }) => states.set(source, "install"));
return states;
}
const files = await getDirectoryInfo();
remoteFiles.forEach(({ source, remoteFilename }) => {
const scriptFile =
filesByStem.get(getScriptFileStem(remoteFilename))?.[0] ?? null;
if (!scriptFile) {
states.set(source, "install");
return;
}
states.set(
source,
files
? getInstallStateFromDirectoryInfo(
plugin,
scriptFile,
remoteFilename,
files,
)
: "error",
);
});
return states;
};
/** Resolves one community script's install/update state. */
export const getScriptInstallState = async (
plugin: ScriptLibraryPluginContext,
source: string,
): Promise<ScriptStoreInstallState> =>
(await getScriptInstallStates(plugin, [source])).get(source) ?? "error";
const restartSidepanelTabIfActive = async (
plugin: ScriptLibraryPluginContext,
scriptFile: TFile,
): Promise<void> => {
const scriptName = plugin.scriptEngine.getScriptName(scriptFile);
const spView = ExcalidrawSidepanelView.getExisting(false);
if (!spView || !scriptName || !spView.getTabByScript(scriptName)) {
return;
}
try {
await spView.restartTabForScript(scriptName);
} catch (error: unknown) {
errorlog({
where: "scriptLibraryUtils.restartSidepanelTabIfActive",
error,
scriptName,
});
}
const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
const scriptStem = getScriptFileStem(fname);
const folder = `${plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
const getLocalScriptPath = (): string =>
`${folder}/${scriptStem}.${getManagedScriptFileExtension(
};
export type InstalledScriptResult = {
scriptFile: TFile;
iconFile: TFile | null;
};
/** Installs or updates one managed community script. */
export const installScript = async (
plugin: ScriptLibraryPluginContext,
source: string,
showNotice = true,
): Promise<InstalledScriptResult> => {
const remoteFilename = decodeRemoteFilename(source);
const scriptStem = getScriptFileStem(remoteFilename);
const folder = getDownloadedScriptsFolder(plugin);
let scriptFile = getLocalScriptFile(plugin, remoteFilename);
const getLocalScriptPath = (): string => {
const targetFolder = scriptFile?.parent?.path ?? folder;
return `${targetFolder}/${scriptStem}.${getManagedScriptFileExtension(
plugin.settings.allowJavaScriptFiles,
plugin.settings.storeScriptFilesAsJavaScript,
)}`;
let scriptFile =
plugin.app.vault.getFileByPath(`${folder}/${scriptStem}.md`) ??
plugin.app.vault.getFileByPath(`${folder}/${scriptStem}.js`);
let scriptPath = getLocalScriptPath();
const svgPath = getIMGFilename(scriptPath, "svg");
let svgFile = plugin.app.vault.getFileByPath(svgPath);
setButtonText(scriptFile ? "CHECKING" : "INSTALL");
button.onclick = async () => {
const download = async (
url: string,
file: TFile,
localPath: string,
): Promise<TFile> => {
const data = await request({ url });
if (!data || data.startsWith("404: Not Found")) {
return null;
}
return await createOrOverwriteFile(
plugin.app,
file?.path ?? localPath,
data,
);
};
};
try {
let scriptPath = getLocalScriptPath();
let iconFile = plugin.app.vault.getFileByPath(
getIMGFilename(scriptPath, "svg"),
);
const fetchRemote = async (url: string): Promise<string | null> => {
const data = await request({ url });
if (!data || data.startsWith("404: Not Found")) {
return null;
}
return data;
};
try {
const [scriptData, iconData] = await Promise.all([
fetchRemote(source),
fetchRemote(getIMGFilename(source, "svg")),
]);
if (!scriptData) {
throw new Error("Script file not found");
}
await plugin.scriptEngine.withScriptFileEventsSuspended(async () => {
scriptPath = getLocalScriptPath();
if (scriptFile && scriptFile.path !== scriptPath) {
if (plugin.app.vault.getFileByPath(scriptPath)) {
// Keep the authoritative Markdown variant when both extensions
// already exist; format migration reports and skips this pair.
scriptPath = scriptFile.path;
} else {
await plugin.scriptEngine.renameManagedScriptFile(
@@ -110,96 +518,95 @@ export const installButton = async (
);
}
}
scriptFile = await download(source, scriptFile, scriptPath);
if (!scriptFile) {
setButtonText("ERROR");
throw new Error("File not found");
scriptFile = await createOrOverwriteFile(
plugin.app,
scriptFile?.path ?? scriptPath,
scriptData,
);
const iconPath = getIMGFilename(scriptFile.path, "svg");
if (iconData) {
const existingIcon = plugin.app.vault.getFileByPath(iconPath);
iconFile = await createOrOverwriteFile(
plugin.app,
existingIcon?.path ?? iconPath,
iconData,
);
} else {
iconFile = null;
}
svgFile = await download(getIMGFilename(source, "svg"), svgFile, svgPath);
setButtonText("UPTODATE");
if (Object.keys(plugin.scriptEngine.scriptIconMap).length === 0) {
await plugin.scriptEngine.loadScripts();
}
const restartSidepanelTabIfActive = async () => {
if (!plugin.scriptEngine || !(scriptFile instanceof TFile)) {
return;
}
const scriptName = plugin.scriptEngine.getScriptName(scriptFile);
const spView = ExcalidrawSidepanelView.getExisting(false);
if (!spView || !scriptName || !spView.getTabByScript(scriptName)) {
return;
}
try {
await spView.restartTabForScript(scriptName);
} catch (error: unknown) {
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.restartSidepanelTab",
error,
scriptName,
});
}
};
await restartSidepanelTabIfActive();
new Notice(`Installed: ${scriptFile.basename}`);
} catch (e: unknown) {
new Notice(`Error installing script: ${fname}`);
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
error: e,
});
});
if (!scriptFile) {
throw new Error("Script file was not created");
}
};
if (button2) {
button2.onclick = button.onclick;
await plugin.scriptEngine.refreshManagedScriptFile(scriptFile);
await restartSidepanelTabIfActive(plugin, scriptFile);
if (showNotice) {
new Notice(`${t("SCRIPT_INSTALLED_NOTICE")}: ${scriptFile.basename}`);
}
return { scriptFile, iconFile };
} catch (error: unknown) {
if (showNotice) {
new Notice(`${t("SCRIPT_INSTALL_ERROR_NOTICE")}: ${remoteFilename}`);
}
errorlog({
where: "scriptLibraryUtils.installScript",
source,
error,
});
throw error;
}
};
//check modified date on github
//https://superuser.com/questions/1406875/how-to-get-the-latest-commit-date-of-a-file-from-a-given-github-reposotiry
if (!scriptFile || !(scriptFile instanceof TFile)) {
return;
/**
* Returns community scripts with updates, considering only managed copies under
* the Downloaded folder. When duplicate managed copies exist, update detection
* uses the same primary-copy selection as the script-store details page.
*/
export const getInstalledScriptUpdates = async (
plugin: ScriptLibraryPluginContext,
): Promise<string[]> => {
if (!plugin.settings.scriptFolderPath) {
return [];
}
const files = new Map<string, number>();
const directoryInfo = JSON.parse(
await request({
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
}),
) as RemoteDirectoryInfo[];
directoryInfo.forEach((file) => files.set(file.fname, file.mtime));
const copiesByStem = getManagedScriptFilesByStem(plugin);
if (copiesByStem.size === 0) {
return [];
}
const files = await getDirectoryInfo();
if (!files) {
return [];
}
const checkModifyDate = (
gitFilename: string,
file: TFile,
): "ERROR" | "UPDATE" | "UPTODATE" => {
if (files.size === 0 || !files.has(gitFilename)) {
//setButtonText("ERROR");
return "ERROR";
const updates: string[] = [];
copiesByStem.forEach((copies, stem) => {
const scriptFile = copies[0];
if (!scriptFile) {
return;
}
const mtime = files.get(gitFilename);
if (!file || mtime > file.stat.mtime) {
//setButtonText("UPDATE");
return "UPDATE";
const remoteFilename = files.has(`${stem}.md`)
? `${stem}.md`
: files.has(`${stem}.js`)
? `${stem}.js`
: null;
if (!remoteFilename) {
return;
}
return "UPTODATE";
};
const scriptButtonText = checkModifyDate(fname, scriptFile);
const svgButtonText = checkModifyDate(
getIMGFilename(fname, "svg"),
!svgFile || !(svgFile instanceof TFile) ? null : svgFile,
);
if (
getInstallStateFromDirectoryInfo(
plugin,
scriptFile,
remoteFilename,
files,
) === "update"
) {
updates.push(stem);
}
});
setButtonText(
scriptButtonText === "UPTODATE" && svgButtonText === "UPTODATE"
? "UPTODATE"
: scriptButtonText === "UPTODATE" && svgButtonText === "ERROR"
? "UPTODATE"
: scriptButtonText === "ERROR"
? "ERROR"
: scriptButtonText === "UPDATE" || svgButtonText === "UPDATE"
? "UPDATE"
: "UPTODATE",
);
return updates.sort((a, b) => a.localeCompare(b));
};
+5 -50
View File
@@ -16,7 +16,6 @@ import {
getCommonBoundingBox,
DEVICE,
getContainerElement,
SCRIPT_INSTALL_FOLDER,
VIEW_TYPE_EXCALIDRAW,
} from "../constants/constants";
import type ExcalidrawPlugin from "../core/main";
@@ -46,18 +45,13 @@ import { VersionMismatchPrompt } from "src/shared/Dialogs/VersionMismatch";
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
import { FileData } from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
import { RemoteDirectoryInfo } from "src/types/githubTypes";
import { UIMode } from "src/shared/Dialogs/UIModeSettingComponent";
import ExcalidrawView from "../view/ExcalidrawView";
import { getEmptyDrawingElementsRuntime } from "src/constants/emptydrawing";
import { makeEntitiesXmlSafe, sanitizedFragment } from "./htmlUtils";
import { URLs } from "src/constants/safeUrls";
import { isInstanceOfSVGSVGElement } from "./typechecks";
import {
getPreferredScriptFiles,
getScriptFileStem,
isScriptFilePath,
} from "./scriptFileUtils";
import { getInstalledScriptUpdates } from "./scriptLibraryUtils";
export { arrayToMap };
export { errorlog, getDataURL } from "./coreUtils";
export { addAppendUpdateCustomData } from "./elementCustomDataUtils";
@@ -164,50 +158,11 @@ async function checkScriptUpdates() {
return;
}
const folder = `${EXCALIDRAW_PLUGIN.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
const installedScripts = getPreferredScriptFiles(
EXCALIDRAW_PLUGIN.app.vault
.getFiles()
.filter(
(file) => file.parent?.path === folder && isScriptFilePath(file.path),
),
);
if (installedScripts.length === 0) {
return;
}
// Get directory info from GitHub
const files = new Map<string, number>();
const directoryInfo = JSON.parse(
await request({
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
}),
) as RemoteDirectoryInfo[];
directoryInfo.forEach((f: RemoteDirectoryInfo) =>
files.set(f.fname, f.mtime),
);
if (files.size === 0) {
return;
}
// Check if any installed scripts have updates
const updates: string[] = [];
for (const scriptFile of installedScripts) {
const stem = getScriptFileStem(scriptFile.name);
const remoteMtime = Math.max(
files.get(`${stem}.md`) ?? 0,
files.get(`${stem}.js`) ?? 0,
);
if (remoteMtime > scriptFile.stat.mtime) {
updates.push(stem);
}
}
const updates = await getInstalledScriptUpdates(EXCALIDRAW_PLUGIN);
if (updates.length > 0) {
const message = `${t("SCRIPT_UPDATES_AVAILABLE")}\n\n${updates.sort().join("\n")}`;
new Notice(message, 8000 + updates.length * 1000);
const message = `${t("SCRIPT_UPDATES_AVAILABLE")}\n\n${updates.join("\n")}`;
const timeout = Math.min(60_000, 30_000 + updates.length * 2_000);
new Notice(message, timeout);
log(message);
}
} catch (e: unknown) {
+33 -3
View File
@@ -1,4 +1,4 @@
import { App, FileView, WorkspaceLeaf } from "obsidian";
import { App, FileView, WorkspaceLeaf, type ViewStateResult } from "obsidian";
import { DEVICE, VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
@@ -18,6 +18,11 @@ export async function switchToExcalidraw(app: App) {
}
export class ExcalidrawLoading extends FileView {
private integrationState: {
mode?: "view" | "edit";
zoomToFit?: true;
} = {};
constructor(
leaf: WorkspaceLeaf,
private plugin: ExcalidrawPlugin,
@@ -30,19 +35,44 @@ export class ExcalidrawLoading extends FileView {
this.displayLoadingText();
}
/** Retains one-shot integration options while the loading view owns the leaf. */
public async setState(
state: Record<string, unknown>,
result: ViewStateResult,
): Promise<void> {
this.integrationState = {
...(state.mode === "view" || state.mode === "edit"
? { mode: state.mode }
: {}),
...(state.zoomToFit === true ? { zoomToFit: true as const } : {}),
};
await super.setState(state, result);
}
/** Includes retained integration options in the handoff to the real Excalidraw view. */
public getState(): Record<string, unknown> {
return { ...super.getState(), ...this.integrationState };
}
public async switchToExcalidraw() {
const prevLeaf = this.app.workspace.getLeaf();
const state = this.leaf.view.getState();
const preserveInactive = this.app.workspace.getMostRecentLeaf() !== this.leaf;
const inactiveResult = preserveInactive
? ({ focus: false } as unknown as ViewStateResult)
: undefined;
// Force a fresh view instance: switching to the same type can be a no-op.
await this.leaf.setViewState({
type: "empty",
state: {},
});
...(preserveInactive ? { active: false } : {}),
}, inactiveResult);
await this.leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state,
});
...(preserveInactive ? { active: false } : {}),
}, inactiveResult);
if (DEVICE.isDesktop) {
return;
}
+78 -17
View File
@@ -56,7 +56,11 @@ import {
sceneCoordsToViewportCoords,
} from "../constants/constants";
import ExcalidrawPlugin from "../core/main";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import {
ExcalidrawAutomate,
type ViewLinkClickHook,
} from "../shared/ExcalidrawAutomate";
import type { PaneTarget } from "../types/utilTypes";
import { TextMode, getTextMode } from "../shared/TextMode";
import { ExcalidrawSidepanelView } from "./sidepanel/Sidepanel";
import {
@@ -578,6 +582,8 @@ export default class ExcalidrawView
private lastAppState: AppState | null = null;
private lastElementsVersion: number = -1;
private pendingMigrationHandoffToken: string | null = null;
private pendingOpenMode: "view" | "edit" | null = null;
private pendingOpenZoomToFit = false;
private pendingMigrationBinaryFiles: BinaryFiles | null = null;
private migrationBinaryFilePublication: Promise<void> | null = null;
private isSynchronizing = false;
@@ -1678,8 +1684,22 @@ export default class ExcalidrawView
element: ExcalidrawElement,
link: string,
event: MouseEvent | null,
action?: PaneTarget,
): boolean {
return this.linkNavigationManager.handleLinkHookCall(element, link, event);
return this.linkNavigationManager.handleLinkHookCall(
element,
link,
event,
action,
);
}
/** Registers an integration hook for link clicks originating from this view only. */
public registerViewLinkClickHook(
hook: ViewLinkClickHook,
ea: ExcalidrawAutomate,
): () => void {
return this.linkNavigationManager.registerViewLinkClickHook(hook, ea);
}
private getLinkTextForElement(
@@ -2983,6 +3003,9 @@ export default class ExcalidrawView
typeof state?.migrationHandoffToken === "string"
? state.migrationHandoffToken
: null;
this.pendingOpenMode =
state?.mode === "view" || state?.mode === "edit" ? state.mode : null;
this.pendingOpenZoomToFit = state?.zoomToFit === true;
await super.setState(state, result);
}
@@ -4008,16 +4031,21 @@ export default class ExcalidrawView
this.semaphores.justLoaded = justloaded;
this.clearDirty();
const om = this.excalidrawData.getOpenMode();
const requestedViewModeEnabled = this.pendingOpenMode === null
? null
: this.pendingOpenMode === "view";
this.clearOwnWriteReloadSuppression();
const penEnabled = this.plugin.isPenMode();
const api = this.excalidrawAPI;
if (api) {
//isLoaded flags that a new file is being loaded, isLoaded will be true after loadDrawing completes
const viewModeEnabled = !this.isLoaded
? excalidrawData.elements.length > 0
? om.viewModeEnabled
: false
: api.getAppState().viewModeEnabled;
const viewModeEnabled = requestedViewModeEnabled ?? (
!this.isLoaded
? excalidrawData.elements.length > 0
? om.viewModeEnabled
: false
: api.getAppState().viewModeEnabled
);
const zenModeEnabled = !this.isLoaded
? om.zenModeEnabled
: api.getAppState().zenModeEnabled;
@@ -4104,8 +4132,9 @@ export default class ExcalidrawView
}
: {}),
zenModeEnabled: om.zenModeEnabled,
viewModeEnabled:
excalidrawData.elements.length > 0 ? om.viewModeEnabled : false,
viewModeEnabled: requestedViewModeEnabled ?? (
excalidrawData.elements.length > 0 ? om.viewModeEnabled : false
),
linkOpacity: this.excalidrawData.getLinkOpacity(),
penMode: penEnabled,
penDetected: penEnabled,
@@ -4498,7 +4527,7 @@ export default class ExcalidrawView
return ICON_NAME;
}
async setMarkdownView(eState?: MarkdownViewOpenState) {
async setMarkdownView(eState?: MarkdownViewOpenState, active?: boolean) {
//save before switching to markdown view.
//this would also happen onClose, but it does not hurt to save it here
//this way isDirty() will return false in onClose, thus
@@ -4531,7 +4560,11 @@ export default class ExcalidrawView
}
plugin.excalidrawFileModes[this.id || file.path] = "markdown";
await plugin.setMarkdownView(leaf, eState as ViewStateResult | undefined);
await plugin.setMarkdownView(
leaf,
eState as ViewStateResult | undefined,
active,
);
} catch (e: unknown) {
errorlog({
where: "ExcalidrawView.setMarkdownView",
@@ -4541,7 +4574,7 @@ export default class ExcalidrawView
}
}
public async openAsMarkdown(eState?: MarkdownViewOpenState) {
public async openAsMarkdown(eState?: MarkdownViewOpenState, active?: boolean) {
if (
this.plugin.settings.compress &&
this.plugin.settings.decompressForMDView
@@ -4551,7 +4584,7 @@ export default class ExcalidrawView
} else if (this.isDirty()) {
await this.save(true, true, true);
}
void this.setMarkdownView(eState);
await this.setMarkdownView(eState, active);
}
public async convertExcalidrawToMD() {
@@ -5320,6 +5353,7 @@ export default class ExcalidrawView
gridColor: st.gridColor,
colorPalette: st.colorPalette,
colorTopPicks: st.colorTopPicks,
fontTopPicks: st.fontTopPicks,
currentStrokeOptions: st.currentStrokeOptions,
frameRendering: st.frameRendering,
objectsSnapModeEnabled: st.objectsSnapModeEnabled,
@@ -5943,11 +5977,24 @@ export default class ExcalidrawView
return;
}
this.semaphores.justLoaded = false;
const pendingOpenMode = this.pendingOpenMode;
const pendingOpenZoomToFit = this.pendingOpenZoomToFit;
this.pendingOpenMode = null;
this.pendingOpenZoomToFit = false;
if (pendingOpenMode) {
const viewModeEnabled = pendingOpenMode === "view";
this.updateScene({
appState: { viewModeEnabled },
captureUpdate: CaptureUpdateAction.NEVER,
});
this.toolsPanelRef?.current?.setExcalidrawViewMode(viewModeEnabled);
}
if (
!this.semaphores.preventAutozoom &&
this.plugin.settings.zoomToFitOnOpen
(pendingOpenZoomToFit || this.plugin.settings.zoomToFitOnOpen)
) {
if (
pendingOpenZoomToFit ||
getExcalidraAndMarkdowViewsForFile(this.app, this.file).length === 1
) {
this.zoomToFit(false, true);
@@ -6677,8 +6724,22 @@ export default class ExcalidrawView
}
window.setTimeout(() => this.removeLinkTooltip(), 500);
let event = e?.detail?.nativeEvent;
if (this.handleLinkHookCall(element, link, event as MouseEvent)) {
const nativeEvent = e?.detail?.nativeEvent;
const ownerMouseEvent = this.ownerWindow?.MouseEvent;
const event = nativeEvent ?? new (ownerMouseEvent ?? MouseEvent)("click", {
...emulateKeysForLinkClick("new-tab"),
});
const hasModifier =
event.shiftKey || event.ctrlKey || event.metaKey || event.altKey;
const linkAction = hasModifier ? linkClickModifierType(event) : "new-tab";
if (
this.handleLinkHookCall(
element,
link,
event as MouseEvent,
linkAction,
)
) {
return;
}
//if(openExternalLink(element.link, this.app, !isSHIFT(event) && !isWinCTRLorMacCMD(event) && !isWinMETAorMacCTRL(event) && !isWinALTorMacOPT(event) ? element : undefined)) return;
@@ -6686,7 +6747,7 @@ export default class ExcalidrawView
return;
}
if (!event.shiftKey && !event.ctrlKey && !event.metaKey && !event.altKey) {
if (!hasModifier) {
void this.linkClick(
null,
null,
+27 -12
View File
@@ -22,6 +22,7 @@ import {
createLeaf,
predictViewType,
} from "src/utils/customEmbeddableUtils";
import { mountEmbeddableHost } from "src/utils/embeddableMountPlan";
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
import { EmbeddableLeafRef } from "src/types/excalidrawViewTypes";
import { t } from "src/lang/helpers";
@@ -859,20 +860,13 @@ function RenderObsidianView({
};
patchMobileView(view);
//if subpath is defined, create a canvas node else create a workspace leaf
if (
subpath &&
view.canvasNodeFactory.isInitialized() &&
file.extension.toLowerCase() === "md"
) {
createNode("markdown");
} else {
const mountWorkspaceLeaf = () => {
const viewType = predictViewType(view.app, file);
// markdown could still be a kanban board or other custom view on top of markdown, those need to be displayed in leaves
if (
viewType !== "markdown" &&
CANVAS_VIEWTYPES.has(viewType) &&
view.canvasNodeFactory.isInitialized()
view.canvasNodeFactory?.isInitialized()
) {
createNode(viewType);
if (viewType === "pdf") {
@@ -900,7 +894,7 @@ function RenderObsidianView({
}
if (
viewType === "markdown" &&
view.canvasNodeFactory.isInitialized()
view.canvasNodeFactory?.isInitialized()
) {
createNode("markdown");
//I haven't found a better way of deciding if an .md file has its own view (e.g., kanban) or not
@@ -931,9 +925,30 @@ function RenderObsidianView({
}
})();
}
}
};
let effectCancelled = false;
//if subpath is defined, create a canvas node else create a workspace leaf
void mountEmbeddableHost({
subpath,
fileExtension: file.extension,
getHost: () => view.canvasNodeFactory,
isCancelled: () =>
effectCancelled || !leafRef.current || !containerRef.current,
createCanvasNode: () => createNode("markdown"),
createWorkspaceLeaf: mountWorkspaceLeaf,
}).catch((error: unknown) => {
errorlog({
where: "CustomEmbeddable.mount",
fn: "mountEmbeddableHost",
error,
});
});
return () => {
effectCancelled = true;
// disconnect observer if any
pdfObserverRef.currentCleanup?.();
pdfObserverRef.current?.disconnect();
@@ -956,7 +971,7 @@ function RenderObsidianView({
if (!leafRef.current) {
return;
}
view.canvasNodeFactory.removeNode(leafRef.current.node, element.id);
view.canvasNodeFactory?.removeNode(leafRef.current.node, element.id);
leafRef.current.leaf?.detach();
leafRef.current = null;
}; //cleanup on unmount
+59 -17
View File
@@ -8,7 +8,14 @@ node.render();
container.appendChild(node.contentEl)
*/
import { Editor, TFile, View, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
import {
type App,
Editor,
TFile,
View,
WorkspaceLeaf,
WorkspaceSplit,
} from "obsidian";
import type ExcalidrawView from "src/view/ExcalidrawView";
import {
getContainerForDocument,
@@ -29,6 +36,12 @@ interface ObsidianCanvas {
removeNode: (node: ObsidianCanvasNode) => void;
}
type DetachedWorkspaceSplit = WorkspaceSplit & {
insertChild(index: number, child: WorkspaceLeaf, resize?: boolean): void;
};
type WorkspaceLeafConstructor = new (app: App) => WorkspaceLeaf;
export interface ObsidianCanvasNodeChild extends View {
file?: TFile;
heading?: string;
@@ -59,6 +72,14 @@ export class CanvasNodeFactory {
nodes = new Map<string, ObsidianCanvasNode>();
initialized: boolean = false;
public isInitialized = () => this.initialized;
private settleInitialized: (initialized: boolean) => void;
/**
* Settles true once `initialize()` succeeded, false once it failed or the
* factory was destroyed.
*/
public readonly whenInitialized = new Promise<boolean>((resolve) => {
this.settleInitialized = resolve;
});
private observer: CustomMutationObserver | MutationObserver;
private readonly pendingEditRequests = new WeakMap<
ObsidianCanvasNode,
@@ -68,24 +89,44 @@ export class CanvasNodeFactory {
constructor(private view: ExcalidrawView) {}
public async initialize() {
const app = this.view.app;
const canvasPlugin = app.internalPlugins.plugins.canvas;
try {
if (!this.view) {
return;
}
const app = this.view.app;
const canvasPlugin = app.internalPlugins.plugins.canvas;
if (!canvasPlugin._loaded) {
await canvasPlugin.load();
if (!canvasPlugin._loaded) {
await canvasPlugin.load();
}
// Closing or migrating the view can destroy this factory during loading.
if (!this.view) {
return;
}
const doc = this.view.ownerDocument;
const rootSplit: WorkspaceSplit =
new (WorkspaceSplit as ConstructableWorkspaceSplit)(
app.workspace,
"vertical",
);
rootSplit.getRoot = () =>
app.workspace[doc === mainDocument ? "rootSplit" : "floatingSplit"];
rootSplit.getContainer = () => getContainerForDocument(doc);
// `workspace.createLeafInParent()` activates its new leaf and schedules a workspace layout
// update. That is observable even though this split is detached: on mobile it navigates away
// from an open sidebar that hosts an embedded Excalidraw view. Construct and insert the
// internal Canvas leaf directly so initialization has no workspace activation side effect.
const LeafConstructor = WorkspaceLeaf as unknown as WorkspaceLeafConstructor;
this.leaf = new LeafConstructor(app);
(rootSplit as DetachedWorkspaceSplit).insertChild(0, this.leaf);
this.canvas = canvasPlugin.views.canvas(this.leaf)
.canvas as ObsidianCanvas;
this.initialized = true;
this.settleInitialized(true);
} catch (error) {
this.settleInitialized(false);
throw error;
}
const doc = this.view.ownerDocument;
const rootSplit: WorkspaceSplit =
new (WorkspaceSplit as ConstructableWorkspaceSplit)(
app.workspace,
"vertical",
);
rootSplit.getRoot = () =>
app.workspace[doc === mainDocument ? "rootSplit" : "floatingSplit"];
rootSplit.getContainer = () => getContainerForDocument(doc);
this.leaf = app.workspace.createLeafInParent(rootSplit, 0);
this.canvas = canvasPlugin.views.canvas(this.leaf).canvas as ObsidianCanvas;
this.initialized = true;
}
public createFileNote(
@@ -277,6 +318,7 @@ export class CanvasNodeFactory {
destroy() {
this.purgeNodes();
this.initialized = false; //calling after purgeNodes becaues purge nodes checks for initialized
this.settleInitialized(false); //release anyone still waiting to be able to create a node
this.observer?.disconnect();
this.view = null;
this.canvas = null;
+45 -1
View File
@@ -16,6 +16,10 @@ import type {
SelectedImage,
} from "../../types/excalidrawViewTypes";
import type { ModifierKeys } from "../../utils/modifierkeyHelper";
import type {
ExcalidrawAutomate,
ViewLinkClickHook,
} from "../../shared/ExcalidrawAutomate";
import { getMermaidText, shouldRenderMermaid } from "../../utils/mermaidUtils";
import type ExcalidrawView from "../ExcalidrawView";
@@ -57,6 +61,11 @@ export interface ViewLinkNavigationDependencies {
* this module does not create a runtime import cycle.
*/
export class ViewLinkNavigationManager {
private readonly viewLinkClickHooks = new Set<{
hook: ViewLinkClickHook;
ea: ExcalidrawAutomate;
}>();
public constructor(
private readonly view: ExcalidrawView,
private readonly dependencies: ViewLinkNavigationDependencies,
@@ -80,6 +89,9 @@ export class ViewLinkNavigationManager {
element: ExcalidrawElement,
link: string,
event: MouseEvent | null,
action = this.dependencies.linkClickModifierType(
event ?? this.dependencies.emulateKeysForLinkClick("new-tab"),
),
): boolean {
if (this.view.getHookServer().onLinkClickHook) {
try {
@@ -102,9 +114,41 @@ export class ViewLinkNavigationManager {
});
}
}
for (const registration of this.viewLinkClickHooks) {
try {
if (
registration.hook({
element,
linkText: link,
event,
action,
view: this.view,
ea: registration.ea,
}) === false
) {
return true;
}
} catch (e: unknown) {
this.dependencies.errorlog({
where: "ViewLinkNavigationManager.handleLinkHookCall",
fn: "registerViewLinkClickHook callback",
error: e,
});
}
}
return false;
}
/** Registers a link-click hook whose lifetime and dispatch are scoped to this view. */
public registerViewLinkClickHook(
hook: ViewLinkClickHook,
ea: ExcalidrawAutomate,
): () => void {
const registration = { hook, ea };
this.viewLinkClickHooks.add(registration);
return () => this.viewLinkClickHooks.delete(registration);
}
/** Resolves the effective link and source element for a view selection. */
public getLinkTextForElement(
selectedText: SelectedElementWithLink,
@@ -550,7 +594,7 @@ export class ViewLinkNavigationManager {
const sceneElements = this.view.excalidrawAPI.getSceneElements() as readonly
ExcalidrawElement[];
const el = sceneElements.filter((element) => element.id === id)[0];
if (this.view.handleLinkHookCall(el, linkText, ev)) {
if (this.view.handleLinkHookCall(el, linkText, ev, linkClickType)) {
return;
}
+15
View File
@@ -98,6 +98,18 @@ const setBlockReferenceIcon = (button: ButtonComponent): void => {
button.setIcon(BLOCK_REFERENCE_ICON_ID);
};
/**
* Forces a Markdown-image editor view into edit mode, regardless of the
* user's `defaultViewMode` vault setting. Reading mode is not meaningful in
* this embedded editor and leaves the user with no way to switch back.
*/
const forceSourceMode = (view: MarkdownView): void => {
const modes = view.modes;
if (modes?.source) {
view.setMode?.(modes.source);
}
};
const getNativeColorValue = (color: string): string => {
if (/^#[0-9a-f]{6}$/i.test(color)) {
return color;
@@ -1673,6 +1685,7 @@ class MarkdownImageEditorController {
} else {
await leaf.openFile(sourceFile, {
active: false,
state: { mode: "source" },
});
}
if (
@@ -1685,6 +1698,7 @@ class MarkdownImageEditorController {
return;
}
if (leaf.view instanceof MarkdownView) {
forceSourceMode(leaf.view);
this.editorView = leaf.view;
this.prepareEditorView(host, leaf.view);
this.revealExternalSourceSubpath(leaf.view, sourceFile, ref);
@@ -1727,6 +1741,7 @@ class MarkdownImageEditorController {
return;
}
fragmentView.setViewData(source.markdown, true);
forceSourceMode(fragmentView);
this.editorView = fragmentView;
this.prepareEditorView(host, fragmentView);
this.watchEditorChanges();
+831 -130
View File
@@ -1014,10 +1014,6 @@ End Obsidian Sheets Plus support
margin-right: 0.5em;
}
.excalidraw-installCodeBlock-link {
padding-right: 10px;
}
.excalidraw-insertpdf-infolabel {
min-width: 2.3em;
text-align: right;
@@ -1096,12 +1092,12 @@ End Obsidian Sheets Plus support
min-width: calc(6 * var(--default-button-size));
}
/* Radix portals the canvas menu under the owning document's body. Keep it on
Obsidian's menu layer so body-level Obsidian tooltips remain above it. */
body > [data-radix-portal] .main-menu {
z-index: var(--layer-menu);
}
/* Radix portals the canvas menu under the owning document's body. Keep it on
Obsidian's menu layer so body-level Obsidian tooltips remain above it. */
body>[data-radix-portal] .main-menu {
z-index: var(--layer-menu);
}
.excalidraw-pen-settings-floating-actions {
position: sticky;
bottom: -20px;
@@ -1616,123 +1612,828 @@ button.excalidraw-font-picker {
}
.excalidraw-font-picker-menu-opening .menu,
.menu.excalidraw-font-picker-menu--desktop {
max-height: min(420px, 60vh);
overflow-y: auto;
}
.setting-item.excalidraw-declarative-full-width {
display: block;
width: 100%;
}
.excalidraw-declarative-settings-toolbar {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: var(--size-4-2) var(--size-4-3);
margin-bottom: var(--size-4-1);
font-size: var(--font-ui-smaller);
}
.excalidraw-declarative-settings-toolbar button,
.excalidraw-declarative-settings-toolbar a {
white-space: nowrap;
}
.excalidraw-declarative-settings-toolbar button {
font-size: inherit;
}
.excalidraw-declarative-settings-toolbar a {
color: var(--text-accent);
text-decoration: none;
}
.excalidraw-declarative-settings-toolbar a:hover {
color: var(--text-accent-hover);
text-decoration: underline;
}
.excalidraw-settings-breadcrumbs {
display: flex;
align-items: baseline;
justify-content: center;
flex-wrap: wrap;
gap: var(--size-4-1);
margin: 0;
color: var(--text-muted);
font-size: var(--font-ui-small);
}
.excalidraw-settings-breadcrumbs__link {
height: auto;
padding: 0;
border: 0;
background: transparent;
box-shadow: none;
color: var(--text-accent);
cursor: pointer;
font-size: inherit;
font-weight: inherit;
text-decoration: none;
touch-action: manipulation;
}
.excalidraw-settings-breadcrumbs__link:hover {
background: transparent;
box-shadow: none;
color: var(--text-accent-hover);
text-decoration: underline;
}
.excalidraw-settings-breadcrumbs__link.is-disabled {
color: var(--text-muted);
cursor: default;
pointer-events: none;
}
.is-mobile .excalidraw-settings-breadcrumbs__link,
.is-tablet .excalidraw-settings-breadcrumbs__link {
min-height: var(--interactive-normal);
padding-inline: var(--size-2-2);
}
.excalidraw-settings-breadcrumbs__current {
color: var(--text-normal);
font-weight: var(--font-semibold);
}
.excalidraw-settings-breadcrumbs__separator {
color: var(--text-faint);
}
.excalidraw-settings .setting-item-description a[href^="#"],
.excalidraw-settings-page .setting-item-description a[href^="#"] {
color: var(--text-accent);
font-weight: var(--font-medium);
text-decoration: underline;
}
.excalidraw-settings .setting-item-description a[href^="#"]:hover,
.excalidraw-settings-page .setting-item-description a[href^="#"]:hover {
color: var(--text-accent-hover);
}
.excalidraw-filename-information {
display: grid;
grid-template-columns: minmax(12rem, 0.8fr) minmax(18rem, 1.2fr);
gap: var(--size-4-4);
align-items: start;
}
.excalidraw-filename-information > :first-child {
min-width: 0;
}
@media (max-width: 700px) {
.excalidraw-filename-information {
grid-template-columns: 1fr;
}
}
.menu.excalidraw-font-picker-menu--desktop {
max-height: min(420px, 60vh);
overflow-y: auto;
}
.setting-item.excalidraw-declarative-full-width {
display: block;
width: 100%;
}
.excalidraw-declarative-settings-toolbar {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: var(--size-4-2) var(--size-4-3);
margin-bottom: var(--size-4-1);
font-size: var(--font-ui-smaller);
}
.excalidraw-declarative-settings-toolbar button,
.excalidraw-declarative-settings-toolbar a {
white-space: nowrap;
}
.excalidraw-declarative-settings-toolbar button {
font-size: inherit;
}
.excalidraw-declarative-settings-toolbar a {
color: var(--text-accent);
text-decoration: none;
}
.excalidraw-declarative-settings-toolbar a:hover {
color: var(--text-accent-hover);
text-decoration: underline;
}
.excalidraw-settings-breadcrumbs {
display: flex;
align-items: baseline;
justify-content: center;
flex-wrap: wrap;
gap: var(--size-4-1);
margin: 0;
color: var(--text-muted);
font-size: var(--font-ui-small);
}
.excalidraw-settings-breadcrumbs__link {
height: auto;
padding: 0;
border: 0;
background: transparent;
box-shadow: none;
color: var(--text-accent);
cursor: pointer;
font-size: inherit;
font-weight: inherit;
text-decoration: none;
touch-action: manipulation;
}
.excalidraw-settings-breadcrumbs__link:hover {
background: transparent;
box-shadow: none;
color: var(--text-accent-hover);
text-decoration: underline;
}
.excalidraw-settings-breadcrumbs__link.is-disabled {
color: var(--text-muted);
cursor: default;
pointer-events: none;
}
.is-mobile .excalidraw-settings-breadcrumbs__link,
.is-tablet .excalidraw-settings-breadcrumbs__link {
min-height: var(--interactive-normal);
padding-inline: var(--size-2-2);
}
.excalidraw-settings-breadcrumbs__current {
color: var(--text-normal);
font-weight: var(--font-semibold);
}
.excalidraw-settings-breadcrumbs__separator {
color: var(--text-faint);
}
.excalidraw-settings .setting-item-description a[href^="#"],
.excalidraw-settings-page .setting-item-description a[href^="#"] {
color: var(--text-accent);
font-weight: var(--font-medium);
text-decoration: underline;
}
.excalidraw-settings .setting-item-description a[href^="#"]:hover,
.excalidraw-settings-page .setting-item-description a[href^="#"]:hover {
color: var(--text-accent-hover);
}
.excalidraw-filename-information {
display: grid;
grid-template-columns: minmax(12rem, 0.8fr) minmax(18rem, 1.2fr);
gap: var(--size-4-4);
align-items: start;
}
.excalidraw-filename-information> :first-child {
min-width: 0;
}
@media (max-width: 700px) {
.excalidraw-filename-information {
grid-template-columns: 1fr;
}
}
/* Community Script Store */
.excalidraw-script-store .modal {
width: min(1100px, 96vw);
max-width: 1100px;
height: min(900px, 92vh);
max-height: 92vh;
}
.excalidraw-script-store .modal-content {
max-width: none;
user-select: text;
}
.excalidraw-script-store__content {
display: flex;
flex-direction: column;
gap: 1rem;
padding-bottom: 1rem;
}
.excalidraw-script-store__loading {
min-height: 16rem;
display: flex;
align-items: center;
justify-content: center;
gap: 0.75rem;
color: var(--text-muted);
}
.excalidraw-script-store__loading-icon svg {
animation: excalidraw-script-store-spin 1s linear infinite;
}
@keyframes excalidraw-script-store-spin {
to {
transform: rotate(360deg);
}
}
.excalidraw-script-store__support-bar {
display: grid;
grid-template-columns: 1fr 1fr;
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-l);
background: var(--background-secondary);
overflow: hidden;
}
.excalidraw-script-store__support-item {
display: flex;
align-items: center;
gap: 0.75rem;
min-width: 0;
padding: 0.65rem 0.85rem;
color: var(--text-normal);
text-decoration: none;
}
.excalidraw-script-store__support-item+.excalidraw-script-store__support-item {
border-left: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__support-item:hover {
background: var(--background-modifier-hover);
color: var(--text-normal);
text-decoration: none;
}
.excalidraw-script-store__support-logo {
flex: 0 0 auto;
width: 2.75rem;
height: 2.75rem;
object-fit: contain;
border-radius: 50%;
}
.excalidraw-script-store__support-icon {
flex: 0 0 2.75rem;
width: 2.75rem;
height: 2.75rem;
display: flex;
align-items: center;
justify-content: center;
color: var(--interactive-accent);
}
.excalidraw-script-store__support-icon svg {
width: 1.75rem;
height: 1.75rem;
}
.excalidraw-script-store__support-text {
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.1rem;
}
.excalidraw-script-store__support-text strong {
font-size: var(--font-ui-medium);
}
.excalidraw-script-store__support-text span {
color: var(--text-muted);
font-size: var(--font-ui-small);
}
.excalidraw-script-store__scripting-promo {
width: 100%;
}
.excalidraw-script-store__scripting-link {
display: block;
width: min(900px, 100%);
margin: 0 auto;
color: var(--text-normal);
text-decoration: none;
}
.excalidraw-script-store__scripting-link:hover {
color: var(--interactive-accent);
text-decoration: none;
}
.excalidraw-script-store__scripting-banner {
display: block;
width: 100%;
aspect-ratio: 3 / 1;
object-fit: cover;
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-l);
}
.excalidraw-script-store__scripting-caption {
padding: 0.45rem 0.5rem 0;
text-align: center;
font-size: var(--font-ui-small);
font-weight: var(--font-semibold);
}
.excalidraw-script-store__updates {
padding: 0.9rem;
border: 1px solid var(--interactive-accent);
border-radius: var(--radius-l);
background: var(--background-secondary);
}
.excalidraw-script-store__updates-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
}
.excalidraw-script-store__updates h2,
.excalidraw-script-store__browse-header h2 {
margin: 0;
}
.excalidraw-script-store__updates p,
.excalidraw-script-store__browse-header p {
margin: 0.2rem 0 0;
color: var(--text-muted);
}
.excalidraw-script-store__inline-icon {
display: inline-flex;
margin-left: 0.45rem;
vertical-align: text-bottom;
}
.excalidraw-script-store__inline-icon svg {
width: 1em;
height: 1em;
}
.excalidraw-script-store__update-list {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
margin-top: 0.75rem;
}
.excalidraw-script-store__update-chip {
padding: 0.25rem 0.6rem;
border-radius: var(--radius-s);
font-size: var(--font-ui-smaller);
}
.excalidraw-script-store__browse-header {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.excalidraw-script-store__controls {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.excalidraw-script-store__search {
position: relative;
flex: 1 1 18rem;
min-width: 12rem;
}
.excalidraw-script-store__search>span {
position: absolute;
left: 0.65rem;
top: 50%;
transform: translateY(-50%);
display: flex;
color: var(--text-faint);
pointer-events: none;
}
.excalidraw-script-store__search svg {
width: 1rem;
height: 1rem;
}
.excalidraw-script-store__search input {
width: 100%;
padding-left: 2rem;
}
.excalidraw-script-store__controls select {
min-width: 12rem;
}
.excalidraw-script-store__view-toggle {
display: flex;
}
.excalidraw-script-store__view-toggle button {
border-radius: 0;
}
.excalidraw-script-store__view-toggle button:first-child {
border-radius: var(--button-radius) 0 0 var(--button-radius);
}
.excalidraw-script-store__view-toggle button:last-child {
border-radius: 0 var(--button-radius) var(--button-radius) 0;
}
.excalidraw-script-store__view-toggle button.is-active {
background: var(--interactive-accent);
color: var(--text-on-accent);
}
.excalidraw-script-store__result-summary {
margin-bottom: 0.55rem;
color: var(--text-muted);
font-size: var(--font-ui-small);
}
.excalidraw-script-store__grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 0.7rem;
}
.excalidraw-script-store__card {
display: flex;
flex-direction: column;
min-height: 15rem;
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-m);
background: var(--background-primary);
overflow: hidden;
transition:
border-color var(--anim-duration-fast) ease-in-out,
transform var(--anim-duration-fast) ease-in-out;
}
.excalidraw-script-store__card:hover {
border-color: var(--background-modifier-border-hover);
transform: translateY(-1px);
}
.excalidraw-script-store__card.has-update {
border-color: var(--interactive-accent);
}
.excalidraw-script-store__card-main {
flex: 1;
display: flex;
align-items: flex-start;
gap: 0.8rem;
width: 100%;
padding: 0.9rem;
border: 0;
border-radius: 0;
box-shadow: none;
background: transparent;
color: var(--text-normal);
text-align: left;
white-space: normal;
cursor: pointer;
}
.excalidraw-script-store__card-main:hover {
background: var(--background-modifier-hover);
}
.excalidraw-script-store__icon {
position: relative;
flex: 0 0 3.1rem;
width: 3.1rem;
height: 3.1rem;
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--radius-m);
background: var(--background-secondary);
overflow: hidden;
}
.excalidraw-script-store__icon img {
position: relative;
z-index: 1;
width: 2.55rem;
height: 2.55rem;
object-fit: contain;
}
/* Script icons are external SVG images and cannot inherit --icon-fill-color
* like the inline SVGs in the Excalidraw tools panel. Match Excalidraw's
* dark-theme image treatment (THEME_FILTER) so monochrome script icons stay
* legible on dark store backgrounds. */
.theme-dark .excalidraw-script-store__icon img,
.theme-dark .excalidraw-script-store__detail-icon img {
filter: invert(93%) hue-rotate(180deg) saturate(1.25);
}
.excalidraw-script-store__icon img.is-hidden,
.excalidraw-script-store__detail-icon img.is-hidden {
display: none;
}
.excalidraw-script-store__icon-fallback,
.excalidraw-script-store__detail-icon-fallback {
position: absolute;
display: none;
align-items: center;
justify-content: center;
color: var(--text-muted);
}
.excalidraw-script-store__icon-fallback.is-visible,
.excalidraw-script-store__detail-icon-fallback.is-visible {
display: flex;
}
.excalidraw-script-store__card-text {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
}
.excalidraw-script-store__title-row {
display: flex;
align-items: flex-start;
flex-wrap: wrap;
gap: 0.3rem;
}
.excalidraw-script-store__title-row h3 {
flex: 1 1 10rem;
min-width: 0;
margin: 0;
font-size: var(--font-ui-medium);
line-height: 1.25;
white-space: normal;
overflow-wrap: anywhere;
}
.excalidraw-script-store__author {
margin-top: 0.15rem;
color: var(--text-faint);
font-size: var(--font-ui-smaller);
}
.excalidraw-script-store__card-text p {
display: -webkit-box;
margin: 0.55rem 0 0;
overflow: hidden;
color: var(--text-muted);
font-size: var(--font-ui-small);
line-height: 1.45;
white-space: normal;
overflow-wrap: anywhere;
-webkit-box-orient: vertical;
-webkit-line-clamp: 5;
}
.excalidraw-script-store__badge,
.excalidraw-script-store__tag {
display: inline-flex;
align-items: center;
gap: 0.2rem;
padding: 0.12rem 0.4rem;
border-radius: var(--radius-s);
background: var(--background-secondary-alt);
color: var(--text-muted);
font-size: var(--font-ui-smaller);
font-weight: var(--font-medium);
}
.excalidraw-script-store__badge svg {
width: 0.85em;
height: 0.85em;
}
.excalidraw-script-store__badge.has-update,
.excalidraw-script-store__badge.is-featured {
color: var(--interactive-accent);
}
.excalidraw-script-store__card-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
min-height: 3.2rem;
padding: 0.65rem 0.8rem;
border-top: 1px solid var(--background-modifier-border);
background: var(--background-secondary);
}
.excalidraw-script-store__card-footer>span {
min-width: 0;
color: var(--text-faint);
font-size: var(--font-ui-smaller);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.excalidraw-script-store__empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 15rem;
text-align: center;
color: var(--text-muted);
}
.excalidraw-script-store__empty h3 {
margin-bottom: 0;
}
.excalidraw-script-store__back {
align-self: flex-start;
display: inline-flex;
align-items: center;
gap: 0.4rem;
}
.excalidraw-script-store__back svg {
width: 1em;
height: 1em;
}
.excalidraw-script-store__detail {
width: min(800px, 100%);
margin: 0 auto;
}
.excalidraw-script-store__detail-hero {
display: flex;
align-items: flex-start;
gap: 1rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__detail-icon {
position: relative;
flex: 0 0 5rem;
width: 5rem;
height: 5rem;
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--radius-l);
background: var(--background-secondary);
color: var(--text-muted);
overflow: hidden;
}
.excalidraw-script-store__detail-icon img {
position: absolute;
width: 4.2rem;
height: 4.2rem;
object-fit: contain;
background: var(--background-secondary);
}
.excalidraw-script-store__detail-title {
min-width: 0;
flex: 1;
}
.excalidraw-script-store__detail-title h1 {
margin: 0;
}
.excalidraw-script-store__detail-byline {
margin-top: 0.25rem;
color: var(--text-muted);
}
.excalidraw-script-store__detail-tags,
.excalidraw-script-store__detail-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.4rem;
margin-top: 0.7rem;
}
.excalidraw-script-store__local-management {
margin-top: 1rem;
padding: 1rem;
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-m);
background: var(--background-secondary);
}
.excalidraw-script-store__local-management h2 {
margin: 0 0 0.8rem;
font-size: var(--font-ui-medium);
}
.excalidraw-script-store__local-copy+.excalidraw-script-store__local-copy {
margin-top: 1rem;
padding-top: 1rem;
border-top: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__local-copy-label {
width: fit-content;
margin-bottom: 0.5rem;
padding: 0.12rem 0.4rem;
border-radius: var(--radius-s);
background: var(--background-primary-alt);
color: var(--text-muted);
font-size: var(--font-ui-smaller);
font-weight: var(--font-medium);
}
.excalidraw-script-store__local-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
}
.excalidraw-script-store__local-info {
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.excalidraw-script-store__local-info code {
max-width: 100%;
overflow: hidden;
color: var(--text-muted);
font-size: var(--font-ui-smaller);
text-overflow: ellipsis;
white-space: nowrap;
}
.excalidraw-script-store__local-actions {
display: flex;
flex: 0 0 auto;
gap: 0.4rem;
}
.excalidraw-script-store__local-note {
margin-top: 0.75rem;
padding: 0.6rem 0.7rem;
border-radius: var(--radius-s);
background: var(--background-primary-alt);
color: var(--text-muted);
font-size: var(--font-ui-smaller);
line-height: 1.4;
}
.excalidraw-script-store__group-row {
display: flex;
align-items: center;
gap: 0.75rem;
margin-top: 0.9rem;
padding-top: 0.9rem;
border-top: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__group-row>label {
flex: 0 0 auto;
font-weight: var(--font-medium);
}
.excalidraw-script-store__group-controls {
display: flex;
flex: 1 1 auto;
align-items: center;
gap: 0.4rem;
min-width: 0;
}
.excalidraw-script-store__group-controls select {
min-width: 10rem;
max-width: 15rem;
}
.excalidraw-script-store__group-controls input {
min-width: 8rem;
flex: 1 1 auto;
}
.excalidraw-script-store__detail-description {
margin-top: 1rem;
line-height: 1.55;
}
.excalidraw-script-store__detail-description img {
max-width: 100%;
height: auto;
border-radius: var(--radius-m);
}
@media (max-width: 700px) {
.excalidraw-script-store__support-bar {
grid-template-columns: 1fr;
}
.excalidraw-script-store__support-item+.excalidraw-script-store__support-item {
border-left: 0;
border-top: 1px solid var(--background-modifier-border);
}
.excalidraw-script-store__updates-header,
.excalidraw-script-store__detail-hero,
.excalidraw-script-store__local-row,
.excalidraw-script-store__group-row {
align-items: stretch;
flex-direction: column;
}
.excalidraw-script-store__local-actions button {
flex: 1 1 auto;
}
.excalidraw-script-store__group-controls {
flex-wrap: wrap;
}
.excalidraw-script-store__group-controls select,
.excalidraw-script-store__group-controls input {
max-width: none;
flex: 1 1 12rem;
}
.excalidraw-script-store__controls>select,
.excalidraw-script-store__view-toggle {
flex: 1 1 auto;
}
.excalidraw-script-store__view-toggle button {
flex: 1;
}
}
@media (max-width: 500px) {
.excalidraw-script-store .modal {
width: 100vw;
height: 100vh;
max-height: 100vh;
}
.excalidraw-script-store__grid {
grid-template-columns: 1fr;
}
.excalidraw-script-store__controls {
align-items: stretch;
}
.excalidraw-script-store__controls>select,
.excalidraw-script-store__view-toggle {
width: 100%;
}
}
.excalidraw .excalidraw-tooltip-wrapper {
--no-tooltip: true;
}