Compare commits

...
Author SHA1 Message Date
zsviczian 1be3313516 Keep open-md drawings as images in note embeds 2026-11-29 13:00:15 +01:00
zsviczian a4c44071b0 Merge pull request #3074 from zsviczian/2026-11-26-visual-resource-browser
Visual Resources browser and Thinking Frameworks gallery
2026-11-29 12:34:44 +01:00
zsviczian c85391d1cc Consolidate Visual Resources discovery and lifecycle checks 2026-11-29 12:26:37 +01:00
zsviczian 6e5e4b5488 Render nested drawing frames in resource thumbnails 2026-11-28 10:39:12 +01:00
zsviczian 58fcd85d3e Persist resource thumbnails and add native hover previews 2026-11-28 10:11:37 +01:00
zsviczian 078f526625 Render faithful low-resolution drawing thumbnails 2026-11-28 08:55:04 +01:00
zsviczian b318e7653d Refine Visual Resources settings, previews, and insertion 2026-11-28 08:18:48 +01:00
zsviczian f88d78ea44 Bound visual previews and extend resource insertion workflows 2026-11-27 21:46:43 +01:00
zsviczian 35075a6a38 Keep renamed stencils visible and reuse resource previews 2026-11-27 17:23:58 +01:00
zsviczian 69c8a865cd Fix Visual Resources stencil previews, names, and text insertion 2026-11-27 07:20:34 +01:00
zsviczian d36cba1a81 Refine Visual Resources toolbar, selection, and frame resizing 2026-11-26 23:09:11 +01:00
zsviczian f68540485a Wait for the native drop receiver to migrate before opening it 2026-11-26 21:39:32 +01:00
zsviczian af80182170 Implement Visual Resources and Thinking Frameworks 2026-11-26 21:36:29 +01:00
zsviczian 7bfe43520f Plan visual resource browser and thinking templates 2026-11-26 06:37:21 +01:00
zsviczian 198b85d53a 2.29.4
Plugin tests / portable (push) Canceled after 0s
CodeQL / Analyze (javascript) (push) Canceled after 0s
2026-11-22 14:53:19 +01:00
zsviczian 02a8318f82 updated messages 2026-11-22 14:13:03 +01:00
zsviczian d7b344ec2c Merge pull request #3068: Add desktop Excalidraw sidepanel popout setting
Add desktop Excalidraw sidepanel popout setting
2026-11-22 11:40:59 +01:00
zsviczian e02edbaac2 Add desktop Excalidraw sidepanel popout setting 2026-11-22 11:40:14 +01:00
zsviczian 75c8f3b792 Merge pull request #3067: Use floating drawing image preview settings
fix: make drawing image preview settings a floating modal
2026-11-22 09:34:25 +01:00
zsviczian 5f199c99d1 fix: use floating modal for drawing image preview settings 2026-11-22 09:33:52 +01:00
zsviczian 5ffd26c484 Merge pull request #3065 from zsviczian/codex/cli-extras-readiness
Preflight CLI Mermaid dependencies and report optional service readiness
2026-11-22 07:57:36 +01:00
zsviczian 13edf710b0 Merge master into CLI readiness branch and retain both regression suites 2026-11-22 07:49:06 +01:00
zsviczian 9cd48595ae Merge pull request #3066 from zsviczian/2026-11-22-cli-issues-3-6-7
Add CLI selection handoffs, drawing embeds and EA stroke tools
2026-11-22 07:47:52 +01:00
zsviczian 3318f21699 Verify staged stroke persistence and wrapped label read-back 2026-11-22 07:26:48 +01:00
zsviczian 30ac87ceda Validate closed polygon geometry before CLI publication 2026-11-22 07:23:05 +01:00
zsviczian 68e6744e4b Keep native render evidence and use explicit light-theme pixel fixtures 2026-11-22 07:17:57 +01:00
zsviczian e33df8410a Extend CLI authoring and add EA stroke conversion and joining 2026-11-22 07:14:33 +01:00
zsviczian b633803349 Preflight CLI Mermaid dependencies and report optional service readiness 2026-11-22 06:28:16 +01:00
zsviczian 5315636096 2.29.3 2026-11-21 14:08:29 +01:00
zsviczian 899e61a026 0.18.150 2026-11-21 13:20:37 +01:00
zsviczian 63bda424ba edited messages.ts 2026-11-21 11:15:43 +01:00
zsviczian 03e0ecd15f Merge pull request #3064: Fix tools panel and canvas keyboard shortcuts
fix: align tools panel and preserve canvas keyboard shortcuts
2026-11-21 11:06:16 +01:00
zsviczian 6789310cbc test: pin portable fractional paste fixture correction 2026-11-21 10:57:49 +01:00
zsviczian ecf668a310 ci: pin the validated glyph comparison follow-up 2026-11-21 10:47:20 +01:00
zsviczian 13489d791f fix: preserve canvas Alt+Arrow navigation against core shortcuts 2026-11-21 10:26:23 +01:00
zsviczian c41468c706 fix: align floating tools panel and cover popout color shortcuts 2026-11-21 08:29:23 +01:00
zsviczian 4f0e2fb7d7 updated excalidraw package 2026-11-20 18:26:11 +01:00
zsviczian 8d50b07302 Merge pull request #3063: Reuse CJK font metadata and narrow private Chroma
perf: reuse CJK font metadata and narrow private Chroma
2026-11-20 13:55:15 +01:00
zsviczian f6d89717ad perf: reuse CJK metadata and narrow private color parsing 2026-11-20 13:46:41 +01:00
zsviczian 73b631abff Merge pull request #3060 from zsviczian/fix/native-context-menu-hit-test
test: use integer coordinates for native context-menu hit testing
2026-11-19 20:51:26 +01:00
137 changed files with 13460 additions and 2091 deletions

No files matched your search

+1 -1
View File
@@ -54,7 +54,7 @@ jobs:
- uses: actions/checkout@v4
with:
repository: zsviczian/excalidraw
ref: 8260fa444f84c616d1486c2a47365c1b72c4be9a
ref: 07b7e0cd0c53c50fa56db6830774cbab99414a56
path: .test-work/checkouts/fork
persist-credentials: false
- uses: actions/checkout@v4
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
- uses: actions/checkout@v4
with:
repository: zsviczian/excalidraw
ref: 8260fa444f84c616d1486c2a47365c1b72c4be9a
ref: 07b7e0cd0c53c50fa56db6830774cbab99414a56
path: .test-work/checkouts/fork
persist-credentials: false
- uses: actions/checkout@v4
+2 -1
View File
@@ -454,13 +454,14 @@ const containerEl = sceneElements.find(
## Validation requirements
- Before launching validation, classify the actual behavior change and state the smallest checks that address its risk. A task label such as "upstream merge", a touched editor file, or an available full-suite command is not sufficient justification for a full profile. State the concrete broad or unresolved risk before escalating. If an oversized run exposes an unrelated failure, preserve it without expanding a localized or mechanical task into its investigation; respect the maintainer's testing limit.
- Treat recoverable native failures as work to diagnose and resolve. Inspect the exact selected sources, locked dependencies, loaded companion versions, pending host requests, owning document/menu renderer and cleanup evidence; fix test infrastructure when it is wrong without weakening product assertions. Rebuild/deploy current workspace artifacts and rerun failed and blocked cases before returning. Preserve failed evidence. If progress actually requires human help (trust, permissions, foreground access or a safe restart), prompt the maintainer promptly instead of silently leaving the lane unfinished. Follow [native recovery](docs/OBSIDIAN_RUNTIME_TESTING.md#recovering-from-native-test-failures).
- Every behavior-changing feature, fix or refactor must add or extend executable tests for its intended behavior and the existing workflows it can affect. For a bug fix, preserve evidence that the regression fails before the fix and passes afterward. Assert observable outcomes; do not substitute registration, inventory, screenshots alone or an implementation-mirroring mock for behavioral evidence.
- Source tests under `scripts/testing/` and `tests/` named `*.test.mjs` are discovered by `test:fast`. Native helpers are not auto-discovered: wire new scenarios into the coordinator/profile and declared required-case/feature mappings. An unreferenced test file provides no executed coverage.
- During implementation, run the affected focused tests and required build after each independently testable checkpoint. Keep `tests/features.json` and `tests/inventory.json` current when coverage or discovery changes. Preserve existing assertions; report unexpected behavior instead of weakening tests or accepting new snapshots automatically.
- Settings/persistence changes need non-default configurations and unknown-key sentinels across actual plugin unload/reload and startup, with both on-disk data and loaded preferences asserted. Calling `loadSettings()` on an existing instance alone does not establish reload preservation. Include pending saves and externally changed data when those lifecycles are affected; preserve backup evidence if an unexpected replacement occurs.
- Select validation by risk and explain the selection. For a localized change, prefer the build, affected source tests and focused native scenarios for the workflows it can actually change. Do not automatically run complete portable or native regression merely because editor input, embeds or another native workflow is touched. Use complete profiles when the change has broad or uncertain impact (for example shared runtime, lifecycle, persistence, packaging or coordinated dependencies), or release acceptance requires them. Label focused and complete evidence accurately; a focused pass is not a complete native pass. Respect a maintainer's instruction to pause or limit testing and record what remains unverified.
- Run the complete portable and native profiles for coordinated release acceptance, after integrating upstream fork changes, and when validating a newly installed Obsidian version, including alphas. Record the actual host version; do not skip a case solely because the host is newer. Repeat complete matching-build runs when the acceptance plan requires them (including #3022); do not impose a new repeat count implicitly on unrelated changes.
- Run the complete portable and native profiles for coordinated release acceptance, upstream integrations with broad or unresolved behavioral impact, and validation of a newly installed Obsidian version, including alphas. An upstream merge that adopts executable code already present in the fork and only removes its fingerprint is mechanical: use the two-parent comparison, relevant inventory checks and required builds; do not start full portable/native profiles. Record the actual host version; do not skip a selected case solely because the host is newer. Repeat complete matching-build runs when the acceptance plan requires them (including #3022); do not impose a new repeat count implicitly on unrelated changes.
- Portable CI runs on pull requests and pushes to `master`. Native CI is an explicitly dispatched, exact-commit workflow on the isolated desktop runner; local native testing is invoked through the documented commands. Neither suite runs inside the shipped plugin during ordinary use. Review the pinned companion revisions in workflows for coordinated changes: a pinned CI combination does not automatically test another repository's latest branch.
- Documentation-only or demonstrably mechanical changes do not require invented behavioral tests. Run their relevant documentation/inventory checks and state why runtime validation is unnecessary. Record the commands, results, source/artifact identities and genuine limitations for every code handoff.
+46
View File
@@ -35,6 +35,7 @@ validated, and what remains uncertain.
| Phase | Status | Current outcome |
| --- | --- | --- |
| Assessment and baseline design | Complete | Initial architecture, risks, sequencing, and validation matrix documented |
| Visual Resources review (#3074) | Implemented | Shared discovery and bounded frame lookup, consolidated collection identity, and retirement guards for framework and collection operations. See the review checkpoint in the action log. |
| Automated test coverage (#3022) | Acceptance complete at the frozen checkpoint; PRs ready for review | Plugin fd32ac68 / fork 053a3b9 / Extras 1cdcb7c pass two complete 357/357 native repeats and 666 portable cases, with matching artifacts, cleanup, baseline restoration and strict negative controls. Historical failures remain public; the original observer-storm cause remains unidentified. See F32 and the immutable acceptance report. The later approved link-history fix has separate focused evidence in F33. |
| Parsed-link drawing history | Implemented; focused source/native regression passes | Preserve earlier shape actions when submitting parsed links. Four new source cases cover plain/wiki/aliased/Markdown links; eight trusted-input sequences undo all seven drawing actions to empty and redo identity, geometry, source, links and bindings. Verify the optional selection-only editor step explicitly; retain all 16 previous text-edit variants. No fork or Extras production change. |
| Timer ownership and coding standards | Implemented; focused/source checks pass; full-suite prerequisites remain | Main-window coordination timers settle conversion/restore/migration waits; teardown cancels conversion and restoration, and Markdown preview debounce survives migration. Cross-cutting rules now live in CODING_STANDARDS.md, linked from both entry guides. |
@@ -71,7 +72,13 @@ validated, and what remains uncertain.
| Extract view link navigation | Implemented; awaiting manual validation | `ViewLinkNavigationManager` now owns element-link resolution, hook dispatch, link prompting, modifier-aware navigation, and special image-link handling while all view methods remain compatibility delegates |
| Retire obsolete Draw.io integration | Implemented; awaiting manual validation | Removed special Diagram-plugin routing and retired the Create DrawIO file script from the maintained library and generated reference catalogs; user-installed vault scripts remain untouched |
| Extract Excalidraw extension rendering | Implemented; awaiting manual validation | `ViewExcalidrawExtensionRenderer` now owns text-to-diagram, diagram-to-code, welcome screen, custom main menu, and embeddable rendering while the view retains its existing render delegates and package-managed React runtime |
| Alt/Option+Arrow core shortcut conflict | Complete; genuine negative control and focused native acceptance pass | Core move-line bindings consumed vertical navigation. A focused owning-canvas wildcard passes navigation to Excalidraw while preserving Markdown line movement and scope cleanup. Component runtime unchanged. |
| Popout color palette keyboard (#3061) | Complete; focused native and full portable acceptance passed | Preserve nested picker focus in the owning document. Exact S/S native main/pass versus popout/fail reproduced before fork change; browser negative control matches. Native reproduction is scoped to main/popout desktop contexts, preserving prior cases elsewhere. |
| Align floating tools-panel header and body | Complete; focused desktop main/popout acceptance passed | Remove the inherited property-panel width cap and let the scrollable body fill its existing container. Native regression reproduces 208 px header versus 200 px body before the fix; both edges match after the fix and after trusted collapse/expand in main and popout. |
| Audit production bundle size | Complete | Ranked packaging, dependency, dead-data, and static-payload reductions; translation extraction remains a last resort |
| Compact runtime: share CJK subset metadata | Implemented; full Windows acceptance passed | Removed the 209-entry runtime copy in favor of the component's existing published `Fonts` registry. Ten whole-module cases preserve the former range/file/byte behavior, disabled/missing-font outcomes and structural URL ownership. Production checkpoint: 5,108,897 bytes versus 5,218,572 baseline. No new fork API, font ID, settings, startup order or vault-loading policy. |
| Compact runtime: narrow private Chroma entry | Implemented; full Windows acceptance passed | Keep all installed input parsers plus validation, alpha and hex operations. The actual build entry matches the full library across 1,670 named/CSS/generated color inputs. SVG and Lucide callers retain their existing API; no dependency replacement. |
| Compact runtime: exact WASM and shared locale keys | Implemented; full Windows acceptance passed | Production component packaging restores exact WASM bytes through existing Pako and preserves all 56 locale default/named namespaces using a shared path dictionary. Five packaging tests and 34 actual-artifact browser cases pass. Combined main.js: 4,841,250 bytes, saving 377,322 bytes. Development JS and both CSS files unchanged. |
| Shorten production module bindings | Implemented; Windows authoring/export/script checks passed | Enabled Terser's module-level identifier mangling while retaining `React` for bootstrap insertion. The production bundle falls from 5,061,540 to 4,948,931 bytes, saving 112,609 bytes (2.22%) and leaving 293,949 bytes below the 5 MiB target. Compressed runtime/bootstrap bytes, external URL/data-URL values, and external dependencies are unchanged; property mangling and top-level dead-code elimination remain disabled. Packaging tests verify private React/JSX, exact published font bytes, locale inflation, and the size target. Popout, cold application startup, physical mobile/offline smoke, and hosted CodeScanner review remain pending |
| Identify drawing-load failures (#2995) | Implemented; Windows concurrent-leaf and fresh-popout checks passed | Cache-wait and backup confirmations, plus the non-blocking no-backup notice, now name their captured file and offer read-only More information. Details show the full path and reported error as text and explain stray frontmatter, missing/malformed drawing data, possible sync damage, and device-local backups. Initial copy is concise; parsing, backup writes, existing OK/Cancel results, load-generation guards, and Markdown fallback remain unchanged. All five maintained locales are updated. Restored popouts after restart, live backup restoration, and physical mobile touch remain pending |
| Wrap reported drawing-load errors (#2995) | Complete; Windows main-window and popout layout checked | A scoped stylesheet rule applies `white-space: pre-wrap` and `overflow-wrap: break-word` to the reported error's pre/code block. Existing line breaks and complete error text are preserved, including long unbroken tokens. Normal and 320 px dialog widths passed without horizontal overflow in the main window and a fresh popout; physical mobile touch remains untested |
@@ -248,6 +255,9 @@ final upstream work is merged into the fork and installed in the plugin.
### Action log
- 2026-11-29 — Visual Resources review (#3074). Share discovery input between the settings tester and the gallery, and reuse bounded scene inspection for curated frames. A render pass reuses dependency stamps across cards from the same drawing. Keep collection identity and orphan removal in one place, and cancel queued collection writes or framework continuations when their plugin instance retires. Interactive creation retains the template and explicit-data contracts.
- Validate rule matching, collection replay and retirement, and interrupted catalog installation with focused source tests. Use the isolated Windows vault to check choosing and dismissing a framework, unloading with its dialog open, reconnecting cached frames and linked assets, staging SVG actions, and popout drops. Physical mobile browsing and independent-device collection edits still require their own coverage.
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-10-23 | Repaired PR #472 published-package host type drift | The four-artifact merge test retained installed 0.18.143 declarations and missed the later 0.18.144 UI-type change. Derive the plugin package-host adapter, protocol/registration and public loadMermaid declarations from published fork types. Add a real consumer contract test as npm prebuild, preserving the maintainer's existing dependency edits. No fork/Extras runtime, settings, public service or scene changes | Contract test fails before and passes after; all 621 installed declarations/runtime files match the lockfile-verified 0.18.144 tarball. Production/library builds have no Mermaid type error; development retains five baseline TS7006 diagnostics. Fourteen fork Mermaid/host tests and 15 bundle/harness checks pass. Windows real-Extras declined-service retry, offline conversion, editable source, main/popout preview, shared parser and byte-preserving save/reopen pass with final clean errors/fixtures. Initial directory cleanup probes failed; final file-only probe passes. main.js 4,985,148 bytes, 257,732 bytes headroom. Highest risks to check separately: enabling/declining Extras and retry, cold startup/restored popouts, macOS/Linux and physical mobile. No whole-product zero-regression certification or new publication |
@@ -3521,3 +3531,39 @@ remain strict pending maintainer classification; no production changes.
the coordinated PR handoff. Highest-risk manual follow-up: physical OS IME
composition/Undo, physical mobile text entry, and macOS popout save/reopen;
desktop emulation does not establish those platforms.
- Runtime compaction, 2026-11-20: created `perf/compact-plugin-runtime` and
`perf/compact-obsidian-artifact` from clean plugin `73b631ab` and fork
`0a93447eb`. The CJK checkpoint consumes the existing published registry and
retains vault reads, five-file concurrency and document registration ownership.
Archived the former 209 descriptors/range selections as test-only fixtures;
ten whole-module cases and the production build pass (109,675 bytes saved).
Risk-based acceptance: local CJK files must load through the same settings in
main/popout documents, survive reload and remain usable offline; physical
mobile font registration remains separate coverage. Private Chroma parser
parity passes 1,670 inputs without changing the SVG/Lucide call surface; final
integrated source/browser/native acceptance remains pending.
- Runtime compaction packaging checkpoint, 2026-11-20: exact WASM saves 209,060 bytes; shared locale keys save 40,024 while preserving named exports. Browser subset export/FontFace decoding passes in both artifacts. Native CJK pixel equivalence and real WASM subset output pass main/popout; initial lazy registration and diagnostic-array reporting test failures are retained, corrected without product changes. Combined bundle is 4,841,250 bytes. Final coordinated acceptance pending. Highest-risk follow-up is first-use offline CJK/text export after reload across main/popout and physical mobile; desktop emulation is separate evidence.
- Final runtime-compaction acceptance, 2026-11-20: full coordinated regression passes all 1,637 canonical cases (1,161 portable, 316 native core, 160 emulated-device cases). Production/development/library and component full/owned types, coverage, package consumers, exact build/deployment hashes, required identities, strict errors and cleanup pass. Four new native main/popout cases verify exact CJK pixels and valid smaller font subsets (1,136 versus 56,156 bytes); warm exports match. Main.js SHA-256 `61fc40f3ccbcc9f824f749b05f5547fadf03e0c02d0e8f193e1b87308144fd80`, 4,841,250 bytes, 377,322 saved. Baseline settings/fixtures restored and original automation-window bounds restored under lock. Source and artifact identities: sibling fork `dev-docs/Obsidian/runtime-compaction-results.json`; full report `.test-work/reports/regression-11104c08-9de2-4380-9781-1373c13eda4e/report.json`. Only acceptance documentation changes after the frozen run. Highest-risk manual checks remain local CJK offline after reload across main/popout, language switching and SVG/PDF text export; physical Android/iOS and other native desktop systems need their own smoke tests. No commit or publication; exact existing dependency/lockfile retained.
- Maintainer runtime-compaction acceptance, 2026-11-20: confirmed working on Obsidian mobile (device/OS unspecified) and authorized commit, push, PR creation and merge in plugin and component. This complements the 1,637-case automated run; it is separate from automated physical-device coverage. Version upgrades/publication remain with the maintainer. Implementation hashes and dependency/lockfile remain unchanged.
- Tools-panel styling, 2026-11-20: scope the existing five-button floating panel body to its parent width (`width: 100%; max-width: none`) instead of Excalidraw property-panel shrink-to-fit/cap. The original native run fails with 208 px versus 200 px; the corrected main/popout toolbar cases pass with matching edges before/after trusted collapse/expand, plus existing authoring/context-menu/undo/save behavior. CSS lint, feature-map source tests, inventory, fresh matching component/plugin builds and diff checks pass. Cleanup and settings/layout restoration pass. Original failure: `.test-work/reports/native-e51fd8ab-2552-4252-962a-43f4f9987daa/`; acceptance: `.test-work/reports/native-c090fb3c-364b-4670-9c8f-8511b2caea4d/`; compact record `.test-work/tools-panel-width/acceptance.json`. Final CSS newline cleanup produces identical three runtime artifact hashes. Maintainer Messages.ts edits were preserved byte-for-byte. Highest-risk manual follow-up is panel placement and five-button wrapping at nondefault UI scales on phone/tablet; physical mobile and other desktop OSes are separate coverage. This is focused desktop validation, not a full regression run.
- Issue #3061, 2026-11-21: before any component edit, fresh main desktop S/S recolors selected text while the same popout case fails with focus on the outer Radix dialog. Cleanup/restoration pass (native-007f0984-867d-43df-a1c5-1b3a0b246457). Actual production browser negative control matches. Fork PropertiesPopover now preserves its owning-document focused descendant before Radix default autofocus; no listeners/timers/API changes. All 36 actual-artifact browser cases pass, including palette keys, Tab, Escape, Undo/Redo and surviving main-editor isolation. Original setup/history-readiness failures retained. Post-fix native and full portable acceptance pending. Tools-panel CSS fix remains bundled; maintainer release edits preserved.
- Final #3061 bundled acceptance, 2026-11-21: full portable regression passes 1,163 canonical cases (36 component browser cases); focused native main/popout now pass the exact S/S selected-text recolor, tools-panel width/collapse and existing toolbar/Undo/save workflows. Full/owned types, coverage, package consumers, 291-path inventory, 15 checker tests, strict error/source gates and cleanup pass. The original negative controls are retained. Native and portable runtime artifacts match exactly; main.js SHA-256 `95daa68f427d14606ae1aa098da28b4d4df2e31bdda5808e7fc212d008e1c8a2`. Baseline restored; original automation-window geometry restored with no pending tasks/popouts/debugger. Exact source and artifact identities: sibling fork `dev-docs/Obsidian/color-shortcuts-3061-results.json`. Runtime code is unchanged after frozen acceptance; only documentation updated. Existing two JSX/comment warnings reproduce on the fork parent. Maintainer Messages.ts edit preserved byte-for-byte. Highest-risk manual follow-up: physical-mobile touch/keyboard appearance, other desktop OSes and popup focus at nondefault UI scales; no complete native profile or upstream PR is claimed. No versions/dependencies changed.
- Maintainer confirmation, 2026-11-21: #3061 fixed; authorized commit/push of the bundled panel/color fixes and a succinct upstream ownership follow-up. User-owned Messages.ts edit remains outside the implementation commit. Package/dependency versions remain separate.
- Alt/Option+Arrow investigation, 2026-11-21: rebuilt the current fork and plugin, copied all four consumer artifacts and deployed only the repository-owned native vault. All 38 browser cases (48 navigation checks), 826 fast cases and focused main/popout toolbar cases (24 navigation checks in full/tray/compact with mouse selection and held Alt) pass. Runtime main.js remains 4,841,292 bytes with SHA-256 95daa68f427d14606ae1aa098da28b4d4df2e31bdda5808e7fc212d008e1c8a2. Initial invalid bindings, pointer readiness and host-layout test setup failures are preserved and corrected without weakening assertions. No product change or user failure reproduction is claimed. Next required input: the failing drawing and selected node/context; highest-probability follow-up is the exact local workflow with its hotkey configuration, plus physical macOS Option input when applicable. Messages.ts, versions, dependencies and the upstream PR remain unchanged. Exact record: sibling fork dev-docs/Obsidian/alt-arrow-navigation-results.json.
- Confirmed Alt/Option+Arrow fix, 2026-11-21: read-only drawing/build inspection identified core move-line bindings. Reproduced failure in both owned windows before the edit (native-050eef18-83bc-4dd9-9ee2-e971568262a2). A focused owning-canvas/one-live-selection wildcard now passes navigation through with popScope cleanup. Fixed native-cd234c13-c71c-45e6-bf25-e91402d1869d passes 24 direction/layout checks, real Markdown line moves, repeated registration and drawing→Markdown→drawing lifetime, plus previous color/panel/history/save assertions. Strict error/source gates, cleanup and baseline restoration pass. All 829 fast cases, five bundle contracts and focused lint pass; four rebuilt fork artifacts match the 38-case browser report. No fork runtime/API/dependency change or additional upstream PR. Main.js: 4,842,001 bytes (+709), SHA-256 f4f212b501b055c23b4a09389b8150f2ab8f1583171caa5e3af663f9c41918f2. Messages.ts preserved. No personal-vault deployment, commit or push. Manual follow-up: install/reload the build and verify the supplied drawing with physical Alt/Option keys, then normal Markdown line movement. Full release acceptance is not claimed.
- Maintainer merge authorization, 2026-11-21: commit the confirmed panel/color/Alt+Arrow work and merge paired plugin/fork PRs. Keep the user Messages.ts edit outside the commits, and leave component versioning/npm publication to the maintainer. Advance hosted/native test source pins to the merged fork; package dependency remains unchanged. Fork CI audit uses the existing reviewed 2c3dcc06e baseline.
- Hosted CI follow-up, 2026-11-21: plugin PR #3064 passed source/type/coverage stages, then an unchanged text-placement browser oracle reported a single fringe pixel (204 to 192) as movement. Both darker glyph masks were identical. Fork PR #494 adds the exact synthetic fixture and a strict glyph-core comparator with seven controls that reject one-pixel displacement in every direction, loss of one core pixel, blank/mismatched images. All 259 owned/coverage cases, 38 browser cases, owned types, focused lint and the 295-path audit pass locally. Component runtime and package version are unchanged. Both CI pins now select merged fork cf11a3ca55aaed413f219c90fbcc1de934d766c8; the full Linux portable job will rerun before plugin merge. The earlier failed CI evidence remains in run 44889615453 and the fork's glyph-pixel-ci.md.
- Linux paste-fixture follow-up, 2026-11-21: run 44891234165 passed the corrected glyph comparison, then measured a legitimate integer natural paste width of 195px. Fork PR #495 removes the system-font assumption by exercising the fractional container limit with an oversized glyph and requiring exactly 200.46px. All 38 browser cases, focused lint/format and the 295-path inventory pass locally. Both CI pins select merged fork 07b7e0cd0c53c50fa56db6830774cbab99414a56. Production code, versions, dependencies and earlier native keyboard evidence are unchanged; the hosted portable rerun remains required before plugin merge.
@@ -11,6 +11,7 @@ Put large requests in a visible vault-relative JSON file and pass input="<file>"
Requests in files include apiVersion:1; the native command supplies command. The in-process ea.executeCLI request also includes command.
Use exact drawing paths including extensions. Never assume an active drawing. :open explicitly creates a tab and can run configured drawing scripts.
Loop: :read source=live detail=elements (or detail=images to inventory) → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
For selected targets use :selection with an explicit path/view, or the drawing command Copy selected elements for agent. Retain packet IDs (including bound-label IDs), read those IDs at the packet revision, and apply only authorized targets. A stale packet needs inspection and a fresh revision, never guessed replacement IDs.
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY with the same requestId only when refused before execution; unknown outcomes require read-back.
New skeleton IDs are local labels; use returned idMap actual IDs for updates. Updates reject identity, bindings and asset internals.
Every write requires requestId. Repeat the identical effective request to retrieve its receipt; different content with the same ID fails.
@@ -18,6 +19,8 @@ Every write requires requestId. Repeat the identical effective request to retrie
:api surface=ea name=<method> gives existing EA signatures. :api surface=lib lists the supported installed Lib reference; advanced exports remain available to scripts.
:icons query=<name> discovers installed canonical Lucide names (paged); create icons / apply op=lucide insert editable native groups. groupMap maps logical icon aliases to groupId/elementIds; idMap remains single-element only. Defaults: size=96, strokeColor=#1e1e1e, roughness=1, opacity=100; optional strokeWidth is final scene units. No trusted script is required.
:script requires trusted=true and an explicit existing local script file. utils.input contains args; utils.excalidrawLib is the installed runtime. Await all work; completion does not imply saved drawing.
:status ready describes plugin startup. Inspect extras.components for optional service versions, active/compatible flags and requirements; extras may be null during startup. mindMapBuilder reports the resident script API's available/ready flags without starting it or selecting a view.
One-shot ea.addMermaid preflights Extras and rejects unavailable dependencies with DEPENDENCY_UNAVAILABLE instead of opening an activation modal. Inspect any earlier script writes before retrying.
One-shot EA is cleaned up; utility prompts fail INTERACTION_REQUIRED. Trusted code can still invoke other interactive APIs: this is not a sandbox, timeout cancellation or transaction.
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Disk exports require local Vault assets; use a loaded live source or placeholders for remote assets.
For cheap previews: :read detail=images, then :export imagePolicy={"default":"placeholder","rules":[{"ids":["wanted-id"],"mode":"original"}]}. This is lossless for the underlying drawing, not the preview.
+66 -2
View File
@@ -73,6 +73,38 @@ types are rectangle, ellipse, diamond, text, arrow, line, frame, and stickynote.
Arrow `start`/`end` bindings and frame `children` reference IDs in their batch.
Frames require children and cannot nest. Use `connect` for existing endpoints.
Line skeletons and line `update.set` accept boolean `polygon`. True requires
an explicitly closed contour: at least four points with the last equal to the
first. The CLI does not reshape the path. False retains ordinary line semantics;
a closed path can still fill from its background color. Use a transparent
background to remove fill. Other element types reject this field.
Line/arrow skeletons allow 2–1000 points, with at most 100000
points per batch. Use a request file for dense contours. Ordinary lines do not
accept `strokeLinecap`; custom free-draw styling belongs in an explicit EA script.
Text skeleton `x` is the left/center/right anchor according to `textAlign`;
an existing text element's `update.set.x` is its stored scene coordinate.
## Selected targets for agents
Select canvas objects and run **Excalidraw: Copy selected elements for agent**,
then paste the JSON packet with the requested edit. The read-only native
equivalent is `:selection path="Drawings/Flow.excalidraw.md" view="<view-id>"`.
It requires an open drawing and an explicit view when duplicate views exist;
it does not write the clipboard or drawing.
The packet includes `packetVersion`, `vault`, `path`, `view`, `revision`, and up
to 500 `elements` including bound labels. Entries contain `id`, `type`, `selected`,
`text`, `frameId`, `containerId`, `labelId`, and scene `bounds` as
`[minX,minY,maxX,maxY]`. Related labels have `selected: false` unless selected
directly. This identifies targets after selection changes; it creates no hidden
marks. Frame selection does not implicitly authorize edits to every descendant.
Read the exact IDs at the packet's live `revision` before editing, then use
`expectedRevision` and actual label IDs for text changes. A stale packet requires
fresh inspection of those IDs and their relationships. Never guess replacement
targets from text or position. A migrated/closed view requires explicit resolution
of the same drawing's current view ID.
## Native Lucide icons
Check `status` for `lucideIcons`, then use `icons query=database limit=50` to
@@ -137,18 +169,26 @@ not every later human edit. A handoff is not reported as durable.
| `group` | `ids`; returns a new group ID |
| `ungroup` | `ids`, `groupId`; preserves other groups |
| `imageMetadata` | `id`, `label` (1–80 characters or `null` to clear), `tags` (up to 12 unique short strings or `null`) |
| `image` | `asset`: exact vault PNG/JPEG/GIF/WebP/SVG; optional `id`, `x`, `y`, `scale` (boolean) |
| `image` | `asset`: exact vault PNG/JPEG/GIF/WebP/SVG or recognized Excalidraw drawing; optional `id`, `x`, `y`, `scale`, `anchor` (booleans) |
| `latex` | `text`; optional `id`, `x`, `y`, `scaleX`, `scaleY`; requires compatible enabled Extras MathJax |
| `lucide` | `id`, `icon`; optional `x`, `y`, `size`, `strokeColor`, `strokeWidth`, `roughness`, `opacity`; returns `groupMap` |
`update` accepts x/y/width/height/angle, strokeColor/backgroundColor/fillStyle,
strokeWidth/strokeStyle/roughness/opacity, locked/link, and text/fontSize/fontFamily/
textAlign/verticalAlign. Text fields require a text element; edit the bound label
textAlign/verticalAlign, and line-only boolean polygon. Text fields require a text element; edit the bound label
ID to change its text. Linear resizing and identity, version, binding, frame,
binary, or Markdown-image metadata edits require a trusted script. Unknown
requested fields are rejected; existing custom data is preserved. Delete uses
tombstones and binding cleanup and does not delete attachment files.
Drawing images use the existing EA loader and retain a source link; ordinary
Markdown notes and direct self-embeds are refused. `scale=true` fits the image to
the normal insertion size. With `scale=false`, `anchor=true` (default) retains
the source-size `100%` option; `anchor=false` allows later manual scaling to
survive refresh. Verify the source link, saved/reopened host, and rendered content.
The existing nested-drawing depth limit remains; source edits may need a host
reload to refresh their rendition. Arbitrary `customData` remains script-only.
## Read, render, and recover
`list` returns exact paths. `read` defaults to a summary without asset bodies;
@@ -246,3 +286,27 @@ results fail without claiming rollback. A terminal timeout cannot preempt
arbitrary synchronous code or undo side effects. PDF, Mermaid, SVG import, and
advanced Markdown-image workflows remain available through existing EA/Extras
APIs with their normal dependency and interaction requirements.
### Stroke conversion and concatenation
Discover `convertLineToFreedraw`, `convertFreedrawToLine`, and `concatenateLines`
with `api surface=ea name=...`. These operate only on copied workbench elements;
publish with `await ea.addElementsToView(false, false)` to mark the view dirty,
then `await ea.targetView.save(false)` and verify saved disk content.
They retain IDs, frame/groups and unrelated metadata, and reject unsupported
labels, bindings and arrowheads before mutation. They return JSON-safe results
with point counts and warnings.
Conversion samples rounded line curves in world coordinates instead of retagging
control points. `tolerance` defaults to 0.5 scene units, `maxPoints` to 10000;
`strokeWidth` overrides the nominal-width estimate. Line-to-free-draw accepts
the fork's full `penOptions`. **excalidraw.com ignores custom free-draw options**,
so appearance can differ. Reverse conversion simplifies the centerline to a
polyline and loses pressure, taper, custom caps and outlines. Compare an export.
Concatenation joins 2–100 compatible open lines by nearest endpoints, handles
reversal, rotation and sharp corners, and samples rounded sections. `maxGap`
defaults to 1 scene unit. The first ID survives; other input IDs are staged as
deleted. Styles, frame, groups and metadata must match; disconnected/branching
sets and exceeded budgets are refused without partial deletion. Keep actual
branches separate, then inspect and save the published result.
+19 -3
View File
@@ -243,6 +243,17 @@ not physical Android/iOS, native OS drag or stylus evidence.
## Earlier focused scenario details
Run `npm run verify:obsidian -- --sidepanel-popout` for the desktop sidepanel
setting. It checks the default right sidebar, popout document ownership,
singleton/tab-input reuse, deferred popout on the next reveal of a live or restored
sidebar tab, docking as a sibling tab without expanding the sidebar through both
settings controls, preservation of later manual moves, Markdown
image insertion retaining popout/editor focus, extraction-section padding, and
non-default settings plus unknown-key preservation across plugin unload and
startup. It restores its settings and closes its owned panels/windows. Mobile's
desktop-preference guard has source coverage; physical mobile and other desktop
operating systems remain separate manual checks.
The following scenario notes retain their feature-specific assertions. Their
native execution now uses the preparation and local vault contract above.
@@ -435,8 +446,8 @@ postprocessor with deferred image generation, including failed renders, temporar
detachment, overlapping attribute updates, repeated callbacks, loader cancellation,
and permanent context unload. They require no Obsidian process or extra DOM package.
The native scenario creates four UUID-named Markdown files (including a hybrid
drawing), one tiny PNG, and adds text to the parent runner's disposable drawing.
The native scenario creates UUID-named Markdown fixtures and one tiny PNG, and
adds text to the parent runner's disposable drawing.
A long embedded note uses a collapsed callout
so three repeated drawing embeds stay in the viewport. It temporarily defers the
test plugin's `awaitInit()`, detaches the owned note's content for longer than the
@@ -444,11 +455,16 @@ loader's cancellation interval, and verifies rendering and decoding after
reattachment. SVG image, PNG, and inline SVG are checked in Live Preview, Reading
mode, warm reopen, and width updates; an additional popout checks detachment and
width updates in its own document. Closing a context with a pending render must
stop insertion. The hybrid fixture uses `excalidraw-open-md: true`, a relative
stop insertion. The hybrid fixture uses `excalidraw-open-md: true` and
`excalidraw-embed-md: true`, a relative
`![[#^as-image]]`, a nested drawing, and a native PNG. Live Preview and Reading mode
must show all three, both directly and inside another note's Markdown transclusion;
a filename-qualified `#^as-image` must still force the drawing side. These checks
run in the popout and require a Markdown drawing for the parent smoke fixture.
In the main window, a drawing with just `excalidraw-open-md: true` opens in the
Markdown editor and embeds as a drawing in both note modes. Native Page Preview
checks both states of the hover setting and the Markdown override from
`excalidraw-embed-md`.
The scenario restores the temporary method override and preview
setting, closes its own leaves, deletes only its recorded fixture paths, and
removes its controller in `finally`. The parent runner still checks deployed
+4
View File
@@ -432,3 +432,7 @@ requires an error-free baseline and the behavioral gate includes all recorded
window errors. Complete core/mobile acceptance and two complete repeats remain
required. Portable CI passed 645 cases at e3f421b3; its artifact upload separately
failed with ECONNRESET after upload, not during build or tests.
### Runtime compaction
`npm run verify:obsidian -- --runtime-compaction` builds the selected local component and plugin, then verifies real local CJK font pixels and first/warm WASM font export in main/popout documents. It restores settings, owned files and layout under the shared host lock. The four cases are also mandatory in the full regression profile. Physical mobile and other native operating systems remain separate coverage.
+34
View File
@@ -0,0 +1,34 @@
# Visual Resources
Open **Visual Resources** from the Excalidraw command palette or use the shapes button beside **Insert Any File**. The filter menu includes vault icons, Lucide icons, images, drawings, stencils, and Thinking Frameworks. **Other visuals** is off by default. It includes unmatched drawings and images based on all configured discovery rules, with excluded folders respected.
## Find and use resources
| What you want to do | Where to start | What the interface makes clear |
| --- | --- | --- |
| Find a vault icon by its group | Enable **Vault icons**, then choose a group. | The filter popover stays open while you make changes. **Select all** and **Select none** affect resource types and preserve group choices. |
| Use a named frame | Enable **Drawings**, then use **Browse named frames** on a drawing card. | An accent outline identifies the drawing shown in the frame pane. Search can find a drawing by one of its frame names. The pane shows all named frames for the selected drawing and closes when the drawing leaves the results. **Has named frames** uses metadata saved with Excalidraw 2.29.4 or newer. |
| Insert an SVG into a drawing | Choose **Insert linked SVG** or **Insert as editable strokes**. | Stroke insertion asks whether to record a source link. Pick a document property or use `excalidraw-svg-sources`. With K-Plex enabled, choose a relationship direction and one of its configured fields. **SVG stroke options** lets you set defaults while browsing. |
| Add a visual to a note or Canvas | Open **Visual Resources** from an editable Markdown note or Canvas, then select an image, drawing, or frame. | The panel names the destination. Markdown accepts a click or a drop from the gallery, and a drop places the embed at the pointer. Canvas adds a file node with the frame reference. |
| Work with several results at once | Choose **Select multiple resources**, check items, then choose **Actions for selected resources**. | Add favorites, organize playlists, move eligible stencils, or insert the selection into the current drawing in a single undo step. |
| Switch collections or adjust the gallery | Open **Collections** using the library icon. The selection and layout controls sit beside it. | Collections contains **Favorites**, playlists, and manually added vault files. Settings and moving the panel sit at the end of the toolbar. |
Drag the divider to resize the gallery and frame selector, or focus it and use the Up and Down arrow keys. On desktop, double-click a vault resource to open its source, or drag it to an Excalidraw drawing to insert it at the drop position. Hold Ctrl (Cmd on macOS) and hover over a vault image or drawing to open Obsidian’s Page Preview. The Page Preview settings control whether the modifier is required.
Drawings reuse fresh exports and suitable cached previews. Otherwise, the browser renders a small PNG of the saved drawing or its chosen thumbnail frame. Named frame cards also render as small PNGs. The renderer downsizes local PNG, JPEG and WebP assets and renders linked vault drawings or their named frames within the same work budget. It uses placeholders for assets outside that budget. The Excalidraw ribbon icon marks drawings that exceed the scene budget.
With image caching enabled, Excalidraw keeps the generated drawing and frame PNGs in a device-local IndexedDB cache with a 100 MiB budget. It evicts the least recently used entries when full, follows the local image cache retention setting, and refreshes previews when their sources change. Use **Purge Cache** under image caching settings to clear it.
Open **Visual Resources settings** to edit one discovery rule at a time, page through rules, and test them against vault filenames. Frame search rules add search keywords without hiding frames from the selected drawing. The options below the tester control excluded folders, size, and light and dark thumbnail backgrounds.
The two journeys that still benefit from visible context are frame browsing and inserting into another editor. A frame is part of its parent drawing, so the frame list stays below that drawing’s search results. The destination label matters when switching between Markdown and Canvas because the same click creates different types of links. The library icon represents the collection menu as a whole. A bookmark would suggest Favorites only, and a list icon is already used for the layout control.
For new blank drawings, choose a framework, continue with a blank drawing, or defer the prompt for seven days. The **Create drawing with a Thinking Framework** command reopens the picker at any time. The first download is explicit, and the plugin's version-update preference also controls catalog checks.
## Vault data
Favorites, manual selections and playlist memberships live in `resource-collections.json` in the Excalidraw folder. Local edits replay against the latest vault contents. Obsidian Sync or another sync provider still determines how simultaneous offline edits to that file are reconciled. Confirmed deletions leave unresolved registry entries, while currently unavailable resources are omitted from the gallery until they resolve.
To rename a stencil, click its name and press Enter to save or Escape to cancel. You can also choose **Rename** from its action menu. The name is saved in the stencil’s owning library. The renamed stencil stays in place, even if its new name no longer matches the current search. Changing the search, filters, or collection applies the current name and sort order.
Stencil moves preserve the original item ID and check the destination before removing the source copy. If the second write fails, both copies may remain. Empty stencil libraries stay available until explicitly deleted.
+10 -10
View File
@@ -5,7 +5,7 @@ Generate HTML, Mermaid, mind maps, editable SVG strokes and images from a canvas
Uses **Excalidraw AI** provider profiles and model preferences, including OpenAI reasoning effort. Configure keys in the plugin (obfuscated vault settings or device-local Obsidian SecretStorage); this script never stores API keys. Your chosen task sends its prompt and, when enabled, selected canvas image to that provider.
Requires Excalidraw 2.29.2 or newer. Open a drawing and run **ExcaliAI**. Preserve that script filename when replacing an older copy so its task library and preferences remain under the same Script Engine settings key.
Requires Excalidraw 2.29.3 or newer. Open a drawing and run **ExcaliAI**. Preserve that script filename when replacing an older copy so its task library and preferences remain under the same Script Engine settings key.
The migration preserves legacy settings and task IDs. Existing JavaScript modal/export orchestration remains in run.js, with import-safe task helpers and typed request helpers. New script UI strings and default prompts are in lang/en.ts; maintained locale files use English fallback for untranslated advanced content.
@@ -17,7 +17,7 @@ Tutorial: https://www.youtube.com/watch?v=A1vrSGBbWgo
Maintained source: https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/excali-ai
Build version: 2026-11-17T17:24:59.281Z
Build version: 2026-11-21T13:00:37.416Z
```javascript
*/
@@ -527,7 +527,7 @@ Build version: 2026-11-17T17:24:59.281Z
scriptFailed: "ExcaliAI could not start. Check that your drawing is open and the selected images are available.",
requestFailed: "ExcaliAI could not complete this task. Check your model settings and try again.",
errorTitle: "Error",
thisScriptRequiresExcalidrawOrLaterPlease: "This script requires Excalidraw 2.23.0 or later. Please update the plugin.",
thisScriptRequiresExcalidrawOrLaterPlease: "This script requires Excalidraw 2.29.3 or later. Please update the plugin.",
textResponse: "Text response",
usesTheTextOrMultimodalModelAnd: "Uses the text or multimodal model and returns structured output such as HTML, Mermaid, a mind map, or Excalidraw strokes.",
writePromptThenGenerateImage: "Write prompt, then generate image",
@@ -720,13 +720,13 @@ Build version: 2026-11-17T17:24:59.281Z
advancedPromptWarning: "Advanced: change this only if you know why.",
reasoningHelp: "Reasoning effort: {effort} (from Excalidraw AI settings).",
reasoningDefault: "API default",
requiresVersion: "This script requires Excalidraw 2.29.2 or later. Please update the plugin."
requiresVersion: "This script requires Excalidraw 2.29.3 or later. Please update the plugin."
};
// src/scripts/excali-ai/lang/de.ts
var de = {
noView: "\xD6ffne zuerst eine Excalidraw-Zeichnung.",
requiresVersion: "Dieses Skript erfordert Excalidraw 2.29.2 oder neuer. Bitte aktualisiere das Plugin.",
requiresVersion: "Dieses Skript erfordert Excalidraw 2.29.3 oder neuer. Bitte aktualisiere das Plugin.",
prompt: "Prompt",
advancedSettings: "{value1} <span>Erweiterte Einstellungen</span>",
systemPrompt: "System-Prompt",
@@ -740,7 +740,7 @@ Build version: 2026-11-17T17:24:59.281Z
// src/scripts/excali-ai/lang/es.ts
var es = {
noView: "Abre primero un dibujo de Excalidraw.",
requiresVersion: "Este script requiere Excalidraw 2.29.2 o posterior. Actualiza el complemento.",
requiresVersion: "Este script requiere Excalidraw 2.29.3 o posterior. Actualiza el complemento.",
prompt: "Instrucciones",
advancedSettings: "{value1} <span>Ajustes avanzados</span>",
systemPrompt: "Instrucciones del sistema",
@@ -754,7 +754,7 @@ Build version: 2026-11-17T17:24:59.281Z
// src/scripts/excali-ai/lang/fr.ts
var fr = {
noView: "Ouvrez d\u2019abord un dessin Excalidraw.",
requiresVersion: "Ce script n\xE9cessite Excalidraw 2.29.2 ou une version ult\xE9rieure. Mettez le plugin \xE0 jour.",
requiresVersion: "Ce script n\xE9cessite Excalidraw 2.29.3 ou une version ult\xE9rieure. Mettez le plugin \xE0 jour.",
prompt: "Instruction",
advancedSettings: "{value1} <span>Param\xE8tres avanc\xE9s</span>",
systemPrompt: "Instruction syst\xE8me",
@@ -768,7 +768,7 @@ Build version: 2026-11-17T17:24:59.281Z
// src/scripts/excali-ai/lang/ru.ts
var ru = {
noView: "\u0421\u043D\u0430\u0447\u0430\u043B\u0430 \u043E\u0442\u043A\u0440\u043E\u0439\u0442\u0435 \u0440\u0438\u0441\u0443\u043D\u043E\u043A Excalidraw.",
requiresVersion: "\u0414\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0441\u043A\u0440\u0438\u043F\u0442\u0430 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F Excalidraw 2.29.2 \u0438\u043B\u0438 \u043D\u043E\u0432\u0435\u0435. \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u0435 \u043F\u043B\u0430\u0433\u0438\u043D.",
requiresVersion: "\u0414\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0441\u043A\u0440\u0438\u043F\u0442\u0430 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F Excalidraw 2.29.3 \u0438\u043B\u0438 \u043D\u043E\u0432\u0435\u0435. \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u0435 \u043F\u043B\u0430\u0433\u0438\u043D.",
prompt: "\u0417\u0430\u043F\u0440\u043E\u0441",
advancedSettings: "{value1} <span>\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438</span>",
systemPrompt: "\u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u0437\u0430\u043F\u0440\u043E\u0441",
@@ -782,7 +782,7 @@ Build version: 2026-11-17T17:24:59.281Z
// src/scripts/excali-ai/lang/zh-cn.ts
var zhCn = {
noView: "\u8BF7\u5148\u6253\u5F00 Excalidraw \u7ED8\u56FE\u3002",
requiresVersion: "\u6B64\u811A\u672C\u9700\u8981 Excalidraw 2.29.2 \u6216\u66F4\u65B0\u7248\u672C\u3002\u8BF7\u66F4\u65B0\u63D2\u4EF6\u3002",
requiresVersion: "\u6B64\u811A\u672C\u9700\u8981 Excalidraw 2.29.3 \u6216\u66F4\u65B0\u7248\u672C\u3002\u8BF7\u66F4\u65B0\u63D2\u4EF6\u3002",
prompt: "\u63D0\u793A\u8BCD",
advancedSettings: "{value1} <span>\u9AD8\u7EA7\u8BBE\u7F6E</span>",
systemPrompt: "\u7CFB\u7EDF\u63D0\u793A\u8BCD",
@@ -888,7 +888,7 @@ Build version: 2026-11-17T17:24:59.281Z
loadExcaliAISettings
} = createTaskHelpers(t);
let dirty = false;
if (!ea2.verifyMinimumPluginVersion || !ea2.verifyMinimumPluginVersion("2.29.2")) {
if (!ea2.verifyMinimumPluginVersion || !ea2.verifyMinimumPluginVersion("2.29.3")) {
new Notice(t("requiresVersion"));
return;
}
+1 -1
View File
@@ -537,7 +537,7 @@
},
{
"fname": "ExcaliAI.md",
"mtime": 1794869591004
"mtime": 1795266037499
},
{
"fname": "ExcaliAI.svg",
+1 -1
View File
@@ -467,7 +467,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/ExcaliAI.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/ExcaliAI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Generate HTML, diagrams, editable SVG strokes and images using your configured AI providers, including OpenAI reasoning effort. Maintained in <a href="https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/excali-ai">ea-scripts</a>.<br><a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:400px;"></a><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/ExcaliAI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Generate HTML, diagrams, editable SVG strokes and images using your configured AI providers, including OpenAI reasoning effort. Requires Excalidraw 2.29.3 or newer. Maintained in <a href="https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/excali-ai">ea-scripts</a>.<br><a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:400px;"></a><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
## Excalidraw Writing Machine
```excalidraw-script-install
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.29.2",
"version": "2.29.4",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.29.2",
"version": "2.29.4",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+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.148",
"@zsviczian/excalidraw": "0.18.150",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -5039,9 +5039,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.148",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.148.tgz",
"integrity": "sha512-T1AOXqAQuUt1/rHwchzEIdgjPgd/scUg+wHlfoTcAZ9kbr/gxiLYKMjPE+5D0mj+RXLig4gMzhNIJKib911NQQ==",
"version": "0.18.150",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.150.tgz",
"integrity": "sha512-iHBp4hAVmHJTXpHFabMl9ruOQchMWQQ6cDX34EHHGcOczewg+7yeK/g3HnsDImzids7bPwEYmENQofqgZ/5GFw==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
+1 -1
View File
@@ -69,7 +69,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.148",
"@zsviczian/excalidraw": "0.18.150",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
+2
View File
@@ -14,6 +14,7 @@ import json from '@rollup/plugin-json';
import { parseEnv } from 'node:util';
import { buildReactRuntime } from './scripts/buildReactRuntime.mjs';
import { localExcalidrawTypePaths } from './scripts/excalidrawTypeSource.mjs';
import { chromaParserOnly } from './scripts/chromaParser.mjs';
import ts from 'typescript';
function compressDeflateBase64(code) {
@@ -320,6 +321,7 @@ function pairedTypeOptions(config) {
}
const getRollupPlugins = (tsconfig, ...plugins) => [
chromaParserOnly(),
typescript(pairedTypeOptions(tsconfig)),
json(),
replace({
+76
View File
@@ -0,0 +1,76 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import ts from "typescript";
/**
* Builds the private color-parser entry used by SVG import and Lucide preparation.
* Keep every input registration from the installed full Chroma entry, including
* CSS/named/wide-gamut formats. Palette generators, interpolation and unrelated
* color operations are not part of either caller or a public plugin API.
* Follow Chroma's own custom-entry design instead of replacing its parser or
* introducing another library. A changed upstream layout must fail the build.
*/
export function createChromaParserEntry(source) {
const tree = ts.createSourceFile(
"chroma-entry.js",
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.JS,
);
const imports = new Set();
const inputs = [];
for (const statement of tree.statements) {
if (
ts.isImportDeclaration(statement) &&
ts.isStringLiteral(statement.moduleSpecifier)
) {
imports.add(statement.moduleSpecifier.text);
}
if (
ts.isExportDeclaration(statement) &&
!statement.exportClause &&
statement.moduleSpecifier &&
ts.isStringLiteral(statement.moduleSpecifier) &&
statement.moduleSpecifier.text.startsWith("./src/io/")
) {
inputs.push(statement.moduleSpecifier.text);
}
}
const required = [
"./src/chroma.js",
"./src/io/named/index.js",
"./src/ops/alpha.js",
"./src/utils/valid.js",
];
if (required.some((path) => !imports.has(path)) || !inputs.length) {
throw new Error(
"Unrecognized Chroma entry: review the parser-only build before upgrading.",
);
}
return [
'import chroma from "./src/chroma.js";',
'import "./src/io/named/index.js";',
'import "./src/ops/alpha.js";',
...inputs.map((path) => `import ${JSON.stringify(path)};`),
'import valid from "./src/utils/valid.js";',
"chroma.valid = valid;",
"export default chroma;",
].join("\n");
}
/** Apply the same private parser in production, development and library builds. */
export function chromaParserOnly() {
const entry = fileURLToPath(import.meta.resolve("chroma-js")).replaceAll(
"\\",
"/",
);
return {
name: "excalidraw-private-chroma-parser",
load(id) {
if (id.replaceAll("\\", "/") !== entry) return null;
this.addWatchFile(id);
return createChromaParserEntry(readFileSync(id, "utf8"));
},
};
}
+5
View File
@@ -245,6 +245,11 @@ export const workflowCases = [
id: "toolbar-context-shortcuts",
features: ["P07"],
assertions: [
"desktop Alt/Option+Arrow changes flowchart selection in full, tray and compact modes",
"desktop canvas navigation overrides conflicting core hotkeys while Markdown line movement and scope cleanup remain intact",
"desktop color-picker shortcuts recolor selected text in its owning window",
"floating tools panel header and body edges align",
"tools panel collapses and expands through trusted input",
"trusted toolbar and context menu",
"keyboard shortcut and cancellation",
"scene state and on-disk save",
+80
View File
@@ -0,0 +1,80 @@
/** Exercise the real build entry against the full library's accepted color behavior. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import vm from "node:vm";
import { test } from "node:test";
import { rollup } from "rollup";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import full from "chroma-js";
import { chromaParserOnly, createChromaParserEntry } from "../chromaParser.mjs";
const entry = fileURLToPath(import.meta.resolve("chroma-js"));
const bundle = await rollup({
input: entry,
plugins: [chromaParserOnly(), nodeResolve()],
});
let slim;
try {
const { output } = await bundle.generate({ format: "cjs" });
const module = { exports: {} };
vm.runInNewContext(output[0].code, { module, exports: module.exports });
slim = module.exports;
} finally {
await bundle.close();
}
test("the private entry preserves every installed color input, hex and alpha result", () => {
const cases = [
...Object.keys(full.colors),
"transparent",
"currentColor",
"invalid",
"rgb(10, 20, 30)",
"rgba(20, 30, 40, 0.4)",
"hsl(240, 50%, 30%)",
"lab(50% 20 -10)",
"lch(50% 20 100)",
"oklab(50% 0.1 -0.1)",
"oklch(50% 0.1 100)",
"color(display-p3 1 0 0)",
"#fff",
"#fff0",
"fff",
"1",
"red\n",
];
let seed = 173;
for (let i = 0; i < 1500; i++) {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
cases.push("#" + seed.toString(16).padStart(8, "0"));
}
for (const value of cases) {
assert.equal(slim.valid(value), full.valid(value), value + " validity");
if (!full.valid(value)) continue;
assert.equal(slim(value).hex(), full(value).hex(), value + " hex");
for (const alpha of [0, 0.17, 0.5, 1]) {
assert.equal(
slim(value).alpha(alpha).hex("rgba"),
full(value).alpha(alpha).hex("rgba"),
value + " alpha",
);
}
}
assert.equal(slim.scale, undefined);
assert.equal(slim.brewer, undefined);
});
test("unexpected dependency entry layouts fail instead of silently dropping parsers", () => {
assert.throws(
() => createChromaParserEntry("export default {};"),
/Unrecognized Chroma entry/,
);
const source = readFileSync(entry, "utf8");
assert.throws(
() =>
createChromaParserEntry(
source.replace("./src/io/named/index.js", "./moved.js"),
),
/Unrecognized Chroma entry/,
);
});
+156
View File
@@ -0,0 +1,156 @@
/** Preserve the former subset selection and physical file bytes using the shared registry. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import NativePromisePool from "es6-promise-pool";
import { sourceHarness } from "./sourceHarness.mjs";
const faces = JSON.parse(
readFileSync(
new URL("../../tests/fixtures/cjk-font-faces.json", import.meta.url),
),
);
const selections = JSON.parse(
readFileSync(
new URL("../../tests/fixtures/cjk-range-selections.json", import.meta.url),
),
);
class PromisePool {
constructor(source, concurrency) {
this.pool = new NativePromisePool(source, concurrency);
}
all() {
return this.pool.start();
}
}
const harness = sourceHarness({
"./utils": {
PromisePool,
promiseTry: (callback) => Promise.resolve().then(callback),
},
"./fileUtils": {
blobToBase64: async (blob) =>
Buffer.from(await blob.arrayBuffer()).toString("base64"),
},
});
const { getCJKFontFaceData, matchesCJKRange } = await harness.importModule(
"src/utils/CJKLoader.ts",
);
test.after(() => harness.close());
function registry(subsets = faces) {
return {
registered: new Map([
[1, { fontFaces: [{ fontFace: { family: "Virgil" }, urls: [] }] }],
[
100,
{
fontFaces: subsets.map(({ uri, descriptors }) => ({
urls: [
new URL(
"https://fixture.invalid/fonts/" + encodeURIComponent(uri),
),
],
fontFace: {
family: "Xiaolai",
unicodeRange: descriptors.unicodeRange,
},
})),
},
],
]),
};
}
for (const { ranges, indices } of selections) {
test(`shared CJK registry preserves former selection and bytes for ${JSON.stringify(ranges)}`, async () => {
const reads = [],
settings = { ...ranges };
const plugin = {
getCJKFontSettings: () => settings,
loadFontFromFile: async (name) => {
reads.push(name);
return new TextEncoder().encode(name).buffer;
},
};
const result = await getCJKFontFaceData(plugin, registry());
const expected = indices.map((i) => faces[i]);
assert.deepEqual(
reads,
expected.map((face) => face.uri),
);
if (!expected.length) {
assert.equal(result, false);
return;
}
assert.equal(result.length, expected.length);
for (let i = 0; i < result.length; i++) {
assert.equal(
Buffer.from(result[i].dataURL.split(",")[1], "base64").toString(),
expected[i].uri,
);
assert.deepEqual(result[i].descriptors, expected[i].descriptors);
}
});
}
test("disabled CJK loading leaves the component registry uninitialized", async () => {
const fonts = {
get registered() {
throw Error("Unexpected registry access");
},
};
assert.equal(
await getCJKFontFaceData(
{ getCJKFontSettings: () => ({ c: false, j: false, k: false }) },
fonts,
),
undefined,
);
});
test("missing registry and missing local files retain the failure signal", async () => {
const plugin = {
getCJKFontSettings: () => ({ c: true, j: true, k: true }),
loadFontFromFile: async () => undefined,
};
assert.equal(
await getCJKFontFaceData(plugin, { registered: new Map() }),
false,
);
assert.equal(await getCJKFontFaceData(plugin, registry()), false);
});
test("range filtering accepts FontFace-normalized uppercase ranges and structural URLs", async () => {
assert.equal(
matchesCJKRange(
{ uri: "test", descriptors: { unicodeRange: "U+4E00-9FFF" } },
{ c: true, j: false, k: false },
),
true,
);
const bytes = new Uint8Array([0, 1, 255]);
const plugin = {
getCJKFontSettings: () => ({ c: true, j: false, k: false }),
loadFontFromFile: async (name) => {
assert.equal(name, "local subset.woff2");
return bytes.buffer;
},
};
const fonts = {
registered: new Map([
[
100,
{
fontFaces: [
{
urls: [{ pathname: "/assets/local%20subset.woff2" }],
fontFace: { family: "Xiaolai", unicodeRange: "U+4E00-9FFF" },
},
],
},
],
]),
};
const result = await getCJKFontFaceData(plugin, fonts);
assert.deepEqual(
[...Buffer.from(result[0].dataURL.split(",")[1], "base64")],
[...bytes],
);
});
+154 -3
View File
@@ -7,6 +7,7 @@ import { transpileModule, ModuleKind, createSourceFile, ScriptTarget, SyntaxKind
function harness({ supported = true, desktop = true, native = true } = {}) {
const cache = new Map(), registrations = new Map(), versionChecks = []; let nextId = 0;
const window = {};
class View {}
class File { constructor(path) { this.path = path; this.extension = path.split('.').at(-1); this.stat = { size: 1 }; } }
const files = [new File('a.excalidraw.md'), new File('Drawings/b.excalidraw.md')];
@@ -15,6 +16,7 @@ function harness({ supported = true, desktop = true, native = true } = {}) {
app: { vault: { getName: () => 'Test', getFileByPath: path => files.find(file => file.path === path), getFiles: () => files,
read: async file => file.content ?? '{}' }, workspace: { getLeavesOfType: () => [] } },
isExcalidrawFile: file => file.path.endsWith('.excalidraw.md'), getCLIRuntime: () => ({ convertToExcalidrawElements() {} }),
extrasGateway: { getStatus: () => ({ installed: false, enabled: false, pluginVersion: null, components: {} }) },
...(native ? { registerCliHandler: (name, desc, flags, fn) => { assert.ok(desc); assert.ok(flags); registrations.set(name, fn); } } : {}),
};
const mocks = {
@@ -32,20 +34,147 @@ function harness({ supported = true, desktop = true, native = true } = {}) {
if (cache.has(file)) return cache.get(file).exports;
const module = { exports: {} }; cache.set(file, module);
const compiled = transpileModule(readFileSync(file, 'utf8'), { compilerOptions: { module: ModuleKind.CommonJS, target: 9 } }).outputText;
new Function('require', 'exports', 'module', compiled)(specifier => load(specifier, resolve(file, '..')), module.exports, module);
new Function('require', 'exports', 'module', 'window', compiled)(specifier => load(specifier, resolve(file, '..')), module.exports, module, window);
return module.exports;
}
const protocol = load('src/core/cli/cliProtocol');
const { ExcalidrawCLI } = load('src/core/managers/ExcalidrawCLI');
return { manager: new ExcalidrawCLI(plugin), protocol, icons: load('src/core/cli/cliIcons'), elements: load('src/core/cli/cliElements'), apply: load('src/core/cli/cliApply'), exporting: load('src/core/cli/cliExport'), images: load('src/core/cli/cliImages'), dimensions: load('src/core/cli/cliImageDimensions'), dependencies: load('src/core/cli/cliDependencies'), customData: load('src/utils/elementCustomDataUtils'), plugin, registrations, versionChecks, files, View, mocks };
return { manager: new ExcalidrawCLI(plugin), protocol, scriptContext: load('src/core/cli/cliScriptContext'), window, icons: load('src/core/cli/cliIcons'), elements: load('src/core/cli/cliElements'), apply: load('src/core/cli/cliApply'), exporting: load('src/core/cli/cliExport'), images: load('src/core/cli/cliImages'), dimensions: load('src/core/cli/cliImageDimensions'), dependencies: load('src/core/cli/cliDependencies'), customData: load('src/utils/elementCustomDataUtils'), plugin, registrations, versionChecks, files, View, mocks };
}
const request = (command, values = {}) => ({ apiVersion: 1, command, ...values });
test('status reports optional services without activating Extras or starting Builder', async () => {
const h = harness();
assert.deepEqual((await h.manager.execute(request('status'))).data.mindMapBuilder, { available: false, ready: false });
h.window.MindMapBuilderAPI = { ready: () => true, setView: () => assert.fail('status retargeted Builder') };
const extras = { components: { mermaid: { version: '3.0.0', compatible: false, active: true } } };
h.plugin.extrasGateway.getStatus = () => extras;
const result = await h.manager.execute(request('status'));
assert.equal(result.ok, true); assert.equal(result.data.ready, true);
assert.deepEqual(result.data.extras, extras);
assert.deepEqual(result.data.mindMapBuilder, { available: true, ready: true });
assert.equal(result.mutation, 'not-applied');
h.window.MindMapBuilderAPI.ready = () => { throw Error('retired script'); };
assert.deepEqual((await h.manager.execute(request('status'))).data.mindMapBuilder, { available: true, ready: false });
h.plugin.isReady = false; delete h.plugin.extrasGateway;
const startup = await h.manager.execute(request('status'));
assert.equal(startup.ok, true); assert.equal(startup.data.ready, false); assert.equal(startup.data.extras, null);
});
test('CLI Mermaid dependency refusal preserves prior script uncertainty and clears invocation context', async () => {
const h = harness(), ea = { destroy() {} };
const file = h.files[0]; file.content = 'await ea.addMermaid(utils.input);';
h.plugin.ea = { getAPI: () => ea };
h.plugin.scriptEngine = { executeScriptFileForCLI: async (file, view, actualEA, input, lib, source, check) => {
check(); assert.equal(h.scriptContext.isCLIScript(actualEA), true);
throw new h.protocol.CLIError('DEPENDENCY_UNAVAILABLE', 'Mermaid 3.6.0 required', undefined, 'Update Extras');
} };
const result = await h.manager.execute(request('script', { script: file.path, trusted: true, requestId: 'missing-mermaid' }));
assert.equal(result.error.code, 'DEPENDENCY_UNAVAILABLE');
assert.equal(result.error.recovery, 'Update Extras');
assert.equal(result.mutation, 'unknown'); assert.equal(result.persistence, 'unknown');
assert.equal(h.scriptContext.isCLIScript(ea), false);
});
test('CLI script JSON return failures remain recoverable without repeating already executed work', async () => {
const h = harness(), file = h.files[0]; file.content = 'return an API result;';
h.plugin.ea = { getAPI: () => ({ destroy() {} }) };
let executions = 0;
h.plugin.scriptEngine = { executeScriptFileForCLI: async (f, v, ea, args, lib, source, check) => {
check(); executions++; return executions === 1 ? { arrowId: undefined, nodeId: 'saved' } : JSON.parse(JSON.stringify({ arrowId: undefined, nodeId: 'saved' }));
} };
const input = request('script', { script: file.path, trusted: true, requestId: 'undefined-result' });
const result = await h.manager.execute(input);
assert.equal(result.error.code, 'OUTCOME_UNKNOWN'); assert.equal(result.persistence, 'unknown');
assert.deepEqual(await h.manager.execute(input), result); assert.equal(executions, 1);
const safe = await h.manager.execute({ ...input, requestId: 'safe-result' });
assert.equal(safe.ok, true); assert.deepEqual(safe.data, { nodeId: 'saved' });
});
function authoringView(h, initial = []) {
let elements = structuredClone(initial), selected = {};
const model = { textElements: new Map(), markdownImages: new Map(), equations: new Map(), mermaids: new Map(),
getFileEntries: () => [], exportPreparedSaveData: () => ({ files: [] }) };
const view = Object.assign(new h.View(), { id: 'owned-view', file: h.files[0], plugin: h.plugin, excalidrawData: model,
isLoaded: true, isClosingOrMigrating: () => false, isSameFileEditingActive: () => false, isPersistenceBusy: () => false,
getScene: () => ({ elements, appState: {}, files: {} }), isDirty: () => false,
excalidrawAPI: { getSceneElements: () => elements, getSceneElementsIncludingDeleted: () => elements, getFiles: () => ({}), getAppState: () => ({ selectedElementIds: selected }) },
addElements: async options => { options.validateBeforePublish(); elements = structuredClone(options.newElements); return true; },
saveWithOutcome: async () => ({ requestedRevision: 1, acknowledgedRevision: 1, currentRevision: 1, status: 'persisted' }),
});
h.plugin.app.workspace.getLeavesOfType = () => [{ view }];
const lib = { getCommonBounds: ([e]) => [e.x, e.y, e.x + e.width, e.y + e.height],
mutateElement: (element, map, set) => { Object.assign(element, set); element.version++; },
convertToExcalidrawElements: skeletons => skeletons.map(e => ({ ...e, groupIds: [], version: 1 })) };
h.plugin.getCLIRuntime = () => lib;
const ea = { elementsDict: {}, imagesDict: {}, setView() {}, getElements() { return Object.values(this.elementsDict); },
copyViewElementsToEAforEditing(values) { for (const e of structuredClone(values)) this.elementsDict[e.id] = e; } };
return { view, ea, lib, select: value => { selected = value; } };
}
test('polygon skeletons and updates support dense bounded line contours without accepting foreign fields', async () => {
const h = harness(), points = Array.from({ length: 250 }, (_, i) => [i, i % 5]);
points[249] = [...points[0]];
assert.doesNotThrow(() => h.elements.validateBatch([{ type: 'line', points, polygon: true }]));
assert.throws(() => h.elements.validateBatch([{ type: 'arrow', polygon: true }]));
assert.throws(() => h.elements.validateBatch([{ type: 'line', polygon: 'yes' }]));
assert.throws(() => h.elements.validateBatch([{ type: 'line', points: Array(1001).fill([0, 0]) }]));
assert.throws(() => h.elements.validateBatch([{ type: 'line', strokeLinecap: 'round' }]));
assert.throws(() => h.elements.validateBatch([{ type: 'line', points: points.slice(0, -1), polygon: true }]), error => error.field === 'polygon');
assert.throws(() => h.elements.validateBatch([{ type: 'line', points: [[0, 0], [1, 1], [0, 0]], polygon: true }]));
assert.equal(h.apply.validateOperations([{ op: 'update', id: 'line', set: { polygon: false } }]).length, 1);
const a = authoringView(h, [{ id: 'line', type: 'line', points: [[0, 0], [50, 0], [50, 50]], x: 0, y: 0, width: 50, height: 50 }]);
const run = () => h.apply.applyDrawing(h.manager, { path: a.view.file.path, expectedRevision: h.manager.targets.revision(a.view), operations: [{ op: 'update', id: 'line', set: { polygon: true } }] }, a.ea);
await assert.rejects(run(), error => error.field === 'polygon');
});
test('selection packets capture exact targets and bound labels independently of later selection', async () => {
const h = harness(), a = authoringView(h, [
{ id: 'shape', type: 'rectangle', x: 10, y: 20, width: 100, height: 60, frameId: 'frame', boundElements: [{ id: 'label', type: 'text' }] },
{ id: 'label', type: 'text', text: 'Target', containerId: 'shape', x: 20, y: 30, width: 80, height: 20 },
{ id: 'other', type: 'rectangle', x: 300, y: 0, width: 40, height: 40 },
]);
a.select({ shape: true });
const result = await h.manager.execute(request('selection', { path: a.view.file.path, view: a.view.id }));
assert.equal(result.ok, true, JSON.stringify(result));
const packet = result.data;
assert.equal(packet.vault, 'Test'); assert.equal(packet.view, a.view.id);
assert.deepEqual(packet.elements.map(e => e.id), ['shape', 'label']);
assert.equal(packet.elements[0].labelId, 'label'); assert.equal(packet.elements[0].text, 'Target');
assert.deepEqual(packet.elements[0].bounds, [10, 20, 110, 80]);
assert.equal(packet.elements[1].selected, false);
a.select({});
const read = await h.manager.execute(request('read', { path: packet.path, view: packet.view, source: 'live', ids: packet.elements.map(e => e.id), revision: packet.revision, detail: 'elements' }));
assert.equal(read.ok, true); assert.equal(read.data.total, 2);
assert.equal((await h.manager.execute(request('selection', { path: packet.path }))).error.code, 'INVALID_INPUT');
});
test('drawing image insertion keeps links and anchor options while refusing ordinary Markdown and source races', async () => {
for (const mode of ['drawing', 'markdown', 'self', 'changed']) {
const h = harness(), a = authoringView(h);
const asset = new h.files[0].constructor(mode === 'markdown' ? 'Notes/Plain.md' : mode === 'self' ? a.view.file.path : 'Maps/Source.excalidraw.md');
if (mode !== 'self') h.files.push(asset);
let published = false, called = false;
a.view.addElements = async options => { options.validateBeforePublish(); published = true; return true; };
a.ea.addImage = async (x, y, file, scale, anchor) => {
called = true; assert.equal(file, asset); assert.equal(scale, false); assert.equal(anchor, false);
if (mode === 'changed') asset.stat.size++;
a.ea.elementsDict.image = { id: 'image', type: 'image', version: 1, groupIds: [] }; return 'image';
};
const revision = h.manager.targets.revision(a.view);
const run = () => h.apply.applyDrawing(h.manager, { path: a.view.file.path, expectedRevision: revision,
operations: [{ op: 'image', id: 'embed', asset: asset.path, scale: false, anchor: false }] }, a.ea);
if (mode === 'drawing') { const result = await run(); assert.equal(result.persistence, 'saved'); assert.equal(result.data.idMap.embed, 'image'); }
else { await assert.rejects(run(), error => error.code === (mode === 'changed' ? 'STALE_REVISION' : 'INVALID_INPUT')); assert.equal(published, false); }
assert.equal(called, mode === 'drawing' || mode === 'changed');
}
});
test('registration validates minimum API, optional method and desktop without bumping the baseline', () => {
for (const options of [{ supported: false }, { native: false }, { desktop: false }]) {
const h = harness(options); h.manager.initialize(); assert.equal(h.registrations.size, 0);
}
const h = harness(); h.manager.initialize(); assert.equal(h.registrations.size, 15);
const h = harness(); h.manager.initialize(); assert.equal(h.registrations.size, 16);
assert.deepEqual(h.versionChecks, ['1.12.2']);
});
@@ -192,6 +321,28 @@ function productionMethod(path, className, name, dependencies = {}) {
return exports.Loaded.prototype[name];
}
test('addMermaid rejects unavailable CLI dependencies before the interactive converter while manual calls retain it', async () => {
const h = harness(); let conversions = 0;
const convert = productionMethod('src/shared/ExcalidrawAutomate.ts', 'ExcalidrawAutomate', 'addMermaid', {
isCLIScript: h.scriptContext.isCLIScript, CLIError: h.protocol.CLIError,
mermaidToExcalidraw: async () => { conversions++; return { elements: [] }; },
});
const api = { features: { isActive: () => true } };
const gateway = { getAPI: () => api, checkVersion: () => ({ valid: true }) };
const ea = { plugin: { extrasGateway: gateway }, style: { fontSize: 20, roundness: null } };
for (const state of ['missing', 'incompatible', 'disabled']) {
gateway.getAPI = () => state === 'missing' ? null : api;
gateway.checkVersion = () => ({ valid: state !== 'incompatible' });
api.features.isActive = () => state !== 'disabled';
await assert.rejects(h.scriptContext.withCLIScriptContext(ea, () => convert.call(ea, 'graph TD; A-->B')), error => error.code === 'DEPENDENCY_UNAVAILABLE');
assert.equal(conversions, 0); assert.equal(h.scriptContext.isCLIScript(ea), false);
}
await convert.call(ea, 'graph TD; A-->B'); assert.equal(conversions, 1);
gateway.getAPI = () => api; gateway.checkVersion = () => ({ valid: true }); api.features.isActive = () => true;
await h.scriptContext.withCLIScriptContext(ea, () => convert.call(ea, 'graph TD; A-->B'));
assert.equal(conversions, 2);
});
test('delayed text preparation leaves concurrent metadata and the scene intact when publication is rejected', async () => {
let resume;
const waiting = new Promise(resolve => { resume = resolve; });
+1 -1
View File
@@ -24,7 +24,7 @@ test("creation actions default to visible, respect independent opt-outs and rele
let leaves = [leaf], ribbonCount = 0, active, resolveCreation;
const plugin = { settings: null, isReady: true,
app: { workspace: { on: (_, callback) => { events.add(callback); return callback; }, onLayoutReady(callback) { this.ready = callback; }, getLeavesOfType: () => leaves, setActiveLeaf: leaf => { active = leaf; } } },
addRibbonIcon() { ribbonCount++; return ribbon; }, createAndOpenDrawing: (...args) => { created.push(args); return new Promise(resolve => { resolveCreation = resolve; }); } };
addRibbonIcon() { ribbonCount++; return ribbon; }, createAndOpenInteractiveDrawing: (...args) => { created.push(args); return new Promise(resolve => { resolveCreation = resolve; }); } };
const ribbon = new dom.Element();
const previousVersion = globalThis.PLUGIN_VERSION;
try {
+13 -1
View File
@@ -4,9 +4,11 @@ import LZString from "lz-string";
import { sourceHarness } from "./sourceHarness.mjs";
const constants = { JSON_parse: value => JSON.parse(value.replaceAll("&#91;", "[")), MD_MARKDOWN_IMAGES: "Markdown Images" };
const decompress = value => LZString.decompressFromBase64(value.replace(/\s/g, ""));
const graph = sourceHarness({
"src/constants/constants": constants, "../constants/constants": constants,
"../utils/sceneDataUtils": { compress() {}, compressAsync() {}, updateFrontmatterInString() {}, decompress: value => LZString.decompressFromBase64(value.replace(/\s/g, "")) },
"../utils/sceneDataUtils": { compress() {}, compressAsync() {}, updateFrontmatterInString() {}, decompress },
"./sceneDataUtils": { decompressAsync: async value => decompress(value) },
"../utils/obsidianUtils": { isObsidianThemeDark: false },
});
const { getDrawingPaddingMax } = await graph.importModule("src/utils/drawingPadding.ts");
@@ -42,3 +44,13 @@ test("padding geometry reads plain, compressed and legacy saved scenes without r
assert.equal(reads,3);
await assert.rejects(readDrawingPreviewElements({cachedRead:async()=>'{"elements":null}'},{extension:"excalidraw"}));
});
test("bounded drawing reads count decoded scene characters against the preview budget", async () => {
const json = JSON.stringify({ elements: [rect("area", 0, 0, 100, 100)] });
const source = `\n## Drawing\n\x60\x60\x60compressed-json\n${LZString.compressToBase64(json)}\n\x60\x60\x60\n`;
const vault = { cachedRead: async () => source };
const file = { extension: "md" };
assert.equal((await readDrawingPreviewElements(vault, file, json.length))[0].id, "area");
await assert.rejects(readDrawingPreviewElements(vault, file, json.length - 1), /geometry exceeds the preview budget/);
});
+18
View File
@@ -29,3 +29,21 @@ for (const [version, accepted] of [["2.2.2", false], ["3.0.0", false], ["3.1.0",
}
});
}
test('Extras status exposes component versions and compatibility without loading or enabling services', () => {
const api = { versions: { mermaid: '3.0.0', mathjax: '1.1.0', pdf: '1.0.0', filesystem: '1.0.0' },
features: { isActive: () => true, enable: () => assert.fail('status enabled a service') },
mermaid: { getModule: () => assert.fail('status loaded Mermaid') } };
const app = { plugins: { manifests: { 'excalidraw-extras': { version: '0.1.2' } }, plugins: { 'excalidraw-extras': { api } } } };
const gateway = new exports.ExcalidrawExtrasGateway(app, {});
let result = gateway.getStatus();
assert.equal(result.enabled, true); assert.equal(result.pluginVersion, '0.1.2');
assert.equal(result.components.mermaid.version, '3.0.0');
assert.equal(result.components.mermaid.requiredVersion, '3.6.0');
assert.equal(result.components.mermaid.exact, true); assert.equal(result.components.mermaid.compatible, false);
assert.equal(result.components.mathjax.compatible, true);
api.versions.mermaid = '3.6.0'; result = gateway.getStatus();
assert.equal(result.components.mermaid.compatible, true);
delete app.plugins.plugins['excalidraw-extras']; result = gateway.getStatus();
assert.equal(result.enabled, false); assert.equal(result.components.mermaid.version, null); assert.equal(result.components.mermaid.active, false);
});
@@ -0,0 +1,47 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
test("closing a floating modal before deferred setup cancels its listeners and positioning", async () => {
const previousWindow = globalThis.window, previousDocument = globalThis.mainDocument;
const pending = new Map(); let nextId = 0, setups = 0;
const win = {
innerWidth: 1000, innerHeight: 800,
setTimeout(callback) { const id = ++nextId; pending.set(id, callback); return id; },
clearTimeout(id) { pending.delete(id); },
};
const doc = Object.assign(new EventTarget(), { defaultView: win, body: {}, activeElement: null });
const element = () => Object.assign(new EventTarget(), {
ownerDocument: doc, style: {},
addClass() { setups++; }, setAttr() {}, querySelector() { return null; },
getBoundingClientRect() { return { width: 200, height: 100 }; },
});
class Modal {
constructor(app) { this.app = app; this.modalEl = element(); this.containerEl = element(); this.bgEl = element(); }
setDimBackground() {} open() {} close() {}
}
globalThis.window = win; globalThis.mainDocument = doc;
const graph = sourceHarness({
obsidian: { Modal },
"src/utils/styleUtils": { setStyle: (el, styles) => Object.assign(el.style, styles) },
"src/utils/coreUtils": { errorlog(error) { throw error; } },
"src/utils/typechecks": {
isInstanceOfHTMLButtonElement: () => false, isInstanceOfHTMLInputElement: () => false,
isInstanceOfHTMLSelectElement: () => false, isInstanceOfHTMLTextAreaElement: () => false,
},
});
try {
const { FloatingModal } = await graph.importModule("src/shared/Dialogs/FloatingModal.ts");
const modal = new FloatingModal({ keymap: { popScope() {} } });
modal.open(); assert.equal(pending.size, 1);
modal.close(); assert.equal(pending.size, 0);
for (const callback of pending.values()) callback();
assert.equal(setups, 0);
modal.close();
assert.equal(pending.size, 0);
} finally {
graph.close();
if (previousWindow === undefined) delete globalThis.window; else globalThis.window = previousWindow;
if (previousDocument === undefined) delete globalThis.mainDocument; else globalThis.mainDocument = previousDocument;
}
});
@@ -0,0 +1,71 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
function fixture() {
const canvas = {}, container = {querySelector: () => canvas}, doc = {activeElement: container};
const state = {selectedElementIds: {a: true}};
const elements = [{id: "a"}, {id: "b"}];
const view = {ownerDocument: doc, excalidrawContainer: container, isClosingOrMigrating: () => false,
excalidrawAPI: {getAppState: () => state, getSceneElements: () => elements}};
const event = extra => ({key: "ArrowUp", altKey: true, target: container,
preventDefault() {throw Error("Eligibility must not consume the event");},
stopPropagation() {throw Error("Eligibility must not consume the event");}, ...extra});
return {view, event, state, elements, doc, canvas, container};
}
test("canvas flowchart arrows remain eligible in their owning main/popout documents", async () => {
const graph = sourceHarness();
try {
const {isCanvasFlowchartNavigationShortcut: eligible} = await graph.importModule("src/view/managers/flowchartNavigationShortcut.ts");
const first = fixture(), second = fixture();
for (const context of [first, second]) {
for (const key of ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"]) assert.equal(eligible(context.view, context.event({key})), true);
assert.equal(eligible(context.view, context.event({repeat: true})), true);
context.doc.activeElement = context.canvas;
assert.equal(eligible(context.view, context.event({target: context.canvas})), true);
}
assert.equal(eligible(first.view, second.event()), false, "A foreign editor must not use the active view's scope");
} finally {graph.close();}
});
test("flowchart scope leaves text fields, property popups and other modifier shortcuts alone", async () => {
const graph = sourceHarness();
try {
const {isCanvasFlowchartNavigationShortcut: eligible} = await graph.importModule("src/view/managers/flowchartNavigationShortcut.ts");
const f = fixture();
for (const target of [{tagName: "TEXTAREA"}, {tagName: "INPUT"}, {className: "color-picker-content"}, {role: "dialog"}, null]) {
f.doc.activeElement = target;
assert.equal(eligible(f.view, f.event({target})), false);
}
f.doc.activeElement = f.container;
for (const flags of [{altKey: false}, {ctrlKey: true}, {metaKey: true}, {shiftKey: true}, {key: "Enter"}, {isComposing: true}, {defaultPrevented: true}]) assert.equal(eligible(f.view, f.event(flags)), false);
f.doc.activeElement = {};
assert.equal(eligible(f.view, f.event()), false, "Unfocused canvas input must retain its normal scope");
} finally {graph.close();}
});
test("flowchart scope requires one live selection and a ready editable canvas", async () => {
const graph = sourceHarness();
try {
const {isCanvasFlowchartNavigationShortcut: eligible} = await graph.importModule("src/view/managers/flowchartNavigationShortcut.ts");
const f = fixture();
for (const selectedElementIds of [{}, {a: true, b: true}, {missing: true}]) {
f.state.selectedElementIds = selectedElementIds;
assert.equal(eligible(f.view, f.event()), false);
}
f.state.selectedElementIds = {a: true, b: false};
assert.equal(eligible(f.view, f.event()), true);
for (const key of ["isLoading", "viewModeEnabled", "editingTextElement", "openDialog", "openPopup", "newElement", "resizingElement"]) {
f.state[key] = true;
assert.equal(eligible(f.view, f.event()), false);
delete f.state[key];
}
assert.equal(eligible(null, f.event()), false);
f.view.isClosingOrMigrating = () => true;
assert.equal(eligible(f.view, f.event()), false);
f.view.isClosingOrMigrating = () => false;
f.view.excalidrawAPI = null;
assert.equal(eligible(f.view, f.event()), false);
} finally {graph.close();}
});
@@ -0,0 +1,173 @@
/** Real native packets, filled contours, drawing embeds and public EA stroke workflows. */
import assert from 'node:assert/strict';
import { createNativeCLIActions } from './nativeCLITransport.mjs';
import { runInAppTask } from './inAppTask.mjs';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
export async function runCLIAuthoringExtensions({ cli, drawingPath, reportDir }) {
const prefix = drawingPath.replace(/\.excalidraw\.md$/, '') + '_authoring';
assert.ok(prefix.split('/').at(-1).startsWith('__excalidraw_cli_smoke_'));
const files = { host: prefix + '.excalidraw.md', request: prefix + '_request.json', source: prefix + '_source.excalidraw.md', note: prefix + '_plain.md', filled: prefix + '_filled.png', open: prefix + '_open.png', embed: prefix + '_embed.png', overview: prefix + '_overview.png', svg: prefix + '.svg' };
const { action, recoveries } = createNativeCLIActions(cli);
const ok = r => { assert.equal(r.ok, true, JSON.stringify(r)); return r; };
const id = suffix => prefix.slice(-30) + '-' + suffix;
const evaluate = code => JSON.parse(cli('eval', 'code=' + code).trim().replace(/^=>\s*/, ''));
const read = () => ok(action('read', { path: files.host, source: 'live', detail: 'elements' })).data;
let strokeResults;
try {
ok(action('create', { requestId: id('source'), path: files.source, elements: [{ type: 'rectangle', x: 0, y: 0, width: 200, height: 90, backgroundColor: '#1971c2', fillStyle: 'solid', label: { text: 'Embedded mind map' } }] }));
const points = Array.from({ length: 250 }, (_, i) => [80 * (Math.cos(i / 249 * Math.PI * 2) - 1), 60 * Math.sin(i / 249 * Math.PI * 2)]);
points[249] = [...points[0]];
const hostRequest = { apiVersion: 1, requestId: id('host'), path: files.host, elements: [
{ id: 'contour', type: 'line', x: 240, y: 100, width: 160, height: 120, polygon: true, points, roughness: 0, strokeColor: '#ff0000', backgroundColor: '#ff0000', fillStyle: 'solid' },
{ id: 'target', type: 'rectangle', x: 400, y: 0, width: 180, height: 80, label: { text: 'Selected target' } },
{ id: 'unrelated', type: 'ellipse', x: 400, y: 200, width: 80, height: 80 },
{ id: 'frame', type: 'frame', children: ['target'], name: 'Packet frame' },
] };
evaluate(`(async()=>{await app.vault.create(${JSON.stringify(files.request)},${JSON.stringify(JSON.stringify(hostRequest))});return JSON.stringify({written:true})})()`);
const created = ok(action('create', hostRequest, files.request));
const opened = ok(action('open', { path: files.host })).data;
const targetId = created.data.idMap.target, polygonId = created.data.idMap.contour;
evaluate(`(()=>{const v=app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.id===${JSON.stringify(opened.viewId)}).view;v.updateScene({appState:{selectedElementIds:{[${JSON.stringify(targetId)}]:true}},captureUpdate:'NEVER'});return JSON.stringify({selected:true})})()`);
const packet = ok(action('selection', { path: files.host, view: opened.viewId })).data;
assert.equal(packet.elements.length, 2); assert.equal(packet.elements.find(e => e.id === targetId).frameId, created.data.idMap.frame);
const labelId = packet.elements.find(e => e.id === targetId).labelId;
assert.ok(labelId && packet.elements.some(e => e.id === labelId && e.containerId === targetId));
const copied = await runInAppTask({ cli, execute: copyAndClearSelection, args: [files.host, [targetId], false], timeoutMs: 30000 });
assert.deepEqual(copied.packet, packet);
const selectedRead = ok(action('read', { path: packet.path, view: packet.view, source: 'live', detail: 'elements', revision: packet.revision, ids: packet.elements.map(e => e.id) })).data;
assert.equal(selectedRead.total, 2);
const unrelatedBefore = read().elements.find(e => e.id === created.data.idMap.unrelated);
ok(action('apply', { requestId: id('targeted'), path: files.host, view: packet.view, expectedRevision: selectedRead.revision, operations: [{ op: 'update', id: labelId, set: { text: 'Packet label edited' } }] }));
// Existing EA publication bumps version metadata on staged copies; all unrelated content must remain identical.
const content = ({ version, versionNonce, updated, ...element }) => element;
assert.deepEqual(content(read().elements.find(e => e.id === created.data.idMap.unrelated)), content(unrelatedBefore));
assert.equal(action('apply', { requestId: id('stale-packet'), path: files.host, expectedRevision: packet.revision, operations: [{ op: 'update', id: targetId, set: { opacity: 20 } }] }).error.code, 'STALE_REVISION');
if (process.env.EXCALIDRAW_CLI_POPOUT === '1') {
const popout = await runInAppTask({ cli, execute: copyAndClearSelection, args: [files.host, [targetId], true], timeoutMs: 45000 });
assert.notEqual(popout.packet.view, packet.view); assert.equal(popout.packet.path, files.host);
assert.deepEqual(popout.packet.elements.map(e => e.id), packet.elements.map(e => e.id));
}
ok(action('apply', { requestId: id('embed'), path: files.host, expectedRevision: read().revision, operations: [{ op: 'image', id: 'embed', asset: files.source, x: 20, y: 300, scale: false, anchor: true }] }));
const embedded = evaluate(`(async()=>{const v=app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.id===${JSON.stringify(opened.viewId)}).view;const image=v.getViewElements().find(e=>e.type==='image'),ef=v.excalidrawData.getFile(image.fileId);await app.vault.create(${JSON.stringify(files.note)},'An ordinary note');return JSON.stringify({source:ef.file.path,text:await app.vault.read(v.file)})})()`);
assert.equal(embedded.source, files.source); assert.ok(embedded.text.includes('|100%'));
const image = read().elements.find(e => e.type === 'image');
ok(action('export', { requestId: id('embed-png'), path: files.host, source: 'live', out: files.embed, theme: 'light', area: { x: image.x, y: image.y, width: image.width, height: image.height }, padding: 0 }));
const embedPixels = await runInAppTask({ cli, execute: redPixels, args: [files.embed], timeoutMs: 30000 });
assert.ok(embedPixels.blue > embedPixels.total * 0.3, JSON.stringify(embedPixels));
for (const asset of [files.note, files.host]) assert.equal(action('apply', { requestId: id(asset === files.note ? 'plain-note' : 'self'), path: files.host, expectedRevision: read().revision, operations: [{ op: 'image', asset }] }).error.code, 'INVALID_INPUT');
const area = { x: 150, y: 90, width: 20, height: 20 };
ok(action('export', { requestId: id('filled'), path: files.host, source: 'live', out: files.filled, theme: 'light', area, padding: 0 }));
const filled = await runInAppTask({ cli, execute: redPixels, args: [files.filled], timeoutMs: 30000 });
assert.ok(filled.red > filled.total * 0.8, JSON.stringify(filled));
assert.equal(read().elements.find(e => e.id === polygonId).polygon, true);
ok(action('apply', { requestId: id('open-line'), path: files.host, expectedRevision: read().revision, operations: [{ op: 'update', id: polygonId, set: { polygon: false, backgroundColor: 'transparent' } }] }));
assert.equal(read().elements.find(e => e.id === polygonId).polygon, false);
ok(action('export', { requestId: id('open-png'), path: files.host, source: 'live', out: files.open, theme: 'light', area, padding: 0 }));
const unfilled = await runInAppTask({ cli, execute: redPixels, args: [files.open], timeoutMs: 30000 });
assert.equal(unfilled.red, 0);
strokeResults = await runInAppTask({ cli, execute: exerciseStrokeAuthoring, args: [files.host], timeoutMs: 90000 });
ok(action('export', { requestId: id('host-svg'), path: files.host, source: 'disk', out: files.svg }));
ok(action('export', { requestId: id('host-png'), path: files.host, source: 'disk', out: files.overview, theme: 'light' }));
const exported = evaluate(`(async()=>{const s=await app.vault.read(app.vault.getFileByPath(${JSON.stringify(files.svg)}));return JSON.stringify({hasImage:s.includes('<image'),hasSourceLabel:s.includes('Embedded mind map')})})()`);
assert.equal(exported.hasImage, true);
evaluate(`(async()=>{for(const l of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===${JSON.stringify(files.host)})){await l.setViewState({type:'empty',state:{}});l.detach()}return JSON.stringify({closed:true})})()`);
ok(action('open', { path: files.host }));
const reopened = read().elements;
assert.equal(reopened.find(e => e.id === labelId).rawText, 'Packet label edited');
assert.equal(reopened.find(e => e.id === labelId).text.replace(/\s+/g, ' '), 'Packet label edited');
assert.equal(reopened.find(e => e.id === strokeResults.convertedId).type, 'line');
assert.equal(reopened.some(e => e.id === strokeResults.removedId), false);
assert.ok(reopened.some(e => e.type === 'image'));
return { status: 'passed', assertions: ['250-point polygon fill and false update verified by decoded pixels', 'live packet and actual copy command retain bound labels after deselection', ...(process.env.EXCALIDRAW_CLI_POPOUT === '1' ? ['actual selection-copy command in a separate popout owner document'] : []), 'targeted label edit preserves unrelated content and refuses a stale packet', 'linked drawing embed/100% anchor and host SVG/PNG/save/reopen', 'ordinary Markdown and self-embed refusal', ...strokeResults.assertions], transportRecoveries: recoveries };
} finally {
try {
// Preserve available render evidence on failures too, before deleting owned fixtures.
if (reportDir) {
const target = join(reportDir, 'authoring-extensions'); mkdirSync(target, { recursive: true });
for (const [key, path] of Object.entries(files).filter(([key]) => ['filled', 'open', 'embed', 'overview', 'svg'].includes(key))) {
const data = evaluate(`(async()=>{const f=app.vault.getFileByPath(${JSON.stringify(path)});if(!f)return JSON.stringify(null);const b=new Uint8Array(await app.vault.readBinary(f));let s='';for(const n of b)s+=String.fromCharCode(n);return JSON.stringify({base64:btoa(s)})})()`);
if (data) writeFileSync(join(target, key + (key === 'svg' ? '.svg' : '.png')), Buffer.from(data.base64, 'base64'));
}
}
} finally {
evaluate(`(async()=>{for(const path of ${JSON.stringify(Object.values(files))}){if(!path.startsWith(${JSON.stringify(prefix)}))throw Error('Unsafe cleanup');for(const l of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await l.setViewState({type:'empty',state:{}});l.detach()}const f=app.vault.getFileByPath(path);if(f)await app.vault.delete(f)}return JSON.stringify({clean:true})})()`);
}
}
}
async function copyAndClearSelection(c, path, ids, popout) {
let view = app.workspace.getLeavesOfType('excalidraw').find(l => l.view.file?.path === path)?.view;
if (!view) throw Error('Owned view missing');
if (popout) {
const originalView = view, leaf = app.workspace.openPopoutLeaf();
c.defer(async () => { await leaf.setViewState({ type: 'empty', state: {} }); leaf.detach(); app.workspace.setActiveLeaf(originalView.leaf, { focus: false }); });
await leaf.setViewState({ type: 'excalidraw', state: { file: path }, active: true });
await c.waitFor(() => leaf.view?.isLoaded && leaf.view?.excalidrawAPI, 'popout editor');
view = leaf.view;
if (view.containerEl.ownerDocument === originalView.containerEl.ownerDocument) throw Error('Expected a separate owner document');
}
view.updateScene({ appState: { selectedElementIds: Object.fromEntries(ids.map(id => [id, true])) }, captureUpdate: 'NEVER' });
const clipboard = view.containerEl.ownerDocument.defaultView.navigator.clipboard;
const original = Object.getOwnPropertyDescriptor(clipboard, 'writeText'); let packet;
Object.defineProperty(clipboard, 'writeText', { configurable: true, value: async value => { packet = JSON.parse(value); } });
try {
app.workspace.setActiveLeaf(view.leaf, { focus: true });
app.commands.executeCommandById('obsidian-excalidraw-plugin:copy-selection-for-agent');
await c.waitFor(() => packet, 'clipboard packet');
view.updateScene({ appState: { selectedElementIds: {} }, captureUpdate: 'NEVER' });
return { packet };
} finally { if (original) Object.defineProperty(clipboard, 'writeText', original); else delete clipboard.writeText; }
}
async function redPixels(c, path) {
const file = app.vault.getFileByPath(path), blob = new Blob([await app.vault.readBinary(file)]);
const url = URL.createObjectURL(blob), image = new Image();
try {
image.src = url; await image.decode();
const canvas = createFragment().createEl('canvas'); canvas.width = image.naturalWidth; canvas.height = image.naturalHeight;
const context = canvas.getContext('2d'); context.drawImage(image, 0, 0);
const data = context.getImageData(0, 0, canvas.width, canvas.height).data; let red = 0, blue = 0;
for (let i = 0; i < data.length; i += 4) {
if (data[i] > 180 && data[i + 1] < 80 && data[i + 2] < 80 && data[i + 3] > 200) red++;
if (data[i] < 80 && data[i + 1] < 180 && data[i + 2] > 150 && data[i + 3] > 200) blue++;
}
const center = (Math.floor(canvas.height / 2) * canvas.width + Math.floor(canvas.width / 2)) * 4;
return { red, blue, total: data.length / 4, center: [...data.slice(center, center + 4)] };
} finally { URL.revokeObjectURL(url); }
}
async function exerciseStrokeAuthoring(c, path) {
const p = app.plugins.plugins['obsidian-excalidraw-plugin'], view = app.workspace.getLeavesOfType('excalidraw').find(l => l.view.file?.path === path)?.view;
const ea = p.ea.getAPI(view), check = (value, message) => { if (!value) throw Error(message); };
c.defer(() => ea.destroy());
ea.style.roughness = 0; ea.style.strokeWidth = 2;
const curve = ea.addLine([[650, 300], [700, 400], [750, 300]]);
ea.getElement(curve).roundness = { type: 2 }; ea.getElement(curve).angle = Math.PI / 6;
ea.getElement(curve).customData = { ownedStroke: 'preserved' };
await ea.addElementsToView(false, false);
let original = view.getViewElements().find(e => e.id === curve), before = p.getCLIRuntime().getCommonBounds([original]);
ea.clear(); ea.copyViewElementsToEAforEditing([original]);
const result = ea.convertLineToFreedraw(curve, { tolerance: 0.2 });
check(result.pointCount > original.points.length && result.warnings.some(w => w.includes('excalidraw.com')), 'Curve sampling or compatibility warning missing');
check(view.getViewElements().find(e => e.id === curve).type === 'line', 'Conversion changed live scene before publication');
await ea.addElementsToView(false, false);
const converted = view.getViewElements().find(e => e.id === curve), after = p.getCLIRuntime().getCommonBounds([converted]);
check(converted.type === 'freedraw' && converted.customData.ownedStroke === 'preserved', 'Free-draw conversion/metadata missing');
check(before.every((n, i) => Math.abs(n - after[i]) < 3), 'Rotated spline moved during conversion');
ea.clear(); ea.copyViewElementsToEAforEditing([converted]);
const back = ea.convertFreedrawToLine(curve, { tolerance: 0.2, strokeWidth: 2 });
check(back.warnings.length > 0, 'Pressure loss warning missing');
await ea.addElementsToView(false, false);
ea.clear();
const first = ea.addLine([[650, 500], [700, 500]]), second = ea.addLine([[700, 550], [700, 500]]);
await ea.addElementsToView(false, false);
const lines = view.getViewElements().filter(e => [first, second].includes(e.id));
ea.clear(); ea.copyViewElementsToEAforEditing(lines);
ea.concatenateLines([first, second], { maxGap: 0 });
check(view.getViewElements().some(e => e.id === second), 'Concatenation deleted live source before publication');
await ea.addElementsToView(false, false); await view.save(false);
check(!view.getViewElements().some(e => e.id === second), 'Concatenation did not remove second source');
return { convertedId: curve, removedId: second, assertions: ['actual rotated spline bounds retained through line/free-draw conversion', 'conversion/concatenation remain isolated until explicit EA publication', 'custom metadata and surviving IDs retained', 'sharp/reversed endpoint concatenation and saved tombstones'] };
}
+3 -2
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { runCLILargeIdentity } from './cliLargeIdentity.mjs';
import { createNativeCLIActions } from './nativeCLITransport.mjs';
export async function runCLIImagePreviewScenario({ cli, drawingPath, reportDir }) {
const prefix = drawingPath.replace(/\.(?:excalidraw\.md|excalidraw|md)$/, '') + '_images';
@@ -11,7 +12,7 @@ export async function runCLIImagePreviewScenario({ cli, drawingPath, reportDir }
const outputs = [], artifacts = []; let largeIdentity;
const control = '__excalidrawImagePreviewRegression';
const evaluate = code => JSON.parse(cli('eval', `code=${code}`).trim().replace(/^=>\s*/, ''));
const action = (command, values = {}) => JSON.parse(cli(`obsidian-excalidraw-plugin:${command}`, `json=${JSON.stringify({ apiVersion: 1, ...values })}`));
const { action, recoveries } = createNativeCLIActions(cli);
const ok = result => { assert.equal(result.ok, true, JSON.stringify(result)); return result; };
const id = suffix => `${prefix.split('/').at(-1).slice(-38)}-${suffix}`;
const viewCode = `app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.file?.path===${JSON.stringify(paths.drawing)})?.view`;
@@ -120,7 +121,7 @@ export async function runCLIImagePreviewScenario({ cli, drawingPath, reportDir }
assert.equal(race?.error?.code, 'STALE_REVISION', JSON.stringify(race));
assert.equal(evaluate(`JSON.stringify({exists:!!app.vault.getFileByPath(${JSON.stringify(raced)})})`).exists, false);
evaluate(`(async()=>{const c=globalThis.${control};c.vault.read=c.read;await c.vault.adapter.writeBinary(c.source.path,c.bytes,{mtime:c.stat.mtime,ctime:c.stat.ctime});Object.assign(c.source.stat,c.stat);delete globalThis.${control};return JSON.stringify({restored:true})})()`);
return { status: 'passed', assertions: ['shared image original/thumbnail/placeholder identities', 'crop, mirroring, rotation, opacity, frame membership and title bounds', 'transparent PNG and SVG icon, light/dark', 'XML/Unicode labels', 'complete SVG omits original payloads', 'source text/elements/dirty unchanged', 'metadata clear preserves tags and customData', 'live/disk thumbnails', 'file transport and omitted-asset overwrite refusal', 'same-size same-mtime disk attachment race refuses publication'], artifacts, popoutCoverage: process.env.EXCALIDRAW_CLI_POPOUT === '1' ? 'passed' : 'not run (set EXCALIDRAW_CLI_POPOUT=1)', ...(largeIdentity ? { largeIdentity } : {}) };
return { status: 'passed', assertions: ['shared image original/thumbnail/placeholder identities', 'crop, mirroring, rotation, opacity, frame membership and title bounds', 'transparent PNG and SVG icon, light/dark', 'XML/Unicode labels', 'complete SVG omits original payloads', 'source text/elements/dirty unchanged', 'metadata clear preserves tags and customData', 'live/disk thumbnails', 'file transport and omitted-asset overwrite refusal', 'same-size same-mtime disk attachment race refuses publication'], artifacts, transportRecoveries: recoveries, popoutCoverage: process.env.EXCALIDRAW_CLI_POPOUT === '1' ? 'passed' : 'not run (set EXCALIDRAW_CLI_POPOUT=1)', ...(largeIdentity ? { largeIdentity } : {}) };
} finally {
evaluate(`(async()=>{const c=globalThis.${control};if(c){c.vault.read=c.read;c.release();if(c.bytes)await c.vault.adapter.writeBinary(c.source.path,c.bytes);delete globalThis.${control}}for(const path of ${JSON.stringify([...Object.values(paths), ...outputs])}){if(!path.startsWith(${JSON.stringify(prefix)}))throw Error('unsafe cleanup');for(const l of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await l.setViewState({type:'empty',state:{}});l.detach()}const f=app.vault.getFileByPath(path);if(f)await app.vault.delete(f)}return JSON.stringify({clean:true})})()`);
}
+35 -4
View File
@@ -1,6 +1,6 @@
/** Trusted in-scene controls, shared-source scope and persisted link/geometry behavior. */
export async function exerciseDrawingImagePreview(c, env, template, drawing, context, modifier) {
const { p, leaf, doc, check, click, key } = env;
const { p, leaf, doc, win, check, click, key } = env;
let view = await env.openDrawing("Image-host", {}, template);
const ea = p.ea.getAPI(view); let first, variant;
try {
@@ -48,7 +48,25 @@ export async function exerciseDrawingImagePreview(c, env, template, drawing, con
await click(buttons.find(button=>all?button.textContent.startsWith("All 3"):button.textContent==="Only this image"));
await c.waitFor(()=>!doc.querySelector(".excalidraw-drawing-preview-popover"),"image settings commit closes popover");
};
let popup=await open(); await chooseFrame(popup); await choosePadding(popup,3); await apply(popup,false);
let popup=await open();
await c.waitFor(()=>popup.closest(".mod-excalidraw-draggable"),"shared floating modal initialized");
check(win.getComputedStyle(popup).position === "absolute", "preview configuration is not a floating modal");
check(win.getComputedStyle(popup.parentElement).pointerEvents === "none", "floating modal blocks the workspace");
const start = popup.getBoundingClientRect(), x = start.left + 8, y = start.top + 8;
await env.input("Input.dispatchMouseEvent", {type:"mousePressed",x,y,button:"left",buttons:1,clickCount:1});
await env.input("Input.dispatchMouseEvent", {type:"mouseMoved",x:x+32,y:y+24,button:"left",buttons:1});
await env.input("Input.dispatchMouseEvent", {type:"mouseReleased",x:x+32,y:y+24,button:"left",buttons:0,clickCount:1});
await c.waitFor(()=>Math.abs(popup.getBoundingClientRect().left-start.left)>4,"native drag moves configuration modal");
const moved = popup.getBoundingClientRect();
await env.input("Input.dispatchMouseEvent", {type:"mousePressed",x:win.innerWidth-20,y:win.innerHeight-80,button:"left",buttons:1,clickCount:1});
await env.input("Input.dispatchMouseEvent", {type:"mouseReleased",x:win.innerWidth-20,y:win.innerHeight-80,button:"left",buttons:0,clickCount:1});
win.dispatchEvent(new win.Event("blur"));
check(popup.isConnected,"outside interaction or window blur closed the floating modal");
const imageBefore = popup.querySelector("img").src;
await chooseFrame(popup); await choosePadding(popup,3);
await c.waitFor(()=>popup.querySelector("img").src!==imageBefore&&popup.querySelector("img").naturalWidth>0,"floating modal live preview decoded");
check(Math.abs(popup.getBoundingClientRect().left-moved.left)<1&&Math.abs(popup.getBoundingClientRect().top-moved.top)<1,"preview rendering reset the dragged modal position");
await apply(popup,false);
check(get(first).fileId!==originalId && get("shared-copy").fileId===originalId,"only-this-image changed a shared copy");
check(link(first).includes("#^frame=frame-marker,padding=3"),"image settings not persisted to embedded link");
check(link(variant).includes("padding=20|100%"),"only-this-image changed a distinct view");
@@ -63,7 +81,15 @@ export async function exerciseDrawingImagePreview(c, env, template, drawing, con
check(link("shared-copy").includes("as-image,padding=5"),"apply-all pinned a default-thumbnail copy");
check(link(variant).includes("frame=frame-marker,padding=5|100%"),"apply-all lost another copy's anchor or frame");
for(let i=0;i<3;i++)check(JSON.stringify(center([first,"shared-copy",variant][i]))===JSON.stringify(oldCenters[i]),"apply-all changed a copy's center");
popup=await open(); await click(popup.querySelector(".checkbox-container")); await apply(popup,true);
popup=await open();
const toggle = popup.querySelector(".checkbox-container"), touch = toggle.getBoundingClientRect();
await env.input("Emulation.setTouchEmulationEnabled", {enabled:true,maxTouchPoints:1});
try {
await env.input("Input.dispatchTouchEvent", {type:"touchStart",touchPoints:[{x:touch.left+touch.width/2,y:touch.top+touch.height/2,id:1}]});
await env.input("Input.dispatchTouchEvent", {type:"touchEnd",touchPoints:[]});
await c.waitFor(()=>toggle.classList.contains("is-enabled"),"touch toggles anchoring without starting a drag");
} finally { await env.input("Emulation.setTouchEmulationEnabled", {enabled:false}); }
await apply(popup,true);
for(const id of [first,"shared-copy",variant]){
const el=get(id), source=view.excalidrawData.getFile(el.fileId);
check(link(id).endsWith("|100%")&&el.customData.isAnchored,"100% state absent from link or derived canvas flag");
@@ -73,10 +99,15 @@ export async function exerciseDrawingImagePreview(c, env, template, drawing, con
const savedLinks=beforeLinks.map(value=>value.replace(/^[^#|]*/,app.metadataCache.fileToLinktext(drawing,view.file.path)));
popup=await open(); await choosePadding(popup,9); await key("Escape","Escape",27);
check(!doc.querySelector(".excalidraw-drawing-preview-popover")&&JSON.stringify(view.getViewElements())===before,"Escape wrote draft image settings");
popup=await open(); await choosePadding(popup,11); await click(popup.querySelector(".modal-close-button, .modal-header-button"));
check(!popup.isConnected&&JSON.stringify(view.getViewElements())===before,"close button wrote draft settings");
await view.drawingImagePreview.open(first); view.drawingImagePreview.reset();
await new Promise(resolve=>window.setTimeout(resolve,30));
check(!doc.querySelector(".excalidraw-drawing-preview-popover"),"quick close left a deferred floating modal behind");
view=await env.saveReopen(view);
c.caseTrace.imageLinks = { expected: savedLinks, after: [first,"shared-copy",variant].map(link) };
check(JSON.stringify([first,"shared-copy",variant].map(link))===JSON.stringify(savedLinks),"reopen lost image preview links or anchoring");
for(const id of [first,"shared-copy",variant])check(view.excalidrawData.getFile(get(id).fileId).file===drawing&&get(id).customData.isAnchored,"reopen changed image source or anchoring");
check(view.getViewElements().filter(el=>el.type==='image').length===3,"settings created duplicate image elements");
return { assertions: ["selected drawing image opens owner-window configuration", "native frame/padding controls prompt once for all three source copies", "only-this-image isolates its link and preserves image area/center", "one native undo/redo restores references and geometry", "apply-all changes only edited fields across shared and distinct references", "100% persists in links and uses intrinsic dimensions", "Escape cancels drafts", "save/reopen preserves all links and three scene elements"] };
return { assertions: ["selected drawing image opens owner-window configuration", "native frame/padding controls prompt once for all three source copies", "only-this-image isolates its link and preserves image area/center", "one native undo/redo restores references and geometry", "apply-all changes only edited fields across shared and distinct references", "100% persists in links and uses intrinsic dimensions", "floating modal drags without blocking workspace or closing on blur", "live preview preserves dragged position", "Escape and close button cancel drafts", "quick close cancels deferred modal setup", "save/reopen preserves all links and three scene elements"] };
}
+93 -5
View File
@@ -4,6 +4,7 @@ import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
const CONTROL = "__excalidrawEmbedRecovery";
const MARKDOWN_SIDE = "Markdown side of the open-md fixture";
function setup(control, drawingPath, paths) {
if (globalThis[control]) throw Error("embed controller already exists");
@@ -11,7 +12,8 @@ function setup(control, drawingPath, paths) {
const plugin = app.plugins.plugins["obsidian-excalidraw-plugin"];
const c = { plugin, drawingPath, paths, owned: [], state: "idle", paused: 0, hold: false,
originalAwaitInit: plugin.awaitInit, hadOwnAwaitInit: Object.hasOwn(plugin, "awaitInit"),
previewImageType: plugin.settings.previewImageType };
previewImageType: plugin.settings.previewImageType,
renderImageInHoverPreviewForMDNotes: plugin.settings.renderImageInHoverPreviewForMDNotes };
globalThis[control] = c;
plugin.awaitInit = async function (...args) {
await c.originalAwaitInit.apply(this, args);
@@ -41,20 +43,26 @@ function snapshot(control) {
nativeImages: nativeImages.map(el => ({ decoded: decoded(el), visible: visible(el) })), owned: c.owned };
}
async function createHybridFixtures(control) {
async function createHybridFixtures(control, markdownSide) {
const c = globalThis[control];
const source = await app.vault.read(app.vault.getFileByPath(c.drawingPath));
if (!source.startsWith("---") || !source.includes("# Excalidraw Data")) throw Error("hybrid embed regression requires a Markdown drawing");
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aL1sAAAAASUVORK5CYII="), ch => ch.charCodeAt(0));
await app.vault.createBinary(c.paths[3], png.buffer); c.owned.push(c.paths[3]);
const embeds = `![[#^as-image]]\n\n![[${c.drawingPath}|180]]\n\n![[${c.paths[3]}|80]]\n\n`;
const hybrid = source.replace(/^---\r?\n/, "---\nexcalidraw-open-md: true\n").replace("# Excalidraw Data", `${embeds}# Excalidraw Data`);
const hybrid = source.replace(/^---\r?\n/, "---\nexcalidraw-open-md: true\nexcalidraw-embed-md: true\n")
.replace("# Excalidraw Data", `${markdownSide}\n\n${embeds}# Excalidraw Data`);
await app.vault.create(c.paths[2], hybrid); c.owned.push(c.paths[2]);
await app.vault.create(c.paths[4], `![[${c.paths[2]}#^as-image]]\n\n![[${c.paths[2]}]]`); c.owned.push(c.paths[4]);
// A native Markdown fallback cannot resolve Excalidraw frame references. It
// would parse this entire drawing and recursively encounter the same embed.
const recursive = source.replace("# Excalidraw Data", `![[${c.paths[5]}#^frame=PDF frame]]\n\n# Excalidraw Data`);
await app.vault.create(c.paths[5], recursive); c.owned.push(c.paths[5]);
const openOnly = source.replace(/^---\r?\n/, "---\nexcalidraw-open-md: true\n")
.replace("# Excalidraw Data", `${markdownSide}\n\n# Excalidraw Data`);
await app.vault.create(c.paths[6], openOnly); c.owned.push(c.paths[6]);
const links = [c.paths[6], c.paths[2]].map(path => `[[${path}]]`).join("\n\n");
await app.vault.create(c.paths[7], `![[${c.paths[6]}]]\n\n${links}`); c.owned.push(c.paths[7]);
}
async function renderPDFEmbeds(control, imageType) {
@@ -96,6 +104,74 @@ async function openHybrid(control, mode, nested) {
if (mode === "source") c.leaf.view.editor.setCursor({ line: 0, ch: 0 });
}
async function verifyOpenMarkdown(control, mode, markdownSide) {
const c = globalThis[control];
c.plugin.settings.previewImageType = "SVGIMG";
const drawing = app.vault.getFileByPath(c.paths[6]);
const deadline = Date.now() + 5000;
const waitFor = async (predicate, label) => {
while (!predicate()) {
if (Date.now() > deadline) throw Error(`${label}: ${JSON.stringify({
actualMode: c.leaf.view.getMode?.(),
contents: c.leaf.view.contentEl?.innerHTML.slice(0, 2400),
images: [...c.leaf.view.contentEl?.querySelectorAll("[fileSource]") ?? []]
.map(el => ({ path: el.getAttribute("fileSource"), width: el.naturalWidth, visible: !!el.getClientRects().length })),
})}`);
await new Promise(resolve => window.setTimeout(resolve, 25));
}
};
await waitFor(() => c.plugin.isExcalidrawFile(drawing), "open-md drawing metadata did not become ready");
await c.leaf.setViewState({ type: "empty", state: {} });
if (!mode) {
await c.leaf.openFile(drawing);
if (c.leaf.view.getViewType() !== "markdown") throw Error("open-md did not open the Markdown editor by default");
return;
}
await c.leaf.setViewState({ type: "markdown", state: { file: c.paths[7], mode, source: false } });
const view = c.leaf.view;
app.workspace.setActiveLeaf(c.leaf, { focus: true });
if (mode === "source") view.editor.setCursor({ line: view.editor.lastLine(), ch: 0 });
await waitFor(() => {
const image = [...view.contentEl.querySelectorAll("[fileSource]")]
.find(el => el.getAttribute("fileSource") === drawing.path);
return image?.tagName === "IMG" && image.complete && image.naturalWidth > 0 && image.getClientRects().length;
}, `open-md did not render as a drawing embed in ${mode}`);
if (view.contentEl.textContent.includes(markdownSide)) throw Error("open-md embed exposed its Markdown side");
}
async function verifyPagePreview(control, index, showDrawing, expectImage, markdownSide) {
const c = globalThis[control];
const view = c.leaf.view;
const doc = view.contentEl.ownerDocument;
const win = doc.defaultView;
const path = c.paths[index];
const link = [...view.contentEl.querySelectorAll("a.internal-link")].find(el => el.getAttribute("data-href") === path);
if (!link) throw Error("Page Preview fixture link is missing");
const event = new win.MouseEvent("mouseover", { bubbles: true, ctrlKey: true, metaKey: true });
const hoverParent = { hoverPopover: null };
c.plugin.settings.renderImageInHoverPreviewForMDNotes = showDrawing;
app.workspace.trigger("hover-link", { event, hoverParent, targetEl: link, source: "preview", sourcePath: view.file.path, linktext: path });
try {
const deadline = Date.now() + 5000;
while (Date.now() < deadline) {
const preview = hoverParent.hoverPopover?.hoverEl;
if (preview) {
const image = [...preview.querySelectorAll("[fileSource]")].find(el => el.getAttribute("fileSource") === path);
if (expectImage ? image?.complete && image.naturalWidth > 0 :
!image && preview.textContent.includes(markdownSide)) return;
}
await new Promise(resolve => win.setTimeout(resolve, 25));
}
throw Error(`Page Preview did not show the expected side: ${JSON.stringify({
index, showDrawing, expectImage,
html: hoverParent.hoverPopover?.hoverEl?.outerHTML.slice(0, 1000),
})}`);
} finally {
hoverParent.hoverPopover?.hide();
c.plugin.settings.renderImageInHoverPreviewForMDNotes = c.renderImageInHoverPreviewForMDNotes;
}
}
async function createFixtures(control) {
const c = globalThis[control];
const view = app.workspace.getLeavesOfType("excalidraw").find(leaf => leaf.view.file?.path === c.drawingPath)?.view;
@@ -170,6 +246,7 @@ async function cleanup(control, expectedPaths) {
if (c.hadOwnAwaitInit) c.plugin.awaitInit = c.originalAwaitInit;
else delete c.plugin.awaitInit;
c.plugin.settings.previewImageType = c.previewImageType;
c.plugin.settings.renderImageInHoverPreviewForMDNotes = c.renderImageInHoverPreviewForMDNotes;
if (c.root && c.parent) c.parent.insertBefore(c.root, c.next?.parentElement === c.parent ? c.next : null);
if (c.leaf) { await c.leaf.setViewState({ type: "empty", state: {} }); c.leaf.detach(); }
for (const path of c.owned) {
@@ -181,7 +258,8 @@ async function cleanup(control, expectedPaths) {
}
export async function runEmbedRecoveryScenario({ cli, drawingPath }) {
const paths = ["large.md", "note.md", "hybrid.excalidraw.md", "pixel.png", "nested.md", "pdf.excalidraw.md"]
const paths = ["large.md", "note.md", "hybrid.excalidraw.md", "pixel.png", "nested.md", "pdf.excalidraw.md",
"open-markdown.excalidraw.md", "frontmatter-consumer.md"]
.map(kind => `__excalidraw_embed_${randomUUID()}_${kind}`);
// Test-only CLI boundary: fn is always a function defined in this module, and
// arguments are JSON literals in JavaScript source, never HTML/script markup.
@@ -206,7 +284,17 @@ export async function runEmbedRecoveryScenario({ cli, drawingPath }) {
invoke(setup, drawingPath, paths);
try {
await act(createFixtures);
await act(createHybridFixtures);
await act(createHybridFixtures, MARKDOWN_SIDE);
await act(verifyOpenMarkdown, null, MARKDOWN_SIDE);
checks.push("open-md still opens the file in the Markdown editor by default");
for (const mode of ["source", "preview"]) {
await act(verifyOpenMarkdown, mode, MARKDOWN_SIDE);
checks.push(`open-md embeds the drawing side in ${mode}`);
}
for (const [index, showDrawing, expectImage] of [[6, false, false], [6, true, true], [2, true, false]]) {
await act(verifyPagePreview, index, showDrawing, expectImage, MARKDOWN_SIDE);
}
checks.push("Obsidian Page Preview honors the hover setting for open-md and preserves the Markdown side for embed-md");
for (const imageType of ["SVGIMG", "PNG", "SVG"]) {
await act(renderPDFEmbeds, imageType);
checks.push(`${imageType}: native Markdown PDF preparation completes with three frames and a native PNG, without recursive drawing transclusion`);
+313 -1
View File
@@ -3,22 +3,38 @@ export async function exerciseInteractionBehavior(c, env, rows, modifier) {
const { p, check, doc, key, click } = env;
for (const row of rows)
await c.case(row.testId, row.featureIds, async () => {
const checkColorShortcut = row.id === "toolbar-context-shortcuts" &&
["main", "popout"].includes(row.context);
Object.assign(p.settings, {
defaultMode: "normal",
disableContextMenu: false,
penModeSingleFingerPanning: false,
});
if (checkColorShortcut) p.settings.desktopUIMode = "full";
let view = await env.openDrawing(row.id),
api = view.excalidrawAPI;
const events = [],
listener = (e) =>
events.push({
type: e.type,
key: e.key,
altKey: e.altKey,
at: e.timeStamp,
trusted: e.isTrusted,
pointerType: e.pointerType,
x:e.clientX,y:e.clientY,target:e.target?.outerHTML?.slice(0,250),
});
const toolsPanelLayouts = [];
const flowchartHotkeys = [];
if (checkColorShortcut) {
// Match the reported core-Obsidian conflict without persisting hotkeys.
for (const [id, arrow] of [["editor:swap-line-up", "ArrowUp"], ["editor:swap-line-down", "ArrowDown"]]) {
check(app.commands.commands[id], "Missing core move-line command");
flowchartHotkeys.push({id, prior: structuredClone(app.hotkeyManager.getHotkeys(id))});
app.hotkeyManager.setHotkeys(id, [{modifiers: ["Alt"], key: arrow}]);
}
p.registerHotkeyOverrides();
}
for (const type of ["keydown", "pointerdown", "contextmenu"])
doc.addEventListener(type, listener, true);
try {
@@ -121,6 +137,296 @@ export async function exerciseInteractionBehavior(c, env, rows, modifier) {
"Palette input was not trusted",
);
} else {
if (checkColorShortcut) {
// Flowchart navigation must receive all four Alt/Option+Arrow keys.
const graph = view.packages.excalidrawLib.convertToExcalidrawElements(
[
{
id: "nav-center",
type: "rectangle",
x: 300,
y: 300,
width: 100,
height: 60,
},
{
id: "nav-up",
type: "rectangle",
x: 300,
y: 100,
width: 100,
height: 60,
},
{
id: "nav-down",
type: "rectangle",
x: 300,
y: 500,
width: 100,
height: 60,
},
{
id: "nav-left",
type: "rectangle",
x: 100,
y: 300,
width: 100,
height: 60,
},
{
id: "nav-right",
type: "rectangle",
x: 500,
y: 300,
width: 100,
height: 60,
},
...[
["up", 0, -200],
["down", 0, 200],
["left", -200, 0],
["right", 200, 0],
].map(([direction, x, y]) => ({
type: "arrow",
x: 350,
y: 330,
width: Math.abs(x),
height: Math.abs(y),
points: [
[0, 0],
[x, y],
],
start: { id: "nav-center" },
end: { id: "nav-" + direction },
})),
].map((el) =>
el.type === "rectangle"
? { ...el, label: { text: el.id, fontFamily: 2 } }
: el
),
{ regenerateIds: false }
);
check(
graph
.filter((el) => el.type === "arrow")
.every(
(el) =>
el.startBinding?.elementId === "nav-center" &&
el.endBinding?.elementId
),
"Flowchart fixture has incomplete bindings"
);
const positions = graph.map(({ id, x, y }) => ({ id, x, y }));
const originalGraphScene = api.getSceneElements();
const navigationMode = api.getEditorInterface().desktopUIMode;
try {
for (const mode of ["full", "tray", "compact"]) {
p.settings.desktopUIMode = mode;
view.setUIMode(mode);
await c.waitFor(
() => api.getEditorInterface().desktopUIMode === mode,
"flowchart UI mode"
);
for (const [direction, keyCode] of [
["up", 38],
["down", 40],
["left", 37],
["right", 39],
]) {
api.updateScene({
elements: graph,
appState: {
selectedElementIds: {},
selectedGroupIds: {},
activeTool: {
type: "selection",
customType: null,
locked: false,
lastActiveTool: null,
},
viewModeEnabled: false,
openPopup: null,
},
captureUpdate: "NEVER",
});
api.setViewport({ target: graph, animation: false });
const canvas = view.containerEl.querySelector("canvas.interactive");
let point, pointSignature, stableSince;
await c.waitFor(() => {
const st = api.getAppState();
point = {
x: (300 + st.scrollX) * st.zoom.value + st.offsetLeft,
y: (310 + st.scrollY) * st.zoom.value + st.offsetTop,
};
// Viewport/selection layout commits can follow the public
// scene update. Measure the settled node before CDP input.
const signature = JSON.stringify([point.x, point.y, st.zoom.value]);
if (signature !== pointSignature) {
pointSignature = signature;
stableSince = Date.now();
}
return doc.elementFromPoint(point.x, point.y) === canvas && Date.now() - stableSince >= 180;
}, "settled uncovered flowchart node");
c.caseTrace = {flowchart: {mode, direction, phase: "mouse selection", point, selected: api.getAppState().selectedElementIds, events}};
await env.input(
"Input.dispatchMouseEvent",
["mousePressed", "mouseReleased"].map((type) => ({
type,
...point,
button: "left",
buttons: type === "mousePressed" ? 1 : 0,
clickCount: 1,
}))
);
await c.waitFor(
() => api.getAppState().selectedElementIds["nav-center"],
"mouse-selected flowchart center"
);
const arrow = "Arrow" + direction[0].toUpperCase() + direction.slice(1);
await env.input("Input.dispatchKeyEvent", {
type: "keyDown",
key: "Alt",
code: "AltLeft",
windowsVirtualKeyCode: 18,
modifiers: 1,
});
try {
await key(arrow, arrow, keyCode, 1);
} finally {
await env.input("Input.dispatchKeyEvent", {
type: "keyUp",
key: "Alt",
code: "AltLeft",
windowsVirtualKeyCode: 18,
modifiers: 0,
});
}
c.caseTrace = {
flowchart: {
mode,
direction,
selected: api.getAppState().selectedElementIds,
activeElement: doc.activeElement?.outerHTML?.slice(0, 600),
events,
},
};
await c.waitFor(
() => api.getAppState().selectedElementIds["nav-" + direction],
"Alt/Option+" + arrow + " selects the flowchart neighbor"
);
check(
positions.every((el) => {
const live = api
.getSceneElements()
.find((item) => item.id === el.id);
return live?.x === el.x && live?.y === el.y;
}),
"Flowchart navigation moved scene elements"
);
}
}
} finally {
api.updateScene({
elements: originalGraphScene,
appState: { selectedElementIds: {}, openPopup: null },
captureUpdate: "NEVER",
});
p.settings.desktopUIMode = navigationMode;
view.setUIMode(navigationMode);
}
// Re-registering the active view must replace its root handlers.
const scope = app.keymap.getRootScope(), handlerCount = scope.keys.length;
p.registerHotkeyOverrides();
p.registerHotkeyOverrides();
check(scope.keys.length === handlerCount, "Flowchart scope handlers accumulated");
// The same configured keys must retain core Markdown line movement.
view = await env.saveReopen(view);
api = view.excalidrawAPI;
const drawing = view.file, leaf = view.leaf;
const note = await env.create("flowchart-hotkey-scope.md", "one\ntwo\nthree");
await leaf.openFile(note);
await c.waitFor(() => leaf.view.getViewType() === "markdown" && leaf.view.editor, "Markdown hotkey target");
app.workspace.setActiveLeaf(leaf, {focus: true});
leaf.view.editor.setCursor({line: 1, ch: 0});
leaf.view.editor.focus();
await c.waitFor(() => leaf.view.containerEl.contains(doc.activeElement) && doc.activeElement?.closest(".cm-editor"), "Markdown editor focus");
await env.input("Input.dispatchKeyEvent", {type: "keyDown", key: "Alt", code: "AltLeft", windowsVirtualKeyCode: 18, modifiers: 1});
try {
await key("ArrowUp", "ArrowUp", 38, 1);
await c.waitFor(() => leaf.view.editor.getValue() === "two\none\nthree", "Alt+Up still moves Markdown lines");
await key("ArrowDown", "ArrowDown", 40, 1);
await c.waitFor(() => leaf.view.editor.getValue() === "one\ntwo\nthree", "Alt+Down still moves Markdown lines");
} finally {
await env.input("Input.dispatchKeyEvent", {type: "keyUp", key: "Alt", code: "AltLeft", windowsVirtualKeyCode: 18, modifiers: 0});
}
await leaf.view.save();
await leaf.openFile(drawing);
await env.ready(leaf);
view = leaf.view;
api = view.excalidrawAPI;
app.workspace.setActiveLeaf(leaf, {focus: true});
await c.waitFor(() => p.activeExcalidrawView === view, "restored active drawing scope");
check(scope.keys.length === handlerCount, "Drawing scope was not restored exactly once");
// #3061: native keys must stay inside a color picker in its own document.
const priorMode = api.getEditorInterface().desktopUIMode;
const originalElements = api.getSceneElements();
view.setUIMode("full");
await c.waitFor(() => api.getEditorInterface().desktopUIMode === "full", "desktop color-picker mode");
const probe = view.packages.excalidrawLib.convertToExcalidrawElements([
{ type: "text", text: "Color shortcut probe", x: 30, y: 30, fontFamily: 2, strokeColor: "#e03131" },
])[0];
try {
api.updateScene({elements: [probe], appState: {selectedElementIds: {[probe.id]: true}, viewModeEnabled: false, openPopup: null}, captureUpdate: "NEVER"});
await c.waitFor(() => api.getAppState().selectedElementIds[probe.id], "selected color shortcut text");
view.excalidrawContainer.focus();
await key("s", "KeyS", 83);
await c.waitFor(() => api.getAppState().openPopup === "elementStroke" && doc.querySelector(".color-picker-content"), "S opens stroke palette");
const picker = doc.querySelector(".color-picker-content");
const choice = picker.querySelector('.color-picker-content--default button[aria-label$="— s"]');
check(choice, "S palette entry missing");
const expected = choice.title.match(/#[0-9a-f]{6}/i)?.[0];
check(expected && expected !== probe.strokeColor, "Color shortcut fixture is ambiguous");
c.caseTrace = {colorShortcut: {context: row.context, expected, activeElement: doc.activeElement?.outerHTML?.slice(0, 800), pickerDocument: picker.ownerDocument === doc}};
await key("s", "KeyS", 83);
await c.waitFor(() => api.getSceneElements().find(el => el.id === probe.id)?.strokeColor === expected, "second S applies palette color to selected text");
check(api.getAppState().activeTool.type === "selection", "Palette shortcut reached tool selection");
await key("Escape", "Escape", 27);
await c.waitFor(() => !doc.querySelector(".color-picker-content"), "palette Escape closes in owning window");
} finally {
api.updateScene({elements: originalElements, appState: {selectedElementIds: {}, openPopup: null}, captureUpdate: "NEVER"});
view.setUIMode(priorMode);
}
}
const panel = view.toolsPanelRef.current;
const wasVisible = panel.state.visible;
if (!wasVisible) panel.toggleVisibility(true);
try {
const wrapper = panel.containerRef.current;
const handle = wrapper.querySelector(".excalidraw-toolsPanel-dragHandle");
const body = wrapper.querySelector(".Island.App-menu__left.scrollbar");
await c.waitFor(() => body.getBoundingClientRect().height > 0, "expanded Obsidian tools panel");
const aligned = () => {
const headerRect = handle.getBoundingClientRect();
const bodyRect = body.getBoundingClientRect();
const layout = {
handle: {left: headerRect.left, right: headerRect.right},
body: {left: bodyRect.left, right: bodyRect.right},
};
check(Math.abs(headerRect.left - bodyRect.left) < 0.5 &&
Math.abs(headerRect.right - bodyRect.right) < 0.5,
"Tools panel edges differ: " + JSON.stringify(layout));
toolsPanelLayouts.push(layout);
};
aligned();
await click(handle);
await c.waitFor(() => body.getBoundingClientRect().height === 0, "tools panel collapse");
await click(handle);
await c.waitFor(() => body.getBoundingClientRect().height > 0, "tools panel expand");
aligned();
} finally {
if (!wasVisible && panel.state.visible) panel.toggleVisibility(true);
}
api.updateScene({
appState: { penMode: false, viewModeEnabled: false },
captureUpdate: "NEVER",
@@ -284,13 +590,19 @@ export async function exerciseInteractionBehavior(c, env, rows, modifier) {
view = await env.saveReopen(view);
}
return {
assertions: row.assertions,
assertions: row.assertions.filter(assertion => checkColorShortcut ||
!assertion.startsWith("desktop ")),
actual: env.geometry(),
input:
"trusted CDP mouse/touch/keyboard; context menu uses mouse compatibility input in mobile emulation",
events,
toolsPanelLayouts,
};
} finally {
for (const {id, prior} of flowchartHotkeys) {
if (prior === undefined) app.hotkeyManager.removeHotkeys(id);
else app.hotkeyManager.setHotkeys(id, prior);
}
for (const type of ["keydown", "pointerdown", "contextmenu"])
doc.removeEventListener(type, listener, true);
if (doc.querySelector(".prompt input.prompt-input, .context-menu"))
+29 -3
View File
@@ -1,6 +1,8 @@
/** Native authoring round-trip on fixtures owned by the guarded parent runner. */
import assert from 'node:assert/strict';
import { runCLIImagePreviewScenario } from './cliImagePreview.mjs';
import { runCLIAuthoringExtensions } from './cliAuthoringExtensions.mjs';
import { createNativeCLIActions } from './nativeCLITransport.mjs';
export async function runNativeCLIScenario({ cli, drawingPath, reportDir }) {
const prefix = drawingPath.replace(/\.(?:excalidraw\.md|excalidraw|md)$/, '') + '_native_cli';
@@ -9,15 +11,19 @@ export async function runNativeCLIScenario({ cli, drawingPath, reportDir }) {
const paths = { drawing: `${prefix}.excalidraw.md`, request: `${prefix}.json`, png: `${prefix}.png`, svg: `${prefix}.svg`, disk: `${prefix}_disk.png`,
script: `${prefix}_script.md`, template: `${prefix}_template.excalidraw.md`, invalid: `${prefix}_invalid.excalidraw.md` };
const evaluate = code => JSON.parse(cli('eval', `code=${code}`).trim().replace(/^=>\s*/, ''));
const action = (command, request = {}) => JSON.parse(cli(`obsidian-excalidraw-plugin:${command}`, `json=${JSON.stringify({ apiVersion: 1, ...request })}`));
const { action, recoveries } = createNativeCLIActions(cli);
const ok = (result) => { assert.equal(result.ok, true, JSON.stringify(result)); return result; };
const write = (path, text) => evaluate(`(async()=>{const path=${JSON.stringify(path)},file=app.vault.getFileByPath(path);if(file)await app.vault.modify(file,${JSON.stringify(text)});else await app.vault.create(path,${JSON.stringify(text)});return JSON.stringify({written:true})})()`);
const viewCode = `app.workspace.getLeavesOfType('excalidraw').find(leaf=>leaf.view.file?.path===${JSON.stringify(paths.drawing)})?.view`;
const control = '__excalidrawNativeCLIRegression';
const extrasControl = '__excalidrawCLIMermaidDependency';
let cleanup = false;
const artifacts = []; let imagePreviews;
const artifacts = []; let imagePreviews, authoringExtensions;
try {
for (const command of ['help', 'status', 'skill', 'list']) ok(action(command));
const status = ok(action('status')).data;
assert.equal(typeof status.mindMapBuilder.ready, 'boolean');
assert.equal(typeof status.extras.components.mermaid.compatible, 'boolean');
assert.equal(ok(action('schema', { action: 'apply' })).data.command, 'apply');
assert.equal(ok(action('api', { name: 'executeCLI' })).data.entries[0].name, 'executeCLI');
const create = { apiVersion: 1, requestId: `${idPrefix}-create`, path: paths.drawing, elements: [
@@ -88,6 +94,7 @@ export async function runNativeCLIScenario({ cli, drawingPath, reportDir }) {
live = read();
const image = ok(action('apply', { requestId: `${idPrefix}-image`, path: paths.drawing, expectedRevision: live.revision, operations: [{ op: 'image', id: 'preview', asset: paths.png, x: 0, y: 200 }] })); assert.ok(image.data.idMap.preview);
assert.equal(ok(action('read', { path: paths.drawing, source: 'disk' })).data.types.image, 1);
authoringExtensions = await runCLIAuthoringExtensions({ cli, drawingPath, reportDir });
imagePreviews = await runCLIImagePreviewScenario({ cli, drawingPath, reportDir });
write(paths.script, 'return {input:utils.input,source:utils.executionSource,converter:typeof utils.excalidrawLib.convertToExcalidrawElements};');
const scriptRequest = { requestId: `${idPrefix}-script`, script: paths.script, trusted: true, args: { x: 0, text: '${literal}' } };
@@ -96,14 +103,33 @@ export async function runNativeCLIScenario({ cli, drawingPath, reportDir }) {
write(paths.script, 'await utils.inputPrompt("must fail");');
assert.equal(action('script', scriptRequest).error.field, 'requestId');
assert.equal(action('script', { ...scriptRequest, requestId: `${idPrefix}-prompt` }).error.code, 'INTERACTION_REQUIRED');
write(paths.script, 'return {nodeId:"already-saved",arrowId:undefined};');
const unsafeResult = { ...scriptRequest, requestId: `${idPrefix}-undefined` };
assert.equal(action('script', unsafeResult).error.code, 'OUTCOME_UNKNOWN');
write(paths.script, 'return JSON.parse(JSON.stringify({nodeId:"already-saved",arrowId:undefined}));');
assert.deepEqual(ok(action('script', { ...scriptRequest, requestId: `${idPrefix}-json-safe` })).data, { nodeId: 'already-saved' });
write(paths.script, 'return await ea.addMermaid("flowchart TD; A-->B");');
evaluate(`(()=>{const g=app.plugins.plugins['obsidian-excalidraw-plugin'].extrasGateway;if(globalThis.${extrasControl})throw Error('Extras test already active');globalThis.${extrasControl}={gateway:g,descriptor:Object.getOwnPropertyDescriptor(g,'getAPI')};g.getAPI=()=>({versions:{mermaid:'3.0.0'},features:{isActive:()=>true,enable:()=>{throw Error('Unexpected activation')}}});return JSON.stringify({ready:true})})()`);
try {
const incompatible = ok(action('status')).data;
assert.equal(incompatible.ready, true);
assert.equal(incompatible.extras.components.mermaid.version, '3.0.0');
assert.equal(incompatible.extras.components.mermaid.compatible, false);
const refused = action('script', { ...scriptRequest, requestId: `${idPrefix}-mermaid-version` });
assert.equal(refused.error.code, 'DEPENDENCY_UNAVAILABLE');
assert.equal(refused.mutation, 'unknown'); assert.equal(refused.persistence, 'unknown');
} finally {
evaluate(`(()=>{const c=globalThis.${extrasControl};if(c.descriptor)Object.defineProperty(c.gateway,'getAPI',c.descriptor);else delete c.gateway.getAPI;delete globalThis.${extrasControl};return JSON.stringify({restored:true})})()`);
}
const close = evaluate(`(async()=>{for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===${JSON.stringify(paths.drawing)})){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}return JSON.stringify({closed:true})})()`); assert.equal(close.closed, true);
ok(action('open', { path: paths.drawing }));
await new Promise(resolve => setTimeout(resolve, 250));
assert.equal(read().elements.find(element => element.id === label.id).rawText, 'Recoverable edit');
} finally {
evaluate(`(()=>{const c=globalThis.${extrasControl};if(c){if(c.descriptor)Object.defineProperty(c.gateway,'getAPI',c.descriptor);else delete c.gateway.getAPI;delete globalThis.${extrasControl}}return JSON.stringify({restored:true})})()`);
const result = evaluate(`(async()=>{const c=globalThis.${control};if(c){if(c.original)c.model.addTextElement=c.original;if(c.originalSave)c.view.saveWithOutcome=c.originalSave;c.release?.();delete globalThis.${control}}const paths=${JSON.stringify(Object.values(paths))};for(const path of paths){if(!path.startsWith(${JSON.stringify(prefix)}))throw Error('unsafe fixture cleanup');for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}const file=app.vault.getFileByPath(path);if(file)await app.vault.delete(file)}return JSON.stringify({clean:true})})()`);
cleanup = result.clean;
}
assert.equal(cleanup, true);
return { id: 'native-cli-authoring', status: 'passed', assertions: ['native discovery/file input', 'stable labels, bindings and frames', 'template prose', 'collision and invalid-batch refusal', 'guarded text save/read-back', 'idempotent receipts', 'competing write BUSY', 'stale async text leaves metadata intact', 'failed save preserves recoverable edit', 'add/connect/group/ungroup/delete and frame child guard', 'live/disk SVG/PNG', 'vault image metadata round-trip', 'trusted script context/source identity/prompt refusal', 'save/reopen', 'owned fixture cleanup'], artifacts, imagePreviews };
return { id: 'native-cli-authoring', status: 'passed', assertions: ['native discovery/file input', 'stable labels, bindings and frames', 'template prose', 'collision and invalid-batch refusal', 'guarded text save/read-back', 'idempotent receipts', 'competing write BUSY', 'stale async text leaves metadata intact', 'failed save preserves recoverable edit', 'add/connect/group/ungroup/delete and frame child guard', 'live/disk SVG/PNG', 'vault image metadata round-trip', 'trusted script context/source identity/prompt refusal', 'save/reopen', 'owned fixture cleanup'], artifacts, imagePreviews, authoringExtensions, transportRecoveries: recoveries };
}
@@ -0,0 +1,18 @@
/** Recover only the exact native write receipt after lost stdout; never replay the write. */
export function createNativeCLIActions(cli) {
const recoveries = [];
const action = (command, request = {}, inputPath) => {
try {
return JSON.parse(cli(`obsidian-excalidraw-plugin:${command}`, inputPath ? `input=${inputPath}` : `json=${JSON.stringify({ apiVersion: 1, ...request })}`));
} catch (error) {
if (!request.requestId || !/\bETIMEDOUT\b/.test(error.message)) throw error;
let receipt;
try { receipt = JSON.parse(cli('obsidian-excalidraw-plugin:result', `requestId=${request.requestId}`)); }
catch { throw error; }
if (receipt.command !== command || receipt.requestId !== request.requestId || !['completed', 'failed'].includes(receipt.status)) throw error;
recoveries.push({ command, requestId: request.requestId, session: receipt.session, transportError: error.message });
return receipt;
}
};
return { action, recoveries };
}
@@ -0,0 +1,38 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createNativeCLIActions } from './nativeCLITransport.mjs';
test('native stdout timeout recovers only the exact settled receipt without replaying a write', () => {
const calls = [], receipt = { command: 'export', requestId: 'original', session: 'session', status: 'completed', ok: true };
const { action, recoveries } = createNativeCLIActions((command, flag) => {
calls.push([command, flag]);
if (command.endsWith(':export')) throw Error('spawnSync ETIMEDOUT');
return JSON.stringify(receipt);
});
assert.deepEqual(action('export', { requestId: 'original' }), receipt);
assert.equal(calls.length, 2); assert.equal(calls[1][0], 'obsidian-excalidraw-plugin:result');
assert.equal(calls[1][1], 'requestId=original');
assert.equal(recoveries.length, 1); assert.equal(recoveries[0].session, 'session');
});
test('pending, unknown and mismatched native receipts retain the original transport failure', () => {
for (const receipt of [
{ command: 'export', requestId: 'original', status: 'pending' },
{ command: 'result', requestId: 'original', status: 'failed', error: { code: 'OUTCOME_UNKNOWN' } },
{ command: 'export', requestId: 'different', status: 'completed' },
]) {
const failure = Error('spawnSync ETIMEDOUT'); let calls = 0;
const { action, recoveries } = createNativeCLIActions(() => { if (++calls === 1) throw failure; return JSON.stringify(receipt); });
assert.throws(() => action('export', { requestId: 'original' }), error => error === failure);
assert.equal(calls, 2); assert.equal(recoveries.length, 0);
}
});
test('native operation failures and unrelated transport errors are never converted into success', () => {
const receipt = { command: 'script', requestId: 'original', status: 'failed', ok: false, error: { code: 'OUTCOME_UNKNOWN' } };
let calls = 0;
const { action } = createNativeCLIActions(() => { if (++calls === 1) throw Error('ETIMEDOUT'); return JSON.stringify(receipt); });
assert.equal(action('script', { requestId: 'original' }).ok, false);
const other = Error('permission denied');
assert.throws(() => createNativeCLIActions(() => { throw other; }).action('export', { requestId: 'original' }), error => error === other);
});
+341
View File
@@ -0,0 +1,341 @@
/** Real local CJK registration and glyph-subset exports in main/popout documents. */
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { runInAppTask } from "./inAppTask.mjs";
import { behaviorEnvironment } from "./behaviorEnvironment.mjs";
import { behaviorInputDriver } from "./behaviorMatrix.mjs";
import { completeConsoleErrors } from "./debuggerSession.mjs";
import {
settleBrowserDiagnostics,
splitWindowErrors,
} from "./browserDiagnostics.mjs";
export const runtimeCompactionCaseIds = ["main", "popout"].flatMap(
(context) => [
`native:runtime-compaction:cjk:${context}`,
`native:runtime-compaction:font-subset:${context}`,
],
);
export async function runRuntimeCompactionScenario({ cli, drawingPath }) {
const root = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
const faces = JSON.parse(
readFileSync(join(root, "tests/fixtures/cjk-font-faces.json"), "utf8"),
);
const face = faces.find(({ descriptors }) =>
descriptors.unicodeRange.split(",").some((range) => {
const [start, end = start] = range
.replace("U+", "")
.split("-")
.map((value) => parseInt(value, 16));
return start <= 0x4e2d && end >= 0x4e2d;
}),
);
assert.match(face.uri, /^Xiaolai-Regular-[a-f0-9]{32}\.woff2$/);
const fork = resolve(
process.env.EXCALIDRAW_FORK_ROOT || join(root, "../excalidraw"),
);
const bytes = readFileSync(
join(fork, "packages/excalidraw/fonts/Xiaolai", face.uri),
);
const asset = {
name: face.uri,
bytes: bytes.toString("base64"),
unicodeRange: face.descriptors.unicodeRange,
};
const execute = new Function(`return async function(c,path,template,asset){
return (${exerciseRuntimeCompaction.toString()})(c,path,template,asset,
${behaviorEnvironment.toString()},${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()});
}`)();
const result = await runInAppTask({
cli,
execute,
args: [
drawingPath,
readFileSync(
join(root, "tests/vault/Drawings/Uncompressed.excalidraw.md"),
"utf8",
),
asset,
],
timeoutMs: 180000,
cleanupMs: 90000,
onRequest: behaviorInputDriver(cli),
});
assert.equal(
result.consoleErrors.flat().length,
0,
"Compaction emitted console errors",
);
assert.equal(
splitWindowErrors(result.windowErrors.flat()).unexpected.length,
0,
"Compaction emitted window errors",
);
assert.ok(
result.browserIdle.flat().every((entry) => entry.status === "passed"),
"Compaction cleanup did not settle",
);
return {
id: "runtime-compaction",
status: "passed",
...result,
consoleErrors: result.consoleErrors.flat(),
windowErrors: result.windowErrors.flat(),
browserIdle: result.browserIdle.flat(),
fontAsset: {
name: asset.name,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
},
};
}
async function exerciseRuntimeCompaction(
c,
parentPath,
template,
asset,
createEnvironment,
collectErrors,
settle,
) {
const check = (value, label) => {
if (!value) throw Error(label);
};
check(
parentPath.startsWith("__excalidraw_cli_smoke_"),
"Unowned compaction parent",
);
const runId = parentPath.match(
/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i,
)?.[0];
check(runId, "Compaction parent has no run identity");
const folder =
"__excalidraw_cli_smoke_" + runId.slice(0, 8) + "_compaction_fonts";
check(
!app.vault.getAbstractFileByPath(folder),
"Compaction font fixture collision",
);
const pluginId = "obsidian-excalidraw-plugin";
let plugin = app.plugins.plugins[pluginId];
const keys = [
"fontAssetsPath",
"loadChineseFonts",
"loadJapaneseFonts",
"loadKoreanFonts",
];
const saved = Object.fromEntries(
keys.map((key) => [
key,
{
present: Object.hasOwn(plugin.settings, key),
value: plugin.settings[key],
},
]),
);
c.defer(async () => {
const live = app.plugins.plugins[pluginId];
check(
live?.isReady,
"Live plugin unavailable for font settings restoration",
);
for (const [key, old] of Object.entries(saved)) {
if (old.present) live.settings[key] = old.value;
else delete live.settings[key];
}
await live.saveSettings();
await app.plugins.disablePlugin(pluginId);
await app.plugins.enablePlugin(pluginId);
await c.waitForCleanup(
() => app.plugins.plugins[pluginId]?.isReady,
"restore original font configuration",
);
const target = app.vault.getFolderByPath(folder);
if (target) {
check(
target.path === folder &&
target.path.startsWith("__excalidraw_cli_smoke_"),
"Refusing unowned font cleanup",
);
await app.vault.delete(target, true);
}
});
await app.vault.createFolder(folder);
const fontBytes = Uint8Array.from(atob(asset.bytes), (char) =>
char.charCodeAt(0),
);
await app.vault.createBinary(folder + "/" + asset.name, fontBytes.buffer);
Object.assign(plugin.settings, {
fontAssetsPath: folder,
loadChineseFonts: true,
loadJapaneseFonts: false,
loadKoreanFonts: false,
});
await plugin.saveSettings();
for (const leaf of app.workspace.getLeavesOfType("excalidraw")) {
if (leaf.view.excalidrawAPI && leaf.view.isDirty())
check(
(await leaf.view.saveWithOutcome()).status === "persisted",
"Save before font reload",
);
}
await app.plugins.disablePlugin(pluginId);
await app.plugins.enablePlugin(pluginId);
await c.waitFor(
() => app.plugins.plugins[pluginId]?.isReady,
"CJK configuration reload",
);
plugin = app.plugins.plugins[pluginId];
check(
plugin.getCJKFontSettings().c,
"Local CJK configuration was not enabled",
);
const consoleErrors = [],
windowErrors = [],
browserIdle = [];
for (const context of ["main", "popout"]) {
const env = await createEnvironment(
c,
parentPath,
{ id: context, input: "mouse" },
template,
collectErrors,
settle,
);
const view = await env.openDrawing("runtime-compaction");
const doc = view.ownerDocument,
win = doc.defaultView;
consoleErrors.push(c.externalConsoleErrors || []);
windowErrors.push(env.windowErrors);
browserIdle.push(env.browserIdle);
await c.case(
"native:runtime-compaction:cjk:" + context,
["P03", "P08"],
async () => {
await c.waitFor(
() => [...doc.fonts].some((face) => face.family === "Xiaolai"),
"local CJK registration in owning document",
);
// Registration remains lazy. Request the glyph before checking loaded state.
const loaded = await doc.fonts.load('28px "Xiaolai"', "中");
check(
loaded.some(
(face) => face.family === "Xiaolai" && face.status === "loaded",
),
"Local CJK font did not load on first use",
);
const reference = new win.FontFace(
"CJKCompactionReference",
fontBytes.buffer,
{ unicodeRange: asset.unicodeRange },
);
await reference.load();
doc.fonts.add(reference);
c.defer(() => {
if (!win.closed) doc.fonts.delete(reference);
});
const raster = (family) => {
const canvas = doc.createElement("canvas");
canvas.width = 80;
canvas.height = 60;
const ctx = canvas.getContext("2d");
ctx.font = '28px "' + family + '"';
ctx.fillStyle = "#123456";
ctx.fillText("中", 5, 40);
return [...ctx.getImageData(0, 0, 80, 60).data];
};
const actual = raster("Xiaolai"),
expected = raster("CJKCompactionReference");
check(
actual.some((value, index) => index % 4 === 3 && value > 0),
"Local CJK raster is blank",
);
check(
actual.every((value, index) => value === expected[index]),
"Shared-registry CJK raster differs from the source font",
);
return {
assertions: [
"local subset settings survive real reload",
"font registered in the view's owning document",
"CJK pixels exactly match the original font bytes",
],
};
},
);
await c.case(
"native:runtime-compaction:font-subset:" + context,
["P03", "P08"],
async () => {
const lib = view.packages.excalidrawLib;
const elements = lib.convertToExcalidrawElements([
{
type: "text",
text: "ABC",
fontFamily: 1,
fontSize: 28,
x: 0,
y: 0,
},
]);
await lib.loadSceneFonts(elements);
const faces = lib.Fonts.registered.get(1).fontFaces;
check(
faces.length === 1 && typeof faces[0].urls[0] === "string",
"Single-face font fixture unavailable",
);
const completeBytes = atob(faces[0].urls[0].split(",")[1]).length;
const options = {
elements,
files: {},
appState: { exportBackground: false },
exportPadding: 0,
};
const payloads = (svg) =>
[
...svg.outerHTML.matchAll(
/data:font\/woff2;base64,([A-Za-z0-9+/=]+)/g,
),
].map((match) => match[1]);
const started = performance.now(),
first = payloads(await lib.exportToSvg(options)),
firstExportMs = performance.now() - started;
check(
first.length === 1 && atob(first[0]).length < completeBytes,
"SVG did not subset the font",
);
const binary = Uint8Array.from(atob(first[0]), (char) =>
char.charCodeAt(0),
);
check(
String.fromCharCode(...binary.subarray(0, 4)) === "wOF2",
"Subset font is not WOFF2",
);
await new win.FontFace(
"SubsetCompactionReference",
binary.buffer,
).load();
const again = payloads(await lib.exportToSvg(options));
check(
JSON.stringify(first) === JSON.stringify(again),
"Repeated font export changed subset bytes",
);
return {
assertions: [
"actual WASM produces smaller embedded font",
"owner-window FontFace decodes output",
"warm export preserves exact subset bytes",
],
firstExportMs,
subsetBytes: binary.length,
completeBytes,
};
},
);
}
return { tests: c.tests, consoleErrors, windowErrors, browserIdle };
}
+255
View File
@@ -0,0 +1,255 @@
/** Focused native sidepanel placement, reuse, teardown and settings reload checks. */
import { runInAppTask } from "./inAppTask.mjs";
export const sidepanelPopoutCaseIds = [
"native:sidepanel:sidebar-default",
"native:sidepanel:popout-reuse",
"native:sidepanel:settings-reload",
"native:sidepanel:markdown-popout-focus",
"native:sidepanel:location-setting-change",
];
export async function runSidepanelPopoutScenario({ cli, drawingPath }) {
const result = await runInAppTask({
cli, execute: exerciseSidepanelPopout, args: [drawingPath], timeoutMs: 120000, cleanupMs: 60000,
});
return { id: "sidepanel-popout", status: "passed", ...result };
}
async function exerciseSidepanelPopout(c, drawingPath) {
const id = "obsidian-excalidraw-plugin", type = "excalidraw-sidepanel";
const workspace = app.workspace, doc = workspace.containerEl.ownerDocument;
const check = (condition, message) => { if (!condition) throw Error(message); };
let plugin = app.plugins.plugins[id];
check(plugin?.isReady, "Plugin is not ready");
check(workspace.getLeavesOfType(type).length === 0, "Preexisting sidepanel must remain untouched");
const markerKey = "__excalidrawSidepanelPopoutTest";
const original = Object.fromEntries(["sidepanelOpenInPopout", markerKey].map(key =>
[key, { present: Object.hasOwn(plugin.settings, key), value: plugin.settings[key] }]));
const ownedLeaves = new Set();
const windows = () => workspace.floatingSplit.children.map(win => win.id).sort().join();
const originalWindows = windows();
const closePanels = async () => {
for (const leaf of ownedLeaves) {
if (workspace.getLeavesOfType(type).includes(leaf)) leaf.detach();
}
await c.waitForCleanup(() => workspace.getLeavesOfType(type).length === 0 && windows() === originalWindows,
"sidepanel leaves and owned popouts close");
};
c.defer(async () => {
await closePanels();
if (!app.plugins.plugins[id]) await app.plugins.enablePlugin(id);
await c.waitForCleanup(() => app.plugins.plugins[id]?.isReady, "live plugin for settings restoration");
plugin = app.plugins.plugins[id];
for (const [key, saved] of Object.entries(original)) {
if (saved.present) plugin.settings[key] = saved.value;
else delete plugin.settings[key];
}
await plugin.saveSettings();
});
const open = async () => {
const panel = await plugin.openSidepanel();
check(panel, "Sidepanel did not open");
ownedLeaves.add(panel.leaf);
await c.waitFor(() => panel.containerEl.isConnected, "sidepanel DOM connects");
return panel;
};
await c.case("native:sidepanel:sidebar-default", ["P08"], async () => {
check(plugin.settings.sidepanelOpenInPopout === false, "Prepared default must be the sidebar");
const panel = await open();
check(panel.leaf.getRoot() === workspace.rightSplit, "Default sidepanel did not open in right sidebar");
check(panel.containerEl.ownerDocument === doc, "Default panel opened in another window");
await closePanels();
return { assertions: ["default opens in right sidebar", "no popout created", "close removes panel"] };
});
await c.case("native:sidepanel:popout-reuse", ["P08"], async () => {
plugin.settings.sidepanelOpenInPopout = true;
const panel = await open();
await c.waitFor(() => panel.containerEl.ownerDocument !== doc, "sidepanel reaches popout document");
const tab = await panel.createTab({ title: "Native sidepanel test" });
const input = tab.contentEl.createEl("textarea");
input.value = "Keep panel input across repeated opens";
check(input.ownerDocument === panel.containerEl.ownerDocument, "Tab belongs to wrong document");
const repeat = await plugin.openSidepanel();
check(repeat === panel && input.isConnected && input.value === "Keep panel input across repeated opens",
"Repeated opening replaced panel or tab contents");
check(workspace.getLeavesOfType(type).length === 1, "Repeated opening duplicated the sidepanel");
plugin.settings.sidepanelOpenInPopout = false;
check(await plugin.openSidepanel() === panel, "Preference change replaced a live panel");
await closePanels();
check(!input.isConnected, "Closed popout retained tab DOM");
const sidebar = await open();
check(sidebar.leaf.getRoot() === workspace.rightSplit, "Reopen did not apply changed preference");
await closePanels();
return { assertions: ["new panel in popout document", "tabs use popout document", "singleton preserves input", "close cleans up", "next open applies preference"] };
});
await c.case("native:sidepanel:settings-reload", ["P01", "P08"], async () => {
const marker = { zero: 0, enabled: false, nested: { retained: true } };
// The settings writer sorts object keys; assert values independent of key order.
const hasMarker = value => value?.zero === 0 && value?.enabled === false && value?.nested?.retained === true;
plugin.settings.sidepanelOpenInPopout = true;
plugin.settings[markerKey] = marker;
await plugin.saveSettings();
const settingsPath = app.vault.configDir + "/plugins/" + id + "/data.json";
const persisted = JSON.parse(await app.vault.adapter.read(settingsPath));
c.observations ??= {};
c.observations.sidepanelSettings = { persistedPreference: persisted.sidepanelOpenInPopout, persistedMarker: persisted[markerKey] };
check(persisted.sidepanelOpenInPopout === true && hasMarker(persisted[markerKey]),
"Non-default preference or unknown settings missing from disk");
const previous = plugin;
await app.plugins.disablePlugin(id);
await app.plugins.enablePlugin(id);
await c.waitFor(() => app.plugins.plugins[id]?.isReady, "replacement plugin startup");
plugin = app.plugins.plugins[id];
check(plugin !== previous && plugin.settings.sidepanelOpenInPopout === true, "Reload lost popout preference");
check(hasMarker(plugin.settings[markerKey]), "Reload lost unknown settings");
const loadedDisk = JSON.parse(await app.vault.adapter.read(settingsPath));
check(loadedDisk.sidepanelOpenInPopout === true && hasMarker(loadedDisk[markerKey]),
"Startup changed persisted preferences");
const panel = await open();
await c.waitFor(() => panel.containerEl.ownerDocument !== doc, "reloaded preference opens popout");
await closePanels();
return { assertions: ["non-default setting and unknown keys persisted", "new plugin loads them at startup", "disk preserved", "reloaded preference opens popout"] };
});
await c.case("native:sidepanel:location-setting-change", ["P08"], async () => {
plugin.settings.sidepanelOpenInPopout = false;
const sibling = workspace.getRightLeaf(false);
const siblingId = sibling.id;
c.defer(() => workspace.getLeafById(siblingId)?.detach());
await sibling.setViewState({ type: "backlink", active: false });
const panel = await open(), panelLeaf = panel.leaf;
const tab = await panel.createTab({ title: "Keep script input while moving" });
const input = tab.contentEl.createEl("textarea");
input.value = "Unsaved script panel content";
const settingsTab = plugin.settingsTab;
const change = async (value, legacy = false) => {
if (legacy) {
const spec = settingsTab.getUIModeSpecs().find(spec => spec.control.key === "sidepanelOpenInPopout");
await settingsTab.settingBindings.setLegacySpecValue(spec, value);
await plugin.saveSettings();
} else {
settingsTab.getSettingDefinitions();
await settingsTab.setControlValue("sidepanelOpenInPopout", value);
}
};
const inPopout = expected => c.waitFor(() =>
(panel.containerEl.ownerDocument !== doc) === expected && panelLeaf.view === panel,
expected ? "existing panel moves to popout" : "existing panel returns to sidebar");
const dock = workspace.rightSplit;
const sidebarTabs = panelLeaf.parent;
const originalGroups = [...dock.children];
for (const legacy of [false, true]) {
dock.collapse();
await change(true, legacy);
check(dock.collapsed && windows() === originalWindows && panelLeaf.getRoot() === dock,
"Editing settings opened a window or expanded the sidebar");
check(await plugin.openSidepanel(false) === panel && windows() === originalWindows,
"A background panel lookup consumed the pending popout");
tab.reveal();
await inPopout(true);
check(tab.contentEl.isConnected && input.value === "Unsaved script panel content", "Move replaced script input");
await change(false, legacy); await inPopout(false);
check(dock.collapsed, "Docking expanded the sidebar");
await c.waitFor(() => windows() === originalWindows, "old popout closes after docking");
check(panelLeaf.parent === sidebarTabs && sibling.parent === sidebarTabs &&
sidebarTabs.children.includes(sibling) && sidebarTabs.children.includes(panelLeaf) &&
dock.children.length === originalGroups.length && originalGroups.every((group, i) => dock.children[i] === group),
"Docking stacked a group instead of adding a sibling tab");
}
await change(true);
await change(false);
check(await open() === panel && windows() === originalWindows, "Disabling did not cancel a queued popout");
// Manual detach while the preference says sidebar must survive later opens
// and same-value writes. Only the next actual preference change moves it.
workspace.moveLeafToPopout(panelLeaf); await inPopout(true);
check(await plugin.openSidepanel() === panel, "Manual popout was replaced");
await change(false); await inPopout(true);
await change(true); await change(false); await inPopout(false);
await change(true); await open(); await inPopout(true);
const placeholder = workspace.getRightLeaf(false), destination = placeholder.parent;
panelLeaf.parent.removeChild(panelLeaf); panelLeaf.setDimension(null);
destination.insertChild(-1, panelLeaf); placeholder.detach();
await workspace.revealLeaf(panelLeaf); await inPopout(false);
check(await plugin.openSidepanel() === panel, "Manual docking was replaced");
await change(true); await inPopout(false);
check(input.isConnected && input.value === "Unsaved script panel content" && workspace.getLeavesOfType(type).length === 1,
"Setting changes replaced tabs or duplicated the panel");
await closePanels();
// Reload a saved collapsed layout with a deferred Excalidraw sidebar tab.
// Use the host layout restore path so the leaf is genuinely deferred.
plugin.settings.sidepanelOpenInPopout = false;
await workspace.revealLeaf(sibling);
dock.collapse();
const restorable = await plugin.openSidepanel(false);
check(restorable, "Could not stage a sidebar panel for layout restoration");
ownedLeaves.add(restorable.leaf);
const layout = workspace.getLayout();
await closePanels();
await workspace.changeLayout(layout);
const deferredLeaf = workspace.getLeavesOfType(type)[0];
if (deferredLeaf) ownedLeaves.add(deferredLeaf);
check(deferredLeaf?.isDeferred && workspace.rightSplit.collapsed, "Restored panel was not deferred in the collapsed sidebar");
await change(true);
check(deferredLeaf.isDeferred && windows() === originalWindows, "Changing settings loaded or moved the deferred panel");
const restoredPanel = await open();
check(restoredPanel.leaf === deferredLeaf && !deferredLeaf.isDeferred, "Reveal did not load the original deferred panel");
await c.waitFor(() => restoredPanel.containerEl.ownerDocument !== doc, "deferred panel reaches popout on first reveal");
await closePanels();
workspace.getLeafById(siblingId)?.detach();
return { assertions: ["both settings adapters defer popout until reveal", "docking preserves collapsed sidebar and sibling tabs", "same view and script input survive", "manual moves and cancellation are respected", "restored deferred panel moves on its first reveal"] };
});
await c.case("native:sidepanel:markdown-popout-focus", ["P05", "P08"], async () => {
plugin.settings.sidepanelOpenInPopout = true;
const leaf = workspace.getLeavesOfType("excalidraw").find(leaf => leaf.view.file?.path === drawingPath);
check(leaf, "Owned test drawing is unavailable after reload");
await c.waitFor(() => leaf.view.excalidrawAPI && leaf.view.isLoaded && !leaf.view.semaphores.justLoaded,
"drawing ready for Markdown insertion");
const view = leaf.view, api = view.excalidrawAPI;
workspace.setActiveLeaf(leaf, { focus: true });
doc.defaultView.focus();
api.updateScene({ appState: { selectedElementIds: {} }, captureUpdate: "NEVER" });
const before = new Set(api.getSceneElements().map(element => element.id));
// Invoke the actual context-menu action, including its normal onClose callback.
const menu = view.onContextMenu(api.getSceneElements(), api.getAppState(), callback => callback?.());
const findAction = node => {
if (!node) return null;
if (Array.isArray(node)) return node.map(findAction).find(Boolean);
if (node.props?.["data-testid"] === "insertMarkdownImage") return node;
return findAction(node.props?.children);
};
const action = findAction(menu);
check(action, "Insert editable Markdown image context-menu action is missing");
action.props.onClick();
await c.waitFor(() => workspace.getLeavesOfType(type).length === 1, "Markdown popout created");
const panelLeaf = workspace.getLeavesOfType(type)[0];
ownedLeaves.add(panelLeaf);
const panel = panelLeaf.view;
await c.waitFor(() => panel.containerEl.ownerDocument !== doc &&
panel.containerEl.querySelector(".excalidraw-markdown-image-editor__markdown-view .cm-content"),
"Markdown editor mounted in popout");
await c.waitFor(() => api.getSceneElements().some(element => !before.has(element.id) && element.type === "image"),
"editable Markdown image inserted");
await new Promise(resolve => window.setTimeout(resolve, 900));
const panelDoc = panel.containerEl.ownerDocument;
const remote = doc.defaultView.require("@electron/remote");
const popout = remote.BrowserWindow.getAllWindows().find(win => win.webContents.id ===
panelDoc.defaultView.require("@electron/remote").getCurrentWebContents().id);
const editor = workspace.activeEditor;
c.observations ??= {};
c.observations.markdownPopoutFocus = {
focusedWindow: remote.BrowserWindow.getFocusedWindow()?.id, popout: popout?.id,
documentFocused: panelDoc.hasFocus(), activeEditorInPopout: editor?.containerEl?.ownerDocument === panelDoc,
editorContainerInPopout: editor?.leaf?.getContainer()?.doc === panelDoc,
activeElement: panelDoc.activeElement?.className,
};
check(popout?.isFocused() && panelDoc.hasFocus(), "Markdown insertion brought the main window in front of its popout");
check(panel.containerEl.querySelector(".cm-content")?.contains(panelDoc.activeElement), "Markdown editor did not retain keyboard focus");
const sourceSection = panel.containerEl.querySelector(".excalidraw-markdown-image-editor__source");
check(Number.parseFloat(panelDoc.defaultView.getComputedStyle(sourceSection).paddingTop) >= 8,
"Markdown extraction section lacks top padding");
await closePanels();
await c.waitForCleanup(() => !view.isSameFileEditingActive() && !view.isPersistenceBusy(), "Markdown editor flush settles");
return { assertions: ["actual context-menu action inserts editable image", "popout remains foreground after insertion", "editor retains keyboard focus", "close flushes editor"] };
});
return { tests: c.tests };
}
+12
View File
@@ -26,6 +26,7 @@ import { runSvgPaintScenario } from "./svgPaint.mjs";
import { runSvgTextScenario } from "./svgText.mjs";
import { runSVGEntryPointsScenario } from "./svgEntryPoints.mjs";
import { runLucideScenario } from "./lucideIcons.mjs";
import { runVisualResourcesScenario } from "./visualResources.mjs";
import { runWorkflowFixesScenario } from "./workflowFixes.mjs";
import { runWorkflowBundleScenario } from "./workflowBundle.mjs";
import { runAIAndEmbedsScenario } from "./aiAndEmbeds.mjs";
@@ -42,6 +43,8 @@ import { runExtrasServicesScenario } from "./extrasServices.mjs";
import { runStabilityScenario } from "./stability.mjs";
import { runAutomateScenario } from "./automate.mjs";
import { runCoreInteractionScenario } from "./coreInteraction.mjs";
import { runRuntimeCompactionScenario } from "./runtimeCompaction.mjs";
import { runSidepanelPopoutScenario } from "./sidepanelPopout.mjs";
import { runPDFImportScenario } from "./pdfImport.mjs";
import { runDeviceMatrix } from "./devices.mjs";
import { deviceProfiles, breakpointProfiles } from "./deviceProfiles.mjs";
@@ -79,6 +82,8 @@ if (
const fullProfile = profile === "full" || profile === "regression";
const coreOnly=process.argv.includes("--core"),coreScenarios=fullProfile||coreOnly;
const lifecycle = coreScenarios || process.argv.includes("--lifecycle");
const runtimeCompaction = coreScenarios || process.argv.includes("--runtime-compaction");
const sidepanelPopout = coreScenarios || process.argv.includes("--sidepanel-popout");
const migrationComparison = process.argv.includes("--migration-comparison");
const markdownMigrationControl = process.argv.includes("--markdown-migration-control");
if (fullProfile && migrationComparison)
@@ -114,6 +119,7 @@ const svgPaint = process.argv.includes("--svg-paint");
const svgText = process.argv.includes("--svg-text");
const svgEntryPoints = process.argv.includes("--svg-entry-points");
const lucide = coreScenarios || process.argv.includes("--lucide");
const visualResources = coreScenarios || process.argv.includes("--visual-resources");
const workflowFixes = coreScenarios || process.argv.includes("--workflow-fixes");
const workflowBundle = coreScenarios || process.argv.includes("--workflow-bundle");
const aiAndEmbeds = coreScenarios || process.argv.includes("--ai-and-embeds");
@@ -158,6 +164,8 @@ const flags = [
"--prepare-only",
"--behavior-matrix",
"--lifecycle",
"--runtime-compaction",
"--sidepanel-popout",
"--migration-comparison",
"--markdown-migration-control",
"--extras-services",
@@ -171,6 +179,7 @@ const flags = [
"--code-cards",
"--kplex-ontology",
"--lucide",
"--visual-resources",
"--text-undo",
"--stability",
"--native-cli",
@@ -331,6 +340,9 @@ try {
}),
]
: []),
...(runtimeCompaction ? [runRuntimeCompactionScenario] : []),
...(sidepanelPopout ? [runSidepanelPopoutScenario] : []),
...(visualResources ? [runVisualResourcesScenario] : []),
...(lifecycle ? [runLifecycleScenario] : []),
...(migrationComparison ? [
context => runLifecycleScenario(context),
+967
View File
@@ -0,0 +1,967 @@
/** Native Visual Resources gestures, curation, and blank-drawing framework workflow. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { runInAppTask } from "./inAppTask.mjs";
import { behaviorInputDriver } from "./behaviorMatrix.mjs";
export const visualResourceCaseIds = [
"native:visual-resources:palette-and-insertion",
"native:visual-resources:panel-controls",
"native:visual-resources:stencils",
"native:visual-resources:svg-strokes-and-curation",
"native:visual-resources:document-targets-and-preview-budget",
"native:visual-resources:popout-drop",
"native:visual-resources:framework-picker",
"native:visual-resources:reload",
];
export async function runVisualResourcesScenario({ cli, drawingPath, reportDir }) {
const library = JSON.parse(readFileSync(new URL("../../../visual-frameworks/thinking-frameworks.excalidrawlib", import.meta.url), "utf8"));
library.libraryItems = library.libraryItems.slice(0, 1);
const input = behaviorInputDriver(cli);
const result = await runInAppTask({ cli, execute: exercise, args: [drawingPath, library], timeoutMs: 150000, cleanupMs: 60000,
onRequest: request => {
if (request.method !== "resource-settings-screenshot") return input(request);
cli("dev:screenshot", "path=" + join(reportDir, "visual-resource-settings.png"));
return { captured: true };
},
onProgress: phase => { if (phase) process.stdout.write("Visual Resources: " + phase + "\n"); } });
assert.deepEqual(result.tests.map(test => test.testId), visualResourceCaseIds);
return { id: "visual-resources-3074", status: "passed", ...result };
}
async function exercise(c, drawingPath, library) {
const id = "obsidian-excalidraw-plugin";
let plugin = app.plugins.plugins[id];
const workspace = app.workspace, vault = app.vault;
c.observations = {};
const root = drawingPath.replace(/\.(excalidraw\.md|excalidraw|md)$/, "") + "_visual_resources";
const check = (value, detail) => { if (!value) throw Error(detail); };
const runCase = (testId, action) => {
c.phase = testId;
return c.case(testId, ["P08"], action);
};
check(root.startsWith("__excalidraw_cli_smoke_") && !vault.getAbstractFileByPath(root), "Unowned visual resources fixture root");
const saved = {};
for (const key of ["folder", "visualResources", "frameworkFolder", "frameworksOnBlank", "frameworksSnoozedUntil", "sidepanelOpenInPopout", "showNewVersionNotification", "templateFilePath", "libraryFolderPath", "libraryStorageMode", "libraryMigrationStatus"]) {
saved[key] = plugin.settings[key];
}
c.defer(async () => {
if (!app.plugins.plugins[id]) await app.plugins.enablePlugin(id);
await c.waitForCleanup(() => app.plugins.plugins[id]?.isReady, "plugin ready for settings restoration");
plugin = app.plugins.plugins[id];
plugin.visualResourcePanel.tab?.close();
for (const leaf of workspace.getLeavesOfType("excalidraw-sidepanel")) leaf.detach();
for (const leaf of workspace.getLeavesOfType("excalidraw").filter(leaf => leaf.view.file?.path.startsWith(root + "/"))) {
await leaf.setViewState({ type: "empty", state: {} });
leaf.detach();
}
Object.assign(plugin.settings, saved);
plugin.stencilLibraryManager.invalidate();
await plugin.saveSettings();
const folder = vault.getFolderByPath(root);
if (folder) await vault.delete(folder, true);
});
await vault.createFolder(root);
const frameworkFolder = root + "/Frameworks";
await vault.createFolder(frameworkFolder);
const svg = await vault.create(root + "/icon - Resource probe.svg", '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 32"><rect width="64" height="32" fill="#22aa66"/></svg>');
await vault.create(frameworkFolder + "/Probe.excalidrawlib", JSON.stringify(library));
Object.assign(plugin.settings, { folder: root, frameworkFolder, templateFilePath: "",
frameworksOnBlank: true, frameworksSnoozedUntil: 0, sidepanelOpenInPopout: false,
showNewVersionNotification: false, visualResources: { filters: ["icon", "lucide", "image", "drawing", "framework"] } });
await plugin.saveSettings();
const drawingData = await vault.read(vault.getFileByPath(drawingPath));
const ownedDrawing = await plugin.createAndOpenDrawing("Visual Resource probe.excalidraw.md", "new-tab", root, drawingData);
let leaf;
await c.waitFor(() => (leaf = workspace.getLeavesOfType("excalidraw").find(leaf => leaf.view.file?.path === ownedDrawing))?.view.excalidrawAPI?.id,
"owned drawing initialized");
const view = leaf?.view, api = view?.excalidrawAPI;
check(api, "Native probe drawing is not ready");
workspace.setActiveLeaf(leaf, { focus: true });
let panel;
const search = query => {
const input = panel.querySelector("input[type=search]");
input.value = query;
input.dispatchEvent(new (input.ownerDocument.defaultView.Event)("input", { bubbles: true }));
};
const card = () => [...panel.querySelectorAll(".excalidraw-resource-body")]
.find(button => button.getAttribute("aria-label") === "Resource probe");
const count = () => api.getSceneElements().length;
const locator = { provider: "vault", path: svg.path };
let persistedThumbnail;
let persistedFrame;
await runCase("native:visual-resources:palette-and-insertion", async () => {
const indexedResources = await plugin.visualResources.list();
const indexed = indexedResources.find(resource => resource.source === svg.path);
check(indexed?.kind === "icon", "Vault icon is absent from discovery results");
const initial = count();
check(app.commands.executeCommandById(id + ":visual-resources"), "Browser command was unavailable");
await c.waitFor(() => (panel = workspace.getLeavesOfType("excalidraw-sidepanel")[0]?.view.containerEl.querySelector(".excalidraw-resource-browser")), "browser mounted");
search("Resource probe");
await c.waitFor(() => {
c.observations.browser = { status: panel.querySelector(".excalidraw-resource-status")?.textContent,
search: panel.querySelector("input[type=search]")?.value, rendered: !!card() };
return card();
}, "configured vault icon searchable");
const win = panel.ownerDocument.defaultView;
const doc = panel.ownerDocument;
const contentsId = win.require("@electron/remote").getCurrentWebContents().id;
const nativeMouse = params => c.requestHost("behavior-input", { contentsId, method: "Input.dispatchMouseEvent", params });
const away = { type: "mouseMoved", x: win.innerWidth - 5, y: win.innerHeight - 5, buttons: 0 };
const modifier = win.navigator.platform.startsWith("Mac") ? 4 : 2;
const activePopover = () => [...doc.querySelectorAll(".hover-popover")].find(el => el.getClientRects().length);
const events = [];
const ref = workspace.on("hover-link", event => {
if (event.source === "excalidraw-visual-resources") events.push(event.linktext);
});
const hover = async (find, modifiers) => {
let position;
await c.waitFor(() => {
const target = find();
if (!target) return false;
const rect = target.getBoundingClientRect();
position = { x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 3) };
return target.contains(doc.elementFromPoint(position.x, position.y));
}, "uncovered resource card for native Page Preview");
await nativeMouse([away, { type: "mouseMoved", ...position, buttons: 0, modifiers }]);
};
try {
await hover(card, 0);
await new Promise(resolve => win.setTimeout(resolve, 650));
check(!activePopover(), "Resource Page Preview appeared without the default modifier");
await hover(card, modifier);
await c.waitFor(() => activePopover()?.querySelector("img")?.naturalWidth, "native hover preview renders the vault SVG");
check(events.at(-1) === svg.path, "The vault icon hover targeted the wrong file");
await nativeMouse(away);
await c.waitFor(() => !activePopover(), "the vault icon preview closes after the pointer leaves");
const drawing = indexedResources.find(resource => resource.source === view.file.path);
const namedCard = title => [...panel.querySelectorAll(".excalidraw-resource-body")]
.find(element => element.getAttribute("aria-label") === title);
search(drawing.title);
await hover(() => namedCard(drawing.title), modifier);
await c.waitFor(() => activePopover(), "native hover preview opens for an Excalidraw file");
check(events.at(-1) === view.file.path, "Drawing hover targeted the wrong file");
await nativeMouse(away);
await c.waitFor(() => !activePopover(), "the drawing preview closes after the pointer leaves");
const lucide = indexedResources.find(resource => resource.locator.provider === "lucide");
search(lucide.title);
const countBeforeHover = events.length;
await hover(() => namedCard(lucide.title), modifier);
await new Promise(resolve => win.setTimeout(resolve, 650));
check(events.length === countBeforeHover && !activePopover(), "Lucide should not open a file preview");
} finally {
workspace.offref(ref);
await nativeMouse(away);
}
search("Resource probe");
await c.waitFor(card, "icon available after Page Preview");
card().dispatchEvent(new win.MouseEvent("click", { bubbles: true, detail: 1 }));
card().dispatchEvent(new win.MouseEvent("click", { bubbles: true, detail: 2 }));
card().dispatchEvent(new win.MouseEvent("dblclick", { bubbles: true, detail: 2 }));
await c.waitFor(() => workspace.getLeavesOfType("image").some(leaf => leaf.view.file?.path === svg.path), "double click opens source");
await new Promise(resolve => win.setTimeout(resolve, 525));
check(count() === initial, "Double click inserted before opening");
const opened = workspace.getLeavesOfType("image").find(leaf => leaf.view.file?.path === svg.path);
opened.detach();
workspace.setActiveLeaf(leaf, { focus: true });
await plugin.visualResourcePanel.open(view);
search("Resource probe");
await c.waitFor(() => card()?.getAttribute("aria-disabled") === null, "drawing ready after source open");
card().dispatchEvent(new win.MouseEvent("click", { bubbles: true, detail: 1 }));
await plugin.visualResourcePanel.open(null);
await new Promise(resolve => win.setTimeout(resolve, 525));
check(count() === initial, "A delayed click published after the target changed");
await plugin.visualResourcePanel.open(view, "Icon Library");
check(workspace.getLeavesOfType("excalidraw-sidepanel").length === 1, "Icon preset duplicated the sidepanel");
check(plugin.settings.visualResources.filters.includes("lucide"), "Icon preset replaced general filters");
search("Resource probe");
await c.waitFor(() => card()?.getAttribute("aria-disabled") !== "true" && card()?.textContent.includes("Resource probe"), "icon preset is ready for insertion");
card().click();
await c.waitFor(() => count() === initial + 1, "single click inserted one linked image");
const image = api.getSceneElements().find(element => element.type === "image");
check(image && image.width === 180, "Vault icon did not keep the existing width");
return { assertions: ["vault icon discovered and rendered", "native modifier hover previews vault SVG and drawing, and skips Lucide", "double-click opens without inserting",
"changing target cancels pending insertion", "one panel serves both presets", "linked icon keeps its configured width"],
linkedImage: image.id, samePanel: true, doubleClickInsertions: 0 };
});
await runCase("native:visual-resources:panel-controls", async () => {
const doc = panel.ownerDocument, win = doc.defaultView;
const preferences = structuredClone(plugin.settings.visualResources);
const controller = plugin.visualResourcePanel;
const showMenu = controller.show;
controller.show = function(menu, ...args) { return showMenu.call(this, menu.setUseNativeMenu(false), ...args); };
c.defer(() => { controller.show = showMenu; });
const trigger = view.containerEl.querySelector(".excalidraw-visual-resources-trigger");
check(trigger, "Canvas toolbar is missing the Visual Resources action");
const adjacent = trigger.previousElementSibling;
check(win.getComputedStyle(trigger).backgroundColor === win.getComputedStyle(adjacent).backgroundColor,
"The shapes button paints different button chrome from Insert Any File");
check(trigger.getBoundingClientRect().height === adjacent.getBoundingClientRect().height,
"The shapes button uses different toolbar sizing");
trigger.click();
await c.waitFor(() => !controller.script, "canvas action opens general resources");
const query = panel.querySelector("input[type=search]");
const toolbarButton = key => [...panel.querySelectorAll(".excalidraw-resource-search-tools button")]
.find(button => button.getAttribute("aria-label") === plugin.getLabel(key));
const filter = toolbarButton("VR_FILTER");
const toolbarLabels = [...panel.querySelectorAll(".excalidraw-resource-search-tools button")].map(button => button.getAttribute("aria-label"));
check(toolbarLabels.join("|") === ["VR_FILTER", "VR_COLLECTIONS", "VR_SELECT", "VR_LAYOUT", "VR_SETTINGS", "VR_POPOUT"]
.map(key => plugin.getLabel(key)).join("|"), "Toolbar actions are out of order or still include the help button");
const originalWidth = panel.style.width;
try {
panel.style.width = "720px";
check(filter.getBoundingClientRect().top < query.getBoundingClientRect().bottom, "The wide toolbar wraps below search");
panel.style.width = "285px";
check(filter.getBoundingClientRect().top >= query.getBoundingClientRect().bottom, "The narrow toolbar does not wrap below search");
} finally { panel.style.width = originalWidth; }
const menuAction = async key => {
let item;
await c.waitFor(() => (item = [...doc.querySelectorAll(".menu-item-title")]
.find(el => el.textContent === plugin.getLabel(key))), "rendered menu action " + key);
item.closest(".menu-item").click();
};
const filterOption = key => panel.querySelector('.excalidraw-resource-filter-popover [data-filter="' + key + '"]');
const groups = JSON.stringify(plugin.settings.visualResources.groups);
filter.click();
await c.waitFor(() => filterOption("none"), "filter popover opens");
filterOption("none").click();
check(!plugin.settings.visualResources.filters.length && JSON.stringify(plugin.settings.visualResources.groups) === groups,
"Select none changed discovery groups or left resource types enabled");
check(!panel.querySelector(".excalidraw-resource-card"), "Select none left visible results");
check(filter.getAttribute("aria-expanded") === "true" && !filterOption("has-named-frames") &&
!panel.querySelector(".excalidraw-resource-filter-section"), "Disabling resource types closed the popover or left fine filters visible");
filterOption("all").click();
check(plugin.settings.visualResources.filters.includes("other") && JSON.stringify(plugin.settings.visualResources.groups) === groups,
"Select all changed discovery groups or skipped a resource type");
check(filter.getAttribute("aria-expanded") === "true" && filterOption("has-named-frames").parentElement.textContent.includes("2.29.4"),
"The drawing facet was missing its requirement, or the popover closed after editing");
filterOption("done").click();
toolbarButton("VR_SETTINGS").click();
let settings;
await c.waitFor(() => (settings = doc.querySelector(".excalidraw-resource-settings-modal")), "settings opens the compact editor");
const grids = settings.querySelector(".excalidraw-resource-settings-card .excalidraw-resource-settings-grid");
const ruleName = () => settings.querySelector(".excalidraw-resource-settings-card-header input");
check(settings.querySelectorAll(".excalidraw-resource-settings-card").length === 1 &&
win.getComputedStyle(grids).gridTemplateColumns.split(" ").length === 2 &&
settings.querySelectorAll('input[type="color"]').length === 2,
"Settings did not show one paged rule, a two-column card, and color swatches");
const firstRule = ruleName().value;
settings.querySelector(".excalidraw-resource-settings-pager button:last-child").click();
check(ruleName().value !== firstRule, "Rule navigation did not change the editable card");
settings.querySelector(".excalidraw-resource-settings-pager button:first-child").click();
await c.requestHost("resource-settings-screenshot", {});
const closeSettings = settings.querySelector(".modal-close-button, .modal-header-button");
if (closeSettings) closeSettings.click();
else await c.requestHost("behavior-input", {
contentsId: win.require("@electron/remote").getCurrentWebContents().id,
method: "Input.dispatchKeyEvent",
params: [{ type: "keyDown", key: "Escape", code: "Escape" }, { type: "keyUp", key: "Escape", code: "Escape" }],
});
await c.waitFor(() => !settings.isConnected, "settings dismissal completes");
search("Resource probe");
await c.waitFor(card, "resource visible after Select all");
const before = count();
toolbarButton("VR_SELECT").click();
const checkbox = [...panel.querySelectorAll("input.excalidraw-resource-checkbox")]
.find(input => input.getAttribute("aria-label") === "Resource probe");
const selectionBar = panel.querySelector(".excalidraw-resource-selection");
const selectedActions = selectionBar.querySelector("button");
check(checkbox && !checkbox.checked && selectedActions.disabled, "Selection mode omitted checkboxes or initial state");
checkbox.focus();
checkbox.click();
check(checkbox.isConnected && checkbox.checked && doc.activeElement === checkbox && !selectedActions.disabled,
"Toggling a checkbox removed focus or failed to enable bulk actions");
check(selectionBar.textContent.includes(plugin.getLabel("VR_SELECTION_COUNT").replace("{COUNT}", "1")),
"Selection count did not update");
selectedActions.click();
await menuAction("VR_FAVORITE");
await c.waitFor(() => plugin.visualResources.collections.state(locator).favorite, "bulk favorite applied without an existing playlist");
await plugin.visualResources.collections.curate([locator], { favorite: false });
await c.waitFor(() => !plugin.visualResources.collections.state(locator).favorite, "test favorite cleared");
checkbox.dispatchEvent(new win.KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
check(!panel.querySelector(".excalidraw-resource-checkbox") && card() && count() === before,
"Exiting selection mode changed the scene or left selection controls");
await vault.create(root + "/icon - Resource probe second.svg", '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8"/></svg>');
const actions = () => card().closest(".excalidraw-resource-card").querySelector(".excalidraw-resource-actions button:last-child");
const isBusy = view.isPersistenceBusy;
let busy = true;
view.isPersistenceBusy = () => busy || isBusy.call(view);
try {
actions().click();
await menuAction("VR_INSERT_SVG");
check(count() === before, "Insertion published before its target finished saving");
busy = false;
await c.waitFor(() => count() === before + 1, "insertion requested during save publishes without canvas refocus");
api.history.undo();
await c.waitFor(() => count() === before, "one undo removes the single insertion");
} finally { view.isPersistenceBusy = isBusy; }
toolbarButton("VR_SELECT").click();
const bulkFixtures = new Set(["Resource probe", "Resource probe second"]);
const bulkInputs = () => [...panel.querySelectorAll(".excalidraw-resource-checkbox")]
.filter(input => bulkFixtures.has(input.getAttribute("aria-label")));
await c.waitFor(() => bulkInputs().length === bulkFixtures.size, "both bulk insert resources are listed");
for (const input of bulkInputs()) input.click();
selectedActions.click();
await menuAction("VR_INSERT_SELECTED");
await c.waitFor(() => count() === before + 2, "bulk insertion publishes both SVGs");
api.history.undo();
await c.waitFor(() => count() === before, "a single undo removes the bulk insertion");
toolbarButton("VR_EXIT_SELECTION").click();
const ea = plugin.ea.getAPI(view);
try {
const frameId = ea.addFrame(480, 310, 230, 160, "Divider test frame");
ea.addElementsToFrame(frameId, [ea.addRect(500, 340, 55, 43)]);
ea.addFrame(760, 310, 180, 160, "Second frame");
ea.addFrame(980, 310, 180, 160, "Third frame");
check(await ea.addElementsToView(false, true, true), "Could not save the owned frame fixture");
} finally { ea.destroy(); }
search("Divider test frame");
let framesButton;
await c.waitFor(() => (framesButton = [...panel.querySelectorAll(".excalidraw-resource-actions button")]
.find(button => button.getAttribute("aria-label") === plugin.getLabel("VR_BROWSE_FRAMES") + " (3)" &&
!button.classList.contains("excalidraw-display-none"))), "named-frame count in search results");
framesButton.click();
const divider = panel.querySelector(".excalidraw-resource-divider");
const galleryPane = panel.querySelector(".excalidraw-resource-main");
const framePane = panel.querySelector(".excalidraw-resource-frames");
await c.waitFor(() => framePane.querySelector(".excalidraw-resource-body")?.textContent.includes("Divider test frame"),
"frame selector with a visible split divider");
check(framePane.querySelectorAll(".excalidraw-resource-body").length === 3, "The master query hid other frames from the selected drawing");
const selectedCard = framesButton.closest(".excalidraw-resource-card");
check(selectedCard.classList.contains("is-frame-source") && win.getComputedStyle(selectedCard).outlineWidth === "2px" &&
framesButton.getAttribute("aria-pressed") === "true", "The drawing with an open frame pane did not get an accent outline");
framesButton.click();
check(!selectedCard.classList.contains("is-frame-source"), "The drawing kept its accent outline after closing its frames");
framesButton.click();
await c.waitFor(() => framePane.querySelectorAll(".excalidraw-resource-body").length === 3, "highlighted drawing reopens its frames");
let x, y;
await c.waitFor(() => {
const start = divider.getBoundingClientRect();
x = Math.round(start.left + start.width / 2);
y = Math.round(start.top + start.height / 2);
const hit = doc.elementFromPoint(x, y);
c.observations.frameDivider = { x, y, hit: hit?.className, bounds: start.toJSON(),
gallery: galleryPane.getBoundingClientRect().height, frames: framePane.getBoundingClientRect().height,
ratio: win.devicePixelRatio, scale: win.visualViewport?.scale, events: [] };
return hit === divider;
}, "frame divider is unobstructed");
const beforeHeight = galleryPane.getBoundingClientRect().height;
const contentsId = win.require("@electron/remote").getCurrentWebContents().id;
const record = event => c.observations.frameDivider.events.push({ type: event.type, x: event.clientX, y: event.clientY,
target: event.target.className?.baseVal ?? event.target.className, trusted: event.isTrusted });
for (const type of ["pointerdown", "pointermove", "pointerup"]) doc.addEventListener(type, record, true);
try {
await c.requestHost("behavior-input", { contentsId, method: "Input.dispatchMouseEvent", params: [
{ type: "mouseMoved", x, y, button: "none", buttons: 0 },
{ type: "mousePressed", x, y, button: "left", buttons: 1, clickCount: 1 },
{ type: "mouseMoved", x, y: y - 45, button: "left", buttons: 1 },
{ type: "mouseReleased", x, y: y - 45, button: "left", buttons: 0, clickCount: 1 },
] });
c.observations.frameDivider.after = { height: galleryPane.getBoundingClientRect().height, split: divider.getAttribute("aria-valuenow") };
} finally {
for (const type of ["pointerdown", "pointermove", "pointerup"]) doc.removeEventListener(type, record, true);
}
await c.waitFor(() => galleryPane.getBoundingClientRect().height < beforeHeight - 12, "pointer drag grows the frame pane");
const afterPointer = Number(divider.getAttribute("aria-valuenow"));
divider.dispatchEvent(new win.KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true, cancelable: true }));
check(Number(divider.getAttribute("aria-valuenow")) > afterPointer, "Divider keyboard input did not resize the panes");
check(query.value === "Divider test frame" && framePane.querySelector(".excalidraw-resource-body"),
"Resizing dropped search or frame context");
search("second.svg");
check(!framesButton.isConnected && galleryPane.querySelector('[aria-label="Resource probe second"]'),
"A search for the unrelated SVG did not replace the selected drawing in the gallery");
check(divider.classList.contains("excalidraw-display-none") && !framePane.querySelector(".excalidraw-resource-body"),
"Leaving the selected drawing outside the search results left its frames visible");
controller.show = showMenu;
plugin.settings.visualResources = preferences;
await plugin.saveSettings();
return { assertions: ["canvas button uses neighboring toolbar styling", "toolbar shares the search row at wide widths and wraps when narrow",
"bulk filter actions change resource types and preserve their fine filters",
"bulk favorite works without a playlist, and selection preserves the scene",
"settings uses a paged compact editor and both background swatches",
"context insertion remains available while the drawing saves, and bulk insertion has one undo",
"frame pane shows the entire selection and follows the parent search results"] };
});
await runCase("native:visual-resources:stencils", async () => {
const doc = panel.ownerDocument, win = doc.defaultView;
const preferences = plugin.settings.visualResources;
const libraryFolderPath = root + "/Stencils";
Object.assign(plugin.settings, { libraryFolderPath, libraryStorageMode: "vault", libraryMigrationStatus: "not-required",
visualResources: { ...preferences, filters: ["stencil"], list: false } });
plugin.stencilLibraryManager.invalidate();
await vault.createFolder(libraryFolderPath);
const source = library.libraryItems[0].elements;
const rectangle = source.find(element => element.type === "rectangle");
const original = { id: "stencil-probe-generated-id", created: 1, status: "unpublished", elements: [
{ ...rectangle, id: "stencil-top", x: 0, y: 0, width: 90, height: 40, backgroundColor: "#ff2222", fillStyle: "solid" },
{ ...rectangle, id: "stencil-bottom", x: 0, y: 700, width: 90, height: 40, backgroundColor: "#22ff22", fillStyle: "solid" },
{ ...source.find(element => element.type === "text"), id: "stencil-text", x: 0, y: 340, width: 90, height: 24,
fontSize: 20, text: "BRAIN", originalText: "BRAIN", rawText: "", autoResize: true },
] };
const sibling = { ...original, id: "sibling", name: "stencil-probe-zz sibling", elements: [original.elements[0]] };
const file = await vault.create(libraryFolderPath + "/Probe.excalidrawlib", JSON.stringify({
...library, source: "native-test", libraryItems: [original, sibling],
}));
await plugin.visualResourcePanel.open(view);
search(original.id);
const cardFor = title => [...panel.querySelectorAll(".excalidraw-resource-card")]
.find(el => el.querySelector('[aria-label="' + title + '"]'));
let tile, img;
await c.waitFor(() => (img = (tile = cardFor(original.id))?.querySelector(".excalidraw-resource-preview img"))?.naturalHeight,
"tall unnamed stencil thumbnail loads");
const preview = img.parentElement.getBoundingClientRect(), image = img.getBoundingClientRect();
const fits = image.top >= preview.top - 1 && image.bottom <= preview.bottom + 1 &&
image.left >= preview.left - 1 && image.right <= preview.right + 1;
const grip = tile.querySelector("[draggable=true]");
await view.changeTextMode("parsed", false);
await c.waitFor(() => plugin.visualResources.writable(view), "drawing prepared for the stencil drop");
const before = new Set(api.getSceneElements().map(element => element.id));
const transfer = new win.DataTransfer();
grip.dispatchEvent(new win.DragEvent("dragstart", { dataTransfer: transfer, bubbles: true }));
const state = api.getAppState();
const event = new win.DragEvent("drop", { dataTransfer: transfer, clientX: state.offsetLeft + 120,
clientY: state.offsetTop + 140, cancelable: true });
check(view.dropManager.onDrop(event) === false && event.defaultPrevented, "Stencil drag did not reach the native scene drop path");
let inserted;
await c.waitFor(() => (inserted = api.getSceneElements().filter(element => !before.has(element.id))).length === 3, "stencil inserted");
const text = inserted.find(element => element.type === "text");
c.observations.stencil = { previewHeight: preview.height, imageHeight: image.height, text: text?.text, width: text?.width };
check(fits && text?.text === "BRAIN" && text.width > 40,
"Stencil preview or text regression: " + JSON.stringify(c.observations.stencil));
check(view.excalidrawData.getRawText(text.id) === "BRAIN", "Inserted text lost its editable source");
await c.waitFor(() => plugin.visualResources.writable(view), "stencil insertion saved");
api.history.undo();
await c.waitFor(() => api.getSceneElements().length === before.size, "one undo removes the stencil");
const stencilLocator = { provider: "stencil", path: file.path, id: original.id };
const diskItem = async () => JSON.parse(await vault.read(file)).libraryItems[0];
check((await diskItem()).elements[2].rawText === "", "Dropping mutated the source stencil");
await plugin.visualResources.collections.curate([stencilLocator], { favorite: true });
await c.waitFor(() => cardFor(original.id)?.querySelector("[aria-pressed=true]"), "favorited stencil is rendered");
const nameInput = () => panel.querySelector(".excalidraw-resource-name-input");
const key = (element, value) => element.dispatchEvent(new win.KeyboardEvent("keydown", { key: value, bubbles: true, cancelable: true }));
cardFor(original.id).querySelector(".excalidraw-resource-rename").click();
check(doc.activeElement === nameInput() && nameInput().selectionEnd === original.id.length,
"Clicking a stencil name did not select the generated ID for editing");
nameInput().value = "Canceled name";
key(nameInput(), "Escape");
check(!nameInput() && !((await diskItem()).name), "Cancel saved a stencil name or closed the panel");
search("stencil-probe");
const thumbnail = title => cardFor(title)?.querySelector(".excalidraw-resource-preview img");
await c.waitFor(() => thumbnail(original.id)?.complete && thumbnail(sibling.name)?.complete, "both previews load");
const originalCard = cardFor(original.id), originalPreview = thumbnail(original.id);
const siblingCard = cardFor(sibling.name), siblingPreview = thumbnail(sibling.name);
const resources = plugin.visualResources;
const previewResource = resources.preview;
const previewRequests = [];
resources.preview = function(resource, dark) {
if (resource.locator.provider === "stencil") previewRequests.push(resource.locator.id);
return previewResource.call(this, resource, dark);
};
c.defer(() => { resources.preview = previewResource; });
cardFor(original.id).querySelector(".excalidraw-resource-rename").click();
nameInput().value = "Tall stencil";
key(nameInput(), "Enter");
await c.waitFor(() => cardFor("Tall stencil"), "rename stays in the original search results");
check(cardFor("Tall stencil") === originalCard && originalCard.nextElementSibling === siblingCard &&
doc.activeElement === originalCard.querySelector(".excalidraw-resource-rename"), "Rename changed tile position or keyboard focus");
plugin.visualResourcePanel.reload();
await c.waitFor(() => !panel.querySelector(".excalidraw-resource-status[aria-live]").textContent, "background refresh finishes");
check(thumbnail("Tall stencil") === originalPreview && thumbnail(sibling.name) === siblingPreview,
"Rename or background refresh recreated the loaded previews");
search("");
check(siblingCard.nextElementSibling === originalCard && thumbnail(sibling.name) === siblingPreview,
"Changing the query should apply normal sort and reuse unmoved preview data");
check(!previewRequests.length, "Rename, refresh, or sorting requested previews for unchanged stencils: " + previewRequests.join(", "));
await vault.process(file, raw => {
const data = JSON.parse(raw);
data.libraryItems[1].elements[0].backgroundColor = "#3388ff";
return JSON.stringify(data);
});
await c.waitFor(() => thumbnail(sibling.name) && thumbnail(sibling.name) !== siblingPreview, "edited stencil preview refreshes");
check(thumbnail("Tall stencil") === originalPreview && previewRequests.every(id => id === sibling.id),
"Editing one stencil requested unrelated stencil previews");
resources.preview = previewResource;
search("Tall stencil");
await c.waitFor(() => cardFor("Tall stencil"), "inline name appears in search");
check((await diskItem()).name === "Tall stencil", "Inline rename did not reach the owning library");
const controller = plugin.visualResourcePanel;
const showMenu = controller.show;
controller.show = function(menu, ...args) { return showMenu.call(this, menu.setUseNativeMenu(false), ...args); };
try {
cardFor("Tall stencil").querySelector(".excalidraw-resource-actions button:last-child").click();
let menuItem;
await c.waitFor(() => (menuItem = [...doc.querySelectorAll(".menu-item-title")]
.find(el => el.textContent === plugin.getLabel("VR_RENAME"))), "stencil action menu has Rename");
menuItem.closest(".menu-item").click();
let editor;
await c.waitFor(() => (editor = doc.querySelector('.modal input[aria-label="' + plugin.getLabel("VR_NAME") + '"]')),
"menu rename opens the name editor");
check(editor.value === "Tall stencil", "Menu rename lost the current stencil name");
editor.value = "Renamed stencil";
editor.dispatchEvent(new win.Event("input", { bubbles: true }));
key(editor, "Enter");
search("Renamed stencil");
await c.waitFor(() => cardFor("Renamed stencil"), "menu name appears in search");
} finally { controller.show = showMenu; }
const renamed = await diskItem();
check(renamed.name === "Renamed stencil" && renamed.id === original.id &&
JSON.stringify(renamed.elements) === JSON.stringify(original.elements), "Renaming changed stencil identity or contents");
check(plugin.visualResources.collections.state(stencilLocator).favorite && count() === before.size,
"Renaming lost the favorite or inserted another stencil");
plugin.settings.visualResources = preferences;
return { assertions: ["tall stencil thumbnail fits entirely", "drag inserts visible and editable text when rawText is empty",
"one undo removes the stencil", "inline rename accepts Enter and cancels with Escape",
"action menu rename preserves identity, elements and curation",
"rename preserves search context, tile position and keyboard focus",
"refresh and sort reuse loaded previews, while edits refresh only their own stencil"] };
});
await runCase("native:visual-resources:svg-strokes-and-curation", async () => {
const resources = plugin.visualResources;
const resource = (await resources.list()).find(item => item.source === svg.path);
const before = count();
await c.waitFor(() => resources.writable(view), "drawing is writable after linked insert");
await resources.insertSvgStrokes(resource, view, () => true, true);
await c.waitFor(() => count() > before, "editable SVG strokes published");
check(api.getSceneElements().filter(element => element.type === "image").length === 1, "Editable import added an image element");
await c.waitFor(() => app.metadataCache.getFileCache(view.file)?.frontmatter?.["excalidraw-svg-sources"]?.length === 1, "SVG source property cached");
const doc = panel.ownerDocument, win = doc.defaultView, controller = plugin.visualResourcePanel;
const previous = Object.getOwnPropertyDescriptor(win, "kplexApi");
const showMenu = controller.show;
Object.defineProperty(win, "kplexApi", { configurable: true, value: { version: 1, v1: {
version: 1,
capabilities: () => ({ ok: true, value: { operations: ["ontology"] } }),
ontology: () => ({ ok: true, value: { fields: [
{ name: "Illustration parent", configured: true, roles: ["parent"] },
{ name: "Derived artwork", configured: true, roles: ["child"] },
] } }),
} } });
controller.show = function(menu, ...args) { return showMenu.call(this, menu.setUseNativeMenu(false), ...args); };
try {
await controller.open(view);
search("Resource probe");
await c.waitFor(() => card() && resources.writable(view), "SVG stroke options have an editable drawing");
card().closest(".excalidraw-resource-card").querySelector(".excalidraw-resource-actions button:last-child").click();
let strokes;
await c.waitFor(() => (strokes = [...doc.querySelectorAll(".menu-item-title")]
.find(el => el.textContent === plugin.getLabel("VR_INSERT_STROKES"))), "stroke insertion offers a property chooser");
strokes.closest(".menu-item").click();
let modal;
await c.waitFor(() => (modal = [...doc.querySelectorAll(".modal")].find(el => el.querySelector(".modal-title")?.textContent ===
plugin.getLabel("VR_INSERT_STROKES"))), "SVG stroke dialog opens");
const setting = key => [...modal.querySelectorAll(".setting-item-name")]
.find(el => el.textContent === plugin.getLabel(key))?.closest(".setting-item");
setting("VR_SVG_RETAIN_LINK").querySelector(".checkbox-container").click();
const direction = setting("VR_KPLEX_DIRECTION").querySelector("select");
const fields = setting("VR_KPLEX_FIELD").querySelector("select");
check([...fields.options].some(option => option.value === "Illustration parent") &&
![...fields.options].some(option => option.value === "Derived artwork"), "K-Plex fields did not follow the selected relationship direction");
direction.value = "child";
direction.dispatchEvent(new win.Event("change", { bubbles: true }));
fields.value = "Derived artwork";
fields.dispatchEvent(new win.Event("change", { bubbles: true }));
check(setting("VR_SVG_PROPERTY").querySelector("input").value === "Derived artwork", "Chosen K-Plex property did not reach the editable field");
modal.querySelector("button.mod-cta").click();
await c.waitFor(() => app.metadataCache.getFileCache(view.file)?.frontmatter?.["Derived artwork"]?.length === 1,
"stroke insertion writes the chosen K-Plex property");
} finally {
if (previous) Object.defineProperty(win, "kplexApi", previous);
else Reflect.deleteProperty(win, "kplexApi");
controller.show = showMenu;
}
await resources.collections.savePlaylist("Native playlist", "native-list");
await resources.collections.curate([locator], { favorite: true, playlist: "native-list", member: true });
await resources.collections.refresh();
check(resources.collections.state(locator).favorite && resources.collections.state(locator).memberships.includes("native-list"), "Favorite and playlist membership did not persist");
await resources.collections.curate([locator], { playlist: "native-list", member: false });
check(resources.collections.state(locator).favorite && !resources.collections.state(locator).memberships.includes("native-list"), "Removing membership changed the independent favorite");
return { assertions: ["SVG conversion publishes editable elements", "source link appears in the default and selected ontology properties",
"playlist membership and favorite are independent"], sourceLinks: 1, nativeElements: count() - before };
});
await runCase("native:visual-resources:document-targets-and-preview-budget", async () => {
const doc = panel.ownerDocument;
const original = await vault.read(view.file);
const large = await vault.create(root + "/Large frame preview probe.excalidraw.md", original + "\n" + " ".repeat(1024 * 1024 + 128));
const medium = await vault.create(root + "/Medium linked preview probe.excalidraw.md", original + "\n" + " ".repeat(128 * 1024));
const solidRaster = async color => {
const canvas = doc.createElement("canvas");
canvas.width = 640;
canvas.height = 480;
const ctx = canvas.getContext("2d");
ctx.fillStyle = color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/jpeg", 0.9));
return await blob.arrayBuffer();
};
const inside = await vault.createBinary(root + "/Preview inside.jpg", await solidRaster("#23c46e"));
const outside = await vault.createBinary(root + "/Preview outside.jpg", await solidRaster("#b20a92"));
const sourceImage = api.getSceneElements().find(el => el.type === "image");
const sourceFrame = api.getSceneElements().find(el => el.type === "frame");
check(sourceImage && sourceFrame, "Preview fixture is missing its native image and frame");
const makeImage = (id, fileId, x) => ({ ...sourceImage, id, fileId, x, y: 0,
frameId: null, angle: 0, width: 400, height: 300, crop: null, scale: [1, 1], index: null, groupIds: [], opacity: 100 });
const previewFrame = { ...sourceFrame, id: "preview-frame", name: "Thumbnail", x: 0, y: 0, width: 400, height: 300 };
const fence = String.fromCharCode(96).repeat(3);
const savedDrawing = (elements, frontmatter = "", embedded = "") => {
const json = JSON.stringify({ type: "excalidraw", version: 2, elements, appState: {}, files: {} });
const compressed = plugin.ea.compressToBase64(json);
return "---\nexcalidraw-plugin: parsed\n" + frontmatter + "---\n\n# Excalidraw Data\n\n" +
embedded + "\n## Drawing\n" + fence + "compressed-json\n" + compressed + "\n" + fence + "\n";
};
const linked = await vault.create(root + "/Preview linked frame.excalidraw.md", savedDrawing([
previewFrame, makeImage("preview-inside", "inside", 0), makeImage("preview-outside", "outside", 700),
], "excalidraw-thumbnail: Thumbnail\n", "## Embedded Files\ninside: [[" + inside.path + "]]\n\noutside: [[" + outside.path + "]]\n"));
const rectangle = library.libraryItems[0].elements.find(el => el.type === "rectangle");
const tile = (id, x, width, color) => ({ ...rectangle, id, x, y: 0, width, height: 300, angle: 0,
opacity: 100, frameId: null, index: null, groupIds: [], backgroundColor: color, strokeColor: color, fillStyle: "solid", roughness: 0 });
const child = await vault.create(root + "/Preview linked drawing child.excalidraw.md", savedDrawing([
{ ...previewFrame, name: "card", frameRole: "marker" },
tile("blue-tile", 0, 400, "#1266dc"),
tile("pink-tile", 400, 410, "#db278f"),
]));
const nested = await vault.create(root + "/Preview linked drawing parent.excalidraw.md", savedDrawing([
{ ...previewFrame, name: "Linked drawing frame", frameRole: "marker" },
makeImage("nested-image", "nested", 0),
], "excalidraw-anchors: [Linked drawing frame]\n", "## Embedded Files\nnested: [[" + child.path + "#^frame=card|100%]]\n"));
const line = library.libraryItems[0].elements.find(el => el.type === "line");
const detailed = await vault.create(root + "/Preview detailed vectors.excalidraw.md", savedDrawing(
Array.from({ length: 1734 }, (_, i) => ({ ...line, id: "preview-line-" + i, index: null, groupIds: [],
x: (i % 40) * 32, y: Math.floor(i / 40) * 18, width: 29, height: 6,
points: Array.from({ length: 30 }, (_, point) => [point, point % 2 * 6]), boundElements: null, angle: 0 }))));
await c.waitFor(() => app.metadataCache.getFileCache(linked)?.frontmatter?.["excalidraw-thumbnail"] === "Thumbnail",
"saved thumbnail frame is indexed");
await c.waitFor(() => plugin.isExcalidrawFile(child) && plugin.isExcalidrawFile(nested), "nested drawing thumbnail fixtures are indexed");
await c.waitFor(() => app.metadataCache.getFileCache(large)?.frontmatter?.["excalidraw-anchors"]?.includes("Divider test frame"),
"large drawing has indexed frame metadata");
const note = await vault.create(root + "/Destination note.md", "Test note\n");
const canvas = await vault.create(root + "/Destination canvas.canvas", '{"nodes":[],"edges":[]}');
const documentLeaf = workspace.getLeaf("tab");
c.defer(() => documentLeaf.detach());
await documentLeaf.setViewState({ type: "markdown", state: { file: note.path, mode: "source" }, active: true });
await c.waitFor(() => documentLeaf.view.file === note && documentLeaf.view.getMode() === "source", "note editor is writable");
workspace.setActiveLeaf(documentLeaf, { focus: true });
check(app.commands.executeCommandById(id + ":visual-resources"), "Visual Resources command unavailable from Markdown");
await c.waitFor(() => plugin.visualResourcePanel.target === documentLeaf.view, "Markdown is the insertion target");
search("Resource probe");
await c.waitFor(() => card()?.getAttribute("aria-disabled") === null, "SVG can be embedded in Markdown");
card().click();
await c.waitFor(() => documentLeaf.view.editor.getValue().includes("![[") &&
documentLeaf.view.editor.getValue().includes("Resource probe"), "note has a linked SVG embed");
const editor = documentLeaf.view.editor;
editor.setValue("Above\nBelow");
const cm = editor.cm;
await c.waitFor(() => cm?.coordsAtPos(6), "Markdown editor has drop coordinates");
const coords = cm.coordsAtPos(6);
const win = cm.dom.ownerDocument.defaultView;
const transfer = new win.DataTransfer();
card().dispatchEvent(new win.DragEvent("dragstart", { dataTransfer: transfer, bubbles: true }));
const dragEvent = type => new win.DragEvent(type, { dataTransfer: transfer, clientX: coords.left + 1,
clientY: (coords.top + coords.bottom) / 2, bubbles: true, cancelable: true });
const over = dragEvent("dragover"), drop = dragEvent("drop");
cm.contentDOM.dispatchEvent(over);
cm.contentDOM.dispatchEvent(drop);
check(over.defaultPrevented && drop.defaultPrevented && editor.getValue().startsWith("Above\n![[") &&
editor.getValue().endsWith("Below"), "Markdown drop did not insert the embed at the pointed-to position");
const controller = plugin.visualResourcePanel;
const show = controller.show;
controller.show = function(menu, ...args) { return show.call(this, menu.setUseNativeMenu(false), ...args); };
try {
card().closest(".excalidraw-resource-card").querySelector(".excalidraw-resource-actions button:last-child").click();
await c.waitFor(() => [...doc.querySelectorAll(".menu-item-title")].some(el => el.textContent === plugin.getLabel("VR_SVG_OPTIONS")),
"stroke source defaults are available from Markdown");
check(![...doc.querySelectorAll(".menu-item-title")].some(el => el.textContent === plugin.getLabel("VR_INSERT_STROKES")),
"Markdown menu offered to insert editable strokes");
controller.menu.hide();
} finally { controller.show = show; }
const read = vault.read;
const cachedRead = vault.cachedRead;
let largeReads = 0;
vault.read = function(file) {
if (file === large) largeReads++;
return read.call(this, file);
};
vault.cachedRead = function(file) {
if (file === large) largeReads++;
return cachedRead.call(this, file);
};
try {
search("Large frame preview probe");
let browse;
await c.waitFor(() => (browse = [...panel.querySelectorAll(".excalidraw-resource-main .excalidraw-resource-actions button")]
.find(button => button.getAttribute("aria-label") === plugin.getLabel("VR_BROWSE_FRAMES") + " (3)")),
"large drawing uses its indexed frame count");
browse.click();
await c.waitFor(() => panel.querySelector(".excalidraw-resource-frames .excalidraw-resource-body")?.textContent.includes("Divider test frame"),
"large drawing lists frames from its metadata");
const resources = plugin.visualResources;
const descriptor = (await resources.list()).find(item => item.source === large.path);
const mediumResource = (await resources.list()).find(item => item.source === medium.path);
check((await resources.preview(mediumResource, false))?.startsWith("data:image/png"), "A medium drawing with linked assets did not produce a tiny raster preview");
const previews = await resources.list();
const linkedResource = previews.find(item => item.source === linked.path);
const detailedResource = previews.find(item => item.source === detailed.path);
const nestedResource = previews.find(item => item.source === nested.path);
const readBinary = vault.readBinary, rasterReads = [];
vault.readBinary = function(file) {
if (file === inside || file === outside) rasterReads.push(file.path);
return readBinary.call(this, file);
};
try {
const url = await resources.preview(linkedResource, false);
check(url?.startsWith("data:image/png"), "Cold linked thumbnail frame did not produce a PNG");
const image = doc.createElement("img");
image.src = url;
await image.decode();
check(image.naturalWidth === 256 && image.naturalHeight === 192, "Thumbnail did not preserve the chosen frame's bounds");
const sample = doc.createElement("canvas");
sample.width = sample.height = 1;
const ctx = sample.getContext("2d");
ctx.drawImage(image, -128, -96);
const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
check(g > 165 && r < 75 && b < 145 && a === 255, "Linked JPEG pixels were replaced by a placeholder: " + [r, g, b, a]);
check(await resources.preview(linkedResource, false) === url && rasterReads.join("|") === inside.path,
"A warm request reloaded the raster or the renderer read assets outside the thumbnail frame");
const oldKey = resources.previewKey(linkedResource, false);
await vault.modifyBinary(inside, await solidRaster("#257ceb"));
await c.waitFor(() => resources.previewKey(linkedResource, false) !== oldKey,
"a linked image change invalidates the thumbnail key");
const changed = await resources.preview(linkedResource, false);
check(changed !== url && changed?.startsWith("data:image/png") && rasterReads.length === 2,
"A stale thumbnail survived a linked image change");
persistedThumbnail = { drawing: linked, attachment: inside, url: changed };
const [namedFrame] = await resources.frames(nestedResource);
check(namedFrame?.title === "Linked drawing frame", "The nested-drawing fixture has no named frame");
const indexedFrame = { ...namedFrame.locator, frame: namedFrame.title };
await resources.collections.curate([indexedFrame, namedFrame.locator], { favorite: true });
try {
const curated = await resources.curatedFrames();
check(curated.some(item => item.locator.path === nested.path && item.locator.frame === indexedFrame.frame) &&
curated.some(item => item.locator.path === nested.path && item.locator.frame === namedFrame.locator.frame),
"Curated frame lookup lost a saved named reference or an exact frame ID");
} finally { await resources.collections.curate([indexedFrame, namedFrame.locator], { favorite: false }); }
const frameKey = JSON.stringify([nested.path, namedFrame.locator.frame, false]);
const frameStamp = resources.previewKey(namedFrame, false);
const oldPng = await (await win.fetch(url)).blob();
await resources.thumbnailCache.put(frameKey, "png-v1" + frameStamp, oldPng);
const frameUrl = await resources.preview(namedFrame, false);
check(frameUrl?.startsWith("data:image/png") && frameUrl !== url, "The named frame did not render a fresh PNG");
image.src = frameUrl;
await image.decode();
check(image.naturalWidth === 256 && image.naturalHeight === 192, "The named frame PNG exceeded its size or lost its aspect ratio");
ctx.clearRect(0, 0, 1, 1);
ctx.drawImage(image, -128, -96);
const [nr, ng, nb, na] = ctx.getImageData(0, 0, 1, 1).data;
check(nr < 40 && ng > 70 && nb > 190 && na === 255, "Named frame did not show the linked drawing's chosen frame: " + [nr, ng, nb, na]);
check((await resources.thumbnailCache.get(frameKey, "png-v2" + frameStamp))?.type === "image/png",
"The named frame PNG was not stored in the same thumbnail cache");
persistedFrame = { drawing: nested, child, resource: namedFrame, url: frameUrl };
check((await resources.preview(detailedResource, false))?.startsWith("data:image/png"),
"The detailed cold drawing with 1,734 elements and 52,020 stroke points did not produce a PNG");
} finally { vault.readBinary = readBinary; }
check(await resources.preview(descriptor, false) === null, "Cold large drawing was rendered");
const frame = (await resources.frames(descriptor))[0];
check(await resources.preview(frame, false) === null && largeReads === 0,
"Listing a large drawing or frame read its full scene");
const placeholder = [...panel.querySelectorAll(".excalidraw-resource-main .excalidraw-resource-card")]
.find(el => el.textContent.includes("Large frame preview probe")).querySelector(".excalidraw-resource-preview svg");
const registered = plugin.drawingCreationUI.ribbon.querySelector("svg");
check(placeholder && placeholder.innerHTML === registered.innerHTML, "An uncached drawing did not use the ribbon icon");
panel.querySelector(".excalidraw-resource-frames .excalidraw-resource-body").click();
await c.waitFor(() => documentLeaf.view.editor.getValue().includes("#^frame="), "named frame embedded in Markdown");
await documentLeaf.openFile(canvas);
workspace.setActiveLeaf(documentLeaf, { focus: true });
await c.waitFor(() => documentLeaf.view.getViewType() === "canvas" && plugin.visualResourcePanel.target === documentLeaf.view,
"native Canvas is the insertion target");
const frameCard = () => panel.querySelector(".excalidraw-resource-frames .excalidraw-resource-body");
await c.waitFor(() => frameCard()?.getAttribute("aria-disabled") === null, "named frame can be added to Canvas");
frameCard().click();
await c.waitFor(async () => JSON.parse(await read.call(vault, canvas)).nodes.some(node =>
node.type === "file" && node.file === large.path && node.subpath?.startsWith("#^frame=")), "Canvas saved a native frame file node");
} finally { vault.read = read; vault.cachedRead = cachedRead; }
await documentLeaf.setViewState({ type: "empty", state: {} });
documentLeaf.detach();
workspace.setActiveLeaf(leaf, { focus: true });
await plugin.visualResourcePanel.open(view);
check(doc === panel.ownerDocument, "document insertion changed the panel's owning document");
return { assertions: ["Markdown receives linked SVG and named-frame embeds, including drop at the pointer",
"Canvas saves a native file node with its frame subpath",
"low-resolution drawing and frame PNGs retain linked JPEGs and linked drawing frames, and skip out-of-frame assets",
"detailed vector scenes produce a PNG and over-budget cold files use the ribbon icon without reading the scene"] };
});
await runCase("native:visual-resources:popout-drop", async () => {
const receivingFile = await plugin.createDrawing("Resource drop receiver.excalidraw.md", root, drawingData);
const receivingLeaf = workspace.openPopoutLeaf();
c.defer(() => {
if (workspace.getLeafById(receivingLeaf.id) === receivingLeaf) receivingLeaf.detach();
});
await c.waitFor(() => receivingLeaf.view.containerEl.ownerDocument !== view.ownerDocument, "receiving leaf migrated to its popout");
await receivingLeaf.setViewState({ type: "excalidraw", state: { file: receivingFile.path }, active: true });
await c.waitFor(() => {
const receiver = receivingLeaf.view;
c.observations.receiver = { sameDocument: receiver.ownerDocument === view.ownerDocument,
loaded: !!receiver.isLoaded, hasEditor: !!receiver.excalidrawAPI,
fileMatches: receiver.file === receivingFile };
return receiver.file === receivingFile && receiver.ownerDocument !== view.ownerDocument && plugin.visualResources.writable(receiver);
}, "writable receiving popout");
const receiver = receivingLeaf.view;
await plugin.visualResourcePanel.open(view, "Icon Library");
search("Resource probe");
await c.waitFor(card, "draggable icon card in the main window sidebar");
const receiveApi = receiver.excalidrawAPI;
receiveApi.updateScene({ appState: { zoom: { value: 1.35 }, scrollX: 33, scrollY: -24 },
captureUpdate: "NEVER", forceFlushSync: true });
const state = receiveApi.getAppState();
const clientX = state.offsetLeft + 115, clientY = state.offsetTop + 125;
const expectedX = (clientX - state.offsetLeft) / state.zoom.value - state.scrollX;
const expectedY = (clientY - state.offsetTop) / state.zoom.value - state.scrollY;
const before = new Set(receiveApi.getSceneElements().map(element => element.id));
const sourceCount = count();
const sourceWindow = panel.ownerDocument.defaultView;
const transfer = new sourceWindow.DataTransfer();
card().dispatchEvent(new sourceWindow.DragEvent("dragstart", { dataTransfer: transfer, bubbles: true }));
const event = new receiver.ownerWindow.DragEvent("drop", { dataTransfer: transfer, clientX, clientY, cancelable: true });
check(receiver.dropManager.onDrop(event) === false && event.defaultPrevented, "The receiving drop manager did not consume the resource");
let inserted;
await c.waitFor(() => (inserted = receiveApi.getSceneElements().find(element => !before.has(element.id))), "resource inserted into receiving popout");
check(inserted.type === "image" && receiver.excalidrawData.getFile(inserted.fileId)?.file?.path === svg.path,
"Dropped SVG lost its source link");
check(Math.abs(inserted.x + inserted.width / 2 - expectedX) < 1 && Math.abs(inserted.y + inserted.height / 2 - expectedY) < 1,
"Resource drop lost the receiving view's zoom or pan");
check(count() === sourceCount && receiveApi.getSceneElements().length === before.size + 1,
"Drop inserted in the wrong drawing or added more than one element");
receiveApi.history.undo();
await c.waitFor(() => receiveApi.getSceneElements().length === before.size, "one undo removes the dropped resource");
await receiver.leaf.setViewState({ type: "empty", state: {} });
receiver.leaf.detach();
return { assertions: ["resource drop reaches the receiving popout", "linked image uses receiving scene coordinates",
"source scene is unchanged", "one undo removes the insertion"] };
});
await runCase("native:visual-resources:framework-picker", async () => {
workspace.setActiveLeaf(leaf, { focus: true });
const prepared = plugin.prepareInteractiveDrawing(true);
const doc = view.ownerDocument;
let picker;
await c.waitFor(() => (picker = doc.querySelector(".excalidraw-framework-picker"))?.querySelector(".excalidraw-resource-body"), "local framework is available offline");
picker.querySelector(".excalidraw-resource-body").click();
const result = await prepared;
check(result.kind === "ready" && result.data.includes(library.libraryItems[0].elements[0].id), "Framework selection did not produce editable scene data");
const path = await plugin.createAndOpenDrawing("Framework probe.excalidraw.md", "new-tab", root, result.data);
await c.waitFor(() => workspace.getLeavesOfType("excalidraw").some(leaf => leaf.view.file?.path === path && leaf.view.excalidrawAPI?.getSceneElements().length > 0), "framework drawing renders with editable elements");
const before = vault.getFiles().length;
const cancelled = plugin.createAndOpenInteractiveDrawing("Cancelled.excalidraw.md", "new-tab", root);
await c.waitFor(() => (picker = doc.querySelector(".excalidraw-framework-picker")), "interactive new drawing picker");
picker.dispatchEvent(new (doc.defaultView.KeyboardEvent)("keydown", { key: "Escape", bubbles: true }));
const close = picker.closest(".modal")?.querySelector(".modal-close-button");
close?.click();
check(await cancelled === "" && vault.getFiles().length === before, "Dismissal created a drawing");
const snoozed = plugin.prepareInteractiveDrawing();
await c.waitFor(() => (picker = doc.querySelector(".excalidraw-framework-picker")), "picker before snoozing");
const later = [...picker.querySelectorAll("button")].find(button => button.textContent === plugin.getLabel("VR_SHOW_LATER"));
check(later, "Show me later action unavailable");
const clickedAt = Date.now();
later.click();
check((await snoozed).kind === "ready", "Snoozing did not continue with a blank drawing");
check(plugin.settings.frameworksSnoozedUntil >= clickedAt + 7 * 86400000, "Snooze did not last seven days");
check((await plugin.prepareInteractiveDrawing()).kind === "ready" && !doc.querySelector(".excalidraw-framework-picker"),
"The automatic picker opened during the snooze");
return { assertions: ["framework opens offline", "selected framework starts an editable drawing",
"dismissal writes nothing", "automatic prompt snoozes for seven days"],
item: library.libraryItems[0].id, cancelledWithoutFile: true, sevenDaySnooze: true };
});
await runCase("native:visual-resources:reload", async () => {
plugin.settings.visualResources = { ...plugin.settings.visualResources, filters: ["lucide", "other"], unknownPreference: "retain" };
await plugin.saveSettings();
const settingsPath = plugin.manifest.dir + "/data.json";
const disk = JSON.parse(await vault.adapter.read(settingsPath));
check(disk.visualResources.unknownPreference === "retain" && disk.frameworksSnoozedUntil > Date.now(),
"New preferences did not persist on disk");
const previous = plugin;
const pendingFramework = plugin.prepareInteractiveDrawing(true);
const owner = workspace.containerEl.ownerDocument;
await c.waitFor(() => owner.querySelector(".excalidraw-framework-picker"), "framework picker present before unloading the plugin");
await app.plugins.disablePlugin(id);
check((await pendingFramework).kind === "cancel" && !owner.querySelector(".excalidraw-framework-picker"),
"Plugin unload did not close and settle the pending framework picker");
await app.plugins.enablePlugin(id);
await c.waitFor(() => app.plugins.plugins[id]?.isReady && app.plugins.plugins[id] !== previous, "fresh plugin startup");
plugin = app.plugins.plugins[id];
await plugin.visualResources.collections.refresh();
check(plugin.settings.visualResources.filters.join(",") === "lucide,other", "General browser filters changed after startup");
check(plugin.settings.visualResources.unknownPreference === "retain" && plugin.settings.frameworksSnoozedUntil === disk.frameworksSnoozedUntil,
"Snooze or unknown preferences were lost during startup");
check(plugin.visualResources.collections.state(locator).favorite, "Vault-wide favorite was lost after plugin reload");
const service = plugin.visualResources;
const thumbnail = (await service.list()).find(resource => resource.source === persistedThumbnail?.drawing.path);
check(thumbnail, "The drawing thumbnail fixture is missing after reload");
const cachedRead = vault.cachedRead, readBinary = vault.readBinary;
let renderedAgain = 0;
vault.cachedRead = function(file) {
if ([persistedThumbnail.drawing, persistedFrame?.drawing, persistedFrame?.child].includes(file)) renderedAgain++;
return cachedRead.call(this, file);
};
vault.readBinary = function(file) {
if (file === persistedThumbnail.attachment) renderedAgain++;
return readBinary.call(this, file);
};
try {
check(await service.preview(thumbnail, false) === persistedThumbnail.url && !renderedAgain,
"The PNG was regenerated after restarting the plugin");
check(persistedFrame && await service.preview(persistedFrame.resource, false) === persistedFrame.url && !renderedAgain,
"The named frame PNG reread its drawing or nested drawing after plugin restart");
const cache = service.thumbnailCache;
const key = JSON.stringify([persistedThumbnail.drawing.path, null, false]);
const stamp = "png-v2" + service.previewKey(thumbnail, false);
check((await cache.get(key, stamp))?.type === "image/png", "IndexedDB did not store the preview as a PNG blob");
await service.clearThumbnailCache();
check(!await cache.get(key, stamp), "Purge Cache left a Visual Resources thumbnail in IndexedDB");
check(await service.preview(thumbnail, false) === persistedThumbnail.url && renderedAgain > 0,
"The thumbnail did not rebuild after purging both cache tiers");
} finally { vault.cachedRead = cachedRead; vault.readBinary = readBinary; }
const win = workspace.containerEl.ownerDocument.defaultView;
const name = "Excalidraw Visual Resources test " + root;
let housekeeping;
const host = { indexedDB: win.indexedDB, IDBKeyRange: win.IDBKeyRange,
setTimeout(callback, delay) {
check(delay === 60_000, "Cache housekeeping is not deferred");
housekeeping = callback;
return 1;
},
clearTimeout() { housekeeping = null; } };
const probe = new service.thumbnailCache.constructor(host, name, () => 1);
const idb = request => new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
try {
const png = new win.Blob([new Uint8Array(300 * 1024)], { type: "image/png" });
await probe.put("expired", "budget", png);
const entries = mode => probe.database.transaction("entries", mode).objectStore("entries");
const record = await idb(entries("readonly").get("expired"));
await idb(entries("readwrite").put({ ...record, used: Date.now() - 172_800_000 }, "expired"));
check(housekeeping && await probe.get("expired", "budget") === null, "An expired cache entry was returned");
housekeeping();
await c.waitFor(async () => !await idb(entries("readonly").get("expired")), "timed purge removes the expired PNG metadata");
check(!await idb(probe.database.transaction("pngs").objectStore("pngs").get("expired")), "Timed purge left the PNG payload behind");
await probe.put("oldest", "budget", png);
const oldest = await idb(entries("readonly").get("oldest"));
await idb(entries("readwrite").put({ ...oldest, used: Date.now() - 86_000_000 }, "oldest"));
for (let i = 0; i < 342; i++) await probe.put("new-" + i, "budget", png);
const size = await idb(probe.database.transaction("totals").objectStore("totals").get("size"));
check(size.bytes <= 100 * 1024 * 1024 && size.count < 343 && !await probe.get("oldest", "budget") &&
(await probe.get("new-341", "budget"))?.size === png.size, "Cache exceeded its limit or kept the oldest PNG in place of the newest");
} finally {
probe.destroy();
await idb(win.indexedDB.deleteDatabase(name));
}
return { assertions: ["settings and unknown keys survive full plugin reload", "vault collection reload restores favorites",
"binary PNGs survive plugin reload without reading the source, purge cleanly and rebuild on demand",
"timed retention removes both records and least-recently-used eviction enforces the 100 MiB budget"] };
});
return { tests: c.tests, observations: c.observations };
}
+3 -2
View File
@@ -16,10 +16,11 @@ function fixture({ connected, nested = false, deferTimers = false, provider }) {
const helpers = new Map();
function helper(name) {
if (helpers.has(name)) return helpers.get(name);
const source = readFileSync(resolve(import.meta.dirname, "../../src/shared/Suggesters", name.slice(2) + ".ts"), "utf8");
const path = name.startsWith("src/") ? "../../" + name : "../../src/shared/Suggesters/" + name.slice(2);
const source = readFileSync(resolve(import.meta.dirname, path + ".ts"), "utf8");
const exports = {};
vm.runInNewContext(ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText,
{ exports, window: ownerWindow });
{ exports, window: ownerWindow, require: helper });
helpers.set(name, exports);
return exports;
}
+69 -17
View File
@@ -36,7 +36,7 @@ function fixture({ recognizeImages = true } = {}) {
class Element {
constructor(classes = "", tag = "div") {
this.classes = new Set(classes.split(" "));
this.classList = this.classes; this.style = {}; this.events = new Map();
this.classList = this.classes; this.style = { setProperty() {} }; this.events = new Map();
this.tag = tag; this.attrs = new Map(); this.children = []; this.isConnected = true;
this.ownerDocument = { defaultView: ownerWindow };
this.ownerDocument.createElement = tag => {
@@ -54,6 +54,7 @@ function fixture({ recognizeImages = true } = {}) {
removeAttribute(key) { this.attrs.delete(key); }
hasAttribute(key) { return this.attrs.has(key); }
get firstElementChild() { return this.children[0] ?? null; }
get firstChild() { return this.firstElementChild; }
hasChildNodes() { return this.children.length > 0; }
closest(selector) {
let el = this;
@@ -122,9 +123,10 @@ function fixture({ recognizeImages = true } = {}) {
} },
"../../shared/EmbeddedFileLoader": { EmbeddedFilesLoader: class { constructor() { this.terminate = false; loaders.push(this); } } },
"../../types/utilTypes": { PreviewImageType: { PNG: "PNG", SVGIMG: "SVGIMG", SVG: "SVG" } },
"../../utils/typechecks": { isInstanceOfHTMLImageElement: el => recognizeImages && el.tag === "img" },
"../../utils/obsidianUtils": { getSafeFrontmatter: fm => fm ?? {}, getParentOfClass: () => null },
"../../utils/typechecks": { isInstanceOfHTMLElement: el => el instanceof Element, isInstanceOfHTMLImageElement: el => recognizeImages && el.tag === "img" },
"../../utils/obsidianUtils": { getSafeFrontmatter: fm => fm ?? {}, getParentOfClass: (el, cls) => el.parentElement?.closest(`.${cls}`) ?? null },
"src/utils/htmlUtils": { setElementDisplay: (el, display) => { if (display === "none") el.addClass("excalidraw-display-none"); else el.removeClass("excalidraw-display-none"); } },
"src/utils/styleUtils": { setStyle: (el, properties) => Object.assign(el.style, properties) },
"../../utils/utils": {
hasExportTheme: () => false, getWithBackground: () => false, isMaskFile: () => false,
getEmbeddedFilenameParts: src => ({ hasBlockref: src.includes("#^"), blockref: src.split("#^")[1] }),
@@ -469,17 +471,65 @@ test("Reading mode resolves explicit self-images, but ignores empty and ordinary
}
});
test("Reading mode preserves a target's Markdown side unless the link explicitly requests an image", async () => {
for (const property of ["excalidraw-open-md", "excalidraw-embed-md"]) {
for (const suffix of ["", "#^as-image"]) {
const f = fixture(); const parent = new f.Element(); const embed = parent.appendChild(new f.Element("internal-embed")); embed.setAttribute("src", `target.excalidraw.md${suffix}`);
f.frontmatters.set("target.excalidraw.md", { [property]: true });
const rendered = f.processor.processReadingMode([embed], f.ctx);
if (suffix) { const job = f.start(); const image = await f.settle(); await job; await rendered; assert.equal(embed.children[0], image); }
else { await rendered; assert.equal(f.jobs.length, 0); assert.equal(parent.children[0], embed); }
for (const mode of ["Reading mode", "Live Preview"]) {
test(`${mode} uses embed-md for the Markdown side and honors explicit images`, async () => {
for (const property of ["excalidraw-open-md", "excalidraw-embed-md"]) {
for (const suffix of ["", "#^as-image"]) {
const f = fixture();
f.container.setAttribute("src", f.targetFile.path + suffix);
const frontmatter = { [property]: true };
f.frontmatters.set(f.targetFile.path, frontmatter);
if (mode === "Live Preview") {
f.ctx.sourcePath = f.targetFile.path;
f.ctx.frontmatter = frontmatter;
}
const rendered = mode === "Reading mode"
? f.processor.processReadingMode([f.container], f.ctx) : f.render();
const expectImage = property === "excalidraw-open-md" || !!suffix;
assert.equal(f.jobs.length, expectImage ? 1 : 0, property + suffix);
if (expectImage) {
const job = f.start();
const image = await f.settle();
await job; await rendered;
assert.equal(f.container.children[0], image);
} else {
await rendered;
assert.equal(f.container.children[0], f.el);
}
}
}
}
});
});
}
for (const [title, properties, showDrawing, expectImage] of [
["a regular drawing", {}, false, true],
["an open-md drawing with the hover setting off", { "excalidraw-open-md": true }, false, false],
["an open-md drawing with the hover setting on", { "excalidraw-open-md": true }, true, true],
["an embed-md drawing with the hover setting on", { "excalidraw-embed-md": true, "excalidraw-open-md": true }, true, false],
]) {
test(`Page Preview shows the correct side for ${title}`, async () => {
const f = fixture();
f.plugin.settings.renderImageInHoverPreviewForMDNotes = showDrawing;
const hover = new f.Element("hover-popover");
const preview = hover.appendChild(new f.Element("markdown-embed"));
const section = preview.appendChild(new f.Element("mod-frontmatter"));
section.appendChild(new f.Element("frontmatter"));
const frontmatter = { "excalidraw-plugin": "parsed", ...properties };
f.frontmatters.set(f.ctx.sourcePath, frontmatter);
const rendered = f.processor.markdownPostProcessor(section, { ...f.ctx, containerEl: preview, frontmatter });
await new Promise(resolve => setImmediate(resolve));
assert.equal(f.jobs.length, expectImage ? 1 : 0);
if (expectImage) {
const job = f.start();
const image = await f.settle();
await job; await rendered;
assert.equal(preview.firstChild, image.firstChild);
} else {
await rendered;
assert.ok(section.querySelector(".frontmatter"));
}
});
}
test("nested Markdown-side drawings and PNGs remain visible; drawing metadata stays hidden", async () => {
for (const property of ["excalidraw-open-md", "excalidraw-embed-md", null]) {
@@ -488,10 +538,12 @@ test("nested Markdown-side drawings and PNGs remain visible; drawing metadata st
f.frontmatters.set(f.ctx.sourcePath, f.ctx.frontmatter);
const section = new f.Element("el-p excalidraw-display-none"); const embed = section.appendChild(new f.Element("internal-embed")); embed.setAttribute("src", src);
const rendered = f.processor.markdownPostProcessor(section, f.ctx); await new Promise(resolve => setImmediate(resolve));
if (property && src !== "image.png") { const job = f.start(); await f.settle(); await job; }
const showsMarkdownSide = property === "excalidraw-embed-md";
assert.equal(f.jobs.length, showsMarkdownSide && src !== "image.png" ? 1 : 0);
if (showsMarkdownSide && src !== "image.png") { const job = f.start(); await f.settle(); await job; }
await rendered;
assert.equal(section.hasClass("excalidraw-display-none"), !property);
if (property && src === "image.png") assert.equal(section.children[0], embed);
assert.equal(section.hasClass("excalidraw-display-none"), !showsMarkdownSide);
if (showsMarkdownSide && src === "image.png") assert.equal(section.children[0], embed);
}
}
});
@@ -525,7 +577,7 @@ test("synchronous embed ownership preserves native text and hybrid Markdown", as
const sources = ["target.excalidraw.md", "target.excalidraw.md#^text", "target.excalidraw.md#Heading", "target.excalidraw.md#^as-image", "target.excalidraw.md#^group=abcdefgh", "target.excalidraw.md#^area=abcdefgh", "target.excalidraw.md#^clippedframe=Slide", "image.png", "missing.md"];
const embeds = sources.map(src => { const el = section.appendChild(new f.Element("internal-embed")); el.setAttribute("src", src); return el; });
const rendered = f.processor.markdownPostProcessor(section, f.ctx);
assert.deepEqual(embeds.map(el => el.hasClass("is-loaded")), [!property, false, false, true, true, true, true, false, false]);
assert.deepEqual(embeds.map(el => el.hasClass("is-loaded")), [property !== "excalidraw-embed-md", false, false, true, true, true, true, false, false]);
await new Promise(resolve => setImmediate(resolve));
while (f.jobs.length) { const job = f.start(); await f.settle(); await job; }
await rendered;
+6
View File
@@ -28,6 +28,9 @@ import { embedRegressionCaseIds } from "./host/embedRegressions.mjs";
import { embedReliabilityCaseIds } from "./host/embedReliability.mjs";
import { frameSemanticsCaseIds, frameSemanticsDeviceCaseIds } from "./host/frameSemantics.mjs";
import { kplexOntologyCaseIds, kplexOntologyDeviceCaseIds } from "./host/kplexOntology.mjs";
import { runtimeCompactionCaseIds } from "./host/runtimeCompaction.mjs";
import { sidepanelPopoutCaseIds } from "./host/sidepanelPopout.mjs";
import { visualResourceCaseIds } from "./host/visualResources.mjs";
export const requiredDeviceCases = [
...deviceProfiles(),
@@ -35,6 +38,9 @@ export const requiredDeviceCases = [
].map((profile) => "native:device:" + profile.id).concat(kplexOntologyDeviceCaseIds, embedControlDeviceCaseIds, frameSemanticsDeviceCaseIds);
export const requiredNativeCases = [
...sidepanelPopoutCaseIds,
...visualResourceCaseIds,
...runtimeCompactionCaseIds,
...workflowBundleCaseIds,
...issue3052CaseIds,
...aiAndEmbedsCaseIds,
@@ -15,6 +15,8 @@ const defaults = {
border: { enabled: false, color: "#000000" }, css: "", transclusion: { border: {} } } },
markdownImageDeletionPreference: "keep", pasteCodeBlockAs: "ask", previewImageType: "SVGIMG",
oEmbedAllowed: false, zoomMax: 3, allowWheelZoom: false, pinnedScripts: [], scriptEngineSettings: {},
visualResources: {}, frameworkFolder: "", frameworksOnBlank: true, frameworksSnoozedUntil: 0,
frameworkCatalogCheckedAt: 0, frameworkCatalog: [], frameworkInstalls: {},
};
async function fixture(t, options = {}) {
const harness = sourceHarness({
@@ -31,6 +33,9 @@ async function fixture(t, options = {}) {
const original = { ...structuredClone(defaults), zoomMax: 7, templateFilePath: "Templates/Custom.md",
allowWheelZoom: true, pinnedScripts: ["Capture Note"],
scriptEngineSettings: { "Capture Note": { noteTypes: { Custom: { template: "Templates/Note.md" } } } },
visualResources: { filters: ["lucide", "other"], iconWidth: 132, groups: ["icon:Shapes"], futureBrowserKey: true },
frameworkFolder: "Assets/Frameworks", frameworksOnBlank: false, frameworksSnoozedUntil: 1800000000000,
frameworkCatalogCheckedAt: 1799990000000, frameworkCatalog: [{ fname: "templates.excalidrawlib", mtime: 1799980000000 }],
futureSetting: { flag: false, zero: 0, paths: ["custom"] } };
const state = { disk: structuredClone(original), writes: [], reads: 0, stats: 0,
recoveryWrites: [], recoveryReads: 0, destroyed: 0, prompts: 0, promptModes: [] };
+166
View File
@@ -0,0 +1,166 @@
import assert from "node:assert/strict";
import test, { after } from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
const device = { isDesktop: true };
const graph = sourceHarness({
obsidian: { ItemView: class {}, WorkspaceLeaf: class {}, setIcon() {} },
"src/constants/constants": { DEVICE: device, ICON_NAME: "excalidraw", VIEW_TYPE_SIDEPANEL: "excalidraw-sidepanel" },
"src/core/main": { default: class {} },
"src/lang/helpers": { t: key => key },
"src/utils/excalidrawViewLookup": { getLastActiveExcalidrawView() {} },
"./SidepanelTab": { ExcalidrawSidepanelTab: class {} },
"src/utils/styleUtils": { hideElement() {}, showElement() {} },
"./MarkdownImageEditor": { handleMarkdownImageEditorSidepanelClosing() {} },
});
const { ExcalidrawSidepanelView: Panel } = await graph.importModule("src/view/sidepanel/Sidepanel.ts");
after(() => graph.close());
function fixture(preference, desktop = true) {
device.isDesktop = desktop;
const leaves = [], reveals = [], placements = [];
const mainDoc = {}, popoutDoc = {};
let ready = 0;
const create = location => {
placements.push(location);
const containerEl = {
ownerDocument: location === "popout" ? popoutDoc : mainDoc,
getBoundingClientRect: () => ({ width: 0, height: 0 }),
};
const leaf = { containerEl, async setViewState(state) {
this.state = state;
this.view = Object.assign(Object.create(Panel.prototype), {
leaf: this, app: plugin.app, containerEl, waitUntilReady: async () => { ready++; },
});
} };
leaves.push(leaf); return leaf;
};
const plugin = { settings: { sidepanelOpenInPopout: preference }, app: { workspace: {
getLeavesOfType: () => leaves,
getRightLeaf: () => create("sidebar"),
openPopoutLeaf: () => create("popout"),
containerEl: { ownerDocument: mainDoc },
moveLeafToPopout: leaf => { placements.push("popout"); leaf.containerEl.ownerDocument = popoutDoc; },
revealLeaf: async leaf => reveals.push(leaf),
} } };
return { plugin, placements, reveals, leaves, mainDoc, popoutDoc, get ready() { return ready; } };
}
test("sidepanel defaults to the sidebar and opts into desktop popouts", async () => {
for (const preference of [undefined, false, true]) {
const f = fixture(preference);
const view = await Panel.getOrCreate(f.plugin);
assert.deepEqual(f.placements, [preference === true ? "popout" : "sidebar"]);
assert.equal(view.leaf, f.leaves[0]);
assert.equal(view.leaf.state.type, "excalidraw-sidepanel");
assert.equal(view.leaf.state.active, true);
assert.deepEqual(f.reveals, [view.leaf]);
assert.equal(f.ready, 1);
}
});
test("mobile sidepanels ignore the synchronized desktop popout preference", async () => {
for (const preference of [false, true]) {
const f = fixture(preference, false);
// Mobile does not provide the desktop-only API.
delete f.plugin.app.workspace.openPopoutLeaf;
await Panel.getOrCreate(f.plugin);
assert.deepEqual(f.placements, ["sidebar"]);
}
});
test("reopening reuses sidepanel tabs and silent creation does not reveal the leaf", async () => {
const f = fixture(true);
const first = await Panel.getOrCreate(f.plugin, false);
first.retainedTab = { text: "unsaved panel input" };
assert.equal(first.leaf.state.active, false);
assert.deepEqual(f.reveals, []);
assert.deepEqual(f.placements, ["sidebar"]);
const second = await Panel.getOrCreate(f.plugin);
assert.equal(first, second);
assert.equal(second.retainedTab.text, "unsaved panel input");
assert.deepEqual(f.placements, ["sidebar", "popout"]);
assert.deepEqual(f.reveals, [first.leaf]);
// Once closed, the new preference applies to the next panel.
f.leaves.length = 0;
f.plugin.settings.sidepanelOpenInPopout = false;
assert.notEqual(await Panel.getOrCreate(f.plugin), first);
assert.deepEqual(f.placements, ["sidebar", "popout", "sidebar"]);
});
test("changing placement defers the popout and docks without revealing the sidebar", async () => {
const f = fixture(false), { mainDoc, popoutDoc } = f, rightRoot = {};
const panel = await Panel.getOrCreate(f.plugin);
const leaf = panel.leaf, workspace = f.plugin.app.workspace, calls = [];
const input = { value: "unsaved script input" };
panel.retainedTab = input;
workspace.containerEl = { ownerDocument: mainDoc };
workspace.rightSplit = rightRoot;
panel.containerEl = { ownerDocument: mainDoc };
let root = rightRoot;
const parent = { removeChild: child => { assert.equal(child, leaf); calls.push("remove"); } };
leaf.parent = parent;
leaf.getRoot = () => root;
leaf.setDimension = value => { assert.equal(value, null); calls.push("reset dimension"); };
workspace.moveLeafToPopout = child => {
assert.equal(child, leaf); calls.push("popout");
panel.containerEl.ownerDocument = popoutDoc; root = {}; leaf.parent = parent;
};
workspace.requestResize = () => calls.push("resize");
workspace.getRightLeaf = split => {
assert.equal(split, false);
return { parent: { insertChild(index, child) {
assert.equal(index, -1); assert.equal(child, leaf); calls.push("dock");
panel.containerEl.ownerDocument = mainDoc; root = rightRoot;
} }, detach: () => calls.push("remove placeholder") };
};
await Panel.applyLocationPreference(f.plugin, true);
assert.equal(panel.containerEl.ownerDocument, mainDoc);
assert.equal(await Panel.getOrCreate(f.plugin, false), panel);
assert.deepEqual(calls, []);
assert.equal(await Panel.getOrCreate(f.plugin), panel);
assert.equal(panel.containerEl.ownerDocument, popoutDoc);
await Panel.applyLocationPreference(f.plugin, false);
assert.equal(panel.containerEl.ownerDocument, mainDoc);
assert.equal(panel.retainedTab, input);
assert.equal(input.value, "unsaved script input");
assert.deepEqual(f.reveals, [leaf, leaf]);
assert.deepEqual(calls, ["popout", "remove", "reset dimension", "dock", "remove placeholder", "resize"]);
await Panel.applyLocationPreference(f.plugin, false);
assert.equal(calls.length, 6, "already docked panel should stay in place");
});
test("a deferred sidebar leaf loads quietly before its queued popout", async () => {
const f = fixture(false);
const workspace = f.plugin.app.workspace;
const leaf = workspace.getRightLeaf(false);
const deferredView = { containerEl: leaf.containerEl };
leaf.view = deferredView;
leaf.loadIfDeferred = async () => {
await leaf.setViewState({ type: "excalidraw-sidepanel", active: false });
};
Panel.applyLocationPreference(f.plugin, true);
assert.equal(leaf.view, deferredView);
assert.deepEqual(f.placements, ["sidebar"]);
await Panel.getOrCreate(f.plugin, false);
assert.equal(leaf.state.active, false);
assert.deepEqual(f.reveals, []);
const panel = await Panel.getOrCreate(f.plugin);
assert.equal(panel.leaf, leaf);
assert.equal(panel.containerEl.ownerDocument, f.popoutDoc);
assert.deepEqual(f.placements, ["sidebar", "popout"]);
});
test("applying sidepanel placement on mobile or without a panel creates no leaves", async () => {
for (const desktop of [false, true]) {
const f = fixture(false, desktop);
await Panel.applyLocationPreference(f.plugin, true);
await Panel.applyLocationPreference(f.plugin, false);
assert.deepEqual(f.placements, []);
}
const f = fixture(true, false);
const panel = await Panel.getOrCreate(f.plugin);
await Panel.applyLocationPreference(f.plugin, true);
assert.equal(await Panel.getOrCreate(f.plugin), panel);
assert.deepEqual(f.placements, ["sidebar"]);
});
+135
View File
@@ -0,0 +1,135 @@
/** Actual geometry/workbench helpers with the existing version-clone boundary isolated. */
import test from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { sourceHarness } from './sourceHarness.mjs';
const require = createRequire(import.meta.url), rough = require('roughjs');
const graph = sourceHarness({
'roughjs/bin/generator': { RoughGenerator: rough.generator().constructor },
'./excalidrawElementUtils': { cloneElement: e => ({ ...structuredClone(e), version: e.version + 1 }) },
});
const { convertWorkbenchStroke } = await graph.importModule('src/utils/strokeConversion.ts');
const { concatenateWorkbenchLines } = await graph.importModule('src/utils/strokeConcatenation.ts');
const { segmentDistance } = await graph.importModule('src/shared/svgToExcalidraw/pathGeometry.ts');
test.after(() => graph.close());
function line(id, points, extra = {}) {
const xs = points.map(p => p[0]), ys = points.map(p => p[1]);
return { id, type: 'line', x: 10, y: 20, angle: 0, points, width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys),
strokeWidth: 2, strokeColor: '#123456', backgroundColor: 'transparent', fillStyle: 'solid', roughness: 0, opacity: 100,
seed: 1, version: 1, groupIds: ['group'], frameId: 'frame', customData: { preserved: 'yes' }, boundElements: [], polygon: false, roundness: null, ...extra };
}
function workbench(elements) {
return { elementsDict: Object.fromEntries(elements.map(e => [e.id, e])), getElement(id) { return this.elementsDict[id]; },
plugin: { getCLIRuntime: () => ({ getCommonBounds: ([e]) => {
const xs = e.points.map(p => p[0] + e.x), ys = e.points.map(p => p[1] + e.y);
return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
} }) } };
}
const world = e => e.points.map(([x, y]) => [x + e.x, y + e.y]);
const near = (a, b, tolerance = 1e-7) => assert.ok(Math.hypot(a[0] - b[0], a[1] - b[1]) <= tolerance, `${a} != ${b}`);
test('line to free-draw retains world placement, identity and metadata for rotated strokes', () => {
const source = line('stroke', [[0, 0], [100, 0]], { angle: Math.PI / 2 });
const ea = workbench([source]);
const result = convertWorkbenchStroke(ea, 'stroke', 'freedraw');
const target = ea.getElement('stroke');
assert.equal(source.type, 'line'); assert.equal(target.type, 'freedraw'); assert.equal(target.angle, 0);
near(world(target)[0], [60, -30]); near(world(target)[1], [60, 70]);
assert.equal(target.version, 2); assert.deepEqual(target.groupIds, ['group']); assert.equal(target.frameId, 'frame');
assert.equal(target.customData.preserved, 'yes'); assert.equal(target.customData.strokeOptions.options.start.cap, true);
assert.equal(target.pressures.length, target.points.length); assert.equal(target.simulatePressure, false);
assert.equal('polygon' in target, false); assert.match(result.warnings[0], /excalidraw.com/);
});
test('rounded line conversion samples the actual spline within tolerance instead of retagging control points', () => {
const source = line('curve', [[0, 0], [50, 100], [100, 0]], { roundness: { type: 2 } });
const ea = workbench([source]), tolerance = 0.2;
convertWorkbenchStroke(ea, source.id, 'freedraw', { tolerance });
const sampled = world(ea.getElement(source.id)); assert.ok(sampled.length > source.points.length);
const ops = rough.generator().curve(source.points, { roughness: 0, preserveVertices: true, disableMultiStroke: true }).sets[0].ops.slice(0, source.points.length);
let start;
for (const op of ops) {
if (op.op === 'move') start = op.data;
else {
const [bx, by, cx, cy, dx, dy] = op.data;
for (let i = 0; i <= 100; i++) {
const t = i / 100, u = 1 - t;
const p = [u ** 3 * start[0] + 3 * u ** 2 * t * bx + 3 * u * t ** 2 * cx + t ** 3 * dx + source.x,
u ** 3 * start[1] + 3 * u ** 2 * t * by + 3 * u * t ** 2 * cy + t ** 3 * dy + source.y];
const error = Math.min(...sampled.slice(1).map((b, j) => segmentDistance(p, sampled[j], b)));
assert.ok(error <= tolerance ** 2 + 1e-8);
}
start = [dx, dy];
}
}
});
test('free-draw to line simplifies centerlines and explicitly removes custom pen and pressure semantics', () => {
const ea = workbench([line('stroke', Array.from({ length: 100 }, (_, i) => [i, i % 2 * 0.1]))]);
convertWorkbenchStroke(ea, 'stroke', 'freedraw');
const result = convertWorkbenchStroke(ea, 'stroke', 'line', { tolerance: 0.5, strokeWidth: 3 });
const target = ea.getElement('stroke');
assert.equal(target.points.length, 2); assert.equal(target.strokeWidth, 3); assert.equal(target.customData.preserved, 'yes');
assert.equal('strokeOptions' in target.customData, false); assert.equal('pressures' in target, false);
assert.match(result.warnings[0], /pressure/i);
});
test('custom free-draw tips/pressure configuration is copied without modifying caller settings', () => {
const ea = workbench([line('a', [[0, 0], [50, 0]]), line('b', [[0, 0], [50, 0]])]);
convertWorkbenchStroke(ea, 'a', 'freedraw');
const pen = structuredClone(ea.getElement('a').customData.strokeOptions);
pen.options.start.cap = false; pen.options.end.taper = 20; pen.options.thinning = 0.6;
pen.hasOutline = true; pen.outlineWidth = 2;
const before = structuredClone(pen);
convertWorkbenchStroke(ea, 'b', 'freedraw', { penOptions: pen });
assert.deepEqual(pen, before); assert.deepEqual(ea.getElement('b').customData.strokeOptions, pen);
ea.getElement('b').customData.strokeOptions.options.end.taper = 10;
assert.equal(pen.options.end.taper, 20);
});
test('conversion preserves closed fills and rejects unsupported relationships or budgets atomically', () => {
const ea = workbench([line('closed', [[0, 0], [50, 0], [0, 50]], { polygon: true, backgroundColor: '#ff0000' })]);
convertWorkbenchStroke(ea, 'closed', 'freedraw');
assert.deepEqual(ea.getElement('closed').points.at(-1), [0, 0]);
convertWorkbenchStroke(ea, 'closed', 'line'); assert.equal(ea.getElement('closed').polygon, true);
const ordinary = workbench([line('ordinary', [[0, 0], [50, 0], [0, 50], [0, 0]], { backgroundColor: '#ff0000' })]);
convertWorkbenchStroke(ordinary, 'ordinary', 'freedraw'); assert.equal(ordinary.getElement('ordinary').backgroundColor, '#ff0000');
const open = workbench([line('open', [[0, 0], [50, 0]], { type: 'freedraw', backgroundColor: '#ff0000' })]);
convertWorkbenchStroke(open, 'open', 'line'); assert.equal(open.getElement('open').polygon, false);
for (const extra of [{ startArrowhead: 'arrow' }, { startBinding: { elementId: 'shape' } }, { endBinding: { elementId: 'shape' } }, { boundElements: [{ id: 'label', type: 'text' }] }]) {
const e = line('bad', [[0, 0], [20, 30]], extra), target = workbench([e]), before = structuredClone(e);
assert.throws(() => convertWorkbenchStroke(target, 'bad', 'freedraw')); assert.deepEqual(target.getElement('bad'), before);
}
const target = workbench([line('curve', [[0, 0], [50, 100], [100, 0]], { roundness: { type: 2 } })]);
const before = structuredClone(target.getElement('curve'));
assert.throws(() => convertWorkbenchStroke(target, 'curve', 'freedraw', { maxPoints: 2 }));
assert.deepEqual(target.getElement('curve'), before);
});
test('concatenation chooses endpoint order, retains sharp corners and publishes no intermediate changes', () => {
const a = line('a', [[0, 0], [50, 0]]), b = line('b', [[50, 50], [50, 0]]), c = line('c', [[50, 50], [20, 80]]);
const ea = workbench([a, b, c]), result = concatenateWorkbenchLines(ea, ['a', 'c', 'b'], { maxGap: 0 });
assert.equal(result.id, 'a'); assert.deepEqual(result.removedIds, ['c', 'b']);
assert.equal(ea.getElement('b').isDeleted, true); assert.equal(ea.getElement('c').isDeleted, true);
assert.equal(a.isDeleted, undefined); assert.equal(b.isDeleted, undefined);
assert.deepEqual(world(ea.getElement('a')), [[10, 20], [60, 20], [60, 70], [30, 100]]);
});
test('concatenation refuses disconnected, conflicting and closed inputs without deleting any source', () => {
for (const extra of [{ x: 1000 }, { strokeColor: '#abcdef' }, { polygon: true }, { startBinding: { elementId: 'shape' } }, { endBinding: { elementId: 'shape' } }, { boundElements: [{ id: 'label', type: 'text' }] }]) {
const ea = workbench([line('a', [[0, 0], [50, 0]]), line('b', [[50, 0], [100, 0]], extra)]), before = structuredClone(ea.elementsDict);
assert.throws(() => concatenateWorkbenchLines(ea, ['a', 'b'])); assert.deepEqual(ea.elementsDict, before);
}
});
test('concatenation samples spline sections and normalizes rotation before endpoint matching', () => {
const rotated = workbench([line('a', [[0, 0], [100, 0]], { angle: Math.PI / 2 }), line('b', [[0, 0], [40, 0]], { x: 60, y: 70 })]);
concatenateWorkbenchLines(rotated, ['a', 'b'], { maxGap: 0.000001 });
const points = world(rotated.getElement('a'));
near(points[0], [60, -30]); near(points[1], [60, 70]); near(points[2], [100, 70]);
const curved = workbench([line('a', [[0, 0], [50, 100], [100, 0]], { roundness: { type: 2 } }), line('b', [[100, 0], [150, 50]])]);
const result = concatenateWorkbenchLines(curved, ['a', 'b'], { maxGap: 0 });
assert.ok(result.pointCount > 4); assert.equal(curved.getElement('a').roundness, null);
near(world(curved.getElement('a')).at(-1), [160, 70]);
});
+1 -1
View File
@@ -38,7 +38,7 @@ test('interactive cancellation never creates a file or opens a leaf; explicit in
});
test('public blank data keeps template/theme/compatibility/compression behavior and its string contract',async()=>{
let selection={kind:'cancel'};const module={exports:{}};
vm.runInNewContext(compile(`export class Manager {${methods('src/core/managers/FileManager.ts',['prepareDrawing','getBlankDrawing','getDrawingContent'])}}`),{
vm.runInNewContext(compile(`export class Manager {${methods('src/core/managers/FileManager.ts',['prepareDrawing','getBlankDrawing','getDrawingContent','selectTemplate'])}}`),{
module,exports:module.exports,selectDrawingTemplate:async()=>selection,getListOfTemplateFiles:()=>[],normalizePath:s=>s,
isObsidianThemeDark:()=>true,changeThemeOfExcalidrawMD:data=>'dark:'+data,
BLANK_DRAWING:'light-json',DARK_BLANK_DRAWING:'dark-json',FRONTMATTER:'frontmatter',getMarkdownDrawingSection:(data,compress)=>`section:${data}:${compress}`,
@@ -0,0 +1,333 @@
/** Exercise production discovery, curation, library ownership, and catalog operations. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { webcrypto } from "node:crypto";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
const base = "src/shared/visualResources/";
const model = await sourceHarness().importModule(base + "visualResourceModel.ts");
const candidate = { path: "Media/icon - Star.svg", folder: "Media", basename: "icon - Star",
extension: "svg", size: 2300, image: true, drawing: false };
test("visual discovery combines AND rules, OR groups and independent catch-all", () => {
const strict = { name: "Tiny", pattern: "^icon - (.*)", folderPattern: "^Media$", extensions: ".SVG", maxKb: "1" };
const match = model.compileVisualRules("icon", [strict, { ...strict, name: "Assets", maxKb: "4" }]);
assert.deepEqual(match(candidate), [{ group: "icon:Assets", keyword: "Star" }]);
assert.deepEqual(match({ ...candidate, folder: "Other" }), []);
const roleMatch = model.compileVisualRules("frame", [{ name: "Marked", pattern: "^Review (.+)", frameType: "magicframe", property: "tags", value: "#approved" }]);
assert.deepEqual(roleMatch({ ...candidate, frame: { name: "Review Phase 1" }, properties: { tags: ["approved"] } }),
[{ group: "frame:Marked", keyword: "Phase 1" }], "indexed names have no role yet");
assert.deepEqual(roleMatch({ ...candidate, frame: { name: "Review Phase 1", type: "frame" }, properties: { tags: ["approved"] } }), []);
assert.deepEqual(roleMatch({ ...candidate, frame: { name: "Review Phase 1", type: "magicframe" }, properties: { tags: ["approved"] } }),
[{ group: "frame:Marked", keyword: "Phase 1" }]);
const vault = { locator: { provider: "vault", path: candidate.path }, kind: "icon", title: "Star", source: candidate.path, keywords: [], groups: ["icon:Assets"] };
const lucide = { ...vault, locator: { provider: "lucide", icon: "lucide-star" }, groups: [] };
const other = { ...vault, locator: { provider: "vault", path: "Media/unmatched.svg" }, kind: "image", other: true, groups: [] };
const resources = [vault, lucide, other];
assert.deepEqual(model.filterVisualResources(resources, "", ["image"]), []);
assert.deepEqual(model.filterVisualResources(resources, "", ["other"], []), [other]);
assert.deepEqual(model.filterVisualResources(resources, "star", ["lucide"]), [lucide]);
assert.deepEqual(model.filterVisualResources(resources, "", ["icon", "other"], []), [other]);
assert.deepEqual(model.filterVisualResources(resources, "", ["icon", "other"], ["icon:Assets"]), [vault, other]);
assert.equal(model.compileVisualExclusions("Media, Templates\nSome Folder")(candidate.path), true);
const old = model.readIconLibrarySettings({ filters: [strict], activeFilterNames: [], defaultIconWidth: 123 });
assert.equal(old.iconWidth, 123);
assert.deepEqual(old.groups, []);
assert.equal(old.rules[0].maxKb, "", "preserve the distributed script's effective size handling");
});
test("frame keywords surface only the parent and provider identities remain independent", () => {
const locator = { provider: "vault", path: "One.md" };
const child = { locator: { ...locator, frame: "r1" }, kind: "frame", source: locator.path, title: "Review plan", keywords: [] };
const parent = { locator, kind: "drawing", source: locator.path, title: "Whole drawing", keywords: [], frames: [child] };
assert.deepEqual(model.filterVisualResources([parent], "review plan", ["drawing"]), [parent]);
assert.notEqual(model.visualResourceKey(locator), model.visualResourceKey(child.locator));
assert.equal(model.visualResourceKey({ provider: "stencil", id: "same", path: "A" }),
model.visualResourceKey({ provider: "stencil", id: "same", path: "B" }));
assert.notEqual(model.visualResourceKey({ provider: "framework", id: "same", path: "A" }),
model.visualResourceKey({ provider: "framework", id: "same", path: "B" }));
});
test("fine filters affect only their owning resource type or frame list", () => {
const icon = { locator: { provider: "vault", path: "one.svg" }, kind: "icon", title: "Mark",
source: "one.svg", keywords: [], groups: ["icon:Logo"] };
const frame = { locator: { provider: "vault", path: "board.md", frame: "a" }, kind: "frame",
title: "Interview", source: "board.md", keywords: [], groups: ["frame:Named frames"] };
const drawing = { locator: { provider: "vault", path: "board.md" }, kind: "drawing",
title: "Board", source: "board.md", keywords: [], groups: ["icon:Logo", "drawing:Boards", "frame:Named frames"], frames: [frame] };
assert.deepEqual(model.filterVisualResources([icon, drawing], "", ["icon", "drawing"], ["drawing:Boards"]), [drawing]);
assert.deepEqual(model.filterVisualResources([drawing], "interview", ["drawing"], ["drawing:Boards"]), [drawing]);
assert.deepEqual(model.filterVisualResources([drawing], "interview", ["drawing"], ["drawing:Boards", "frame:Named frames"]), [drawing]);
assert.deepEqual(model.filterVisualResources([drawing], "", ["drawing"], ["frame:Named frames"]), []);
assert.deepEqual(model.filterVisualResources([icon, drawing], "", ["icon"], ["icon:Logo"]), [icon, drawing]);
const withoutFrames = { ...drawing, frames: [] };
assert.deepEqual(model.filterVisualResources([withoutFrames, drawing], "", ["drawing"], undefined, true), [drawing]);
});
test("drawing thumbnail geometry admits detailed drawings and separates asset loading from vector work", () => {
assert.equal(model.admitDrawingPreview([{ type: "rectangle" }, { type: "image" }]), true);
assert.equal(model.admitDrawingPreview(Array(1734).fill({ type: "ellipse" })), true);
assert.equal(model.admitDrawingPreview([{ type: "freedraw", points: Array(49_000).fill([1, 1]) }]), true);
assert.equal(model.admitDrawingPreview(Array(2401).fill({ type: "ellipse" })), false);
assert.equal(model.admitDrawingPreview([{ type: "freedraw", points: Array(64_001).fill([1, 1]) }]), false);
assert.equal(model.admitDrawingPreview([{ type: "text", text: "x".repeat(12_001) }]), false);
const shared = model.drawingPreviewGeometryBudget();
assert.equal(model.admitDrawingPreview([{ type: "freedraw", points: Array(49_000).fill([1, 1]) }], shared), true);
assert.equal(model.admitDrawingPreview([{ type: "freedraw", points: Array(15_001).fill([1, 1]) }], shared), false);
assert.equal(model.admitDrawingPreview([{ type: "freedraw", points: Array(15_000).fill([1, 1]) }], shared), true);
});
class Component { registerEvent() {} }
class TFolder {}
const vaultSetup = () => {
const records = new Map(), folders = new Map(), listeners = new Map();
const vault = {
records,
changes: 0,
on(event, listener) { const bucket = listeners.get(event) ?? []; bucket.push(listener); listeners.set(event, bucket); },
trigger(event, ...args) { for (const listener of listeners.get(event) ?? []) listener(...args); },
getAbstractFileByPath(path) { return this.getFileByPath(path) ?? this.getFolderByPath(path); },
getFileByPath(path) { return records.get(path)?.file ?? null; },
getFolderByPath(path) { return folders.get(path) ?? null; },
async createFolder(path) { const folder = Object.assign(new TFolder(), { path, children: [] }); folders.set(path, folder); return folder; },
async create(path, text) {
if (records.has(path)) throw Error("Collision");
const name = path.split("/").at(-1);
const parent = this.getFolderByPath(path.slice(0, path.lastIndexOf("/")));
const file = { path, name, parent, extension: name.split(".").at(-1), stat: { mtime: ++this.changes } };
records.set(path, { file, text });
parent?.children.push(file);
this.trigger("create", file);
return file;
},
async read(file) { return records.get(file.path).text; },
async cachedRead(file) { return this.read(file); },
async process(file, update) {
const record = records.get(file.path);
const text = update(record.text);
if (text !== record.text) { record.text = text; file.stat.mtime = ++this.changes; this.trigger("modify", file); }
return text;
},
async modify(file, text) { return this.process(file, () => text); },
async trash(file) {
records.delete(file.path);
file.parent.children = file.parent.children.filter(child => child !== file);
this.trigger("delete", file);
},
getFiles: () => Array.from(records.values(), record => record.file),
};
return vault;
};
const obsidian = { Component, TFolder, normalizePath: path => path.replaceAll("//", "/"), Notice: class {} };
const makePlugin = vault => ({
settings: { folder: "Drawings", libraryFolderPath: "Libraries", libraryFileName: "User", libraryStorageMode: "vault",
frameworkFolder: "Frameworks", frameworkInstalls: {}, frameworkCatalog: [], frameworkCatalogCheckedAt: 0, showNewVersionNotification: false },
app: { vault, workspace: { containerEl: { ownerDocument: { defaultView: { crypto: webcrypto, setTimeout, clearTimeout } } } },
fileManager: { trashFile: file => vault.trash(file) } },
register() {}, registerEvent() {}, async saveSettings() {},
getLegacyStencilLibrary: () => ({ libraryItems: [] }),
});
const t = { t: key => key };
test("collections replay edits on the latest file and retain memberships through moves", async () => {
const harness = sourceHarness({ obsidian });
try {
const { ResourceCollections } = await harness.importModule(base + "ResourceCollections.ts");
const vault = vaultSetup(), plugin = makePlugin(vault);
const store = new ResourceCollections(plugin);
store.onload();
await store.refresh();
assert.equal(vault.getFileByPath("Drawings/resource-collections.json"), null);
await store.savePlaylist("Parent", "parent");
await store.savePlaylist("Child", "child", "parent");
await store.savePlaylist("Other", "other");
await assert.rejects(store.removePlaylist("parent"), /contains children/);
const original = { provider: "vault", path: "Folder/drawing.md", frame: "frame-id" };
await Promise.all([store.curate([original], { favorite: true }), store.curate([original], { playlist: "child", member: true }),
store.curate([original], { playlist: "other", member: true })]);
assert.deepEqual(store.state(original), { favorite: true, memberships: ["child", "other"] });
const file = vault.getFileByPath("Drawings/resource-collections.json");
await vault.process(file, raw => {
const disk = JSON.parse(raw);
disk.playlists.remote = { name: "Remote", members: ["dangling"] };
return JSON.stringify(disk);
});
vault.trigger("rename", { path: "Renamed" }, "Folder");
const moved = { ...original, path: "Renamed/drawing.md" };
await store.curate([moved], { playlist: "other", member: false });
const restored = new ResourceCollections(plugin);
await restored.refresh();
assert.deepEqual(restored.state(moved), { favorite: true, memberships: ["child"] });
assert.deepEqual(restored.state(original), { favorite: false, memberships: [] });
assert.deepEqual(restored.playlists.find(([id]) => id === "remote")[1].members, []);
const replacement = { provider: "stencil", id: "s1", path: "Libraries/A.excalidrawlib" };
await store.curate([replacement], { favorite: true, playlist: "other", member: true });
vault.trigger("delete", { path: replacement.path });
const destination = "Libraries/B.excalidrawlib";
await store.moveStencils(["s1"], replacement.path, destination);
assert.deepEqual(store.state({ ...replacement, path: destination }), { favorite: true, memberships: ["other"] });
vault.trigger("delete", { path: moved.path });
await store.curate([moved], { manual: true });
assert.equal(store.state(moved).favorite, false);
const beforeUnload = await vault.read(file);
const retiredEdit = store.curate([moved], { favorite: true });
store.onunload();
await assert.rejects(retiredEdit, /retired/);
assert.equal(await vault.read(file), beforeUnload);
} finally { harness.close(); }
});
test("stencil moves keep empty files and can resume after source cleanup fails", async () => {
const harness = sourceHarness({ obsidian, "src/lang/helpers": t,
"src/constants/constants": { restoreLibraryItems: items => items },
"src/constants/safeUrls": { URLs: { GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG: "release" } },
"src/shared/Dialogs/StencilLibraryMigrationPrompt": { StencilLibraryMigrationPrompt: class {} },
"src/utils/obsidianUtils": { getExcalidrawViews: () => [] },
});
const originalVersion = globalThis.PLUGIN_VERSION;
globalThis.PLUGIN_VERSION = "test";
try {
const { StencilLibraryManager } = await harness.importModule("src/core/managers/StencilLibraryManager.ts");
const vault = vaultSetup(), plugin = makePlugin(vault);
const manager = new StencilLibraryManager(plugin);
const source = await manager.createResourceLibrary("Source");
const destination = await manager.createResourceLibrary("Destination");
assert.ok((await manager.getResourceLibraries()).paths.includes(destination));
const shape = { id: "keep-id", name: "Independent shape", created: 1, status: "unpublished", elements: [] };
const envelope = items => JSON.stringify({ type: "excalidrawlib", version: 2, libraryItems: items });
await vault.modify(vault.getFileByPath(source), envelope([shape]));
manager.invalidate();
const processFile = vault.process.bind(vault);
vault.process = async (file, update) => {
if (file.path === source) throw Error("Source write failed");
return processFile(file, update);
};
await assert.rejects(manager.moveResourceStencils(source, destination, [shape.id]), /Source write failed/);
const items = async path => JSON.parse(await vault.read(vault.getFileByPath(path))).libraryItems;
assert.deepEqual(await items(source), [shape]);
assert.deepEqual(await items(destination), [shape]);
vault.process = processFile;
await manager.moveResourceStencils(source, destination, [shape.id]);
assert.deepEqual(await items(source), []);
assert.equal((await manager.getResourceLibraries()).items.find(entry => entry.item.id === shape.id).path, destination);
await vault.modify(vault.getFileByPath(source), envelope([{ ...shape, name: "Different" }]));
await assert.rejects(manager.moveResourceStencils(source, destination, [shape.id]), /collision/);
assert.equal((await items(source))[0].name, "Different");
await manager.deleteResourceLibrary(source, null, [shape.id]);
assert.equal(vault.getFileByPath(source), null);
assert.deepEqual(await items(destination), [shape]);
} finally { globalThis.PLUGIN_VERSION = originalVersion; harness.close(); }
});
test("stencil rename changes only the owned item name in vault and legacy libraries", async () => {
const harness = sourceHarness({ obsidian, "src/lang/helpers": t,
"src/constants/constants": { restoreLibraryItems: items => items },
"src/constants/safeUrls": { URLs: { GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG: "release" } },
"src/shared/Dialogs/StencilLibraryMigrationPrompt": { StencilLibraryMigrationPrompt: class {} },
"src/utils/obsidianUtils": { getExcalidrawViews: () => [] },
});
const originalVersion = globalThis.PLUGIN_VERSION;
globalThis.PLUGIN_VERSION = "test";
try {
const { StencilLibraryManager } = await harness.importModule("src/core/managers/StencilLibraryManager.ts");
const vault = vaultSetup(), plugin = makePlugin(vault);
const manager = new StencilLibraryManager(plugin);
const owner = await manager.createResourceLibrary("Owner");
const other = await manager.createResourceLibrary("Other");
const stencil = { id: "generated", status: "unpublished", created: 1, elements: [{ id: "label", type: "text", text: "The shape", rawText: "" }] };
const remote = { ...stencil, id: "remote", name: "Remote edit" };
let legacy = { type: "excalidrawlib", version: 2, custom: "keep", libraryItems: [stencil] };
const read = async path => JSON.parse(await vault.read(vault.getFileByPath(path)));
await vault.modify(vault.getFileByPath(owner), JSON.stringify(legacy));
await vault.modify(vault.getFileByPath(other), JSON.stringify(legacy));
await manager.getResourceLibraries();
// Sync changes the file after the browser has taken a snapshot.
const edit = { ...legacy, libraryItems: [{ ...stencil, status: "published" }, remote] };
await vault.modify(vault.getFileByPath(owner), JSON.stringify(edit));
await manager.renameResourceStencil(owner, stencil.id, " Tall shape ");
assert.deepEqual(await read(owner), { ...edit, libraryItems: [{ ...edit.libraryItems[0], name: "Tall shape" }, remote] });
assert.deepEqual(await read(other), legacy);
await assert.rejects(manager.renameResourceStencil(owner, "removed", "New"), /unique match/);
await assert.rejects(manager.renameResourceStencil(owner, stencil.id, " "), /empty/);
plugin.settings.libraryStorageMode = "data-json";
plugin.getLegacyStencilLibrary = () => legacy;
plugin.setLegacyStencilLibrary = async data => { legacy = data; };
await manager.renameResourceStencil(undefined, stencil.id, "Legacy shape");
assert.deepEqual(legacy, { type: "excalidrawlib", version: 2, custom: "keep", libraryItems: [{ ...stencil, name: "Legacy shape" }] });
assert.equal((await manager.getResourceLibraries()).items[0].item.name, "Legacy shape");
} finally { globalThis.PLUGIN_VERSION = originalVersion; harness.close(); }
});
test("framework catalog is local-first and coalesces checks for 24 hours", async () => {
const asset = readFileSync(new URL("../../visual-frameworks/thinking-frameworks.excalidrawlib", import.meta.url), "utf8");
const directory = readFileSync(new URL("../../visual-frameworks/directory-info.json", import.meta.url), "utf8");
const remote = JSON.parse(directory)[0];
let requested = [], shutdown = false, current = directory, pendingAsset;
let now = 1800000000000;
const dateNow = Date.now;
Date.now = () => now;
const harness = sourceHarness({
obsidian: { ...obsidian, Modal: class {}, Setting: class {}, requestUrl: async ({ url }) => {
requested.push(url);
if (shutdown) throw Error("Offline");
if (url !== "catalog" && pendingAsset) return { text: await pendingAsset };
return { text: url === "catalog" ? current : asset };
}},
"src/constants/constants": { restoreLibraryItems: items => items },
"src/constants/safeUrls": { URLs: { VISUAL_FRAMEWORKS_CATALOG: "catalog", VISUAL_FRAMEWORKS_DIRECTORY: "files" } },
"src/lang/helpers": t,
});
try {
const { FrameworkCatalog, parseFrameworkLibrary } = await harness.importModule(base + "FrameworkCatalog.ts");
assert.equal(parseFrameworkLibrary(asset).length, 21);
assert.throws(() => parseFrameworkLibrary('{"type":"excalidrawlib","version":2,"libraryItems":[null]}'));
const vault = vaultSetup(), plugin = makePlugin(vault), catalog = new FrameworkCatalog(plugin);
assert.deepEqual(await catalog.list(), []);
assert.deepEqual(await catalog.updates(), []);
assert.deepEqual(requested, []);
plugin.settings.showNewVersionNotification = true;
await Promise.all([catalog.updates(), catalog.updates()]);
assert.deepEqual(requested, ["catalog"]);
await catalog.install();
assert.deepEqual(requested, ["catalog", "files/" + remote.fname]);
assert.equal((await catalog.list()).length, 21);
assert.ok(plugin.settings.frameworkInstalls["Frameworks/" + remote.fname].digest);
current = JSON.stringify([{ ...remote, mtime: remote.mtime + 1 }]);
now += 24 * 60 * 60 * 1000 - 1;
assert.deepEqual(await catalog.updates(), []);
now++;
assert.equal((await catalog.updates()).length, 1);
assert.equal(requested.length, 3, "the update check never downloads a library");
const path = "Frameworks/" + remote.fname;
const file = vault.getFileByPath(path);
const modified = asset + "\n";
await vault.modify(file, modified);
catalog.confirmReplace = async () => false;
await catalog.install();
assert.equal(await vault.read(file), modified, "declining replacement keeps local edits");
assert.equal(plugin.settings.frameworkInstalls[path].mtime, remote.mtime);
catalog.confirmReplace = async () => true;
await catalog.install();
assert.equal(await vault.read(file), asset, "accepting replacement installs the validated revision");
assert.equal(plugin.settings.frameworkInstalls[path].mtime, remote.mtime + 1);
shutdown = true;
now += 24 * 60 * 60 * 1000;
assert.deepEqual(await catalog.updates(), []);
assert.equal((await catalog.list()).length, 21);
shutdown = false;
let finishAsset;
pendingAsset = new Promise(resolve => { finishAsset = resolve; });
const retired = new FrameworkCatalog(plugin);
await vault.trash(file);
const install = retired.install();
const downloads = requested.filter(url => url.startsWith("files/")).length;
for (let turn = 0; turn < 12 && requested.filter(url => url.startsWith("files/")).length === downloads; turn++) await Promise.resolve();
assert.ok(requested.filter(url => url.startsWith("files/")).length > downloads, "library download is in flight");
retired.destroy();
finishAsset(asset);
await assert.rejects(install, /changed during installation/);
assert.equal(vault.getFileByPath(path), null, "a completed download cannot recreate a library after unload");
} finally { Date.now = dateNow; harness.close(); }
});
+1 -1
View File
@@ -29,7 +29,7 @@ async function setup(t) {
"../../constants/constants": { MD_EX_SECTIONS: [] },
"../../lang/helpers": { t: key => key },
"../../utils/pathUtils": { cleanSectionHeading: text => text },
"src/constants/constants": { ICON_NAME: "excalidraw", VIEW_TYPE_SIDEPANEL: "sidepanel" },
"src/constants/constants": { DEVICE: { isDesktop: true }, ICON_NAME: "excalidraw", VIEW_TYPE_SIDEPANEL: "sidepanel" },
"src/lang/helpers": { t: key => key },
"src/utils/excalidrawViewLookup": { getLastActiveExcalidrawView: () => null },
"./SidepanelTab": { ExcalidrawSidepanelTab: class {} },
+1
View File
@@ -186,6 +186,7 @@ export const getIconAsJSX = (iconId: string) => {
};
export const ICONS = {
Shapes: getIconAsJSX("shapes"),
ExportImage: getIconAsJSX("image-down"),
Info: getIconAsJSX("info"),
BackOfNote: getIconAsJSX("text-select"),
+20
View File
@@ -40,10 +40,26 @@ const defineUrl = (url: string, purpose: string) => ({ url, purpose });
* Single source of truth for all external URLs and their security/audit justifications.
*/
export const URL_REGISTRY = {
VISUAL_FRAMEWORKS_DIRECTORY: defineUrl(
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/visual-frameworks",
UrlPurpose.APP_LOGIC,
),
VISUAL_FRAMEWORKS_CATALOG: defineUrl(
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/visual-frameworks/directory-info.json",
UrlPurpose.APP_LOGIC,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI: defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-cli",
UrlPurpose.DOCS,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI_ISSUE_3: defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-cli/issues/3",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI_ISSUE_6: defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-cli/issues/6",
UrlPurpose.RELEASE_LOG,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON:
defineUrl(
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/directory-info.json",
@@ -72,6 +88,10 @@ export const URL_REGISTRY = {
"https://github.com/zsviczian/obsidian-excalidraw-plugin/issues",
UrlPurpose.DOCS,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUE_3053: defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3053",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_EXTRAS_ISSUES: defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-extras/issues",
UrlPurpose.RELEASE_LOG,
+8 -5
View File
@@ -4,7 +4,7 @@ import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import type { ExcalidrawCLI } from "src/core/managers/ExcalidrawCLI";
import type { ConnectionPoint } from "src/types/types";
import { CLIError, boolean, number, object, string, vaultPath } from "./cliProtocol";
import { CLI_STYLE_FIELDS, constructBatch, fields, validateBatch, validateStyle } from "./cliElements";
import { CLI_STYLE_FIELDS, constructBatch, fields, validateBatch, validatePolygonPoints, validateStyle } from "./cliElements";
import { drawingFile, drawingView, liveIdentity } from "./cliTarget";
import { sameCLIIdentity } from "./cliIdentity";
import { cliImageMetadataPatch } from "src/utils/elementCustomDataUtils";
@@ -15,7 +15,7 @@ export const CLI_OPERATION_FIELDS: Record<string, string[]> = {
lucide: CLI_ICON_FIELDS,
add: ["elements"], update: ["id", "set"], delete: ["ids", "children"],
connect: ["id", "from", "to", "fromSide", "toSide"], group: ["ids"], ungroup: ["ids", "groupId"],
image: ["id", "asset", "x", "y", "scale"], imageMetadata: ["id", "label", "tags"], latex: ["id", "text", "x", "y", "scaleX", "scaleY"],
image: ["id", "asset", "x", "y", "scale", "anchor"], imageMetadata: ["id", "label", "tags"], latex: ["id", "text", "x", "y", "scaleX", "scaleY"],
};
function ids(value: unknown): string[] {
@@ -53,7 +53,7 @@ export function validateOperations(input: unknown): Record<string, unknown>[] {
if (op === "connect") { string(operation.from, "from"); string(operation.to, "to"); side(operation.fromSide); side(operation.toSide); }
if (["image", "latex"].includes(op)) {
number(operation.x, "x", 0, -1000000, 1000000); number(operation.y, "y", 0, -1000000, 1000000);
if (op === "image") { vaultPath(operation.asset, "asset"); boolean(operation.scale, "scale", true); }
if (op === "image") { vaultPath(operation.asset, "asset"); boolean(operation.scale, "scale", true); boolean(operation.anchor, "anchor", true); }
else { string(operation.text, "text"); number(operation.scaleX, "scaleX", 1, 0.1, 4); number(operation.scaleY, "scaleY", 1, 0.1, 4); }
}
if (operation.id !== undefined) string(operation.id, "id");
@@ -109,6 +109,8 @@ export async function applyDrawing(cli: ExcalidrawCLI, request: Record<string, u
for (const element of batch.elements) elementsMap.set(element.id, element);
} else if (op === "update") {
const element = resolve(operation.id), set = { ...object(operation.set) };
validateStyle(set, element.type);
if (set.polygon === true && element.type === "line") validatePolygonPoints(element.points);
if (element.type !== "text" && ["text", "fontSize", "fontFamily", "textAlign", "verticalAlign"].some(key => key in set)) throw new CLIError("INVALID_INPUT", "Text fields require a text element; edit its bound label ID.", "set");
if (["arrow", "line", "freedraw"].includes(element.type) && ["width", "height"].some(key => key in set)) throw new CLIError("INVALID_INPUT", "Linear resizing requires a trusted EA script.", "set");
if ("text" in set) { set.rawText = set.text; set.originalText = set.text; }
@@ -162,10 +164,11 @@ export async function applyDrawing(cli: ExcalidrawCLI, request: Record<string, u
}
} else if (op === "image") {
const path = vaultPath(operation.asset, "asset"), asset = plugin.app.vault.getFileByPath(path);
if (!asset || !["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(asset.extension.toLowerCase())) throw new CLIError("INVALID_INPUT", "Image requires an existing vault raster image or SVG.", "asset");
if (!asset || !(["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(asset.extension.toLowerCase()) || plugin.isExcalidrawFile(asset))) throw new CLIError("INVALID_INPUT", "Image requires an existing vault raster image, SVG or recognized Excalidraw drawing.", "asset");
if (asset === file) throw new CLIError("INVALID_INPUT", "A drawing cannot embed itself.", "asset");
if (asset.stat.size > 16 * 1024 * 1024) throw new CLIError("INVALID_INPUT", "Image exceeds 16 MiB.", "asset");
const stat = JSON.stringify(asset.stat);
const actual = await ea.addImage(number(operation.x, "x", 0, -1000000, 1000000), number(operation.y, "y", 0, -1000000, 1000000), asset, boolean(operation.scale, "scale", true));
const actual = await ea.addImage(number(operation.x, "x", 0, -1000000, 1000000), number(operation.y, "y", 0, -1000000, 1000000), asset, boolean(operation.scale, "scale", true), boolean(operation.anchor, "anchor", true));
if (plugin.app.vault.getFileByPath(path) !== asset || JSON.stringify(asset.stat) !== stat) throw new CLIError("STALE_REVISION", "Image changed during preparation.", "asset");
recordId(operation.id, actual);
} else if (op === "latex") {
+4
View File
@@ -20,6 +20,7 @@ export const CLI_COMMANDS: Record<CLICommand, CommandDescriptor> = {
schema: { description: "Inspect one command's fields and side effects", fields: { action: "Command to describe" }, example: { action: "create" } },
api: { description: "Search EA documentation or the supported installed Lib reference", fields: { surface: "ea (default) or lib", name: "Exact method name", query: "Case-insensitive search" }, example: { surface: "ea", name: "addText" } },
list: { description: "List drawing paths without opening them", fields: { folder: "Optional exact folder", ...page }, example: { limit: 50 } },
selection: { description: "Capture up to 500 selected live elements and bound labels as a stable agent handoff packet; no clipboard or drawing writes", fields: { ...target }, example: { path: "Drawings/Flow.excalidraw.md", view: "from-open-or-read" } },
read: { description: "Read an explicit live or disk drawing; no base64 asset bodies", fields: { ...target, ...source, ...page, detail: "summary (default), elements, or images (asset metadata only)", selectedOnly: "Live selection only", ids: "JSON array of element IDs" }, example: { path: "Drawings/Flow.excalidraw.md", source: "live", detail: "elements" } },
open: { description: "Explicitly open a ready Excalidraw view; normal drawing scripts can run", fields: { ...target }, example: { path: "Drawings/Flow.excalidraw.md" } },
create: { description: "Create an exact new path using EA's serializer; never overwrite", fields: { ...write, path: target.path, template: "Optional exact drawing template; no picker", elements: "Validated batch of installed Excalidraw skeletons", icons: "Optional array of at most 100 grouped native Lucide icons with unique logical IDs" }, writes: true, example: { requestId: "flow-1", path: "Drawings/Flow.excalidraw.md", elements: [{ id: "a", type: "rectangle", x: 0, y: 0, width: 200, height: 80, label: { text: "Start" } }] } },
@@ -60,6 +61,7 @@ Put large requests in a visible vault-relative JSON file and pass input="<file>"
Requests in files include apiVersion:1; the native command supplies command. The in-process ea.executeCLI request also includes command.
Use exact drawing paths including extensions. Never assume an active drawing. :open explicitly creates a tab and can run configured drawing scripts.
Loop: :read source=live detail=elements (or detail=images to inventory) → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
For selected targets use :selection with an explicit path/view, or the drawing command Copy selected elements for agent. Retain packet IDs (including bound-label IDs), read those IDs at the packet revision, and apply only authorized targets. A stale packet needs inspection and a fresh revision, never guessed replacement IDs.
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY with the same requestId only when refused before execution; unknown outcomes require read-back.
New skeleton IDs are local labels; use returned idMap actual IDs for updates. Updates reject identity, bindings and asset internals.
Every write requires requestId. Repeat the identical effective request to retrieve its receipt; different content with the same ID fails.
@@ -67,6 +69,8 @@ Every write requires requestId. Repeat the identical effective request to retrie
:api surface=ea name=<method> gives existing EA signatures. :api surface=lib lists the supported installed Lib reference; advanced exports remain available to scripts.
:icons query=<name> discovers installed canonical Lucide names (paged); create icons / apply op=lucide insert editable native groups. groupMap maps logical icon aliases to groupId/elementIds; idMap remains single-element only. Defaults: size=96, strokeColor=#1e1e1e, roughness=1, opacity=100; optional strokeWidth is final scene units. No trusted script is required.
:script requires trusted=true and an explicit existing local script file. utils.input contains args; utils.excalidrawLib is the installed runtime. Await all work; completion does not imply saved drawing.
:status ready describes plugin startup. Inspect extras.components for optional service versions, active/compatible flags and requirements; extras may be null during startup. mindMapBuilder reports the resident script API's available/ready flags without starting it or selecting a view.
One-shot ea.addMermaid preflights Extras and rejects unavailable dependencies with DEPENDENCY_UNAVAILABLE instead of opening an activation modal. Inspect any earlier script writes before retrying.
One-shot EA is cleaned up; utility prompts fail INTERACTION_REQUIRED. Trusted code can still invoke other interactive APIs: this is not a sandbox, timeout cancellation or transaction.
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Disk exports require local Vault assets; use a loaded live source or placeholders for remote assets.
For cheap previews: :read detail=images, then :export imagePolicy={"default":"placeholder","rules":[{"ids":["wanted-id"],"mode":"original"}]}. This is lossless for the underlying drawing, not the preview.
+22 -5
View File
@@ -5,7 +5,8 @@ import { nanoid } from "src/constants/constants";
import { CLIError, boolean, number, object, string } from "./cliProtocol";
export const CLI_SHAPES = ["rectangle", "ellipse", "diamond", "text", "arrow", "line", "frame", "stickynote"];
export const CLI_STYLE_FIELDS = ["x", "y", "width", "height", "angle", "strokeColor", "backgroundColor", "fillStyle", "strokeWidth", "strokeStyle", "roughness", "opacity", "locked", "link", "text", "fontSize", "fontFamily", "textAlign", "verticalAlign"];
export const CLI_MAX_LINEAR_POINTS = 1000;
export const CLI_STYLE_FIELDS = ["x", "y", "width", "height", "angle", "strokeColor", "backgroundColor", "fillStyle", "strokeWidth", "strokeStyle", "roughness", "opacity", "locked", "link", "text", "fontSize", "fontFamily", "textAlign", "verticalAlign", "polygon"];
const skeletonFields = new Set([...CLI_STYLE_FIELDS, "id", "type", "roundness", "label", "points", "start", "end", "startArrowhead", "endArrowhead", "children", "name"]);
const arrowheads = ["arrow", "bar", "circle", "circle_outline", "triangle", "triangle_outline", "diamond", "diamond_outline"];
@@ -15,7 +16,7 @@ export function fields(value: Record<string, unknown>, allowed: readonly string[
}
/** Validates the finite assignable style/geometry surface shared by batches and updates. */
export function validateStyle(value: Record<string, unknown>): void {
export function validateStyle(value: Record<string, unknown>, type?: string): void {
for (const key of ["x", "y", "angle"]) if (value[key] !== undefined) number(value[key], key, 0, -1_000_000, 1_000_000);
for (const key of ["width", "height"]) if (value[key] !== undefined) number(value[key], key, 0, 0, 100_000);
for (const [key, min, max] of [["opacity", 0, 100], ["strokeWidth", 0, 100], ["roughness", 0, 3], ["fontSize", 1, 1000], ["fontFamily", 1, 10]] as const) {
@@ -29,6 +30,20 @@ export function validateStyle(value: Record<string, unknown>): void {
if (value.text !== undefined && (typeof value.text !== "string" || value.text.length > 10000)) throw new CLIError("INVALID_INPUT", "Text must be a string of at most 10000 characters.", "text");
if (value.link !== undefined && value.link !== null) string(value.link, "link");
if (value.locked !== undefined) boolean(value.locked, "locked");
if (value.polygon !== undefined) {
boolean(value.polygon, "polygon");
if (type !== undefined && type !== "line") throw new CLIError("INVALID_INPUT", "Polygon applies only to line elements.", "polygon");
}
}
/** Matches the fork's isValidPolygon contract; restoration resets an open path's flag. */
export function validatePolygonPoints(points: unknown): void {
const first: unknown = Array.isArray(points) ? points[0] : null;
const last: unknown = Array.isArray(points) ? points.at(-1) : null;
if (!Array.isArray(points) || points.length < 4 || !Array.isArray(first) || !Array.isArray(last) ||
first[0] !== last[0] || first[1] !== last[1]) {
throw new CLIError("INVALID_INPUT", "Polygon requires at least four points with the last point equal to the first. Close the contour explicitly.", "polygon");
}
}
/** Complete validation precedes conversion; relationship references are batch-local. */
@@ -36,7 +51,7 @@ export function validateBatch(input: unknown): Record<string, unknown>[] {
if (!Array.isArray(input) || input.length > 500) throw new CLIError("INVALID_INPUT", "Expected at most 500 skeletons.", "elements");
const batch = input.map((entry, index) => {
const element = object(entry, `elements[${index}]`);
fields(element, [...skeletonFields]); validateStyle(element);
fields(element, [...skeletonFields]); validateStyle(element, string(element.type, "type"));
if (!CLI_SHAPES.includes(string(element.type, "type"))) throw new CLIError("INVALID_INPUT", "Unsupported skeleton type.", "type");
if (element.type !== "frame") { number(element.x, "x", 0, -1_000_000, 1_000_000); number(element.y, "y", 0, -1_000_000, 1_000_000); }
if (element.type === "text" && typeof element.text !== "string") throw new CLIError("INVALID_INPUT", "Text skeleton requires text.", "text");
@@ -58,12 +73,13 @@ export function validateBatch(input: unknown): Record<string, unknown>[] {
if (roundness.value !== undefined) number(roundness.value, "roundness.value", 0, 0, 1000);
}
if (element.points !== undefined) {
if (!["line", "arrow"].includes(string(element.type, "type")) || !Array.isArray(element.points) || element.points.length < 2 || element.points.length > 100) throw new CLIError("INVALID_INPUT", "Expected 2–100 linear points.", "points");
if (!["line", "arrow"].includes(string(element.type, "type")) || !Array.isArray(element.points) || element.points.length < 2 || element.points.length > CLI_MAX_LINEAR_POINTS) throw new CLIError("INVALID_INPUT", `Expected 2–${CLI_MAX_LINEAR_POINTS} linear points.`, "points");
for (const point of element.points) {
if (!Array.isArray(point) || point.length !== 2) throw new CLIError("INVALID_INPUT", "Expected [x,y] point.", "points");
point.forEach(coordinate => number(coordinate, "points", 0, -100000, 100000));
}
}
if (element.polygon === true) validatePolygonPoints(element.points);
for (const key of ["startArrowhead", "endArrowhead"]) if (element[key] !== undefined) {
if (!["arrow", "line"].includes(string(element.type, "type"))) throw new CLIError("INVALID_INPUT", "Arrowheads require a linear element.", key);
if (element[key] !== null && !arrowheads.includes(string(element[key], key))) throw new CLIError("INVALID_INPUT", "Unknown arrowhead.", key);
@@ -89,6 +105,7 @@ export function validateBatch(input: unknown): Record<string, unknown>[] {
}
} else if (element.children !== undefined) throw new CLIError("INVALID_INPUT", "Children require a frame.", "children");
}
if (batch.reduce((sum, element) => sum + (Array.isArray(element.points) ? element.points.length : 0), 0) > 100000) throw new CLIError("INVALID_INPUT", "Batch exceeds 100000 linear points.", "points");
return batch;
}
@@ -113,7 +130,7 @@ export function constructBatch(input: unknown, lib: NonNullable<Packages["excali
const ids = new Set(elements.map(element => element.id));
if (ids.size !== elements.length || Object.values(idMap).some(id => !ids.has(id)) || elements.some(element => !CLI_SHAPES.includes(element.type) || element.id.length !== 8)) throw new CLIError("INVALID_INPUT", "Converter did not preserve the requested batch identities.", "elements");
for (const element of elements) {
validateStyle(element);
validateStyle(element, element.type);
const references = [...(element.boundElements ?? []).map(bound => bound.id), element.frameId,
...(element.type === "text" ? [element.containerId] : []),
...(element.type === "arrow" ? [element.startBinding?.elementId, element.endBinding?.elementId] : [])].filter(Boolean);
+5 -36
View File
@@ -1,5 +1,6 @@
/** Bounded raster-header inspection before a CLI thumbnail can invoke a decoder. */
import { CLIError } from "./cliProtocol";
import { inspectRasterDimensions } from "src/utils/rasterImageDimensions";
/**
* Accept only formats whose encoded dimensions can be established cheaply.
@@ -16,41 +17,9 @@ export function thumbnailDimensions(url: string): { width: number; height: numbe
return rasterDimensions(bytes);
}
/** Inspect raw PNG/JPEG/WebP headers without asking the browser to decode pixels. */
/** Check the supported formats before invoking a browser decoder. */
export function rasterDimensions(bytes: Uint8Array): { width: number; height: number } {
const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const header = String.fromCharCode(...bytes.subarray(0, 16));
let width = 0, height = 0;
if (header.startsWith("\x89PNG\r\n\x1a\n") && bytes.length >= 24 && header.slice(12, 16) === "IHDR") {
width = data.getUint32(16); height = data.getUint32(20);
} else if (bytes[0] === 0xff && bytes[1] === 0xd8) {
let offset = 2;
while (offset + 4 <= bytes.length) {
if (bytes[offset++] !== 0xff) break;
while (bytes[offset] === 0xff) offset++;
const marker = bytes[offset++];
if (marker === 0xda || marker === 0xd9) break;
if (marker === 0x01 || marker >= 0xd0 && marker <= 0xd7) continue;
if (offset + 2 > bytes.length) break;
const size = data.getUint16(offset);
if (size < 2 || offset + size > bytes.length) break;
if ([0xc0, 0xc1, 0xc2].includes(marker) && size >= 8) {
height = data.getUint16(offset + 3); width = data.getUint16(offset + 5); break;
}
offset += size;
}
} else if (header.startsWith("RIFF") && header.slice(8, 12) === "WEBP" && bytes.length >= 30) {
const kind = header.slice(12, 16);
if (kind === "VP8X" && !(bytes[20] & 2)) {
width = 1 + bytes[24] + bytes[25] * 256 + bytes[26] * 65536;
height = 1 + bytes[27] + bytes[28] * 256 + bytes[29] * 65536;
} else if (kind === "VP8 " && bytes[23] === 0x9d && bytes[24] === 0x01 && bytes[25] === 0x2a) {
width = data.getUint16(26, true) & 0x3fff; height = data.getUint16(28, true) & 0x3fff;
} else if (kind === "VP8L" && bytes[20] === 0x2f) {
const packed = data.getUint32(21, true);
width = 1 + (packed & 0x3fff); height = 1 + ((packed >>> 14) & 0x3fff);
}
}
if (!width || !height || width * height > 16_000_000) throw new CLIError("ASSETS_UNAVAILABLE", "Thumbnail dimensions are unknown or exceed 16 million pixels; choose original or placeholder.");
return { width, height };
const dimensions = inspectRasterDimensions(bytes);
if (!dimensions) throw new CLIError("ASSETS_UNAVAILABLE", "Thumbnail dimensions are unknown or exceed 16 million pixels; choose original or placeholder.");
return dimensions;
}
+7 -3
View File
@@ -2,11 +2,11 @@
import type { CLICommand } from "src/types/excalidrawCliTypes";
import { CLI_COMMANDS } from "./cliCommands";
import { CLI_OPERATION_FIELDS } from "./cliApply";
import { CLI_SHAPES, CLI_STYLE_FIELDS } from "./cliElements";
import { CLI_MAX_LINEAR_POINTS, CLI_SHAPES, CLI_STYLE_FIELDS } from "./cliElements";
import { CLI_ICON_FIELDS } from "./cliIcons";
const required: Partial<Record<CLICommand, string[]>> = {
schema: ["action"], read: ["path"], open: ["path"], create: ["requestId", "path"],
schema: ["action"], read: ["path"], selection: ["path"], open: ["path"], create: ["requestId", "path"],
apply: ["requestId", "path", "expectedRevision", "operations"], export: ["requestId", "path", "out"],
script: ["requestId", "script", "trusted"], result: ["requestId"],
};
@@ -16,6 +16,10 @@ const operationRequired: Record<string, string[]> = {
group: ["ids"], ungroup: ["ids", "groupId"], image: ["asset"], imageMetadata: ["id"], latex: ["text"],
};
function property(name: string): Record<string, unknown> {
if (name === "x") return { type: "number", description: "For text skeletons, x is the left/center/right alignment anchor according to textAlign. Existing-element updates use the scene element's x coordinate." };
if (name === "polygon") return { type: "boolean", description: "Line elements only. True requires at least four points, last equal to first; the CLI does not reshape the path. False retains regular line semantics; a closed path can still fill from backgroundColor." };
if (name === "anchor") return { type: "boolean", default: true, description: "With scale=false, anchor the image/drawing embed to 100% of its source size. With scale=true this option has no effect." };
if (name === "asset") return { type: "string", description: "Exact vault path of a raster image, SVG or plugin-recognized Excalidraw drawing (including .excalidraw.md). Ordinary Markdown notes and self-embeds are refused." };
if (["x", "y", "size", "width", "height", "angle", "fontSize", "fontFamily", "opacity", "strokeWidth", "roughness", "offset", "limit", "padding", "scale", "scaleX", "scaleY", "maxWidth", "maxHeight", "maxPixels", "maxArtifactBytes"].includes(name)) return { type: "number" };
if (name === "icons") return { type: "array", maxItems: 100, items: { type: "object", required: ["id", "icon"], additionalProperties: false, properties: Object.fromEntries(CLI_ICON_FIELDS.map(field => [field, property(field)])) } };
if (["overwrite", "trusted", "selectedOnly", "locked"].includes(name)) return { type: "boolean" };
@@ -45,7 +49,7 @@ function property(name: string): Record<string, unknown> {
};
if (name === "tags") return { anyOf: [{ type: "null" }, { type: "array", maxItems: 12, uniqueItems: true, items: { type: "string", maxLength: 32 } }] };
if (["area", "roundness", "label", "start", "end"].includes(name)) return { type: "object" };
if (name === "points") return { type: "array", minItems: 2, maxItems: 100, items: { type: "array", minItems: 2, maxItems: 2, items: { type: "number" } } };
if (name === "points") return { type: "array", minItems: 2, maxItems: CLI_MAX_LINEAR_POINTS, description: "Line/arrow contour points; up to 100000 points across a skeleton batch.", items: { type: "array", minItems: 2, maxItems: 2, items: { type: "number" } } };
if (name === "link") return { type: ["string", "null"] };
return { type: "string" };
}
+14
View File
@@ -0,0 +1,14 @@
/** Invocation identity stays with the one-shot EA, never a shared current-script flag. */
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
const cliScripts = new WeakSet<ExcalidrawAutomate>();
/** Whether an EA belongs to a currently executing native CLI script. */
export const isCLIScript = (ea: ExcalidrawAutomate): boolean => cliScripts.has(ea);
/** Releases the invocation marker even when execution or result serialization fails. */
export async function withCLIScriptContext<T>(ea: ExcalidrawAutomate, run: () => Promise<T>): Promise<T> {
cliScripts.add(ea);
try { return await run(); }
finally { cliScripts.delete(ea); }
}
+5 -1
View File
@@ -5,6 +5,7 @@ import type { ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
import { CLIError, boolean, jsonValue, vaultPath } from "./cliProtocol";
import { drawingFile, drawingView, liveIdentity } from "./cliTarget";
import { sameCLIIdentity } from "./cliIdentity";
import { withCLIScriptContext } from "./cliScriptContext";
/** Source content participates in the effective request identity, including cached scripts. */
export async function prepareScript(cli: ExcalidrawCLI, request: Record<string, unknown>) {
@@ -35,10 +36,13 @@ export async function executeScript(cli: ExcalidrawCLI, request: Record<string,
const outcome: Partial<ExcalidrawCLIResult> = { mutation: "unknown", persistence: "unknown", ...(view ? { target: { vault: plugin.app.vault.getName(), path: drawing.path, viewId: view.id } } : {}) };
let started = false;
try {
const value = await plugin.scriptEngine.executeScriptFileForCLI(prepared.file, view ?? undefined, ea, request.args ?? null, plugin.getCLIRuntime(), prepared.source, () => { check(); started = true; });
const value = await withCLIScriptContext(ea, () => plugin.scriptEngine.executeScriptFileForCLI(prepared.file, view ?? undefined, ea, request.args ?? null, plugin.getCLIRuntime(), prepared.source, () => { check(); started = true; }));
return { ...outcome, data: jsonValue(value === undefined ? null : value), warnings: ["Script completion does not verify drawing persistence. Trusted scripts must await their writes and saves."] };
} catch (error) {
if (!started && error instanceof CLIError) throw error;
if (error instanceof CLIError && error.code === "DEPENDENCY_UNAVAILABLE") {
throw new CLIError(error.code, error.message, error.field, error.recovery, outcome);
}
const interaction = error instanceof Error && error.message.startsWith("INTERACTION_REQUIRED:");
throw new CLIError(interaction ? "INTERACTION_REQUIRED" : started ? "OUTCOME_UNKNOWN" : "SCRIPT_FAILED", interaction ? error.message : "Script execution or result serialization failed.", undefined, "Inspect drawing/output before retrying; script side effects cannot be rolled back.", started ? outcome : {});
}
+41
View File
@@ -0,0 +1,41 @@
/** Stable selection handoff uses the existing live revision and never changes the scene. */
import type ExcalidrawPlugin from "src/core/main";
import type ExcalidrawView from "src/view/ExcalidrawView";
import type { ExcalidrawCLI } from "src/core/managers/ExcalidrawCLI";
import { CLIError } from "./cliProtocol";
/** Capture selected elements plus their bound labels before focus/selection can change. */
export function selectionPacket(cli: ExcalidrawCLI, view: ExcalidrawView) {
const revision = cli.targets.revision(view);
const all = view.excalidrawAPI.getSceneElements().filter(element => !element.isDeleted);
const byId = new Map(all.map(element => [element.id, element]));
const selected = view.excalidrawAPI.getAppState().selectedElementIds;
const included = new Set(all.filter(element => selected[element.id]).map(element => element.id));
if (!included.size) throw new CLIError("INVALID_INPUT", "Select elements in the requested live drawing first.");
for (const id of [...included]) {
for (const bound of byId.get(id).boundElements ?? []) {
if (bound.type === "text" && byId.get(bound.id)?.type === "text") included.add(bound.id);
}
}
if (included.size > 500) throw new CLIError("INVALID_INPUT", "Select at most 500 elements including bound labels.");
const lib = cli.plugin.getCLIRuntime();
const elements = all.filter(element => included.has(element.id)).map(element => {
const labelId = element.boundElements?.find(bound => bound.type === "text" && included.has(bound.id))?.id ?? null;
const label = labelId ? byId.get(labelId) : null;
const text = element.type === "text" ? element.originalText ?? element.text : label?.type === "text" ? label.originalText ?? label.text : null;
const bounds = lib.getCommonBounds([element]);
if (!bounds.every(Number.isFinite)) throw new CLIError("INVALID_INPUT", "Selection contains invalid bounds.");
return { id: element.id, type: element.type, selected: selected[element.id] === true, text,
frameId: element.frameId ?? null, containerId: element.type === "text" ? element.containerId ?? null : null, labelId, bounds };
});
return { packetVersion: 1, vault: cli.plugin.app.vault.getName(), path: view.file.path, view: view.id, revision, elements };
}
/** Copy only the packet captured for the command's original view, using its owning clipboard. */
export async function copySelectionPacket(plugin: ExcalidrawPlugin, view: ExcalidrawView): Promise<void> {
const clipboard = view.containerEl.ownerDocument.defaultView?.navigator.clipboard;
if (!clipboard) throw new Error("Clipboard unavailable");
const result = await plugin.executeCLI({ apiVersion: 1, command: "selection", path: view.file.path, view: view.id });
if (!result.ok) throw new Error("Selection could not be captured");
await clipboard.writeText(JSON.stringify(result.data, null, 2));
}
+9
View File
@@ -0,0 +1,9 @@
/** Optional script readiness is separate from plugin startup and never starts a script. */
export function mindMapBuilderStatus() {
// This separately installed script has no package declaration to import.
const api = Object.getOwnPropertyDescriptor(window, "MindMapBuilderAPI")?.value as
{ ready?: () => boolean } | undefined;
const available = typeof api?.ready === "function";
try { return { available, ready: available && api.ready() === true }; }
catch { return { available, ready: false }; }
}
+2 -1
View File
@@ -2,6 +2,7 @@ import { Extension } from "@codemirror/state";
import ExcalidrawPlugin from "src/core/main";
import { HideTextBetweenCommentsExtension } from "./Fadeout";
import { createDrawingEmbedExtension } from "./drawingEmbedExtension";
import { visualResourceDropExtension } from "./visualResourceDropExtension";
export const EDITOR_FADEOUT = "fadeOutExcalidrawMarkup";
type TaggedExtension = Extension & { exID?: string };
@@ -24,7 +25,7 @@ export class EditorHandler {
setup(): void {
const drawingEmbeds = createDrawingEmbedExtension(this.plugin);
this.activeEditorExtensions.push(drawingEmbeds.extension);
this.activeEditorExtensions.push(drawingEmbeds.extension, visualResourceDropExtension(this.plugin));
this.disposeDrawingEmbeds = drawingEmbeds.dispose;
this.plugin.registerEditorExtension(this.activeEditorExtensions);
this.updateCMExtensionState(
@@ -0,0 +1,36 @@
import { Prec } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { editorInfoField, MarkdownView } from "obsidian";
import type ExcalidrawPlugin from "../main";
/** Accept the resource browser's own drag in the Markdown editor under the pointer. */
export function visualResourceDropExtension(plugin: ExcalidrawPlugin) {
const accepting = (event: DragEvent, editor: EditorView) => {
const info = editor.state.field(editorInfoField, false);
const service = plugin.visualResources;
if (event.defaultPrevented || editor.state.readOnly || !(info instanceof MarkdownView) ||
info.getMode() !== "source" || !info.file || !event.dataTransfer ||
!service?.canDropInMarkdown(event.dataTransfer, info.file)) return null;
return { file: info.file, transfer: event.dataTransfer, service };
};
return Prec.high(EditorView.domEventHandlers({
dragover(event, editor) {
if (!accepting(event, editor)) return false;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
return true;
},
drop(event, editor) {
const target = accepting(event, editor);
if (!target) return false;
const position = editor.posAtCoords({ x: event.clientX, y: event.clientY }, false);
if (position === null) return false;
const link = target.service.markdownDrop(target.transfer, target.file);
if (!link) return false;
event.preventDefault();
editor.dispatch({ changes: { from: position, insert: link }, selection: { anchor: position + link.length }, userEvent: "input.drop" });
editor.focus();
return true;
},
}));
}
+1
View File
@@ -23,6 +23,7 @@ export type { Point } from "src/types/types";
export type { MathJaxRenderOptions } from "src/types/mathJaxTypes";
export type { LucideIconOptions, LucideIconResult, LucideIconEntry } from "src/types/lucideTypes";
export type { ExcalidrawCLIRequest, ExcalidrawCLIResult, CLICommand, CLIJSON } from "src/types/excalidrawCliTypes";
export type { StrokeConversionOptions, StrokeConversionResult, ConcatenateLinesOptions, ConcatenateLinesResult } from "src/types/strokeConversionTypes";
export const getEA = (view?: ExcalidrawView): ExcalidrawAutomate | null => {
try {
return window.ExcalidrawAutomate.getAPI(view);
+28 -1
View File
@@ -99,9 +99,12 @@ import { ObserverManager } from "./managers/ObserverManager";
import { PackageManager } from "./managers/PackageManager";
import { MonkeyPatchManager } from "./managers/MonkeyPatchManager";
import ExcalidrawView from "../view/ExcalidrawView";
import { isCanvasFlowchartNavigationShortcut } from "../view/managers/flowchartNavigationShortcut";
import { ExcalidrawSidepanelView } from "../view/sidepanel/Sidepanel";
import { CommandManager } from "./managers/CommandManager";
import { LucideIconPicker } from "src/view/sidepanel/LucideIconPicker";
import { VisualResources } from "src/shared/visualResources/VisualResources";
import { VisualResourcePanel } from "src/view/sidepanel/VisualResourcePanel";
import type { ObsidianExcalidrawHostAdapter } from "@zsviczian/excalidraw/types/excalidraw/obsidianExcalidrawHost";
import { EventManager } from "./managers/EventManager";
import { UniversalInsertFileModal } from "src/shared/Dialogs/UniversalInsertFileModal";
@@ -180,6 +183,8 @@ export default class ExcalidrawPlugin extends Plugin {
private monkeyPatchManager: MonkeyPatchManager;
private commandManager: CommandManager;
public lucidePicker: LucideIconPicker;
public visualResources: VisualResources;
public visualResourcePanel: VisualResourcePanel;
private eventManager: EventManager;
private settingsManager: PluginSettingsManager;
private settingsTab: ExcalidrawSettingTab;
@@ -532,6 +537,8 @@ export default class ExcalidrawPlugin extends Plugin {
this.commandManager = new CommandManager(this);
this.lucidePicker = new LucideIconPicker(this);
this.stencilLibraryManager = new StencilLibraryManager(this);
this.visualResources = new VisualResources(this);
this.visualResourcePanel = new VisualResourcePanel(this);
try {
initCompressionWorker();
@@ -787,7 +794,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
private async actionRibbonClick(e: MouseEvent) {
await this.createAndOpenDrawing(
await this.createAndOpenInteractiveDrawing(
getDrawingFilename(this.settings),
linkClickModifierType(emulateCTRLClickForLinks(e)),
);
@@ -951,6 +958,13 @@ export default class ExcalidrawPlugin extends Plugin {
// Force handlers to the front of the list
overrideHandlers.forEach(() => scope.keys.unshift(scope.keys.pop()));
// A wildcard may decline unrelated keys; an explicit key handler cannot.
// Claim only canvas navigation so core editor shortcuts cannot swallow it.
const flowchartHandler = scope.register(null, null, (event) => {
if (isCanvasFlowchartNavigationShortcut(this.activeExcalidrawView, event)) return true;
});
scope.keys.unshift(scope.keys.pop());
const handler_ctrlF = scope.register(["Mod"], "f", () => true);
scope.keys.unshift(scope.keys.pop()); // Force our handler to the front of the list
const forceSaveCommand = this.commandManager?.forceSaveCommand;
@@ -966,6 +980,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
this.popScope = () => {
overrideHandlers.forEach((handler) => scope.unregister(handler));
scope.unregister(flowchartHandler);
scope.unregister(handler_ctrlF);
if (saveHandler) {
scope.unregister(saveHandler);
@@ -1158,6 +1173,11 @@ export default class ExcalidrawPlugin extends Plugin {
return this.fileManager.prepareDrawing();
}
/** Prepare a new interactive drawing before a file or leaf is created. */
public prepareInteractiveDrawing(forceFramework = false): Promise<PreparedDrawing> {
return this.fileManager.prepareInteractiveDrawing(forceFramework);
}
public async createDrawing(
filename: string,
foldername?: string,
@@ -1224,6 +1244,13 @@ export default class ExcalidrawPlugin extends Plugin {
return file.path;
}
/** Create a drawing from an interactive UI entry point, including the optional framework prompt. */
public async createAndOpenInteractiveDrawing(filename: string, location: PaneTarget, foldername?: string): Promise<string> {
const prepared = await this.prepareInteractiveDrawing();
if (prepared.kind === "cancel") return "";
return this.createAndOpenDrawing(filename, location, foldername, prepared.data);
}
public async setMarkdownView(
leaf: WorkspaceLeaf,
eState?: ViewStateResult,
+37 -6
View File
@@ -36,6 +36,7 @@ import { ExcalidrawAutomate } from "../../shared/ExcalidrawAutomate";
import { search } from "src/utils/excalidrawAutomateUtils";
import { selectDrawingTemplate } from "../../shared/Dialogs/TemplatePrompt";
import { t } from "../../lang/helpers";
import { copySelectionPacket } from "src/core/cli/cliSelection";
import {
createOrOverwriteFile,
getAliasWithSize,
@@ -200,7 +201,7 @@ export class CommandManager {
file.path.substring(0, file.path.lastIndexOf(file.name)),
);
}
void this.plugin.createAndOpenDrawing(
void this.plugin.createAndOpenInteractiveDrawing(
getDrawingFilename(this.settings),
linkClickModifierType(emulateCTRLClickForLinks(e)),
folderpath,
@@ -553,6 +554,25 @@ export class CommandManager {
callback: () => { void this.plugin.lucidePicker.open(this.plugin.activeExcalidrawView); },
});
this.addCommand({
id: "visual-resources",
name: t("VR_TITLE"),
callback: () => { void this.plugin.visualResourcePanel.openFromWorkspace(); },
});
this.addCommand({
id: "visual-resources-icons",
name: t("VR_ICON_LIBRARY"),
callback: () => { void this.plugin.visualResourcePanel.openFromWorkspace("Icon Library"); },
});
this.addCommand({
id: "thinking-frameworks-new-drawing",
name: t("VR_NEW_WITH_FRAMEWORK"),
callback: async () => {
const prepared = await this.plugin.prepareInteractiveDrawing(true);
if (prepared.kind === "ready") await this.plugin.createAndOpenDrawing(getDrawingFilename(this.settings), "new-tab", undefined, prepared.data);
},
});
this.addCommand({
id: "excalidraw-open",
name: t("OPEN_EXISTING_NEW_PANE"),
@@ -606,7 +626,7 @@ export class CommandManager {
id: "excalidraw-autocreate",
name: t("NEW_IN_NEW_PANE"),
callback: () => {
void this.plugin.createAndOpenDrawing(
void this.plugin.createAndOpenInteractiveDrawing(
getDrawingFilename(this.settings),
"new-pane",
);
@@ -617,7 +637,7 @@ export class CommandManager {
id: "excalidraw-autocreate-newtab",
name: t("NEW_IN_NEW_TAB"),
callback: () => {
void this.plugin.createAndOpenDrawing(
void this.plugin.createAndOpenInteractiveDrawing(
getDrawingFilename(this.settings),
"new-tab",
);
@@ -628,7 +648,7 @@ export class CommandManager {
id: "excalidraw-autocreate-on-current",
name: t("NEW_IN_ACTIVE_PANE"),
callback: () => {
void this.plugin.createAndOpenDrawing(
void this.plugin.createAndOpenInteractiveDrawing(
getDrawingFilename(this.settings),
"active-pane",
);
@@ -642,7 +662,7 @@ export class CommandManager {
if (checking) {
return !DEVICE.isMobile;
}
void this.plugin.createAndOpenDrawing(
void this.plugin.createAndOpenInteractiveDrawing(
getDrawingFilename(this.settings),
"popout-window",
);
@@ -658,7 +678,7 @@ export class CommandManager {
activeView.file.basename,
this.settings,
);
const prepared = await this.plugin.prepareDrawing();
const prepared = await this.plugin.prepareInteractiveDrawing();
if (prepared.kind === "cancel") return;
const folder = this.settings.embedUseExcalidrawFolder
? null
@@ -912,6 +932,17 @@ export class CommandManager {
},
});
this.addCommand({
id: "copy-selection-for-agent",
name: t("CLI_COPY_SELECTION"),
checkCallback: (checking: boolean) => {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (!view?.excalidrawAPI || !view.getViewSelectedElements().length) return false;
if (!checking) void copySelectionPacket(this.plugin, view).catch(() => new Notice(t("CLI_COPY_SELECTION_ERROR")));
return true;
},
});
this.addCommand({
id: "disable-frameclipping",
name: t("TOGGLE_FRAME_CLIPPING"),
+1 -1
View File
@@ -57,7 +57,7 @@ export class DrawingCreationUI extends Component {
pending = true; button.disabled = true;
this.plugin.app.workspace.setActiveLeaf(leaf, { focus: true });
// Same folder, format and template-selection path as the existing command.
void this.plugin.createAndOpenDrawing(getDrawingFilename(this.plugin.settings), "active-pane")
void this.plugin.createAndOpenInteractiveDrawing(getDrawingFilename(this.plugin.settings), "active-pane")
.catch((error: unknown) => errorlog({ where: "DrawingCreationUI.createAndOpenDrawing", error }))
.finally(() => { pending = false; button.disabled = false; });
});
+8 -1
View File
@@ -14,6 +14,8 @@ import { commandSchema } from "src/core/cli/cliSchema";
import { imageInventory } from "src/core/cli/cliImages";
import { nanoid } from "src/constants/constants";
import { getLucideIcons } from "src/shared/lucideIcons";
import { mindMapBuilderStatus } from "src/core/cli/cliStatus";
import { selectionPacket } from "src/core/cli/cliSelection";
type Receipt = { fingerprint: string; result: ExcalidrawCLIResult; finishedAt?: number; preExecutionBusy?: boolean };
@@ -178,7 +180,7 @@ export class ExcalidrawCLI {
if (request.format !== undefined && !["json", "markdown"].includes(string(request.format, "format"))) throw new CLIError("INVALID_INPUT", "Expected json or markdown.", "format");
return { markdown: CLI_SKILL };
}
if (command === "status") return { apiVersion: 1, nativeCLI: Platform.isDesktop && requireApiVersion("1.12.2") && typeof (plugin as ExcalidrawPlugin & Partial<ObsidianCliRuntime>).registerCliHandler === "function", ready: plugin.isReady, vault: plugin.app.vault.getName(), version: plugin.manifest.version, converter: plugin.isReady && typeof plugin.getCLIRuntime().convertToExcalidrawElements === "function", lucideIcons: plugin.isReady, receiptTTLSeconds: 900, receiptCapacity: 128 };
if (command === "status") return { apiVersion: 1, nativeCLI: Platform.isDesktop && requireApiVersion("1.12.2") && typeof (plugin as ExcalidrawPlugin & Partial<ObsidianCliRuntime>).registerCliHandler === "function", ready: plugin.isReady, vault: plugin.app.vault.getName(), version: plugin.manifest.version, converter: plugin.isReady && typeof plugin.getCLIRuntime().convertToExcalidrawElements === "function", lucideIcons: plugin.isReady, extras: plugin.extrasGateway?.getStatus() ?? null, mindMapBuilder: mindMapBuilderStatus(), receiptTTLSeconds: 900, receiptCapacity: 128 };
if (command === "schema") {
const action = string(request.action, "action");
if (!Object.hasOwn(CLI_COMMANDS, action)) throw new CLIError("UNSUPPORTED_COMMAND", "Unknown action.", "action");
@@ -192,6 +194,11 @@ export class ExcalidrawCLI {
return { surface, subset: surface === "lib", entries: entries.filter(entry => request.name ? entry.name.toLowerCase() === query : `${entry.name} ${entry.description}`.toLowerCase().includes(query)).slice(0, 20) };
}
if (!plugin.isReady) throw new CLIError("NOT_READY", "Excalidraw is still initializing.", undefined, "Retry status after startup.");
if (command === "selection") {
const file = drawingFile(plugin, request.path), view = drawingView(plugin, file, request.view);
if (!view) throw new CLIError("NOT_READY", "Selection requires an open live drawing.", "path");
return selectionPacket(this, view);
}
if (command === "icons") {
const query = request.query === undefined ? "" : request.query;
if (typeof query !== "string" || query.length > 128) throw new CLIError("INVALID_INPUT", "Expected an icon query of at most 128 characters.", "query");
+45 -7
View File
@@ -1,4 +1,6 @@
import type { ExactDrawingCreationOptions, PreparedDrawing } from "src/types/drawingCreationTypes";
import type { LibraryItem } from "@zsviczian/excalidraw/types/excalidraw/types";
import { ThinkingFrameworksPicker } from "src/shared/Dialogs/ThinkingFrameworksPicker";
import {
App,
FrontMatterCache,
@@ -60,6 +62,8 @@ export class PluginFileManager {
private plugin: ExcalidrawPlugin;
private app: App;
private excalidrawFiles: Set<TFile> = new Set<TFile>();
private frameworkPickers = new Set<ThinkingFrameworksPicker>();
private disposed = false;
get settings() {
return this.plugin.settings;
@@ -135,6 +139,9 @@ export class PluginFileManager {
}
public destroy() {
this.disposed = true;
for (const picker of this.frameworkPickers) picker.close();
this.frameworkPickers.clear();
this.excalidrawFiles.clear();
}
@@ -188,12 +195,39 @@ export class PluginFileManager {
}
public async prepareDrawing(): Promise<PreparedDrawing> {
const selection = await selectDrawingTemplate(getListOfTemplateFiles(this.plugin), this.app, normalizePath(this.settings.templateFilePath));
const selection = await this.selectTemplate();
if (selection.kind === "cancel") return selection;
return { kind: "ready", data: await this.getDrawingContent(selection.kind === "template" ? selection.file : undefined) };
}
private async getDrawingContent(template?: TFile): Promise<string> {
/** Resolve all prompts before the interactive creation path touches the vault or workspace. */
public async prepareInteractiveDrawing(forceFramework = false): Promise<PreparedDrawing> {
if (this.disposed) return { kind: "cancel" };
if (!forceFramework) {
const selection = await this.selectTemplate();
if (selection.kind === "cancel") return selection;
if (selection.kind === "template") return { kind: "ready", data: await this.getDrawingContent(selection.file) };
if (!this.settings.frameworksOnBlank || this.settings.frameworksSnoozedUntil > Date.now() || !this.plugin.visualResources) {
return { kind: "ready", data: await this.getDrawingContent() };
}
}
const picker = new ThinkingFrameworksPicker(this.plugin);
this.frameworkPickers.add(picker);
try {
picker.open();
const choice = await picker.result;
if (this.disposed || choice.kind === "cancel") return { kind: "cancel" };
return { kind: "ready", data: await this.getDrawingContent(undefined, choice.kind === "framework" ? choice.item : undefined) };
} finally { this.frameworkPickers.delete(picker); }
}
private async selectTemplate() {
if (this.disposed) return { kind: "cancel" } as const;
const selection = await selectDrawingTemplate(getListOfTemplateFiles(this.plugin), this.app, normalizePath(this.settings.templateFilePath));
return this.disposed ? { kind: "cancel" } as const : selection;
}
private async getDrawingContent(template?: TFile, framework?: LibraryItem): Promise<string> {
if (template) {
if (
(template.extension == "md" && !this.settings.compatibilityMode) ||
@@ -208,15 +242,19 @@ export class PluginFileManager {
}
}
}
if (this.settings.compatibilityMode) {
return this.settings.matchTheme && isObsidianThemeDark()
? DARK_BLANK_DRAWING
: BLANK_DRAWING;
}
const blank =
this.settings.matchTheme && isObsidianThemeDark()
? DARK_BLANK_DRAWING
: BLANK_DRAWING;
if (framework) {
const scene = { ...JSON_parse<object>(blank), elements: framework.elements };
const json = JSON.stringify(scene);
if (this.settings.compatibilityMode) return json;
const text = framework.elements.filter(element => element.type === "text")
.map(element => (element.rawText ?? element.originalText ?? element.text) + " ^" + element.id + "\n\n").join("");
return FRONTMATTER + "\n# Excalidraw Data\n\n## Text Elements\n" + text + "\n" + getMarkdownDrawingSection(json, this.settings.compress);
}
if (this.settings.compatibilityMode) return blank;
return `${FRONTMATTER}\n${getMarkdownDrawingSection(
blank,
this.settings.compress,
+4 -1
View File
@@ -85,7 +85,10 @@ export class FontManager {
* and registers custom font metrics with the shared Excalidraw runtime.
*/
public async initializeFonts(): Promise<void> {
const cjkFontFaceData = await getCJKFontFaceData(this.plugin);
const cjkFontFaceData = await getCJKFontFaceData(
this.plugin,
this.getRuntimePackage().excalidrawLib.Fonts,
);
if (cjkFontFaceData === false) {
new Notice(
t("FONTS_LOAD_ERROR") + this.plugin.settings.fontAssetsPath,
+26 -27
View File
@@ -38,6 +38,7 @@ import {
isObsidianThemeDark,
getFileCSSClasses,
getSafeFrontmatter,
type ValidFrontmatter,
} from "../../utils/obsidianUtils";
import { linkClickModifierType } from "../../utils/modifierkeyHelper";
import { ImageKey, getImageCache } from "../../shared/ImageCache";
@@ -897,9 +898,12 @@ const resolveEmbedTarget = (src: string, sourcePath: string): TFile | null => {
return isExplicitImageEmbed(src) ? vault.getFileByPath(sourcePath) : null;
};
const embedsMarkdown = (file: TFile): boolean => {
const frontmatter = getSafeFrontmatter(metadataCache.getFileCache(file)?.frontmatter);
return Boolean(frontmatter["excalidraw-open-md"] || frontmatter["excalidraw-embed-md"]);
const getCachedFrontmatter = (file: TFile | null): ValidFrontmatter =>
getSafeFrontmatter(file && metadataCache.getFileCache(file)?.frontmatter);
const showsMarkdownInHover = (frontmatter: ValidFrontmatter): boolean => {
return Boolean(frontmatter["excalidraw-embed-md"] ||
(frontmatter["excalidraw-open-md"] && !plugin.settings.renderImageInHoverPreviewForMDNotes));
};
const getDrawingImageTarget = (embed: Element, sourcePath: string): TFile | null => {
@@ -907,7 +911,7 @@ const getDrawingImageTarget = (embed: Element, sourcePath: string): TFile | null
const file = resolveEmbedTarget(src, sourcePath);
if (!file || !(file instanceof TFile) || !plugin.isExcalidrawFile(file)) return null;
if (isTextOnlyEmbed(embed)) return null;
if (embedsMarkdown(file) && !isExplicitImageEmbed(src)) return null;
if (getCachedFrontmatter(file)["excalidraw-embed-md"] && !isExplicitImageEmbed(src)) return null;
return file;
};
@@ -1098,21 +1102,12 @@ const tmpObsidianWYSIWYG = async (
return; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/835
}
const safeFrontmatter = getSafeFrontmatter(ctx.frontmatter);
if (
(safeFrontmatter["excalidraw-open-md"] || safeFrontmatter["excalidraw-embed-md"] || embedsMarkdown(file)) &&
!(internalEmbedDiv.hasClass("internal-embed") && isExplicitImageEmbed(internalEmbedDiv.getAttribute("src")))
) {
return;
}
if (!plugin.settings.renderImageInHoverPreviewForMDNotes) {
//const isHoverPopover = internalEmbedDiv.parentElement?.hasClass("hover-popover");
const safeFrontmatter = getSafeFrontmatter(ctx.frontmatter);
const shouldOpenMD = Boolean(safeFrontmatter["excalidraw-open-md"]);
if (isHoverPopover && shouldOpenMD) {
return;
}
const frontmatter = ctx.frontmatter ? getSafeFrontmatter(ctx.frontmatter) : getCachedFrontmatter(file);
const isInternalEmbed = internalEmbedDiv.hasClass("internal-embed");
if (!isInternalEmbed) {
const showMarkdown = isHoverPopover ? showsMarkdownInHover(frontmatter) :
frontmatter["excalidraw-open-md"] || frontmatter["excalidraw-embed-md"];
if (showMarkdown) return;
}
//const isPrinting = Boolean(internalEmbedDiv.hasClass("print"));
@@ -1129,7 +1124,7 @@ const tmpObsidianWYSIWYG = async (
const markdownEmbed = internalEmbedDiv.hasClass("markdown-embed");
const markdownReadingView = isPrinting || isMarkdownReadingMode; //internalEmbedDiv.hasClass("markdown-reading-view")
if (
!internalEmbedDiv.hasClass("internal-embed") &&
!isInternalEmbed &&
(markdownEmbed || markdownReadingView)
) {
if (isPrinting) {
@@ -1263,6 +1258,8 @@ const tmpObsidianWYSIWYG = async (
) {
return;
}
const targetFrontmatter = embedTargetFile === file ? frontmatter : getCachedFrontmatter(embedTargetFile);
if (targetFrontmatter["excalidraw-embed-md"] && !isExplicitImageEmbed(embedSrc)) return;
const currentPlugin = plugin;
await renderMarkdownEmbed(el, internalEmbedDiv, ctx, {
@@ -1331,10 +1328,10 @@ export const markdownPostProcessor = async (
containerEl && getParentOfClass(containerEl, "hover-popover"),
);
const safeFrontmatter = getSafeFrontmatter(ctx.frontmatter);
const isPreview =
isHoverPopover &&
Boolean(safeFrontmatter["excalidraw-open-md"]) &&
!plugin.settings.renderImageInHoverPreviewForMDNotes;
const isInternalEmbed = Boolean(containerEl?.closest(".internal-embed"));
const isMarkdownHover = isHoverPopover && !isInternalEmbed && showsMarkdownInHover(
ctx.frontmatter ? safeFrontmatter : getCachedFrontmatter(vault.getFileByPath(ctx.sourcePath)),
);
//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
@@ -1357,7 +1354,7 @@ export const markdownPostProcessor = async (
return;
}
if (!isPreview && embeddedItems.length === 0) {
if (!isMarkdownHover && embeddedItems.length === 0) {
if (isFrontmatter) {
docIDs.add(ctx.docId);
} else {
@@ -1385,8 +1382,10 @@ export const markdownPostProcessor = async (
//transcluded text element or some other transcluded content inside the Excalidraw file
//in reading mode these elements should be hidden
const excalidrawFile = Boolean(safeFrontmatter["excalidraw-plugin"]);
if (!(isPreview || isMarkdownReadingMode || isPrinting) && excalidrawFile) {
if (!(safeFrontmatter["excalidraw-open-md"] || safeFrontmatter["excalidraw-embed-md"])) {
if (!(isMarkdownReadingMode || isPrinting) && excalidrawFile) {
const showMarkdown = isMarkdownHover || safeFrontmatter["excalidraw-embed-md"] ||
(!isInternalEmbed && !isHoverPopover && safeFrontmatter["excalidraw-open-md"]);
if (!showMarkdown) {
setElementDisplay(el, "none");
return;
}
@@ -208,6 +208,11 @@ export class PluginSettingsManager {
DEFAULT_SETTINGS,
decryptedSettings,
);
// UI filters and the catalog's installed revisions are mutated through the
// normal settings writer. Give each loaded instance its own records.
this.host.settings.visualResources = { ...this.host.settings.visualResources };
this.host.settings.frameworkInstalls = { ...this.host.settings.frameworkInstalls };
if (!Array.isArray(this.host.settings.frameworkCatalog)) this.host.settings.frameworkCatalog = [];
if (typeof decryptedSettings.libraryStorageMode === "undefined") {
const legacyLibrary: unknown =
typeof decryptedSettings.library === "string" &&
+187 -16
View File
@@ -43,10 +43,12 @@ export class StencilLibraryManager {
private migrationPrompt: Promise<void> | null = null;
private saveQueue: Promise<void> = Promise.resolve();
private reloadTimer: number | null = null;
private readonly ownWritePaths = new Set<string>();
private readonly ownWritePaths = new Map<string, number>();
private isUpdatingOpenViews = false;
private readonly ownerWindow: Window;
constructor(private readonly plugin: ExcalidrawPlugin) {
this.ownerWindow = plugin.app.workspace.containerEl.ownerDocument.defaultView;
const handleLibraryFileChange = (file: { path: string }) => {
if (
file.path.startsWith(`${this.getFolderPath()}/`) &&
@@ -78,8 +80,10 @@ export class StencilLibraryManager {
);
plugin.register(() => {
if (this.reloadTimer !== null) {
window.clearTimeout(this.reloadTimer);
this.ownerWindow.clearTimeout(this.reloadTimer);
}
for (const timeout of this.ownWritePaths.values()) this.ownerWindow.clearTimeout(timeout);
this.ownWritePaths.clear();
});
}
@@ -121,12 +125,177 @@ export class StencilLibraryManager {
if (this.isUpdatingOpenViews) {
return;
}
await this.queueSave(() => this.plugin.settings.libraryStorageMode === "data-json"
? this.plugin.setLegacyStencilLibrary(this.createFileData(items))
: this.persistChanges(items));
}
/** Read the effective items, their owners, and the valid destination libraries. */
public async getResourceLibraries(): Promise<{
items: Array<{ item: LibraryItem; path: string | undefined }>;
paths: string[];
defaultPath?: string;
}> {
await this.saveQueue;
if (this.plugin.settings.libraryStorageMode === "data-json") {
await this.plugin.setLegacyStencilLibrary(this.createFileData(items));
const items = restoreLibraryItems(getLibraryItems(this.plugin.getLegacyStencilLibrary()), "unpublished");
const owned = items.map<{ item: LibraryItem; path: string | undefined }>(item => ({ item, path: undefined }));
return { items: owned, paths: [] };
}
await this.ensureLoaded();
const defaultPath = this.getLocalLibraryPath();
const paths = [defaultPath, ...this.libraryFiles().filter(file => file.path !== defaultPath).map(file => file.path)];
return { items: this.currentItems.map(item => ({ item, path: this.itemSource.get(item.id) })), paths, defaultPath };
}
/** Rename one stencil in its current owner without rewriting its elements. */
public async renameResourceStencil(path: string | undefined, id: string, name: string): Promise<void> {
const title = name.trim();
if (!title) throw Error("Stencil name is empty");
const rename = (items: LibraryItems): LibraryItems => {
const matching = items.filter(item => item.id === id);
if (matching.length !== 1) throw Error("Stencil no longer has a unique match in its library");
if (matching[0].name === title) return items;
return items.map(item => item.id === id ? { ...item, name: title } : item);
};
if (path === undefined) {
await this.queueSave(async () => {
if (this.plugin.settings.libraryStorageMode !== "data-json") throw Error("Stencil storage changed");
const data = this.plugin.getLegacyStencilLibrary();
const items = getLibraryItems(data);
const renamed = rename(items);
if (renamed === items) return;
await this.plugin.setLegacyStencilLibrary(this.withLibraryItems(data, renamed));
await this.updateLibrariesInOpenViews(restoreLibraryItems(renamed, "unpublished"));
});
return;
}
this.saveQueue = this.saveQueue.then(() => this.persistChanges(items));
await this.saveQueue;
await this.editResourceLibraries(async () => {
const vault = this.plugin.app.vault;
const file = vault.getFileByPath(path);
if (!file) throw Error("Library is missing");
await vault.process(file, raw => {
const data = this.parseLibrary(raw);
const items = getLibraryItems(data);
const renamed = rename(items);
return renamed === items ? raw : JSON.stringify(this.withLibraryItems(data, renamed), null, 2);
});
}, path);
}
/** Create an empty standard library in the configured vault folder. */
public async createResourceLibrary(name: string): Promise<string> {
const filename = name.trim().replace(/\.excalidrawlib$/i, "");
if (!filename || filename.startsWith(".") || /[\\/:*?"<>|]/.test(filename) || filename.endsWith(".")) {
throw Error("Invalid library filename");
}
const path = this.getFolderPath() + "/" + filename + "." + LIBRARY_EXTENSION;
await this.editResourceLibraries(async () => {
if (this.plugin.app.vault.getAbstractFileByPath(path)) throw Error("Library already exists");
await this.ensureFolder();
await this.plugin.app.vault.create(path, JSON.stringify(this.createFileData([]), null, 2));
}, path);
return path;
}
/** Copy first, verify the destination, then remove only unchanged source items. */
public async moveResourceStencils(source: string, destination: string, ids: readonly string[]): Promise<void> {
if (source === destination || !ids.length) return;
await this.editResourceLibraries(async () => this.moveItems(source, destination, new Set(ids)), source, destination);
}
/** Trash a library only after a confirmed delete or a completed move of its contents. */
public async deleteResourceLibrary(path: string, destination: string | null, confirmedIds: readonly string[]): Promise<void> {
if (path === destination) throw Error("Source and destination must differ");
await this.editResourceLibraries(async () => {
const vault = this.plugin.app.vault;
const file = vault.getFileByPath(path);
if (!file) return;
const confirmed = new Set(confirmedIds);
const current = getLibraryItems(this.parseLibrary(await vault.read(file)));
if (current.some(item => !confirmed.has(item.id))) throw Error("Library contents changed");
if (destination) {
await this.moveItems(path, destination, new Set(current.map(item => item.id)));
if (getLibraryItems(this.parseLibrary(await vault.read(file))).length) throw Error("Library contents changed");
}
await this.plugin.app.fileManager.trashFile(file);
}, ...(destination ? [path, destination] : [path]));
}
private async moveItems(source: string, destination: string, ids: ReadonlySet<string>): Promise<void> {
const vault = this.plugin.app.vault;
const sourceFile = vault.getFileByPath(source);
let destinationFile = vault.getFileByPath(destination);
if (!sourceFile || !destinationFile && destination !== this.getLocalLibraryPath()) throw Error("Library is missing");
const sourceItems = getLibraryItems(this.parseLibrary(await vault.read(sourceFile)));
const moving = sourceItems.filter(item => ids.has(item.id));
if (!moving.length) return;
if (new Set(moving.map(item => item.id)).size !== moving.length) throw Error("Duplicate stencil IDs in source library");
const merge = (data: StencilLibraryData) => {
const items = getLibraryItems(data);
for (const item of moving) {
const existing = items.find(other => other.id === item.id);
if (existing && JSON.stringify(existing) !== JSON.stringify(item)) throw Error("Destination stencil ID collision");
}
return this.withLibraryItems(data, this.mergeById(items, moving));
};
if (!destinationFile) {
await this.ensureFolder();
destinationFile = await vault.create(destination, JSON.stringify(merge(this.createFileData([])), null, 2));
} else {
await vault.process(destinationFile, raw => JSON.stringify(merge(this.parseLibrary(raw)), null, 2));
}
const destinationRevision = destinationFile.stat.mtime;
const recorded = getLibraryItems(this.parseLibrary(await vault.read(destinationFile)));
if (!moving.every(item => recorded.some(other => JSON.stringify(item) === JSON.stringify(other)))) {
throw Error("Destination stencil write could not be verified");
}
const expected = new Map(moving.map(item => [item.id, JSON.stringify(item)]));
await vault.process(sourceFile, raw => {
if (vault.getFileByPath(destination) !== destinationFile || destinationFile.stat.mtime !== destinationRevision) {
throw Error("Destination library changed during move");
}
const data = this.parseLibrary(raw);
const items = getLibraryItems(data);
if (items.some(item => expected.has(item.id) && expected.get(item.id) !== JSON.stringify(item))) {
throw Error("Stencil changed during move; both copies were kept");
}
return JSON.stringify(this.withLibraryItems(data, items.filter(item => !expected.has(item.id))), null, 2);
});
}
private parseLibrary(raw: string): StencilLibraryData {
const data = JSON.parse(raw) as StencilLibraryData;
if (data?.type !== "excalidrawlib" || data.version !== 2 || !Array.isArray(data.libraryItems)) throw Error("Invalid stencil library");
return data;
}
private withLibraryItems(data: StencilLibraryData, items: LibraryItems): StencilLibraryFileData {
return { ...data, type: "excalidrawlib", version: 2, libraryItems: items };
}
private libraryFiles() {
const folder = this.getFolderPath();
return this.plugin.app.vault.getFolderByPath(folder)?.children.filter(file =>
!(file instanceof TFolder) && file.name.toLowerCase().endsWith("." + LIBRARY_EXTENSION)) ?? [];
}
private queueSave(edit: () => Promise<void>): Promise<void> {
const pending = this.saveQueue.then(edit);
this.saveQueue = pending.catch(() => {});
return pending;
}
private async editResourceLibraries(edit: () => Promise<void>, ...paths: string[]): Promise<void> {
try { await this.queueSave(async () => {
if (this.plugin.settings.libraryStorageMode !== "vault" || paths.some(path =>
path.slice(0, path.lastIndexOf("/")) !== this.getFolderPath() || !path.toLowerCase().endsWith("." + LIBRARY_EXTENSION))) {
throw Error("Vault stencil libraries are required");
}
try { await edit(); }
finally { this.invalidate(); }
}); }
finally { await this.reloadLibrariesInOpenViews(); }
}
public async showMigrationPrompt(): Promise<void> {
@@ -160,11 +329,15 @@ export class StencilLibraryManager {
await this.saveQueue;
this.invalidate();
await this.ensureLoaded();
await this.updateLibrariesInOpenViews(this.currentItems);
}
private async updateLibrariesInOpenViews(items: LibraryItems): Promise<void> {
this.isUpdatingOpenViews = true;
try {
for (const view of getExcalidrawViews(this.plugin.app, true)) {
await view.excalidrawAPI.updateLibrary({
libraryItems: this.currentItems,
libraryItems: items,
merge: false,
});
}
@@ -268,9 +441,9 @@ export class StencilLibraryManager {
private scheduleOpenViewReload(): void {
if (this.reloadTimer !== null) {
window.clearTimeout(this.reloadTimer);
this.ownerWindow.clearTimeout(this.reloadTimer);
}
this.reloadTimer = window.setTimeout(() => {
this.reloadTimer = this.ownerWindow.setTimeout(() => {
this.reloadTimer = null;
void this.reloadLibrariesInOpenViews().catch((error) =>
console.error("Could not reload stencil libraries", error),
@@ -504,7 +677,7 @@ export class StencilLibraryManager {
}
}
/** Writes a non-empty library or removes its file when no items remain. */
/** Write a standard library file, retaining empty libraries as destinations. */
private async persistLibraryFile(
path: string,
data: StencilLibraryFileData,
@@ -513,12 +686,10 @@ export class StencilLibraryManager {
if (data.libraryItems.length === 0 && !existing) {
return;
}
this.ownWritePaths.add(path);
const prior = this.ownWritePaths.get(path);
if (prior !== undefined) this.ownerWindow.clearTimeout(prior);
this.ownWritePaths.set(path, 0);
try {
if (data.libraryItems.length === 0) {
await this.plugin.app.fileManager.trashFile(existing);
return;
}
await this.ensureFolder();
const content = JSON.stringify(data, null, 2);
if (existing) {
@@ -530,10 +701,10 @@ export class StencilLibraryManager {
}
await this.plugin.app.vault.create(path, content);
} finally {
window.setTimeout(
this.ownWritePaths.set(path, this.ownerWindow.setTimeout(
() => this.ownWritePaths.delete(path),
OWN_WRITE_EVENT_WINDOW_MS,
);
));
}
}
}
+25
View File
@@ -112,6 +112,7 @@ import {
canNavigateSettingsPages,
navigateToSettingsPage,
} from "src/core/settings/settingsNavigation";
import { ExcalidrawSidepanelView } from "src/view/sidepanel/Sidepanel";
declare const mainDocument: Document;
@@ -1708,6 +1709,15 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
private getGeneralDrawingFolderSpecs(): SettingSpec[] {
let previousFolder = "";
return [
{
name: t("VR_FRAMEWORK_FOLDER"),
desc: t("VR_FRAMEWORK_FOLDER_DESC"),
control: { type: "text", key: "frameworkFolder", vaultPath: { kind: "folder", options: { optional: true } } },
},
{
name: t("VR_PROMPT_ON_BLANK"),
control: { type: "toggle", key: "frameworksOnBlank" },
},
{
name: t("FOLDER_NAME"),
desc: fragWithHTML(t("FOLDER_DESC")),
@@ -2805,6 +2815,21 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
private getUIModeSpecs(): SettingSpec[] {
return [
{
name: t("SIDEPANEL_POPOUT_NAME"),
desc: t("SIDEPANEL_POPOUT_DESC"),
aliases: ["sidepanel", "popout", "separate window"],
visible: () => DEVICE.isDesktop,
control: {
type: "toggle",
key: "sidepanelOpenInPopout",
before: (value) => {
if (value !== this.plugin.settings.sidepanelOpenInPopout) {
ExcalidrawSidepanelView.applyLocationPreference(this.plugin, value);
}
},
},
},
{
name: t("SHOW_TAB_TITLEBAR_BUTTONS"),
aliases: ["tab buttons", "titlebar buttons"],
+17
View File
@@ -11,6 +11,7 @@
*/
import { Modifier } from "obsidian";
import type { ThumbnailRenamePolicy } from "src/types/frameTypes";
import type { FrameworkInstallState, FrameworkRemote, VisualResourcePreferences } from "src/types/visualResourceTypes";
import type { CodeBlockInsertionPreference } from "src/types/codeBlockTypes";
import { PenStyle } from "src/types/penTypes";
import { DynamicStyle, GridSettings } from "src/types/types";
@@ -219,7 +220,15 @@ export interface ExcalidrawSettings {
taskboneAPIKeySource?: "settings" | "secret";
taskboneAPIKeySecret?: string;
pinnedScripts: string[];
visualResources: VisualResourcePreferences;
frameworkFolder: string;
frameworksOnBlank: boolean;
frameworksSnoozedUntil: number;
frameworkCatalogCheckedAt: number;
frameworkCatalog: FrameworkRemote[];
frameworkInstalls: Record<string, FrameworkInstallState>;
sidepanelTabs: string[];
sidepanelOpenInPopout: boolean;
customPens: PenStyle[];
numberOfCustomPens: number;
pdfScale: number;
@@ -574,7 +583,15 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
taskboneAPIKeySource: "settings",
taskboneAPIKeySecret: "",
pinnedScripts: [],
visualResources: {},
frameworkFolder: "",
frameworksOnBlank: true,
frameworksSnoozedUntil: 0,
frameworkCatalogCheckedAt: 0,
frameworkCatalog: [],
frameworkInstalls: {},
sidepanelTabs: [],
sidepanelOpenInPopout: false,
customPens: [
{ ...PENS.default },
{ ...PENS.highlighter },
+133 -2
View File
@@ -16,6 +16,133 @@ declare const PLUGIN_VERSION: string;
// English
export default {
// Visual Resources and Thinking Frameworks
VR_INSERT_SELECTED: "Insert selected into drawing",
VR_HAS_NAMED_FRAMES: "Has named frames",
VR_HAS_NAMED_FRAMES_DESC: "Finds drawings with named frames saved in Excalidraw 2.29.4 or newer.",
VR_FILTER_DONE: "Done",
VR_FRAME_SEARCH_RULES: "Frame search rules",
VR_COPY_PROMPT_DESC: "Copy instructions for writing discovery rules with an AI assistant.",
VR_PROMPT_COPIED: "Prompt copied.",
VR_RULES_DESC: "Use case-insensitive regular expressions. Put the search keyword in a capture group, such as (.+).",
VR_RULE_POSITION: "Rule {CURRENT} / {TOTAL}",
VR_TEST_PATH: "Find a sample file by name or path",
VR_EXCLUSIONS_DESC: "Comma or newline separated vault paths.",
VR_RULE_ADVANCED: "Advanced conditions",
VR_NO_LIMIT: "No limit",
VR_TRANSPARENT: "Transparent",
VR_BROWSE_FRAMES: "Browse named frames",
VR_ICON_GROUPS: "Vault icon groups",
VR_DRAWING_GROUPS: "Drawing groups",
VR_FRAME_GROUPS: "Frame groups within drawings",
VR_STENCIL_LIBRARIES: "Stencil libraries",
VR_INSERT_TARGET: "Insert into {TITLE}",
VR_INSERT_NOTE: "Insert into note",
VR_INSERT_CANVAS: "Add to Canvas",
VR_SVG_OPTIONS: "SVG stroke options",
VR_SVG_PROPERTY: "Source link property",
VR_KPLEX_DIRECTION: "Direction from drawing to SVG",
VR_KPLEX_FIELD: "K-Plex relationship field",
VR_KPLEX_CHOOSE: "Choose a relationship field",
VR_REL_PARENT: "Parent",
VR_REL_CHILD: "Child",
VR_REL_LEFT: "Left friend",
VR_REL_RIGHT: "Right friend",
VR_TITLE: "Visual Resources",
VR_SEARCH: "Search visual resources",
VR_FILTER: "Filter resources",
VR_COLLECTIONS: "Collections",
VR_POPOUT: "Move between sidebar and window",
VR_HELP: "Visual Resources help",
VR_HELP_TEXT: "Search by title, file path, or frame name. Use the arrow keys to navigate and Enter to insert. On desktop, double-click a file to open it or drag it to a drawing to insert at the drop position. Use the collection and resource menus to organize favorites and playlists.",
VR_SETTINGS: "Visual Resources settings",
VR_LAYOUT: "Toggle grid or list",
VR_SELECT_ALL_FILTERS: "Select all",
VR_SELECT_NO_FILTERS: "Select none",
VR_EXIT_SELECTION: "Exit selection mode",
VR_SELECTION_COUNT: "{COUNT} selected",
VR_RESIZE_FRAMES: "Resize the gallery and frames",
VR_SELECT: "Select multiple resources",
VR_SELECTED_ACTIONS: "Actions for selected resources",
VR_BACK: "Back to resources",
VR_ALL: "All resources",
VR_FAVORITES: "Favorites",
VR_FAVORITE: "Add to favorites",
VR_UNFAVORITE: "Remove from favorites",
VR_NEW_PLAYLIST: "New playlist",
VR_RENAME: "Rename",
VR_DELETE_PLAYLIST: "Delete playlist",
VR_REMOVE_CURRENT: "Remove from this playlist",
VR_ADD_FILE: "Add a vault file",
VR_ICON: "Vault icons",
VR_LUCIDE: "Lucide icons",
VR_ICON_LIBRARY: "Icon Library",
VR_IMAGE: "Images",
VR_DRAWING: "Drawings",
VR_FRAME: "Named frames",
VR_MARKER_FRAME: "Marker frames",
VR_NOTE: "Notes",
VR_STENCIL: "Stencils",
VR_FRAMEWORKS: "Thinking Frameworks",
VR_OTHER: "Other visuals",
VR_ACTIONS: "Resource actions",
VR_RESOURCE_INFO: "Resource information",
VR_INSERT: "Insert into drawing",
VR_INSERT_SVG: "Insert linked SVG",
VR_INSERT_STROKES: "Insert as editable strokes",
VR_SVG_RETAIN_LINK: "Link to the source SVG in drawing properties",
VR_OPEN_SOURCE: "Open in new tab",
VR_REVEAL: "Reveal in file navigation",
VR_REVEAL_SYSTEM: "Reveal in system file explorer",
VR_REVEAL_LIBRARY: "Reveal backing library in file navigation",
VR_REVEAL_LIBRARY_SYSTEM: "Reveal backing library in system file explorer",
VR_ALL_LIBRARIES: "All stencil libraries",
VR_DEFAULT_LIBRARY: "Default library",
VR_MANAGE_LIBRARIES: "Manage stencil libraries",
VR_MOVE_LIBRARY: "Move to library",
VR_CREATE_LIBRARY: "Create library",
VR_DELETE_LIBRARY: "Delete library",
VR_MOVE_AND_DELETE: "Move items and delete library",
VR_LEGACY_LIBRARY: "Enable vault-backed stencil storage in settings to manage multiple libraries.",
VR_LIBRARY_STORAGE: "Open stencil storage settings",
VR_DISCOVERY: "Discovery rules",
VR_RULE: "New rule",
VR_ADD_RULE: "Add rule",
VR_COPY_PROMPT: "Copy LLM prompt",
VR_PROMPT: "Help me create Visual Resources discovery rules using sample vault paths. Select Icons, Drawings, or Frames. Within each named rule, every filled criterion must match. A file or frame can match any rule. Use a case-insensitive JavaScript filename or frame title regex with a capture group for the search keyword, for example ^icon - (.+)$. Optional fields are folder path regex, comma-separated extensions, maximum size in KB, a frontmatter property such as tags and its value, and a regular or marker frame type. Explain how each sample path or title matches.",
VR_TEST: "Test filters",
VR_EXCLUSIONS: "Excluded folders",
VR_ICON_WIDTH: "Default icon width",
VR_THUMB_SIZE: "Thumbnail size",
VR_LIGHT_BG: "Light mode thumbnail background",
VR_DARK_BG: "Dark mode thumbnail background",
VR_SAVE: "Save",
VR_DELETE: "Delete",
VR_NAME: "Name",
VR_PATTERN: "Filename or title regex",
VR_FOLDER_PATTERN: "Folder path regex",
VR_EXTENSIONS: "File extensions",
VR_MAX_KB: "Maximum size (KB)",
VR_PROPERTY: "Document property or tag field",
VR_PROPERTY_VALUE: "Property value",
VR_FRAME_TYPE: "Frame type",
VR_RULE_ERROR: "Check rule names and regular expressions.",
VR_LOADING: "Loading resources…",
VR_NO_DRAWING: "Select an editable drawing, note, or Canvas to insert resources.",
VR_EMPTY: "No matching resources",
VR_ACTION_FAILED: "Visual resource action failed.",
VR_INSERT_FAILED: "Could not insert the visual resource.",
VR_NEW_WITH_FRAMEWORK: "Create drawing with a Thinking Framework",
VR_FRAMEWORK_FOLDER: "Thinking Frameworks folder",
VR_FRAMEWORK_FOLDER_DESC: "Leave empty to use Frameworks in your Excalidraw folder.",
VR_PROMPT_ON_BLANK: "Offer Thinking Frameworks on new blank drawings",
VR_DONT_SHOW: "Don't show on blank drawings",
VR_SHOW_LATER: "Show me later",
VR_DOWNLOAD_FRAMEWORK: "Download framework library",
VR_UPDATE_FRAMEWORK: "Update framework library",
VR_REPLACE_FRAMEWORK: "Replace modified framework library?",
VR_DOWNLOAD_FAILED: "Could not download the framework library.",
// RankMessage.ts
RANK_MESSAGE_TITLE: "Congratulations, glorious knight!",
RANK_MESSAGE_BODY: "You have {{filecount}} Excalidraw drawings in your Vault earning you a new rank: **{{rank}}**! You've ascended to **{{title}}**!\n\nI've spent the past 5+ years building this plugin. If you appreciate my work, consider supporting me on [Ko-Fi]({{koFiUrl}}) or join the next [Visual Thinking Workshop]({{workshopUrl}}) cohort.",
@@ -90,6 +217,8 @@ export default {
CLI_COPY_SKILL: "Copy agent instructions",
CLI_AGENT_INSTRUCTIONS: `Read: ${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<user instructions>>`,
CLI_DESCRIPTION: "Native Excalidraw CLI",
CLI_COPY_SELECTION: "Copy selected elements for agent",
CLI_COPY_SELECTION_ERROR: "Could not copy the selected elements. Select fewer elements and try again.",
INITIALIZATION_MESSAGE:
"Excalidraw is waiting for Obsidian to initialize all of your plugins...",
@@ -460,6 +589,8 @@ export default {
SHOW_TAB_TITLEBAR_BUTTONS: "Show tab titlebar buttons",
OPEN_LINK: "Open selected text as link\n(SHIFT+CLICK to open in a new pane)",
EXCALIDRAW_SIDEPANEL: "Excalidraw Sidepanel",
SIDEPANEL_POPOUT_NAME: "Open Excalidraw sidepanel in a popout window",
SIDEPANEL_POPOUT_DESC: "On desktop, enabling this opens the Excalidraw sidepanel in a separate window the next time you show it. Disabling it docks the panel without expanding the sidebar. Later manual moves are preserved.",
LINK_BUTTON_CLICK_NO_TEXT:
"Select an element that contains an internal or external link.\n",
LINEAR_ELEMENT_LINK_CLICK_ERROR:
@@ -1299,9 +1430,9 @@ export default {
EMBED_THEME_BACKGROUND: "Image theme and background color",
EMBED_THEME_BACKGROUND_DESC:
"Choose exported-image background and theme behavior and whether previews follow Obsidian's theme.",
EMBED_IMAGE_CACHE_NAME: "Cache images for embedding in markdown",
EMBED_IMAGE_CACHE_NAME: "Cache rendered images and thumbnails",
EMBED_IMAGE_CACHE_DESC:
"Cache images for embedding in markdown. Cached drawings are refreshed when the drawing or one of its nested vault-file dependencies changes.",
"Store rendered Markdown embeds and Visual Resources drawing thumbnails on this device. Cached drawings are refreshed when the drawing or one of its nested vault-file dependencies changes.",
SCENE_IMAGE_CACHE_NAME: "Cache nested Excalidraws in Scene",
SCENE_IMAGE_CACHE_DESC:
"Cache nested Excalidraws in the Scene for faster scene rendering. This will speed up the rendering process, especially if you have deeply nested Excalidraws in your scene. " +
+133 -2
View File
@@ -16,6 +16,133 @@ declare const PLUGIN_VERSION: string;
// Español
export default {
// Visual Resources and Thinking Frameworks
VR_INSERT_SELECTED: "Insertar selección en el dibujo",
VR_HAS_NAMED_FRAMES: "Tiene marcos con nombre",
VR_HAS_NAMED_FRAMES_DESC: "Encuentra dibujos con marcos con nombre guardados con Excalidraw 2.29.4 o posterior.",
VR_FILTER_DONE: "Listo",
VR_FRAME_SEARCH_RULES: "Reglas de búsqueda de marcos",
VR_COPY_PROMPT_DESC: "Copia instrucciones para crear reglas de detección con un asistente de IA.",
VR_PROMPT_COPIED: "Instrucciones copiadas.",
VR_RULES_DESC: "Usa expresiones regulares sin distinción de mayúsculas. Captura la palabra clave con un grupo como (.+).",
VR_RULE_POSITION: "Regla {CURRENT} / {TOTAL}",
VR_TEST_PATH: "Buscar un archivo de ejemplo por nombre o ruta",
VR_EXCLUSIONS_DESC: "Rutas de la bóveda separadas por comas o saltos de línea.",
VR_RULE_ADVANCED: "Condiciones avanzadas",
VR_NO_LIMIT: "Sin límite",
VR_TRANSPARENT: "Transparente",
VR_BROWSE_FRAMES: "Explorar marcos con nombre",
VR_ICON_GROUPS: "Grupos de iconos de la bóveda",
VR_DRAWING_GROUPS: "Grupos de dibujos",
VR_FRAME_GROUPS: "Grupos de marcos dentro de los dibujos",
VR_STENCIL_LIBRARIES: "Bibliotecas de plantillas",
VR_INSERT_TARGET: "Insertar en {TITLE}",
VR_INSERT_NOTE: "Insertar en la nota",
VR_INSERT_CANVAS: "Añadir a Canvas",
VR_SVG_OPTIONS: "Opciones de trazos SVG",
VR_SVG_PROPERTY: "Propiedad del enlace al original",
VR_KPLEX_DIRECTION: "Dirección del dibujo al SVG",
VR_KPLEX_FIELD: "Campo de relación de K-Plex",
VR_KPLEX_CHOOSE: "Elegir un campo de relación",
VR_REL_PARENT: "Padre",
VR_REL_CHILD: "Hijo",
VR_REL_LEFT: "Amigo izquierdo",
VR_REL_RIGHT: "Amigo derecho",
VR_TITLE: "Recursos visuales",
VR_SEARCH: "Buscar recursos visuales",
VR_FILTER: "Filtrar recursos",
VR_COLLECTIONS: "Colecciones",
VR_POPOUT: "Mover entre barra lateral y ventana",
VR_HELP: "Ayuda de Recursos visuales",
VR_HELP_TEXT: "Busca por título, ruta o nombre de marco. Usa las flechas para navegar y Entrar para insertar. En el escritorio, haz doble clic para abrir un archivo o arrástralo al dibujo para insertarlo. Organiza favoritos y listas desde sus menús.",
VR_SETTINGS: "Ajustes de Recursos visuales",
VR_LAYOUT: "Alternar cuadrícula y lista",
VR_SELECT_ALL_FILTERS: "Seleccionar todo",
VR_SELECT_NO_FILTERS: "Deseleccionar todo",
VR_EXIT_SELECTION: "Salir del modo de selección",
VR_SELECTION_COUNT: "{COUNT} seleccionados",
VR_RESIZE_FRAMES: "Cambiar el tamaño de la galería y los marcos",
VR_SELECT: "Seleccionar varios recursos",
VR_SELECTED_ACTIONS: "Acciones para los recursos seleccionados",
VR_BACK: "Volver a los recursos",
VR_ALL: "Todos los recursos",
VR_FAVORITES: "Favoritos",
VR_FAVORITE: "Añadir a favoritos",
VR_UNFAVORITE: "Quitar de favoritos",
VR_NEW_PLAYLIST: "Nueva lista",
VR_RENAME: "Cambiar nombre",
VR_DELETE_PLAYLIST: "Eliminar lista",
VR_REMOVE_CURRENT: "Quitar de esta lista",
VR_ADD_FILE: "Añadir archivo de la bóveda",
VR_ICON: "Iconos de la bóveda",
VR_LUCIDE: "Iconos de Lucide",
VR_ICON_LIBRARY: "Biblioteca de iconos",
VR_IMAGE: "Imágenes",
VR_DRAWING: "Dibujos",
VR_FRAME: "Marcos con nombre",
VR_MARKER_FRAME: "Marcos marcadores",
VR_NOTE: "Notas",
VR_STENCIL: "Plantillas de biblioteca",
VR_FRAMEWORKS: "Marcos de pensamiento",
VR_OTHER: "Otros recursos visuales",
VR_ACTIONS: "Acciones del recurso",
VR_RESOURCE_INFO: "Información del recurso",
VR_INSERT: "Insertar en el dibujo",
VR_INSERT_SVG: "Insertar SVG enlazado",
VR_INSERT_STROKES: "Insertar como trazos editables",
VR_SVG_RETAIN_LINK: "Vincular el SVG original en las propiedades del dibujo",
VR_OPEN_SOURCE: "Abrir en una pestaña nueva",
VR_REVEAL: "Mostrar en el explorador de archivos",
VR_REVEAL_SYSTEM: "Mostrar en el explorador del sistema",
VR_REVEAL_LIBRARY: "Mostrar la biblioteca en el explorador de archivos",
VR_REVEAL_LIBRARY_SYSTEM: "Mostrar la biblioteca en el explorador del sistema",
VR_ALL_LIBRARIES: "Todas las bibliotecas de plantillas",
VR_DEFAULT_LIBRARY: "Biblioteca predeterminada",
VR_MANAGE_LIBRARIES: "Gestionar bibliotecas de plantillas",
VR_MOVE_LIBRARY: "Mover a otra biblioteca",
VR_CREATE_LIBRARY: "Crear biblioteca",
VR_DELETE_LIBRARY: "Eliminar biblioteca",
VR_MOVE_AND_DELETE: "Mover elementos y eliminar biblioteca",
VR_LEGACY_LIBRARY: "Activa el almacenamiento de plantillas en la bóveda para gestionar varias bibliotecas.",
VR_LIBRARY_STORAGE: "Abrir los ajustes de almacenamiento de plantillas",
VR_DISCOVERY: "Reglas de búsqueda",
VR_RULE: "Nueva regla",
VR_ADD_RULE: "Añadir regla",
VR_COPY_PROMPT: "Copiar instrucciones para IA",
VR_PROMPT: "Ayúdame a crear reglas de Recursos visuales con rutas de ejemplo. Selecciona Iconos, Dibujos o Marcos. Cada criterio de una regla debe coincidir. Basta con que coincida una regla. Usa una expresión regular de JavaScript sin distinción de mayúsculas, con un grupo de captura para la palabra clave, como ^icon - (.+)$. Puedes añadir ruta, extensiones, tamaño máximo en KB, propiedad o etiqueta y tipo de marco. Explica los resultados con ejemplos.",
VR_TEST: "Probar filtros",
VR_EXCLUSIONS: "Carpetas excluidas",
VR_ICON_WIDTH: "Anchura predeterminada del icono",
VR_THUMB_SIZE: "Tamaño de miniatura",
VR_LIGHT_BG: "Fondo de miniaturas en modo claro",
VR_DARK_BG: "Fondo de miniaturas en modo oscuro",
VR_SAVE: "Guardar",
VR_DELETE: "Eliminar",
VR_NAME: "Nombre",
VR_PATTERN: "Expresión regular del nombre o título",
VR_FOLDER_PATTERN: "Expresión regular de la ruta",
VR_EXTENSIONS: "Extensiones de archivo",
VR_MAX_KB: "Tamaño máximo (KB)",
VR_PROPERTY: "Propiedad del documento o campo de etiquetas",
VR_PROPERTY_VALUE: "Valor de la propiedad",
VR_FRAME_TYPE: "Tipo de marco",
VR_RULE_ERROR: "Revisa los nombres y las expresiones regulares.",
VR_LOADING: "Cargando recursos…",
VR_NO_DRAWING: "Selecciona un dibujo, una nota o un Canvas editable para insertar recursos.",
VR_EMPTY: "No se encontraron recursos",
VR_ACTION_FAILED: "No se pudo completar la acción.",
VR_INSERT_FAILED: "No se pudo insertar el recurso visual.",
VR_NEW_WITH_FRAMEWORK: "Crear dibujo con un marco de pensamiento",
VR_FRAMEWORK_FOLDER: "Carpeta de marcos de pensamiento",
VR_FRAMEWORK_FOLDER_DESC: "Déjalo en blanco para usar Frameworks dentro de tu carpeta de Excalidraw.",
VR_PROMPT_ON_BLANK: "Mostrar marcos de pensamiento en nuevos dibujos en blanco",
VR_DONT_SHOW: "No mostrar en dibujos en blanco",
VR_SHOW_LATER: "Mostrar más tarde",
VR_DOWNLOAD_FRAMEWORK: "Descargar biblioteca de marcos",
VR_UPDATE_FRAMEWORK: "Actualizar biblioteca de marcos",
VR_REPLACE_FRAMEWORK: "¿Sustituir la biblioteca de marcos modificada?",
VR_DOWNLOAD_FAILED: "No se pudo descargar la biblioteca de marcos.",
// RankMessage.ts
RANK_MESSAGE_TITLE: "¡Enhorabuena, noble caballero!",
RANK_MESSAGE_BODY: "¡Tienes {{filecount}} dibujos de Excalidraw en tu bóveda y has conseguido un nuevo rango: **{{rank}}**! ¡Tu nuevo título es **{{title}}**!\n\nHe dedicado más de 5 años a desarrollar este complemento. Si valoras mi trabajo, considera apoyarme en [Ko-Fi]({{koFiUrl}}) o unirte al próximo grupo de [Visual Thinking Workshop]({{workshopUrl}}).",
@@ -90,6 +217,8 @@ export default {
CLI_COPY_SKILL: "Copiar instrucciones para agentes",
CLI_AGENT_INSTRUCTIONS: `Lee: ${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<instrucciones del usuario>>`,
CLI_DESCRIPTION: "CLI nativa de Excalidraw",
CLI_COPY_SELECTION: "Copiar elementos seleccionados para el agente",
CLI_COPY_SELECTION_ERROR: "No se pudieron copiar los elementos seleccionados. Selecciona menos elementos e inténtalo de nuevo.",
// Sugester
SELECT_FILE_TO_INSERT: "Selecciona un archivo para insertar",
@@ -957,6 +1086,8 @@ export default {
}'>Modo de Lectura de Markdown</a> en 'Apariencia y Comportamiento' más arriba.<br>` +
`⚠️ Debes cerrar y volver a abrir el archivo de Excalidraw/Markdown para que los cambios surtan efecto. ⚠️`,
MODES_HEAD: "Modos",
SIDEPANEL_POPOUT_NAME: "Abrir el panel lateral de Excalidraw en una ventana independiente",
SIDEPANEL_POPOUT_DESC: "En escritorio, al activar este ajuste, el panel lateral de Excalidraw se abre en una ventana independiente la próxima vez que lo muestres. Al desactivarlo, el panel vuelve a la barra lateral sin desplegarla. Los movimientos manuales posteriores se conservan.",
MODES_DESC:
"Elige diseños de interfaz específicos para cada dispositivo, controles de la barra de título y la posición de la bandeja para diestros o zurdos.",
HOTKEY_OVERRIDE_HEAD: "Anulaciones de atajos de teclado",
@@ -1259,9 +1390,9 @@ export default {
EMBED_THEME_BACKGROUND_DESC:
"Elige el fondo y el tema de las imágenes exportadas y si las vistas previas siguen el tema de Obsidian.",
EMBED_IMAGE_CACHE_NAME:
"Guardar imágenes en caché para incrustar en Markdown",
"Guardar imágenes renderizadas y miniaturas en caché",
EMBED_IMAGE_CACHE_DESC:
"Guarda imágenes en caché para incrustarlas en Markdown. Los bosquejos almacenados en caché se actualizan cuando cambia el bosquejo o una de sus dependencias de archivos de la bóveda.",
"Guarda en este dispositivo las imágenes renderizadas para Markdown y las miniaturas de dibujos de Recursos visuales. Los dibujos en caché se actualizan cuando cambia el dibujo o alguno de los archivos de la bóveda de los que depende.",
SCENE_IMAGE_CACHE_NAME:
"Guardar bosquejos anidados de Excalidraw en caché en la escena",
SCENE_IMAGE_CACHE_DESC:
+133 -2
View File
@@ -14,6 +14,133 @@ import {
// русский
export default {
// Visual Resources and Thinking Frameworks
VR_INSERT_SELECTED: "Вставить выбранное в рисунок",
VR_HAS_NAMED_FRAMES: "Есть именованные рамки",
VR_HAS_NAMED_FRAMES_DESC: "Находит рисунки с именованными рамками, сохранённые в Excalidraw 2.29.4 или новее.",
VR_FILTER_DONE: "Готово",
VR_FRAME_SEARCH_RULES: "Правила поиска рамок",
VR_COPY_PROMPT_DESC: "Скопируйте инструкции для создания правил с помощью ИИ.",
VR_PROMPT_COPIED: "Инструкции скопированы.",
VR_RULES_DESC: "Учитываются регулярные выражения без учёта регистра. Поместите ключевое слово в группу, например (.+).",
VR_RULE_POSITION: "Правило {CURRENT} из {TOTAL}",
VR_TEST_PATH: "Найти пример файла по имени или пути",
VR_EXCLUSIONS_DESC: "Пути в хранилище через запятые или переносы строк.",
VR_RULE_ADVANCED: "Дополнительные условия",
VR_NO_LIMIT: "Без ограничений",
VR_TRANSPARENT: "Прозрачный",
VR_BROWSE_FRAMES: "Просмотреть именованные рамки",
VR_ICON_GROUPS: "Группы значков хранилища",
VR_DRAWING_GROUPS: "Группы рисунков",
VR_FRAME_GROUPS: "Группы рамок внутри рисунков",
VR_STENCIL_LIBRARIES: "Библиотеки трафаретов",
VR_INSERT_TARGET: "Вставка в {TITLE}",
VR_INSERT_NOTE: "Вставить в заметку",
VR_INSERT_CANVAS: "Добавить на холст Canvas",
VR_SVG_OPTIONS: "Параметры штрихов SVG",
VR_SVG_PROPERTY: "Свойство ссылки на источник",
VR_KPLEX_DIRECTION: "Направление от рисунка к SVG",
VR_KPLEX_FIELD: "Поле связи K-Plex",
VR_KPLEX_CHOOSE: "Выберите поле связи",
VR_REL_PARENT: "Родитель",
VR_REL_CHILD: "Потомок",
VR_REL_LEFT: "Друг слева",
VR_REL_RIGHT: "Друг справа",
VR_TITLE: "Визуальные ресурсы",
VR_SEARCH: "Поиск визуальных ресурсов",
VR_FILTER: "Фильтровать ресурсы",
VR_COLLECTIONS: "Коллекции",
VR_POPOUT: "Переместить между панелью и окном",
VR_HELP: "Справка по визуальным ресурсам",
VR_HELP_TEXT: "Ищите по заголовку, пути или имени рамки. Стрелки перемещают фокус, Enter вставляет ресурс. На компьютере двойной щелчок открывает файл, а перетаскивание вставляет его на рисунок. Избранное и списки доступны в меню.",
VR_SETTINGS: "Настройки визуальных ресурсов",
VR_LAYOUT: "Переключить сетку и список",
VR_SELECT_ALL_FILTERS: "Выбрать все",
VR_SELECT_NO_FILTERS: "Снять все отметки",
VR_EXIT_SELECTION: "Выйти из режима выбора",
VR_SELECTION_COUNT: "Выбрано: {COUNT}",
VR_RESIZE_FRAMES: "Изменить размеры галереи и рамок",
VR_SELECT: "Выбрать несколько ресурсов",
VR_SELECTED_ACTIONS: "Действия с выбранными ресурсами",
VR_BACK: "Назад к ресурсам",
VR_ALL: "Все ресурсы",
VR_FAVORITES: "Избранное",
VR_FAVORITE: "Добавить в избранное",
VR_UNFAVORITE: "Удалить из избранного",
VR_NEW_PLAYLIST: "Новый список",
VR_RENAME: "Переименовать",
VR_DELETE_PLAYLIST: "Удалить список",
VR_REMOVE_CURRENT: "Удалить из текущего списка",
VR_ADD_FILE: "Добавить файл хранилища",
VR_ICON: "Значки хранилища",
VR_LUCIDE: "Значки Lucide",
VR_ICON_LIBRARY: "Библиотека значков",
VR_IMAGE: "Изображения",
VR_DRAWING: "Рисунки",
VR_FRAME: "Именованные рамки",
VR_MARKER_FRAME: "Рамки-маркеры",
VR_NOTE: "Заметки",
VR_STENCIL: "Трафареты",
VR_FRAMEWORKS: "Схемы мышления",
VR_OTHER: "Другие визуальные ресурсы",
VR_ACTIONS: "Действия с ресурсом",
VR_RESOURCE_INFO: "Сведения о ресурсе",
VR_INSERT: "Вставить в рисунок",
VR_INSERT_SVG: "Вставить связанный SVG",
VR_INSERT_STROKES: "Вставить как редактируемые штрихи",
VR_SVG_RETAIN_LINK: "Сохранить ссылку на исходный SVG в свойствах рисунка",
VR_OPEN_SOURCE: "Открыть в новой вкладке",
VR_REVEAL: "Показать в списке файлов",
VR_REVEAL_SYSTEM: "Показать в системном проводнике",
VR_REVEAL_LIBRARY: "Показать файл библиотеки в списке файлов",
VR_REVEAL_LIBRARY_SYSTEM: "Показать файл библиотеки в системном проводнике",
VR_ALL_LIBRARIES: "Все библиотеки трафаретов",
VR_DEFAULT_LIBRARY: "Библиотека по умолчанию",
VR_MANAGE_LIBRARIES: "Управление библиотеками трафаретов",
VR_MOVE_LIBRARY: "Переместить в библиотеку",
VR_CREATE_LIBRARY: "Создать библиотеку",
VR_DELETE_LIBRARY: "Удалить библиотеку",
VR_MOVE_AND_DELETE: "Переместить элементы и удалить библиотеку",
VR_LEGACY_LIBRARY: "Включите хранение трафаретов в хранилище, чтобы управлять несколькими библиотеками.",
VR_LIBRARY_STORAGE: "Открыть настройки хранения трафаретов",
VR_DISCOVERY: "Правила поиска",
VR_RULE: "Новое правило",
VR_ADD_RULE: "Добавить правило",
VR_COPY_PROMPT: "Копировать запрос для ИИ",
VR_PROMPT: "Помоги составить правила визуальных ресурсов по примерам путей. Выбери значки, рисунки или рамки. Внутри правила должны выполняться все условия. Достаточно одного подходящего правила. Используй регулярное выражение JavaScript без учёта регистра с группой для ключевого слова, например ^icon - (.+)$. Дополнительно укажи папку, расширения, размер в КБ, свойства или теги и тип рамки. Объясни совпадения на примерах.",
VR_TEST: "Проверить фильтры",
VR_EXCLUSIONS: "Исключённые папки",
VR_ICON_WIDTH: "Ширина значка по умолчанию",
VR_THUMB_SIZE: "Размер миниатюр",
VR_LIGHT_BG: "Фон миниатюры в светлой теме",
VR_DARK_BG: "Фон миниатюры в тёмной теме",
VR_SAVE: "Сохранить",
VR_DELETE: "Удалить",
VR_NAME: "Название",
VR_PATTERN: "Выражение для имени или заголовка",
VR_FOLDER_PATTERN: "Выражение для пути папки",
VR_EXTENSIONS: "Расширения файлов",
VR_MAX_KB: "Максимальный размер (КБ)",
VR_PROPERTY: "Свойство заметки или поле тегов",
VR_PROPERTY_VALUE: "Значение свойства",
VR_FRAME_TYPE: "Тип рамки",
VR_RULE_ERROR: "Проверьте имена правил и регулярные выражения.",
VR_LOADING: "Загрузка ресурсов…",
VR_NO_DRAWING: "Выберите редактируемый рисунок, заметку или холст Canvas для вставки ресурсов.",
VR_EMPTY: "Подходящих ресурсов нет",
VR_ACTION_FAILED: "Не удалось выполнить действие с ресурсом.",
VR_INSERT_FAILED: "Не удалось вставить визуальный ресурс.",
VR_NEW_WITH_FRAMEWORK: "Создать рисунок по схеме мышления",
VR_FRAMEWORK_FOLDER: "Папка схем мышления",
VR_FRAMEWORK_FOLDER_DESC: "Пустое значение использует папку Frameworks внутри папки Excalidraw.",
VR_PROMPT_ON_BLANK: "Предлагать схемы мышления для новых пустых рисунков",
VR_DONT_SHOW: "Не показывать для пустых рисунков",
VR_SHOW_LATER: "Показать позже",
VR_DOWNLOAD_FRAMEWORK: "Скачать библиотеку схем",
VR_UPDATE_FRAMEWORK: "Обновить библиотеку схем",
VR_REPLACE_FRAMEWORK: "Заменить изменённую библиотеку схем?",
VR_DOWNLOAD_FAILED: "Не удалось скачать библиотеку схем.",
// RankMessage.ts
RANK_MESSAGE_TITLE: "Поздравляю, славный рыцарь!",
RANK_MESSAGE_BODY: "В вашем хранилище {{filecount}} рисунков Excalidraw, и вы заслужили новый ранг: **{{rank}}**! Ваш новый титул — **{{title}}**!\n\nЯ посвятил разработке этого плагина более 5 лет. Если вы цените мою работу, поддержите меня на [Ko-Fi]({{koFiUrl}}) или присоединяйтесь к следующему потоку [Visual Thinking Workshop]({{workshopUrl}}).",
@@ -88,6 +215,8 @@ export default {
CLI_COPY_SKILL: "Копировать инструкции для агентов",
CLI_AGENT_INSTRUCTIONS: `Прочитай: ${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<инструкции пользователя>>`,
CLI_DESCRIPTION: "Нативный CLI Excalidraw",
CLI_COPY_SELECTION: "Копировать выбранные элементы для агента",
CLI_COPY_SELECTION_ERROR: "Не удалось скопировать выбранные элементы. Выберите меньше элементов и повторите попытку.",
// main.ts
SETTINGS_DATA_INVALID:
@@ -883,6 +1012,8 @@ export default {
`См. другие связанные настройки для <a href='#${TAG_MDREADINGMODE}'>режима чтения разметки</a> в разделе 'Внешний вид и поведение' выше.<br>` +
"⚠️ Обратите внимание, что необходимо закрыть активный файл excalidraw/markdown и открыть его снова, чтобы изменения вступили в силу. ⚠️",
MODES_HEAD: "Режимы интерфейса",
SIDEPANEL_POPOUT_NAME: "Открывать боковую панель Excalidraw в отдельном окне",
SIDEPANEL_POPOUT_DESC: "На компьютере эта настройка открывает боковую панель Excalidraw в отдельном окне при следующем показе. При отключении панель возвращается на боковую панель Obsidian без её раскрытия. Последующие перемещения вручную сохраняются.",
MODES_DESC:
"Выберите интерфейс Excalidraw для каждого устройства, кнопки заголовка и расположение панели для правой или левой руки.",
HOTKEY_OVERRIDE_HEAD: "Переопределение горячих клавиш",
@@ -1171,9 +1302,9 @@ export default {
EMBED_THEME_BACKGROUND: "Тема изображения и цвет фона",
EMBED_THEME_BACKGROUND_DESC:
"Выберите фон и тему экспортируемых изображений, а также следование предпросмотра теме Obsidian.",
EMBED_IMAGE_CACHE_NAME: "Кэширование изображений для вставки в markdown",
EMBED_IMAGE_CACHE_NAME: "Кэширование изображений и миниатюр",
EMBED_IMAGE_CACHE_DESC:
"Кэшируйте изображения для вставки в Markdown. Кэшированные рисунки обновляются при изменении рисунка или одного из его вложенных файлов в хранилище.",
"Сохраняйте на этом устройстве изображения для вставки в Markdown и миниатюры рисунков из визуальных ресурсов. Кэш обновляется при изменении рисунка или одного из связанных файлов в хранилище.",
SCENE_IMAGE_CACHE_NAME: "Кэширование вложенных Excalidraws в Cцене",
SCENE_IMAGE_CACHE_DESC:
"Кэшируйте вложенные Excalidraws в сцене для ускорения рендеринга сцены. Это ускорит процесс рендеринга, особенно если в сцене есть глубоко вложенные Excalidraw. " +
+133 -2
View File
@@ -11,6 +11,133 @@ declare const PLUGIN_VERSION: string;
// 简体中文
export default {
// Visual Resources and Thinking Frameworks
VR_INSERT_SELECTED: "将选中资源插入绘图",
VR_HAS_NAMED_FRAMES: "有命名画框",
VR_HAS_NAMED_FRAMES_DESC: "查找用 Excalidraw 2.29.4 或更高版本保存且含命名画框的绘图。",
VR_FILTER_DONE: "完成",
VR_FRAME_SEARCH_RULES: "画框搜索规则",
VR_COPY_PROMPT_DESC: "复制用于让 AI 助手编写发现规则的说明。",
VR_PROMPT_COPIED: "已复制提示词。",
VR_RULES_DESC: "正则表达式不区分大小写。使用 (.+) 等捕获组提取关键词。",
VR_RULE_POSITION: "规则 {CURRENT} / {TOTAL}",
VR_TEST_PATH: "按名称或路径查找示例文件",
VR_EXCLUSIONS_DESC: "使用逗号或换行分隔仓库路径。",
VR_RULE_ADVANCED: "高级条件",
VR_NO_LIMIT: "无限制",
VR_TRANSPARENT: "透明",
VR_BROWSE_FRAMES: "浏览命名画框",
VR_ICON_GROUPS: "仓库图标分组",
VR_DRAWING_GROUPS: "绘图分组",
VR_FRAME_GROUPS: "绘图内的画框分组",
VR_STENCIL_LIBRARIES: "模板库",
VR_INSERT_TARGET: "插入到 {TITLE}",
VR_INSERT_NOTE: "插入到笔记",
VR_INSERT_CANVAS: "添加到 Canvas",
VR_SVG_OPTIONS: "SVG 笔画选项",
VR_SVG_PROPERTY: "来源链接属性",
VR_KPLEX_DIRECTION: "从绘图到 SVG 的关系方向",
VR_KPLEX_FIELD: "K-Plex 关系字段",
VR_KPLEX_CHOOSE: "选择关系字段",
VR_REL_PARENT: "父级",
VR_REL_CHILD: "子级",
VR_REL_LEFT: "左侧关联",
VR_REL_RIGHT: "右侧关联",
VR_TITLE: "视觉资源",
VR_SEARCH: "搜索视觉资源",
VR_FILTER: "筛选资源",
VR_COLLECTIONS: "收藏集",
VR_POPOUT: "在侧栏和独立窗口间切换",
VR_HELP: "视觉资源帮助",
VR_HELP_TEXT: "可按标题、路径或画框名称搜索。用方向键移动,按 Enter 插入。在桌面端,双击打开文件,拖到画布可在放置处插入。使用菜单管理收藏和列表。",
VR_SETTINGS: "视觉资源设置",
VR_LAYOUT: "切换网格或列表",
VR_SELECT_ALL_FILTERS: "全选",
VR_SELECT_NO_FILTERS: "全不选",
VR_EXIT_SELECTION: "退出多选模式",
VR_SELECTION_COUNT: "已选择 {COUNT} 项",
VR_RESIZE_FRAMES: "调整图库和画框区域的大小",
VR_SELECT: "多选资源",
VR_SELECTED_ACTIONS: "对所选资源执行操作",
VR_BACK: "返回资源",
VR_ALL: "所有资源",
VR_FAVORITES: "收藏",
VR_FAVORITE: "加入收藏",
VR_UNFAVORITE: "移出收藏",
VR_NEW_PLAYLIST: "新建列表",
VR_RENAME: "重命名",
VR_DELETE_PLAYLIST: "删除列表",
VR_REMOVE_CURRENT: "从此列表移除",
VR_ADD_FILE: "添加库文件",
VR_ICON: "库图标",
VR_LUCIDE: "Lucide 图标",
VR_ICON_LIBRARY: "图标库",
VR_IMAGE: "图像",
VR_DRAWING: "绘图",
VR_FRAME: "命名画框",
VR_MARKER_FRAME: "标记画框",
VR_NOTE: "笔记",
VR_STENCIL: "图形模板",
VR_FRAMEWORKS: "思考框架",
VR_OTHER: "其他视觉资源",
VR_ACTIONS: "资源操作",
VR_RESOURCE_INFO: "资源信息",
VR_INSERT: "插入绘图",
VR_INSERT_SVG: "插入链接的 SVG",
VR_INSERT_STROKES: "插入为可编辑笔画",
VR_SVG_RETAIN_LINK: "将 SVG 来源链接添加到绘图属性",
VR_OPEN_SOURCE: "在新标签页中打开",
VR_REVEAL: "在文件导航中显示",
VR_REVEAL_SYSTEM: "在系统文件管理器中显示",
VR_REVEAL_LIBRARY: "在文件导航中显示所属库",
VR_REVEAL_LIBRARY_SYSTEM: "在系统文件管理器中显示所属库",
VR_ALL_LIBRARIES: "所有图形模板库",
VR_DEFAULT_LIBRARY: "默认库",
VR_MANAGE_LIBRARIES: "管理图形模板库",
VR_MOVE_LIBRARY: "移动到库",
VR_CREATE_LIBRARY: "创建库",
VR_DELETE_LIBRARY: "删除库",
VR_MOVE_AND_DELETE: "移动项目并删除库",
VR_LEGACY_LIBRARY: "要管理多个库,请在设置中启用将图形模板存储在库中。",
VR_LIBRARY_STORAGE: "打开图形模板存储设置",
VR_DISCOVERY: "发现规则",
VR_RULE: "新规则",
VR_ADD_RULE: "添加规则",
VR_COPY_PROMPT: "复制 LLM 提示词",
VR_PROMPT: "请用示例路径帮我创建视觉资源发现规则。选择图标、绘图或画框。同一规则内所有条件必须匹配,多个规则满足其一即可。文件名或画框标题用不区分大小写的 JavaScript 正则表达式,例如 ^icon - (.+)$,捕获组用于提取关键词。可指定文件夹正则、扩展名、大小上限(KB)、属性或标签及画框类型。用例子说明匹配结果。",
VR_TEST: "测试筛选",
VR_EXCLUSIONS: "排除文件夹",
VR_ICON_WIDTH: "默认图标宽度",
VR_THUMB_SIZE: "缩略图大小",
VR_LIGHT_BG: "浅色模式缩略图背景",
VR_DARK_BG: "深色模式缩略图背景",
VR_SAVE: "保存",
VR_DELETE: "删除",
VR_NAME: "名称",
VR_PATTERN: "文件名或标题正则",
VR_FOLDER_PATTERN: "文件夹路径正则",
VR_EXTENSIONS: "文件扩展名",
VR_MAX_KB: "最大大小(KB)",
VR_PROPERTY: "文档属性或标签字段",
VR_PROPERTY_VALUE: "属性值",
VR_FRAME_TYPE: "画框类型",
VR_RULE_ERROR: "请检查规则名称和正则表达式。",
VR_LOADING: "正在加载资源…",
VR_NO_DRAWING: "选择可编辑的绘图、笔记或 Canvas 来插入资源。",
VR_EMPTY: "没有匹配的资源",
VR_ACTION_FAILED: "视觉资源操作失败。",
VR_INSERT_FAILED: "无法插入视觉资源。",
VR_NEW_WITH_FRAMEWORK: "用思考框架创建绘图",
VR_FRAMEWORK_FOLDER: "思考框架文件夹",
VR_FRAMEWORK_FOLDER_DESC: "留空则使用 Excalidraw 文件夹中的 Frameworks。",
VR_PROMPT_ON_BLANK: "创建空白绘图时推荐思考框架",
VR_DONT_SHOW: "创建空白绘图时不再显示",
VR_SHOW_LATER: "稍后显示",
VR_DOWNLOAD_FRAMEWORK: "下载框架库",
VR_UPDATE_FRAMEWORK: "更新框架库",
VR_REPLACE_FRAMEWORK: "替换已修改的框架库?",
VR_DOWNLOAD_FAILED: "无法下载框架库。",
// RankMessage.ts
RANK_MESSAGE_TITLE: "恭喜你,荣耀的骑士!",
RANK_MESSAGE_BODY: "你的库中已有 {{filecount}} 幅 Excalidraw 绘图,因此获得了新等级:**{{rank}}**!你的新称号是 **{{title}}**!\n\n过去 5 年多来,我一直在开发这个插件。如果你认可我的工作,欢迎通过 [Ko-Fi]({{koFiUrl}}) 支持我,或报名参加下一期 [Visual Thinking Workshop]({{workshopUrl}})。",
@@ -85,6 +212,8 @@ export default {
CLI_COPY_SKILL: "复制智能体说明",
CLI_AGENT_INSTRUCTIONS: `阅读:${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<用户指令>>`,
CLI_DESCRIPTION: "Excalidraw 原生 CLI",
CLI_COPY_SELECTION: "复制所选元素供智能体使用",
CLI_COPY_SELECTION_ERROR: "无法复制所选元素。请减少所选元素后重试。",
INITIALIZATION_MESSAGE: "等待所有插件就绪…",
// Sugester
@@ -420,6 +549,8 @@ export default {
SHOW_TAB_TITLEBAR_BUTTONS: "显示标签页标题栏按钮",
OPEN_LINK: "打开所选元素里的链接 \n(按住 Shift 在新面板打开)",
EXCALIDRAW_SIDEPANEL: "Excalidraw 侧边面板",
SIDEPANEL_POPOUT_NAME: "在独立窗口中打开 Excalidraw 侧边面板",
SIDEPANEL_POPOUT_DESC: "在桌面端启用后,下次显示 Excalidraw 侧边面板时会在独立窗口中打开。停用后,面板会停靠回侧边栏,但不会展开侧边栏。之后手动移动的位置会保留。",
LINK_BUTTON_CLICK_NO_TEXT: "请选择一个包含内部或外部链接的元素。\n",
LINEAR_ELEMENT_LINK_CLICK_ERROR:
`箭头和线条元素的链接无法通过 ${labelCTRL()} + 点击元素来跳转,因为这也会激活线条编辑器。\n` +
@@ -1207,9 +1338,9 @@ export default {
EMBED_THEME_BACKGROUND: "图像的主题和背景色",
EMBED_THEME_BACKGROUND_DESC:
"选择导出图像的背景和主题,以及预览是否跟随 Obsidian 主题。",
EMBED_IMAGE_CACHE_NAME: "为嵌入到 Markdown 文档中的绘图创建预览图缓存",
EMBED_IMAGE_CACHE_NAME: "缓存渲染图像和缩略图",
EMBED_IMAGE_CACHE_DESC:
"缓存用于嵌入 Markdown 的图像。绘图或其嵌套的仓库文件依赖发生变化时,缓存的绘图会刷新。",
"在此设备上缓存 Markdown 嵌入图像和视觉资源中的绘图缩略图。绘图或其依赖的仓库文件发生变化时,缓存会刷新。",
SCENE_IMAGE_CACHE_NAME: "缓存场景中嵌套的绘图",
SCENE_IMAGE_CACHE_DESC:
"Excalidraw 会识别嵌套绘图及其嵌入仓库文件源的变化,并相应更新缓存。" +
+133 -2
View File
@@ -11,6 +11,133 @@ declare const PLUGIN_VERSION: string;
// 繁體中文
export default {
// Visual Resources and Thinking Frameworks
VR_INSERT_SELECTED: "將選取的資源插入繪圖",
VR_HAS_NAMED_FRAMES: "有命名畫框",
VR_HAS_NAMED_FRAMES_DESC: "尋找以 Excalidraw 2.29.4 或更新版本儲存且含命名畫框的繪圖。",
VR_FILTER_DONE: "完成",
VR_FRAME_SEARCH_RULES: "畫框搜尋規則",
VR_COPY_PROMPT_DESC: "複製用於請 AI 助手編寫探索規則的說明。",
VR_PROMPT_COPIED: "已複製提示詞。",
VR_RULES_DESC: "正規表示式不區分大小寫。使用 (.+) 等擷取群組取得關鍵字。",
VR_RULE_POSITION: "規則 {CURRENT} / {TOTAL}",
VR_TEST_PATH: "依名稱或路徑尋找範例檔案",
VR_EXCLUSIONS_DESC: "使用逗號或換行分隔儲存庫路徑。",
VR_RULE_ADVANCED: "進階條件",
VR_NO_LIMIT: "無限制",
VR_TRANSPARENT: "透明",
VR_BROWSE_FRAMES: "瀏覽命名畫框",
VR_ICON_GROUPS: "儲存庫圖示分組",
VR_DRAWING_GROUPS: "繪圖分組",
VR_FRAME_GROUPS: "繪圖內的畫框分組",
VR_STENCIL_LIBRARIES: "範本庫",
VR_INSERT_TARGET: "插入到 {TITLE}",
VR_INSERT_NOTE: "插入到筆記",
VR_INSERT_CANVAS: "加入 Canvas",
VR_SVG_OPTIONS: "SVG 筆畫選項",
VR_SVG_PROPERTY: "來源連結屬性",
VR_KPLEX_DIRECTION: "從繪圖到 SVG 的關係方向",
VR_KPLEX_FIELD: "K-Plex 關係欄位",
VR_KPLEX_CHOOSE: "選擇關係欄位",
VR_REL_PARENT: "父層",
VR_REL_CHILD: "子層",
VR_REL_LEFT: "左側關聯",
VR_REL_RIGHT: "右側關聯",
VR_TITLE: "視覺資源",
VR_SEARCH: "搜尋視覺資源",
VR_FILTER: "篩選資源",
VR_COLLECTIONS: "收藏集",
VR_POPOUT: "在側欄和獨立視窗間切換",
VR_HELP: "視覺資源說明",
VR_HELP_TEXT: "可按標題、路徑或畫框名稱搜尋。用方向鍵移動,按 Enter 插入。在桌面端,按兩下開啟檔案,拖到畫布可在放置處插入。使用選單管理收藏和清單。",
VR_SETTINGS: "視覺資源設定",
VR_LAYOUT: "切換網格或清單",
VR_SELECT_ALL_FILTERS: "全選",
VR_SELECT_NO_FILTERS: "取消全選",
VR_EXIT_SELECTION: "退出多選模式",
VR_SELECTION_COUNT: "已選取 {COUNT} 項",
VR_RESIZE_FRAMES: "調整圖庫和畫框區域的大小",
VR_SELECT: "多選資源",
VR_SELECTED_ACTIONS: "對所選資源執行動作",
VR_BACK: "返回資源",
VR_ALL: "所有資源",
VR_FAVORITES: "最愛",
VR_FAVORITE: "加入最愛",
VR_UNFAVORITE: "移出最愛",
VR_NEW_PLAYLIST: "新增清單",
VR_RENAME: "重新命名",
VR_DELETE_PLAYLIST: "刪除清單",
VR_REMOVE_CURRENT: "從此清單移除",
VR_ADD_FILE: "加入儲存庫檔案",
VR_ICON: "儲存庫圖示",
VR_LUCIDE: "Lucide 圖示",
VR_ICON_LIBRARY: "圖示庫",
VR_IMAGE: "影像",
VR_DRAWING: "繪圖",
VR_FRAME: "命名畫框",
VR_MARKER_FRAME: "標記畫框",
VR_NOTE: "筆記",
VR_STENCIL: "圖形範本",
VR_FRAMEWORKS: "思考框架",
VR_OTHER: "其他視覺資源",
VR_ACTIONS: "資源動作",
VR_RESOURCE_INFO: "資源資訊",
VR_INSERT: "插入繪圖",
VR_INSERT_SVG: "插入連結的 SVG",
VR_INSERT_STROKES: "插入為可編輯筆畫",
VR_SVG_RETAIN_LINK: "將 SVG 來源連結加入繪圖屬性",
VR_OPEN_SOURCE: "在新分頁中開啟",
VR_REVEAL: "在檔案導覽中顯示",
VR_REVEAL_SYSTEM: "在系統檔案管理員中顯示",
VR_REVEAL_LIBRARY: "在檔案導覽中顯示所屬庫",
VR_REVEAL_LIBRARY_SYSTEM: "在系統檔案管理員中顯示所屬庫",
VR_ALL_LIBRARIES: "所有圖形範本庫",
VR_DEFAULT_LIBRARY: "預設庫",
VR_MANAGE_LIBRARIES: "管理圖形範本庫",
VR_MOVE_LIBRARY: "移至庫",
VR_CREATE_LIBRARY: "建立庫",
VR_DELETE_LIBRARY: "刪除庫",
VR_MOVE_AND_DELETE: "移動項目並刪除庫",
VR_LEGACY_LIBRARY: "要管理多個庫,請在設定中啟用在儲存庫內儲存圖形範本。",
VR_LIBRARY_STORAGE: "開啟圖形範本儲存設定",
VR_DISCOVERY: "探索規則",
VR_RULE: "新增規則",
VR_ADD_RULE: "加入規則",
VR_COPY_PROMPT: "複製 LLM 提示詞",
VR_PROMPT: "請用範例路徑幫我建立視覺資源探索規則。選擇圖示、繪圖或畫框。同一規則內所有條件均須符合,多個規則符合其一即可。檔名或畫框標題用不區分大小寫的 JavaScript 正規表示式,例如 ^icon - (.+)$,以擷取群組擷取關鍵字。可指定資料夾正規式、副檔名、大小上限(KB)、屬性或標籤及畫框類型。用範例說明符合結果。",
VR_TEST: "測試篩選",
VR_EXCLUSIONS: "排除資料夾",
VR_ICON_WIDTH: "預設圖示寬度",
VR_THUMB_SIZE: "縮圖大小",
VR_LIGHT_BG: "淺色模式縮圖背景",
VR_DARK_BG: "深色模式縮圖背景",
VR_SAVE: "儲存",
VR_DELETE: "刪除",
VR_NAME: "名稱",
VR_PATTERN: "檔名或標題正規式",
VR_FOLDER_PATTERN: "資料夾路徑正規式",
VR_EXTENSIONS: "副檔名",
VR_MAX_KB: "大小上限(KB)",
VR_PROPERTY: "文件屬性或標籤欄位",
VR_PROPERTY_VALUE: "屬性值",
VR_FRAME_TYPE: "畫框類型",
VR_RULE_ERROR: "請檢查規則名稱和正規表示式。",
VR_LOADING: "正在載入資源…",
VR_NO_DRAWING: "選擇可編輯的繪圖、筆記或 Canvas 來插入資源。",
VR_EMPTY: "沒有符合的資源",
VR_ACTION_FAILED: "視覺資源動作失敗。",
VR_INSERT_FAILED: "無法插入視覺資源。",
VR_NEW_WITH_FRAMEWORK: "使用思考框架建立繪圖",
VR_FRAMEWORK_FOLDER: "思考框架資料夾",
VR_FRAMEWORK_FOLDER_DESC: "留空會使用 Excalidraw 資料夾中的 Frameworks。",
VR_PROMPT_ON_BLANK: "建立空白繪圖時提供思考框架",
VR_DONT_SHOW: "建立空白繪圖時不再顯示",
VR_SHOW_LATER: "稍後顯示",
VR_DOWNLOAD_FRAMEWORK: "下載框架庫",
VR_UPDATE_FRAMEWORK: "更新框架庫",
VR_REPLACE_FRAMEWORK: "要取代已修改的框架庫嗎?",
VR_DOWNLOAD_FAILED: "無法下載框架庫。",
// RankMessage.ts
RANK_MESSAGE_TITLE: "恭喜你,榮耀的騎士!",
RANK_MESSAGE_BODY: "你的儲存庫中已有 {{filecount}} 幅 Excalidraw 繪圖,因此獲得了新等級:**{{rank}}**!你的新稱號是 **{{title}}**!\n\n過去 5 年多來,我一直在開發這個外掛。如果你認同我的工作,歡迎透過 [Ko-Fi]({{koFiUrl}}) 支持我,或報名參加下一期 [Visual Thinking Workshop]({{workshopUrl}})。",
@@ -85,6 +212,8 @@ export default {
CLI_COPY_SKILL: "複製代理程式說明",
CLI_AGENT_INSTRUCTIONS: `閱讀:${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<使用者指令>>`,
CLI_DESCRIPTION: "Excalidraw 原生 CLI",
CLI_COPY_SELECTION: "複製所選元素供代理程式使用",
CLI_COPY_SELECTION_ERROR: "無法複製所選元素。請減少所選元素後重試。",
INITIALIZATION_MESSAGE: "等待所有外掛就緒…",
// Sugester
@@ -420,6 +549,8 @@ export default {
SHOW_TAB_TITLEBAR_BUTTONS: "顯示標籤頁標題欄按鈕",
OPEN_LINK: "開啟所選元素裡的連結 \n(按住 Shift 在新面板開啟)",
EXCALIDRAW_SIDEPANEL: "Excalidraw 側邊面板",
SIDEPANEL_POPOUT_NAME: "在獨立視窗中開啟 Excalidraw 側邊面板",
SIDEPANEL_POPOUT_DESC: "在桌面端啟用後,下次顯示 Excalidraw 側邊面板時會在獨立視窗中開啟。停用後,面板會停駐回側邊欄,但不會展開側邊欄。之後手動移動的位置會保留。",
LINK_BUTTON_CLICK_NO_TEXT: "請選擇一個包含內部或外部連結的元素。\n",
LINEAR_ELEMENT_LINK_CLICK_ERROR:
`箭頭和線條元素的連結無法透過 ${labelCTRL()} + 點選元素來跳轉,因為這也會啟用線條編輯器。\n` +
@@ -1207,9 +1338,9 @@ export default {
EMBED_THEME_BACKGROUND: "影像的主題和背景色",
EMBED_THEME_BACKGROUND_DESC:
"選擇匯出影像的背景和主題,以及預覽是否跟隨 Obsidian 主題。",
EMBED_IMAGE_CACHE_NAME: "為嵌入到 Markdown 文件中的繪圖建立預覽圖快取",
EMBED_IMAGE_CACHE_NAME: "快取轉譯影像與縮圖",
EMBED_IMAGE_CACHE_DESC:
"快取用於嵌入 Markdown 的影像。繪圖或其巢狀的倉庫檔案相依項發生變化時,快取的繪圖會重新整理。",
"在此裝置上快取 Markdown 嵌入影像及視覺資源中的繪圖縮圖。繪圖或其相依的倉庫檔案發生變更時,快取會重新整理。",
SCENE_IMAGE_CACHE_NAME: "快取場景中巢狀的繪圖",
SCENE_IMAGE_CACHE_DESC:
"Excalidraw 會識別巢狀繪圖及其嵌入倉庫檔案來源的變化,並相應更新快取。" +
@@ -3,12 +3,13 @@ import type { ExcalidrawFrameElement } from "@zsviczian/excalidraw/types/element
import type ExcalidrawView from "src/view/ExcalidrawView";
import type { EmbeddedFile } from "src/shared/EmbeddedFileLoader";
import { getDrawingPreviewParts, rewriteDrawingPreviewLink, type DrawingPreviewChanges } from "src/utils/drawingPreviewLink";
import { setStyle } from "src/utils/styleUtils";
import { FloatingModal } from "./FloatingModal";
import { t } from "src/lang/helpers";
import { OUTER_PADDING_MAX } from "src/utils/drawingPadding";
/** Draft image-link controls: preview locally, then commit once after choosing scope. */
export class DrawingImagePreviewPopover extends Component {
export class DrawingImagePreviewPopover extends FloatingModal {
private events: Component | null = null;
private popup: HTMLElement;
private image: HTMLImageElement;
private timer: number | null = null;
@@ -18,20 +19,27 @@ export class DrawingImagePreviewPopover extends Component {
private readonly original: string;
private readonly changes: DrawingPreviewChanges = {};
constructor(private readonly view: ExcalidrawView, private readonly source: EmbeddedFile,
constructor(view: ExcalidrawView, private readonly source: EmbeddedFile,
private readonly frames: readonly ExcalidrawFrameElement[], private readonly defaultPadding: number, private readonly areaPaddingMax: number,
private readonly isCurrent: () => boolean,
private readonly render: (link: string) => Promise<{ image: { dataURL: string } }>,
private readonly commit: (changes: DrawingPreviewChanges) => Promise<boolean>, private readonly closed: () => void) {
super(); this.original = source.linkParts.original;
super(view.app); this.original = source.linkParts.original;
}
/** Mount in the selected image's owning window, outside canvas paint containment. */
onload(): void {
protected shouldNotStartDrag(target: HTMLElement, event: PointerEvent | TouchEvent): boolean {
return !!target.closest(".setting-item-control") || super.shouldNotStartDrag(target, event);
}
/** Use the shared draggable modal without blocking interaction with the drawing. */
onOpen(): void {
this.active = true;
const doc = this.view.ownerDocument, win = doc.defaultView;
this.popup = doc.body.createDiv({ cls: "excalidraw-drawing-preview-popover", attr: { role: "dialog", "aria-label": t("PREVIEW_CONFIGURE") } });
this.popup.createEl("strong", { text: t("PREVIEW_CONFIGURE") });
this.events = new Component(); this.events.load();
const doc = this.modalEl.ownerDocument;
this.modalEl.addClass("excalidraw-drawing-preview-popover");
this.modalEl.setAttribute("aria-label", t("PREVIEW_CONFIGURE"));
this.setTitle(t("PREVIEW_CONFIGURE"));
this.popup = this.contentEl;
this.popup.createDiv({ cls: "setting-item-description", text: t("PREVIEW_CONFIGURE_HELP") });
this.image = this.popup.createDiv({ cls: "excalidraw-drawing-preview-image" }).createEl("img", { attr: { alt: t("PREVIEW_VIEW") } });
const parts = getDrawingPreviewParts(this.original), ref = parts.blockref ?? parts.sectionref;
@@ -86,36 +94,24 @@ export class DrawingImagePreviewPopover extends Component {
const buttons = this.popup.createDiv({ cls: "excalidraw-drawing-preview-buttons" });
const cancel = buttons.createEl("button", { text: t("PROMPT_BUTTON_CANCEL"), attr: { type: "button" } });
const apply = buttons.createEl("button", { text: t("PREVIEW_APPLY"), cls: "mod-cta", attr: { type: "button" } });
this.registerDomEvent(cancel, "click", () => { if (!this.applying) this.unload(); });
this.events.registerDomEvent(cancel, "click", () => { if (!this.applying) this.close(); });
const save = async () => {
if (this.applying || !this.current()) return;
if (!Object.keys(this.changes).length) { this.unload(); return; }
if (!Object.keys(this.changes).length) { this.close(); return; }
this.applying = true; apply.disabled = true;
try { if (await this.commit({ ...this.changes })) this.unload(); }
try { if (await this.commit({ ...this.changes })) this.close(); }
finally { this.applying = false; apply.disabled = false; }
};
this.registerDomEvent(apply, "click", () => { void save(); });
this.registerDomEvent(this.popup, "pointerdown", event => event.stopPropagation());
this.registerDomEvent(this.popup, "wheel", event => event.stopPropagation());
this.registerDomEvent(doc, "pointerdown", event => { if (!this.applying && !event.composedPath().includes(this.popup)) this.unload(); });
this.registerDomEvent(doc, "keydown", event => {
if (event.key === "Escape" && !this.applying) { event.preventDefault(); event.stopPropagation(); this.unload(); }
this.events.registerDomEvent(apply, "click", () => { void save(); });
this.events.registerDomEvent(this.popup, "wheel", event => event.stopPropagation());
this.events.registerDomEvent(doc, "keydown", event => {
if (event.key === "Escape" && !this.applying) { event.preventDefault(); event.stopPropagation(); this.close(); }
}, true);
this.registerDomEvent(win, "resize", () => this.place());
this.registerDomEvent(win, "blur", () => { if (!this.applying) this.unload(); });
this.place(); this.queuePreview(); this.popup.querySelector("select")?.focus();
this.queuePreview();
}
private current(): boolean { return this.active && this.isCurrent(); }
private place(): void {
if (!this.current()) { this.unload(); return; }
const anchor = this.view.excalidrawContainer.querySelector(".excalidraw-selected-element-menu") ?? this.view.excalidrawContainer;
const bounds = anchor.getBoundingClientRect(), popup = this.popup.getBoundingClientRect(), win = this.popup.ownerDocument.defaultView;
setStyle(this.popup, { left: `${Math.max(8, Math.min(bounds.left, win.innerWidth - popup.width - 8))}px`,
top: `${Math.max(8, Math.min(bounds.bottom + 4, win.innerHeight - popup.height - 8))}px` });
}
private queuePreview(): void {
const generation = ++this.generation;
if (this.timer !== null) window.clearTimeout(this.timer);
@@ -124,15 +120,17 @@ export class DrawingImagePreviewPopover extends Component {
if (!link || !this.current()) return;
try {
const result = await this.render(link);
if (this.current() && generation === this.generation) { this.image.src = result.image.dataURL; this.place(); }
if (this.current() && generation === this.generation) { this.image.src = result.image.dataURL; }
} catch { /* The owned controller reports apply failures; a stale draft never writes. */ }
})(); }, 300);
}
/** Cancel delayed renders and release this window's controls without a scene write. */
onunload(): void {
onClose(): void {
if (!this.active) return;
this.active = false; this.generation++;
if (this.timer !== null) window.clearTimeout(this.timer);
this.timer = null; this.popup?.remove(); this.closed();
this.timer = null; this.events?.unload(); this.events = null;
this.contentEl.empty(); this.closed();
}
}
+7 -1
View File
@@ -98,6 +98,7 @@ function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
export class FloatingModal extends Modal {
private dragging = false;
private openTimer: number | null = null;
private offsetX = 0;
private offsetY = 0;
private readonly pointerDownHandler: (e: PointerEvent | TouchEvent) => void;
@@ -270,7 +271,8 @@ export class FloatingModal extends Modal {
// prevent automatic selection / focus restoration
this.shouldRestoreSelection = false;
}
window.setTimeout(() => {
this.openTimer = window.setTimeout(() => {
this.openTimer = null;
const { containerEl, modalEl, bgEl } = this;
containerEl.addClass("mod-excalidraw-draggable");
@@ -336,6 +338,10 @@ export class FloatingModal extends Modal {
}
close(): void {
if (this.openTimer !== null) {
window.clearTimeout(this.openTimer);
this.openTimer = null;
}
// Optional: restore previous focus if body ended up focused
if (
this.disableKeyCapture &&
+26 -1
View File
@@ -17,6 +17,20 @@ 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.30.0": `
## New and improved
- Browse visuals, named frames, stencils, and Lucide icons in **Visual Resources**. Organize favorites and playlists, and insert vault visuals into Excalidraw, Markdown, or Obsidian Canvas.
- Start a new drawing with an editable **Thinking Framework**, or choose **Blank drawing** to start from scratch.
## Fixed
- Drawings that open in Markdown embed as drawings unless \`excalidraw-embed-md\` is enabled, and Page Preview honors the hover setting again.
`,
"2.29.4": `
## New and improved
- Choose whether the Excalidraw sidepanel opens in the sidebar or a separate desktop window under **Excalidraw appearance and behavior → UI Modes**. [#3053](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUE_3053})
- Copy selected canvas elements for an agent to edit, including their bound labels and exact drawing targets. [CLI #3](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI_ISSUE_3}) CLI agents can also insert linked drawing images and create longer filled line contours.
- Scripts can convert between lines and free-draw strokes while preserving curved paths, and join compatible line sections. [CLI #6](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI_ISSUE_6}) Custom free-draw styling can look different on excalidraw.com.
`,
"2.29.3": `
## New and improved
- Choose OpenAI reasoning effort per text model and use updated AI model recommendations on new installs. ExcaliAI uses the selected model's effort. [#3056](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3056).
@@ -24,10 +38,21 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
- Create a **New Drawing** from empty tabs. Hide this action and the ribbon icon independently in settings. [#3047](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3047).
- PNG fullscreen previews open faster, then sharpen in the background while preserving zoom and pan.
- Press P again while using the pen to return to the selection tool. [#3044](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3044).
- Configure drawing images directly in the scene: choose a view, padding and original-size anchoring, then update one image or all copies of the same drawing.
- Configure nested excalidraw images directly in the scene: choose a view, padding and original-size anchoring, then update one image or all copies of the same drawing.
- Choose a named frame or marker frame as the drawing thumbnail, pick frames from embed controls, and use **Navigate to frame** to jump within a drawing. Named frames are listed in the document's \`excalidraw-anchors\` property. [#3042](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3042).
- Adjust outer padding for thumbnails, whole scenes and frames, or expand the captured area of \`area=\` drawing embeds from their Live Preview toolbar. Preview changes with the slider, then close it to save; Escape cancels. Inspired by 🙏[Evgene-Kopylov](${URLs.GITHUB_COM}/Evgene-Kopylov) [#2868](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2868).
## New and improved from Excalidraw.com
- **Keep editing across apps.** Switching to another app and back no longer ends text editing. [#12675](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12675).
- **Flowchart navigation.** Alt/Option+arrow keys choose nearby nodes more predictably, including in uneven layouts. [#12646](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12646).
- **Drawing minimap and zoom menu.** Navigate large drawings with the minimap beside the zoom level on desktop/tablet, or select the zoom level for zoom-to-fit and zoom-to-selection. [#12605](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12605).
- **Text wrapping.** Drag the sides of standalone text while editing to set its wrap width, or toggle auto-resize with Alt/Option+W. [#12634](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12634), [#12672](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12672).
- **Zoom while editing.** Keyboard zoom keeps the text cursor in place on screen. [#12622](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12622).
- **Steadier text.** Center- and right-aligned text no longer jumps while typing at different zoom levels. [#12623](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12623).
- **Wrap and unwrap.** W includes enclosed elements when framing a selection and keeps existing shapes when detaching their text. [#12638](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12638).
- **Smoother large drawings.** Pan large scenes and draw frames around large groups with less lag. [#12489](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12489), [#12692](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12692).
- **Toolbar hints.** Your **Preferences → Toolbar hints** choice is now saved with each drawing. [#12165](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12165).
## Fixed
- Scroll embedded Markdown directly in reading mode, including when **Lock to reading mode** is enabled. [#3055](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3055).
- Drawing embed controls appear in Live Preview tables and remain reachable in phone Reading view. [#3049](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3049).
+1 -1
View File
@@ -37,7 +37,7 @@ export class OpenFileDialog extends FuzzySuggestModal<TFile> {
this.inputEl.onkeyup = (e) => {
if (e.key == "Enter" && this.action == openDialogAction.openFile) {
if (this.containerEl.innerText.includes(EMPTY_MESSAGE)) {
void this.plugin.createAndOpenDrawing(
void this.plugin.createAndOpenInteractiveDrawing(
`${this.plugin.settings.folder}/${this.inputEl.value}.excalidraw.md`,
this.onNewPane ? "new-pane" : "active-pane",
);
+20 -1
View File
@@ -500,7 +500,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"Creates a mermaid diagram and returns the ids of the created elements as a string[]. " +
"The elements will be added to ea. To add them to the canvas you'll need to use addElementsToView. " +
"Depending on the diagram type the result will be either a single SVG image, or a number of excalidraw elements.<br>" +
"If there is an error, the function returns a string with the error message.",
"If there is an error, the function returns a string with the error message. " +
"In one-shot CLI scripts, unavailable, disabled or incompatible Excalidraw Extras Mermaid throws DEPENDENCY_UNAVAILABLE without opening an activation modal; inspect CLI status.extras before conversion.",
after: "",
},
{
@@ -527,6 +528,24 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Adds a text label to a line or arrow. Currently only works with a simple straight 2-point (start & end) line",
after: "",
},
{
field: "convertLineToFreedraw",
after: "",
code: "convertLineToFreedraw(id: string, options?: StrokeConversionOptions): StrokeConversionResult;",
desc: "Converts a line already copied into the EA workbench to free-draw, retaining its ID, frame, groups and unrelated metadata. Rounded curves are sampled within tolerance (default 0.5 scene units); maxPoints defaults to 10000. Options also accept strokeWidth and the fork's full penOptions. Returns id, type, pointCount and warnings. Custom options are ignored by excalidraw.com. Labels/arrowheads and exceeded budgets are refused without mutation. Publish and save explicitly.",
},
{
field: "convertFreedrawToLine",
after: "",
code: "convertFreedrawToLine(id: string, options?: StrokeConversionOptions): StrokeConversionResult;",
desc: "Fits a copied workbench free-draw centerline to an editable polyline, retaining its ID. tolerance bounds simplification error (default 0.5 scene units); maxPoints defaults to 10000. Pressure, taper and custom cap/outline behavior are removed. Nominal width is approximated unless strokeWidth is supplied. Returns JSON-safe id, type, pointCount and warnings. Does not publish/save; invalid input leaves the workbench unchanged.",
},
{
field: "concatenateLines",
after: "",
code: "concatenateLines(ids: string[], options?: ConcatenateLinesOptions): ConcatenateLinesResult;",
desc: "Joins 2–100 compatible open workbench lines by nearby endpoints, allowing reversed/rotated paths and sharp corners. maxGap defaults to 1 scene unit, tolerance to 0.5, maxPoints to 10000. Rounded segments are sampled before joining. The first ID survives and removedIds are staged as deleted. Styles, frame, groups and metadata must match; labels, arrowheads and disconnected/branching sets are refused without partial mutation. Returns id, removedIds, pointCount and warnings. Publish/save explicitly.",
},
{
field: "clear",
code: "clear(): void;",
@@ -0,0 +1,114 @@
import { Component, Modal, Setting } from "obsidian";
import type ExcalidrawPlugin from "src/core/main";
import { navigateToSettingsPage } from "src/core/settings/settingsNavigation";
import { t } from "src/lang/helpers";
import type { VisualResource } from "src/types/visualResourceTypes";
import type { LibraryItem } from "@zsviczian/excalidraw/types/excalidraw/types";
import { setElementHidden } from "src/utils/htmlUtils";
import { VisualResourceGallery, visualResourceButton } from "../visualResources/VisualResourceGallery";
import { filterVisualResources, frameworkResource } from "../visualResources/visualResourceModel";
export type FrameworkChoice = { kind: "framework"; item: LibraryItem } | { kind: "blank" } | { kind: "cancel" };
const SNOOZE = 7 * 24 * 60 * 60 * 1000;
/** Centered new-drawing chooser. The result is settled before any file or leaf is created. */
export class ThinkingFrameworksPicker extends Modal {
public readonly result: Promise<FrameworkChoice>;
private finish: (choice: FrameworkChoice) => void;
private readonly lifetime = new Component();
private openPicker = false;
constructor(private readonly plugin: ExcalidrawPlugin) {
super(plugin.app);
this.result = new Promise(resolve => { this.finish = resolve; });
}
/** Render the same local resource gallery with blank and snooze actions. */
public onOpen(): void {
const service = this.plugin.visualResources;
const catalog = service.frameworks;
this.openPicker = true;
this.lifetime.load();
this.setTitle(t("VR_FRAMEWORKS"));
const root = this.contentEl.createDiv({ cls: "excalidraw-framework-picker" });
const toolbar = root.createDiv({ cls: "excalidraw-resource-toolbar" });
const search = toolbar.createEl("input", { type: "search", placeholder: t("VR_SEARCH"), attr: { "aria-label": t("VR_SEARCH") } });
const update = visualResourceButton(toolbar, "download", t("VR_UPDATE_FRAMEWORK"));
setElementHidden(update, true);
const settings = visualResourceButton(toolbar, "settings", t("VR_SETTINGS"));
settings.onclick = () => {
this.plugin.app.setting.open();
if (!navigateToSettingsPage(this.plugin.app, this.plugin.manifest.id, [t("BASIC_HEAD"), t("BASIC_FILES_FOLDERS_HEAD")])) {
this.plugin.app.setting.openTabById(this.plugin.manifest.id);
}
};
const actions = root.createDiv({ cls: "excalidraw-framework-actions" });
const download = actions.createEl("button", { text: t("VR_DOWNLOAD_FRAMEWORK"), attr: { type: "button" } });
setElementHidden(download, true);
const blank = actions.createEl("button", { text: t("PROMPT_BLANK_DRAWING"), cls: "mod-cta", attr: { type: "button" } });
blank.onclick = () => this.choose({ kind: "blank" });
const later = actions.createEl("button", { text: t("VR_SHOW_LATER"), attr: { type: "button" } });
later.onclick = () => {
this.plugin.settings.frameworksSnoozedUntil = Date.now() + SNOOZE;
void this.plugin.saveSettings();
this.choose({ kind: "blank" });
};
let resources: VisualResource[] = [];
const gallery = this.lifetime.addChild(new VisualResourceGallery(root, service, {
activate: resource => {
void service.libraryItem(resource.locator).then(item => {
if (!this.openPicker || !item) return;
this.choose({ kind: "framework", item });
}).catch(() => catalog.notifyFailure());
},
favorite: resource => {
const record = service.collections.state(resource.locator);
void service.collections.curate([resource.locator], { favorite: !record.favorite }).catch(() => catalog.notifyFailure());
},
}));
const redraw = () => {
if (this.openPicker) gallery.show(filterVisualResources(resources, search.value, ["framework"]));
};
const load = async () => {
const local = await catalog.list();
if (!this.openPicker) return;
resources = local.map(({ path, item }) => frameworkResource(path, item));
setElementHidden(download, !!resources.length);
redraw();
};
const install = async () => {
update.disabled = download.disabled = true;
try { await catalog.install(); await load(); setElementHidden(update, !(await catalog.updates()).length); }
catch { if (this.openPicker) catalog.notifyFailure(); }
finally { update.disabled = download.disabled = false; }
};
update.onclick = download.onclick = () => { void install(); };
search.oninput = redraw;
search.onkeydown = event => { if (event.key === "ArrowDown") { event.preventDefault(); gallery.focusFirst(); } };
new Setting(root).setName(t("VR_DONT_SHOW")).addToggle(toggle => toggle
.setValue(!this.plugin.settings.frameworksOnBlank).onChange(value => {
this.plugin.settings.frameworksOnBlank = !value;
this.plugin.settings.frameworksSnoozedUntil = 0;
void this.plugin.saveSettings();
}));
this.lifetime.register(service.collections.subscribe(redraw));
void service.collections.refresh().catch(() => {});
void load().catch(() => catalog.notifyFailure());
void catalog.updates().then(updates => {
if (this.openPicker) setElementHidden(update, !updates.length);
}).catch(() => {});
}
private choose(choice: FrameworkChoice): void {
this.finish(choice);
this.close();
}
/** Dismissing the picker is an explicit cancellation. */
public onClose(): void {
this.openPicker = false;
this.finish({ kind: "cancel" });
this.lifetime.unload();
this.contentEl.empty();
}
}
+11 -2
View File
@@ -172,6 +172,8 @@ type LoadImageOptions = {
onStaleCacheHit?: (validation: DeferredCacheValidation) => void;
deferUncachedExcalidraw?: boolean;
onExcalidrawGenerationDeferred?: () => void;
/** Reuse a bounded Excalidraw cache entry without generating a new SVG. */
cachedExcalidrawMaxBytes?: number;
markdownTransclusionRender?: MarkdownImageRenderSettings;
fileId?: FileId;
pdfScale?: number;
@@ -874,6 +876,7 @@ export class EmbeddedFilesLoader {
public async getObsidianImage(
inFile: TFile | EmbeddedFile,
depth: number,
options?: LoadImageOptions,
): Promise<{
mimeType: MimeType;
fileId: FileId;
@@ -884,7 +887,7 @@ export class EmbeddedFilesLoader {
pdfPageViewProps?: PDFPageViewProps;
}> {
try {
return await this._getObsidianImage(inFile, depth);
return await this._getObsidianImage(inFile, depth, options);
} finally {
this.emptyPDFDocsMap();
}
@@ -901,6 +904,7 @@ export class EmbeddedFilesLoader {
bypassCache = false,
onStaleCacheHit,
deferUncachedGeneration = false,
cachedPreviewMaxBytes,
}: {
isDark: boolean;
file: TFile;
@@ -912,6 +916,7 @@ export class EmbeddedFilesLoader {
bypassCache?: boolean;
onStaleCacheHit?: (validation: DeferredCacheValidation) => void;
deferUncachedGeneration?: boolean;
cachedPreviewMaxBytes?: number;
}): Promise<{
dataURL: DataURL;
hasSVGwithBitmap: boolean;
@@ -989,6 +994,8 @@ export class EmbeddedFilesLoader {
expectedPayloadKind: "svg",
requireSvgInspectionMetadata: true,
svgFormat: "data-url",
maxPayloadBytes: cachedPreviewMaxBytes,
maxIntrinsicDimension: cachedPreviewMaxBytes === undefined ? undefined : 16_384,
onCacheHit: ({ mtime, size, hasSVGwithBitmap }) => {
cachedSize = size;
cachedHasSVGwithBitmap = hasSVGwithBitmap;
@@ -1016,7 +1023,7 @@ export class EmbeddedFilesLoader {
};
}
if (deferUncachedGeneration) {
if (deferUncachedGeneration || cachedPreviewMaxBytes !== undefined) {
return {
dataURL: null,
hasSVGwithBitmap,
@@ -1056,6 +1063,7 @@ export class EmbeddedFilesLoader {
depth + 1,
getExportPadding(this.plugin, file),
);
if (this.terminate) return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
const svg = replaceSVGColors(
generatedSVG,
inFile instanceof EmbeddedFile ? inFile.colorMap : null,
@@ -1247,6 +1255,7 @@ export class EmbeddedFilesLoader {
bypassCache: options?.bypassCache,
onStaleCacheHit: options?.onStaleCacheHit,
deferUncachedGeneration: options?.deferUncachedExcalidraw,
cachedPreviewMaxBytes: options?.cachedExcalidrawMaxBytes,
});
if (this.terminate) {
return null;
+44
View File
@@ -4,6 +4,11 @@ import type { LucideIconOptions, LucideIconResult } from "src/types/lucideTypes"
import ExcalidrawPlugin from "src/core/main";
import LZString from "lz-string";
import type { ExcalidrawCLIRequest, ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
import { isCLIScript } from "src/core/cli/cliScriptContext";
import { CLIError } from "src/core/cli/cliProtocol";
import { convertWorkbenchStroke } from "src/utils/strokeConversion";
import { concatenateWorkbenchLines } from "src/utils/strokeConcatenation";
import type { ConcatenateLinesOptions, ConcatenateLinesResult, StrokeConversionOptions, StrokeConversionResult } from "src/types/strokeConversionTypes";
import {
FillStyle,
StrokeStyle,
@@ -1402,6 +1407,36 @@ export class ExcalidrawAutomate {
return this.elementsDict[id];
}
/**
* Convert a copied workbench line to a free-draw stroke, sampling rounded curves
* within tolerance (default 0.5 scene units). Retains its ID/frame/groups/metadata.
* Custom pen options are ignored by excalidraw.com. Returns warnings and point count;
* does not publish/save. Throws before mutation for unsupported relationships or budgets.
*/
public convertLineToFreedraw(id: string, options: StrokeConversionOptions = {}): StrokeConversionResult {
return convertWorkbenchStroke(this, id, "freedraw", options);
}
/**
* Fit a copied workbench free-draw centerline to an editable polyline, retaining ID.
* Default error tolerance is 0.5 scene units. Pressure/custom pen behavior is lost;
* nominal width is approximated unless strokeWidth is supplied. Does not publish/save.
* Throws without mutation on invalid input or exceeded geometry/work budgets.
*/
public convertFreedrawToLine(id: string, options: StrokeConversionOptions = {}): StrokeConversionResult {
return convertWorkbenchStroke(this, id, "line", options);
}
/**
* Join 2–100 compatible open workbench lines through nearby endpoints (default gap 1).
* Samples rounded segments, handles reversed/rotated paths and keeps sharp junctions.
* Retains the first ID; stages the other IDs as deleted. Rejects disconnected sets,
* incompatible styles/metadata and labels/arrowheads without any mutation. Publish/save explicitly.
*/
public concatenateLines(ids: string[], options: ConcatenateLinesOptions = {}): ConcatenateLinesResult {
return concatenateWorkbenchLines(this, ids, options);
}
/**
* Returns an object describing the bound text element.
*
@@ -2953,11 +2988,20 @@ export class ExcalidrawAutomate {
* @param {string} diagram - The mermaid diagram string.
* @param {boolean} [groupElements=true] - Whether to group the elements.
* @returns {Promise<string[]|string>} Promise resolving to the IDs of the created elements or an error message.
* @throws CLI dependency error when Extras Mermaid is unavailable, disabled or incompatible in a one-shot CLI invocation.
*/
async addMermaid(
diagram: string,
groupElements: boolean = true,
): Promise<string[] | string> {
if (isCLIScript(this)) {
const gateway = this.plugin.extrasGateway;
const api = gateway.getAPI();
if (!api || !gateway.checkVersion("mermaid", api).valid || !api.features.isActive("mermaid")) {
throw new CLIError("DEPENDENCY_UNAVAILABLE", "CLI Mermaid conversion requires compatible, enabled Excalidraw Extras Mermaid.", undefined,
"Inspect status.extras, update Excalidraw Extras and enable Mermaid before retrying. Read back any earlier script writes first.");
}
}
const result = await mermaidToExcalidraw(diagram, {
themeVariables: { fontSize: `${this.style.fontSize}` },
flowchart: { curve: this.style.roundness === null ? "linear" : "basis" },
+2 -3
View File
@@ -83,6 +83,7 @@ import {
import {
changeThemeOfExcalidrawMD,
DRAWING_COMPRESSED_REG,
EMBEDDED_VAULT_FILE_REG,
getExcalidrawMarkdownHeader,
getExcalidrawMarkdownHeaderSection,
getJSON,
@@ -1077,9 +1078,7 @@ export class ExcalidrawData {
? data.substring(indexOfNewEmbeddedFiles + embeddedFilesNewLength)
: data.substring(indexOfOldEmbeddedFiles + embeddedFilesOldLength);
//Load Embedded files
const REG_FILEID_FILEPATH =
/([\w\d]*):\s*!?\[\[([^\]]*)]]\s*(\{[^}]*})?\n/gm;
res = data.matchAll(REG_FILEID_FILEPATH);
res = data.matchAll(EMBEDDED_VAULT_FILE_REG);
while (!(parts = res.next()).done) {
const embeddedFile = new EmbeddedFile(
this.plugin,
+6
View File
@@ -44,6 +44,8 @@ export type ImageKey = {
} & FILENAMEPARTS;
type GetImageFromCacheOptions = {
maxPayloadBytes?: number;
maxIntrinsicDimension?: number;
skipDependencyCheck?: boolean;
minRenderScale?: number;
expectedPayloadKind?: FileCacheData["payloadKind"];
@@ -547,6 +549,9 @@ class ImageCache {
this.touchedCacheKeys.delete(key);
return undefined;
}
if (options?.maxPayloadBytes !== undefined && cachedData.blob.size > options.maxPayloadBytes) return undefined;
if (options?.maxIntrinsicDimension !== undefined && cachedData.size &&
Math.max(cachedData.size.height, cachedData.size.width) > options.maxIntrinsicDimension) return undefined;
const file = this.app.vault.getFileByPath(key_.filepath.split("#")[0]);
if (!file) {
@@ -785,6 +790,7 @@ class ImageCache {
}
public async clearImageCache(): Promise<void> {
await this.plugin?.visualResources?.clearThumbnailCache();
if (!this.isReady()) {
return; // Database not initialized yet
}
+25 -2
View File
@@ -5,7 +5,7 @@ import {
TAbstractFile,
TFile,
} from "obsidian";
import { PLUGIN_ID } from "../constants/constants";
import { PLUGIN_ID, SCRIPT_INSTALL_FOLDER } from "../constants/constants";
import ExcalidrawView from "../view/ExcalidrawView";
import ExcalidrawPlugin from "../core/main";
import { GenericInputPrompt, GenericSuggester } from "./Dialogs/Prompt";
@@ -797,7 +797,7 @@ export class ScriptEngine {
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
void this.executeScriptFile(view, f, scriptName);
void this.runPaletteScript(view, f, scriptName);
return true;
}
return false;
@@ -807,6 +807,29 @@ export class ScriptEngine {
await iconLoad;
}
private async runPaletteScript(view: ExcalidrawView, file: TFile, scriptName: string): Promise<void> {
if (file.basename === "Icon Library" && scriptName.startsWith(SCRIPT_INSTALL_FOLDER + "/") && this.plugin.visualResourcePanel) {
// This checksum names the distributed Icon Library revision that the native
// browser replaces. A user-edited script keeps its original command behavior.
const stock = "85c939dc4b26755d00f1f74008dca0d1c03b4796f398d03cf62bc05b5a4541a1";
try {
const api = view.excalidrawAPI;
const target = view.file;
const source = (await this.app.vault.cachedRead(file)).replaceAll("\r\n", "\n").trim();
const bytes = await view.ownerWindow.crypto.subtle.digest("SHA-256", new TextEncoder().encode(source));
const digest = Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, "0")).join("");
if (view.file !== target || view.excalidrawAPI !== api || view.isClosingOrMigrating()) return;
if (digest === stock) {
await this.plugin.visualResourcePanel.open(view, scriptName);
return;
}
} catch (error: unknown) {
errorlog({ where: "ScriptEngine.runPaletteScript", scriptName, error });
}
}
await this.executeScriptFile(view, file, scriptName);
}
unloadScripts() {
Array.from(this.loadedScriptPaths).forEach((path) => {
this.unloadScript(this.getScriptName(path), path);
+7 -35
View File
@@ -2,13 +2,10 @@
* this consumer validates bounded detached data and retains only the offered API incarnation.
* Every read reacquires the public window entry point, including after reload or in a popout. */
type DataRecord = Record<string, unknown>;
type PublicRead = (this: DataRecord, ...args: unknown[]) => unknown;
import { getKplexPublicRead, isPublicRecord as record } from "src/utils/kplexPublicApi";
export type OntologyFieldSuggestion = Readonly<{name: string; partner?: string; description?: string}>;
export type OntologyCompletionOffer = Readonly<{
provider: DataRecord;
api: DataRecord;
read: PublicRead;
export type OntologyCompletionOffer = Readonly<NonNullable<ReturnType<typeof getKplexPublicRead>> & {
configuration: number;
text: string;
cursor: number;
@@ -20,25 +17,6 @@ const MAX_TEXT = 65_536;
const MAX_ITEMS = 100;
const MAX_OUTPUT = 1_048_576;
/** Narrow only plain object-shaped protocol values; arrays are never envelopes or API roots. */
function record(value: unknown): value is DataRecord {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/** A public method is invoked with its captured API as receiver, preserving service ownership. */
function callable(value: unknown): value is PublicRead {
return typeof value === "function";
}
/** Read the documented public root, preferring the input's realm and its supported popout alias. */
function providerFor(input: HTMLInputElement | HTMLTextAreaElement): DataRecord | null {
const owner = input.ownerDocument.defaultView ?? window;
const local: unknown = Reflect.get(owner, "kplexApi");
if (record(local)) return local;
const main: unknown = Reflect.get(window, "kplexApi");
return record(main) ? main : null;
}
/** Request current public completion without loading K-Plex, reading private settings or issuing
* graph work. Missing, old, disabled, retired, malformed and throwing providers are silent fallbacks.
* Replacement integrity is checked against the original input, never a normalized display label. */
@@ -50,15 +28,9 @@ export function readKplexOntologyCompletion(
if (input.isConnected === false || cursor === null || cursor !== input.selectionEnd ||
text.length > MAX_TEXT || !Number.isInteger(limit) || limit < 1 || limit > MAX_ITEMS) return null;
try {
const provider = providerFor(input);
if (!provider || provider.version !== 1 || !record(provider.v1)) return null;
const api = provider.v1;
if (api.version !== 1 || !callable(api.capabilities) || !callable(api.completeOntology)) return null;
const capabilities: unknown = api.capabilities.call(api);
if (!record(capabilities) || capabilities.ok !== true || !record(capabilities.value) ||
!Array.isArray(capabilities.value.operations) || capabilities.value.operations.length > 64 ||
!capabilities.value.operations.includes("completeOntology")) return null;
const read = api.completeOntology;
const operation = getKplexPublicRead(input.ownerDocument.defaultView ?? window, "completeOntology");
if (!operation) return null;
const { api, read } = operation;
const result: unknown = read.call(api, {text, cursor, limit});
if (!record(result) || result.ok !== true || !record(result.revision) ||
!Number.isSafeInteger(result.revision.configuration) || Number(result.revision.configuration) < 0 ||
@@ -81,7 +53,7 @@ export function readKplexOntologyCompletion(
if (budget > MAX_OUTPUT) return null;
items.push({name: field.name, partner, description});
}
return {provider, api, read, configuration: Number(result.revision.configuration), text, cursor,
return {...operation, configuration: Number(result.revision.configuration), text, cursor,
range: {start, end: cursor}, items};
} catch {
// Another optional plugin's failure must not interrupt ordinary input or existing suggestions.
+2
View File
@@ -26,6 +26,8 @@ export const DRAWING_COMPRESSED_REG =
const DRAWING_COMPRESSED_REG_FALLBACK =
/(\n##? Drawing\n(?:```compressed-json\n)?)(.*)((```)?(%%)?)/gm;
export const EMBEDDED_VAULT_FILE_REG = /([\w\d]*):\s*!?\[\[([^\]]*)]]\s*(\{[^}]*})?\n/gm;
const isCompressedMD = (data: string): boolean => {
return data.match(/```compressed-json\n/gm) !== null;
};
@@ -0,0 +1,185 @@
const PNGS = "pngs";
const ENTRIES = "entries";
const TOTALS = "totals";
const ACCESS = "used";
const BUDGET = 100 * 1024 * 1024;
const MAX_ENTRIES = 8192;
const PURGE_DELAY_MS = 60_000;
interface Entry {
stamp: string;
bytes: number;
used: number;
}
interface Totals {
bytes: number;
count: number;
}
type CacheHost = Pick<Window, "indexedDB" | "setTimeout" | "clearTimeout"> & { IDBKeyRange: typeof IDBKeyRange };
/** Device-local derived PNGs. All accounting and eviction are in one transaction. */
export class DrawingThumbnailCache {
private opening: Promise<IDBDatabase | null> | null = null;
private database: IDBDatabase | null = null;
private disposed = false;
private purgeTimer: number | null = null;
constructor(private readonly owner: CacheHost, private readonly databaseName: string,
private readonly retentionDays: () => number) {}
private cutoff(): number {
return Date.now() - Math.max(1, this.retentionDays()) * 86_400_000;
}
private open(): Promise<IDBDatabase | null> {
if (this.disposed || !this.owner.indexedDB) return Promise.resolve(null);
if (this.database) return Promise.resolve(this.database);
return this.opening ??= new Promise<IDBDatabase | null>((resolve, reject) => {
const request = this.owner.indexedDB.open(this.databaseName, 1);
let blocked = false;
request.onupgradeneeded = () => {
if (blocked || this.disposed) { request.transaction?.abort(); return; }
const db = request.result;
db.createObjectStore(PNGS);
db.createObjectStore(ENTRIES).createIndex(ACCESS, ACCESS);
db.createObjectStore(TOTALS);
};
request.onerror = () => reject(request.error);
request.onblocked = () => { blocked = true; resolve(null); };
request.onsuccess = () => {
const db = request.result;
if (blocked || this.disposed) { db.close(); resolve(null); return; }
this.database = db;
const close = () => {
db.close();
if (this.database === db) this.database = null;
};
db.onversionchange = close;
db.onclose = close;
this.schedulePurge();
resolve(db);
};
}).catch((): null => null).finally(() => { this.opening = null; });
}
private schedulePurge(): void {
if (this.purgeTimer !== null) return;
this.purgeTimer = this.owner.setTimeout(() => {
this.purgeTimer = null;
void this.purgeExpired();
}, PURGE_DELAY_MS);
}
/** IDB callbacks keep queued requests in the same active transaction on mobile WebViews. */
private async transaction<T>(queue: (tx: IDBTransaction, result: (value: T) => void) => void): Promise<T | null> {
const db = await this.open();
if (!db || this.disposed) return null;
try {
return await new Promise<T | null>((resolve, reject) => {
const tx = db.transaction([PNGS, ENTRIES, TOTALS], "readwrite");
let result: T | null = null;
tx.oncomplete = () => resolve(result);
tx.onabort = () => reject(tx.error);
queue(tx, value => { result = value; });
});
} catch {
// Storage being full or unavailable must not interfere with rendering.
return null;
}
}
/** Reads a matching PNG and updates only its small access record. */
public get(id: string, stamp: string): Promise<Blob | null> {
return this.transaction<Blob>((tx, result) => {
const entries = tx.objectStore(ENTRIES);
const match = entries.get(id) as IDBRequest<Entry | undefined>;
match.onsuccess = () => {
const entry = match.result;
if (entry?.stamp !== stamp || entry.used < this.cutoff()) return;
const request = tx.objectStore(PNGS).get(id) as IDBRequest<Blob | undefined>;
request.onsuccess = () => {
const png = request.result;
if (!png || png.type !== "image/png") return;
// Repeated visits to the same drawing need only update recency once a minute.
if (Date.now() - entry.used >= 60_000) entries.put({ ...entry, used: Date.now() }, id);
result(png);
};
};
});
}
/** Replaces the same drawing/frame/theme entry and evicts the least recently used PNGs. */
public async put(id: string, stamp: string, png: Blob): Promise<void> {
const bytes = png.size + 2 * (id.length + stamp.length);
if (!png.size || png.type !== "image/png" || bytes > 384 * 1024) return;
await this.transaction((tx) => {
const entries = tx.objectStore(ENTRIES);
const pngs = tx.objectStore(PNGS);
const totals = tx.objectStore(TOTALS);
const state = totals.get("size") as IDBRequest<Totals | undefined>;
const old = entries.get(id) as IDBRequest<Entry | undefined>;
old.onsuccess = () => {
const size = state.result ?? { bytes: 0, count: 0 };
size.bytes += bytes - (old.result?.bytes ?? 0);
size.count += old.result ? 0 : 1;
entries.put({ stamp, bytes, used: Date.now() } satisfies Entry, id);
pngs.put(png, id);
if (size.bytes <= BUDGET && size.count <= MAX_ENTRIES) {
totals.put(size, "size");
return;
}
this.removeEntries(tx, size, () => size.bytes <= BUDGET && size.count <= MAX_ENTRIES, undefined, id);
};
});
}
private removeEntries(tx: IDBTransaction, size: Totals, finished: () => boolean, range?: IDBKeyRange, keep?: string): void {
const pngs = tx.objectStore(PNGS);
const scan = tx.objectStore(ENTRIES).index(ACCESS).openCursor(range);
scan.onsuccess = () => {
const cursor = scan.result;
if (!cursor || finished()) {
tx.objectStore(TOTALS).put(size, "size");
return;
}
if (cursor.primaryKey !== keep) {
const entry = cursor.value as Entry;
size.bytes -= entry.bytes;
size.count--;
pngs.delete(cursor.primaryKey);
cursor.delete();
}
cursor.continue();
};
}
private async purgeExpired(): Promise<void> {
await this.transaction(tx => {
const cutoff = this.owner.IDBKeyRange.upperBound(this.cutoff(), true);
const state = tx.objectStore(TOTALS).get("size") as IDBRequest<Totals | undefined>;
state.onsuccess = () => {
if (state.result) this.removeEntries(tx, state.result, () => false, cutoff);
};
});
// The first open schedules housekeeping. A purge after a database
// reconnect should not leave a second timer behind.
if (this.purgeTimer !== null) this.owner.clearTimeout(this.purgeTimer);
this.purgeTimer = null;
}
public async clear(): Promise<void> {
await this.transaction(tx => {
for (const name of [PNGS, ENTRIES, TOTALS]) tx.objectStore(name).clear();
});
}
public destroy(): void {
this.disposed = true;
if (this.purgeTimer !== null) this.owner.clearTimeout(this.purgeTimer);
this.purgeTimer = null;
this.database?.close();
this.database = null;
}
}
@@ -0,0 +1,207 @@
import { Modal, Notice, Setting, normalizePath, requestUrl } from "obsidian";
import type { LibraryItem } from "@zsviczian/excalidraw/types/excalidraw/types";
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { restoreLibraryItems } from "src/constants/constants";
import { URLs } from "src/constants/safeUrls";
import type ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import type { FrameworkRemote } from "src/types/visualResourceTypes";
const DAY = 24 * 60 * 60 * 1000;
/** Read standard v2 libraries with unique stable item IDs and editable geometry. */
export function parseFrameworkLibrary(raw: string): LibraryItem[] {
if (raw.length > 8 * 1024 * 1024) throw Error("Framework library is too large");
const data = JSON.parse(raw) as { type?: string; version?: number; libraryItems?: LibraryItem[] };
const ids = new Set<string>();
if (data?.type !== "excalidrawlib" || data.version !== 2 || !Array.isArray(data.libraryItems) ||
!data.libraryItems.length || data.libraryItems.length > 300 || data.libraryItems.some(item => {
if (!item || typeof item.id !== "string" || !item.id || ids.has(item.id) ||
typeof item.name !== "string" || !item.name.trim() || !Array.isArray(item.elements) ||
!item.elements.length || item.elements.length > 3000 || item.elements.some((element: ExcalidrawElement) =>
!element || typeof element.id !== "string" || typeof element.type !== "string" ||
![element.x, element.y, element.width, element.height].every(Number.isFinite) ||
element.type === "iframe" || element.type === "embeddable" || element.type === "image")) return true;
ids.add(item.id);
return false;
})) throw Error("Invalid framework library");
return [...restoreLibraryItems(data.libraryItems, "published")];
}
function parseCatalog(raw: string): FrameworkRemote[] {
if (raw.length > 64 * 1024) throw Error("Framework catalog is too large");
const data = JSON.parse(raw) as FrameworkRemote[];
const names = new Set<string>();
if (!Array.isArray(data) || data.length > 100 || data.some(entry => {
if (!entry || typeof entry.fname !== "string" || !/^[a-z0-9][a-z0-9_-]{0,100}\.excalidrawlib$/i.test(entry.fname) ||
!Number.isSafeInteger(entry.mtime) || entry.mtime <= 0 || names.has(entry.fname.toLowerCase())) return true;
names.add(entry.fname.toLowerCase());
return false;
})) throw Error("Invalid framework catalog");
return data;
}
/** Local framework provider and explicit, validated catalog installation. */
export class FrameworkCatalog {
private checking: Promise<FrameworkRemote[]> | null = null;
private installing: Promise<void> | null = null;
private confirmation: Modal | null = null;
private disposed = false;
private readonly cache = new Map<string, { mtime: number; items: LibraryItem[] }>();
constructor(private readonly plugin: ExcalidrawPlugin) {}
public destroy(): void {
this.disposed = true;
this.confirmation?.close();
this.cache.clear();
}
/** Use the configured folder, defaulting to Frameworks within the Excalidraw root. */
public get folder(): string {
return normalizePath(this.plugin.settings.frameworkFolder.trim() || this.plugin.settings.folder + "/Frameworks");
}
/** Discover local libraries without contacting the catalog service. */
public async list() {
if (this.disposed) return [];
const vault = this.plugin.app.vault;
const paths = (vault.getFolderByPath(this.folder)?.children ?? [])
.filter(child => child.name.toLowerCase().endsWith(".excalidrawlib") && vault.getFileByPath(child.path))
.map(child => child.path);
for (const path of this.cache.keys()) if (!paths.includes(path)) this.cache.delete(path);
const result: Array<{ path: string; item: LibraryItem }> = [];
for (const path of paths) {
for (const item of await this.items(path)) result.push({ path, item });
}
return result;
}
/** Resolve one local library item, re-reading only when its file changed. */
public async items(path: string): Promise<LibraryItem[]> {
if (this.disposed) return [];
const vault = this.plugin.app.vault;
const file = vault.getFileByPath(path);
if (!file || file.parent?.path !== this.folder || file.extension.toLowerCase() !== "excalidrawlib") return [];
const cached = this.cache.get(path);
if (cached?.mtime === file.stat.mtime) return cached.items;
const mtime = file.stat.mtime;
try {
const items = parseFrameworkLibrary(await vault.cachedRead(file));
if (this.disposed || vault.getFileByPath(path) !== file || file.path !== path ||
file.stat.mtime !== mtime || file.parent?.path !== this.folder) return [];
this.cache.set(path, { mtime, items });
return items;
} catch { return []; }
}
/** Check on picker open under the shared version/script update policy. */
public async updates(): Promise<FrameworkRemote[]> {
if (this.disposed || !this.plugin.settings.showNewVersionNotification) return [];
const catalog = await this.remote(false);
if (this.disposed) return [];
return catalog.filter(entry => {
const path = this.folder + "/" + entry.fname;
const installed = this.plugin.settings.frameworkInstalls[path];
return !!installed && installed.mtime < entry.mtime && !!this.plugin.app.vault.getFileByPath(path);
});
}
private remote(explicit: boolean): Promise<FrameworkRemote[]> {
if (this.disposed) return Promise.resolve<FrameworkRemote[]>([]);
if (this.checking !== null) return this.checking;
const settings = this.plugin.settings;
const now = Date.now();
if ((!explicit || settings.frameworkCatalog.length) && now - settings.frameworkCatalogCheckedAt < DAY) {
return Promise.resolve(settings.frameworkCatalog);
}
settings.frameworkCatalogCheckedAt = now;
const current = () => !this.disposed && this.plugin.settings === settings;
this.checking = (async () => {
try {
const response = await requestUrl({ url: URLs.VISUAL_FRAMEWORKS_CATALOG });
if (!current()) return [];
settings.frameworkCatalog = parseCatalog(response.text);
return settings.frameworkCatalog;
} catch (error) {
if (explicit) throw error;
return settings.frameworkCatalog;
} finally {
if (current()) await this.plugin.saveSettings();
}
})().finally(() => { this.checking = null; });
return this.checking;
}
/** Install or update only after the user invokes this action. */
public async install(): Promise<void> {
this.installing ??= this.download().finally(() => { this.installing = null; });
return this.installing;
}
private async download(): Promise<void> {
const catalog = await this.remote(true);
if (!catalog.length) throw Error("Framework catalog is empty");
const vault = this.plugin.app.vault;
const folder = this.folder;
for (const entry of catalog) {
if (this.disposed || this.folder !== folder) throw Error("Framework catalog target retired");
const path = folder + "/" + entry.fname;
const file = vault.getFileByPath(path);
const validate = () => {
if (this.disposed || this.folder !== folder || vault.getFileByPath(path) !== file)
throw Error("Framework folder changed during installation");
};
const previous = this.plugin.settings.frameworkInstalls[path];
if (file && previous?.mtime === entry.mtime) continue;
const content = (await requestUrl({ url: URLs.VISUAL_FRAMEWORKS_DIRECTORY + "/" + encodeURIComponent(entry.fname) })).text;
validate();
parseFrameworkLibrary(content);
const before = file ? await vault.read(file) : null;
const digest = await this.digest(content);
if (before !== null && previous?.digest !== await this.digest(before)) {
validate();
if (!await this.confirmReplace(entry.fname)) continue;
}
validate();
if (file) await vault.process(file, current => {
validate();
if (current !== before) throw Error("Framework library changed during installation");
return content;
});
else {
if (!vault.getFolderByPath(folder)) await vault.createFolder(folder);
validate();
await vault.create(path, content);
}
if (this.disposed) return;
this.plugin.settings.frameworkInstalls[path] = { mtime: entry.mtime, digest };
this.cache.delete(path);
await this.plugin.saveSettings();
}
}
private async digest(content: string): Promise<string> {
const win = this.plugin.app.workspace.containerEl.ownerDocument.defaultView;
const bytes = new Uint8Array(await win.crypto.subtle.digest("SHA-256", new TextEncoder().encode(content)));
return Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
}
private confirmReplace(name: string): Promise<boolean> {
return new Promise(resolve => {
const modal = new Modal(this.plugin.app);
modal.setTitle(t("VR_REPLACE_FRAMEWORK"));
modal.contentEl.createEl("p", { text: name });
this.confirmation = modal;
modal.onClose = () => { this.confirmation = null; resolve(false); };
new Setting(modal.contentEl).addButton(button => button.setWarning().setButtonText(t("VR_REPLACE_FRAMEWORK")).onClick(() => {
resolve(true);
modal.close();
}));
modal.open();
});
}
/** Report an actionable catalog failure without blocking blank drawing creation. */
public notifyFailure(): void { new Notice(t("VR_DOWNLOAD_FAILED")); }
}
@@ -0,0 +1,301 @@
import { Component, normalizePath, type TFile } from "obsidian";
import type ExcalidrawPlugin from "src/core/main";
import type { VisualResourceLocator } from "src/types/visualResourceTypes";
import { visualResourceKey } from "./visualResourceModel";
interface CollectionResource {
locator: VisualResourceLocator;
favorite?: boolean;
manual?: boolean;
missing?: boolean;
}
interface Playlist {
name: string;
parent?: string;
members: string[];
}
interface CollectionFile {
version: 1;
resources: Record<string, CollectionResource>;
playlists: Record<string, Playlist>;
}
const empty = (): CollectionFile => ({ version: 1, resources: {}, playlists: {} });
function isLocator(value: unknown): value is VisualResourceLocator {
if (!value || typeof value !== "object") return false;
const locator = value as Record<string, unknown>;
return locator.provider === "lucide" && typeof locator.icon === "string" ||
locator.provider === "vault" && typeof locator.path === "string" &&
(locator.frame === undefined || typeof locator.frame === "string") ||
locator.provider === "stencil" && typeof locator.id === "string" &&
(locator.path === undefined || typeof locator.path === "string") ||
locator.provider === "framework" && typeof locator.path === "string" && typeof locator.id === "string";
}
/** Validate the synced file and repair dangling references without guessing identities. */
export function readResourceCollections(raw: string): CollectionFile {
const parsed: unknown = JSON.parse(raw);
if (!parsed || typeof parsed !== "object") throw Error("Invalid resource collections");
const data = parsed as Partial<CollectionFile>;
if (data.version !== 1 || !data.resources || !data.playlists ||
typeof data.resources !== "object" || typeof data.playlists !== "object" ||
Array.isArray(data.resources) || Array.isArray(data.playlists)) throw Error("Unsupported resource collections");
const resources = Object.fromEntries(Object.entries(data.resources).filter(([, resource]) => resource && isLocator(resource.locator)));
const playlists = Object.fromEntries(Object.entries(data.playlists).flatMap(([id, list]) => {
if (!list || typeof list.name !== "string" || !Array.isArray(list.members)) return [];
const parent = typeof list.parent === "string" ? list.parent : undefined;
return [[id, { name: list.name, parent, members: [...new Set(list.members)].filter(key => Object.hasOwn(resources, key)) }]];
}));
for (const [id, list] of Object.entries(playlists)) {
const seen = new Set([id]);
let parent = list.parent;
while (parent) {
if (!Object.hasOwn(playlists, parent) || seen.has(parent)) { delete list.parent; break; }
seen.add(parent);
parent = playlists[parent].parent;
}
}
return { version: 1, resources, playlists };
}
function collectionKey(locator: VisualResourceLocator): string {
return locator.provider === "stencil" ? JSON.stringify([locator.provider, locator.id, locator.path]) : visualResourceKey(locator);
}
function indexResources(data: CollectionFile): Map<string, string> {
const index = new Map<string, string>();
for (const [id, resource] of Object.entries(data.resources)) {
if (resource.missing) continue;
const key = collectionKey(resource.locator);
if (!index.has(key)) index.set(key, id);
}
return index;
}
function removeUncuratedResource(data: CollectionFile, id: string): boolean {
const resource = data.resources[id];
if (!resource || resource.favorite || resource.manual || Object.values(data.playlists).some(list => list.members.includes(id))) return false;
delete data.resources[id];
return true;
}
type CollectionEdit = (data: CollectionFile) => void;
type ScheduledEdit = { edit: CollectionEdit; create: boolean; resolve: () => void; reject: (error: unknown) => void };
/** Owns the vault's normalized curation file. Writes replay against the latest vault revision. */
export class ResourceCollections extends Component {
private data = empty();
private loadedPath = "";
private revision = 0;
private disposed = false;
private queue: Promise<unknown> = Promise.resolve();
private listeners = new Set<() => void>();
private stateIndex = new Map<string, { favorite: boolean; memberships: string[] }>();
private scheduled = new Map<string, ScheduledEdit[]>();
constructor(private readonly plugin: ExcalidrawPlugin) {
super();
}
private get path() { return normalizePath(this.plugin.settings.folder + "/resource-collections.json"); }
/** Observe external sync and update paths for known vault renames and deletions. */
public onload(): void {
const vault = this.plugin.app.vault;
const refresh = () => { void this.refresh().catch(() => this.notify()); };
this.registerEvent(vault.on("modify", file => { if (file.path === this.path) refresh(); }));
this.registerEvent(vault.on("create", file => { if (file.path === this.path) refresh(); }));
this.registerEvent(vault.on("delete", file => {
if (file.path === this.path) refresh();
else this.relocate(file.path);
}));
this.registerEvent(vault.on("rename", (file, oldPath) => {
if (oldPath === this.loadedPath || file.path === this.path) refresh();
this.relocate(oldPath, file.path);
}));
}
public onunload(): void {
this.disposed = true;
this.listeners.clear();
}
private notify(): void { this.listeners.forEach(listener => listener()); }
/** Subscribe to refreshed local and external curation. */
public subscribe(listener: () => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
/** Reload when opening the gallery, including changes made while the plugin was inactive. */
public async refresh(): Promise<void> {
if (this.disposed) return;
const path = this.path;
const revision = ++this.revision;
const file = this.plugin.app.vault.getFileByPath(path);
const data = file ? readResourceCollections(await this.plugin.app.vault.read(file)) : empty();
if (this.disposed || path !== this.path || revision !== this.revision) return;
this.loadedPath = path;
this.data = data;
const playlists = new Map<string, string[]>();
for (const [id, playlist] of this.playlists) for (const member of playlist.members) {
const memberships = playlists.get(member) ?? [];
memberships.push(id);
playlists.set(member, memberships);
}
this.stateIndex.clear();
for (const [key, id] of indexResources(data)) {
this.stateIndex.set(key, { favorite: !!data.resources[id].favorite, memberships: playlists.get(id) ?? [] });
}
this.notify();
}
/** Playlists in display order, with parent IDs and membership counts. */
public get playlists() { return Object.entries(this.data.playlists); }
/** Resolvable curated locators. Confirmed deletions remain recorded for repair. */
public get curated() { return Object.values(this.data.resources).filter(resource => !resource.missing); }
/** Return the favorite and membership state of a resource. */
public state(locator: VisualResourceLocator) {
return this.stateIndex.get(collectionKey(locator)) ?? { favorite: false, memberships: [] };
}
/** Apply one explicit user intent to one or more resources together. */
public curate(locators: VisualResourceLocator[], options: { favorite?: boolean; manual?: boolean; playlist?: string; member?: boolean }): Promise<void> {
return this.edit(data => {
const indexed = indexResources(data);
for (const locator of locators) {
const key = collectionKey(locator);
let id = indexed.get(key);
if (!id) {
if (!options.favorite && !options.manual && !options.member) continue;
id = this.id();
data.resources[id] = { locator: { ...locator } };
indexed.set(key, id);
}
const resource = data.resources[id];
if (options.favorite !== undefined) resource.favorite = options.favorite || undefined;
if (options.manual !== undefined) resource.manual = options.manual || undefined;
const list = options.playlist && data.playlists[options.playlist];
if (list) {
list.members = list.members.filter(member => member !== id);
if (options.member) list.members.push(id);
}
if (removeUncuratedResource(data, id)) indexed.delete(key);
}
});
}
/** Create or rename a playlist under its chosen parent. */
public savePlaylist(name: string, id = this.id(), parent?: string): Promise<void> {
return this.edit(data => {
if (!name.trim() || parent && !Object.hasOwn(data.playlists, parent)) return;
let ancestor = parent;
while (ancestor) {
if (ancestor === id) return;
ancestor = data.playlists[ancestor]?.parent;
}
data.playlists[id] = { name: name.trim(), parent, members: data.playlists[id]?.members ?? [] };
});
}
/** Remove the playlist after its child playlists have been removed. */
public removePlaylist(id: string): Promise<void> {
return this.edit(data => {
if (!Object.hasOwn(data.playlists, id)) return;
if (Object.values(data.playlists).some(playlist => playlist.parent === id)) throw Error("Playlist contains children");
const { members } = data.playlists[id];
delete data.playlists[id];
for (const member of members) removeUncuratedResource(data, member);
});
}
/** Update a stencil's library locator after an ownership-validated move. */
public moveStencils(ids: readonly string[], source: string, destination: string): Promise<void> {
const moving = new Set(ids);
return this.edit(data => {
for (const entry of Object.values(data.resources)) {
const locator = entry.locator;
if (locator.provider !== "stencil" || locator.path !== source || !moving.has(locator.id)) continue;
locator.path = destination;
delete entry.missing;
}
}, false);
}
private id(): string {
return this.plugin.app.workspace.containerEl.ownerDocument.defaultView.crypto.randomUUID().replace(/-/g, "").slice(0, 16);
}
private relocate(from: string, to?: string): void {
void this.edit(data => {
for (const record of Object.values(data.resources)) {
const locator = record.locator;
if (!("path" in locator) || !locator.path || record.missing) continue;
if (locator.path !== from && !locator.path.startsWith(from + "/")) continue;
if (to) locator.path = to + locator.path.slice(from.length);
else record.missing = true;
}
}, false).catch(() => this.notify());
}
private edit(edit: CollectionEdit, create = true): Promise<void> {
if (this.disposed) return Promise.reject(Error("Resource collections retired"));
const path = this.path;
return new Promise((resolve, reject) => {
const active = this.scheduled.get(path);
if (active) { active.push({ edit, create, resolve, reject }); return; }
const edits = [{ edit, create, resolve, reject }];
this.scheduled.set(path, edits);
const run = this.queue.then(() => {
this.scheduled.delete(path);
return this.write(path, edits);
});
this.queue = run.catch(() => {});
void run.then(() => edits.forEach(edit => edit.resolve()), error => edits.forEach(edit => edit.reject(error)));
});
}
private async write(path: string, edits: ScheduledEdit[]): Promise<void> {
const validate = () => {
if (this.disposed || path !== this.path) throw Error("Resource collections target retired");
};
validate();
const vault = this.plugin.app.vault;
const apply = (raw: string | null) => {
validate();
const data = raw === null ? empty() : readResourceCollections(raw);
const before = JSON.stringify(data);
for (const entry of edits) entry.edit(data);
const after = JSON.stringify(data);
return before === after ? raw : after + "\n";
};
let file: TFile | null = vault.getFileByPath(path);
if (!file && edits.some(entry => entry.create)) {
const content = apply(null);
if (content === null) return;
const slash = path.lastIndexOf("/");
const folder = slash < 0 ? "" : path.slice(0, slash);
if (folder && !vault.getFolderByPath(folder)) await vault.createFolder(folder);
validate();
file = vault.getFileByPath(path);
if (!file) {
try { await vault.create(path, content); }
catch (error) {
file = vault.getFileByPath(path);
if (!file) throw error;
}
}
}
if (file) await vault.process(file, raw => {
if (vault.getFileByPath(path) !== file) throw Error("Resource collections file changed");
return apply(raw) ?? raw;
});
await this.refresh();
}
}
@@ -0,0 +1,93 @@
import { Modal, Notice, Setting } from "obsidian";
import type ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import { getKplexPublicRead, isPublicRecord } from "src/utils/kplexPublicApi";
import { setElementHidden } from "src/utils/htmlUtils";
const DEFAULT_PROPERTY = "excalidraw-svg-sources";
const directions = { parent: "VR_REL_PARENT", child: "VR_REL_CHILD", left: "VR_REL_LEFT", right: "VR_REL_RIGHT",
previous: "LUCIDE_PREVIOUS", next: "LUCIDE_NEXT" } as const;
type Direction = keyof typeof directions;
function ontologyFields(owner: Window): { name: string; roles: Direction[] }[] {
try {
const operation = getKplexPublicRead(owner, "ontology");
if (!operation) return [];
const result: unknown = operation.read.call(operation.api, { includeDiscovered: false, limit: 2048 });
if (!isPublicRecord(result) || result.ok !== true || !isPublicRecord(result.value) ||
!Array.isArray(result.value.fields) || result.value.fields.length > 2048) return [];
return result.value.fields.flatMap(field => {
if (!isPublicRecord(field) || field.configured !== true || typeof field.name !== "string" ||
!field.name || field.name.length > 1024 || !Array.isArray(field.roles)) return [];
const offeredRoles: readonly unknown[] = field.roles;
const roles = Object.keys(directions).filter((role): role is Direction => offeredRoles.includes(role));
return roles.length ? [{ name: field.name, roles }] : [];
});
} catch { return []; }
}
/** Choose the source relationship as part of stroke insertion, or edit its default anywhere. */
export class SvgStrokeOptions extends Modal {
constructor(private readonly plugin: ExcalidrawPlugin, private readonly insert?: (property: string | false) => void) {
super(plugin.app);
}
public onOpen(): void {
this.setTitle(t(this.insert ? "VR_INSERT_STROKES" : "VR_SVG_OPTIONS"));
const preferences = this.plugin.settings.visualResources;
let enabled = !!preferences.linkSvgSource;
let property = preferences.svgSourceProperty || DEFAULT_PROPERTY;
const fields = ontologyFields(this.contentEl.ownerDocument.defaultView);
const link = new Setting(this.contentEl).setName(t("VR_SVG_RETAIN_LINK"));
const fieldsRoot = this.contentEl.createDiv();
link.addToggle(toggle => toggle.setValue(enabled).onChange(value => {
enabled = value;
setElementHidden(fieldsRoot, !enabled);
}));
setElementHidden(fieldsRoot, !enabled);
let propertyInput: HTMLInputElement;
new Setting(fieldsRoot).setName(t("VR_SVG_PROPERTY")).addText(input => {
propertyInput = input.setValue(property).onChange(value => { property = value; }).inputEl;
propertyInput.maxLength = 1024;
});
if (fields.length) {
const available = Object.keys(directions).filter((role): role is Direction => fields.some(field => field.roles.includes(role as Direction)));
let direction = fields.find(field => field.name === property)?.roles[0] ?? available[0];
let options: HTMLSelectElement;
const update = () => {
options.empty();
options.createEl("option", { value: "", text: t("VR_KPLEX_CHOOSE") });
for (const field of fields.filter(item => item.roles.includes(direction))) options.createEl("option", { value: field.name, text: field.name });
options.value = [...options.options].some(option => option.value === property) ? property : "";
};
const picker = fieldsRoot.createDiv();
new Setting(picker).setName(t("VR_KPLEX_DIRECTION")).addDropdown(control => {
for (const role of available) control.addOption(role, t(directions[role]));
control.setValue(direction).onChange(value => { direction = value as Direction; update(); });
});
new Setting(picker).setName(t("VR_KPLEX_FIELD")).addDropdown(control => {
options = control.selectEl;
control.onChange(value => {
if (value) propertyInput.value = property = value;
});
});
update();
}
new Setting(this.contentEl).addButton(button => button.setCta()
.setButtonText(t(this.insert ? "VR_INSERT_STROKES" : "VR_SAVE")).onClick(async () => {
const field = property.trim() || DEFAULT_PROPERTY;
preferences.linkSvgSource = enabled;
preferences.svgSourceProperty = field;
button.setDisabled(true);
try {
await this.plugin.saveSettings();
if (!this.contentEl.isConnected) return;
this.close();
this.insert?.(enabled ? field : false);
} catch {
new Notice(t("VR_ACTION_FAILED"));
button.setDisabled(false);
}
}));
}
}
@@ -0,0 +1,411 @@
import { Component, Platform, setIcon, setTooltip, type HoverParent, type HoverPopover } from "obsidian";
import { ICON_NAME } from "src/constants/constants";
import { t } from "src/lang/helpers";
import type { VisualResource } from "src/types/visualResourceTypes";
import { setElementHidden } from "src/utils/htmlUtils";
import { removeStyle, setStyle } from "src/utils/styleUtils";
import type { PreviewDependencyStamps, VisualResources } from "./VisualResources";
import { visualResourceKey } from "./visualResourceModel";
const PAGE_SIZE = 48;
const PREVIEW_CONCURRENCY = 3;
const KIND_ICONS = { icon: "star", image: "image", drawing: ICON_NAME, frame: "frame",
note: "file-text", stencil: "library", framework: "layout-template" } as const;
export const KIND_NAMES = {
icon: "VR_ICON", image: "VR_IMAGE", drawing: "VR_DRAWING", frame: "VR_FRAME",
note: "VR_NOTE", stencil: "VR_STENCIL", framework: "VR_FRAMEWORKS", lucide: "VR_LUCIDE", other: "VR_OTHER",
} as const;
interface GalleryActions {
activate: (resource: VisualResource) => void;
deferredActivation?: (resource: VisualResource) => () => void;
open?: (resource: VisualResource) => void;
canActivate?: (resource: VisualResource) => boolean;
favorite?: (resource: VisualResource) => void;
frames?: (resource: VisualResource) => void;
frameCount?: (resource: VisualResource) => number | null;
frameSelected?: (resource: VisualResource) => boolean;
pageChanged?: () => void;
menu?: (resource: VisualResource, button: HTMLElement, event: MouseEvent) => void;
rename?: (resource: VisualResource, name: string) => void;
drag?: (resource: VisualResource, transfer: DataTransfer) => void;
escape?: () => void;
selected?: (resource: VisualResource) => boolean;
}
interface GalleryOptions {
list?: boolean;
size?: number;
background?: string;
}
type PreviewSlot = { element: HTMLElement; desired?: string; ready?: string; loading?: string };
type GalleryCard = {
element: HTMLElement;
variant: string;
preview: PreviewSlot;
control: HTMLElement;
checkbox?: HTMLInputElement;
update: (resource: VisualResource, selected: boolean | undefined) => void;
};
type PreviewTask = {
card: GalleryCard;
resource: VisualResource;
stamp: string;
dark: boolean;
};
/** Create a compact keyboard- and touch-accessible control with a native button target. */
export function visualResourceButton(parent: HTMLElement, icon: string, label: string, pressed?: boolean): HTMLButtonElement {
const button = parent.createEl("button", { cls: "clickable-icon", attr: { type: "button", "aria-label": label } });
if (pressed !== undefined) button.setAttribute("aria-pressed", String(pressed));
setIcon(button, icon);
return button;
}
/** Viewport-driven previews and shared card semantics for sidepanel and picker. */
export class VisualResourceGallery extends Component implements HoverParent {
public hoverPopover: HoverPopover | null = null;
private hoverTarget: HTMLElement | null = null;
private resources: readonly VisualResource[] = [];
private options: GalleryOptions = {};
private page = 0;
private cards = new Map<string, GalleryCard>();
private active = 0;
private pending: PreviewTask[] = [];
private observed = new Map<Element, PreviewTask>();
private observer: IntersectionObserver | null = null;
private click: { win: Window; id: number } | null = null;
private disposed = false;
private controls: HTMLElement[] = [];
private checkboxes = new Map<HTMLInputElement, VisualResource>();
public readonly root: HTMLElement;
private readonly grid: HTMLElement;
private readonly empty: HTMLElement;
private readonly pager: HTMLElement;
private readonly previous: HTMLButtonElement;
private readonly next: HTMLButtonElement;
constructor(parent: HTMLElement, private readonly service: VisualResources, private readonly actions: GalleryActions) {
super();
this.root = parent.createDiv({ cls: "excalidraw-resource-gallery" });
this.grid = this.root.createDiv({ cls: "excalidraw-resource-grid" });
this.empty = this.grid.createDiv({ cls: "excalidraw-resource-status", text: t("VR_EMPTY") });
this.pager = this.root.createDiv({ cls: "excalidraw-resource-toolbar" });
this.previous = visualResourceButton(this.pager, "chevron-left", t("LUCIDE_PREVIOUS"));
this.next = visualResourceButton(this.pager, "chevron-right", t("LUCIDE_NEXT"));
}
/** Attach shared navigation and cleanup to the gallery's lifecycle. */
public onload(): void {
this.registerDomEvent(this.previous, "click", () => this.changePage(-1));
this.registerDomEvent(this.next, "click", () => this.changePage(1));
this.registerDomEvent(this.root, "keydown", event => {
if (event.key === "Escape") { this.cancelClick(); this.actions.escape?.(); return; }
const index = this.controls.indexOf(event.target as HTMLElement);
if (index < 0) return;
const top = this.controls[0].getBoundingClientRect().top;
const wrap = this.controls.findIndex(button => Math.abs(button.getBoundingClientRect().top - top) > 4);
const columns = this.options.list ? 1 : wrap === -1 ? this.controls.length : wrap;
const offsets = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -columns, ArrowDown: columns };
const offset = offsets[event.key as keyof typeof offsets];
if (offset === undefined) return;
event.preventDefault();
this.controls[Math.max(0, Math.min(this.controls.length - 1, index + offset))]?.focus();
});
this.register(() => {
this.disposed = true;
this.resetPreviews();
this.cards.clear();
this.cancelClick();
this.closeHoverPreview();
this.root.remove();
});
}
/** Focus the first rendered resource from the search field. */
public focusFirst(): void { this.controls[0]?.focus(); }
/** Whether the current page actually contains the selected drawing. */
public shows(resource: VisualResource): boolean { return this.cards.has(visualResourceKey(resource.locator)); }
/** Synchronize visible checkboxes while keeping focus and thumbnails in place. */
public updateSelection(): void {
for (const [checkbox, resource] of this.checkboxes) {
checkbox.checked = this.actions.selected?.(resource) ?? false;
}
}
/** Stop a pending pointer gesture when the target changes, a drag starts, or the gallery moves. */
public cancelClick(): void {
if (this.click) this.click.win.clearTimeout(this.click.id);
this.click = null;
}
/** Close the native preview when its gallery or owner window changes. */
public closeHoverPreview(): void {
this.hoverPopover?.hide();
this.hoverPopover = null;
this.hoverTarget = null;
}
/** Render a bounded page of matching descriptors. */
public show(resources: readonly VisualResource[], options: GalleryOptions = {}, reset = true): void {
if (reset) this.page = 0;
this.resources = resources;
this.options = options;
this.page = Math.min(this.page, Math.max(0, Math.ceil(resources.length / PAGE_SIZE) - 1));
this.render();
}
private resetPreviews(): void {
this.observer?.disconnect();
this.observer = null;
this.pending = [];
this.observed.clear();
}
private render(): void {
this.resetPreviews();
this.controls = [];
this.checkboxes.clear();
this.grid.toggleClass("is-list", !!this.options.list);
setStyle(this.grid, { "--excalidraw-resource-size": (this.options.size ?? 100) + "px" });
const win = this.root.ownerDocument.defaultView;
if (win?.IntersectionObserver) {
const observer = this.observer = new win.IntersectionObserver(entries => {
if (this.observer !== observer) return;
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const task = this.observed.get(entry.target);
observer.unobserve(entry.target);
this.observed.delete(entry.target);
if (task) this.enqueue(task);
}
}, { rootMargin: "64px" });
}
const offset = this.page * PAGE_SIZE;
const visible = this.resources.slice(offset, offset + PAGE_SIZE);
const keys = new Set(visible.map(resource => visualResourceKey(resource.locator)));
for (const [key, card] of this.cards) {
if (keys.has(key)) continue;
card.element.remove();
this.cards.delete(key);
}
const focused = this.root.ownerDocument.activeElement as HTMLElement | null;
const dark = this.root.ownerDocument.body.hasClass("theme-dark");
const dependencies: PreviewDependencyStamps = new Map();
let next = this.empty.nextElementSibling;
for (const resource of visible) {
const key = visualResourceKey(resource.locator);
const selected = this.actions.selected?.(resource);
const variant = JSON.stringify([resource.kind, selected !== undefined, !!resource.inspectFrames, !!this.options.list]);
let card = this.cards.get(key);
if (card?.variant !== variant) {
const old = card;
card = this.card(resource, selected, variant, old?.preview);
if (old) {
if (next === old.element) next = next.nextElementSibling;
old.element.remove();
}
this.cards.set(key, card);
}
if (card.element !== next) this.grid.insertBefore(card.element, next);
next = card.element.nextElementSibling;
card.update(resource, selected);
this.controls.push(card.control);
if (card.checkbox) this.checkboxes.set(card.checkbox, resource);
this.queuePreview(card, resource, dark, dependencies);
}
if (focused?.isConnected && this.root.contains(focused) && this.root.ownerDocument.activeElement !== focused) {
focused.focus({ preventScroll: true });
}
if (this.hoverTarget && !this.hoverTarget.isConnected) this.closeHoverPreview();
setElementHidden(this.empty, !!visible.length);
setElementHidden(this.pager, this.resources.length <= PAGE_SIZE);
this.previous.disabled = offset === 0;
this.next.disabled = offset + PAGE_SIZE >= this.resources.length;
}
private changePage(offset: number): void {
this.cancelClick();
this.page += offset;
this.render();
this.focusFirst();
this.actions.pageChanged?.();
}
private card(resource: VisualResource, selected: boolean | undefined, variant: string, reused?: PreviewSlot): GalleryCard {
const card = this.grid.createDiv({ cls: "excalidraw-resource-card" });
const rename = selected === undefined && resource.locator.provider === "stencil" && this.actions.rename;
const row = rename ? card.createDiv({ cls: "excalidraw-resource-body is-renamable" }) : card;
const button = selected === undefined ? row.createEl("button", {
cls: rename ? "excalidraw-resource-preview-button" : "excalidraw-resource-body",
attr: { type: "button", "aria-label": resource.title },
}) : null;
const body = button ?? card.createEl("label", { cls: "excalidraw-resource-body" });
if (resource.locator.provider === "vault") body.onmouseenter = event => {
if (this.service.hover(resource, event, body, this)) this.hoverTarget = body;
};
const checkbox = button ? undefined : body.createEl("input", {
cls: "excalidraw-resource-checkbox", type: "checkbox", attr: { "aria-label": resource.title },
});
if (checkbox) checkbox.onchange = () => this.actions.activate(resource);
const preview = reused ?? { element: body.createSpan({ cls: "excalidraw-resource-preview", attr: { "aria-hidden": "true" } }) };
const icon = resource.locator.provider === "lucide" ? "sparkles" : KIND_ICONS[resource.kind];
if (reused) body.append(preview.element);
else setIcon(preview.element, resource.drawing ? ICON_NAME : icon);
const text = (rename ? row : body).createSpan({ cls: "excalidraw-resource-label" });
const title = rename ? this.editableTitle(text, () => resource.title, name => rename(resource, name)) : text.createSpan();
const source = this.options.list ? text.createSpan({ cls: "excalidraw-resource-source" }) : undefined;
setIcon(card.createSpan({ cls: "excalidraw-resource-kind", attr: {
role: "img", "aria-label": t(KIND_NAMES[resource.locator.provider === "lucide" ? "lucide" : resource.kind]),
} }), icon);
const actions = card.createDiv({ cls: "excalidraw-resource-actions" });
let frameButton: HTMLButtonElement;
let frameCount: HTMLElement;
if (resource.inspectFrames && this.actions.frames) {
frameButton = visualResourceButton(actions, "frame", t("VR_FRAME"));
frameCount = frameButton.createSpan();
setElementHidden(frameButton, true);
frameButton.onclick = () => { this.cancelClick(); this.actions.frames?.(resource); };
}
const star = this.actions.favorite ? visualResourceButton(actions, "bookmark", "") : undefined;
if (star) star.onclick = () => { this.cancelClick(); this.actions.favorite?.(resource); };
if (this.actions.menu) {
const menu = visualResourceButton(actions, "ellipsis", t("VR_ACTIONS"));
menu.onclick = event => { this.cancelClick(); this.actions.menu?.(resource, menu, event); };
card.oncontextmenu = event => { event.preventDefault(); this.cancelClick(); this.actions.menu?.(resource, menu, event); };
}
if (button) {
const canOpen = !!this.actions.open && resource.locator.provider === "vault";
button.onclick = event => {
if (event.detail > 1) return;
if (this.actions.canActivate && !this.actions.canActivate(resource)) return;
if (!canOpen || !Platform.isDesktopApp || !event.detail) {
this.actions.activate(resource);
return;
}
this.cancelClick();
const activate = this.actions.deferredActivation?.(resource) ?? (() => this.actions.activate(resource));
const win = card.ownerDocument.defaultView;
this.click = { win, id: win.setTimeout(() => { this.click = null; activate(); }, 500) };
};
if (canOpen) button.ondblclick = () => {
this.cancelClick();
this.actions.open?.(resource);
};
if (this.actions.drag) {
button.draggable = true;
button.ondragstart = event => {
this.cancelClick();
if (event.dataTransfer) this.actions.drag?.(resource, event.dataTransfer);
};
button.ondragend = () => this.service.endDrag();
}
}
const control = button ?? checkbox;
return { element: card, variant, preview, control, checkbox, update: (next, checked) => {
resource = next;
title.setText(resource.title);
if (rename) title.setAttribute("aria-label", t("VR_RENAME") + " " + resource.title);
source?.setText(resource.source);
control.setAttribute("aria-label", resource.title);
if (checkbox) checkbox.checked = checked;
if (button) {
if (this.actions.canActivate && !this.actions.canActivate(resource)) button.setAttribute("aria-disabled", "true");
else button.removeAttribute("aria-disabled");
}
if (star) {
const { favorite } = this.service.collections.state(resource.locator);
star.setAttribute("aria-pressed", String(favorite));
star.setAttribute("aria-label", t(favorite ? "VR_UNFAVORITE" : "VR_FAVORITE"));
}
if (frameButton) {
const count = this.actions.frameCount?.(resource) ?? null;
const selected = this.actions.frameSelected?.(resource) ?? false;
card.toggleClass("is-frame-source", selected);
setElementHidden(frameButton, count === null);
frameButton.setAttribute("aria-label", t("VR_BROWSE_FRAMES") + (count ? " (" + count + ")" : ""));
frameButton.setAttribute("aria-pressed", String(selected));
frameCount.setText(count ? String(count) : "");
}
if (this.options.background) setStyle(preview.element, { backgroundColor: this.options.background });
else removeStyle(preview.element, ["backgroundColor"]);
} };
}
private editableTitle(label: HTMLElement, title: () => string, rename: (name: string) => void): HTMLButtonElement {
const name = label.createEl("button", { cls: "excalidraw-resource-rename", attr: { type: "button" } });
setTooltip(name, t("VR_RENAME"));
name.onclick = () => {
const input = label.createEl("input", { cls: "excalidraw-resource-name-input", type: "text",
value: title(), attr: { "aria-label": t("VR_NAME") } });
const finish = (save: boolean, refocus: boolean) => {
input.onblur = null;
if (!input.isConnected) return;
input.replaceWith(name);
if (refocus) name.focus();
const next = input.value.trim();
if (save && next && next !== title()) rename(next);
};
input.onblur = () => finish(true, false);
input.oncontextmenu = event => event.stopPropagation();
input.onkeydown = event => {
if (event.isComposing || event.key !== "Enter" && event.key !== "Escape") return;
event.preventDefault();
event.stopPropagation();
finish(event.key === "Enter", true);
};
name.remove();
input.focus();
input.select();
};
return name;
}
private enqueue(task: PreviewTask): void {
this.pending.push(task);
this.drain();
}
private queuePreview(card: GalleryCard, resource: VisualResource, dark: boolean, dependencies: PreviewDependencyStamps): void {
const stamp = this.service.previewKey(resource, dark, dependencies);
const { preview } = card;
preview.desired = stamp;
if (preview.ready === stamp || preview.loading === stamp) return;
const task = { card, resource, stamp, dark };
if (this.observer) {
this.observed.set(preview.element, task);
this.observer.observe(preview.element);
} else this.enqueue(task);
}
private drain(): void {
while (this.active < PREVIEW_CONCURRENCY && this.pending.length && !this.disposed) {
const task = this.pending.shift();
this.active++;
void this.loadPreview(task).catch(() => {}).finally(() => { this.active--; this.drain(); });
}
}
private async loadPreview(task: PreviewTask): Promise<void> {
const { preview } = task.card;
const current = () => preview.element.isConnected && preview.desired === task.stamp;
if (!current() || preview.ready === task.stamp || preview.loading === task.stamp) return;
preview.loading = task.stamp;
try {
const image = await this.service.preview(task.resource, task.dark, current);
if (!current()) return;
preview.ready = task.stamp;
if (typeof image === "string" && preview.element.querySelector("img")?.getAttribute("src") === image) return;
preview.element.empty();
if (typeof image === "string") preview.element.createEl("img", { attr: { src: image, alt: "", draggable: "false" } });
else if (image) preview.element.append(image);
else setIcon(preview.element, task.resource.drawing ? ICON_NAME :
task.resource.locator.provider === "lucide" ? "sparkles" : KIND_ICONS[task.resource.kind]);
} finally {
if (preview.loading === task.stamp) preview.loading = undefined;
}
}
}
@@ -0,0 +1,214 @@
import { Modal, Notice, Setting, setTooltip } from "obsidian";
import type ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import type { VisualDiscoveryRule } from "src/types/visualResourceTypes";
import { compileVisualExclusions, compileVisualRules } from "./visualResourceModel";
import { indexedVisualFrameNames, readVisualResourceCandidate } from "./visualResourceDiscovery";
import { visualResourceButton } from "./VisualResourceGallery";
const RULE_KINDS = [["icon", "VR_ICON"], ["drawing", "VR_DRAWING"], ["frame", "VR_FRAME_SEARCH_RULES"]] as const;
type RuleKind = typeof RULE_KINDS[number][0];
/** Edit named discovery blocks and test them against the vault's current metadata. */
export class VisualResourceSettings extends Modal {
private draft: ExcalidrawPlugin["settings"]["visualResources"];
private kind: RuleKind = "icon";
private pages: Record<RuleKind, number> = { icon: 0, drawing: 0, frame: 0 };
private readonly originalNames = new Map<VisualDiscoveryRule, string>();
constructor(private readonly plugin: ExcalidrawPlugin, private readonly changed: () => void, scriptName?: string) {
super(plugin.app);
const old = plugin.visualResources.iconSettings(scriptName);
this.draft = {
iconWidth: old.iconWidth, thumbnailSize: old.thumbnailSize,
lightBackground: old.lightBackground, darkBackground: old.darkBackground, excludeFolders: old.exclusion,
...plugin.settings.visualResources, rules: structuredClone(plugin.visualResources.rules(scriptName)),
};
for (const [kind] of RULE_KINDS) for (const rule of this.draft.rules[kind]) this.originalNames.set(rule, kind + ":" + rule.name);
}
/** Render the settings in the owning Obsidian modal. */
public onOpen(): void {
this.setTitle(t("VR_SETTINGS"));
this.modalEl.addClass("excalidraw-resource-settings-modal");
this.contentEl.addClass("excalidraw-resource-settings");
this.render();
}
private render(): void {
this.contentEl.empty();
const copy = this.titleEl.createEl("button", { text: t("VR_COPY_PROMPT"), attr: { type: "button" } });
copy.onclick = () => void this.contentEl.ownerDocument.defaultView.navigator.clipboard.writeText(t("VR_PROMPT"))
.then(() => new Notice(t("VR_PROMPT_COPIED"))).catch(() => new Notice(t("VR_ACTION_FAILED")));
this.contentEl.createEl("p", { cls: "setting-item-description", text: t("VR_COPY_PROMPT_DESC") });
const header = this.contentEl.createDiv({ cls: "excalidraw-resource-settings-heading" });
header.createEl("h3", { text: t("VR_DISCOVERY") });
const scope = header.createEl("select", { attr: { "aria-label": t("VR_DISCOVERY") } });
for (const [kind, name] of RULE_KINDS) scope.createEl("option", { value: kind, text: t(name) });
scope.value = this.kind;
this.contentEl.createEl("p", { cls: "setting-item-description", text: t("VR_RULES_DESC") });
const deck = this.contentEl.createDiv();
const tester = this.contentEl.createEl("details", { cls: "excalidraw-resource-settings-tester" });
tester.createEl("summary", { text: t("VR_TEST") });
const query = tester.createEl("input", { type: "search", placeholder: t("VR_TEST_PATH"), attr: { "aria-label": t("VR_TEST_PATH") } });
const status = tester.createDiv({ cls: "excalidraw-resource-settings-test-results", attr: { "aria-live": "polite" } });
const test = () => { if (tester.open) this.test(status, query.value); };
const draw = () => { this.renderRule(deck, test); test(); };
scope.onchange = () => { this.kind = scope.value as RuleKind; draw(); };
tester.ontoggle = test;
query.oninput = test;
draw();
const appearance = this.contentEl.createDiv({ cls: "excalidraw-resource-settings-appearance" });
new Setting(appearance).setName(t("VR_EXCLUSIONS")).setDesc(t("VR_EXCLUSIONS_DESC")).addTextArea(text => {
text.inputEl.rows = 2;
text.setValue(this.draft.excludeFolders).onChange(value => { this.draft.excludeFolders = value; test(); });
});
this.number(appearance, "VR_ICON_WIDTH", "iconWidth", 20, 2000);
this.number(appearance, "VR_THUMB_SIZE", "thumbnailSize", 64, 240);
this.color(appearance, "VR_LIGHT_BG", "lightBackground");
this.color(appearance, "VR_DARK_BG", "darkBackground");
const footer = this.modalEl.createDiv({ cls: "excalidraw-resource-settings-footer" });
new Setting(footer).addButton(button => button.setCta().setButtonText(t("VR_SAVE")).onClick(async () => {
button.setDisabled(true);
try {
const renamed = new Map<string, string>();
for (const [kind] of RULE_KINDS) {
const seen = new Set<string>();
for (const rule of this.draft.rules[kind]) {
rule.name = rule.name.trim();
if (!rule.name || seen.has(rule.name)) throw Error("Discovery rule names must be unique");
seen.add(rule.name);
new RegExp(rule.pattern);
if (rule.folderPattern) new RegExp(rule.folderPattern);
const original = this.originalNames.get(rule);
if (original) renamed.set(original, kind + ":" + rule.name);
}
}
const originals = new Set(this.originalNames.values());
const remap = (groups: string[]) => groups.flatMap(group => renamed.get(group) ?? (originals.has(group) ? [] : [group]));
const current = this.plugin.settings.visualResources;
const { rules, iconWidth, thumbnailSize, lightBackground, darkBackground, excludeFolders } = this.draft;
this.plugin.settings.visualResources = {
...current, rules, iconWidth, thumbnailSize, lightBackground, darkBackground, excludeFolders,
groups: current.groups && remap(current.groups),
iconGroups: current.iconGroups && Object.fromEntries(Object.entries(current.iconGroups).map(([script, groups]) => [script, remap(groups)])),
};
await this.plugin.saveSettings();
this.changed();
this.close();
} catch { new Notice(t("VR_RULE_ERROR")); button.setDisabled(false); }
}));
}
private number(parent: HTMLElement, label: "VR_ICON_WIDTH" | "VR_THUMB_SIZE", key: "iconWidth" | "thumbnailSize", min: number, max: number): void {
new Setting(parent).setName(t(label)).addText(control => {
control.inputEl.type = "number";
control.inputEl.min = String(min);
control.inputEl.max = String(max);
control.setValue(String(this.draft[key])).onChange(value => {
const number = Number(value);
if (Number.isFinite(number) && number >= min && number <= max) this.draft[key] = number;
});
control.inputEl.onblur = () => { control.setValue(String(this.draft[key])); };
});
}
private color(parent: HTMLElement, label: "VR_LIGHT_BG" | "VR_DARK_BG", key: "lightBackground" | "darkBackground"): void {
const row = new Setting(parent).setName(t(label));
const picker = row.controlEl.createEl("input", { type: "color", attr: { "aria-label": t(label) } });
const base = (value: string) => /^#[a-f0-9]{6}(?:[a-f0-9]{2})?$/i.test(value) ? value.slice(0, 7) : "#ffffff";
picker.value = base(this.draft[key]);
row.addText(control => {
control.setValue(this.draft[key]).setPlaceholder(t("VR_TRANSPARENT")).onChange(value => {
this.draft[key] = value;
picker.value = base(value);
});
picker.oninput = () => {
const old = this.draft[key];
const alpha = /^#[a-f0-9]{8}$/i.test(old) ? old.slice(7) : "";
control.setValue(this.draft[key] = picker.value + alpha);
};
});
}
private renderRule(deck: HTMLElement, test: () => void): void {
deck.empty();
const definitions = this.draft.rules[this.kind];
const index = this.pages[this.kind] = Math.min(this.pages[this.kind], Math.max(0, definitions.length - 1));
const redraw = () => { this.renderRule(deck, test); test(); };
const rule = definitions[index];
if (rule) {
const pager = deck.createDiv({ cls: "excalidraw-resource-settings-pager" });
const prev = visualResourceButton(pager, "arrow-left", t("LUCIDE_PREVIOUS"));
pager.createEl("strong", { text: t("VR_RULE_POSITION").replace("{CURRENT}", String(index + 1)).replace("{TOTAL}", String(definitions.length)) });
const next = visualResourceButton(pager, "arrow-right", t("LUCIDE_NEXT"));
prev.disabled = index === 0;
next.disabled = index === definitions.length - 1;
prev.onclick = () => { this.pages[this.kind]--; redraw(); };
next.onclick = () => { this.pages[this.kind]++; redraw(); };
const card = deck.createDiv({ cls: "excalidraw-resource-settings-card" });
const header = card.createDiv({ cls: "excalidraw-resource-settings-card-header" });
const name = header.createEl("input", { type: "text", value: rule.name, placeholder: t("VR_NAME"), attr: { "aria-label": t("VR_NAME") } });
name.oninput = () => { rule.name = name.value; test(); };
const remove = visualResourceButton(header, "trash-2", t("VR_DELETE"));
setTooltip(remove, t("VR_DELETE"));
remove.onclick = () => { definitions.splice(index, 1); redraw(); };
type FieldKey = "pattern" | "folderPattern" | "extensions" | "maxKb" | "property" | "value";
const field = (container: HTMLElement, key: FieldKey, label: Parameters<typeof t>[0], placeholder = "", type = "text") => {
const wrapper = container.createEl("label");
wrapper.createSpan({ text: t(label) });
const input = wrapper.createEl("input", { type, value: rule[key] ?? "", placeholder });
input.oninput = () => { rule[key] = input.value; test(); };
};
const grid = card.createDiv({ cls: "excalidraw-resource-settings-grid" });
field(grid, "folderPattern", "VR_FOLDER_PATTERN");
field(grid, "pattern", "VR_PATTERN", "(.+)");
field(grid, "extensions", "VR_EXTENSIONS", "png, jpg, svg, md");
field(grid, "maxKb", "VR_MAX_KB", t("VR_NO_LIMIT"), "number");
const extra = card.createEl("details", { cls: "excalidraw-resource-settings-advanced" });
extra.open = !!rule.property || !!rule.value || !!rule.frameType;
extra.createEl("summary", { text: t("VR_RULE_ADVANCED") });
const fields = extra.createDiv({ cls: "excalidraw-resource-settings-grid" });
field(fields, "property", "VR_PROPERTY");
field(fields, "value", "VR_PROPERTY_VALUE");
if (this.kind === "frame") new Setting(extra).setName(t("VR_FRAME_TYPE")).addDropdown(control => control
.addOption("", t("VR_ALL")).addOption("frame", t("VR_FRAME")).addOption("magicframe", t("VR_MARKER_FRAME"))
.setValue(rule.frameType ?? "").onChange(value => {
rule.frameType = value === "frame" || value === "magicframe" ? value : undefined;
test();
}));
}
const add = deck.createEl("button", { cls: "excalidraw-resource-settings-add", text: t("VR_ADD_RULE"), attr: { type: "button" } });
add.onclick = () => {
const stem = t("VR_RULE");
let name = stem;
for (let i = 2; definitions.some(item => item.name === name); i++) name = stem + " " + i;
this.pages[this.kind] = definitions.push({ name, pattern: "(.+)" }) - 1;
redraw();
const input = deck.querySelector<HTMLInputElement>(".excalidraw-resource-settings-card-header input");
input?.focus();
input?.select();
};
}
private test(status: HTMLElement, query: string): void {
const match = compileVisualRules(this.kind, this.draft.rules[this.kind]);
const excluded = compileVisualExclusions(this.draft.excludeFolders);
const search = query.trim().toLowerCase();
const results: string[] = [];
for (const file of this.app.vault.getFiles()) {
if (file.extension === "excalidrawlib" || excluded(file.path) || !file.path.toLowerCase().includes(search)) continue;
const candidate = readVisualResourceCandidate(this.plugin, file);
if (!candidate.image && !candidate.drawing && candidate.extension !== "md") continue;
const names = this.kind === "frame" ? indexedVisualFrameNames(candidate) : [""];
for (const name of names) {
const rules = match(name ? { ...candidate, frame: { name } } : candidate);
if (rules.length) results.push(file.path + " · " + rules.map(rule => rule.keyword).join(", "));
}
if (results.length >= 25) break;
}
status.empty();
if (!results.length) status.setText(t("VR_EMPTY"));
else for (const result of results.slice(0, 25)) status.createDiv({ text: result });
}
}
@@ -0,0 +1,42 @@
import { MarkdownView, type TFile, type View } from "obsidian";
import { VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import type ExcalidrawView from "src/view/ExcalidrawView";
/** The small native Canvas surface used by Obsidian's file-node insertion. */
type CanvasControls = {
readonly?: boolean;
posFromEvt(event: MouseEvent): { x: number; y: number };
createFileNode(options: { pos: { x: number; y: number }; file: TFile; subpath?: string; save: boolean; focus: boolean }): unknown;
};
export function drawingTarget(view: View | null): ExcalidrawView | null {
return view?.getViewType() === VIEW_TYPE_EXCALIDRAW ? view as ExcalidrawView : null;
}
export function isDocumentTarget(view: View | null): boolean {
return view?.getViewType() === "markdown" || view?.getViewType() === "canvas";
}
export function canvasTarget(view: View | null): CanvasControls | null {
if (view?.getViewType() !== "canvas") return null;
const canvas = view.canvas as (CanvasControls & NonNullable<View["canvas"]>) | undefined;
return typeof canvas?.createFileNode === "function" && typeof canvas.posFromEvt === "function" ? canvas : null;
}
export function writableDocument(view: View | null): boolean {
return !!view?.file && view.leaf.view === view &&
(view instanceof MarkdownView ? view.getMode() === "source" : canvasTarget(view)?.readonly === false);
}
export function addCanvasResource(view: View, file: TFile, subpath?: string): void {
const canvas = canvasTarget(view);
if (!canvas || canvas.readonly !== false || !view.containerEl.isConnected) throw Error("Canvas target is unavailable");
const viewport = view.containerEl.getBoundingClientRect();
const win = view.containerEl.ownerDocument.defaultView;
const pos = canvas.posFromEvt(new win.MouseEvent("mousemove", {
clientX: viewport.left + viewport.width / 2,
clientY: viewport.top + viewport.height / 2,
}));
if (!Number.isFinite(pos.x) || !Number.isFinite(pos.y)) throw Error("Canvas position is unavailable");
canvas.createFileNode({ pos, file, subpath, save: true, focus: false });
}
@@ -0,0 +1,644 @@
import { FileSystemAdapter, getIcon, MarkdownView, Notice, Platform, type HoverParent, type TFile, type View } from "obsidian";
import type { LibraryItem } from "@zsviczian/excalidraw/types/excalidraw/types";
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { IMAGE_TYPES, nanoid } from "src/constants/constants";
import type ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import { FRAME_ANCHORS_PROPERTY, FRAME_THUMBNAIL_PROPERTY, getSceneFrames } from "src/utils/frameMetadata";
import { getTemplate } from "src/utils/excalidrawAutomateUtils";
import { readDrawingPreviewElements, readDrawingPreviewScene } from "src/utils/drawingPreviewScene";
import { repositionElementsToCursor } from "src/utils/excalidrawElementUtils";
import { getExcalidrawEmbeddedFilesFiletree, getIMGFilename } from "src/utils/fileUtils";
import { blobToDataURL } from "src/utils/coreUtils";
import type { VisualDiscoveryRule, VisualResource, VisualResourceLocator } from "src/types/visualResourceTypes";
import type ExcalidrawView from "src/view/ExcalidrawView";
import { EmbeddedFilesLoader } from "../EmbeddedFileLoader";
import { getLucideIcons, prepareLucideIcon } from "../lucideIcons";
import { FrameworkCatalog } from "./FrameworkCatalog";
import { ResourceCollections } from "./ResourceCollections";
import { addCanvasResource, drawingTarget, writableDocument } from "./VisualResourceTargets";
import { compileVisualExclusions, compileVisualRules, DRAWING_PREVIEW_SCENE_LENGTH, DRAWING_PREVIEW_SOURCE_BYTES,
frameworkResource,
MAX_THUMBNAIL_ELEMENTS, readIconLibrarySettings, visualResourceKey } from "./visualResourceModel";
import { indexedVisualFrameNames, readVisualResourceCandidate } from "./visualResourceDiscovery";
import { rasterizeDrawingResource } from "./drawingResourceThumbnail";
import { DrawingThumbnailCache } from "./DrawingThumbnailCache";
const DRAG_TYPE = "application/x-obsidian-excalidraw-visual-resource";
const HOVER_SOURCE = "excalidraw-visual-resources";
const THUMBNAIL_VERSION = "png-v2";
const PREVIEW_CACHE_BYTES = 2 * 1024 * 1024;
const DRAWING_PREVIEW_BYTES = 256 * 1024;
const COLD_DRAWING_BYTES = 64 * 1024;
type ScenePoint = { x: number; y: number };
export type PreviewDependencyStamps = Map<TFile, [path: string, modified: number, size: number][]>;
type MindMapBuilder = {
ready(): boolean;
getView(): { ok: boolean; data?: { view: ExcalidrawView } };
getSelection(): { ok: boolean; data?: { nodeId?: string } };
addNode(options: { text: string; parentId: string }): Promise<{ ok: boolean }>;
};
/** Coordinates existing vault, library, and Lucide providers for both gallery surfaces. */
export class VisualResources {
public readonly collections: ResourceCollections;
public readonly frameworks: FrameworkCatalog;
private drag: { token: string; resource: VisualResource; file: TFile | null } | null = null;
private disposed = false;
private readonly previews = new Map<string, string>();
private readonly libraryPreviewKeys = new WeakMap<LibraryItem["elements"], string>();
private readonly framePreviews = new Map<string, { stamp: string; frames: Promise<VisualResource[]> }>();
private previewBytes = 0;
private previewEpoch = 0;
private readonly thumbnailCache: DrawingThumbnailCache;
private drawingPreviewQueue: Promise<unknown> = Promise.resolve();
private previewScene: { file: TFile; path: string; mtime: number; scene: Awaited<ReturnType<typeof readDrawingPreviewScene>> } | null = null;
private readonly lucideAttachments = new Map<string, TFile>();
constructor(private readonly plugin: ExcalidrawPlugin) {
this.collections = plugin.addChild(new ResourceCollections(plugin));
this.frameworks = new FrameworkCatalog(plugin);
const owner = plugin.app.workspace.containerEl.ownerDocument.defaultView;
this.thumbnailCache = new DrawingThumbnailCache(owner, "Excalidraw Visual Resources " + plugin.app.appId,
() => plugin.settings.imageCacheRetentionDays ?? 30);
if (Platform.isDesktopApp) plugin.registerHoverLinkSource(HOVER_SOURCE, { display: t("VR_TITLE"), defaultMod: true });
plugin.register(() => {
this.disposed = true;
this.frameworks.destroy();
this.thumbnailCache.destroy();
this.endDrag();
this.previews.clear();
this.framePreviews.clear();
this.previewScene = null;
this.lucideAttachments.clear();
});
}
/** Read compatible script settings as defaults without altering the installed script. */
public iconSettings(scriptName = "Icon Library") {
const settings = this.plugin.settings.scriptEngineSettings;
const stock = Object.keys(settings).find(name => name.startsWith("Downloaded/") && name.endsWith("/Icon Library"));
return readIconLibrarySettings(settings[scriptName] ?? (stock ? settings[stock] : undefined));
}
/** The browser's new rules override imported defaults once explicitly configured. */
public rules(scriptName?: string): Record<"icon" | "drawing" | "frame", VisualDiscoveryRule[]> {
return this.plugin.settings.visualResources.rules ?? {
icon: this.iconSettings(scriptName).rules,
drawing: [],
frame: [{ name: t("VR_FRAME"), pattern: "(.+)" }],
};
}
/** Enumerate indexed descriptors. Drawings are read when inspecting children or rendering previews. */
public async list(scriptName?: string, progress?: (resources: VisualResource[]) => void): Promise<VisualResource[]> {
const rules = this.rules(scriptName);
const icon = compileVisualRules("icon", rules.icon);
const drawing = compileVisualRules("drawing", rules.drawing);
const frame = compileVisualRules("frame", rules.frame);
const excluded = compileVisualExclusions(this.plugin.settings.visualResources.excludeFolders ?? this.iconSettings(scriptName).exclusion);
const curated = new Set(this.collections.curated.map(record => visualResourceKey(record.locator)));
const result: VisualResource[] = [];
for (const file of this.plugin.app.vault.getFiles()) {
if (file.extension === "excalidrawlib") continue;
const locator = { provider: "vault", path: file.path } as const;
const explicit = curated.has(visualResourceKey(locator));
if (!explicit && excluded(file.path)) continue;
const candidate = readVisualResourceCandidate(this.plugin, file);
const icons = icon(candidate);
const drawings = drawing(candidate);
const children = indexedVisualFrameNames(candidate).map(name => {
const matches = frame({ ...candidate, frame: { name } });
return this.frameResource(file, name, name, matches.map(match => match.group), matches.map(match => match.keyword));
});
if (!candidate.image && !candidate.drawing && !(candidate.extension === "md" && (explicit || icons.length))) continue;
const matches = [...icons, ...drawings];
const kind = candidate.drawing && (drawings.length || children.length || !icons.length) ? "drawing"
: candidate.extension === "md" && !candidate.drawing ? "note"
: icons.length ? "icon" : "image";
const keywords = matches.map(match => match.keyword);
result.push({ locator, kind, title: keywords[0] || file.basename, source: file.path, keywords,
groups: [...new Set([...matches.map(match => match.group), ...children.flatMap(child => child.groups ?? [])])],
other: !matches.length && !children.length && !explicit && (!candidate.drawing || rules.drawing.length > 0),
frames: children, drawing: candidate.drawing,
inspectFrames: children.length > 0 || candidate.drawing && candidate.extension === "excalidraw",
});
}
for (const icon of getLucideIcons()) {
result.push({ locator: { provider: "lucide", icon: icon.icon }, kind: "icon", title: icon.name, source: "Lucide", keywords: [icon.icon] });
}
if (progress) progress([...result].sort((a, b) => a.title.localeCompare(b.title)));
const [stencils, frameworks] = await Promise.all([this.plugin.stencilLibraryManager.getResourceLibraries(), this.frameworks.list()]);
for (const { item, path } of stencils.items) {
result.push({ locator: { provider: "stencil", id: item.id, path }, kind: "stencil",
title: item.name || item.id, source: path ?? t("VR_DEFAULT_LIBRARY"), keywords: [], previewElements: item.elements });
}
for (const { item, path } of frameworks) result.push(frameworkResource(path, item));
return result.sort((a, b) => a.title.localeCompare(b.title));
}
/** Load the chosen drawing once to give duplicate names unambiguous native references. */
public async frames(resource: VisualResource, scriptName?: string): Promise<VisualResource[]> {
if (resource.locator.provider !== "vault") return [];
const file = this.sourceFile(resource);
if (!file || !this.plugin.isExcalidrawFile(file)) return [];
if (file.stat.size > COLD_DRAWING_BYTES && resource.frames?.length) return resource.frames;
if (file.stat.size > DRAWING_PREVIEW_SOURCE_BYTES) return [];
return this.inspectFrames(file, scriptName);
}
private async inspectFrames(file: TFile, scriptName?: string): Promise<VisualResource[]> {
const frameRules = this.rules(scriptName).frame;
const stamp = JSON.stringify([file.stat.mtime, frameRules]);
const cached = this.framePreviews.get(file.path);
if (cached?.stamp === stamp) return cached.frames;
const pending = this.readFrameResources(file, frameRules);
this.framePreviews.set(file.path, { stamp, frames: pending });
if (this.framePreviews.size > 64) this.framePreviews.delete([...this.framePreviews.keys()][0]);
try { return await pending; }
catch (error: unknown) {
if (this.framePreviews.get(file.path)?.frames === pending) this.framePreviews.delete(file.path);
throw error;
}
}
private async readFrameResources(file: TFile, frameRules: VisualDiscoveryRule[]): Promise<VisualResource[]> {
const candidate = readVisualResourceCandidate(this.plugin, file);
const matches = compileVisualRules("frame", frameRules);
const frames = getSceneFrames(await readDrawingPreviewElements(this.plugin.app.vault, file, DRAWING_PREVIEW_SCENE_LENGTH));
const nameCounts = new Map<string, number>();
for (const frame of frames) nameCounts.set(frame.name, (nameCounts.get(frame.name) ?? 0) + 1);
return frames.flatMap(frame => {
if (!frame.name?.trim()) return [];
const rules = matches({ ...candidate, frame: { name: frame.name, type: frame.frameRole === "marker" ? "magicframe" : "frame" } });
const resource = this.frameResource(file, frame.id, frame.name, rules.map(rule => rule.group), rules.map(rule => rule.keyword));
if (nameCounts.get(frame.name) > 1) resource.title += " (" + frame.id.slice(0, 8) + ")";
return [resource];
});
}
private frameResource(file: TFile, id: string, name: string, groups: string[], keywords: string[] = []): VisualResource {
return { locator: { provider: "vault", path: file.path, frame: id }, kind: "frame",
title: name, source: file.path, keywords: [...new Set([name, ...keywords])], groups: [...new Set(groups)] };
}
/** Resolve curated frames by stored frame ID, including those no longer matching discovery rules. */
public async curatedFrames(scriptName?: string): Promise<VisualResource[]> {
const grouped = new Map<string, Set<string>>();
for (const { locator } of this.collections.curated) {
if (locator.provider !== "vault" || !locator.frame) continue;
const frames = grouped.get(locator.path) ?? new Set<string>();
frames.add(locator.frame);
grouped.set(locator.path, frames);
}
const results: VisualResource[] = [];
for (const [path, ids] of grouped) {
const file = this.plugin.app.vault.getFileByPath(path);
if (!file || !this.plugin.isExcalidrawFile(file)) continue;
// Large drawings can supply named references from metadata. Preserve
// those saved curation keys even if the drawing later becomes smaller.
for (const name of indexedVisualFrameNames(readVisualResourceCandidate(this.plugin, file))) {
if (ids.delete(name)) results.push(this.frameResource(file, name, name, []));
}
if (!ids.size || file.stat.size > DRAWING_PREVIEW_SOURCE_BYTES) continue;
try {
for (const frame of await this.inspectFrames(file, scriptName)) {
if (frame.locator.provider === "vault" && ids.has(frame.locator.frame)) results.push(frame);
}
} catch { /* A temporarily unreadable source retains its curation. */ }
}
return results;
}
/** Resolve a library item by its current provider and owner. */
public async libraryItem(locator: VisualResourceLocator): Promise<LibraryItem | undefined> {
if (locator.provider === "framework") return (await this.frameworks.items(locator.path)).find(item => item.id === locator.id);
if (locator.provider !== "stencil") return;
const library = await this.plugin.stencilLibraryManager.getResourceLibraries();
return library.items.find(({ item, path }) => item.id === locator.id && locator.path === path)?.item;
}
/** Resolve the vault file behind a resource (including a backing library when present). */
public sourceFile(resource: VisualResource): TFile | null {
const locator = resource.locator;
return "path" in locator && locator.path ? this.plugin.app.vault.getFileByPath(locator.path) : null;
}
/** Open the source in a new tab, using the existing frame-link navigation route. */
public async openSource(resource: VisualResource): Promise<void> {
if (resource.locator.provider !== "vault") return;
const file = this.sourceFile(resource);
if (file) await this.plugin.app.workspace.openLinkText(this.link(resource, file), "", "tab");
}
private link(resource: VisualResource, file: TFile): string {
return file.path + (resource.locator.provider === "vault" && resource.locator.frame ? "#^frame=" + resource.locator.frame : "");
}
/** Route eligible gallery cards through Obsidian's Page Preview and its modifier settings. */
public hover(resource: VisualResource, event: MouseEvent, targetEl: HTMLElement, hoverParent: HoverParent): boolean {
if (!Platform.isDesktopApp || resource.locator.provider !== "vault") return false;
const file = this.sourceFile(resource);
if (!file || !this.plugin.isExcalidrawFile(file) && !IMAGE_TYPES.includes(file.extension.toLowerCase())) return false;
this.plugin.app.workspace.trigger("hover-link", {
event, targetEl, hoverParent, source: HOVER_SOURCE, sourcePath: "", linktext: this.link(resource, file),
});
return true;
}
private markdownLink(source: TFile, target: TFile, subpath?: string): string {
const link = this.plugin.app.fileManager.generateMarkdownLink(source, target.path, subpath);
const embed = IMAGE_TYPES.includes(source.extension.toLowerCase()) || this.plugin.isExcalidrawFile(source);
return embed ? "!" + link : link;
}
/** A drawing can receive inserts only while the current editor and file are live. */
public writable(view: ExcalidrawView | null): view is ExcalidrawView {
return !!view?.file && view.isLoaded && view.leaf.view === view && !!view.excalidrawAPI && !view.excalidrawAPI.isDestroyed &&
!view.isClosingOrMigrating() && !view.isSameFileEditingActive() &&
!view.excalidrawAPI.getAppState().viewModeEnabled &&
this.plugin.app.vault.getFileByPath(view.file.path) === view.file;
}
private async waitForDrawing(view: ExcalidrawView, validate: () => void): Promise<void> {
for (let attempts = 0; view.isPersistenceBusy(); attempts++) {
validate();
if (attempts >= 120) throw Error("Drawing did not finish saving");
await new Promise<void>(resolve => window.setTimeout(resolve, 25));
}
validate();
}
public canInsertInto(resource: VisualResource, view: View | null): boolean {
if (this.writable(drawingTarget(view))) return true;
if (!writableDocument(view)) return false;
if (resource.locator.provider === "lucide") return true;
const source = this.sourceFile(resource);
return resource.locator.provider === "vault" && !!source && source !== view.file;
}
/** Place a vault link in a Markdown editor or native Canvas, or insert on an Excalidraw scene. */
public async insertInto(resource: VisualResource, view: View | null, active: () => boolean, scriptName?: string): Promise<void> {
const drawing = drawingTarget(view);
if (drawing) return this.insert(resource, drawing, active, undefined, scriptName);
if (!this.canInsertInto(resource, view) || !active()) return;
const vault = this.plugin.app.vault;
const target = view.file;
const path = target.path;
const valid = () => !this.disposed && active() && view.file === target && target.path === path &&
vault.getFileByPath(path) === target && writableDocument(view);
const subpath = resource.locator.provider === "vault" && resource.locator.frame ? "#^frame=" + resource.locator.frame : undefined;
try {
const source = resource.locator.provider === "lucide" ? await this.lucideAttachment(resource.locator.icon, path, valid) : this.sourceFile(resource);
if (!source || !valid()) return;
if (view instanceof MarkdownView) {
view.editor.replaceSelection(this.markdownLink(source, target, subpath));
} else {
addCanvasResource(view, source, subpath);
}
} catch { if (active()) new Notice(t("VR_INSERT_FAILED")); }
}
private async lucideAttachment(icon: string, targetPath: string, active: () => boolean): Promise<TFile | null> {
if (!/^[a-z0-9-]+$/.test(icon)) return null;
const svg = getIcon(icon);
if (!svg) return null;
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
const { vault, fileManager } = this.plugin.app;
const cached = this.lucideAttachments.get(icon);
if (cached && vault.getFileByPath(cached.path) === cached && await vault.cachedRead(cached) === svg.outerHTML) return cached;
const path = await fileManager.getAvailablePathForAttachment(icon + ".svg", targetPath);
if (!active()) return null;
const file = await vault.create(path, svg.outerHTML);
this.lucideAttachments.set(icon, file);
return file;
}
/** Insert through the corresponding native engine, revalidating after each asynchronous preparation. */
public insert(resource: VisualResource, view: ExcalidrawView | null, active: () => boolean, point?: ScenePoint, scriptName?: string): Promise<void> {
return this.insertMany([resource], view, active, point, scriptName);
}
/** Prepare the selection together and publish one undoable scene update. */
public async insertMany(resources: readonly VisualResource[], view: ExcalidrawView | null, active: () => boolean, point?: ScenePoint, scriptName?: string): Promise<void> {
if (!resources.length || !this.writable(view) || this.disposed || !active()) return;
const file = view.file, path = file.path, api = view.excalidrawAPI, owner = view.ownerDocument;
const validate = () => {
if (this.disposed || !active() || !this.writable(view) || view.file !== file || file.path !== path ||
view.excalidrawAPI !== api || view.ownerDocument !== owner) throw Error("Visual resource target retired");
};
const state = api.getAppState();
const center = point ?? { x: -state.scrollX + state.width / (2 * state.zoom.value), y: -state.scrollY + state.height / (2 * state.zoom.value) };
const size = this.plugin.settings.visualResources.iconWidth ?? this.iconSettings(scriptName).iconWidth;
const ea = this.plugin.ea.getAPI(view);
const sources: Array<{ resource: VisualResource; file: TFile }> = [];
let approximated = false;
const prepare = async (resource: VisualResource): Promise<ExcalidrawElement[]> => {
validate();
if (resource.locator.provider === "lucide") {
const lucideSize = this.plugin.lucidePicker.insertionSize;
const prepared = prepareLucideIcon({ icon: resource.locator.icon, size: lucideSize, x: center.x - lucideSize / 2, y: center.y - lucideSize / 2,
strokeColor: state.currentItemStrokeColor, roughness: state.currentItemRoughness, opacity: state.currentItemOpacity });
for (const element of prepared.elements) {
element.x += (lucideSize - prepared.result.viewport.width) / 2;
element.y += (lucideSize - prepared.result.viewport.height) / 2;
}
approximated ||= !!prepared.result.warnings.length;
return prepared.elements;
}
if (resource.locator.provider !== "vault") {
const item = await this.libraryItem(resource.locator);
if (!item) return [];
validate();
// Native library files can carry display text with empty Obsidian raw text.
const copies = ea.cloneElements([...item.elements]).map(element =>
element.type === "text" && !element.rawText
? { ...element, rawText: element.originalText || element.text }
: element,
);
return repositionElementsToCursor(copies, center, true);
}
const source = this.sourceFile(resource);
if (!source || source === file && this.plugin.isExcalidrawFile(source)) return [];
const frameId = resource.locator.frame;
const anchors: unknown = frameId && this.plugin.app.metadataCache.getFileCache(source)?.frontmatter?.[FRAME_ANCHORS_PROPERTY];
if (frameId && !(Array.isArray(anchors) && anchors.includes(frameId))) {
const data = await getTemplate(this.plugin, source.path, false, null, 0);
if (!getSceneFrames(data.elements).some(frame => frame.id === frameId)) return [];
validate();
}
const link = this.link(resource, source);
const isNote = source.extension === "md" && !this.plugin.isExcalidrawFile(source);
type MindMapWindow = Window & { MindMapBuilderAPI?: MindMapBuilder };
const mainWindow = this.plugin.app.workspace.containerEl.ownerDocument.defaultView;
const mindMap = resources.length === 1 && !point && scriptName && !isNote && (
(owner.defaultView as MindMapWindow).MindMapBuilderAPI ?? (mainWindow as MindMapWindow).MindMapBuilderAPI);
if (mindMap && typeof mindMap.ready === "function" && mindMap.ready() && mindMap.getView?.().data?.view === view) {
const selection = mindMap.getSelection();
if (selection.ok && selection.data?.nodeId && (await mindMap.addNode({ text: "![["
+ link + "|" + size + "]]", parentId: selection.data.nodeId })).ok) return [];
validate();
}
if (!isNote && !this.plugin.isExcalidrawFile(source) && !IMAGE_TYPES.includes(source.extension.toLowerCase())) return [];
const id = isNote ? ea.addText(center.x, center.y, "[[" + link + "]]") :
await ea.addImage(0, 0, resource.locator.frame ? link : source, true);
const element = ea.getElement(id);
if (!element) return [];
if ((resource.kind === "icon" || !!scriptName) && !isNote) {
element.height = size * (element.width ? element.height / element.width : 1);
element.width = size;
}
element.x = center.x - element.width / 2;
element.y = center.y - element.height / 2;
sources.push({ resource, file: source });
return [element];
};
try {
await this.waitForDrawing(view, validate);
const elements: ExcalidrawElement[] = [];
let right: number | undefined;
for (const resource of resources) {
const prepared = await prepare(resource);
if (!prepared.length) continue;
const bounds = ea.getBoundingBox(prepared);
const left = right === undefined ? bounds.topX : right + 24;
elements.push(...(right === undefined ? prepared : repositionElementsToCursor(prepared, { x: left, y: bounds.topY }, false)));
right = left + bounds.width;
}
if (!elements.length) return;
await this.waitForDrawing(view, validate);
const publish = () => {
validate();
if (sources.some(source => this.sourceFile(source.resource) !== source.file)) throw Error("Visual resource source retired");
};
if (await view.addElements({ newElements: elements, images: ea.imagesDict, newElementsOnTop: true, validateBeforePublish: publish })) {
api.selectElements(elements);
await view.saveWithOutcome();
if (approximated) new Notice(t("LUCIDE_APPROXIMATION"));
}
} catch {
if (active()) new Notice(t("VR_INSERT_FAILED"));
} finally { ea.destroy(); }
}
/** Insert editable SVG geometry and optionally add a vault wikilink to the drawing's properties. */
public async insertSvgStrokes(resource: VisualResource, view: ExcalidrawView | null, active: () => boolean, retainSource: boolean | string): Promise<void> {
if (!this.writable(view) || !active() || resource.locator.provider !== "vault") return;
const source = this.sourceFile(resource);
if (source?.extension.toLowerCase() !== "svg" || source.stat.size > 2_000_000) return;
const vault = this.plugin.app.vault;
const file = view.file, path = file.path, api = view.excalidrawAPI, owner = view.ownerDocument;
const stillTarget = () => view.file === file && file.path === path && view.excalidrawAPI === api &&
view.ownerDocument === owner && view.leaf.view === view && !view.isClosingOrMigrating() && vault.getFileByPath(path) === file;
const validate = () => {
if (this.disposed || !active() || !stillTarget() || !this.writable(view) || this.sourceFile(resource) !== source) throw Error("SVG target retired");
};
const ea = this.plugin.ea.getAPI(view);
try {
await this.waitForDrawing(view, validate);
const text = await vault.read(source);
validate();
if (!ea.importSVG(text) || !ea.getElements().length) return;
const elements = ea.getElements();
ea.addToGroup(elements.map(element => element.id));
view.setCurrentPositionToCenter();
if (!await view.addElements({ newElements: elements, newElementsOnTop: true, repositionToCursor: true,
shouldRestoreElements: true, validateBeforePublish: validate })) return;
api.selectElements(elements);
const saved = await view.saveWithOutcome();
if (!retainSource || file.extension !== "md" || !stillTarget() || this.sourceFile(resource) !== source) return;
if (saved.acknowledgedRevision === null || saved.acknowledgedRevision < saved.requestedRevision) throw Error("SVG insertion save was not acknowledged");
const link = "[[" + this.plugin.app.metadataCache.fileToLinktext(source, file.path) + "]]";
await this.plugin.app.fileManager.processFrontMatter(file, (frontmatter: Record<string, unknown>) => {
if (!stillTarget()) return;
const property = typeof retainSource === "string" ? retainSource : "excalidraw-svg-sources";
const current: unknown = Object.hasOwn(frontmatter, property) ? frontmatter[property] : undefined;
const links: unknown[] = Array.isArray(current) ? current : current === undefined ? [] : [current];
if (!links.includes(link)) Object.defineProperty(frontmatter, property, { value: [...links, link], enumerable: true, writable: true, configurable: true });
});
} finally { ea.destroy(); }
}
/** Start an internal drag with an opaque, one-use token. */
public startDrag(transfer: DataTransfer, resource: VisualResource): void {
const token = nanoid();
this.drag = { token, resource, file: this.sourceFile(resource) };
transfer.setData(DRAG_TYPE, token);
transfer.effectAllowed = "copy";
}
/** Clear in-memory identity when an internal drag ends or its source retires. */
public endDrag(): void { this.drag = null; }
/** Accept only the current in-process drag payload. */
public isDrag(transfer: DataTransfer | null): boolean { return !!this.drag && !!transfer?.types.includes(DRAG_TYPE); }
public canDropInMarkdown(transfer: DataTransfer, target: TFile): boolean {
const drag = this.drag;
return !this.disposed && this.isDrag(transfer) && drag.resource.locator.provider === "vault" &&
!!drag.file && drag.file !== target && this.sourceFile(drag.resource) === drag.file &&
this.plugin.app.vault.getFileByPath(target.path) === target;
}
/** Consume a vault-resource drag and produce the same link as a click insertion. */
public markdownDrop(transfer: DataTransfer, target: TFile): string | null {
if (!this.canDropInMarkdown(transfer, target) || transfer.getData(DRAG_TYPE) !== this.drag.token) return null;
const { resource, file } = this.drag;
this.endDrag();
const frame = resource.locator.provider === "vault" && resource.locator.frame;
return this.markdownLink(file, target, frame ? "#^frame=" + frame : undefined);
}
/** Consume a drop once in the receiving drawing. */
public drop(transfer: DataTransfer | null, view: ExcalidrawView, point: ScenePoint): boolean {
if (!this.drag || transfer?.getData(DRAG_TYPE) !== this.drag.token) return false;
const { resource, file } = this.drag;
this.endDrag();
void this.insert(resource, view, () => this.sourceFile(resource) === file, point);
return true;
}
/** Identify the rendered content independently of gallery ordering and labels. */
public previewKey(resource: VisualResource, dark: boolean, memo?: PreviewDependencyStamps): string {
if (resource.previewElements) {
let geometry = this.libraryPreviewKeys.get(resource.previewElements);
if (geometry === undefined) {
// Restoring older items can repair indices and bump version metadata.
geometry = JSON.stringify(resource.previewElements.map(({ version, versionNonce, updated, ...element }) => element));
this.libraryPreviewKeys.set(resource.previewElements, geometry);
}
return JSON.stringify([visualResourceKey(resource.locator), dark]) + geometry;
}
const file = this.sourceFile(resource);
const drawing = file && this.plugin.isExcalidrawFile(file);
let dependencies = memo?.get(file);
if (drawing && !dependencies) {
dependencies = getExcalidrawEmbeddedFilesFiletree(file, this.plugin).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
.map(source => [source.path, source.stat.mtime, source.stat.size]);
memo?.set(file, dependencies);
}
const rendition = drawing && resource.locator.provider === "vault" && !resource.locator.frame ? this.exportedPreview(file, dark) : null;
const thumbnail: unknown = drawing ? this.plugin.app.metadataCache.getFileCache(file)?.frontmatter?.[FRAME_THUMBNAIL_PROPERTY] : null;
return JSON.stringify([visualResourceKey(resource.locator), !!drawing, file?.stat.mtime, file?.stat.size, dark, dependencies ?? [],
rendition?.path, rendition?.stat.mtime, typeof thumbnail === "string" ? thumbnail : null]);
}
private exportedPreview(file: TFile, dark: boolean): TFile | null {
const vault = this.plugin.app.vault;
const thumbnail: unknown = this.plugin.app.metadataCache.getFileCache(file)?.frontmatter?.[FRAME_THUMBNAIL_PROPERTY];
if (typeof thumbnail === "string" && thumbnail.trim()) return null;
const theme = dark ? "dark" : "light";
for (const extension of [theme + ".png", theme + ".svg", "png", "svg"]) {
const candidate = vault.getFileByPath(getIMGFilename(file.path, extension));
if (candidate && candidate.stat.mtime >= file.stat.mtime && candidate.stat.size <= DRAWING_PREVIEW_BYTES) return candidate;
}
return null;
}
/** Return a local image preview, with SVG markup used only as an image URL. */
public async preview(resource: VisualResource, dark: boolean, active: () => boolean = () => true): Promise<string | SVGSVGElement | null> {
if (resource.locator.provider === "lucide") return getIcon(resource.locator.icon);
const file = this.sourceFile(resource);
if (resource.locator.provider === "vault" && file && !this.plugin.isExcalidrawFile(file))
return IMAGE_TYPES.includes(file.extension.toLowerCase()) ? this.plugin.app.vault.getResourcePath(file) : null;
const key = this.previewKey(resource, dark);
const cached = this.previews.get(key);
if (cached) {
this.previews.delete(key);
this.previews.set(key, cached);
return cached;
}
if (resource.locator.provider === "vault" && file) {
const frame = resource.locator.frame;
const path = file.path, mtime = file.stat.mtime;
const epoch = this.previewEpoch;
const pending = this.drawingPreviewQueue.then(async () => {
if (this.disposed || !active() || this.sourceFile(resource) !== file || file.path !== path || file.stat.mtime !== mtime) return null;
const rendition = !frame && this.exportedPreview(file, dark);
if (rendition) return this.plugin.app.vault.getResourcePath(rendition);
const current = () => !this.disposed && active() && this.sourceFile(resource) === file && file.path === path && file.stat.mtime === mtime;
const persistent = () => epoch === this.previewEpoch && this.plugin.settings.allowImageCache;
const cacheId = JSON.stringify([path, frame ?? null, dark]);
const stamp = THUMBNAIL_VERSION + key;
const png = persistent() ? await this.thumbnailCache.get(cacheId, stamp) : null;
if (!current()) return null;
let image = png && persistent() ? await blobToDataURL(png) : null;
if (!image && !frame) {
const loader = new EmbeddedFilesLoader(this.plugin, dark);
const result = await loader.getObsidianImage(file, 0, {
cachedExcalidrawMaxBytes: DRAWING_PREVIEW_BYTES,
});
image = result?.dataURL ?? null;
}
let rendered: Blob | null = null;
if (!image && current() && file.stat.size <= DRAWING_PREVIEW_SOURCE_BYTES) {
// Yield between cold previews so scrolling and editing can continue.
await new Promise<void>(resolve => window.setTimeout(resolve, 16));
if (!current()) return null;
const previous = this.previewScene;
const scene = previous?.file === file && previous.path === path && previous.mtime === mtime
? previous.scene : await readDrawingPreviewScene(this.plugin.app.vault, file, DRAWING_PREVIEW_SCENE_LENGTH);
if (!current()) return null;
if (scene.elements.length <= MAX_THUMBNAIL_ELEMENTS) this.previewScene = { file, path, mtime, scene };
const thumbnail: unknown = this.plugin.app.metadataCache.getFileCache(file)?.frontmatter?.[FRAME_THUMBNAIL_PROPERTY];
rendered = await rasterizeDrawingResource(this.plugin, file, scene, frame, thumbnail, dark, current);
if (rendered && current()) image = await blobToDataURL(rendered);
}
if (!image || !current() || this.previewKey(resource, dark) !== key) return null;
if (rendered && persistent()) await this.thumbnailCache.put(cacheId, stamp, rendered);
if (!current()) return null;
if (epoch === this.previewEpoch) this.rememberPreview(key, image);
return image;
});
this.drawingPreviewQueue = pending.catch(() => {});
return pending;
}
const ea = this.plugin.ea.getAPI();
try {
const options = { ...ea.getExportSettings(false, false), drawingThumbnail: true };
const source = resource.previewElements ?? (await this.libraryItem(resource.locator))?.elements;
if (!source) return null;
const elements = structuredClone(Array.from(source));
for (const element of elements) ea.elementsDict[element.id] = element;
const svg = await ea.createSVG(undefined, false, options, undefined, dark ? "dark" : "light", 4);
if (!svg) return null;
const data = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg.outerHTML);
if (resource.previewElements) this.rememberPreview(key, data);
return data;
} finally { ea.destroy(); }
}
/** Clears both thumbnail tiers and retires writes already rendering. */
public async clearThumbnailCache(): Promise<void> {
this.previewEpoch++;
this.previews.clear();
this.previewBytes = 0;
await this.thumbnailCache.clear();
}
private rememberPreview(key: string, data: string): void {
if (this.disposed || key.length + data.length >= PREVIEW_CACHE_BYTES) return;
const previous = this.previews.get(key);
this.previewBytes += previous === undefined ? key.length + data.length : data.length - previous.length;
this.previews.set(key, data);
for (const [oldKey, preview] of this.previews) {
if (this.previewBytes <= PREVIEW_CACHE_BYTES) break;
this.previews.delete(oldKey);
this.previewBytes -= oldKey.length + preview.length;
}
}
/** Drop frame discovery entries owned by the changed path or a moved folder. */
public invalidatePreview(path: string): void {
for (const source of this.framePreviews.keys()) if (source === path || source.startsWith(path + "/")) this.framePreviews.delete(source);
}
/** Reveal a backing file in the system explorer when the desktop adapter exposes that operation. */
public revealSystem(resource: VisualResource): (() => void) | null {
const file = this.sourceFile(resource);
const app = this.plugin.app;
if (!Platform.isDesktopApp || !file || !(app.vault.adapter instanceof FileSystemAdapter) || !app.showInFolder) return null;
return () => app.showInFolder?.(file.path);
}
}
@@ -0,0 +1,185 @@
import type { ExcalidrawElement, FileId, NonDeleted } from "@zsviczian/excalidraw/types/element/src/types";
import type { BinaryFiles, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import type { TFile } from "obsidian";
import { exportToBlob } from "src/constants/constants";
import type ExcalidrawPlugin from "src/core/main";
import { EMBEDDED_VAULT_FILE_REG, RE_EXCALIDRAWDATA_NOSECTION_OK } from "src/shared/excalidrawMarkdownParsing";
import { blobToDataURL } from "src/utils/coreUtils";
import { readDrawingPreviewScene } from "src/utils/drawingPreviewScene";
import { getEmbeddedFilenameParts } from "src/utils/embeddedFilenameParts";
import { getElementsInArea } from "src/utils/excalidrawElementUtils";
import { getFrameBasedOnFrameNameOrId } from "src/utils/excalidrawViewUtils";
import { FRAME_THUMBNAIL_PROPERTY, resolveThumbnailFrame } from "src/utils/frameMetadata";
import { getLinkParts } from "src/utils/linkUtils";
import { inspectRasterDimensions } from "src/utils/rasterImageDimensions";
import { admitDrawingPreview, DRAWING_PREVIEW_SCENE_LENGTH, DRAWING_PREVIEW_SOURCE_BYTES, drawingPreviewGeometryBudget } from "./visualResourceModel";
const THUMBNAIL_SIDE = 256;
const MAX_ASSET_COUNT = 16;
const MAX_ASSET_BYTES = 4 * 1024 * 1024;
const MAX_TOTAL_ASSET_BYTES = 8 * 1024 * 1024;
const MAX_TOTAL_ASSET_PIXELS = 40_000_000;
const MAX_NESTED_DRAWING_DEPTH = 2;
const RASTER_TYPES = new Map([["png", "image/png"], ["jpeg", "image/jpeg"], ["jpg", "image/jpeg"], ["webp", "image/webp"]]);
type PreviewScene = Awaited<ReturnType<typeof readDrawingPreviewScene>>;
type PreviewDimensions = { width: number; height: number; originalWidth: number; originalHeight: number };
type ReducedImage = PreviewDimensions & { url: DataURL; drawing?: true };
type PNGThumbnail = { png: Blob; dimensions: PreviewDimensions };
type RenderContext = {
plugin: ExcalidrawPlugin;
dark: boolean;
active: () => boolean;
ancestors: Set<TFile>;
geometry: ReturnType<typeof drawingPreviewGeometryBudget>;
assetsLeft: number;
bytesLeft: number;
pixelsLeft: number;
sceneLengthLeft: number;
};
async function reduceRaster(blob: Blob, expected: { width: number; height: number }, owner: Document, active: () => boolean): Promise<ReducedImage | null> {
const fragment = owner.defaultView.createFragment();
const image = fragment.createEl("img");
const urls = owner.defaultView.URL;
const url = urls.createObjectURL(blob);
const canvas = fragment.createEl("canvas");
try {
image.src = url;
await image.decode();
if (!active()) return null;
const { naturalWidth: originalWidth, naturalHeight: originalHeight } = image;
if (!(originalWidth === expected.width && originalHeight === expected.height ||
originalWidth === expected.height && originalHeight === expected.width)) return null;
const scale = Math.min(1, THUMBNAIL_SIDE / Math.max(originalWidth, originalHeight));
const width = canvas.width = Math.max(1, Math.round(originalWidth * scale));
const height = canvas.height = Math.max(1, Math.round(originalHeight * scale));
const context = canvas.getContext("2d");
if (!context) return null;
context.drawImage(image, 0, 0, width, height);
return { url: canvas.toDataURL("image/png") as DataURL, width, height, originalWidth, originalHeight };
} finally {
canvas.width = 0;
image.removeAttribute("src");
urls.revokeObjectURL(url);
}
}
async function reduceDrawing(context: RenderContext, file: TFile, reference: string): Promise<ReducedImage | null> {
if (context.ancestors.has(file) || context.ancestors.size > MAX_NESTED_DRAWING_DEPTH ||
file.stat.size > DRAWING_PREVIEW_SOURCE_BYTES || context.sceneLengthLeft <= 0) return null;
const parts = getEmbeddedFilenameParts(reference);
const frameId = parts.hasFrameref || parts.hasClippedFrameref ? parts.blockref ?? parts.sectionref : undefined;
if (!frameId && (parts.hasSectionref || parts.hasBlockref && parts.blockref !== "as-image")) return null;
const app = context.plugin.app;
const scene = await readDrawingPreviewScene(app.vault, file, context.sceneLengthLeft);
if (!context.active()) return null;
context.sceneLengthLeft -= scene.length;
const thumbnail: unknown = app.metadataCache.getFileCache(file)?.frontmatter?.[FRAME_THUMBNAIL_PROPERTY];
context.ancestors.add(file);
try {
const image = await renderDrawingThumbnail(context, file, scene, frameId, thumbnail);
if (!image || !context.active()) return null;
return { ...image.dimensions, url: await blobToDataURL(image.png), drawing: true };
} finally { context.ancestors.delete(file); }
}
/** Reduce visible linked images and drawings under one shared work budget. */
async function loadVisibleImages(context: RenderContext, drawing: TFile, source: string, elements: readonly ExcalidrawElement[]) {
const ids = new Set(elements.flatMap(element => element.type === "image" && element.fileId ? [element.fileId] : []));
const reduced = new Map<FileId, ReducedImage>();
if (!ids.size) return reduced;
const { app } = context.plugin;
const owner = app.workspace.containerEl.ownerDocument;
const data = source.slice(Math.max(0, source.search(RE_EXCALIDRAWDATA_NOSECTION_OK)));
const section = /^(?:## Embedded Files|# Embedded files)\n([\s\S]*?)(?=^#{1,2} |(?![\s\S]))/m.exec(data)?.[1];
if (!section) return reduced;
for (const [, rawId, link] of section.matchAll(EMBEDDED_VAULT_FILE_REG)) {
const id = rawId as FileId;
if (!ids.delete(id)) continue;
if (!context.active() || context.assetsLeft <= 0) break;
const asset = app.metadataCache.getFirstLinkpathDest(getLinkParts(link).path, drawing.path);
if (!asset) continue;
const type = RASTER_TYPES.get(asset.extension.toLowerCase());
const nestedDrawing = context.plugin.isExcalidrawFile(asset);
const size = asset.stat.size;
if ((!type && !nestedDrawing) || size > Math.min(MAX_ASSET_BYTES, context.bytesLeft)) continue;
context.assetsLeft--;
context.bytesLeft -= size;
try {
if (nestedDrawing) {
const image = await reduceDrawing(context, asset, link);
if (image) reduced.set(id, image);
continue;
}
const bytes = await app.vault.readBinary(asset);
if (bytes.byteLength > size || !context.active()) continue;
const dims = inspectRasterDimensions(new Uint8Array(bytes, 0, Math.min(bytes.byteLength, 262_144)));
if (!dims || dims.width * dims.height > context.pixelsLeft) continue;
context.pixelsLeft -= dims.width * dims.height;
const image = await reduceRaster(new Blob([bytes], { type }), dims, owner, context.active);
if (image) reduced.set(id, image);
} catch {
// A missing or corrupt image can still be represented by its bounds.
}
}
return reduced;
}
async function renderDrawingThumbnail(context: RenderContext, drawing: TFile, scene: PreviewScene,
frameId: string | undefined, thumbnail: unknown): Promise<PNGThumbnail | null> {
const { elements, source } = scene;
const frame = frameId ? getFrameBasedOnFrameNameOrId(frameId, elements) : resolveThumbnailFrame(elements, thumbnail);
if (frameId && !frame) return null;
const content = frame ? getElementsInArea(elements, frame, { includeBoundElements: true }).filter(element => element.id !== frame.id) : elements;
if (!content.length || !admitDrawingPreview(content, context.geometry)) return null;
const images = await loadVisibleImages(context, drawing, source, content);
if (!context.active()) return null;
const files: BinaryFiles = {};
const geometry = content.map((element): NonDeleted<ExcalidrawElement> => {
if (element.type === "image" && element.fileId) {
const id = element.fileId;
const image = images.get(id);
if (image) {
files[id] = { id, mimeType: "image/png", dataURL: image.url, created: drawing.stat.mtime };
const scaleX = image.width / image.originalWidth, scaleY = image.height / image.originalHeight;
const crop = element.crop;
return { ...element, status: "saved", isDeleted: false,
customData: image.drawing ? { ...element.customData, invertBitmapInDarkmode: false } : element.customData,
crop: crop ? {
x: crop.x * scaleX, y: crop.y * scaleY, width: crop.width * scaleX, height: crop.height * scaleY,
naturalWidth: image.width, naturalHeight: image.height,
} : null };
}
}
if (element.type === "image" || element.type === "embeddable" || element.type === "iframe")
return { ...element, isDeleted: false, type: "rectangle", fillStyle: "solid", strokeColor: "#868e96", backgroundColor: "#868e9633", roughness: 0 };
return { ...element, isDeleted: false };
});
let dimensions: PreviewDimensions = null;
const png = await exportToBlob({
elements: geometry,
files,
exportingFrame: frame ? { ...frame, isDeleted: false } : undefined,
appState: { exportBackground: false, exportWithDarkMode: context.dark },
mimeType: "image/png",
exportPadding: 4,
getDimensions: (width, height) => {
if (![width, height].every(value => Number.isFinite(value) && value > 0)) throw Error("Invalid thumbnail dimensions");
const scale = Math.min(1, THUMBNAIL_SIDE / Math.max(width, height));
dimensions = { width: Math.max(1, Math.floor(width * scale)), height: Math.max(1, Math.floor(height * scale)),
originalWidth: width, originalHeight: height };
return { width: dimensions.width, height: dimensions.height, scale };
},
});
return dimensions ? { png, dimensions } : null;
}
/** Render one drawing or named frame into a PNG using only bounded in-area dependencies. */
export async function rasterizeDrawingResource(plugin: ExcalidrawPlugin, drawing: TFile, scene: PreviewScene, frameId: string | undefined,
thumbnail: unknown, dark: boolean, active: () => boolean): Promise<Blob | null> {
const context: RenderContext = { plugin, dark, active, ancestors: new Set([drawing]), geometry: drawingPreviewGeometryBudget(),
assetsLeft: MAX_ASSET_COUNT, bytesLeft: MAX_TOTAL_ASSET_BYTES, pixelsLeft: MAX_TOTAL_ASSET_PIXELS,
sceneLengthLeft: DRAWING_PREVIEW_SCENE_LENGTH - scene.length };
return (await renderDrawingThumbnail(context, drawing, scene, frameId, thumbnail))?.png ?? null;
}
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more