Compare commits

...
Author SHA1 Message Date
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
zsviczian 32827ab679 test: align native context-menu hit testing with integer coordinates 2026-11-19 20:50:48 +01:00
zsviczian bb65485b9b added show hints to saved appState variables 2026-11-19 06:54:35 +01:00
zsviczian 5e8ec2a4a2 bumped packages 2026-11-17 20:56:54 +01:00
zsviczian da2a8c6990 Merge pull request #3057 from zsviczian/feat/ai-reasoning-secrets-embeds
Add AI reasoning effort, optional SecretStorage, and migrated ExcaliAI
2026-11-17 18:36:48 +01:00
zsviczian 02c3339cf6 Add AI reasoning controls, secret storage, and migrated ExcaliAI
Implement optional OpenAI reasoning effort and device-local SecretStorage references while preserving obfuscated settings keys. Refresh new-install presets, publish the migrated script download, fix reading-mode Markdown scrolling, and guard saving retired editors.
2026-11-17 18:26:52 +01:00
zsviczian cd667faacf Update Slideshow previews for scene backgrounds and dark mode 2026-11-16 19:10:13 +01:00
zsviczian 7b8b19c2b5 Better slideshow transition controls with icons, previews, better UX flow etc. 2026-11-16 09:34:41 +01:00
zsviczian fcd0bb937a Localize rank achievement dialog in supported languages 2026-11-15 21:40:01 +01:00
zsviczian 1a8ee3e46d Merge pull request #3052 from zsviczian/2026-11-14-issue-3049-embed-and-startup-fixes
Fix drawing embed controls, add empty-tab creation and harden Extras handling
2026-11-15 12:39:20 +01:00
zsviczian 3f0a4cca22 Record progressive PNG native acceptance and guarded deployment 2026-11-15 12:30:41 +01:00
zsviczian b5f97ceaf4 Recognize owned PNG images after popout document adoption 2026-11-15 12:20:38 +01:00
zsviczian 57b50cb920 Snapshot inline PNG pixels before popout activation can retire its source 2026-11-15 12:11:20 +01:00
zsviczian 599815d9e0 Gate only fullscreen detail reads during native PNG checks 2026-11-15 12:03:57 +01:00
zsviczian 3ac946ec16 Measure PNG detail against dimensions captured before image retirement 2026-11-15 11:50:44 +01:00
zsviczian 036aa54800 Upgrade PNG fullscreen detail in background and cancel on close 2026-11-15 11:46:59 +01:00
zsviczian 7aedebfa4e Open PNG embed previews without rerasterizing the drawing 2026-11-15 11:28:15 +01:00
zsviczian 165c3faa51 Record maintainer approval to retain Extras guards 2026-11-15 07:49:16 +01:00
zsviczian 18af543a37 Enable New Drawing by default and require consent for plugin compatibility 2026-11-15 07:44:08 +01:00
zsviczian 20ea50d494 Record issue fixes validation and remaining manual checks 2026-11-14 23:51:52 +01:00
zsviczian 7878222101 Keep selection while holding the pen toggle shortcut 2026-11-14 23:42:48 +01:00
zsviczian fdca179677 Keep PNG sources readable for the rendered image lifetime 2026-11-14 22:52:06 +01:00
zsviczian 867c48d154 Refresh owned PNG payloads across window migration 2026-11-14 22:04:57 +01:00
zsviczian 8479d6d3a1 Preserve PNG document ownership and teardown cleanup 2026-11-14 21:53:55 +01:00
zsviczian df3fc0bf74 Give PNG drawing embeds independent blob URL lifetimes 2026-11-14 21:39:18 +01:00
zsviczian ddc046255c Settle owned drawing saves before native plugin reload 2026-11-14 20:54:55 +01:00
zsviczian 3af2423238 Harden issue regression fixtures and pin paired CI sources 2026-11-14 20:48:44 +01:00
zsviczian 8dbd9ad7ad Fix embed controls and add optional empty-tab drawing creation
Prefer physical table ownership for wrapped embeds and reset relative mobile toolbar offsets. Add independent ribbon and empty-tab action preferences using the canonical creation/settings pipelines, with maintained translations and deterministic cleanup.

Toggle pen to selection on a second unmodified P at the plugin capture boundary. Cancel incomplete Extras APIs cleanly while preserving version gates; the incomplete #3051 reporter cause remains unconfirmed. Pair native video coverage with fork PR #484's two-condition iframe fix.

Validation: 781 plugin source cases, five bundle checks, development/production builds, focused lint, CSS and inventory pass. Fork source/browser/type/audit evidence and inherited-test limitations are documented. Native CLI testing is explicitly paused at maintainer request. Versions and dependencies remain unchanged. Refs #3049, #3047, #3044, #3048 and #3051.
2026-11-14 08:30:51 +01:00
zsviczian 90966e62b3 docs: plan drawing embed, startup and creation fixes 2026-11-14 07:45:55 +01:00
zsviczian 78674a39cc test: cover upstream minimap and zoom menu integration
Exercise minimap painting, owner-document portals, centered wheel zoom, live host limits and teardown across full, compact and tray layouts in main windows and popouts. Add a focused --minimap lane and adapt Zen controls to the new zoom menu.

Validation: 13 native runner tests and inventory check pass. Previously verified 1004 portable cases and 11 focused native cases with the merged local fork. Complete native limitations remain tracked in #3049. Dependency files and package versions are unchanged; the unpublished fork artifacts remain a local handoff.
2026-11-13 22:10:50 +01:00
zsviczian 8b6f79efa3 Merge pull request #3046 from zsviczian/2026-11-12-issue-2714-embed-reliability-bundle
Harden file insertion, heading embeds, SVG exports and focused Save As
2026-11-13 18:28:20 +01:00
zsviczian 6a3e2eb2e4 Harden file insertion, heading embeds, SVG exports and focused Save As
Implement the scoped fixes for PR #3046:
- Ignore unsupported aliases while retaining whole string/list aliases and paths.
- Use Obsidian source-heading identities for section targets, preserving legacy
  image-transclusion matching.
- Block Ctrl/Cmd+Shift+S only in the focused drawing editor, retaining normal
  save and explicit legacy export.
- Honor internal-link removal in manual vault and clipboard SVG exports through
  the existing scene filter without mutating source elements or changing hooks.

Add source and native regressions, including standalone H2 wikilinks, aliased
and unresolved wikilinks, save/reopen, image decoding and ordinary section-link
navigation in Reading and Live Preview. Preserve the original NBSP attachment
with provenance. Add the requested CLI troubleshooting guidance and remove the
temporary plan-only handoff.

Validation: 993 portable cases passed; 776 fast/source tests passed; all ten
PR-specific native cases passed in main and popout, including the expanded
wikilink matrix. Production build and all five bundle tests passed. No new lint
diagnostics; the repository retains 116 existing errors. The exact tested build
was deployed to Zsolt's Brain with backed-up artifacts and unchanged settings.

The complete native profile remains failed: table controls also fail on the
unchanged baseline; the offscreen phone toolbar remains unclassified against
baseline. Initial zoom-settling and popout code-image reopen failures passed
focused reruns. macOS, physical mobile and minimum-version Obsidian remain
untested. Original SVG escaping (#2570) and NBSP (#2389) reports did not reproduce
on this Windows host; they gain coverage without speculative serializer/cache
changes. Optional simple-columns compatibility (#2858) is deferred.
2026-11-12 22:03:32 +01:00
zsviczian bf7cd48984 docs: add temporary handoff for six-issue reliability draft PR 2026-11-12 11:05:41 +01:00
zsviczian 87f0f929fb Merge pull request #3043 from zsviczian/2026-11-11-issue-3042-frame-anchors-thumbnails
Add frame thumbnails and persisted drawing-image preview controls (#3042)
2026-11-11 18:16:00 +01:00
zsviczian 9390d8dda1 Pin portable CI to Ubuntu 24.04 supported by Playwright 2026-11-11 18:06:21 +01:00
zsviczian c5441e7ef5 Shorten drawing preview padding descriptions 2026-11-11 17:53:28 +01:00
zsviczian 1907a6d9a8 Stabilize padding sliders and derive area ranges from saved geometry 2026-11-11 16:34:11 +01:00
zsviczian c9f1984823 Refine drawing preview padding controls and guidance 2026-11-11 12:27:53 +01:00
zsviczian 805fd4d8d4 Add persisted preview settings for embedded drawings 2026-11-11 10:38:26 +01:00
zsviczian 87c5de54ed feat: add frame anchors, thumbnails and navigation (#3042) 2026-11-11 08:10:34 +01:00
zsviczian 407e11d9e8 docs: stage plan-only handoff for semantic frame anchor issue #3042 2026-11-11 06:24:44 +01:00
zsviczian 83c35ffffe Merge pull request #3041 from zsviczian/2026-11-10-embed-rendering-padding
Fix drawing embed rendering and add area padding controls
2026-11-10 14:53:00 +01:00
zsviczian c7d0818476 Fix drawing embed rendering and add area padding controls 2026-11-10 14:52:13 +01:00
zsviczian 2ef81a5d03 updated slideshow script. Added the option include slide frames around slides in handout exports. 2026-11-08 15:20:41 +01:00
zsviczian 9c209a82cb 2.29.2 2026-11-07 18:01:54 +01:00
zsviczian c5b82a7000 code scanner fixes 2026-11-07 15:07:49 +01:00
zsviczian a5747b26b7 0.18.147 2026-11-07 13:30:31 +01:00
zsviczian 0da8ab3216 Merge pull request #3037 from zsviczian/2026-11-06-issue-3036-embed-controls
Add resize, source editing, and fullscreen controls for drawing embeds
2026-11-07 11:57:56 +01:00
zsviczian 3fa23d63dc Refine drawing embed controls, preview, and modifier navigation 2026-11-07 11:56:57 +01:00
zsviczian 13bac7afab Support embed controls in drawings opened as Markdown 2026-11-07 08:44:57 +01:00
zsviczian 07c1efc2ff Recover offscreen native resize targets after pending caret scroll 2026-11-07 02:46:17 +01:00
zsviczian b32edf1dfe Record validated embed runtime and final native acceptance target 2026-11-07 01:51:14 +01:00
zsviczian 7de41e7324 Allow aligned previews to shrink below toolbar width 2026-11-07 01:33:33 +01:00
zsviczian a395c7d59b Measure bounded table resizing and await extraction ownership 2026-11-07 01:20:18 +01:00
zsviczian 38ea57463c Record table input ownership in native failures 2026-11-07 01:08:25 +01:00
zsviczian 0a3c495a2e Preserve aligned embed geometry during resize previews 2026-11-07 01:03:00 +01:00
zsviczian 2252e5aeef Stabilize embed layout and native input lifetimes 2026-11-07 00:44:18 +01:00
zsviczian 76ffd8ed4d Harden embed controls for native tables and mobile input 2026-11-06 23:34:50 +01:00
zsviczian 0f24b038bb Keep embed controls aligned after cancellation and reflow 2026-11-06 17:14:00 +01:00
zsviczian 809e08af16 Release Reading embed controls when the plugin unloads 2026-11-06 17:04:09 +01:00
zsviczian 14115712a8 Add source-owned drawing embed controls and fullscreen preview 2026-11-06 16:47:19 +01:00
zsviczian 5d442b70ff docs: prepare implementation handoff for Excalidraw embed controls (#3036) 2026-11-06 15:08:19 +01:00
zsviczian 375b460c0b Merge pull request #3035 from zsviczian/feat/mermaid-3.6-extras-requirement
Require Extras Mermaid 3.6 and align conversion coverage
2026-11-05 22:26:32 +01:00
zsviczian 1f429d9616 Document the coordinated Mermaid 3.6 service requirement 2026-11-05 22:17:36 +01:00
zsviczian 8d54f16c57 Preserve native readiness across reload and follow extraction modal ownership 2026-11-05 21:41:53 +01:00
zsviczian ed42804dae Wait for native synchronization ownership and pin verified Extras consumer 2026-11-05 20:51:07 +01:00
zsviczian 2697b755ef Require Extras Mermaid 3.6 and align conversion regression coverage 2026-11-05 20:19:46 +01:00
zsviczian f31dff9ec1 fix: prevent recursive Markdown embeds during PDF export
Claim drawing image embeds synchronously before yielding to Obsidian's native embed discovery. Preserve native images, text references and hybrid Markdown rendering, and cover main/popout PDF preparation. Correct macOS editing commands in native test input.

Validation: 871 portable cases passed, PDF/embed and installed K-Plex checks passed. Separate native Mac Cmd+S and failed-path cleanup checks remain failing; their evidence is preserved.
2026-11-05 07:05:13 +01:00
zsviczian 03f0011635 Merge pull request #3034 from zsviczian/codex/migrate-printable-layout-wizard
feat(scripts): update MindMap Builder, Slideshow and Printable Layout Wizard
2026-11-04 08:30:56 +01:00
173 changed files with 24707 additions and 6385 deletions

No files matched your search

+2 -2
View File
@@ -54,13 +54,13 @@ jobs:
- uses: actions/checkout@v4
with:
repository: zsviczian/excalidraw
ref: 278ed4937dde5fd9e77c83a4e25e5a9b3d8028f7
ref: 8260fa444f84c616d1486c2a47365c1b72c4be9a
path: .test-work/checkouts/fork
persist-credentials: false
- uses: actions/checkout@v4
with:
repository: zsviczian/obsidian-excalidraw-extras
ref: e247088e1222935a2bb006e94658b639916e0814
ref: 4bd7af3325a8059a5ca68fc3e88169507b08c773
path: .test-work/checkouts/extras
persist-credentials: false
- uses: actions/checkout@v4
+3 -3
View File
@@ -8,7 +8,7 @@ permissions:
contents: read
jobs:
portable:
runs-on: ubuntu-latest
runs-on: ubuntu-24.04
timeout-minutes: 35
env:
EXCALIDRAW_FORK_ROOT: ${{ github.workspace }}/.test-work/checkouts/fork
@@ -18,13 +18,13 @@ jobs:
- uses: actions/checkout@v4
with:
repository: zsviczian/excalidraw
ref: 278ed4937dde5fd9e77c83a4e25e5a9b3d8028f7
ref: 8260fa444f84c616d1486c2a47365c1b72c4be9a
path: .test-work/checkouts/fork
persist-credentials: false
- uses: actions/checkout@v4
with:
repository: zsviczian/obsidian-excalidraw-extras
ref: e247088e1222935a2bb006e94658b639916e0814
ref: 4bd7af3325a8059a5ca68fc3e88169507b08c773
path: .test-work/checkouts/extras
persist-credentials: false
- uses: actions/setup-node@v4
+15
View File
@@ -8,6 +8,11 @@ DOM/window ownership, cleanup, security, naming, type changes, localization, and
validation. Add future cross-cutting requirements there instead of duplicating
them here. Read [CONTRIBUTING.md](CONTRIBUTING.md) for setup and build workflows.
**Do not attempt compatibility work with another plugin without explicitly asking
for maintainer consent. Such work is out of scope by default.** Follow the
[mandatory compatibility consent control](CODING_STANDARDS.md#compatibility-with-other-plugins-requires-maintainer-consent);
a general issue-investigation request does not grant compatibility approval.
## Purpose
This repository contains the Obsidian Excalidraw plugin: an Obsidian.md plugin that integrates a heavily customized Excalidraw fork into Obsidian.
@@ -362,6 +367,16 @@ Follow the mandatory [validation requirements](CODING_STANDARDS.md#validation-re
### Obsidian CLI runtime lane
Do not infer that CLI is disabled from a transient `Command "eval" not found`
response or the preparation runner's generic first-open message. Check the
installed CLI's help, the selected vault's canonical path and initialization,
and pending dialogs; retry a benign read-only `eval` readiness probe before
requesting human help. Preserve the actual error and distinguish a temporarily
unready vault from missing CLI registration or trust. Do not invent a separate
"developer CLI" setting: verify any claimed setting against the installed UI
or official documentation before asking the maintainer to change it. An already
enabled CLI does not need to be enabled again.
Resolve recoverable dependency, host-request, menu-renderer and cleanup failures and rerun failed/blocked cases before returning. Follow [native failure recovery](docs/OBSIDIAN_RUNTIME_TESTING.md#recovering-from-native-test-failures); ask the maintainer promptly when an actual human prerequisite prevents progress.
Start with the layered [testing guide](docs/TESTING.md) and [Obsidian runtime testing](docs/OBSIDIAN_RUNTIME_TESTING.md). Use `npm run test:native` to prepare and test `.test-work/vaults/excalidraw-auto-test/`. Every native sequence builds selected workspace revisions, freezes and hash-verifies the plugin and available Extras artifacts, installs and enables them, applies the immutable seed's settings, verifies the running CLI vault/config identity and restores the declared baseline. Use the matching local fork when available. Never reuse stale installed builds. Missing Extras is explicit and cannot satisfy Extras-dependent coverage. Serialize preparation, deployment, scenarios and cleanup under the shared application-user-data lock. Specific maintained scripts remain tested in ea-scripts; focus here on core Excalidraw and ExcalidrawAutomate. Inventory and screenshots do not establish behavior; missing important matrix cases remain unfinished.
+25 -2
View File
@@ -80,7 +80,7 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- Do not write an element's `style` attribute directly. Use `setStyle` and `removeStyle` from `src/utils/styleUtils.ts` when a dynamic inline style is genuinely necessary.
- Use the existing visibility helpers instead of the native `hidden` property or attribute, which is not reliable in Obsidian's styled UI. Choose `hideElement`/`showElement` or `setComponentVisibility` from `src/utils/styleUtils.ts`, or `setElementHidden`/`setElementDisplay` from `src/utils/htmlUtils.ts` when a boolean/display-oriented API is clearer.
- Search `src/utils/styleUtils.ts` and `src/utils/htmlUtils.ts` before introducing new DOM styling helpers or display classes.
- Run Obsidian CodeScanner after CSS changes. Preserve compatibility with the declared minimum Obsidian version and prefer a widely supported property when it provides the same result; for example, a basic underline is preferable to optional underline-thickness/offset styling.
- Run `npm run lint:css` after CSS changes to check the public Obsidian scanner policy locally; hosted CodeScanner can apply additional review checks. Preserve compatibility with the declared minimum Obsidian version and prefer a widely supported property when it provides the same result; for example, a basic underline is preferable to optional underline-thickness/offset styling. Avoid `!important`: increase selector specificity for stylesheet rules, and expose scoped CSS-variable overrides with the original values as fallbacks when renderer-owned inline dimensions need to change.
- For a known vault path, use the most specific synchronous lookup: `app.vault.getFolderByPath()` for folders and `app.vault.getFileByPath()` for files. Use `getAbstractFileByPath()` only when either type is intentionally accepted, and avoid adapter-level existence checks when the Vault API already models the target.
- Radix content in the customized Excalidraw package may be rendered through `ObsidianRadixPortal` directly under the owning document's body. A body portal escapes component ancestor selectors and modal stacking contexts. When a trigger is visible but its menu or popover is not, first inspect whether the content mounted behind a modal or lost ancestor-scoped styles. Use a class on the portaled content, a portal-safe selector, and an explicit stacking level when required; validate main-window, popout, click-outside, and Escape behavior.
@@ -180,6 +180,29 @@ Use TSDoc as the documentation standard. It is the modern TypeScript-friendly ev
- Add short module-level documentation to files whose behavior is easy to misread, such as `rollup.config.mjs`, `src/core/managers/PackageManager.ts`, migration code in `src/core/main.ts`, and the `MathjaxToSVG/` subproject.
- Internal/private code should only be commented when the behavior is non-obvious. Avoid trivial comments.
## Compatibility with other plugins requires maintainer consent
Compatibility work with another plugin is out of scope by default. Once an
agent identifies that a proposed fix would accommodate another plugin's behavior,
it MUST explicitly ask for maintainer consent before implementing that work.
A general request to investigate or fix an issue is not approval for plugin
compatibility work.
The consent request must name the other plugin, distinguish the confirmed core
defect from the plugin interaction, describe the proposed accommodation, and
explain its complexity and maintenance cost. This includes lifecycle changes,
startup delays or retries, monkey patches, compatibility shims, fallback paths,
and relaxed API/version requirements. Apply this control to companion-plugin
compatibility changes as well; do not expand a supported integration's contract
without explicit approval.
Read-only triage may establish which component owns a failure. Do not presume
that Excalidraw should compensate for another plugin that is outdated, broken,
or incompatible with an Obsidian update. Report that boundary and prefer a fix
in the responsible plugin unless the maintainer explicitly approves otherwise.
Previously approved integrations are not authorization for new compatibility
work, and this policy does not authorize removing existing integrations.
## Backward Compatibility Requirements
Backwards compatibility is a strong requirement in this repository.
@@ -436,7 +459,7 @@ const containerEl = sceneElements.find(
- 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.
- Before declaring a code PR ready, run `npm run test:regression:portable`. Also run the affected native scenarios for editor input/history, rendering/embeds, settings/persistence, window ownership/lifecycle, CLI/EA integration or real Extras services. Run the complete `npm run test:native` profile before readiness when those native workflows are affected. A focused pass is not a complete native pass.
- 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.
- 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.
+18
View File
@@ -17,6 +17,12 @@ subsystem constraints, and agent workflows.
Before spending your valuable time writing code for a new feature or significant refactor, please **open an issue** to discuss it first. This ensures your idea aligns with the project's roadmap and architecture, and helps prevent wasted effort or complex merge conflicts later.
**Compatibility with another plugin is out of scope by default. Agents MUST
explicitly ask for maintainer consent before attempting compatibility work.**
A request to investigate or fix an issue does not implicitly approve workarounds
for another plugin. Identify the plugin, proposed accommodation and maintenance
cost first; see the mandatory [compatibility consent control](CODING_STANDARDS.md#compatibility-with-other-plugins-requires-maintainer-consent).
## 🚀 Getting Started
1. Fork the repository and clone it locally.
@@ -60,6 +66,14 @@ dependency graph rather than suppressing the warning. Check with
- **Check production packaging:** Run `npm run test:bundle` after `npm run build` to verify the private React bootstrap, bundled font bytes, compressed locales, and release size target.
- **Build the public library API:** Run `npm run lib` when changing exports or ExcalidrawAutomate APIs
- **Run ESLint:** Run `npm run code`
- **Check CSS scanner policy:** Run `npm run lint:css`. This uses the public
[`stylelint-config-obsidianmd`](https://github.com/obsidianmd/stylelint-config)
policy rules, with the browser target derived from `manifest.json`'s
`minAppVersion` using Obsidian's published Electron mapping. It follows the
[scanner workflow](https://github.com/obsidianmd/obsidian-workflows/blob/main/src/lint.ts)
without adding the theme package's formatting rules. The command fails on
warnings, so newly introduced policy findings can be caught before submission.
This is a local CSS check, not the complete hosted CodeScanner review.
- **Fix ESLint Warnings:** Run `node ./scripts/fix-eslint-warnings.mjs`
The shipped plugin is `dist/main.js`, `dist/styles.css`, and `dist/manifest.json`. Keep `main.js` below the **5 MB release target (5 × 1024 × 1024 = 5,242,880 bytes)** and report its byte size and remaining headroom after dependency or packaging changes.
@@ -97,6 +111,10 @@ For Markdown embed changes, also run `npm run test:markdown-embeds` and
`npm run verify:obsidian:plugin -- --embed-recovery`. See the runtime guide for
fixture ownership, deferred rendering, popout coverage, and remaining manual checks.
For relative links, detached Reading sections and area-padding controls, use the
six-case `node scripts/testing/host/verify.mjs --embed-regressions` lane. See
[drawing embed controls](docs/DRAWING_EMBED_CONTROLS.md) for behavior and scope.
For drawing-load warning changes, run `npm run test:drawing-load-error` to check
file identity, read-only details, filename truncation, and unchanged confirmation results.
+21
View File
@@ -72,6 +72,9 @@ validated, and what remains uncertain.
| 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 |
| 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 |
@@ -3521,3 +3524,21 @@ 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.
+77
View File
@@ -0,0 +1,77 @@
# AI models and credential sources
AI remains optional. Text, images and files are sent only when an AI workflow is
invoked. Provider profiles select the API family, base URL and credential source;
model entries select a model ID and its capabilities.
## Credential storage
Existing profiles and Taskbone continue using their saved keys by default. These
are **obfuscated**, not plain text, in the vault's plugin settings. Obfuscation is
reversible and is not encryption.
On Obsidian 1.11.4 or newer, create a secret in Obsidian's settings, then choose
**Obsidian SecretStorage (this device)** and its name in the provider or Taskbone
settings. Choosing that source removes the saved key from Excalidraw settings.
Only the source and reference name are synced. Configure that secret on each
device; an unavailable secret produces an error rather than falling back to a
synced key. Excalidraw does not create, change or delete shared secrets.
Switching back to **Obfuscated settings** requires entering a key again. Existing
backups and version-control history may still contain previously saved keys.
The script-facing `getAISettings()` exposes availability, never credential values
or secret names. Secret values are resolved afresh for each request.
## Reasoning effort
Add or edit an OpenAI text model and select **Reasoning effort**. **Default** omits
the parameter and keeps the API's default. Choices are filtered through the
reviewed capability table in `src/utils/aiReasoning.ts`; unrecognized models offer
Default only. Dated snapshots of listed model IDs use the same capabilities.
For example, `gpt-6.1-sol` supports low, medium, high, xhigh and max; Terra and Luna
also support none. Unsupported stored or scripted values fail before transport.
OpenAI-only fields never enter Anthropic, Google, xAI or compatible-provider
requests. Sampling parameters are omitted for reasoning models that reject them,
including models reasoning at their API default. GPT-6 uses
`max_completion_tokens`, including its reasoning-token budget.
EA requests inherit the selected text-model preference. A `reasoningEffort`
override chooses another supported level; `null` explicitly restores the API
default for that request. Raw `model` overrides do not inherit another model's
effort. ExcaliAI applies and displays the selected OpenAI model's effort for
text results, image analysis and the prompt-writing step before image generation.
## Recommendations for new installations
| Purpose | Default | Reason |
| --- | --- | --- |
| Text | `gpt-6-luna` | Efficient general text tasks |
| Image-aware text | `gpt-6.1-terra` | Visual reasoning |
| Image generation/editing | `gpt-image-2.6-flare` | Fast interactive iteration |
The new-install catalog also offers Sol, Claude Sonnet/Haiku/Opus 5.5, Gemini 3.8
Flash, Grok 4.7, GPT Image 2.6 Sunburst, stable Gemini image models and Grok Imagine
Image 2.0. Existing users keep their complete model maps, defaults, provider URLs,
keys and custom fields; an upgrade never replaces their configured entries.
Add current model IDs explicitly when retiring an old user-configured model.
GPT Image 2.6 supports custom dimensions. The settings supply a useful subset
within its documented limits rather than claiming that the old GPT Image sizes
are exhaustive. PNG remains the pipeline's default output; SVG/GIF-specific
options are not exposed by this change. Gemini Lite exposes only its supported
1K tier; xAI pixel selections are converted to its `aspect_ratio` parameter.
Provider documentation reviewed on November 16, 2026:
- [OpenAI model compatibility](https://developers.openai.com/api/docs/guides/latest-model)
- [OpenAI image generation and dimensions](https://developers.openai.com/api/docs/guides/image-generation)
- [Claude models](https://platform.claude.com/docs/en/models/overview)
- [Gemini models](https://ai.google.dev/gemini-api/docs/models)
- [Gemini image Lite](https://aistudio.google.com/docs/models/gemini-3.1-flash-lite-image)
- [xAI image generation](https://docs.x.ai/developers/model-capabilities/images/generation)
Automated tests use fake credentials and mocked transport. They validate request
construction, response normalization, secret isolation and persistence without
paid API access. Live model availability, account permissions, provider billing
and output quality require a separate test with the maintainer's own keys.
+209
View File
@@ -0,0 +1,209 @@
# Drawing embed controls
In Live Preview, hover a drawing embed to show its toolbar. Small embeds place
the toolbar below the image; touch layouts keep the controls visible. Drag the
bottom-right corner to resize, or focus it and use the arrow keys. A completed
resize changes only that occurrence in the containing note, with one undo step.
The toolbar offers **Outer padding** for default thumbnails, whole scenes, groups
and frame references, using the **box-select** icon. **Area expansion** keeps the
**square-dot** icon for `area=` references: it includes more of the surrounding
drawing. Outer padding adds space without including additional elements.
A compact horizontal Obsidian slider appears directly below the toolbar and previews
padding in increments of 1. Outer padding ranges from 0 to 100. Area expansion
uses the largest distance from a zero-padding crop edge to the corresponding
scene edge, plus 100. Saved geometry is read once when the control opens, without
refreshing embedded text or images, and the range stays fixed during the gesture.
The controls occupy the first row, with one small value underneath and then a
short description. Changing digit counts never changes the track width.
Existing saved padding remains unchanged until edited, including values above
the current slider maximum. You can drag, click the track, use the
arrow keys, or scroll over the slider. Closing the popup or pressing Enter saves
one source change; Escape cancels. **Use default padding** removes the explicit
`,padding=N` parameter and uses the drawing's export padding preference.
The padding preview holds the embed's displayed dimensions steady while its
content changes. It does not change the drawing file. A stale source, closed
note, replaced widget, or plugin unload cancels the gesture and its pending
preview. Paths, aliases, Markdown titles, dimensions, and table escapes are
preserved. Identical embeds remain independent.
Padding controls require an editable Live Preview source binding. They are absent for text references,
Reading view, read-only editors, nested Markdown transclusions, and Canvas.
Reading view retains preview and open-drawing actions.
Padding is independent of the selected view. For example,
`![[Drawing#^as-image,padding=30|300]]` follows the current default thumbnail with
30 units of outer padding; `![[Drawing#^frame=,padding=30|300]]` shows the whole
scene with that padding. Switching views retains the padding override. Thumbnail
contents stay clipped to the original frame rectangle before padding is added.
## Drawing images inside a scene
Select a drawing-backed image and use **Configure drawing preview** (scan-eye)
next to its existing image actions. The popover previews the chosen view and
padding without editing the scene. A thin outline marks the rendered image's
bounds, including transparent padding. The view selector explains how to create
views by adding frames or marker frames and replacing their default names.
**Anchor at original size (100%)** follows
the rendered source dimensions and disables manual resizing. **Apply** commits;
Cancel or Escape discards the draft.
When the source drawing appears in several images in the same scene, Apply asks
whether to update **All images** or **Only this image**. Only edited settings are
applied, preserving each copy's other view, padding and anchor choices. Each
image retains its center; unanchored images retain their area when the aspect
ratio changes. Anchored images follow their new intrinsic dimensions.
Configuration is saved in each image's embedded-file link, including `|100%`.
Independent references are created internally; the source drawing is never
duplicated or modified. One Undo restores the previous references and geometry.
## Frames and drawing thumbnails
Select a named frame or marker frame and use **Set as drawing thumbnail** in its
context menu. The document property `excalidraw-thumbnail` stores its exact name
and can also be edited manually. Names must be unique. Implicit previews in
notes, hover previews and other drawings crop to the frame rectangle, without
its outline or title. A missing, invalid or ambiguous name falls back to the
whole scene. PNG/SVG autoexports continue to export the full scene.
On save, `excalidraw-anchors` lists unique named frames and marker frames in
scene order. Unnamed frames are omitted; a frame deliberately named `Frame`
is included. New properties appear at the top of frontmatter and existing
properties retain their positions. Unrelated properties are preserved.
The first rename of a thumbnail frame asks whether to always update its document
property, ask on each rename or leave it unchanged. Change this preference later
in the saving settings. Deleting the frame leaves a stale name and the preview
falls back to the whole scene.
For editable Live Preview embeds whose drawing has frames, the **scan-eye**
button opens a frame picker. **Default thumbnail** removes the explicit override;
**Whole scene** writes `#^frame=` and ignores the thumbnail property. Other items
choose a frame by ID, including unnamed frames and names ending in `,padding=N`.
Existing explicit `frame=` and `clippedframe=` rendering remains unchanged.
Use **Excalidraw: Navigate to frame** to fuzzy-search regular and marker frames
in the current drawing. It uses the existing viewport navigation and selection
behavior, preserving editing mode and Search text.
## Focused validation
Source checks cover detached Reading sections, relative paths, source ownership,
history, padding previews, cancellation, and cleanup. Run the affected
`scripts/testing/*embed*.test.mjs` files with Node's test runner, plus
`scripts/testing/markdownEmbeds.test.mjs`, then build and run CSS policy lint.
`node scripts/testing/host/verify.mjs --embed-regressions` builds and deploys the
current workspace artifacts into the marker-owned test vault. It checks six
cases in the main window and a popout: relative and vault-path links in Live
Preview; detached long-note Reading rendering in all three image formats;
and padding preview, exact-occurrence editing, undo, cancellation, and unchanged
drawing bytes. These cases also belong to complete native profiles.
The prepared test vault must be open, trusted, and CLI-enabled. See
[native testing](OBSIDIAN_RUNTIME_TESTING.md). A prepared build with an unmet
host prerequisite is not a native test pass. Physical touch devices and other
desktop operating systems remain separate manual environments.
For frame metadata, thumbnails, navigation and source controls, run
`node scripts/testing/host/verify.mjs --frame-semantics`. Add
`--devices --device-profiles=phone-portrait-light,tablet-portrait-full-light`
for focused phone/tablet emulation. Complete profiles include these cases too.
Before the UI refinement below, the 2026-11-11 Windows run on Obsidian 1.14.5 passed thirteen desktop frame
cases (main window, popout and actual plugin reload), twelve frame cases in
phone/tablet emulation, both device profiles, and the six existing embed regressions.
It exercises the selected-image popover, both shared-source choices, native
Undo/Redo, intrinsic-size anchoring, cancellation and save/reopen. Saved links
retain their configuration while following the writer's existing path-shortening
rules. SVG, SVG-image and PNG checks verify padded thumbnail dimensions and
ensure padding never reveals neighboring elements outside the thumbnail frame.
The aggregate report records **37 passed, zero failed or blocked**, with artifact
hashes, source stability and baseline restoration verified. Reports are under
`.test-work/reports/preview-config-2026-11-11-03/`; earlier failed receipts remain
intact. Desktop console/window errors are zero and all cleanup gates passed.
Focused source checks passed 111/111, existing image-geometry/parsing checks
32/32, and bundle/runner/host-contract checks 19/19. Targeted lint added no
findings (24 existing findings remain in adjacent legacy code); CSS policy lint,
inventory and feature mappings passed. The production bundle is 5,128,954 bytes,
leaving 113,926 bytes under 5 MiB. Physical touch devices, other operating systems
and the minimum supported host version remain manual checks. Complete regression
profiles were not run.
The subsequent UI refinement uses one-unit steps in both padding sliders, puts
the compact controls above their description without a visible heading, explains
named frames in the view selector, and outlines the preview image's actual bounds.
Its focused source checks passed 111/111 and bundle checks 5/5; targeted ESLint
and CSS policy lint are clean. The six native embed cases, extended with these
UI assertions in the main window and popout, passed with four host gates (10/10)
and successful source stability, baseline restoration and cleanup. Receipt:
`.test-work/reports/preview-ui-2026-11-11-01/`. This build is 5,129,362 bytes,
leaving 113,518 bytes under 5 MiB. Mobile emulation was not repeated for this
refinement; physical touch remains a separate check.
The range/readout refinement passed 115 focused source checks, five bundle
checks, and the same six native cases plus four host gates (10/10) on Windows
Obsidian 1.14.5. Native mouse dragging verifies a fixed 5,100-unit area limit
from a distant scene element, one visible value below each track, unchanged
track widths, the 100-unit outer-padding cap, and retention of a saved 750-unit
override until edited. Switching an in-scene image between area and whole-scene
views restores the appropriate range. Plain, compressed and legacy geometry
readers, deleted elements and off-center crops have source coverage.
Targeted lint adds zero findings; CSS policy lint, source stability, artifact
hashes, baseline restoration and cleanup pass, with zero unexpected console or
window errors. Receipt: `.test-work/reports/preview-ranges-2026-11-11-01/`.
The bundle is 5,130,731 bytes, leaving 112,149 bytes under 5 MiB. Mobile layouts
and physical touch were not repeated for this refinement.
## Investigation checkpoint: 2026-11-10
Baseline: plugin `master@2ef81a5d`; implementation branch
`2026-11-10-embed-rendering-padding`. No component or Extras source changes.
- **#3039:** synchronous `is-loaded` claiming prevents native fallback, while
connection checks can abandon an off-document section before queueing or
during export. Claiming was added in `f31dff9e`; the detachment checks are
older. Neither originated in #3037. Reading embeds now use the existing
Markdown render-context owner, including generation checks and disposal.
- **#3040:** `src` belongs to the containing note, but Live Preview runs the
drawing's postprocessor with the drawing's own `sourcePath`. Re-resolving a
relative link from that folder can fail or choose the wrong target. The
re-resolution came from `5e2bb771` (#2979). For a matching relative drawing
link, rendering now retains Obsidian's already-resolved drawing identity.
Unrelated native images and text transclusions keep their original routing.
Both new regression cases failed before the changes and passed afterward.
The final focused run passed **94/94** cases: 89 source checks and five built
bundle checks. Targeted ESLint, CSS policy lint, inventory, feature mappings,
and `git diff --check` passed. The production build adds no TypeScript
diagnostics; its existing 18 circular-dependency warnings remain. `main.js`
is 5,101,162 bytes, leaving 141,718 bytes below the 5 MiB target.
The first native preparation stopped because the test vault was not open. After
the maintainer opened it, a fresh Windows run on Obsidian **1.14.5** passed all
**six targeted cases**, with zero unexpected console/window errors and matching
built, installed and reported artifact hashes. This establishes focused Windows
evidence; the reports' Obsidian 1.15 environment remains a separate check.
The original native report retains its failed cleanup status: baseline restoration
found an inactive synthetic drawing from **2026-11-07**, unrelated to the current
run. It had no open view, controller or print task. Recovery backed up that exact
file, verified its unchanged bytes and timestamp, deleted it through the Vault
API, and reran the baseline-restoration gate successfully. Immutable fixtures
needed no repairs; plugin and Extras settings were verified on disk and in memory.
The failed report and separate successful `cleanup-recovery.json` receipt remain
under `.test-work/reports/embed-regressions-2026-11-10-verified/`. Full regression
profiles were not run.
The subsequent UI refinement replaces the padding trigger with `square-dot` and
the vertical popup with an Obsidian `SliderComponent` in one compact horizontal
row beneath the toolbar. It retains the value readout and an icon-only default
reset. Placement flips above the toolbar when needed to stay in the viewport.
All 15 focused padding/controller checks, the production build, targeted ESLint,
CSS policy lint and registry checks passed. This visual refinement was not rerun
in the native lane; the six native results above apply to the preceding UI.
The rebuilt `main.js` is 5,101,447 bytes, below the 5 MiB target.
+213
View File
@@ -0,0 +1,213 @@
# Drawing controls, creation actions and companion reliability
Validation record for [plugin PR #3052](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/3052)
and [fork PR #484](https://github.com/zsviczian/excalidraw/pull/484).
[Sanitized case results, source identities and artifact hashes](testing-evidence/3052/results.json)
are committed with this record; full local reports remain ignored.
## Tested checkpoints
| Component | Revision and scope |
| --- | --- |
| Plugin baseline | `78674a39ccf046b93b5de4155edcc871d82602cf` |
| Complete portable/native checkpoint | `fdca179677bcabccb83e883e89026723345be67b` |
| Final keyboard follow-up | `78782221011caa2e8eb0e5f9655f426d4bb60c01`; only production difference from the complete checkpoint is the pen-repeat guard |
| Fork | `8260fa444f84c616d1486c2a47365c1b72c4be9a`, based on `29b11ad978d0a793f6502dcdc259f3481054c368` |
| Extras | Clean `4bd7af3325a8059a5ca68fc3e88169507b08c773`; manifest 0.2.1, API package 0.1.1, Mermaid service 3.6.0 |
| K-Plex in the complete native run | Clean `69eb4642dbf7bb995bff6d1b2e8409fd6e2c5046` |
Native host: Windows, Obsidian **1.15.1**, installer **1.14.5**,
Electron **43.8.3**, Chromium **150.0.7871.250**. Build tooling uses Node 22.22.3.
Only the marker-owned `.test-work/vaults/excalidraw-auto-test/` was used.
Every sequence rebuilt, froze, installed and hash-verified its selected sources
under the shared application-user-data lock, then restored its declared baseline.
## Issue outcomes
Maintainer follow-up, 2026-11-15: the empty-tab action is now **New Drawing**
and enabled by default, overriding the original issue's opt-in proposal. Explicit
persisted opt-outs remain respected; no migration overwrites existing choices.
The creation regression now loads the actual production defaults and checks
default visibility, independent opt-outs, host rerenders and cleanup. The native
and portable counts below remain evidence for their explicitly named earlier
checkpoints, which preceded this default/copy change.
This follow-up's production build and all 789 fast cases pass, including the five
bundle checks and maintained-locale inflation. The strengthened real-defaults
creation regression fails before the default change and passes afterward. This
localized default/copy change does not alter the creation pipeline or controller;
the earlier complete native run is not represented as a new native validation.
The new production bundle is 5,145,119 bytes (97,761 bytes below 5 MiB).
The maintainer also requested a mandatory consent control for compatibility work
with another plugin. It is canonical in `CODING_STANDARDS.md` and prominently
linked from `AGENTS.md` and `CONTRIBUTING.md`. On 2026-11-15 the maintainer
explicitly approved retaining the generic #3051 Extras guards and their regression
coverage. No Lazy Loader-specific production workaround was introduced or approved.
| Issue | Implementation and observable evidence |
| --- | --- |
| [#3049](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3049) | Prefer the physical table/cell boundary even when native images have an `internal-embed` wrapper. Preserve file, renderer-generation, document and stale-source guards. Reset `right` for in-flow phone/coarse-pointer controls. Source regressions fail before the fix. Native main/split/popout and phone/tablet cases pass for PNG and both SVG formats, repeated cells, alignment, exact source, history, fullscreen and Reading controls. |
| [#3047](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3047) | Independent ribbon visibility and **New Drawing** action, both on by default after the maintainer's 2026-11-15 follow-up, using the existing folder/format/template pipeline. Both settings layouts and maintained locales are covered. Earlier native main/popout creation passes; nondefault preferences and an unknown-key sentinel survive actual plugin reload and on-disk persistence. Core empty-tab actions remain present. |
| [#3044](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3044) | Plugin-only unmodified P toggle through the existing editor API. Exclude inputs, embeds, modifiers, composition, active drawing, view mode and retired views. Review found that repeats after selection commits could reenter pen; the strengthened state-mutating source test fails before the final guard and passes afterward. Actual repeated-key input passes in main/popout: second P selects mouse, holding it preserves selection, fresh P selects pen, input text and V still work. |
| [#3048](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3048) | Two fingerprinted fork conditions route normalized YouTube videos/playlists through the existing iframe instead of a guest webview. Four real-editor provider cases pass after two baseline failures. Both actual browser artifacts pass nested cross-origin offline-player fullscreen at zoom 0.5 and 2. Native main/popout tests pass iframe routing, viewport-sized HTML fullscreen and trusted player-button exit. Actual YouTube playback and physical Escape remain unverified. |
| [#3051](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3051) | Guard absent/incomplete Extras APIs, check versions before feature access and reject missing/non-string component versions through the normal unavailable/update path. Preserve the exact Mermaid 3.6 handshake. Native missing/incomplete API cancellation, continued drawing access, recovery and late plugin enablement pass. The original startup failure is not reproduced or claimed fixed. |
The [reporter's follow-up](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/3051#issuecomment-6875289427)
says a two-plugin vault works and immediate loading avoids the approximately
60-plugin vault's failure with Lazy Loader's 20-second delay. Its quoted
NotebookLM explanations are not established facts: the main plugin owns the
waiting view/layout-ready path and already converts fallback Markdown leaves.
Controlled enablement after layout readiness works without a usable Extras API.
Current Extras also already includes MathJax startup isolation (`6c55a9d`).
No unrelated startup refactor or automatic closure of #3051 is justified.
## Maintainer-approved PNG correction
### Android fullscreen follow-up, 2026-11-15
The maintainer reports a long "Loading preview" wait on physical Android when
Markdown preview type is PNG, while Native SVG opens quickly. Git history traces
the fullscreen `fwidth: "1600"` / fresh-payload path to commit `14115712` in
PR #3037; PR #3052 retained it. That path bypasses the cache and requests scale 3,
so it can rasterize nine times the base pixel area on every opening. This is a
confirmed unnecessary-work path, not a measured attribution of every Android delay.
Owned PNG images now retain a weakly keyed reference to their existing encoded
blob. Fullscreen reuses those pixels through a new independently owned URL in the
source document without waiting for another scene export or cache availability.
At the maintainer's request, a fresh 3x PNG export then runs in the background.
The viewer waits for its decode before replacing only the image, preserving the
existing fit, zoom, pan and pointer gesture. Closing aborts deferred startup,
embedded-file loading and subsequent raster/DOM work. An already running browser
encoder cannot be preempted; its late result is discarded without an object URL
or image insertion. SVG/Native SVG and unowned-payload fallback paths remain unchanged.
The new routing regression fails before the fix because fullscreen starts a second
raster export. Pixel-copy coverage includes cached/uncached images, close/reopen,
source retirement, document ownership and plugin teardown. All 41 focused
Markdown/PNG cases, all 791 fast cases, 251 measured source cases and the
production build pass for the first-stage checkpoint `7aedebfa`. The progressive
follow-up adds executable swap/decode/failure/cancellation cases and native
read-gated assertions for immediate display, 3x replacement, preserved zoom/pan
and closing a pending export. Native embed validation and
physical Android confirmation are recorded separately; earlier full-profile
counts are not acceptance evidence for this follow-up.
Progressive follow-up source validation passes 54 focused cases, 796 fast cases,
the production build and all five bundle checks. `main.js` is 5,147,272 bytes
(95,608 bytes below the release target). Focused lint is clean for the viewer,
postprocessor, PNG ownership helper and preview types. The export utility reports
two pre-existing unsafe-`any` findings at its unchanged text-conversion code;
no new lint finding is introduced by the cancellation checks. Before/after
regression output is retained under `.test-work/reports/pr3052-progressive-*`.
Final production checkpoint `b5f97cea` passes **55 focused source tests, 797 fast
tests and 30/30 fresh focused native cases**, with strict error/idle gates,
cleanup and baseline restoration passing. Main, split, popout and emulated phone
exercise PNG, SVG image and Native SVG; desktop coverage includes tray mode.
PNG opens with the exact 248x180 / 6,316-byte displayed payload and an independent
URL, then replaces it with the decoded 744x542 export without changing zoom/pan.
Closing a pending upgrade prevents late insertion. Actual dimensions include
normal export rounding. Physical Android performance remains unverified.
Native popout validation exposed a production bug: adopting an image changes its
document but retains its original JavaScript prototype. The destination-window
`instanceof` check therefore missed the owned PNG and used the blocking fallback.
The PNG ownership record now narrows these images for cloning, upgrade/decode and
root-image disposal. General window type guards and SVG behavior are unchanged.
The new adopted-image source regression fails before this correction and passes
afterward. Earlier test-gate/measurement failures, the constrained desktop run and
the actual popout failure remain recorded in the
[sanitized follow-up results](testing-evidence/3052/png-progressive.json).
The final bundle is **5,147,278 bytes**, leaving **95,602 bytes** below the release
target. [Hosted Plugin tests](https://github.com/zsviczian/obsidian-excalidraw-plugin/actions/runs/43708519373)
and [CodeQL](https://github.com/zsviczian/obsidian-excalidraw-plugin/actions/runs/43708519308)
pass for `b5f97cea`. The tested build was deployed to Zsolt's Brain with a backup,
verified plugin reload, identical settings bytes and unchanged enabled-plugin
configuration. No package version, dependency, lockfile or fork source changed.
Native validation independently exposed concurrent cold renders revoking an
earlier image's URL, and warm-cache siblings sharing a revocable URL. The
postprocessor now reads cached raster blobs and gives every image its own URL.
The cache stores the blob without owning that renderer's URL. Cache schemas,
drawing backups and fork source are unchanged.
Images and wrappers enter the destination document before loading. A live image's
URL is created in the stable main plugin realm and stays readable until
replacement, discard, decode failure or plugin unload. This supports frame pixel
consumers and actual Markdown main-to-popout-to-main migration. Plugin teardown
releases remaining sources; weak references provide a fallback for legacy DOM
consumers that omit retirement callbacks.
Source cases cover cold concurrency, warm siblings, pixel reads, uncached
payloads, errors, cache shutdown and stale plugin disposers. The PNG helper has
100% measured line/function and 89.47% branch coverage at the complete checkpoint.
Its source is unchanged by the final keyboard follow-up.
## Validation results and acceptance scope
| Lane | Result |
| --- | --- |
| Complete portable at `fdca1796` | **1,023 canonical cases pass**, plus source/package gates: 789 plugin fast, 161 fork owned, 24 fork built-browser, 30 Extras source and 19 Extras browser cases |
| Measured plugin source at that checkpoint | **250 cases in 39 files pass**; coverage gate passes |
| Complete native at `fdca1796` | **468/468 required cases pass**, including **160 device cases**, 40 device/layout profiles and all 258 behavioral obligations |
| Native diagnostics and restoration | Both negative controls pass; strict idle, unexpected-error, source-stability, cleanup and baseline-restoration gates pass. One isolated ResizeObserver notification, no storm. Deliberately injected write-failure logs remain recorded separately from unexpected errors. |
| Final localized follow-up at `78782221` | Strengthened source test red before / green after; all **789 fast cases pass**. Fresh focused native build passes all nine issue identities, **13 total checks**, including actual held-P input in both windows. Errors, cleanup and baseline restoration pass. |
| Hosted final source checks | [Plugin tests](https://github.com/zsviczian/obsidian-excalidraw-plugin/actions/runs/43649533527) and [CodeQL](https://github.com/zsviczian/obsidian-excalidraw-plugin/actions/runs/43649533590) both pass at `78782221`. |
| Builds and packaging | Complete checkpoint production/development/library and package-consumer gates pass. Final keyboard production/native rebuild passes. Production artifact: **5,145,115 bytes**, **97,765 bytes** below 5 MiB. Its SHA-256 is in the evidence file. |
| Lint and inventory | Modified postprocessor/PNG helper and final pen helper have zero focused ESLint errors/warnings. CSS policy, feature mappings and public/test inventory pass. Full-plugin lint retains the previously recorded **116-error backlog**; no global clean-lint claim. |
| Fork checks | Full/owned types, both Obsidian modes and declarations pass. Owned coverage floors pass; final local run measures 48.03% lines, 64.03% branches, 44.86% functions. Fifteen audit tests and the 276-path ledger comparison against upstream `82d5847e57dcb6fb5982833ea9ec2137fe0b2bd5` pass. |
The complete native run is deliberately identified separately from the final
localized keyboard follow-up. A complete native profile was not repeated after
that guard-only change. The final fast working-tree diff was verified byte-for-byte
against the subsequently committed `78782221`; its fresh native artifacts use the
clean commit. Fork and Extras artifact hashes match the complete checkpoint.
## Retained failures and limits
- Earlier native runs exposed PNG cache, document-migration and premature
URL-release failures; the existing frame pixel assertions were retained.
A complete run also recorded a sustained ResizeObserver storm. No observer
production fix, error suppression or gate waiver is claimed. The final complete
run passed with native observer methods and one isolated notification.
- One portable attempt stopped before browser execution because the local
Playwright cache path was unset. Pointing it to the existing pinned Chromium
cache produced the complete 1,023-case pass; no source change was needed.
- Required raw inherited `yarn test:update` remains red and discovers ignored
historical copies. Its current-tree subset has 1,331 passed / 1,513 failed
assertions plus one todo across 175 files (82 failing). This is not a clean
compatibility result or parent comparison. All 16 generated primary-tree
snapshot/inline-snapshot edits were preserved as a patch and restored.
- Physical Windows Escape could not be checked: desktop automation failed twice
to activate the visible/focused test window, sent no physical input and cleaned
its owned fixture. CDP Escape does not invoke Chromium's reserved browser
shortcut, so it was not substituted as a passing physical test.
Priority manual checks before release: physical phone/tablet touch on Reading and
table controls; actual stylus-button P/hold/release; real YouTube
playback/fullscreen/Escape in main and popout; minimum supported Obsidian and
other desktop OSes; isolated whole-app cold startup. Desktop mobile emulation
does not establish physical Android/iOS behavior. The exact #3051 third-party
startup combination remains unconfirmed.
Local reports include `pr3052-portable-live-source-ready/`,
`pr3052-native-full-live-source/`, `pr3052-pen-repeat-fast/` and
`pr3052-native-pen-repeat-final/` under `.test-work/reports/`.
Use `npm.cmd run test:regression:portable` with the pinned Playwright Chromium
cache, `npm.cmd run test:native` for a complete native profile, and
`npm.cmd run verify:obsidian:plugin -- --issue-3052` for the focused issue lane.
Run the complete portable and native commands separately: the combined wrapper's
30-minute child timeout is shorter than this native profile's approximately
44-minute execution.
## Package handoff
CI pins the tested fork/Extras implementations. Four generated local fork files
were copied into the ignored installed package and hash-verified for integration.
No package version, dependency or lockfile was changed. Publication and the exact
published dependency handoff remain a later maintainer step. This PR includes no
personal-vault deployment or merge. Keep both PRs draft for the remaining manual
and release-coordination checks.
+16 -4
View File
@@ -125,10 +125,10 @@ full-profile result.
use the normal coordinator to deploy/hash-verify them, enable services and
check the actual live API versions against the plugin gateway. Do not fake a
version or relax a version handshake to accept mismatched components.
The converter package version and Extras service-contract version are distinct:
current Extras bundles converter 3.1.0 while advertising service contract 3.0.0.
Verify each at its own boundary rather than changing the handshake to match a
package version.
The converter package version and Extras service-contract version are distinct.
The coordinated 3.6 upgrade bundles converter 3.6.0 and advertises service
contract 3.6.0. Verify both boundaries and keep the producer advertisement and
consumer requirement paired.
2. For `Concurrent host requests`, inspect the outstanding request ID, method,
target renderer, acknowledgement and original error. Distinguish UI-readiness
waits from transport completion. Settle or explicitly cancel the exact owned
@@ -150,6 +150,10 @@ full-profile result.
deadline waiting for a lost acknowledgement. A timed-out error-buffer clear
may be accepted only after reading an empty buffer; never clear again and erase
newly captured errors. Known read-only CLI commands use bounded read retries.
This includes only the exact exported `nativeReadyCode` reload probe: its
renderer may disappear during mobile-mode reload, so it must not depend on
that renderer retaining an operation receipt. Other evals and lookalikes
retain strict receipt ownership and are never replayed as readiness reads.
A screenshot reply may be recovered only from its uniquely owned, previously
absent artifact after the native image decoder confirms a complete image.
Never capture again to obtain a replacement acknowledgement, and never treat
@@ -417,6 +421,14 @@ npm run test:markdown-embeds
npm run verify:obsidian:plugin -- --embed-recovery
```
For #3039, #3040 and interactive area padding, run
`node scripts/testing/host/verify.mjs --embed-regressions`. Its six main/popout
cases cover relative Live Preview links, long detached Reading sections in PNG,
SVG image and native SVG formats, plus padding preview, exact source edits,
undo, cancellation and unchanged drawing bytes. See
[drawing embed controls](DRAWING_EMBED_CONTROLS.md). The cases are also included
in complete native profiles; this focused command does not run those profiles.
Use `npm.cmd` in PowerShell. `--embed-recovery` also works with `verify:obsidian`
and can be combined with `--text-undo` or `--grouped-link-click`. The offline tests exercise the real
postprocessor with deferred image generation, including failed renders, temporary
+19
View File
@@ -1,5 +1,20 @@
# Maintaining the test lanes
## Coordinated Mermaid 3.6 requirement — 2026-11-05
The plugin requires Extras Mermaid service exactly **3.6.0**. Extras must build
the matching converter 3.6/Pele 1.13 implementation, including legacy caller
curve compatibility. The handshake rejects older services and unmatched patch
versions. The component's npm dependency stays at 0.18.146 for the explicitly
requested intermediate handoff; local integration uses the merged fork source.
The portable/native workflow source pins select that same fork/Extras pair.
Run the normal portable and native profiles before readiness. A requested
personal-vault deployment backs up installed binaries and settings, saves open
drawings before reload, verifies artifact hashes and preserves settings and
enabled-plugin configuration. It does not run the synthetic native test suite
inside the personal vault.
Optional K-Plex ontology completion has a combined fresh-build native lane:
`npm run test:kplex-ontology`. Its source, API contract, fixture ownership and
release coordination are documented in [K-Plex ontology completion](KPLEX_ONTOLOGY_COMPLETION.md).
@@ -417,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.
@@ -0,0 +1,599 @@
{
"schemaVersion": 1,
"checkpoint": "b5f97ceaf44fff67c4ff44888059593a1ce9ffd3",
"source": {
"pluginRevision": "b5f97ceaf44fff67c4ff44888059593a1ce9ffd3",
"pluginDirty": false,
"forkRevision": "ddd461189de7810f319832430467207c34f257ad",
"forkDirty": false,
"buildMode": "workspace-frozen",
"requestedProfile": "focused",
"node": "v22.22.3",
"platform": "win32"
},
"producers": {
"fork": {
"commit": "ddd461189de7810f319832430467207c34f257ad",
"dirty": false,
"diffHash": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
"lockfileHash": "5ff2005c676da0a7250e859ce363fc40c832a64104732e21d40e827b02632d18"
},
"extras": {
"commit": "4bd7af3325a8059a5ca68fc3e88169507b08c773",
"dirty": false,
"diffHash": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
"lockfileHash": "e6419e0a6e01e7292c905ccd51efc54223eff4f80e8d1d9229ce94194eb282f9"
},
"plugin": {
"commit": "b5f97ceaf44fff67c4ff44888059593a1ce9ffd3",
"dirty": false,
"diffHash": "4f53cda18c2baa0c0354bb5f9a3ecbe5ed12ab4d8e11ba873c2f11161202b945",
"lockfileHash": "741c0318ef12f5b1661e3d86b9044949aab9f2132db6d23d2b119a3b4740d2b1"
}
},
"artifactHashes": {
"main.js": "9d28c331bf96ddd1449336ca36d7799367cf7a00767495a456db596f761ecb03",
"manifest.json": "8e82828fd9125615e8a361d0f15553e548cac2ee7a303e55387378a53b925fd9",
"styles.css": "c66306b0fd8f29348b58e50339b2ae614c82524c043c3241dc39e12ee287665e"
},
"mainBytes": 5147278,
"sourceChecks": {
"focused": 55,
"fast": 797,
"build": "passed",
"focusedLint": "passed",
"existingExportUtilityFindings": 2
},
"native": {
"scope": "Focused embed/recovery with one emulated phone layout; physical Android not tested",
"status": "passed",
"cleanup": "passed",
"cases": [
{
"testId": "plugin-load",
"status": "passed",
"assertions": [
"commands registered",
"drawing/font/export runtime available",
"host protocol 4"
]
},
{
"testId": "drawing-main-window",
"status": "passed",
"assertions": [
"Excalidraw API ready",
"wrapper mounted",
"owner document matches",
"main application document"
]
},
{
"testId": "markdown-embed-recovery-2953",
"status": "passed",
"assertions": [
"SVGIMG: native Markdown PDF preparation completes with three frames and a native PNG, without recursive drawing transclusion",
"PNG: native Markdown PDF preparation completes with three frames and a native PNG, without recursive drawing transclusion",
"SVG: native Markdown PDF preparation completes with three frames and a native PNG, without recursive drawing transclusion",
"SVGIMG: detached Live Preview context completes and reattaches",
"SVGIMG: width attribute refresh preserves all three embeds",
"SVGIMG: Reading mode after Live Preview",
"SVGIMG: warm Live Preview reopen",
"PNG: detached Live Preview context completes and reattaches",
"PNG: width attribute refresh preserves all three embeds",
"PNG: Reading mode after Live Preview",
"PNG: warm Live Preview reopen",
"SVG: detached Live Preview context completes and reattaches",
"SVG: width attribute refresh preserves all three embeds",
"SVG: Reading mode after Live Preview",
"SVG: warm Live Preview reopen",
"permanent context unload rejects insertion into the retired embed containers",
"popout: detached context, reattachment and width refresh in the owning document",
"SVGIMG: popout Markdown PDF preparation preserves drawing frames and the native PNG",
"PNG: popout Markdown PDF preparation preserves drawing frames and the native PNG",
"SVG: popout Markdown PDF preparation preserves drawing frames and the native PNG",
"hybrid source, nested=false: self-image, drawing and native PNG visible in popout",
"hybrid source, nested=true: self-image, drawing and native PNG visible in popout",
"hybrid preview, nested=false: self-image, drawing and native PNG visible in popout",
"hybrid preview, nested=true: self-image, drawing and native PNG visible in popout"
]
},
{
"testId": "native:embed-controls:main:PNG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"fullscreen PNG initially keeps exact encoded pixels and dimensions with an independent URL",
"decoded 3x upgrade preserves zoom and pan",
"close cancels pending upgrade without late image insertion",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
],
"pngReuse": {
"inlineWidth": 248,
"inlineHeight": 180,
"encodedBytes": 6316,
"independentURL": true,
"elapsedMs": 999.6999999880791,
"detailWidth": 744,
"detailHeight": 542,
"zoomPanPreserved": true,
"cancelledPendingUpgrade": true
}
},
{
"testId": "native:embed-controls:main:SVGIMG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
]
},
{
"testId": "native:embed-controls:main:SVG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
]
},
{
"testId": "native:embed-ownership:main",
"status": "passed",
"assertions": [
"same-line repeated embeds target only their own token",
"inline/fenced examples have no controls",
"independent note and pane stay unchanged",
"one-step undo",
"refresh remounts controls exactly once",
"switching source unloads controls and fullscreen",
"drawing bytes unchanged"
]
},
{
"testId": "native:embed-table:main",
"status": "passed",
"assertions": [
"native table widget public boundaries and physical cell ownership",
"escaped wiki and Markdown-image dimensions render",
"only second identical row changes",
"same-note split synchronization",
"left/right pointer previews retain measured size and aspect ratio",
"one-step undo/reset",
"exact Markdown syntax selection",
"aliases/styles/title and other cells preserved",
"drawing bytes unchanged"
]
},
{
"testId": "native:embed-hybrid:main",
"status": "passed",
"assertions": [
"drawing opened as Markdown owns self and other drawing embeds",
"short self-link identity",
"exact resize/reset and single undo",
"physical save preserves serialized drawing data",
"exact source selection",
"Live Preview and Reading fullscreen",
"Reading controls do not edit source",
"other drawing unchanged"
]
},
{
"testId": "native:embed-controls:split:PNG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"fullscreen PNG initially keeps exact encoded pixels and dimensions with an independent URL",
"decoded 3x upgrade preserves zoom and pan",
"close cancels pending upgrade without late image insertion",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
],
"pngReuse": {
"inlineWidth": 248,
"inlineHeight": 180,
"encodedBytes": 6316,
"independentURL": true,
"elapsedMs": 1042.8999999761581,
"detailWidth": 744,
"detailHeight": 542,
"zoomPanPreserved": true,
"cancelledPendingUpgrade": true
}
},
{
"testId": "native:embed-controls:split:SVGIMG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
]
},
{
"testId": "native:embed-controls:split:SVG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
]
},
{
"testId": "native:embed-ownership:split",
"status": "passed",
"assertions": [
"same-line repeated embeds target only their own token",
"inline/fenced examples have no controls",
"independent note and pane stay unchanged",
"one-step undo",
"refresh remounts controls exactly once",
"switching source unloads controls and fullscreen",
"drawing bytes unchanged"
]
},
{
"testId": "native:embed-table:split",
"status": "passed",
"assertions": [
"native table widget public boundaries and physical cell ownership",
"escaped wiki and Markdown-image dimensions render",
"only second identical row changes",
"same-note split synchronization",
"left/right pointer previews retain measured size and aspect ratio",
"one-step undo/reset",
"exact Markdown syntax selection",
"aliases/styles/title and other cells preserved",
"drawing bytes unchanged"
]
},
{
"testId": "native:embed-hybrid:split",
"status": "passed",
"assertions": [
"drawing opened as Markdown owns self and other drawing embeds",
"short self-link identity",
"exact resize/reset and single undo",
"physical save preserves serialized drawing data",
"exact source selection",
"Live Preview and Reading fullscreen",
"Reading controls do not edit source",
"other drawing unchanged"
]
},
{
"testId": "native:embed-controls:popout:PNG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"fullscreen PNG initially keeps exact encoded pixels and dimensions with an independent URL",
"decoded 3x upgrade preserves zoom and pan",
"close cancels pending upgrade without late image insertion",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
],
"pngReuse": {
"inlineWidth": 248,
"inlineHeight": 180,
"encodedBytes": 6316,
"independentURL": true,
"elapsedMs": 1179.800000011921,
"detailWidth": 744,
"detailHeight": 542,
"zoomPanPreserved": true,
"cancelledPendingUpgrade": true
}
},
{
"testId": "native:embed-controls:popout:SVGIMG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
]
},
{
"testId": "native:embed-controls:popout:SVG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
]
},
{
"testId": "native:embed-ownership:popout",
"status": "passed",
"assertions": [
"same-line repeated embeds target only their own token",
"inline/fenced examples have no controls",
"independent note and pane stay unchanged",
"one-step undo",
"refresh remounts controls exactly once",
"switching source unloads controls and fullscreen",
"drawing bytes unchanged"
]
},
{
"testId": "native:embed-table:popout",
"status": "passed",
"assertions": [
"native table widget public boundaries and physical cell ownership",
"escaped wiki and Markdown-image dimensions render",
"only second identical row changes",
"same-note split synchronization",
"left/right pointer previews retain measured size and aspect ratio",
"one-step undo/reset",
"exact Markdown syntax selection",
"aliases/styles/title and other cells preserved",
"drawing bytes unchanged"
]
},
{
"testId": "native:embed-hybrid:popout",
"status": "passed",
"assertions": [
"drawing opened as Markdown owns self and other drawing embeds",
"short self-link identity",
"exact resize/reset and single undo",
"physical save preserves serialized drawing data",
"exact source selection",
"Live Preview and Reading fullscreen",
"Reading controls do not edit source",
"other drawing unchanged"
]
},
{
"testId": "javascript-errors",
"status": "passed"
},
{
"testId": "source-stability",
"status": "passed"
},
{
"testId": "native:embed-controls:phone:PNG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"fullscreen PNG initially keeps exact encoded pixels and dimensions with an independent URL",
"decoded 3x upgrade preserves zoom and pan",
"close cancels pending upgrade without late image insertion",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
],
"pngReuse": {
"inlineWidth": 248,
"inlineHeight": 180,
"encodedBytes": 6316,
"independentURL": true,
"elapsedMs": 851.7999999523163,
"detailWidth": 744,
"detailHeight": 542,
"zoomPanPreserved": true,
"cancelledPendingUpgrade": true
}
},
{
"testId": "native:embed-controls:phone:SVGIMG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
]
},
{
"testId": "native:embed-controls:phone:SVG",
"status": "passed",
"assertions": [
"trusted proportional resize previews without source writes",
"only second identical token changed",
"one-step undo/redo and reset",
"Escape cancellation",
"exact Markdown-image syntax selection and roundtrip",
"independently owned fullscreen zoom/pan/fit/Escape/focus",
"inline payload survives modal cleanup",
"Reading controls cannot write",
"ordinary image unchanged",
"Open drawing and drawing bytes unchanged"
]
},
{
"testId": "native:embed-ownership:phone",
"status": "passed",
"assertions": [
"same-line repeated embeds target only their own token",
"inline/fenced examples have no controls",
"independent note and pane stay unchanged",
"one-step undo",
"refresh remounts controls exactly once",
"switching source unloads controls and fullscreen",
"drawing bytes unchanged"
]
},
{
"testId": "native:embed-table:phone",
"status": "passed",
"assertions": [
"native table widget public boundaries and physical cell ownership",
"escaped wiki and Markdown-image dimensions render",
"only second identical row changes",
"same-note split synchronization",
"left/right pointer previews retain measured size and aspect ratio",
"one-step undo/reset",
"exact Markdown syntax selection",
"aliases/styles/title and other cells preserved",
"drawing bytes unchanged"
]
},
{
"testId": "native:embed-hybrid:phone",
"status": "passed",
"assertions": [
"drawing opened as Markdown owns self and other drawing embeds",
"short self-link identity",
"exact resize/reset and single undo",
"physical save preserves serialized drawing data",
"exact source selection",
"Live Preview and Reading fullscreen",
"Reading controls do not edit source",
"other drawing unchanged"
]
},
{
"testId": "native:device:phone-portrait-light",
"status": "passed",
"assertions": [
"actual Obsidian mobile/desktop mode",
"measured editor classification",
"actual host and drawing theme",
"visible uncovered tool",
"trusted pointer selects and draws",
"device edit saves to disk",
"applicable Zen footer controls do not overlap and accept trusted input",
"code format options and remember toggle fit and accept trusted input",
"chosen code image preserves editable source and saves"
]
}
],
"baselineRestoration": {
"restored": true,
"pluginEnabled": true,
"extrasEnabled": true,
"kplexEnabled": false,
"theme": "moonstone",
"restoredFixturePaths": []
},
"deviceRestoration": {
"restored": true
},
"unexpectedConsoleErrors": 0
},
"hosted": [
{
"name": "Plugin tests",
"status": "success",
"url": "https://github.com/zsviczian/obsidian-excalidraw-plugin/actions/runs/43708519373"
},
{
"name": "CodeQL",
"status": "success",
"url": "https://github.com/zsviczian/obsidian-excalidraw-plugin/actions/runs/43708519308"
}
],
"priorRuns": [
{
"directory": "pr3052-native-png-fullscreen",
"finding": "Prepared test vault was closed; opened its existing registration and verified readiness."
},
{
"directory": "pr3052-native-progressive-png",
"finding": "Test read dimensions after image disposal; captured dimensions before replacement."
},
{
"directory": "pr3052-native-progressive-png-final",
"finding": "Existing fixed +40px resize check failed at a 629px desktop viewport; reran at 1536x960 and restored bounds. No production resize change or narrow-pane fix claimed."
},
{
"directory": "pr3052-native-progressive-png-wide",
"finding": "Blanket read gate prevented first-image preparation; narrowed it to a populated viewer. Subsequent diagnostics identified the adopted-image slow fallback."
},
{
"directory": "pr3052-native-progressive-png-verified",
"finding": "Initial popout PNG assertion failed; retained report and added stable snapshots/diagnostics."
},
{
"directory": "pr3052-native-progressive-png-acceptance",
"finding": "248x180 inline PNG stayed valid while first popout preview was already 744x542. Confirmed production owning-window instanceof check misses adopted images; fixed via PNG ownership record."
}
],
"deployment": {
"target": "Zsolts Brain",
"status": "passed",
"settingsBytesUnchanged": true,
"enabledConfigurationPreserved": true,
"pluginReloadVerified": true
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,290 @@
# Drawing embed controls (#3036 / PR #3037)
Implementation branch: `2026-11-06-issue-3036-embed-controls`, based on
`375b460c0b2baf01a65e818a8c9b485e92615ebd`.
## Behavior and ownership
Direct Live Preview drawing embeds get proportional corner resizing, reset,
selection of their exact embed syntax, fullscreen viewing and Open drawing.
Normal Reading mode gets fullscreen viewing and Open drawing only. Print/PDF,
hover previews, Canvas and nested Markdown contexts get no toolbar. A drawing
opened in its Markdown view supports direct self-embeds and other drawing embeds;
its generated metadata preview has no source-bound controls.
An ambiguous or retired source binding never writes.
The editor bridge uses public `editorInfoField`, `editorLivePreviewField` and
CodeMirror DOM/source boundaries. It checks the complete source token, owning
file/editor and canonical drawing/reference. It does not depend on native private
widget fields, the active note, a global occurrence index or whole-file replacement.
Bindings map through prefix edits and retire on edits inside their token. Native
table widgets use their public source boundary and the physical table cell;
rectangular shape, delimiter row, complete token and row/column identity must
agree before a write. Escaped table aliases also retain their displayed size.
Movement changes CSS only. A completed resize uses one isolated editor history
transaction. Unchanged or cancelled gestures preserve the original source bytes.
Changed percentage sizing becomes pixels. Explicit height or width/height sizing
becomes a pixel box preserving the displayed aspect ratio; width-only sizing
remains width-only. Reset removes just the dimension field. Paths, references,
titles, aliases, style suffixes, whitespace and escaped table separators remain
unchanged. Existing wrapper layout remains responsible for alignment and percentage
sizing. Controls follow the visible image bounds.
Cancellation restores control placement immediately; scrolling and viewport
changes and image decoding remeasure it through an owned ResizeObserver. Hover
toolbars sit inside the image because native widgets use paint containment.
Small images and always-visible touch toolbars use normal flow below the image.
A full-width no-op keeps percentage syntax
instead of shrinking solely to create space for the handle.
Fullscreen uses the existing exporter with the same drawing/reference and theme,
but bypasses the shared image cache. It owns and releases that fresh image. SVG
links are inactive in the viewer. Closing a source owner closes its viewers and
cancels gestures; late exports are discarded. Open drawing and the existing
double-click/long-press gestures share the same navigation helper, including mask
prompts and modifier/reference behavior.
Reading-mode controls have one plugin-owned registry in addition to their render
context lifetime. Context cleanup removes each owner from the registry, and
plugin unload closes any remaining controls/viewers. Hidden Live Preview controls
retire when switching to Reading mode. A Reading export completing
after plugin unload is discarded before touching the document.
No dependency, release version, fork or Extras change is required. The unmerged
area-padding PR #2868 is not a dependency.
## Native API spike
On Windows / Obsidian 1.14.5, the existing renderer left no working native image
edit/resize controls in the Markdown editor. Two identical wiki embeds and a
Markdown image embed had distinct public `posAtDOM` starts and parent boundaries.
The boundary included the exact token and a trailing newline. Private widget
fields were inspected for research only; production uses the public boundaries.
The spike ran three times with cleanup and baseline restoration.
Evidence: `.test-work/reports/pr3037-native-spike/widget-spike.json`.
## Automated checks
Whole production-module tests exercise lossless dimension rewriting, real
CodeMirror history/range mapping, controller gestures and cleanup, fullscreen
async ownership and shared navigation. Existing postprocessor/lifecycle tests
also cover cache bypass and toolbar exclusions. New source modules participate
in `test:source-coverage` and native cases are required by the regression profile
and P05 feature mapping.
Run the affected native desktop matrix with:
```sh
node scripts/testing/host/verify.mjs --embed-controls
```
The complete native profile also includes the phone/tablet workflows in actual
Obsidian mobile emulation with trusted CDP touch input. This is not physical-device
coverage. Native cases assert exact source, history and unchanged drawing bytes;
screenshots alone do not establish behavior.
The development native attempts are retained under
`.test-work/reports/pr3037-controls-focused*`. The first attempt stopped on a
malformed test PNG, which was corrected. The next attempts exposed incorrect
held-button input in the harness, then a production stale-generation remount
loop after resizing. The latter starved the renderer's replacement timer and CLI.
The bridge now rejects stale generations before mounting; a bounded production
bridge test reproduces and prevents the loop. A recovery build was hash-verified
in the owned test vault. The stalled run remains failed, including cleanup.
It is not acceptance evidence. The maintainer restarted Obsidian; acknowledged
CLI recovery removed only the failed run's owned fixtures and restored the
declared baseline. Recovery evidence is retained under
`.test-work/recovery/pr3037-stale-renderer/restarted-baseline.json`.
The focused desktop matrix passed on Windows / Obsidian 1.14.5 after recovery:
all 15 embed cases across main, split and popout contexts, with clean console,
source stability, cleanup and baseline restoration. It covers all three image
modes, repeated/same-line tokens, table cells, same-note split synchronization,
history, source selection, fullscreen keyboard controls/focus, Reading mode and
popout input with the main window minimized. Evidence:
`.test-work/reports/pr3037-controls-focused-10/report.json`.
Trusted touch initially exposed the host's `body.emulate-mobile .clickable-icon`
rule overriding the resize handle's touch action. A scoped selector now outranks
that rule. All ten phone/tablet embed cases, including resize/history/reset,
tables, fullscreen pinch and pan, passed against the fresh frozen build:
`.test-work/reports/pr3037-phone-probe-3/report.json`.
Toolbar compatibility mouse/touch events are isolated from the surrounding native
table, preserving button default activation. Editing table syntax intentionally
opens Obsidian's inner cell editor; the host retains its hidden display preview.
The native test exits through a trusted footer click instead of moving only the
outer editor's caret. It verifies that this roundtrip preserves every source byte.
Complete portable regression at `76ffd8ed4dbb347e0c1a7ef01d5778f9537a41d3`
passed 934 canonical cases, with successful cleanup and no missing cases. It
includes 717 plugin tests and 199 source-coverage tests. GitHub Plugin tests and
CodeQL passed at that revision. The first complete native attempt remains failed:
399 passed, five failed, cleanup passed. Evidence is retained under
`.test-work/reports/pr3037-native-76ffd8ed/`.
The November 7 checkpoint addresses the observed native readiness failures:
- Focus the table handle through trusted hover/scroll/click input before keyboard
resizing, while retaining inactive-pane ownership and exact transaction checks.
- Wait for saved fixture frontmatter before each stability reopen; disk persistence
completes before Obsidian republishes the cache used by its default-view router.
- Flush live Markdown saves before retiring views and deleting owned fixtures.
- Restore Electron zoom and require bounded geometry/notification idle before
closing the owning popout; keep the strict host exception gate unchanged.
- Coalesce the controller's ResizeObserver-driven layout writes into an owned
animation frame and cancel it on unload. This does not attribute or suppress the
host's historically recorded observer notifications.
All six stability cycles and the restored-zoom workflow passed focused validation
without unexpected host errors. Full phone/tablet workflows passed 108 cases with
clean error gates, cleanup and restoration. The corrected desktop input sequence
then passed all 15 embed cases with baseline restoration. Evidence:
`.test-work/reports/pr3037-native-readiness-focused-1/`, including
`devices/report.json` and `controls-input-probe.json`. Failed predecessor attempts
remain separate; the focused parent report's hidden-handle input failure is not
acceptance evidence.
At the readiness checkpoint, 717 tests in 87 files passed. Modified embed modules
had zero targeted lint or TypeScript diagnostics. Complete-profile acceptance was
still required; the latest validated runtime results are recorded below. Minimum
Obsidian 1.8.7, macOS, physical Android/iOS and hosted CodeScanner remain separate
unverified gates.
The isolated alignment check found that the existing
`div.excalidraw-svg-left/right` width rule overrode the gesture's single-class
width rule. A requested 220 px preview measured 600 px in a 600 px container for
both alignments, in PNG, SVG image and inline SVG. The scoped two-class gesture
selector measures 220 px in all nine default/left/right and image-mode cases.
Evidence: `.test-work/pr3037-alignment-css-probe.json` and
`.test-work/pr3037-alignment-css-fixed.json`. The native input cases now assert
actual preview size/aspect ratio during movement and exercise pointer resizing
of left-aligned wiki embeds and right-aligned Markdown-image table cells. Fresh
complete acceptance is required after this CSS checkpoint.
Including the real in-flow toolbar in the small-preview probe exposed the
alignment table layout's intrinsic minimum: an 80 px preview remained 140 px.
Gesture-only block layout on the frame and image removes that minimum while
retaining the alignment's float. Normal table layout returns when the gesture
class is removed. All nine small-preview cases then measure 80 px; evidence is
retained in `.test-work/pr3037-alignment-css-toolbar-probe.json` and
`.test-work/pr3037-alignment-css-toolbar-fixed.json`.
The complete-sequence split fixture can leave only 170 px for its owning pane.
Table resize checks therefore shrink from the measured displayed width instead
of assuming an eight-pixel enlargement fits. Pointer checks likewise shrink by
20 px while measuring actual geometry. Exact source, other-cell preservation,
same-note synchronization and isolated undo remain required. Passive focus/key
evidence is retained on failure. The independent extraction workflow now waits
for the owner to leave save/synchronization work and for its new editor tab to
appear, and verifies the rendered tab's full drawing identity.
## Previous validated runtime checkpoint
Runtime source: `7de41e73247f5a5f7631519115d2856384661092`.
- Complete portable profile: **934 canonical cases passed**, cleanup passed, no
missing cases. Includes 717 plugin tests and 199 source-coverage tests, fork and
Extras source/browser suites, builds and isolated package-consumer checks.
- Focused native desktop/touch profile: **31 cases passed**, cleanup and baseline
restoration passed. This includes all 25 dedicated embed cases across main,
split, minimized-main popout, phone and tablet contexts. It measures actual
preview geometry, including left/right table gestures, rather than CSS values
alone. Both device profiles passed their exception and cleanup gates.
- Evidence: `.test-work/reports/pr3037-portable-7de41e73/report.json` and
`.test-work/reports/pr3037-alignment-native-focused-2/report.json`.
- Production `main.js`: 5,088,831 bytes, 154,049 bytes below the 5 MiB target.
The complete matching-build native profile at the documentation checkpoint
passed all 265 desktop cases and cleanup, then stopped at the phone resize
handle's hit test. Cleanup and baseline restoration passed; incomplete device
coverage does not count as acceptance. Evidence remains in
`.test-work/reports/pr3037-native-final-2026-11-07/`.
A diagnostic repeat captured the focused handle above the viewport (center
approximately -30 px, editor scrollTop 613). CodeMirror's pending caret scroll
could supersede the initial `scrollIntoView()` after image measurement. The
native driver now permits at most three re-scrolls only when the handle center
is outside the editor viewport. It still requires a real uncovered hit and
120 ms of stable geometry before trusted input; an in-view overlay remains a
failure. No product code, gesture assertions or exception gates changed.
The failing diagnostic is retained in
`.test-work/reports/pr3037-phone-layout-probe-1/`. The corrected repeat passed
137 canonical cases, including all 108 phone/tablet cases, cleanup and baseline
restoration: `.test-work/reports/pr3037-phone-layout-probe-2/`. All 717 fast tests
also passed after the driver repair.
Complete acceptance is rerun after this test-harness checkpoint using
`.test-work/reports/pr3037-native-final-2026-11-07-2/report.json`; the PR description
records that run's actual status, counts and exact source commit after completion.
That driver-only checkpoint kept production runtime identical to `7de41e73`. Previous
failed runs remain retained and do not count as acceptance evidence.
`npm run code` reports 118 existing errors outside the modified production
modules; targeted lint and targeted TypeScript diagnostics pass. Production
builds retain the same existing 18 Rollup circular-dependency warnings. The
`madge` executable and hosted Obsidian CodeScanner are not installed locally.
## Drawing Markdown support follow-up
The first implementation incorrectly excluded every drawing file from the editor
bridge, even when the user had opened it as Markdown. A direct self-embed in that
editor therefore rendered its image without controls. The reported deployment's
JavaScript and CSS matched the previously validated artifact; rebuilding that
revision could not resolve the omission.
Remove only the source-file classification exclusion. Complete widget tokens,
canonical target identity, live editor/file/document ownership, read-only state,
renderer generation and nested-context exclusions remain required. Generated
drawing metadata previews still have no source-bound controls.
The new self-embed source test fails on the old guard and passes afterward:
`.test-work/pr3037-hybrid-before-fix.log`. All 718 fast tests, targeted lint and
inventory checks pass. Focused native validation passes 36 cases, including all
30 embed cases and the five new drawing-Markdown cases in main, split, popout,
phone and tablet contexts. It uses the real Open as Markdown action and verifies
exact resize/reset edits, single undo, exact syntax selection, physical source
preservation and fullscreen from Live Preview and Reading mode. Evidence:
`.test-work/reports/pr3037-hybrid-focused-4/`; cleanup and baseline restoration
passed. Failed fixture-setup runs remain retained; guarded recovery restored the
owned test view, retired its completed controller and restored the baseline.
The interrupted complete acceptance attempts for this follow-up used
`.test-work/reports/pr3037-hybrid-portable-final/report.json` and
`.test-work/reports/pr3037-hybrid-native-final/aggregate.json` as intended final
report paths. They were stopped at the maintainer's request; partial artifacts
remain, and final reports may be absent. Earlier complete passes establish the
prior runtime, not this new checkpoint.
## Control appearance and preview refinement
Maintainer review requested an inset, theme-colored corner grip, compact
top-right controls, stable small-image controls during resizing, explicit drawing
navigation for self/reference embeds, and a viewport-sized movable/resizable
preview with a drawing-edit action. Modifier clicks on inline and preview images
and pencil actions use the configured navigation rules; pencil help describes
the live platform-specific settings. Accessible labels for the viewer, toolbars
and grip no longer create unsolicited hover tooltips.
The follow-up builds successfully. Targeted static lint passes. Regression
fixtures and coverage mappings are updated but have **not been executed**: the
maintainer paused testing. The preceding complete runs at `13bac7af` were
interrupted and do not count as completed acceptance. In particular, the new
visual geometry, dialog dragging/native resizing and live navigation still need
focused Obsidian validation when testing resumes. The maintainer reviewed the
appearance, requested a slightly rounded neutral-gray grip, and authorized merge
while testing remained paused. The final production bundle is 5,094,032 bytes,
148,848 bytes below 5 MiB. No personal-vault deployment was performed by the agent
during this follow-up.
## Priority review
1. Resize/reset/edit repeated, same-line and table embeds; verify one-step undo,
untouched surrounding syntax and unchanged drawing files.
2. Compare all three preview modes, fragments, themes, inline SVG links and mask
navigation. Close the viewer during export and switch notes during interaction.
3. Repeat through refresh, detach/reattach, split panes, popout teardown and plugin
reload, then use physical phone/tablet touch for scrolling, focus and gestures.
+2848 -2679
View File
File diff suppressed because it is too large. Load diff
+321 -104
View File
@@ -74,9 +74,11 @@ Frame slides support a build sequence stored on the frame's slideshow metadata.
- **Slide in:** animate an SVG overlay from the chosen direction.
- **Zoom in:** animate an SVG overlay from approximately 5% scale at the target center.
Steps can trigger on presenter advance or sequentially after a delay. Fade, slide, and zoom default to 350 ms; timed steps default to a 1000 ms delay. Steps can be reordered with drag/drop, buttons, or `Alt+Arrow Up/Down`, previewed, edited, and deleted. Editor previews position SVG motion overlays in the drawing host coordinate space, matching presentation geometry even when the Excalidraw leaf is offset by sidepanels or other workspace chrome.
Choose effects and slide directions with the editor's buttons. After **Add step**, the form is ready to add another animation and retains your effect, direction, and timing choices for the editing session. Selecting a different element or group opens its first animation, or prepares a new step if it has none. Use **New step** to animate the same selection again; select any sequence row to edit a later animation. Sequence rows include thumbnails of their targets.
Groups are stored by group ID and resolved dynamically when the presentation runs. Bound text and its container are treated as one visual unit. Marker frames do not own their contents, so animation eligibility is determined by geometric overlap between each element rectangle and the marker-frame rectangle rather than by `frameId`. Adding a target that already belongs to another animation step moves it to the new step instead of creating conflicting builds.
Steps can trigger on presenter advance or sequentially after a delay. Fade, slide, and zoom default to 350 ms; timed steps default to a 1000 ms delay. Steps can be reordered with drag/drop, buttons, or `Alt+Arrow Up/Down`, previewed, edited, and deleted. Editor previews position SVG motion overlays in the drawing host coordinate space, matching presentation geometry even when the Excalidraw leaf is offset by sidepanels or other workspace chrome. Motion overlays remain in place while the canvas paints the completed animation, avoiding a blank frame at the handoff.
Groups are stored by group ID and resolved dynamically when the presentation runs. Bound text and its container are treated as one visual unit. Marker frames do not own their contents, so animation eligibility is determined by geometric overlap between each element rectangle and the marker-frame rectangle rather than by `frameId`. A target can appear in multiple steps, including repeated entrances and exits. Adding or editing a step preserves the target's other animations.
Presentation navigation is hierarchical: Forward reveals the next pending build before advancing the slide; Backward reverses the most recently completed build before moving to the previous slide. Previous slides entered while navigating backward start fully built, while direct jumps enter the destination in its initial build state. Timed callbacks and animation frames are invalidated on navigation and exit. Temporary scene changes use `captureUpdate: "NEVER"`; real elements are changed only through opacity, while slide/zoom motion uses disposable SVG overlays. Any interruption or presentation exit explicitly restores every animated target to its final/original visibility before cleanup.
@@ -129,10 +131,11 @@ Select **Print slideshow to PDF** in the sidepanel or presentation toolbar to op
- The **Print only visible slides** toggle is on by default. Turn it off to include excluded slides, including decks whose slides are all excluded.
- Choose the configured slide size, **A4**, **Letter**, **16:9**, or **Custom**, then select **Landscape** or **Portrait**. Width and height are editable in pixels (96 pixels per inch), from 320 to 14400 pixels. Holding Shift while opening setup starts with the current viewport dimensions.
- Each slide is clipped to its own rectangle and fitted intact inside its page or handout slot. Changing paper aspect ratio never pulls neighboring slides into the printout or splits a slide across pages. Handout slots retain the configured presentation aspect ratio.
- **Include frames around slides** adds a border using the configured slide aspect ratio in notes and handout layouts, including notes continuations. It is off by default and hidden for **Slides only**, which always prints without added frames.
- **Margins** offers **None** (default, edge-to-edge slides), **Minimal** (10 px), and **Normal** (60 px). Margins apply to slides and handouts without adding a second inset in the PDF exporter.
- Notes use Obsidian's Markdown renderer, preserving headings, emphasis, links, lists, tables, and code as formatted HTML. Long notes continue in another slot with the slide repeated.
- **Page ranges** accepts output-page selections such as `1-3;5;9-`; leave it blank for all pages. Ranges count final pages, including notes continuation pages, and preserve their original order.
- Confirmed print preferences (layout, visibility, page size, orientation/dimensions, margins, and page ranges) are saved in script settings and restored the next time print setup opens. The slideshow source initially follows the current drawing.
- Confirmed print preferences (layout, visibility, handout frames, page size, orientation/dimensions, margins, and page ranges) are saved in script settings and restored the next time print setup opens. The slideshow source initially follows the current drawing.
PDF creation uses Excalidraw's existing desktop PDF export and its normal save dialog.
@@ -159,7 +162,7 @@ The note includes every frame slide in sorter order, including excluded slides.
Alt/Option.
- **Open the Slideshow sidepanel:** Hold Cmd on macOS or Ctrl on Windows/Linux while invoking the script.
Build version: 2026-11-04T07:18:10.636Z
Build version: 2026-11-16T17:57:13.580Z
```javascript
*/
@@ -203,6 +206,7 @@ Build version: 2026-11-04T07:18:10.636Z
printNotesPage: "Notes \u2014 one slide per page",
printHandout2: "Handout \u2014 two slides with notes per page",
printHandout3: "Handout \u2014 three slides with notes per page",
printIncludeFrames: "Include frames around slides",
printVisibleOnly: "Print only visible slides",
printVisibleOnlyHint: "Turn off to include excluded slides.",
printPageRanges: "Page ranges",
@@ -356,7 +360,7 @@ Build version: 2026-11-04T07:18:10.636Z
animationCheckpoint3: "Animation editing is available for frame slides.",
animationEditorTitle: "Animations \u2014 {title}",
closeAnimationEditor: "Close animation editor",
animationSelectionHint: "Select elements or groups in the drawing, then configure and add them as a build step.",
animationSelectionHint: "Select an element or group to edit its first animation or add a new one. Add step readies the next animation; New step animates the same selection again.",
animationOutsideFrameIgnored: "Ignored {count} selected item(s) outside this frame.",
animationOutsideSlideIgnored: "Ignored {count} selected item(s) outside this slide.",
animationTargets: "Targets",
@@ -836,9 +840,30 @@ Build version: 2026-11-04T07:18:10.636Z
}
// src/scripts/slideshow/icons.ts
var ANIMATION_ICON_NAMES = {
appear: "eye",
fade: "circle-fading-plus",
slide: "arrow-right-to-line",
zoom: "zoom-in",
disappear: "eye-off",
"slide-out": "arrow-right-from-line",
"zoom-out": "zoom-out",
left: "arrow-big-left-dash",
right: "arrow-big-right-dash",
up: "arrow-big-up-dash",
down: "arrow-big-down-dash",
"after-delay": "timer",
advance: "step-forward"
};
var FADE_OUT_ICON = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-fading-minus preview-icon"><path d="M12 2a10 10 0 0 1 7.38 16.75"/><path d="M8 12h8"/><path d="M2.5 8.875a10 10 0 0 0-.5 3"/><path d="M2.83 16a10 10 0 0 0 2.43 3.4"/><path d="M4.636 5.235a10 10 0 0 1 .891-.857"/><path d="M8.644 21.42a10 10 0 0 0 7.631-.38"/></svg>';
function iconMarkup(ea2, iconName) {
return ea2.obsidian.getIcon(iconName)?.outerHTML ?? "";
}
function getAnimationEditorIcon(ea2, choice, exits) {
if (choice === "fade-out") return FADE_OUT_ICON;
const direction = exits ? choice : choice === "left" ? "right" : choice === "right" ? "left" : choice === "up" ? "down" : choice === "down" ? "up" : choice;
return iconMarkup(ea2, `lucide-${ANIMATION_ICON_NAMES[direction]}`);
}
function getSlideshowIcons(ea2) {
return {
finish: iconMarkup(ea2, "lucide-x"),
@@ -1830,22 +1855,6 @@ Build version: 2026-11-04T07:18:10.636Z
}
return { targets, ignoredSelectionCount };
}
function targetsOverlap(slideScope, left, right, elements) {
const leftIds = new Set(resolveAnimationTargetElementIds(slideScope, [left], elements));
return resolveAnimationTargetElementIds(slideScope, [right], elements).some((id) => leftIds.has(id));
}
function removeAnimationTargetConflicts(slideScope, steps, incomingTargets, elements, editedStepId, incomingEffect) {
return steps.flatMap((step) => {
if (step.id === editedStepId) return [structuredClone(step)];
if (incomingEffect !== void 0 && isExitAnimationEffect(step.effect) !== isExitAnimationEffect(incomingEffect)) {
return [structuredClone(step)];
}
const targets = step.targets.filter(
(target) => !incomingTargets.some((incoming) => targetsOverlap(slideScope, target, incoming, elements))
);
return targets.length === 0 ? [] : [{ ...structuredClone(step), targets }];
});
}
function getOpacity(element) {
return asAnimationShape(element).opacity;
}
@@ -1854,14 +1863,6 @@ Build version: 2026-11-04T07:18:10.636Z
step: structuredClone(step),
elementIds: resolveAnimationTargetElementIds(slideScope, step.targets, elements)
}));
const claimedByLaterStep = /* @__PURE__ */ new Set();
for (let index = resolved.length - 1; index >= 0; index -= 1) {
const current = resolved[index];
if (!current) continue;
const phase = isExitAnimationEffect(current.step.effect) ? "exit" : "enter";
current.elementIds = current.elementIds.filter((id) => !claimedByLaterStep.has(`${phase}:${id}`));
for (const id of current.elementIds) claimedByLaterStep.add(`${phase}:${id}`);
}
return resolved.filter((step) => step.elementIds.length > 0);
}
var AnimationRuntime = class {
@@ -1993,6 +1994,7 @@ Build version: 2026-11-04T07:18:10.636Z
await this.runStepEffect(resolved, true, generation);
if (!this.active || generation !== this.generation) return true;
this.active.completedSteps -= 1;
this.applyBuildState();
this.emitState();
return true;
} catch (error) {
@@ -2197,7 +2199,13 @@ Build version: 2026-11-04T07:18:10.636Z
overlay.style.opacity = "0";
}
await this.wait(duration + 24, generation);
if (generation === this.generation) this.applyResolvedOpacity(resolved, endsHidden ? 0 : null);
if (generation === this.generation) {
this.applyResolvedOpacity(resolved, endsHidden ? 0 : null);
if (!endsHidden) {
await this.nextFrame(generation);
await this.nextFrame(generation);
}
}
overlay.remove();
this.overlays.delete(overlay);
}
@@ -2809,8 +2817,14 @@ Build version: 2026-11-04T07:18:10.636Z
}
};
// src/scripts/slideshow/previewAppearance.ts
function getPreviewAppearance(state) {
const color = typeof state.viewBackgroundColor === "string" ? state.viewBackgroundColor : "#ffffff";
const backgroundColor = state.theme === "dark" ? window.ExcalidrawLib.applyDarkModeFilter(color) : color;
return { theme: state.theme, backgroundColor, key: `${state.theme}|${color}` };
}
// src/scripts/slideshow/SlidePreviewService.ts
var FALLBACK_BACKGROUND = "#ffffff";
var PREVIEW_CACHE_BYTES = 64 * 1024 * 1024;
var DEFAULT_PREVIEW_WIDTH = 960;
var PREVIEW_EXPORT_CONCURRENCY = 2;
@@ -2826,9 +2840,6 @@ Build version: 2026-11-04T07:18:10.636Z
slide.kind === "path" ? elements.filter((element) => element.id !== slide.pathId) : elements
);
}
function readBackgroundColor(appState) {
return typeof appState.viewBackgroundColor === "string" ? appState.viewBackgroundColor : FALLBACK_BACKGROUND;
}
function getHiddenBuildElementIds(slide, completedAnimationSteps, elements, config) {
if (slide.animationSteps.length === 0) return [];
if (completedAnimationSteps === void 0 && !slide.animationSteps.some((step) => isExitAnimationEffect(step.effect))) {
@@ -2846,14 +2857,6 @@ Build version: 2026-11-04T07:18:10.636Z
step,
ids: resolveAnimationTargetElementIds(scope, step.targets, elements)
}));
const claimedByLaterStep = /* @__PURE__ */ new Set();
for (let index = resolved.length - 1; index >= 0; index -= 1) {
const current = resolved[index];
if (!current) continue;
const phase = isExitAnimationEffect(current.step.effect) ? "exit" : "enter";
current.ids = current.ids.filter((id) => !claimedByLaterStep.has(`${phase}:${id}`));
for (const id of current.ids) claimedByLaterStep.add(`${phase}:${id}`);
}
const hiddenIds = /* @__PURE__ */ new Set();
const initialized = /* @__PURE__ */ new Set();
for (const current of resolved) {
@@ -2890,7 +2893,7 @@ Build version: 2026-11-04T07:18:10.636Z
generation = 0;
/** Returns the drawing background used behind previews. */
getBackgroundColor() {
return readBackgroundColor(this.api.getAppState());
return getPreviewAppearance(this.api.getAppState()).backgroundColor;
}
/** Returns the configured presentation aspect ratio used by sorter previews. */
getAspectRatio() {
@@ -2919,8 +2922,7 @@ Build version: 2026-11-04T07:18:10.636Z
image.style.backgroundColor = cached.backgroundColor;
return image;
}
async exportPreview(localElements, slide, hiddenElementIds, originalOpacities, targetWidth, generation, cacheKey) {
const appState = this.api.getAppState();
async exportPreview(localElements, slide, hiddenElementIds, originalOpacities, targetWidth, generation, cacheKey, appearance = getPreviewAppearance(this.api.getAppState())) {
const rect = getPreviewNavigationRect(
slide,
this.config.maxZoom,
@@ -2933,7 +2935,7 @@ Build version: 2026-11-04T07:18:10.636Z
width: Math.abs(rect.right - rect.left),
height: Math.abs(rect.bottom - rect.top)
};
if (generation !== this.generation) return void 0;
if (generation !== this.generation || getPreviewAppearance(this.api.getAppState()).key !== appearance.key) return void 0;
const hiddenIds = new Set(hiddenElementIds);
const exportElements = localElements.map((element) => {
let opacity = element.opacity;
@@ -2948,12 +2950,12 @@ Build version: 2026-11-04T07:18:10.636Z
elements: exportElements,
area: exportArea,
targetWidth,
theme: appState.theme
theme: appearance.theme
});
if (generation !== this.generation) return void 0;
if (generation !== this.generation || getPreviewAppearance(this.api.getAppState()).key !== appearance.key) return void 0;
const cached = {
objectUrl: URL.createObjectURL(blob),
backgroundColor: readBackgroundColor(appState)
backgroundColor: appearance.backgroundColor
};
this.cached.set(cacheKey, cached, blob.size);
return cached;
@@ -2969,6 +2971,7 @@ Build version: 2026-11-04T07:18:10.636Z
this.config
);
const appState = this.api.getAppState();
const appearance = getPreviewAppearance(appState);
const targetWidth = Math.max(Math.trunc(state.targetWidth ?? DEFAULT_PREVIEW_WIDTH), 1);
const opacityKey = state.originalOpacities ? [...state.originalOpacities.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([id, opacity]) => `${id}:${opacity}`).join(",") : "none";
const rect = getPreviewNavigationRect(
@@ -2987,8 +2990,7 @@ Build version: 2026-11-04T07:18:10.636Z
includeBoundElements: true
});
const cacheKey = [
appState.theme,
readBackgroundColor(appState),
appearance.key,
slide.kind === "path" ? `path:${slide.pathId}` : "frame",
`hidden:${hiddenElementIds.join(",")}`,
`opacity:${opacityKey}`,
@@ -3008,7 +3010,8 @@ Build version: 2026-11-04T07:18:10.636Z
state.originalOpacities,
targetWidth,
generation,
cacheKey
cacheKey,
appearance
),
() => generation === this.generation
);
@@ -3458,17 +3461,27 @@ Build version: 2026-11-04T07:18:10.636Z
.slideshow-animation-editor__section { display:flex; flex-direction:column; gap:6px; }
.slideshow-animation-editor__section-title { font-weight:600; font-size:var(--font-ui-small); }
.slideshow-animation-editor__targets { display:flex; flex-wrap:wrap; gap:5px; }
.slideshow-animation-editor__target { display:inline-flex; align-items:center; gap:4px; padding:3px 4px 3px 7px; border-radius:999px; background:var(--background-secondary); font-size:var(--font-ui-smaller); }
.slideshow-animation-editor__target { display:inline-flex; align-items:center; gap:4px; padding:4px; border-radius:8px; background:var(--background-secondary); }
.slideshow-animation-editor__target-preview { width:64px; height:56px; display:flex; align-items:center; justify-content:center; overflow:hidden; border-radius:4px; }
.slideshow-animation-editor__target-preview img { width:100%; height:100%; object-fit:contain; }
.slideshow-animation-editor__target button { width:22px; height:22px; min-width:22px; padding:3px; display:flex; align-items:center; justify-content:center; }
.slideshow-animation-editor__form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; }
.slideshow-animation-editor__form label { display:flex; flex-direction:column; gap:4px; color:var(--text-muted); font-size:var(--font-ui-smaller); }
.slideshow-animation-editor__form select, .slideshow-animation-editor__form input { width:100%; box-sizing:border-box; }
.slideshow-animation-editor__choices-section { grid-column:1/-1; display:flex; flex-direction:column; gap:5px; color:var(--text-muted); font-size:var(--font-ui-smaller); }
.slideshow-animation-editor__choices { display:grid; grid-template-columns:repeat(auto-fit,minmax(90px,1fr)); gap:5px; }
.slideshow-animation-editor__choices button { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:5px; min-height:64px; height:auto; padding:7px; white-space:normal; }
.slideshow-animation-editor__choice-icon { display:flex; flex:0 0 24px; align-items:center; justify-content:center; }
.slideshow-animation-editor .slideshow-animation-editor__choice-icon svg { width:24px; height:24px; }
.slideshow-animation-editor__choices button[aria-pressed="true"] { color:var(--text-accent); border:1px solid var(--interactive-accent); background:var(--background-modifier-hover); box-shadow:0 0 0 1px var(--interactive-accent); }
.slideshow-animation-editor__form-actions { display:flex; flex-wrap:wrap; gap:6px; }
.slideshow-animation-editor__form-actions button { display:inline-flex; align-items:center; gap:5px; }
.slideshow-animation-editor__steps { display:flex; flex-direction:column; gap:6px; }
.slideshow-animation-editor__step { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:6px; padding:6px; border:1px solid var(--background-modifier-border); border-radius:6px; background:var(--background-primary); }
.slideshow-animation-editor__step.is-selected { border-color:var(--interactive-accent); box-shadow:0 0 0 1px var(--interactive-accent); }
.slideshow-animation-editor__step-summary { min-width:0; text-align:left; white-space:normal; }
.slideshow-animation-editor__step-summary { display:flex; align-items:center; gap:10px; min-width:0; height:auto; text-align:left; white-space:normal; }
.slideshow-animation-editor__step-preview { flex:0 0 64px; height:56px; display:flex; align-items:center; justify-content:center; overflow:hidden; border-radius:4px; background:var(--background-secondary); }
.slideshow-animation-editor__step-preview img { width:100%; height:100%; object-fit:contain; }
.slideshow-animation-editor__step-actions { display:grid; grid-template-columns:repeat(2,28px); gap:3px; }
.slideshow-animation-editor__step-actions button { width:28px; height:28px; padding:4px; display:flex; align-items:center; justify-content:center; }
@@ -4295,6 +4308,7 @@ Build version: 2026-11-04T07:18:10.636Z
const defaults = {
layout: "slides",
visibleOnly: true,
includeFrames: false,
margin: "none",
width,
height,
@@ -4308,6 +4322,7 @@ Build version: 2026-11-04T07:18:10.636Z
if (["slides", "notes", "handout-2", "handout-3"].includes(String(saved.layout)))
defaults.layout = saved.layout;
if (typeof saved.visibleOnly === "boolean") defaults.visibleOnly = saved.visibleOnly;
if (typeof saved.includeFrames === "boolean") defaults.includeFrames = saved.includeFrames;
if (["none", "minimal", "normal"].includes(String(saved.margin)))
defaults.margin = saved.margin;
if (["configured", "A4", "Letter", "16:9", "custom"].includes(String(saved.preset)))
@@ -4396,6 +4411,15 @@ Build version: 2026-11-04T07:18:10.636Z
["handout-3", t("printHandout3")]
]);
layout.value = preferences.layout;
let includeFrames = preferences.includeFrames ?? false;
const framesRow = new ea2.obsidian.Setting(modal.contentEl).setName(t("printIncludeFrames")).addToggle(
(toggle) => toggle.setValue(includeFrames).onChange((value) => {
includeFrames = value;
})
);
const updateFramesVisibility = () => framesRow.settingEl.toggle(layout.value !== "slides");
layout.addEventListener("change", updateFramesVisibility);
updateFramesVisibility();
const theme = select(t("printTheme"), [
["light", t("printThemeLight")],
["dark", t("printThemeDark")]
@@ -4482,6 +4506,7 @@ Build version: 2026-11-04T07:18:10.636Z
sourceKey: source.value,
layout: layout.value,
visibleOnly,
includeFrames: layout.value !== "slides" && includeFrames,
theme: theme.value,
pageRanges: ranges.value.trim(),
margin: margin.value
@@ -4489,6 +4514,7 @@ Build version: 2026-11-04T07:18:10.636Z
void savePrintPreferences(ea2, {
layout: result.layout,
visibleOnly,
includeFrames,
margin: result.margin,
width: result.width,
height: result.height,
@@ -4661,6 +4687,19 @@ Build version: 2026-11-04T07:18:10.636Z
clone.setAttribute("x", String(boxes.slide.x));
clone.setAttribute("y", String(boxes.slide.y + y));
page.appendChild(clone);
if (settings.includeFrames) {
page.createSvg("rect", {
attr: {
x: slideBox.x,
y: slideBox.y + y,
width: slideBox.width,
height: slideBox.height,
fill: "none",
stroke: colors.border,
"stroke-width": 1
}
});
}
appendPrintNotes(page, notes, { ...boxes.notes, y: boxes.notes.y + y });
slot += 1;
}
@@ -5395,6 +5434,70 @@ Build version: 2026-11-04T07:18:10.636Z
});
}
// src/scripts/slideshow/AnimationTargetPreviewService.ts
var AnimationTargetPreviewService = class {
constructor(ea2, api) {
this.ea = ea2;
this.api = api;
}
ea;
api;
queue = new AsyncTaskQueue(1);
cache = new ByteBudgetLruCache(
4 * 1024 * 1024,
(url) => URL.revokeObjectURL(url)
);
destroyed = false;
/** Exports only the scoped visual targets, including bound text, at at most 160px per side. */
async createPreview(scope, targets, doc, isRelevant, originalOpacities) {
if (this.destroyed) return null;
const elements = this.ea.getViewElements();
const ids = new Set(resolveAnimationTargetElementIds(scope, targets, elements));
const selected = elements.filter((element) => ids.has(element.id)).map((element) => {
const opacity = originalOpacities?.get(element.id) ?? element.opacity;
return opacity === element.opacity ? element : { ...element, opacity };
});
if (selected.length === 0) return null;
const appearance = getPreviewAppearance(this.api.getAppState());
const key = `${appearance.key}|${getSceneVisualFingerprint(selected)}`;
let url = this.cache.get(key);
if (!url) {
url = await this.queue.enqueue(key, async () => {
if (getPreviewAppearance(this.api.getAppState()).key !== appearance.key) return void 0;
const bounds = this.ea.getBoundingBox(selected);
const blob = await this.ea.createViewPNG({
withBackground: true,
theme: appearance.theme,
frameRendering: { enabled: false, name: false, outline: false, clip: false },
padding: 4,
selectedOnly: false,
embedScene: false,
elementsOverride: selected,
scale: Math.min(2, 160 / Math.max(bounds.width + 8, bounds.height + 8, 1))
});
if (this.destroyed || getPreviewAppearance(this.api.getAppState()).key !== appearance.key) return void 0;
const objectUrl = URL.createObjectURL(blob);
this.cache.set(key, objectUrl, blob.size);
return objectUrl;
}, () => !this.destroyed);
}
await Promise.resolve();
if (!url || this.destroyed || !isRelevant()) return null;
const image = doc.createElement("img");
image.src = url;
image.alt = "";
image.draggable = false;
image.style.backgroundColor = appearance.backgroundColor;
return image;
}
/** Invalidates queued exports and releases URLs, including when a running export finishes later. */
destroy() {
this.destroyed = true;
this.queue.clear();
this.cache.clear();
}
};
// src/scripts/slideshow/slideDeckMutations.ts
function normalizeNotes2(notes) {
return notes.trim().length === 0 ? void 0 : notes;
@@ -5909,7 +6012,8 @@ Build version: 2026-11-04T07:18:10.636Z
}
function sameTargets(left, right) {
if (left.length !== right.length) return false;
return left.every((target, index) => targetKey(target) === targetKey(right[index] ?? target));
const keys = new Set(right.map(targetKey));
return left.every((target) => keys.has(targetKey(target)));
}
function uniqueStepId(steps) {
const used = new Set(steps.map((step) => step.id));
@@ -5932,6 +6036,7 @@ Build version: 2026-11-04T07:18:10.636Z
this.options = options;
this.steps = options.slide.animationSteps.map((step) => structuredClone(step));
this.drawingFile = options.hostView.file;
this.targetPreviews = new AnimationTargetPreviewService(options.ea, options.api);
this.previewRuntime = new AnimationRuntime({
ea: options.ea,
api: options.api,
@@ -5949,18 +6054,33 @@ Build version: 2026-11-04T07:18:10.636Z
delayMs = 1e3;
durationMs = 350;
direction = "left";
newStepDefaults = {
effect: this.effect,
trigger: this.trigger,
delayMs: this.delayMs,
durationMs: this.durationMs,
direction: this.direction
};
lastSelectionTargets = null;
destroyed = false;
saving = false;
ignoreSelectionUntil = 0;
selectingStep = false;
recycleTimer = 0;
pendingRecycleElements = null;
previewRuntime;
targetPreviews;
drawingFile;
targetPreviewBindings = /* @__PURE__ */ new Map();
previewAppearanceKey = "";
previewGeneration = 0;
/** Renders the editor into its current sidepanel container. */
render() {
if (this.destroyed) return;
const { container, icons, t } = this.options;
const doc = container.ownerDocument;
this.targetPreviewBindings.clear();
this.previewGeneration += 1;
this.previewAppearanceKey = getPreviewAppearance(this.options.api.getAppState()).key;
container.replaceChildren();
container.className = "slideshow-animation-editor";
const instructions = doc.createElement("div");
@@ -5990,9 +6110,10 @@ Build version: 2026-11-04T07:18:10.636Z
this.targets.forEach((target, index) => {
const chip = doc.createElement("span");
chip.className = "slideshow-animation-editor__target";
const label = doc.createElement("span");
label.textContent = this.getTargetLabel(target);
chip.appendChild(label);
const preview = this.createTargetPreview(doc, [target], "slideshow-animation-editor__target-preview");
preview.setAttribute("role", "img");
preview.setAttribute("aria-label", this.getTargetLabel(target));
chip.appendChild(preview);
const remove = this.iconButton(doc, icons.close, t("removeAnimationTarget"), false, () => {
this.targets.splice(index, 1);
this.render();
@@ -6005,7 +6126,7 @@ Build version: 2026-11-04T07:18:10.636Z
container.appendChild(targetSection);
const form = doc.createElement("div");
form.className = "slideshow-animation-editor__form";
const effectSelect = this.createSelect(doc, t("animationEffect"), [
const effectSelect = this.createChoices(doc, t("animationEffect"), [
["appear", t("animationEffectAppear")],
["fade", t("animationEffectFade")],
["slide", t("animationEffectSlide")],
@@ -6016,14 +6137,16 @@ Build version: 2026-11-04T07:18:10.636Z
["zoom-out", t("animationEffectZoomOut")]
], this.effect, (value) => {
this.effect = value;
this.rememberFormDefaults();
this.render();
});
form.appendChild(effectSelect);
const triggerSelect = this.createSelect(doc, t("animationTrigger"), [
const triggerSelect = this.createChoices(doc, t("animationTrigger"), [
["advance", t("animationTriggerAdvance")],
["after-delay", t("animationTriggerDelay")]
], this.trigger, (value) => {
this.trigger = value;
this.rememberFormDefaults();
this.render();
});
form.appendChild(triggerSelect);
@@ -6031,6 +6154,7 @@ Build version: 2026-11-04T07:18:10.636Z
form.appendChild(
this.numberField(doc, t("animationDelayMs"), this.delayMs, 0, (value) => {
this.delayMs = value;
this.rememberFormDefaults();
})
);
}
@@ -6038,6 +6162,7 @@ Build version: 2026-11-04T07:18:10.636Z
form.appendChild(
this.numberField(doc, t("animationDurationMs"), this.durationMs, 0, (value) => {
this.durationMs = value;
this.rememberFormDefaults();
})
);
}
@@ -6054,8 +6179,10 @@ Build version: 2026-11-04T07:18:10.636Z
["down", t("animationDirectionDown")]
];
form.appendChild(
this.createSelect(doc, t("animationDirection"), directionOptions, this.direction, (value) => {
this.createChoices(doc, t("animationDirection"), directionOptions, this.direction, (value) => {
this.direction = value;
this.rememberFormDefaults();
this.render();
})
);
}
@@ -6103,12 +6230,19 @@ Build version: 2026-11-04T07:18:10.636Z
}
/** Processes live scene changes while animation editing is active. */
handleSceneChange(elements, appState) {
if (this.destroyed || !this.isCurrentDrawing()) return;
const appearanceKey = getPreviewAppearance(this.options.api.getAppState()).key;
if (appearanceKey !== this.previewAppearanceKey) {
this.previewAppearanceKey = appearanceKey;
this.previewGeneration += 1;
for (const [preview, targets] of this.targetPreviewBindings) this.loadTargetPreview(preview, targets);
}
this.captureSelection(elements, appState);
this.scheduleMissingTargetRecycle(elements);
}
/** Captures the live canvas selection while animation editing is active. */
captureSelection(elements, appState) {
if (this.destroyed || !this.isCurrentDrawing() || Date.now() < this.ignoreSelectionUntil) {
if (this.destroyed || !this.isCurrentDrawing() || this.selectingStep) {
return;
}
const captured = captureAnimationTargets(
@@ -6117,10 +6251,22 @@ Build version: 2026-11-04T07:18:10.636Z
appState.selectedElementIds,
appState.selectedGroupIds
);
if (sameTargets(captured.targets, this.targets) && captured.ignoredSelectionCount === this.ignoredSelectionCount) {
if (this.lastSelectionTargets !== null && sameTargets(captured.targets, this.lastSelectionTargets) && captured.ignoredSelectionCount === this.ignoredSelectionCount) {
return;
}
this.targets = captured.targets;
const selectionChanged = this.lastSelectionTargets === null || !sameTargets(captured.targets, this.lastSelectionTargets);
this.lastSelectionTargets = captured.targets;
if (selectionChanged) {
const ids = new Set(resolveAnimationTargetElementIds(this.getSlideScope(), captured.targets, elements));
const firstStep = this.steps.find(
(step) => resolveAnimationTargetElementIds(this.getSlideScope(), step.targets, elements).some((id) => ids.has(id))
);
if (firstStep) this.loadStepForm(firstStep);
else {
this.startNewStep();
this.targets = captured.targets;
}
}
this.ignoredSelectionCount = captured.ignoredSelectionCount;
this.render();
}
@@ -6131,6 +6277,9 @@ Build version: 2026-11-04T07:18:10.636Z
if (this.recycleTimer) this.options.hostView.ownerWindow.clearTimeout(this.recycleTimer);
this.recycleTimer = 0;
this.pendingRecycleElements = null;
this.targetPreviewBindings.clear();
this.previewGeneration += 1;
this.targetPreviews.destroy();
if (this.isCurrentDrawing()) await this.previewRuntime.leaveSlide();
else this.previewRuntime.abandonActiveSlide();
}
@@ -6166,7 +6315,7 @@ Build version: 2026-11-04T07:18:10.636Z
} else {
this.selectedStepId = null;
this.targets = [];
this.resetFormDefaults();
this.startNewStep();
}
}
this.options.onSaved(this.steps);
@@ -6188,11 +6337,14 @@ Build version: 2026-11-04T07:18:10.636Z
const summary = doc.createElement("button");
summary.type = "button";
summary.className = "slideshow-animation-editor__step-summary";
summary.textContent = t("animationStepSummary", {
const label = doc.createElement("span");
label.textContent = t("animationStepSummary", {
number: index + 1,
effect: this.effectLabel(step.effect),
targets: step.targets.length
});
const preview = this.createTargetPreview(doc, step.targets, "slideshow-animation-editor__step-preview");
summary.append(preview, label);
summary.addEventListener("click", () => this.selectStep(step));
row.appendChild(summary);
const actions = doc.createElement("div");
@@ -6245,7 +6397,8 @@ Build version: 2026-11-04T07:18:10.636Z
});
return row;
}
selectStep(step) {
/** Loads a saved step without changing the user's defaults for the next new step. */
loadStepForm(step) {
this.selectedStepId = step.id;
this.targets = step.targets.map((target) => structuredClone(target));
this.effect = step.effect;
@@ -6254,14 +6407,56 @@ Build version: 2026-11-04T07:18:10.636Z
this.durationMs = step.durationMs ?? 350;
this.direction = step.direction ?? "left";
this.ignoredSelectionCount = 0;
}
/** Shares the bounded thumbnail cache between selected-target cards and sequence rows. */
createTargetPreview(doc, targets, className) {
const preview = doc.createElement("span");
preview.className = className;
this.targetPreviewBindings.set(preview, targets);
this.loadTargetPreview(preview, targets);
return preview;
}
/** Updates image content in place so appearance changes preserve the mounted form controls. */
loadTargetPreview(preview, targets) {
const generation = this.previewGeneration;
void this.targetPreviews.createPreview(
this.getSlideScope(),
targets,
preview.ownerDocument,
() => !this.destroyed && generation === this.previewGeneration && preview.isConnected && this.isCurrentDrawing(),
this.previewRuntime.getOriginalOpacities()
).then((image) => {
if (image && !this.destroyed && generation === this.previewGeneration && preview.isConnected) preview.replaceChildren(image);
}).catch((error) => console.error("Slideshow animation thumbnail failed", error));
}
selectStep(step) {
this.loadStepForm(step);
const ids = resolveAnimationTargetElementIds(
this.getSlideScope(),
step.targets,
this.options.ea.getViewElements()
);
const elements = this.options.ea.getViewElements().filter((element) => ids.includes(element.id));
this.ignoreSelectionUntil = Date.now() + 500;
if (elements.length > 0) this.options.ea.selectElementsInView(elements);
this.selectingStep = true;
try {
if (elements.length > 0) this.options.ea.selectElementsInView(elements);
this.options.api.updateScene({
appState: {
selectedGroupIds: Object.fromEntries(step.targets.filter((target) => target.type === "group").map((target) => [target.id, true]))
},
captureUpdate: "NEVER",
forceFlushSync: true
});
const state = this.options.api.getAppState();
this.lastSelectionTargets = captureAnimationTargets(
this.getSlideScope(),
this.options.ea.getViewElements(),
state.selectedElementIds,
state.selectedGroupIds
).targets;
} finally {
this.selectingStep = false;
}
this.render();
}
async saveCurrentStep() {
@@ -6269,17 +6464,10 @@ Build version: 2026-11-04T07:18:10.636Z
this.saving = true;
this.render();
try {
const elements = this.options.ea.getViewElements();
const selectedId = this.selectedStepId;
let steps = removeAnimationTargetConflicts(
this.getSlideScope(),
this.steps,
this.targets,
elements,
selectedId ?? void 0,
this.effect
);
const steps = this.steps.map((step2) => structuredClone(step2));
const step = this.buildFormStep(selectedId ?? uniqueStepId(steps));
this.rememberFormDefaults();
if (selectedId) {
const index = steps.findIndex((candidate) => candidate.id === selectedId);
if (index >= 0) steps[index] = step;
@@ -6290,8 +6478,9 @@ Build version: 2026-11-04T07:18:10.636Z
await this.saveAnimationSteps(steps);
if (!this.isCurrentDrawing()) return;
this.steps = steps;
this.selectedStepId = step.id;
this.targets = step.targets.map((target) => structuredClone(target));
if (!selectedId && this.selectedStepId === null && sameTargets(this.targets, step.targets)) {
this.startNewStep();
}
this.options.onSaved(this.steps);
} catch (error) {
console.error("Slideshow animation metadata save failed", error);
@@ -6314,7 +6503,7 @@ Build version: 2026-11-04T07:18:10.636Z
if (this.selectedStepId === stepId) {
this.selectedStepId = null;
this.targets = [];
this.resetFormDefaults();
this.startNewStep();
}
this.render();
}
@@ -6360,7 +6549,7 @@ Build version: 2026-11-04T07:18:10.636Z
}
startNewStep() {
this.selectedStepId = null;
this.resetFormDefaults();
Object.assign(this, this.newStepDefaults);
}
getSlideScope() {
const appState = this.options.api.getAppState();
@@ -6372,12 +6561,15 @@ Build version: 2026-11-04T07:18:10.636Z
isCurrentDrawing() {
return this.options.hostView.file === this.drawingFile;
}
resetFormDefaults() {
this.effect = "appear";
this.trigger = "advance";
this.delayMs = 1e3;
this.durationMs = 350;
this.direction = "left";
/** Remembers explicit form choices independently of saved-step selection. */
rememberFormDefaults() {
this.newStepDefaults = {
effect: this.effect,
trigger: this.trigger,
delayMs: this.delayMs,
durationMs: this.durationMs,
direction: this.direction
};
}
getTargetLabel(target) {
if (target.type === "group") {
@@ -6419,22 +6611,32 @@ Build version: 2026-11-04T07:18:10.636Z
button.addEventListener("click", callback);
return button;
}
createSelect(doc, labelText, options, value, onChange) {
const label = doc.createElement("label");
const text = doc.createElement("span");
text.textContent = labelText;
label.appendChild(text);
const select = doc.createElement("select");
for (const [optionValue, optionLabel] of options) {
const option = doc.createElement("option");
option.value = optionValue;
option.textContent = optionLabel;
select.appendChild(option);
/** Renders accessible effect/direction buttons using the same form state as timing controls. */
createChoices(doc, labelText, choices, value, onChange) {
const section = doc.createElement("div");
section.className = "slideshow-animation-editor__choices-section";
const heading = doc.createElement("span");
heading.textContent = labelText;
const buttons = doc.createElement("div");
buttons.className = "slideshow-animation-editor__choices";
buttons.setAttribute("role", "group");
buttons.setAttribute("aria-label", labelText);
for (const [choice, label] of choices) {
const button = doc.createElement("button");
button.type = "button";
const icon = doc.createElement("span");
icon.className = "slideshow-animation-editor__choice-icon";
icon.setAttribute("aria-hidden", "true");
icon.innerHTML = getAnimationEditorIcon(this.options.ea, choice, isExitAnimationEffect(this.effect));
const text = doc.createElement("span");
text.textContent = label;
button.append(icon, text);
button.setAttribute("aria-pressed", String(choice === value));
button.addEventListener("click", () => onChange(choice));
buttons.appendChild(button);
}
select.value = value;
select.addEventListener("change", () => onChange(select.value));
label.appendChild(select);
return label;
section.append(heading, buttons);
return section;
}
numberField(doc, labelText, value, min, onChange) {
const label = doc.createElement("label");
@@ -6596,6 +6798,13 @@ Build version: 2026-11-04T07:18:10.636Z
else this.renderPreview(host, slide, generation);
}
}
/** Marks appearance changes for a fresh export even while ordinary scene refreshes are paused. */
invalidatePreviewAppearance() {
this.options.container.querySelectorAll(".slideshow-sorter__preview").forEach((host) => {
host.dataset.previewDirty = "true";
});
this.refreshPreviews();
}
/** Re-establishes lazy loading after focus returns, without touching already-populated thumbnails. */
resumePreviewRendering() {
if (!this.previewRenderingEnabled) return;
@@ -7103,6 +7312,7 @@ Build version: 2026-11-04T07:18:10.636Z
row.appendChild(content);
const preview = doc.createElement("div");
preview.className = "slideshow-sorter__preview";
preview.dataset.slideId = slide.id;
preview.style.backgroundColor = this.options.previewService.getBackgroundColor();
preview.style.aspectRatio = this.options.previewService.getAspectRatio();
content.appendChild(preview);
@@ -7775,6 +7985,7 @@ Build version: 2026-11-04T07:18:10.636Z
ownerWindow;
lastFingerprint = "";
lastPreviewFingerprint = "";
lastPreviewAppearanceKey = "";
lastChromeFingerprint = "";
pendingRefresh = false;
sorterMutationDepth = 0;
@@ -7952,6 +8163,12 @@ Build version: 2026-11-04T07:18:10.636Z
this.bindView(view);
return;
}
const appearanceKey = getPreviewAppearance(appState).key;
if (appearanceKey !== this.lastPreviewAppearanceKey) {
this.lastPreviewAppearanceKey = appearanceKey;
this.sorter?.invalidatePreviewAppearance();
this.refreshPreviewsOnce();
}
if (this.sorterMutationDepth > 0) {
this.pendingRefresh = true;
return;
+3 -3
View File
@@ -401,7 +401,7 @@
},
{
"fname": "Slideshow.md",
"mtime": 1793776869187
"mtime": 1794851991282
},
{
"fname": "Slideshow.svg",
@@ -537,7 +537,7 @@
},
{
"fname": "ExcaliAI.md",
"mtime": 1779295681335
"mtime": 1794869591004
},
{
"fname": "ExcaliAI.svg",
@@ -703,4 +703,4 @@
"fname": "VoronoiDiagramGenerator.svg",
"mtime": 1785564296587
}
]
]
+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">Various AI features based on GPT Vision.<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. 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.1",
"version": "2.29.2",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.29.1",
"version": "2.29.2",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1601 -1342
View File
File diff suppressed because it is too large. Load diff
+6 -3
View File
@@ -53,6 +53,7 @@
"skill": "npm run lib && node scripts/skill-builder.mjs",
"mindmap": "node scripts/deploy-mindmap-builder.mjs",
"lint": "eslint .",
"lint:css": "stylelint styles.css --config stylelint.config.mjs --max-warnings 0",
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx}\" && eslint --max-warnings=0 --ext .ts,.tsx ./src --fix",
"repo:export": "node scripts/generate-repository-zip.mjs",
"repo:update": "node scripts/update-repository.mjs",
@@ -68,7 +69,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.146",
"@zsviczian/excalidraw": "0.18.148",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -109,7 +110,7 @@
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@xmldom/xmldom": "0.9.12",
"@zsviczian/excalidraw-extras-api": "^0.1.1",
"@zsviczian/excalidraw-extras-api": "^0.1.2",
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
"c8": "12.0.0",
"cross-env": "^7.0.3",
@@ -124,6 +125,8 @@
"prettier": "^3.0.1",
"rollup": "^4.14.0",
"rollup-plugin-visualizer": "^7.0.1",
"stylelint": "17.6.0",
"stylelint-config-obsidianmd": "0.1.0",
"tslib": "^2.8.1",
"typescript": "5.9.3",
"uglify-js": "^3.19.3"
@@ -151,4 +154,4 @@
"node": ">=22.0.0",
"npm": ">=10.0.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"));
},
};
}
+131
View File
@@ -0,0 +1,131 @@
import assert from "node:assert/strict";
import test, { after } from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
const requests = [];
let providerResponse = { choices: [{message: {content: "```mermaid\ngraph TD; A-->B\n```"}, finish_reason: "stop"}], usage: {prompt_tokens: 12, completion_tokens: 20} };
const graph = sourceHarness({
obsidian: {
Notice: class {},
arrayBufferToBase64: value => Buffer.from(value).toString("base64"),
base64ToArrayBuffer: value => Uint8Array.from(Buffer.from(value,"base64")).buffer,
requestUrl: async request => {
requests.push(request);
return {status:200,headers:{},json:providerResponse,text:JSON.stringify(providerResponse),arrayBuffer:new ArrayBuffer(0)};
},
},
"./obsidianUtils": {strictArrayBuffer: value => value.buffer ?? value},
"./debugHelper": {log: () => {}},
"src/lang/helpers": {t: key => key},
});
after(() => graph.close());
const ai = await graph.importModule(process.env.AI_BASELINE_MODULE || "src/utils/AIUtils.ts");
const {encryptPersistedAPIKeys, decryptPersistedAPIKeys} = await graph.importModule("src/utils/settingsKeyObfuscation.ts");
const {resolveStoredAPIKey} = await graph.importModule("src/utils/apiKeyStorage.ts");
function plugin(provider = "openai", model = "gpt-6.1-sol", extra = {}) {
return {app: {secretStorage: {getSecret: id => id === "test-secret" ? "fake-device-key" : null}}, settings: {
aiEnabled:true, aiProviderProfiles:{profile:{provider,apiKey:"fake-manual-key",baseURL:"https://example.invalid/v1"}},
aiTextModelConfigs:{text:{providerId:"profile",model,multimodalSupport:true,...extra}},
aiImageModelConfigs:{image:{providerId:"profile",model:"gpt-image-2.6-flare",supportedSizes:["1024x1024"],supportsPromptImageTransforms:true,supportsMaskImageEdits:true}},
aiDefaultTextModel:"text",aiDefaultMultimodalModel:"text",aiDefaultImageGenerationModel:"image",aiDefaultMaxResponseTokens:4096,aiDefaultMaxOutgoingTokens:0,
}};
}
test("OpenAI text and multimodal requests inherit configured reasoning and use completion token limits", async () => {
for(const image of [undefined,{dataURL:"data:image/png;base64,AA=="}]) {
requests.length=0;
const result = await ai.generateAIText({text:"Convert sketch to Mermaid",image,temperature:0.7}, {plugin:plugin("openai","gpt-6.1-sol",{reasoningEffort:"low"})});
assert.equal(result.response.status,200);assert.match(result.content,/mermaid/);
const body=JSON.parse(requests.at(-1).body);
assert.equal(body.reasoning_effort,"low");assert.equal(body.max_completion_tokens,4096);
assert.equal("max_tokens" in body,false);assert.equal("temperature" in body,false);
assert.equal(Array.isArray(body.messages.at(-1).content),Boolean(image));
}
});
test("Default omits effort; explicit none permits sampling; null resets a model preference", async () => {
for(const [config,override,expected,sampling] of [
[{}, {}, undefined,false], [{reasoningEffort:"low"},{reasoningEffort:null},undefined,false],
[{},{reasoningEffort:"none"},"none",true],
]) {
requests.length=0;
await ai.generateAIText({text:"Hello",temperature:0.5,...override},{plugin:plugin("openai","gpt-6.1-terra",config)});
const body=JSON.parse(requests.at(-1).body);
assert.equal(body.reasoning_effort,expected);assert.equal("temperature" in body,sampling);
}
});
test("unsupported efforts fail before transport and a raw model override cannot inherit another model's effort", async () => {
requests.length=0;
const result=await ai.generateAIText({text:"Hello"},{plugin:plugin("openai","gpt-6.1-sol",{reasoningEffort:"none"})});
assert.equal(result.response.status,400);assert.equal(requests.length,0);
await ai.generateAIText({text:"Hello",model:"gpt-4o"},{plugin:plugin("openai","gpt-6.1-sol",{reasoningEffort:"low"})});
assert.equal("reasoning_effort" in JSON.parse(requests.at(-1).body),false);
});
test("all provider text pipelines normalize responses without OpenAI reasoning fields leaking", async () => {
for(const [provider,model,json] of [
["anthropic","claude-sonnet-5-5",{content:[{type:"text",text:"done"}],usage:{input_tokens:2,output_tokens:3}}],
["google","gemini-3.8-flash",{candidates:[{content:{parts:[{text:"done"}]}}]}],
["xai","grok-4.7",{choices:[{message:{content:"done"}}]}],
["openai-compatible","custom-model",{choices:[{message:{content:"done"}}]}],
]) {
providerResponse=json;requests.length=0;
const result=await ai.generateAIText({text:"Hi",reasoningEffort:"low"},{plugin:plugin(provider,model,{reasoningEffort:"high"})});
assert.equal(result.content,"done",provider);
assert.equal("reasoning_effort" in JSON.parse(requests.at(-1).body),false,provider);
}
});
test("keys are resolved live; a missing secret never falls back or sends a request; snapshots reveal no keys", async () => {
const p=plugin();Object.assign(p.settings.aiProviderProfiles.profile,{apiKeySource:"secret",apiKeySecret:"test-secret"});
providerResponse={choices:[{message:{content:"done"}}]};requests.length=0;
await ai.generateAIText({text:"Hi"},{plugin:p});
assert.equal(requests.at(-1).headers.Authorization,"Bearer fake-device-key");
assert.equal(p.settings.aiProviderProfiles.profile.apiKey,"fake-manual-key");
const snapshot=ai.getAISettings(p);assert.equal(snapshot.providerProfiles.profile.hasApiKey,true);
assert.doesNotMatch(JSON.stringify(snapshot),/fake-device-key|fake-manual-key|test-secret/);
p.app.secretStorage.getSecret=()=>null;requests.length=0;
const result=await ai.generateAIText({text:"Hi"},{plugin:p});assert.equal(result.response.status,401);assert.equal(requests.length,0);
assert.equal(ai.getAISettings(p).providerProfiles.profile.hasApiKey,false);
assert.equal(resolveStoredAPIKey({},p.settings.aiProviderProfiles.profile),"");
});
test("persisted secret references contain no key values while manual keys round-trip obfuscated", () => {
const settings={future:{unknown:0},aiProviderProfiles:{manual:{provider:"openai",apiKey:"fake-manual",baseURL:"custom"},secret:{provider:"openai",apiKey:"must-remove",baseURL:"custom",apiKeySource:"secret",apiKeySecret:"test-secret"}},taskboneAPIkey:"must-remove-too",taskboneAPIKeySource:"secret",taskboneAPIKeySecret:"ocr-secret"};
const disk=encryptPersistedAPIKeys(settings);
assert.match(disk.aiProviderProfiles.manual.apiKey,/^ex-obf:v1:/);assert.equal(disk.aiProviderProfiles.secret.apiKey,"");assert.equal(disk.taskboneAPIkey,"");
assert.equal(disk.aiProviderProfiles.secret.apiKeySecret,"test-secret");assert.deepEqual(disk.future,{unknown:0});
assert.equal(decryptPersistedAPIKeys(disk).aiProviderProfiles.manual.apiKey,"fake-manual");
assert.equal(settings.aiProviderProfiles.secret.apiKey,"must-remove");
});
test("current image providers generate and edit through their actual payload and response adapters",async()=>{
const dataURL="data:image/png;base64,AA==";
for(const [provider,model,json] of [
["openai","gpt-image-2.6-flare",{data:[{b64_json:"AA=="}]}],
["openai","gpt-image-2.6-sunburst",{data:[{b64_json:"AA=="}]}],
["google","gemini-3.1-flash-image",{candidates:[{content:{parts:[{inlineData:{mimeType:"image/png",data:"AA=="}}]}}]}],
["google","gemini-3.1-flash-lite-image",{candidates:[{content:{parts:[{inlineData:{mimeType:"image/png",data:"AA=="}}]}}]}],
["google","gemini-3-pro-image",{candidates:[{content:{parts:[{inlineData:{mimeType:"image/png",data:"AA=="}}]}}]}],
["xai","grok-imagine-image-2.0",{data:[{url:"https://example.invalid/output.png"}]}],
]) {
providerResponse=json;
const p=plugin(provider);p.settings.aiImageModelConfigs.image.model=model;
p.settings.aiImageModelConfigs.image.supportsMaskImageEdits=provider==="openai";
for(const editing of [false,true]){
requests.length=0;
const result=await (editing?ai.transformAIImage:ai.generateAIImage)({text:"A blue rectangle",...(editing?{image:dataURL}:{}),imageGenerationProperties:{size:"1024x1024",n:1}},{plugin:p});
assert.equal(result.response.status,200,model);assert.equal(result.images.length,1,model);assert.ok(result.firstImage.dataURL||result.firstImage.url,model);
const request=requests.at(-1);
if(provider==="google"){
const body=JSON.parse(request.body);assert.ok(body.contents);assert.equal(body.generationConfig.imageConfig.aspectRatio,"1:1");
assert.equal(body.generationConfig.imageConfig.imageSize,"1K");
}else if(provider==="xai"){
const body=JSON.parse(request.body);assert.equal(body.aspect_ratio,"1:1");assert.equal("size" in body,false);assert.equal(Boolean(body.image),editing);
}else if(editing){
assert.match(request.url,/images\/edits$/);assert.match(request.contentType,/multipart\/form-data/);
}else{
const body=JSON.parse(request.body);assert.equal(body.model,model);assert.equal(body.size,"1024x1024");assert.equal("response_format" in body,false);
}
}
if(provider==="openai"){
requests.length=0;const result=await ai.maskEditAIImage({text:"Change color",image:dataURL,imageGenerationProperties:{size:"1024x1024",mask:dataURL}},{plugin:p});
assert.equal(result.response.status,200);const body=new TextDecoder().decode(requests.at(-1).body);assert.match(body,/name="mask"/);assert.match(body,/name="image"/);
}
}
});
@@ -0,0 +1,89 @@
import assert from "node:assert/strict";
import test, { after } from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
const notices=[];
class Element {
children=[]; controls=[]; visible=true;
ownerDocument={addEventListener(){},removeEventListener(){}};
empty(){this.children=[];this.controls=[];}
createDiv(){const child=new Element();this.children.push(child);return child;}
createEl(){return this.createDiv();}
addEventListener(){} removeEventListener(){}
}
class Control {
options={};inputEl={addEventListener(){}};
addOption(key,value){this.options[key]=value;return this;}
setValue(value){this.value=value;return this;}
onChange(callback){this.change=callback;return this;}
onClick(callback){this.click=callback;return this;}
setPlaceholder(){return this;} setDisabled(value){this.disabled=value;return this;}
setButtonText(){return this;} setCta(){return this;}
}
class Setting {
constructor(container){this.settingEl=new Element();container.children.push(this.settingEl);container.controls.push(this);}
setName(name){this.name=name;return this;} setDesc(){return this;}
addDropdown(cb){this.dropdown=new Control();cb(this.dropdown);return this;}
addText(cb){this.text=new Control();cb(this.text);return this;}
addToggle(cb){this.toggle=new Control();cb(this.toggle);return this;}
addButton(cb){cb(new Control());return this;}
}
class Modal {
constructor(app){this.app=app;this.contentEl=new Element();this.containerEl=new Element();}
close(){this.closed=true;}
}
const graph=sourceHarness({
obsidian:{Setting,Modal,Notice:class{constructor(value){notices.push(value);}}},
"src/lang/helpers":{t:key=>key},
"src/utils/modifierkeyHelper":{isWinCTRLorMacCMD:()=>false},
"src/utils/styleUtils":{hideElement:el=>{el.visible=false;},showElement:el=>{el.visible=true;}},
});
after(()=>graph.close());
const {AIModelConfigModal}=await graph.importModule("src/shared/Dialogs/AIModelConfigModal.ts");
const {AIProviderProfileModal}=await graph.importModule("src/shared/Dialogs/AIProviderProfileModal.ts");
const {renderAPIKeySettings}=await graph.importModule("src/shared/components/apiKeySettings.ts");
function find(root,name){for(const control of root.controls)if(control.name===name)return control;for(const child of root.children){const value=find(child,name);if(value)return value;}}
test("reasoning dropdown filters models, preserves edits across provider changes and blocks invalid saves",async()=>{
const saves=[],modal=new AIModelConfigModal({},[],(...args)=>saves.push(args),{kind:"text",providerIds:["openai","google"],providerProfiles:{openai:{provider:"openai"},google:{provider:"google"}},initialModelId:"test",initialConfig:{providerId:"openai",model:"gpt-6.1-sol",reasoningEffort:"low",futureField:42}});
modal.onOpen();
let reasoning=find(modal.contentEl,"AI_REASONING_NAME");assert.deepEqual(Object.keys(reasoning.dropdown.options),["","low","medium","high","xhigh","max"]);
find(modal.contentEl,"AI_MODEL_CONFIG_MODAL_PROVIDER_NAME").dropdown.change("google");assert.equal(find(modal.contentEl,"AI_REASONING_NAME"),undefined);
find(modal.contentEl,"AI_MODEL_CONFIG_MODAL_PROVIDER_NAME").dropdown.change("openai");
assert.equal(find(modal.contentEl,"AI_REASONING_NAME").dropdown.value,"low");
find(modal.contentEl,"AI_MODEL_CONFIG_MODAL_MODEL_NAME").text.change("gpt-6.1-terra");
reasoning=find(modal.contentEl,"AI_REASONING_NAME");assert.ok("none" in reasoning.dropdown.options);reasoning.dropdown.change("none");
find(modal.contentEl,"AI_MODEL_CONFIG_MODAL_MODEL_NAME").text.change("gpt-6.1-sol");
await modal.save();assert.equal(saves.length,0);assert.equal(notices.at(-1),"AI_REASONING_INVALID");
find(modal.contentEl,"AI_REASONING_NAME").dropdown.change("");await modal.save();
assert.equal(saves[0][1].reasoningEffort,undefined);assert.equal(saves[0][1].futureField,42);modal.onClose();
});
test("unknown model names offer only API default and image models do not gain a text control",()=>{
for(const [kind,model] of [["text","custom"],["image","gpt-image-2.6-flare"]]){
const modal=new AIModelConfigModal({},[],()=>{}, {kind,providerIds:["openai"],providerProfiles:{openai:{provider:"openai"}},initialConfig:{providerId:"openai",model}});
modal.onOpen();const control=find(modal.contentEl,"AI_REASONING_NAME");
if(kind==="text")assert.deepEqual(Object.keys(control.dropdown.options),[""]);else assert.equal(control,undefined);
modal.onClose();
}
});
test("credential source changes remove the synced key and store only the selected reference",()=>{
const root=new Element(),config={apiKey:"fake-original"};let changes=0;
renderAPIKeySettings({secretStorage:{listSecrets:()=>["fake-secret"]}},root,config,()=>changes++,{name:"key",description:"description"});
find(root,"API_KEY_SOURCE_NAME").dropdown.change("secret");
assert.equal(config.apiKey,"");assert.equal(find(root,"key").settingEl.visible,false);
find(root,"API_KEY_SECRET_NAME").dropdown.change("fake-secret");assert.equal(config.apiKeySecret,"fake-secret");assert.equal(changes,2);
find(root,"API_KEY_SOURCE_NAME").dropdown.change("settings");assert.equal(find(root,"key").settingEl.visible,true);
assert.equal(find(root,"key").text.value,"");
});
test("old hosts keep manual keys usable and retain an unavailable stored secret choice",()=>{
for(const source of ["settings","secret"]){const root=new Element(),config={apiKey:"manual",apiKeySource:source,apiKeySecret:"missing"};
renderAPIKeySettings({},root,config,()=>{}, {name:"key",description:"description"});
const dropdown=find(root,"API_KEY_SOURCE_NAME").dropdown;assert.equal("secret" in dropdown.options,source==="secret");
assert.equal(find(root,"API_KEY_SECRET_NAME").dropdown.disabled,true);assert.equal(config.apiKeySource,source);
}
});
test("profile edits preserve unknown fields and require a secret reference before saving",async()=>{
const saved=[],modal=new AIProviderProfileModal({},[],(...args)=>saved.push(args),{initialProfileId:"profile",initialProfile:{provider:"openai",apiKey:"fake",baseURL:"custom",future:99}});
modal.onOpen();find(modal.contentEl,"API_KEY_SOURCE_NAME").dropdown.change("secret");await modal.save();assert.equal(saved.length,0);assert.equal(notices.at(-1),"API_KEY_SECRET_SELECT");
find(modal.contentEl,"API_KEY_SECRET_NAME").dropdown.change("selected");await modal.save();assert.equal(saved[0][1].future,99);assert.equal(saved[0][1].apiKey,"");modal.onClose();
});
+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],
);
});
@@ -0,0 +1,61 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
import { embedTestDOM } from "./embedTestDOM.mjs";
test("creation actions default to visible, respect independent opt-outs and release their listeners", async () => {
const dom = embedTestDOM(), events = new Set(), created = [], errors = [];
dom.Element.prototype.contains = function (node) { return node === this || this.children.some(child => child.contains(node)); };
class Component extends dom.Component { registerEvent(ref) { this.register(() => events.delete(ref)); } }
const graph = sourceHarness({
obsidian: { Component, setIcon: (el, icon) => { el.icon = icon; } },
"src/constants/constants": { ICON_NAME: "excalidraw" }, "src/lang/helpers": { t: key => key },
"src/utils/fileUtils": { getDrawingFilename: settings => settings.drawingFilenamePrefix + ".excalidraw.md" },
"src/utils/coreUtils": { errorlog: error => errors.push(error) },
"src/utils/styleUtils": { hideElement: el => el.addClass("hidden"), showElement: el => el.removeClass("hidden") },
"src/types/utilTypes": { PreviewImageType: { SVG: "SVG" } },
"src/utils/pens": { PENS: {} },
"src/utils/carveout": { ANNOTATED_PREFIX: "Annotated", CROPPED_PREFIX: "Cropped" },
"src/utils/geminiImageModelUtils": { getGeminiSupportedSizes: () => [] },
});
const container = new dom.Element(), list = container.createDiv({ cls: "empty-state-action-list" });
const existing = list.createEl("button", { text: "New note" });
const leaf = { view: { containerEl: container, getViewType: () => "empty" } };
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; }); } };
const ribbon = new dom.Element();
const previousVersion = globalThis.PLUGIN_VERSION;
try {
globalThis.PLUGIN_VERSION = "test";
const { DEFAULT_SETTINGS } = await graph.importModule("src/core/settingsDefaults.ts");
assert.equal(DEFAULT_SETTINGS.showRibbonIcon, true);
assert.equal(DEFAULT_SETTINGS.showNewDrawingInEmptyTab, true);
plugin.settings = { ...DEFAULT_SETTINGS, drawingFilenamePrefix: "Configured" };
const { DrawingCreationUI } = await graph.importModule("src/core/managers/DrawingCreationUI.ts");
const manager = new DrawingCreationUI(plugin, () => {}); manager.load(); manager.refresh();
assert.equal(list.children.length, 2); assert.equal(ribbon.hasClass("hidden"), false);
plugin.settings.showNewDrawingInEmptyTab = false; manager.refresh();
assert.deepEqual(list.children, [existing]); assert.equal(ribbon.hasClass("hidden"), false);
plugin.settings.showRibbonIcon = false; plugin.settings.showNewDrawingInEmptyTab = true; manager.refresh();
assert.equal(ribbon.hasClass("hidden"), true); assert.equal(list.children.length, 2);
const button = list.querySelector(".excalidraw-new-drawing");
const observer = dom.observers.at(-1);
button.fire("click"); button.fire("click");
assert.equal(active, leaf); assert.deepEqual(created, [["Configured.excalidraw.md", "active-pane"]]);
resolveCreation(""); await new Promise(resolve => setImmediate(resolve)); assert.equal(button.disabled, false);
list.empty(); observer.fire(); observer.fire(); assert.deepEqual(list.children, [button]);
plugin.settings.showNewDrawingInEmptyTab = false; manager.refresh();
assert.equal(button.isConnected, false); assert.equal(observer.connected, false);
plugin.settings.showNewDrawingInEmptyTab = true; manager.refresh(); leaves = []; manager.refresh();
assert.equal(list.children.length, 0); assert.equal(ribbonCount, 1);
manager.unload(); plugin.app.workspace.ready(); assert.equal(ribbon.isConnected, false);
assert.ok(dom.observers.every(observer => !observer.connected));
assert.equal(events.size, 0); assert.equal(dom.listenerCount(), 0); assert.deepEqual(errors, []);
} finally {
graph.close();
if (previousVersion === undefined) delete globalThis.PLUGIN_VERSION;
else globalThis.PLUGIN_VERSION = previousVersion;
}
});
@@ -0,0 +1,116 @@
import assert from "node:assert/strict";
import test from "node:test";
import vm from "node:vm";
import { readFileSync } from "node:fs";
import ts from "typescript";
import { sourceHarness } from "./sourceHarness.mjs";
function productionScale() {
const compile = (path, dependencies = {}) => {
const source = readFileSync(new URL("../../" + path, import.meta.url), "utf8"), exports = {};
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText;
vm.runInNewContext(code, { exports, require: name => dependencies[name] ?? {}, Date }); return exports;
};
return compile("src/utils/utils.ts", {
"../constants/constants": { EXCALIDRAW_PLUGIN: null, mutateElement: (el, _map, patch) => Object.assign(el, patch) },
"./elementCustomDataUtils": compile("src/utils/elementCustomDataUtils.ts"),
"./collectionUtils": { arrayToMap: elements => new Map(elements.map(el => [el.id, el])) },
"src/types/markdownImageTypes": { MARKDOWN_IMAGE_CUSTOM_DATA_KEY: "markdownImage" },
"roughjs/bin/math": { Random: class {} },
}).scaleLoadedImage;
}
async function fixture() {
const prompts = [], errors = [], notices = [], renders = [], history = [], registry = new Map(), payloads = [];
const file = { path: "Host.md" }, drawing = { path: "Source.md", basename: "Source <drawing>" };
const graph = sourceHarness({ obsidian: { Notice: class { constructor(value) { notices.push(value); } }, parseYaml: () => ({}) },
"src/constants/constants": { CaptureUpdateAction: { IMMEDIATELY: "IMMEDIATELY" }, getCommonBoundingBox() {}, fileid: () => "new-" + registry.size + "-" + renders.length },
"src/shared/Dialogs/DrawingImagePreviewPopover": { DrawingImagePreviewPopover: class {} },
"src/lang/helpers": { t: key => key === "PREVIEW_SHARED_HELP" ? '“{drawing}” appears in {count} images in this scene.' : key },
"src/utils/coreUtils": { errorlog: error => errors.push(error) },
});
const { DrawingImagePreviewController } = await graph.importModule("src/view/managers/DrawingImagePreviewController.ts");
const { getDrawingPreviewParts } = await graph.importModule("src/utils/drawingPreviewLink.ts");
class Descriptor {
file = drawing; isMarkdownSection = false; colorMap = null;
constructor(_plugin, _host, link) { this.linkParts = { original: link }; }
shouldScale() { return !this.linkParts.original.endsWith("|100%"); }
setImage(image) { this.image = image; }
}
class Loader {
async getObsidianImage(descriptor) {
renders.push(descriptor.linkParts.original); if (pause) await pause;
const parts = getDrawingPreviewParts(descriptor.linkParts.original), p = parts.padding ?? 0;
const size = parts.blockref === "tall" ? { width: 100 + 2*p, height: 300 + 2*p } : { width: 300 + 2*p, height: 100 + 2*p };
return { fileId: "generated", mimeType: "image/svg+xml", dataURL: "data:image/svg+xml;base64,AA==", created: 1, hasSVGwithBitmap: false, size };
}
}
class Prompt {
titleEl = { setText() {} };
constructor(_plugin, message, buttons) { this.message = message; this.buttons = buttons; this.waitForClose = new Promise(resolve => { this.choose = resolve; }); prompts.push(this); }
close() { this.choose(null); }
}
const source = new Descriptor(null, null, "Source.md"); registry.set("shared", source);
registry.set("other", new Descriptor(null, null, "Source.md#^frame=tall,padding=20|100%"));
const image = (id, fileId, x, width, height) => ({ id, fileId, type: "image", x, y: 10, width, height, version: 1, versionNonce: 1, customData: { retained: true }, crop: null });
let elements = [image("one", "shared", 0, 300, 100), image("two", "shared", 400, 150, 50), image("three", "other", 650, 100, 300)], alive = true, pause;
const api = { getAppState: () => ({ theme: "light" }), addFiles: data => payloads.push(data) };
const view = { file, excalidrawAPI: api, plugin: { _loaded: true, isExcalidrawFile: candidate => candidate === drawing },
excalidrawData: { getFile: id => registry.get(id), setFile: (id, value) => registry.set(id, value) },
getViewElements: () => elements, updateScene: update => { history.push(elements); elements = update.elements; }, setDirty() {},
};
const controller = new DrawingImagePreviewController(view, { Prompt, EmbeddedFile: Descriptor, EmbeddedFilesLoader: Loader, scaleLoadedImage: productionScale() });
return { controller, source, view, prompts, errors, notices, renders, registry, payloads, elements: () => elements,
async apply(changes, choice = "one") { const result = controller.apply("one", source, changes, () => alive); prompts.at(-1).choose(choice); return await result; },
undo() { elements = history.pop(); }, retire() { alive = false; controller.reset(); },
pause() { let resume; pause = new Promise(resolve => { resume = resolve; }); return resume; },
changeTarget() { elements = elements.map(el => el.id === "one" ? { ...el, version: 10 } : el); },
close() { controller.reset(); graph.close(); },
};
}
test("only this image gets a new persisted link and uses real external-update geometry; undo retains the original reference", async () => {
const f = await fixture();
try {
assert.equal(await f.apply({ frame: "tall", padding: 30 }), true);
const [one, two, three] = f.elements();
assert.notEqual(one.fileId, "shared"); assert.equal(two.fileId, "shared"); assert.equal(three.fileId, "other");
assert.equal(f.registry.get(one.fileId).linkParts.original, "Source.md#^frame=tall,padding=30");
assert.ok(Math.abs(one.width * one.height - 30000) < .001); assert.equal(one.x + one.width/2, 150); assert.equal(one.y + one.height/2, 60);
assert.equal(one.customData.retained, true); assert.equal(f.payloads.length, 1);
assert.match(f.prompts[0].message, /Source &lt;drawing&gt;/); assert.doesNotMatch(f.prompts[0].message, /fileId|shared/);
f.undo(); assert.equal(f.elements()[0].fileId, "shared"); assert.equal(f.registry.get("shared").linkParts.original, "Source.md");
} finally { f.close(); }
});
test("apply to all copies changes only edited fields, preserving distinct views, anchoring and each image center", async () => {
const f = await fixture();
try {
const old = f.elements().map(el => ({ center: [el.x+el.width/2,el.y+el.height/2], area: el.width*el.height }));
assert.equal(await f.apply({ padding: 50 }, "all"), true);
const elements = f.elements(); assert.equal(elements[0].fileId, elements[1].fileId);
assert.equal(f.registry.get(elements[0].fileId).linkParts.original, "Source.md#^as-image,padding=50");
assert.equal(f.registry.get(elements[2].fileId).linkParts.original, "Source.md#^frame=tall,padding=50|100%");
for (let i=0;i<3;i++) { const el=elements[i]; assert.deepEqual([el.x+el.width/2,el.y+el.height/2],old[i].center); if(i<2)assert.ok(Math.abs(el.width*el.height-old[i].area)<.001); }
assert.equal(elements[2].width, 200); assert.equal(elements[2].height, 400); assert.equal(elements[2].customData.isAnchored, true);
} finally { f.close(); }
});
test("100% anchoring follows rendered intrinsic dimensions and remains in the link", async () => {
const f = await fixture();
try { assert.equal(await f.apply({ anchored: true }), true); const el=f.elements()[0];
assert.equal(f.registry.get(el.fileId).linkParts.original, "Source.md|100%"); assert.equal(el.width,300); assert.equal(el.height,100); assert.equal(el.customData.isAnchored,true);
} finally { f.close(); }
});
test("cancel, stale scene changes and retired views do not register partial links or write a scene", async () => {
for (const kind of ["cancel", "changed", "retired"]) {
const f=await fixture();
try {
if(kind==='cancel')assert.equal(await f.apply({padding:20},null),false);
else {const resume=f.pause(), pending=f.apply({padding:20}); await new Promise(resolve=>setImmediate(resolve));
if(kind==='changed')f.changeTarget();else f.retire(); resume(); assert.equal(await pending,false);}
assert.equal(f.registry.size,2); assert.equal(f.payloads.length,0); assert.equal(f.elements()[0].fileId,'shared');
} finally {f.close();}
}
});
@@ -0,0 +1,44 @@
import assert from "node:assert/strict";
import test from "node:test";
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 graph = sourceHarness({
"src/constants/constants": constants, "../constants/constants": constants,
"../utils/sceneDataUtils": { compress() {}, compressAsync() {}, updateFrontmatterInString() {}, decompress: value => LZString.decompressFromBase64(value.replace(/\s/g, "")) },
"../utils/obsidianUtils": { isObsidianThemeDark: false },
});
const { getDrawingPaddingMax } = await graph.importModule("src/utils/drawingPadding.ts");
const { readDrawingPreviewElements } = await graph.importModule("src/utils/drawingPreviewScene.ts");
test.after(() => graph.close());
const bounds = elements => ({ minX: Math.min(...elements.map(el => el.x)), minY: Math.min(...elements.map(el => el.y)),
maxX: Math.max(...elements.map(el => el.x + el.width)), maxY: Math.max(...elements.map(el => el.y + el.height)) });
const rect = (id, x, y, width, height, extra = {}) => ({ id, type: "rectangle", x, y, width, height, ...extra });
test("area range covers off-center scene edges beyond 2000 and ignores deleted elements", () => {
const elements = [rect("area",200,50,100,100),rect("left",-900,-500,20,20),rect("far",6000,4000,200,200),rect("deleted",1e9,1e9,1,1,{isDeleted:true})];
assert.equal(getDrawingPaddingMax(elements,"Draw#^area=area,padding=0",bounds),6000);
assert.equal(getDrawingPaddingMax(elements,"Draw#^area=area,padding=999",bounds),6000,"current padding must not affect the limit");
assert.equal(getDrawingPaddingMax(elements,"Draw#^frame=area",bounds),100);
assert.equal(getDrawingPaddingMax(elements,"Draw",bounds),100);
assert.equal(getDrawingPaddingMax(elements,"Draw#^area=missing",bounds),100);
const withText = [rect("box",-100,-100,400,300),rect("text",0,0,20,20,{type:"text",containerId:"box"}),rect("far",1000,0,10,10)];
assert.equal(getDrawingPaddingMax(withText,"Draw#^area=text",bounds),810,"bound text uses the same container as the zero-padding crop");
});
test("padding geometry reads plain, compressed and legacy saved scenes without resolving embeds", async () => {
const scene={elements:[rect("area",0,0,100,100),rect("saved-text",300,0,23,20,{type:"text",text:"Saved text"}),rect("deleted",999,0,1,1,{isDeleted:true})]};
const json=JSON.stringify(scene), sources=[
`# Text Elements\nA changed embedded note ^saved-text\n\n## Drawing\n\x60\x60\x60json\n${json}\n\x60\x60\x60\n`,
`\n## Drawing\n\x60\x60\x60compressed-json\n${LZString.compressToBase64(json)}\n\x60\x60\x60\n`,json,
];
let reads=0;
for(let index=0;index<sources.length;index++){
const vault={cachedRead:async()=>{reads++;return sources[index];}};
const elements=await readDrawingPreviewElements(vault,{extension:index===2?"excalidraw":"md"});
assert.equal(elements.length,2);assert.equal(elements[1].text,"Saved text");assert.equal(elements[1].width,23);
}
assert.equal(reads,3);
await assert.rejects(readDrawingPreviewElements({cachedRead:async()=>'{"elements":null}'},{extension:"excalidraw"}));
});
@@ -0,0 +1,37 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
const graph = sourceHarness({ "./pathUtils": { cleanBlockRef: value => value, cleanSectionHeading: value => value } });
const { rewriteDrawingPreviewLink: rewrite, getDrawingPreviewParts: parts } = await graph.importModule("src/utils/drawingPreviewLink.ts");
const { getEmbeddedFileMasterLink: restore } = await graph.importModule("src/utils/linkUtils.ts");
const { getThumbnailPaddingConfig } = await graph.importModule("src/utils/thumbnailPadding.ts");
test.after(() => graph.close());
test("thumbnail and whole-scene padding remain independent of frame selection and anchoring", () => {
assert.equal(rewrite("Draw.md", { padding: 40 }), "Draw.md#^as-image,padding=40");
assert.equal(rewrite("Draw.md#^group=abc", { padding: 40 }), "Draw.md#^group=abc,padding=40");
assert.equal(parts("Draw.md#^as-image,padding=40|100%").blockref, "as-image");
assert.equal(parts("Draw.md#^as-image,padding=40|100%").padding, 40);
assert.equal(rewrite("Draw.md#^frame=,padding=40|100%", { frame: null }), "Draw.md#^as-image,padding=40|100%");
assert.equal(rewrite("Draw.md#^as-image,padding=40|100%", { frame: "b" }), "Draw.md#^frame=b,padding=40|100%");
assert.equal(rewrite("Draw.md#^frame=b,padding=40|100%", { padding: null }), "Draw.md#^frame=b|100%");
assert.equal(rewrite("Draw.md#^frame=b,padding=40|100%", { anchored: false }), "Draw.md#^frame=b,padding=40");
assert.equal(rewrite("100% ../Draw.md#^area=a|Caption", { anchored: true }), "100% ../Draw.md#^area=a|Caption|100%");
});
test("preview changes preserve raw encoding, padding, other aliases and the shared master-map link", () => {
const old = "../Draw%20one%23%5Eclippedframe%3DOld%2Cpadding%3D00%2E50|Alias|100%";
assert.equal(rewrite(old, { frame: "new" }), "../Draw%20one%23%5Eclippedframe%3Dnew%2Cpadding%3D00%2E50|Alias|100%");
assert.equal(rewrite("Draw.md#^frame=Part,padding=10, two", { padding: 20 }), "Draw.md#^frame=Part,padding=10, two,padding=20");
assert.equal(restore("Draw.md|100%", "^as-image,padding=40|100%"), "Draw.md#^as-image,padding=40|100%");
assert.equal(restore("Draw.md|100%", "^frame=b,padding=40"), "Draw.md#^frame=b,padding=40|100%");
assert.equal(restore("Draw.md", "^frame=b,padding=40|Caption"), "Draw.md#^frame=b,padding=40|Caption");
assert.equal(restore("Draw.md|100%", null), "Draw.md|100%");
});
test("outer thumbnail padding enlarges the viewport while retaining the original frame clip", () => {
const frame = { id: "f", x: 100, y: 200, width: 300, height: 150 };
const config = getThumbnailPaddingConfig({ exportingFrame: frame, withBackground: false, withTheme: true }, { theme: "dark" }, 25, 2);
assert.deepEqual(config, { exportingFrame: frame, padding: 0, scale: 2, fit: "none", origin: "canvas", x: 75, y: 175, width: 350, height: 200, theme: "dark", canvasBackgroundColor: false });
assert.equal(config.exportingFrame, frame);
});
@@ -0,0 +1,39 @@
import assert from "node:assert/strict";
import test from "node:test";
import vm from "node:vm";
import { readFileSync } from "node:fs";
import ts from "typescript";
const compile = (path, dependencies = {}) => {
const code = ts.transpileModule(readFileSync(new URL("../../" + path, import.meta.url), "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText;
const exports = {}; vm.runInNewContext(code, { exports, require: name => dependencies[name] ?? {} }); return exports;
};
const parts = compile("src/utils/embeddedFilenameParts.ts");
const links = compile("src/utils/linkUtils.ts", { "./pathUtils": { cleanBlockRef: value => value, cleanSectionHeading: value => value } });
const { EmbeddedFile } = compile("src/shared/EmbeddedFileLoader.ts", {
"../utils/sceneDataUtils": links, "../utils/embeddedAssetUtils": parts, obsidian: { Notice: class {} },
});
const drawing = { path: "Folder/Draw.md", extension: "md" }, note = { path: "Note.md", extension: "md" };
const plugin = { settings: { mdSVGwidth: 500, mdSVGmaxHeight: 500 }, isExcalidrawFile: file => file === drawing,
app: { metadataCache: { getFirstLinkpathDest: path => path === "Note.md" ? note : drawing } } };
test("embedded drawing loader recognizes padded default and whole-scene links while retaining 100%", () => {
for (const [link, frame, anchored] of [
["Draw.md#^as-image,padding=40|100%", false, true],
["Draw.md#^frame=,padding=30", true, false],
["Draw.md#^frame=some-id,padding=20|100%", true, true],
]) {
const file = new EmbeddedFile(plugin, "Host.md", link);
assert.equal(file.file, drawing); assert.equal(file.filenameparts.filepath, drawing.path);
assert.equal(file.isMarkdownSection, false); assert.equal(file.filenameparts.hasFrameref, frame);
assert.equal(file.shouldScale(), !anchored); assert.equal(file.linkParts.original, link);
assert.ok(file.filenameparts.padding > 0);
}
});
test("an ordinary Markdown block named as-image keeps its section-transclusion behavior", () => {
const file = new EmbeddedFile(plugin, "Host.md", "Note.md#^as-image");
assert.equal(file.file, note); assert.equal(file.isMarkdownSection, true);
});
@@ -0,0 +1,62 @@
/** Exercise the real bridge's scheduling with public CM ranges and controlled DOM observers. */
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState, StateField } from "@codemirror/state";
import * as cmView from "@codemirror/view";
import { sourceHarness } from "./sourceHarness.mjs";
for (const tableEmbed of [false, true]) for (const selfEmbed of [false, true]) test((tableEmbed ? "table embeds with internal-embed wrappers: " : "") + (selfEmbed
? "drawing Markdown self-embeds retain controls and the same lifecycle guards"
: "invalid render generations cannot remount controls or starve the renderer debounce"), async () => {
const pending = [], originalQueue = globalThis.queueMicrotask, observers = [];
let generation = true, loaded = 0, unloaded = 0, retireWhileMapping = false;
globalThis.queueMicrotask = callback => pending.push(callback);
const drawing = { path: "Map.excalidraw.md" }, file = selfEmbed ? drawing : { path: "Source.md" };
const token = tableEmbed ? "![[Map.excalidraw.md\\|180]]" : "![[Map.excalidraw.md|180]]";
const text = tableEmbed ? `| Drawing |\n| --- |\n| ${token} |` : token;
class MarkdownView { mode = "source"; file = file; getMode() { return this.mode; } }
const info = new MarkdownView(), sourceContainer = { style: { display: "" } };
const editorInfoField = StateField.define({ create: () => info, update: value => value });
const editorLivePreviewField = StateField.define({ create: () => true, update: value => value });
const doc = { defaultView: { MutationObserver: class {
constructor(callback) { this.callback = callback; observers.push(this); }
observe(target) { this.connected = true; (this.targets ??= []).push(target); }
disconnect() { this.connected = false; }
} } };
const frame = { isConnected: true, ownerDocument: doc }, parent = { childNodes: [] };
const native = { parentNode: parent, closest: () => null, contains: el => el === frame };
const root = { parentNode: parent, closest: () => null, contains: el => el === frame };
const table = { closest: () => root, rows: [{ cells: [{}] }, { cells: [{}] }] };
const row = { parentElement: { parentElement: table }, rowIndex: 1 };
const cell = { closest: () => table, parentElement: row, colSpan: 1, rowSpan: 1, cellIndex: 0 };
parent.childNodes.push(tableEmbed ? root : native);
const contentDOM = { querySelectorAll: () => [image], contains: el => el === frame };
const image = { parentElement: frame, closest: selector => ({ ".internal-embed": native, ".cm-content": contentDOM,
"table.table-editor": tableEmbed ? table : null, "td, th": tableEmbed ? cell : null })[selector] ?? null };
const actions = { target: drawing.path, isCurrent: () => generation };
const mutation = () => { for (const observer of observers) if (observer.connected) observer.callback(); };
const graph = sourceHarness({
obsidian: { editorInfoField, editorLivePreviewField, MarkdownView },
"@codemirror/view": { ...cmView, ViewPlugin: { fromClass: value => value } },
"../managers/DrawingEmbedControls": { DrawingEmbedControls: class { load() { loaded++; mutation(); } unload() { unloaded++; mutation(); } } },
"../managers/drawingEmbedActions": { getDrawingEmbedActions: () => actions },
});
try {
const { createDrawingEmbedExtension } = await graph.importModule("src/core/editor/drawingEmbedExtension.ts");
const plugin = { isExcalidrawFile: value => value === drawing, app: { metadataCache: { getFirstLinkpathDest: () => drawing } } };
const bridge = createDrawingEmbedExtension(plugin);
const view = { dom: { ownerDocument: doc, closest: () => sourceContainer }, contentDOM, state: EditorState.create({ doc: text + "\n", extensions: [editorInfoField, editorLivePreviewField] }),
posAtDOM(el, offset) { if (retireWhileMapping) generation = false; return el === parent && offset === 1 ? text.length + 1 : 0; } };
const drain = () => { for (let i = 0; pending.length && i < 10; i++) pending.shift()(); assert.equal(pending.length, 0, "unbounded remount/mutation loop"); };
new bridge.extension(view); drain(); assert.equal(loaded, 1);
assert.ok(observers[0].targets.includes(sourceContainer), "source visibility changes must schedule ownership sync");
info.mode = "preview"; mutation(); drain(); assert.equal(loaded, 1); assert.equal(unloaded, 1);
info.mode = "source"; sourceContainer.style.display = "none"; mutation(); drain(); assert.equal(loaded, 1);
sourceContainer.style.display = ""; mutation(); drain(); assert.equal(loaded, 2);
generation = false; mutation(); drain(); assert.equal(loaded, 2); assert.equal(unloaded, 2);
generation = true; mutation(); drain(); assert.equal(loaded, 3);
generation = false; mutation(); drain();
generation = true; retireWhileMapping = true; mutation(); drain(); assert.equal(loaded, 3, "source invalidated during DOM mapping was mounted");
bridge.dispose(); drain(); assert.ok(observers.every(observer => !observer.connected));
} finally { graph.close(); globalThis.queueMicrotask = originalQueue; }
});
@@ -0,0 +1,173 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
import { embedTestDOM } from "./embedTestDOM.mjs";
async function fixture(text = "![[Map|Alias|180x130|left]]", padding = false, paddingSource = true, frames = []) {
const dom = embedTestDOM(), notices = [], modals = [], writes = [], menus = [];
class Menu {
items = []; constructor() { menus.push(this); }
setUseNativeMenu() { return this; } addSeparator() { return this; }
addItem(callback) { const item = { setTitle(value) { this.title = value; return this; }, setChecked(value) { this.checked = value; return this; }, onClick(callback) { this.click = callback; return this; } }; callback(item); this.items.push(item); return this; }
onHide(callback) { this.onHidden = callback; } showAtPosition(position, doc) { this.position = position; this.doc = doc; } hide() { this.hidden = true; this.onHidden?.(); }
}
let current = true, sourceCurrent = true, selects = 0, opens = 0;
const graph = sourceHarness({ obsidian: { Menu, Component: dom.Component, MarkdownRenderChild: dom.MarkdownRenderChild, SliderComponent: class {}, Notice: class { constructor(text) { notices.push(text); } }, setIcon(element, icon) { element.icon = icon; }, setTooltip() {} },
"src/lang/helpers": { t: key => key },
"src/utils/styleUtils": { setStyle: (el, values) => Object.assign(el.style, values), removeStyle: (el, keys) => { for (const key of keys) delete el.style[key]; } },
"src/shared/Dialogs/DrawingEmbedPreviewModal": { DrawingEmbedPreviewModal: class { constructor(_app, _preview, _opener, close) { this.onClosed = close; modals.push(this); } open() { this.active = true; } close() { this.active = false; this.onClosed(); } } },
});
const { DrawingEmbedControls } = await graph.importModule("src/core/managers/DrawingEmbedControls.ts");
const content = new dom.Element({ cls: "cm-content" }), frame = content.createDiv();
const image = frame.createEl("img", { cls: "excalidraw-embedded-img" }); image.bounds = { left: 0, top: 0, right: 180, bottom: 130, width: 180, height: 130 };
const source = { text, isCurrent: () => sourceCurrent, replace: value => { if (!sourceCurrent) return false; writes.push(value); return true; }, select: () => { selects++; return sourceCurrent; } };
if (paddingSource) source.replacePadding = () => true;
if (paddingSource) source.replaceFrame = reference => { if (!sourceCurrent) return false; writes.push(["frame", reference]); return true; };
const controls = new DrawingEmbedControls(frame, { app: {}, target: "Map", frames, isCurrent: () => current, openDrawing: () => opens++, getOpenTooltip: () => "configured open shortcuts", ...(padding ? { padding: { value: 10 } } : {}) }, source); controls.load();
const handle = frame.querySelector(".excalidraw-embed-resize-handle"), toolbar = frame.querySelector(".excalidraw-embed-toolbar");
handle.bounds = { left: 156, top: 106, right: 178, bottom: 128, width: 22, height: 22 };
const buttons = toolbar.children.filter(element => element.tagName === "BUTTON");
return { ...dom, frame, image, handle, toolbar, buttons, controls, writes, source, notices, modals, menus, current: value => current = value, sourceCurrent: value => sourceCurrent = value, selects: () => selects, opens: () => opens,
close: () => { controls.unload(); graph.close(); assert.equal(dom.listenerCount(), 0); assert.ok(dom.observers.every(observer => !observer.connected)); } };
}
function start(f) { f.handle.fire("pointerdown", { button: 0, pointerId: 1, clientX: 180, clientY: 130 }); }
test("frame picker requires editable ownership, offers unnamed frames by ID, and owns its menu document", async () => {
const frames = [{ id: "frame-a", reference: "frame-a", name: "中心,padding=50" }, { id: "frame-b", reference: "frame-b", name: null, marker: true }];
for (const writable of [true, false]) {
const f = await fixture(undefined, false, writable, frames);
try {
const trigger = f.buttons.find(button => button.getAttribute("data-excalidraw-embed-action") === "frame");
assert.equal(!!trigger, writable);
if (!trigger) continue;
assert.equal(trigger.icon, "scan-eye"); trigger.fire("click");
const menu = f.menus[0]; assert.equal(menu.doc, f.document);
assert.deepEqual(menu.items.map(item => item.title), ["FRAME_DEFAULT", "FRAME_WHOLE", "中心,padding=50", "FRAME_UNNAMED_MARKER (frame-b)"]);
assert.deepEqual(f.writes, []); menu.items[3].click(); assert.deepEqual(f.writes, [["frame", "frame-b"]]);
f.sourceCurrent(false); menu.items[1].click(); assert.equal(f.writes.length, 1);
} finally { f.close(); }
if (writable) assert.equal(f.menus[0].hidden, true);
}
});
test("padding toolbar action requires both an area-rendering capability and a writable source", async () => {
for (const area of [false, true]) for (const writable of [false, true]) {
const f = await fixture(undefined, area, writable);
try {
const button = f.buttons.find(button => button.getAttribute("data-excalidraw-embed-action") === "padding");
assert.equal(!!button, area && writable);
if (button) assert.equal(button.icon, "box-select");
}
finally { f.close(); }
}
});
test("toolbar compatibility events cannot activate the surrounding native table cell", async () => {
const f = await fixture();
try {
for (const name of ["mousedown", "touchstart"]) {
let stopped = false;
const event = f.toolbar.fire(name, { stopPropagation() { stopped = true; } });
assert.equal(stopped, true); assert.equal(event.prevented, undefined);
}
assert.deepEqual(f.writes, []); assert.equal(f.selects(), 0);
f.buttons[2].fire("click"); assert.equal(f.selects(), 1);
} finally { f.close(); }
});
test("resize previews proportionally without writing, then commits once on the owned pointer release", async () => {
const f = await fixture();
try {
start(f); f.fire(f.window, "pointermove", { pointerId: 1, clientX: 220, clientY: 130 });
assert.deepEqual(f.writes, []); assert.equal(f.frame.style["--excalidraw-embed-resize-width"], "220px");
assert.equal(Number.parseFloat(f.frame.style["--excalidraw-embed-resize-height"]), 220 / (180 / 130));
f.fire(f.window, "pointerup", { pointerId: 2 }); assert.deepEqual(f.writes, []);
f.fire(f.window, "pointerup", { pointerId: 1 });
assert.deepEqual(f.writes, ["![[Map|Alias|220x159|left]]"]); assert.equal(f.handle.captures.size, 0);
assert.equal(f.frame.hasClass("excalidraw-embed-resizing"), false);
assert.equal(f.frame.style["--excalidraw-embed-resize-height"], undefined);
} finally { f.close(); }
});
test("Escape, lost capture, stale source and visual replacement cancel without stale writes", async () => {
for (const cancel of ["escape", "capture", "source", "replace", "unload"]) {
const f = await fixture();
try {
start(f); f.fire(f.window, "pointermove", { pointerId: 1, clientX: 200, clientY: 130 });
if (cancel === "escape") f.fire(f.window, "keydown", { key: "Escape" });
if (cancel === "capture") f.handle.fire("lostpointercapture");
if (cancel === "source") f.sourceCurrent(false);
if (cancel === "replace") {
f.frame.empty(); f.frame.createEl("img", { cls: "excalidraw-embedded-img" }); f.observers[0].fire();
assert.equal(f.frame.querySelectorAll(".excalidraw-embed-toolbar").length, 1); assert.equal(f.toolbar.parentElement, f.frame);
}
if (cancel === "unload") f.controls.unload();
f.fire(f.window, "pointerup", { pointerId: 1 }); assert.deepEqual(f.writes, []); assert.equal(f.handle.captures.size, 0);
} finally { f.close(); }
}
});
test("keyboard resizing commits once on release, keeps shortcuts, and reset preserves aliases", async () => {
const f = await fixture();
try {
f.handle.fire("keydown", { key: "ArrowRight", ctrlKey: true }); assert.equal(f.frame.hasClass("excalidraw-embed-resizing"), false);
f.handle.fire("keydown", { key: "ArrowRight" }); f.handle.fire("keydown", { key: "ArrowRight" }); assert.deepEqual(f.writes, []);
f.handle.fire("keyup", { key: "ArrowRight" }); assert.deepEqual(f.writes, ["![[Map|Alias|196x142|left]]"]);
f.handle.fire("keydown", { key: "Home" }); assert.equal(f.writes.at(-1), "![[Map|Alias|left]]");
f.buttons[2].fire("click"); assert.equal(f.selects(), 1);
f.buttons[1].fire("click"); assert.equal(f.opens(), 1);
f.buttons[0].fire("click"); assert.equal(f.modals[0].active, true);
} finally { f.close(); }
assert.equal(f.modals[0].active, false);
});
test("cancel and viewport changes restore controls to the visible image corner", async () => {
const f = await fixture();
try {
const originalFrame = { ...f.frame.bounds }, originalImage = { ...f.image.bounds };
f.frame.getBoundingClientRect = () => f.frame.hasClass("excalidraw-embed-resizing") ? { ...originalFrame, right: 220, width: 220, bottom: 159, height: 159 } : originalFrame;
f.image.getBoundingClientRect = () => f.frame.hasClass("excalidraw-embed-resizing") ? { ...originalImage, right: 220, width: 220, bottom: 159, height: 159 } : originalImage;
start(f); f.fire(f.window, "pointermove", { pointerId: 1, clientX: 220, clientY: 130 });
assert.equal(f.frame.style["--excalidraw-embed-control-right"], "2px");
f.fire(f.window, "keydown", { key: "Escape" });
assert.equal(f.frame.style["--excalidraw-embed-control-right"], "522px"); assert.deepEqual(f.writes, []);
originalImage.left = 50; originalImage.right = 230; f.fire(f.window, "resize");
assert.equal(f.frame.style["--excalidraw-embed-toolbar-right"], "474px");
assert.equal(f.frame.style["--excalidraw-embed-control-right"], "472px");
} finally { f.close(); }
});
test("a full-width no-op retains percentage syntax and a replacement gesture uses restored dimensions", async () => {
const f = await fixture("![[Map|100%]]");
try {
f.frame.parentElement.bounds.right = 180;
start(f); f.fire(f.window, "pointermove", { pointerId: 1, clientX: 200, clientY: 130 });
f.fire(f.window, "pointerup", { pointerId: 1 }); assert.deepEqual(f.writes, []);
f.frame.parentElement.bounds.right = 700;
const original = { ...f.image.bounds };
f.image.getBoundingClientRect = () => f.frame.hasClass("excalidraw-embed-resizing") ? { ...original, width: Number.parseFloat(f.frame.style["--excalidraw-embed-resize-width"]), height: Number.parseFloat(f.frame.style["--excalidraw-embed-resize-height"]) } : original;
start(f); f.fire(f.window, "pointermove", { pointerId: 1, clientX: 220, clientY: 130 });
f.handle.fire("pointerdown", { button: 0, pointerId: 2, clientX: 180, clientY: 130 });
f.fire(f.window, "pointermove", { pointerId: 2, clientX: 188, clientY: 130 });
f.fire(f.window, "pointerup", { pointerId: 2 }); assert.deepEqual(f.writes, ["![[Map|188]]"]);
} finally { f.close(); }
});
test("late image sizing leaves the toolbar inside paint containment and remeasures the changed frame", async () => {
const f = await fixture();
try {
f.toolbar.bounds = { ...f.toolbar.bounds, width: 142, height: 40 };
f.frame.getBoundingClientRect = () => ({ ...f.frame.bounds, bottom: f.frame.hasClass("excalidraw-embed-controls-below") ? 170 : 130 });
f.image.bounds = { ...f.image.bounds, bottom: 0, height: 0 };
f.frame.fire("load"); assert.equal(f.frame.hasClass("excalidraw-embed-controls-below"), true);
f.image.bounds = { ...f.image.bounds, bottom: 130, height: 130 };
const observer = f.observers.find(observer => observer.resize); assert.equal(observer.target, f.image);
observer.fire(); observer.fire();
assert.equal(f.pendingFrames(), 1); assert.equal(f.frame.hasClass("excalidraw-embed-controls-below"), true);
f.flushFrames(); assert.equal(f.frame.hasClass("excalidraw-embed-controls-below"), false);
assert.equal(f.frame.style["--excalidraw-embed-control-top"], "4px");
assert.equal(f.frame.style["--excalidraw-embed-control-bottom"], "2px");
observer.fire(); assert.equal(f.pendingFrames(), 1);
} finally { f.close(); }
assert.equal(f.pendingFrames(), 0); f.flushFrames();
});
@@ -0,0 +1,52 @@
import assert from 'node:assert/strict';
import test,{after} from 'node:test';
import {sourceHarness} from './sourceHarness.mjs';
const graph=sourceHarness();
const {rewriteEmbedDimensions:edit,getEmbedDimensions,readDrawingEmbedToken,parseEmbedAlias}=await graph.importModule('src/core/editor/embedDimensions.ts');
after(()=>graph.close());
for(const [source,size,expected] of [
['![[Map.excalidraw.md#^area=foo,padding=1.5]]',{width:420},'![[Map.excalidraw.md#^area=foo,padding=1.5|420]]'],
['![[Map|400]]',{width:400},'![[Map|400]]'],
['![[Map| Caption | 300x200 |left]]',{width:450,height:300},'![[Map| Caption | 450x300 |left]]'],
['![[Map|Caption|50%x25%|right]]',{width:360,height:180},'![[Map|Caption|360x180|right]]'],
['![[Map|x200|center]]',{width:400,height:200},'![[Map|400x200|center]]'],
['![[Map|left]]',{width:320},'![[Map|320|left]]'],
['![[Map|Caption|left]]',{width:320},'![[Map|Caption|320|left]]'],
['![[Map|Caption|unknown|left]]',{width:320},'![[Map|Caption|320|unknown|left]]'],
['![[Map|]]',{width:320},'![[Map|320]]'],
['![[Map\\|Alias\\|50%x25%\\|left]]',null,'![[Map\\|Alias\\|left]]'],
['![[Map\\| x100 \\|center]]',{width:200,height:100},'![[Map\\| 200x100 \\|center]]'],
['![[Map|400|left]]',null,'![[Map|left]]'],
['![[Map|400]]',null,'![[Map]]'],
['![[Map|Alias|left]]',null,'![[Map|Alias|left]]'],
['![Caption|200](Drawings/Map.excalidraw.md#^frame=F,padding=5 "Keep title")',{width:300},'![Caption|300](Drawings/Map.excalidraw.md#^frame=F,padding=5 "Keep title")'],
['![](<Drawings/Árvíz 测试.excalidraw.md#^clippedframe=My Frame> "Keep (title)")',{width:320},'![320](<Drawings/Árvíz 测试.excalidraw.md#^clippedframe=My Frame> "Keep (title)")'],
['![400|left](Map.md#^as-image)',null,'![left](Map.md#^as-image)'],
['![Caption|400](Drawings/My%20Map.md "Keep")',null,'![Caption](Drawings/My%20Map.md "Keep")'],
['![400](Map.md)',null,'![](Map.md)'],
['![](<Drawings/A)B.md#^frame=Frame (> "Title")',{width:120},'![120](<Drawings/A)B.md#^frame=Frame (> "Title")'],
['![left](Map.md)',{width:320},'![320|left](Map.md)'],
]) test(`dimension slot: ${source} → ${expected}`,()=>assert.equal(edit(source,size),expected));
test('token parsing stops at its closing boundary and preserves destinations and titles',()=>{
const first='![Caption\\] kept|200](<Drawings/A (B).md#^group=abcd1234> "Title ) kept")';
const token=readDrawingEmbedToken(first+' ![[Other]]');
assert.equal(token.text,first);assert.equal(token.target,'Drawings/A (B).md#^group=abcd1234');
assert.equal(edit(first+' ![[Other]]',{width:100}),null);
assert.equal(readDrawingEmbedToken('![[Map]] extra').text,'![[Map]]');
});
test('invalid tokens or non-positive/non-finite dimensions are not written',()=>{
for(const source of ['text ![[Map]]','![[Map]','![alt](unclosed','ordinary text'])assert.equal(edit(source,{width:100}),null);
for(const width of [0,-1,Infinity,NaN,1.5,100001])assert.equal(edit('![[Map]]',{width}),null);
assert.equal(edit('![[Map]]',{width:100,height:0}),null);
});
test('the established alias/style and percentage grammar remains intact',()=>{
assert.deepEqual(getEmbedDimensions('![[Map|Caption|x40%|left]]'),{width:undefined,height:'40%'});
assert.deepEqual(parseEmbedAlias('Caption|300x200|left'),{alias:'Caption',width:'300',height:'200',style:'left'});
assert.deepEqual(parseEmbedAlias('300|right'),{width:'300',style:'right'});
assert.deepEqual(parseEmbedAlias('Caption|invalid|left'),{alias:'Caption',style:'left'});
assert.deepEqual(parseEmbedAlias('01|right'),{alias:'01',style:'right'});
});
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import test, { after } from "node:test";
import { EditorState, Transaction } from "@codemirror/state";
import { history, undo } from "@codemirror/commands";
import { sourceHarness } from "./sourceHarness.mjs";
const graph = sourceHarness();
const { rewriteEmbedFrame } = await graph.importModule("src/core/editor/embedFrame.ts");
const { DrawingEmbedSource } = await graph.importModule("src/core/editor/embedSource.ts");
after(() => graph.close());
test("frame selection preserves raw paths, clipping, dimensions, titles, padding and escaped table aliases", () => {
for (const [text, expected] of [
["![[../Drawing|Caption|200x100|left]]", "![[../Drawing#^frame=frame-id|Caption|200x100|left]]"],
["![[Map#^clippedframe=Part, One,padding=50\\|200\\|right]]", "![[Map#^clippedframe=frame-id,padding=50\\|200\\|right]]"],
['![Caption|200](<Map%20one#%5eframe%3dOld> "Keep title")', '![Caption|200](<Map%20one#%5eframe%3dframe-id> "Keep title")'],
['![Caption](Map%20one%23%5Eclippedframe%3DOld%2Cpadding%3D00%2E50 "Keep")', '![Caption](Map%20one%23%5Eclippedframe%3Dframe-id%2Cpadding%3D00%2E50 "Keep")'],
]) assert.equal(rewriteEmbedFrame(text, "frame-id"), expected);
assert.equal(rewriteEmbedFrame('![[Map#^frame=Old,padding=50|200]]', null), '![[Map#^as-image,padding=50|200]]');
assert.equal(rewriteEmbedFrame('![[Map#^clippedframe=Old,padding=50|200]]', ''), '![[Map#^frame=,padding=50|200]]');
for (const ref of ['../Other', 'frame#evil', 'Name,padding=20']) assert.equal(rewriteEmbedFrame('![[Map]]', ref), null);
});
test("frame selection edits only the owned occurrence and is one undo step", () => {
const token = '![[Map|200]]', doc = token + '\n' + token;
let state = EditorState.create({ doc, extensions: [history()] });
const view = { get state() { return state; }, dispatch(spec) { state = (spec instanceof Transaction ? spec : state.update(spec)).state; } };
const source = new DrawingEmbedSource(view, token.length + 1, doc.length, token, () => true);
assert.equal(source.replaceFrame('frame-id'), true);
assert.equal(state.doc.toString(), token + '\n![[Map#^frame=frame-id|200]]');
assert.equal(undo(view), true); assert.equal(state.doc.toString(), doc);
assert.equal(source.replaceFrame('other'), false);
});
+71
View File
@@ -0,0 +1,71 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import ts from "typescript";
test("embed controls have complete maintained translations without lossy shell encoding", () => {
let expected;
for (const language of ["en", "ru", "es", "zh-cn", "zh-tw"]) {
const path = new URL(`../../src/lang/locale/${language}.ts`, import.meta.url);
const source = readFileSync(path, "utf8"), start = source.indexOf("// Drawing embed controls (#3036)"), end = source.indexOf("// Native CLI and agent discovery", start);
assert.ok(start >= 0 && end > start, language);
const tree = ts.createSourceFile(path.pathname, source, ts.ScriptTarget.Latest, true), strings = new Map();
const visit = node => {
if (ts.isPropertyAssignment(node) && node.getStart(tree) >= start && node.getStart(tree) < end && node.name.text?.startsWith("EMBED_")) {
assert.ok(ts.isStringLiteral(node.initializer)); strings.set(node.name.text, node.initializer.text);
}
ts.forEachChild(node, visit);
};
visit(tree);
assert.equal(strings.size, 17, language); expected ??= [...strings.keys()].sort();
assert.deepEqual([...strings.keys()].sort(), expected, language);
for (const [key, value] of strings) {
assert.ok(value.trim()); assert.doesNotMatch(value, /\?|\uFFFD/, language + ": " + key);
if (language === "ru") assert.match(value, /\p{Script=Cyrillic}/u, key);
if (language.startsWith("zh-")) assert.match(value, /\p{Script=Han}/u, key);
}
}
});
test("frame controls have complete maintained translations", () => {
let expected;
for (const language of ["en", "ru", "es", "zh-cn", "zh-tw"]) {
const path = new URL(`../../src/lang/locale/${language}.ts`, import.meta.url), source = readFileSync(path, "utf8");
const tree = ts.createSourceFile(path.pathname, source, ts.ScriptTarget.Latest, true), strings = new Map();
const visit = node => {
if (ts.isPropertyAssignment(node) && node.getStart(tree) < source.indexOf("// Drawing embed controls (#3036)") && node.name.text?.startsWith("FRAME_")) {
assert.ok(ts.isStringLiteral(node.initializer)); strings.set(node.name.text, node.initializer.text);
}
ts.forEachChild(node, visit);
};
visit(tree); assert.equal(strings.size, 17, language); expected ??= [...strings.keys()].sort();
assert.deepEqual([...strings.keys()].sort(), expected, language);
for (const [key, value] of strings) {
assert.ok(value.trim()); assert.doesNotMatch(value, /\uFFFD/, language + ": " + key);
if (language === "ru") assert.match(value, /\p{Script=Cyrillic}/u, key);
if (language.startsWith("zh-")) assert.match(value, /\p{Script=Han}/u, key);
}
}
});
test("preview configuration and scope explanations have maintained translations", () => {
let expected;
for (const language of ["en", "ru", "es", "zh-cn", "zh-tw"]) {
const path = new URL(`../../src/lang/locale/${language}.ts`, import.meta.url), source = readFileSync(path, "utf8");
const tree = ts.createSourceFile(path.pathname, source, ts.ScriptTarget.Latest, true), strings = new Map();
const visit = node => {
if (ts.isPropertyAssignment(node) && node.getStart(tree) < source.indexOf("FRAME_NAVIGATE:") && node.name.text?.startsWith("PREVIEW_")) {
assert.ok(ts.isStringLiteral(node.initializer)); strings.set(node.name.text, node.initializer.text);
}
ts.forEachChild(node, visit);
};
visit(tree); assert.equal(strings.size, 16, language); expected ??= [...strings.keys()].sort();
assert.deepEqual([...strings.keys()].sort(), expected, language);
for (const [key, value] of strings) {
assert.ok(value.trim()); assert.doesNotMatch(value, /\uFFFD/, language + ": " + key);
if (language === "ru") assert.match(value, /\p{Script=Cyrillic}/u, key);
if (language.startsWith("zh-")) assert.match(value, /\p{Script=Han}/u, key);
}
for (const token of ["{drawing}","{count}"]) assert.ok(strings.get("PREVIEW_SHARED_HELP").includes(token));
}
});
@@ -0,0 +1,177 @@
import assert from "node:assert/strict";
import test, { after } from "node:test";
import { EditorState, Transaction } from "@codemirror/state";
import { history, undo, redo } from "@codemirror/commands";
import { sourceHarness } from "./sourceHarness.mjs";
import { embedTestDOM } from "./embedTestDOM.mjs";
const graph = sourceHarness();
const { rewriteEmbedPadding, withAreaPadding } = await graph.importModule("src/core/editor/embedPadding.ts");
const { DrawingEmbedSource } = await graph.importModule("src/core/editor/embedSource.ts");
after(() => graph.close());
test("padding edits preserve wiki, Markdown, encoded paths, titles, aliases and escaped table delimiters", () => {
for (const [text, expected] of [
["![[../Map#^area=abcdefgh|Caption|200x100|left]]", "![[../Map#^area=abcdefgh,padding=50|Caption|200x100|left]]"],
["![[Map#area=Frame name,padding=.5\\|200\\|right]]", "![[Map#area=Frame name,padding=50\\|200\\|right]]"],
['![Caption|200](Map%20one#%5Earea=abcdefgh,padding=1.5 "Keep title")', '![Caption|200](Map%20one#%5Earea=abcdefgh,padding=50 "Keep title")'],
['![Map](<../Map one#^area=abcdefgh> "same Map")', '![Map](<../Map one#^area=abcdefgh,padding=50> "same Map")'],
["![[#^area=abcdefgh]]", "![[#^area=abcdefgh,padding=50]]"],
["![[100% Map#^area=abcdefgh]]", "![[100% Map#^area=abcdefgh,padding=50]]"],
['![Map](Map%20one%23%5Earea%3Dabcdefgh%2Cpadding%3D10 "Keep")', '![Map](Map%20one%23%5Earea%3Dabcdefgh,padding=50 "Keep")'],
]) assert.equal(rewriteEmbedPadding(text, 50), expected);
assert.equal(rewriteEmbedPadding("![[Map#^area=abcdefgh,padding=50|200]]", null), "![[Map#^area=abcdefgh|200]]");
for (const target of ["Map#^text", "Map#^group=", "Map#^area=", "Map#^area=abc,padding=-1", "Map#^area=abc,padding=1,padding=2"])
assert.equal(withAreaPadding(target, 10), null, target);
for (const value of [-1, Number.MAX_SAFE_INTEGER + 1, NaN, Infinity]) assert.equal(withAreaPadding("Map#^area=abc", value), null);
assert.equal(withAreaPadding("Map#^area=abc", 5000), "Map#^area=abc,padding=5000");
assert.equal(withAreaPadding("Map#^frame=Part, One,padding=20", 50), "Map#^frame=Part, One,padding=50");
assert.equal(withAreaPadding("Map#^clippedframe=Part,padding=20, Two", 50), "Map#^clippedframe=Part,padding=20, Two,padding=50");
});
test("padding changes only the owned repeated occurrence in one undo step and preserves target guards", () => {
const token = "![[Map#^area=abcdefgh|200]]", doc = token + "\n" + token;
let state = EditorState.create({ doc, extensions: [history()] }), writes = 0;
const view = { get state() { return state; }, dispatch(spec) { const tr = spec instanceof Transaction ? spec : state.update(spec); state = tr.state; if (tr.docChanged) writes++; } };
const binding = new DrawingEmbedSource(view, token.length + 1, doc.length, token, () => true);
assert.equal(binding.replace("![[Other#^area=abcdefgh|200]]"), false);
assert.equal(binding.replacePadding(50), true);
assert.equal(state.doc.toString(), token + "\n![[Map#^area=abcdefgh,padding=50|200]]");
assert.equal(writes, 1); assert.equal(binding.replacePadding(100), false);
assert.equal(undo(view), true); assert.equal(state.doc.toString(), doc);
assert.equal(redo(view), true); assert.match(state.doc.toString(), /padding=50/);
});
test("padding never writes through a stale source, owner or physical table-cell range", () => {
for (const kind of ["owner", "range", "source"]) {
const text = "![[Map#^area=abcdefgh|200]]";
let state = EditorState.create({ doc: text }), writes = 0;
const view = { get state() { return state; }, dispatch() { writes++; } };
const binding = new DrawingEmbedSource(view, 0, text.length, text, () => kind !== "owner", () => kind !== "range");
if (kind === "source") state = state.update({ changes: { from: 3, to: 6, insert: "New" } }).state;
assert.equal(binding.replacePadding(50), false, kind); assert.equal(writes, 0);
}
});
async function fixture({ value = 10, target = "Map", getMax } = {}) {
const dom = embedTestDOM(), timers = new Map(), requests = [], discarded = [], writes = [];
let id = 0, current = true, closed = 0;
dom.document.events = new Map(); dom.document.body = new dom.Element(); dom.window.innerHeight = 600;
dom.window.setTimeout = callback => { timers.set(++id, callback); return id; };
dom.window.clearTimeout = id => timers.delete(id);
const previous = globalThis.window; globalThis.window = dom.window;
class SliderComponent {
constructor(parent) { this.sliderEl = parent.createEl("input", { cls: "slider", attr: { type: "range" } }); }
setLimits(min, max, step) { for (const [key, value] of Object.entries({ min, max, step })) this.sliderEl.setAttribute(key, String(value)); return this; }
setValue(value) { this.sliderEl.value = String(value); return this; }
}
const module = sourceHarness({ obsidian: { Component: dom.Component, Notice: class {}, SliderComponent, setIcon() {}, setTooltip() {} },
"src/lang/helpers": { t: key => key }, "src/utils/styleUtils": { setStyle: (el, values) => Object.assign(el.style, values) } });
const { DrawingEmbedPaddingControl } = await module.importModule("src/core/managers/DrawingEmbedPaddingControl.ts");
const frame = new dom.Element(), toolbar = frame.createDiv({ cls: "excalidraw-embed-toolbar" }), opener = toolbar.createEl("button"), original = frame.createEl("img", { cls: "excalidraw-embedded-img" });
const actions = { target, isCurrent: () => current, discard: image => discarded.push(image), padding: { value, getMax,
create: (value, active) => new Promise(resolve => requests.push({ value, active, resolve })) } };
const source = { isCurrent: () => current, replacePadding: value => { writes.push(value); return true; } };
const popup = new DrawingEmbedPaddingControl(frame, opener, actions, source, () => closed++); popup.load();
const root = dom.document.body.children[0], slider = root.querySelector("input");
const flush = () => { for (const [id, callback] of timers) { timers.delete(id); callback(); } };
const change = index => { slider.value = String(index); slider.fire("input"); };
const close = () => { popup.close(false); module.close(); globalThis.window = previous; assert.equal(dom.listenerCount(), 0); assert.equal(timers.size, 0); };
return { ...dom, frame, toolbar, opener, original, root, popup, slider, requests, discarded, writes, timers, change, flush, close, closed: () => closed, current: value => { current = value; } };
}
test("padding row aligns beneath the whole toolbar, stays onscreen, and exposes disclosure state", async () => {
const f = await fixture();
try {
f.toolbar.bounds = { left: 550, right: 730, top: 100, bottom: 132, width: 180, height: 32 };
f.opener.bounds = { left: 610, right: 638, top: 102, bottom: 130, width: 28, height: 28 };
f.root.bounds = { left: 0, right: 240, top: 0, bottom: 36, width: 240, height: 36 };
f.fire(f.window, "resize");
assert.equal(f.root.style.left, "490px"); assert.equal(f.root.style.top, "136px");
assert.equal(f.opener.getAttribute("aria-expanded"), "true");
assert.equal(f.slider.getAttribute("min"), "0");
assert.equal(f.slider.getAttribute("max"), "100");
assert.equal(f.slider.getAttribute("step"), "1");
assert.equal(f.root.children[0].hasClass("excalidraw-embed-padding-row"), true);
assert.equal(f.root.children[1].hasClass("excalidraw-padding-value"), true);
assert.equal(f.root.children[2].hasClass("excalidraw-embed-padding-help"), true);
assert.equal(f.root.querySelector(".excalidraw-embed-padding-heading"), null);
assert.equal(f.root.children.length, 3, "controls, value and description occupy separate rows");
f.toolbar.bounds = { ...f.toolbar.bounds, top: 580, bottom: 612 };
f.fire(f.window, "resize"); assert.equal(f.root.style.top, "540px", "near the bottom the row flips above its toolbar");
f.popup.close(false); assert.equal(f.opener.getAttribute("aria-expanded"), "false");
} finally { f.close(); }
});
test("padding previews debounce without writing; closing commits exactly once and releases fresh payloads", async () => {
const f = await fixture();
try {
f.change(2); f.change(3); assert.equal(f.timers.size, 1); assert.equal(f.requests.length, 0); f.flush();
assert.equal(f.requests[0].value, 3); assert.deepEqual(f.writes, []);
const preview = new f.Element(); f.requests[0].resolve(preview); await Promise.resolve();
assert.equal(f.frame.children.includes(f.original), true, "original widget and source identity remain stable");
assert.equal(f.frame.hasClass("excalidraw-embed-padding-previewing"), true);
f.popup.close(true); f.popup.close(true);
assert.deepEqual(f.writes, [3]); assert.deepEqual(f.discarded, [preview]); assert.equal(f.closed(), 1);
assert.equal(f.document.body.children.length, 0); assert.equal(f.frame.hasClass("excalidraw-embed-padding-previewing"), false);
} finally { f.close(); }
});
test("newer padding previews win; late exports after Escape, unload or stale source are discarded", async () => {
for (const cancel of ["Escape", "unload", "source"]) {
const f = await fixture();
try {
f.change(2); f.flush(); f.change(3); f.flush();
const old = new f.Element(); f.requests[0].resolve(old); await Promise.resolve();
assert.deepEqual(f.discarded, [old]); assert.equal(f.requests[0].active(), false);
if (cancel === "Escape") f.fire(f.document, "keydown", { key: "Escape" });
if (cancel === "unload") f.popup.unload();
if (cancel === "source") { f.current(false); f.popup.close(true); }
const late = new f.Element(); f.requests[1].resolve(late); await Promise.resolve();
assert.deepEqual(f.discarded, [old, late]); assert.deepEqual(f.writes, []); assert.equal(f.requests[1].active(), false);
} finally { f.close(); }
}
});
test("padding wheel, outside close and default reset use the configured gesture without duplicate writes", async () => {
const f = await fixture();
try {
f.slider.fire("wheel", { deltaY: -1 });
f.fire(f.document, "pointerdown", { composedPath: () => [f.document] });
assert.deepEqual(f.writes, [11]); assert.equal(f.timers.size, 0);
} finally { f.close(); }
const reset = await fixture();
try { reset.root.querySelector("button").fire("click"); assert.deepEqual(reset.writes, [null]); }
finally { reset.close(); }
});
test("area limits load once before the gesture and stay fixed across value digit changes", async () => {
let calls=0, resolve;
const limit=new Promise(done=>{resolve=done;});
const f=await fixture({target:"Map#^area=a",getMax:()=>{calls++;return limit;}});
try{
assert.equal(f.slider.disabled,true);assert.equal(calls,1);
resolve(5432);await Promise.resolve();await Promise.resolve();
assert.equal(f.slider.disabled,false);assert.equal(f.slider.getAttribute("max"),"5432");
f.change(9);f.change(100);f.change(2000);
assert.equal(f.slider.getAttribute("max"),"5432");assert.equal(calls,1);
assert.equal(f.root.children[1].text,"2000");
assert.equal(f.root.children[0].querySelector("output"),null,"readout must not affect the track row");
f.popup.close(true);assert.deepEqual(f.writes,[2000]);
}finally{f.close();}
let resolveStale;
const stale=await fixture({target:"Map#^area=a",getMax:()=>new Promise(done=>{resolveStale=done;})});
try{
stale.popup.close(false);resolveStale(9000);await Promise.resolve();await Promise.resolve();
assert.equal(stale.slider.disabled,true,"a closed popup must ignore the completed range read");
assert.deepEqual(stale.writes,[]);
}finally{stale.close();}
});
test("opening a capped padding control preserves larger saved values until edited", async () => {
const f=await fixture({value:750});
try{
assert.equal(f.slider.value,"100");assert.equal(f.root.children[1].text,"750");
f.popup.close(true);assert.deepEqual(f.writes,[]);
}finally{f.close();}
});
@@ -0,0 +1,161 @@
/** Whole production viewer with a minimal owned DOM; native input is tested separately. */
import assert from "node:assert/strict";
import test, { after } from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
const document = { defaultView: { closed: false, innerWidth: 800, innerHeight: 600, events: new Map() }, activeElement: null };
const frames = new Map(), timers = new Map(); let clockId = 0;
document.defaultView.requestAnimationFrame = callback => { frames.set(++clockId, callback); return clockId; };
document.defaultView.cancelAnimationFrame = id => frames.delete(id);
const oldWindow = globalThis.window;
globalThis.window = { setTimeout: callback => { timers.set(++clockId, callback); return clockId; }, clearTimeout: id => timers.delete(id) };
let listeners = 0;
class Element {
constructor(options = {}) { this.children = []; this.attrs = { ...options.attr }; this.classes = new Set((options.cls || "").split(" ")); this.events = new Map(); this.style = {}; this.ownerDocument = document; this.isConnected = true; this.captures = new Set(); }
createDiv(options) { return this.createEl("div", typeof options === "string" ? { cls: options } : options); }
createSpan(options) { return this.createEl("span", options); }
createEl(tag, options) { const el = new Element(options); el.tag = tag; this.append(el); return el; }
append(el) { el.parent = this; this.children.push(el); }
replaceChild(el, old) { const index = this.children.indexOf(old); assert.notEqual(index, -1); this.children[index] = el; el.parent = this; old.parent = null; }
addClass(cls) { this.classes.add(cls); }
setAttribute(key, value) { this.attrs[key] = value; }
removeAttribute(key) { delete this.attrs[key]; }
getAttribute(key) { return this.attrs[key] ?? null; }
setText(text) { this.text = text; }
focus() { document.activeElement = this; }
remove() { this.isConnected = false; if (this.parent) this.parent.children = this.parent.children.filter(el => el !== this); }
empty() { for (const child of [...this.children]) child.remove(); }
find(cls) { return this.children.find(el => el.classes.has(cls)) ?? this.children.map(el => el.find(cls)).find(Boolean); }
fire(name, event = {}) { const e = { preventDefault() { this.prevented = true; }, stopPropagation() { this.stopped = true; }, ...event }; for (const callback of [...this.events.get(name) || []]) callback(e); return e; }
getBoundingClientRect() { return { left: 0, top: 0, right: 800, bottom: 600, width: 800, height: 600 }; }
setPointerCapture(id) { this.captures.add(id); }
hasPointerCapture(id) { return this.captures.has(id); }
releasePointerCapture(id) { this.captures.delete(id); }
}
class Component {
cleanups = [];
load() {}
register(callback) { this.cleanups.push(callback); }
registerDomEvent(el, event, callback) {
if (!el.events.has(event)) el.events.set(event, new Set());
el.events.get(event).add(callback); listeners++;
this.cleanups.push(() => { el.events.get(event).delete(callback); listeners--; });
}
unload() { for (const cleanup of this.cleanups.splice(0)) cleanup(); }
}
class Modal {
constructor() { this.containerEl = new Element(); this.modalEl = this.containerEl.createDiv(); this.titleEl = this.modalEl.createDiv(); this.contentEl = this.modalEl.createDiv(); }
setTitle(title) { this.title = title; }
open() { this.onOpen(); }
close() { this.onClose(); this.modalEl.remove(); }
}
const graph = sourceHarness({ obsidian: { Component, Modal, setIcon() {}, setTooltip() {} }, "src/lang/helpers": { t: key => key }, "src/utils/ownedPNGImage": { hasOwnedPNGImageSource: el => el.tag === "img" }, "src/utils/styleUtils": { setStyle: (el, values) => Object.assign(el.style, values) } });
const { DrawingEmbedPreviewModal } = await graph.importModule("src/shared/Dialogs/DrawingEmbedPreviewModal.ts");
after(() => { graph.close(); if (oldWindow === undefined) delete globalThis.window; else globalThis.window = oldWindow; });
const flush = () => new Promise(resolve => setImmediate(resolve));
function fixture(upgrade) {
let resolve, reject, isCurrent, closed = 0;
const discarded = [], opened = [], opener = new Element(), promise = new Promise((yes, no) => { resolve = yes; reject = no; });
const modal = new DrawingEmbedPreviewModal({}, { upgrade, create: active => { isCurrent = active; return promise; }, discard: el => discarded.push(el), isCurrent: () => true, getOpenTooltip: () => "configured shortcuts", openDrawing: event => opened.push(event) }, opener, () => closed++);
modal.open();
return { modal, opener, resolve, reject, discarded, opened, current: () => isCurrent(), closed: () => closed };
}
const deferred = () => { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { resolve, reject, promise }; };
const raster = (decode = Promise.resolve()) => { const el = new Element(); el.tag = "img"; el.decode = () => decode; return el; };
async function renderFrames() { for (let i = 0; i < 2; i++) { for (const [id, callback] of [...frames]) { frames.delete(id); callback(); } await flush(); } }
test("progressive PNG detail swaps only after decode and preserves live zoom pan and pointer capture", async () => {
const exportJob = deferred(), decodeJob = deferred(); let signal, calls = 0;
const f = fixture((active, abort) => { assert.equal(active(), true); calls++; signal = abort; return exportJob.promise; });
const initial = raster(); f.resolve(initial); await flush();
const stage = f.modal.contentEl.find("excalidraw-embed-preview-stage"), surface = stage.find("excalidraw-embed-preview-surface");
assert.deepEqual(surface.children, [initial]); assert.equal(calls, 0, "initial image must precede expensive work");
await renderFrames(); assert.equal(calls, 1); assert.equal(timers.size, 0);
f.modal.modalEl.fire("keydown", { key: "+" }); f.modal.modalEl.fire("keydown", { key: "ArrowRight" });
stage.fire("pointerdown", { button: 0, pointerId: 9, clientX: 10, clientY: 10 });
const transform = surface.style.transform, zoom = stage.getAttribute("data-zoom"), detail = raster(decodeJob.promise);
exportJob.resolve(detail); await flush(); assert.deepEqual(surface.children, [initial]);
decodeJob.resolve(); await flush(); assert.deepEqual(surface.children, [detail]);
assert.equal(surface.style.transform, transform); assert.equal(stage.getAttribute("data-zoom"), zoom); assert.equal(stage.hasPointerCapture(9), true);
assert.deepEqual(f.discarded, [initial]); f.modal.close();
assert.deepEqual(f.discarded, [initial, detail]); assert.equal(signal.aborted, false, "completed operation releases its controller"); assert.equal(listeners, 0);
});
test("closing progressive PNG cancels frames exports and decoding and releases late private images", async () => {
for (const phase of ["initial-decode", "frames", "export", "detail-decode"]) {
const initialDecode = deferred(), exportJob = deferred(), detailDecode = deferred(); let signal, calls = 0;
const f = fixture((_active, abort) => { signal = abort; calls++; return exportJob.promise; });
const initial = raster(phase === "initial-decode" ? initialDecode.promise : Promise.resolve()), detail = raster(detailDecode.promise);
f.resolve(initial); await flush();
if (["export", "detail-decode"].includes(phase)) await renderFrames();
if (phase === "detail-decode") { exportJob.resolve(detail); await flush(); }
f.modal.close(); await flush();
assert.equal(frames.size, 0); assert.equal(timers.size, 0); assert.equal(listeners, 0);
if (signal) assert.equal(signal.aborted, true);
initialDecode.resolve(); exportJob.resolve(detail); detailDecode.resolve(); await flush();
assert.equal(calls, ["export", "detail-decode"].includes(phase) ? 1 : 0);
assert.deepEqual(f.discarded, calls ? [initial, detail] : [initial]);
}
});
test("failed PNG detail export keeps the initial preview and hidden-window fallback settles", async () => {
const f = fixture(async () => { throw Error("export failed"); }), initial = raster();
f.resolve(initial); await flush();
for (const callback of [...timers.values()]) callback(); await flush();
assert.equal(frames.size, 0); assert.equal(timers.size, 0);
assert.deepEqual(f.modal.contentEl.find("excalidraw-embed-preview-surface").children, [initial]);
assert.deepEqual(f.discarded, []); f.modal.close(); assert.deepEqual(f.discarded, [initial]);
});
test("closing during fullscreen export cancels ownership and discards only the late private payload", async () => {
const f = fixture(), privateImage = new Element();
assert.equal(f.current(), true); assert.ok(listeners > 0);
f.modal.close(); assert.equal(f.current(), false); assert.equal(listeners, 0);
f.resolve(privateImage); await flush();
assert.deepEqual(f.discarded, [privateImage]); assert.equal(f.closed(), 1); assert.equal(document.activeElement, f.opener);
});
test("fullscreen zoom, fit, pan and pinch own their handlers and private image lifetime", async () => {
const f = fixture(), image = new Element(); f.resolve(image); await flush();
const stage = f.modal.contentEl.find("excalidraw-embed-preview-stage"), surface = stage.find("excalidraw-embed-preview-surface");
assert.ok(surface.children.includes(image));
f.modal.modalEl.fire("keydown", { key: "+", target: f.modal.contentEl.find("excalidraw-embed-preview-toolbar").children[0] }); assert.equal(Number(stage.getAttribute("data-zoom")), 1.25);
f.modal.modalEl.fire("keydown", { key: "ArrowRight", target: stage }); assert.match(surface.style.transform, /-24px/);
f.modal.modalEl.fire("keydown", { key: "0", target: stage }); assert.equal(stage.getAttribute("data-zoom"), "1");
stage.fire("pointerdown", { button: 0, pointerId: 1, clientX: 10, clientY: 10 });
stage.fire("pointerdown", { button: 0, pointerId: 2, clientX: 30, clientY: 10 });
stage.fire("pointermove", { pointerId: 2, clientX: 50, clientY: 10 });
assert.equal(Number(stage.getAttribute("data-zoom")), 2);
assert.equal(surface.fire("click").prevented, true);
f.modal.close(); assert.equal(listeners, 0); assert.equal(stage.captures.size, 0); assert.deepEqual(f.discarded, [image]);
});
test("failed fullscreen export reports failure and a detached opener is never focused", async () => {
const f = fixture(); f.reject(Error("export failed")); await flush();
assert.equal(f.modal.contentEl.find("excalidraw-embed-preview-status").text, "EMBED_PREVIEW_FAILED");
f.opener.isConnected = false; document.activeElement = null;
f.modal.close(); assert.equal(document.activeElement, null); assert.equal(listeners, 0); assert.deepEqual(f.discarded, []);
});
test("preview pencil and modifier clicks preserve modifiers and close before opening the drawing", () => {
for (const target of ["pencil", "image"]) {
const f = fixture(), stage = f.modal.contentEl.find("excalidraw-embed-preview-stage");
const event = { ctrlKey: true, metaKey: true, shiftKey: true, altKey: false };
if (target === "pencil") f.modal.contentEl.find("excalidraw-embed-preview-toolbar").children.find(el => el.getAttribute("data-excalidraw-embed-action") === "open").fire("click", event);
else stage.fire("click", event);
assert.equal(f.closed(), 1); assert.equal(f.opened.length, 1);
for (const key of Object.keys(event)) assert.equal(f.opened[0][key], event[key]);
assert.equal(listeners, 0);
}
});
test("dragging a viewport preview restores movable bounds and releases its pointer ownership", () => {
const f = fixture(), header = f.modal.titleEl;
header.fire("pointerdown", { button: 0, pointerId: 7, clientX: 100, clientY: 20 });
for (const callback of document.defaultView.events.get("pointermove")) callback({ pointerId: 7, clientX: 120, clientY: 30, preventDefault() {} });
assert.equal(f.modal.modalEl.style.width, "680px"); assert.equal(f.modal.modalEl.style.height, "510px");
assert.equal(f.modal.modalEl.style["--excalidraw-preview-left"], "35px");
assert.equal(f.modal.modalEl.style["--excalidraw-preview-top"], "10px");
f.modal.close(); assert.equal(header.captures.size, 0); assert.equal(listeners, 0);
});
@@ -0,0 +1,52 @@
import assert from 'node:assert/strict';
import test,{after} from 'node:test';
import {EditorState,Transaction} from '@codemirror/state';
import {history,undo,redo} from '@codemirror/commands';
import {sourceHarness} from './sourceHarness.mjs';
const graph=sourceHarness();
const {DrawingEmbedSource}=await graph.importModule('src/core/editor/embedSource.ts');
after(()=>graph.close());
test('a physical-cell range validator blocks stale resize and source selection without history entries',()=>{
let state=EditorState.create({doc:'![[Map|100]]',extensions:[history()]}),allowed=false,validations=0,focused=false;
const view={get state(){return state;},dispatch(spec){state=state.update(spec).state;},focus(){focused=true;}};
const binding=new DrawingEmbedSource(view,0,state.doc.length,state.doc.toString(),()=>true,(from,to)=>{validations++;assert.equal(state.sliceDoc(from,to),'![[Map|100]]');return allowed;});
assert.equal(binding.replace('![[Map|108]]'),false);assert.equal(binding.select(),false);assert.equal(focused,false);assert.equal(undo(view),false);
const transaction=state.update({changes:{from:0,insert:'prefix '}});state=transaction.state;binding.map(transaction.changes);
assert.equal(validations,2,'range validation must not read pre-update DOM while mapping');
allowed=true;assert.equal(binding.replace('![[Map|108]]'),true);assert.equal(state.doc.toString(),'prefix ![[Map|108]]');
});
function fixture(doc='before ![[Map|200]] after ![[Map|200]]',occurrence=1){
let state=EditorState.create({doc,extensions:[history()]});let owner=true,focused=false,writes=0;
const text='![[Map|200]]',from=doc.indexOf(text,occurrence===0?0:doc.indexOf(text)+1);
const view={get state(){return state;},dispatch(spec){const transaction=spec instanceof Transaction?spec:state.update(spec);state=transaction.state;if(transaction.docChanged)writes++;},focus(){focused=true;}};
const binding=new DrawingEmbedSource(view,from,from+text.length,text,()=>owner);
return{view,binding,owner:value=>owner=value,focused:()=>focused,writes:()=>writes};
}
test('only the bound repeated occurrence changes, with one undo and redo step',()=>{
const f=fixture();assert.equal(f.binding.replace('![[Map|320]]'),true);
assert.equal(f.view.state.doc.toString(),'before ![[Map|200]] after ![[Map|320]]');assert.equal(f.writes(),1);
assert.equal(undo(f.view),true);assert.equal(f.view.state.doc.toString(),'before ![[Map|200]] after ![[Map|200]]');
assert.equal(redo(f.view),true);assert.equal(f.view.state.doc.toString(),'before ![[Map|200]] after ![[Map|320]]');
});
test('prefix transactions map the source range without selecting another identical token',()=>{
const f=fixture(),transaction=f.view.state.update({changes:{from:0,insert:'prefix '}});f.view.dispatch(transaction);f.binding.map(transaction.changes);
assert.equal(f.binding.replace('![[Map|260]]'),true);assert.equal(f.view.state.doc.toString(),'prefix before ![[Map|200]] after ![[Map|260]]');
});
test('source editing selects the exact containing-note token without changing source',()=>{
const f=fixture();assert.equal(f.binding.select(),true);assert.equal(f.view.state.selection.main.from,26);assert.equal(f.view.state.selection.main.to,38);assert.equal(f.focused(),true);assert.equal(f.writes(),0);
});
test('stale, changed-owner, changed-destination and retired bindings never write',()=>{
for(const kind of ['owner','token','retired','target']){const f=fixture();
if(kind==='owner')f.owner(false);
if(kind==='token'){const change=f.view.state.update({changes:{from:30,to:31,insert:'X'}});f.view.dispatch(change);f.binding.map(change.changes);}
if(kind==='retired')f.binding.invalidate();
const before=f.view.state.doc.toString(),writes=f.writes();
assert.equal(f.binding.replace(kind==='target'?'![[Other|300]]':'![[Map|300]]'),false,kind);
assert.equal(f.view.state.doc.toString(),before);assert.equal(f.writes(),writes);
}
});
test('a no-op creates no history event and completed bindings cannot replay',()=>{
const f=fixture();assert.equal(f.binding.replace(f.binding.text),true);assert.equal(f.writes(),0);assert.equal(undo(f.view),false);
assert.equal(f.binding.replace('![[Map|300]]'),true);assert.equal(f.binding.replace('![[Map|350]]'),false);assert.equal(f.writes(),1);
});
+62
View File
@@ -0,0 +1,62 @@
/** Small lifecycle/DOM boundary for production embed-controller tests; no rendering claim. */
export function embedTestDOM() {
const observers = [], frames = new Map(); let listeners = 0, nextFrame = 0;
const window = { events: new Map(), closed: false, innerWidth: 800, MutationObserver: class {
constructor(callback) { this.callback = callback; observers.push(this); }
observe() { this.connected = true; }
disconnect() { this.connected = false; }
fire() { if (this.connected) this.callback(); }
} };
window.requestAnimationFrame = callback => { const id = ++nextFrame; frames.set(id, callback); return id; };
window.cancelAnimationFrame = id => frames.delete(id);
window.ResizeObserver = class extends window.MutationObserver {
constructor(callback) { super(callback); this.resize = true; }
observe(target) { super.observe(); this.target = target; }
};
const document = { defaultView: window, activeElement: null };
class Element {
constructor(options = {}) { this.children = []; this.attrs = { ...options.attr }; this.classes = new Set((options.cls || "").split(" ")); this.events = new Map(); this.style = {}; this.ownerDocument = document; this.isConnected = true; this.captures = new Set(); this.bounds = { left: 0, top: 0, right: 700, bottom: 130, width: 700, height: 130 }; }
createDiv(options) { return this.createEl("div", typeof options === "string" ? { cls: options } : options); }
createSpan(options) { return this.createEl("span", options); }
createEl(tag, options) { const el = new Element(options); el.tagName = tag.toUpperCase(); el.text = options?.text; this.append(el); return el; }
append(el) { el.remove(); el.isConnected = true; el.parentElement = this; this.children.push(el); }
addClass(...classes) { for (const cls of classes) this.classes.add(cls); }
removeClass(...classes) { for (const cls of classes) this.classes.delete(cls); }
toggleClass(cls, value) { if (value) this.classes.add(cls); else this.classes.delete(cls); }
hasClass(cls) { return this.classes.has(cls); }
setAttribute(key, value) { this.attrs[key] = value; }
removeAttribute(key) { delete this.attrs[key]; }
getAttribute(key) { return this.attrs[key] ?? null; }
setText(text) { this.text = text; }
focus() { document.activeElement = this; }
remove() { this.isConnected = false; if (this.parentElement) this.parentElement.children = this.parentElement.children.filter(el => el !== this); this.parentElement = null; }
empty() { for (const child of [...this.children]) child.remove(); }
matches(selector) { return selector.startsWith(".") ? this.classes.has(selector.slice(1)) : this.tagName === selector.toUpperCase(); }
querySelectorAll(selector) { return this.children.flatMap(el => [...(selector.split(",").some(part => el.matches(part.trim())) ? [el] : []), ...el.querySelectorAll(selector)]); }
querySelector(selector) { return this.querySelectorAll(selector)[0] ?? null; }
closest(selector) { for (let el = this; el; el = el.parentElement) if (selector.split(",").some(part => el.matches(part.trim()))) return el; return null; }
getBoundingClientRect() { return this.bounds; }
fire(name, event = {}) { return fire(this, name, event); }
setPointerCapture(id) { this.captures.add(id); }
hasPointerCapture(id) { return this.captures.has(id); }
releasePointerCapture(id) { this.captures.delete(id); }
}
const fire = (target, name, event = {}) => {
const e = { currentTarget: target, preventDefault() { this.prevented = true; }, stopPropagation() {}, ...event };
for (const callback of [...target.events.get(name) || []]) callback(e); return e;
};
class Component {
cleanups = [];
load() { this.onload?.(); }
register(callback) { this.cleanups.push(callback); }
registerDomEvent(el, event, callback) {
if (!el.events.has(event)) el.events.set(event, new Set());
el.events.get(event).add(callback); listeners++;
this.register(() => { el.events.get(event).delete(callback); listeners--; });
}
unload() { for (const cleanup of this.cleanups.splice(0)) cleanup(); this.onunload?.(); }
}
class MarkdownRenderChild extends Component { constructor(containerEl) { super(); this.containerEl = containerEl; } }
return { Element, Component, MarkdownRenderChild, window, document, fire, observers, listenerCount: () => listeners,
pendingFrames: () => frames.size, flushFrames: () => { const callbacks = [...frames.values()]; frames.clear(); for (const callback of callbacks) callback(); } };
}
@@ -0,0 +1,30 @@
import assert from 'node:assert/strict';
import test, {after} from 'node:test';
import {sourceHarness} from './sourceHarness.mjs';
const graph=sourceHarness({
obsidian:{TFile:class{},MarkdownView:class{},Menu:class{},FileView:class{}},
'../../utils/fileUtils':{getLink:()=>''},
'../../utils/obsidianUtils':{editorInsertText(){},getExcalidrawViews:()=>[],getParentOfClass:()=>null,isUnwantedLeaf:()=>false,setExcalidrawView(){}},
'src/shared/ExcalidrawAutomate':{ExcalidrawAutomate:class{}},
'src/constants/constants':{FRONTMATTER_KEYS:{},ICON_NAME:'',VIEW_TYPE_EXCALIDRAW:'excalidraw'},
'src/view/ExcalidrawView':{default:class{}},
'src/lang/helpers':{t:key=>key},
'src/utils/excalidrawViewUtils':{getChangedTopLevelDependencyFileIDs:()=>[],setMobileNavbarPosition(){}},
'src/utils/styleUtils':{setStyle(){}},
});
after(()=>graph.close());
const {EventManager}=await graph.importModule('src/core/managers/EventManager.ts');
test('click and file-menu saving ignore a retired editor before reading its persistence state',()=>{
const plugin={app:{},activeExcalidrawView:{excalidrawAPI:null,isDirty(){throw Error('Retired persistence owner');},save(){throw Error('Retired save');}}};
const manager=new EventManager(plugin);
assert.doesNotThrow(()=>manager.onClickSaveActiveDrawing({target:{className:'markdown'}}));
assert.doesNotThrow(()=>manager.onFileMenuSaveActiveDrawing());
});
test('click and file-menu saving retain the live dirty editor behavior',()=>{
let saves=0;const view={excalidrawAPI:{},isDirty:()=>true,save(){saves++;}};
const manager=new EventManager({app:{},activeExcalidrawView:view});
manager.onClickSaveActiveDrawing({target:{className:'markdown'}});
manager.onFileMenuSaveActiveDrawing();assert.equal(saves,2);
manager.onClickSaveActiveDrawing({target:{className:'excalidraw__canvas'}});assert.equal(saves,2);
view.isDirty=()=>false;manager.onFileMenuSaveActiveDrawing();assert.equal(saves,2);
});
+2 -2
View File
@@ -15,7 +15,7 @@ vm.runInNewContext(code, {
});
// This is the Extras service contract, independent of its bundled converter's version.
for (const [version, accepted] of [["2.2.2", false], ["3.0.0", true], ["3.0.1", false], ["3.1.0", false]]) {
for (const [version, accepted] of [["2.2.2", false], ["3.0.0", false], ["3.1.0", false], ["3.6.0", true], ["3.6.1", false]]) {
test(`Mermaid ${version} is ${accepted ? "accepted" : "rejected"} by the exact-version handshake`, () => {
const gateway = new exports.ExcalidrawExtrasGateway({
plugins: { manifests: { "excalidraw-extras": { version: "0.1.2" } } },
@@ -24,7 +24,7 @@ for (const [version, accepted] of [["2.2.2", false], ["3.0.0", true], ["3.0.1",
assert.equal(result.valid, accepted);
if (!accepted) {
assert.equal(result.isExact, true);
assert.equal(result.reqVersion, "3.0.0");
assert.equal(result.reqVersion, "3.6.0");
assert.equal(result.currentVersion, version);
}
});
@@ -0,0 +1,29 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
test("an enabled Extras plugin with an absent or incomplete API cancels service access cleanly", async () => {
const notices = [], graph = sourceHarness({
obsidian: { Modal: class {
contentEl = { empty() {} };
open() { this.onOpen(); } close() { this.onClose(); }
}, Notice: class { constructor(text) { notices.push(text); } }, Setting: class {} },
"../lang/helpers": { t: key => key }, "src/lang/locale/en": { default: {} },
});
try {
const { ExcalidrawExtrasGateway } = await graph.importModule("src/utils/ExcalidrawExtrasGateway.ts");
for (const api of [undefined, {}, { versions: {} }, { features: {}, versions: {} }, { versions: {}, features: { isActive() { return true; } } }]) {
const gateway = new ExcalidrawExtrasGateway({ plugins: {
manifests: { "excalidraw-extras": { version: "0.1.2" } }, plugins: { "excalidraw-extras": { api } },
} }, {});
assert.equal(await gateway.getMermaid(), null);
}
assert.equal(notices.length, 5);
assert.ok(notices.every(text => text === "EXTRAS_GATEWAY_API_MISSING"));
const gateway = new ExcalidrawExtrasGateway({ plugins: { manifests: { "excalidraw-extras": { version: "0.2.1" } } } }, {});
for (const versions of [undefined, {}, { mathjax: undefined }, { mathjax: 1 }]) {
const result = gateway.checkVersion("mathjax", { versions });
assert.equal(result.valid, false); assert.equal(result.currentVersion, "0.0.0");
}
} finally { graph.close(); }
});
+43
View File
@@ -0,0 +1,43 @@
/** Run the actual picker constructor against unsupported frontmatter and valid aliases. */
import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
import vm from "node:vm";
import ts from "typescript";
const exports = {};
class SuggestionModal {
constructor(app, input, items) { this.app = app; this.inputEl = input; this.items = items; }
setPlaceholder() {}
}
vm.runInNewContext(ts.transpileModule(readFileSync(new URL("../../src/shared/Suggesters/FileSuggestionModal.ts", import.meta.url), "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText, { exports, require: name => ({
"./SuggestionModal": { SuggestionModal }, "src/lang/helpers": { t: value => value },
"src/utils/styleUtils": { setStyle() {} },
}[name] ?? {}) });
function picker(values) {
const items = values.map((aliases, i) => ({ path: `Notes/File-${i}.md`, aliases }));
const app = { metadataCache: { getFileCache: file => ({ frontmatter: { aliases: file.aliases } }) } };
const input = { inputEl: { clientWidth: 200, addEventListener() {} } };
return { items, modal: new exports.FileSuggestionModal(app, input, items, {}) };
}
test("unsupported alias metadata cannot hide mixed vault files or mutate YAML values", () => {
const values = [undefined, null, {}, { "[object Object]": null }, 1, true, [null, {}, false, 7, ""]];
const before = structuredClone(values);
const { items, modal } = picker(values);
assert.equal(modal.getItems().length, items.length);
assert.deepEqual(Array.from(modal.getItems(), item => item.path), items.map(item => item.path));
assert.deepEqual(values, before);
});
test("string aliases remain whole and valid list members remain searchable after reopening", () => {
for (let i = 0; i < 2; i++) {
const { modal } = picker(["Whole alias", ["First", null, {}, "Second", ""]]);
assert.deepEqual(Array.from(modal.getItems(), item => modal.getItemText(item)), [
"Notes/File-0.md", "Notes/File-0.md|Whole alias", "Notes/File-1.md", "Notes/File-1.md|First", "Notes/File-1.md|Second",
]);
}
});
@@ -0,0 +1,39 @@
import assert from "node:assert/strict";
import test, { after } from "node:test";
import { load } from "js-yaml";
import { sourceHarness } from "./sourceHarness.mjs";
const graph = sourceHarness({ obsidian: { parseYaml: load } });
const { getFrameAnchors, resolveThumbnailFrame, syncFrameAnchors, writeFrameProperty, readFrameProperty } = await graph.importModule("src/utils/frameMetadata.ts");
after(() => graph.close());
const frame = (id, name, frameRole) => ({ id, name, type: "frame", x: 10, y: 20, width: 200, height: 100, frameRole });
test("frame anchors include actual regular and marker names, preserving order and punctuation", () => {
const scene = [frame("a", null), frame("b", " "), frame("c", "Frame"), frame("d", "中心, padding=20", "marker"), frame("e", "Frame"), { ...frame("f", "Deleted"), isDeleted: true }];
assert.deepEqual(getFrameAnchors(scene), ["Frame", "中心, padding=20"]);
const source = '---\ncustom: "keep"\nnested:\n value: yes\n---\nBody\n';
const result = syncFrameAnchors(source, scene);
assert.deepEqual(readFrameProperty(result, "excalidraw-anchors"), ["Frame", "中心, padding=20"]);
assert.ok(result.includes('custom: "keep"\nnested:\n value: yes\n')); assert.ok(result.endsWith("---\nBody\n"));
assert.equal(syncFrameAnchors(result, scene), result);
assert.ok(syncFrameAnchors(source, scene, false).indexOf("excalidraw-anchors:") > source.indexOf("nested:"));
});
test("frame metadata replaces only its own multiline property and leaves invalid YAML untouched", () => {
const source = '---\nfirst: 1\nexcalidraw-anchors:\n - Old\n# Keep this comment\nlast: 2\n---\nText\n';
const result = syncFrameAnchors(source, [frame("a", "A: \"quote\"")]);
assert.equal(result, '---\nfirst: 1\nexcalidraw-anchors:\n - "A: \\"quote\\""\n# Keep this comment\nlast: 2\n---\nText\n'.replaceAll('\\\\"','\\"'));
assert.equal(syncFrameAnchors('---\nbroken: [\n---\n', [frame("a", "A")]), '---\nbroken: [\n---\n');
assert.equal(syncFrameAnchors('---\ncustom: 1\n---\n', []), '---\ncustom: 1\n---\n');
assert.equal(writeFrameProperty(source, "other", "no"), source);
assert.equal(syncFrameAnchors('---\n---\nBody', [frame("a", "A")]), '---\nexcalidraw-anchors:\n - "A"\n---\nBody');
assert.equal(syncFrameAnchors('---\r\nkeep: yes\r\n---\r\nBody', [frame("a", "A")]), '---\r\nexcalidraw-anchors:\r\n - "A"\r\nkeep: yes\r\n---\r\nBody');
});
test("thumbnail YAML uses exact unique names and supports manual edits, commas and suffixes", () => {
const scene = [frame("a", "Main,padding=10"), frame("b", "Dupe"), frame("c", "Dupe", "marker")];
assert.equal(resolveThumbnailFrame(scene, "Main,padding=10")?.id, "a");
for (const name of [null, "", "Dupe", "a", "missing", []]) assert.equal(resolveThumbnailFrame(scene, name), null);
const doc = writeFrameProperty('---\nfoo: yes\n---\nBody', "excalidraw-thumbnail", "Main,padding=10");
assert.equal(readFrameProperty(doc), "Main,padding=10");
assert.equal(readFrameProperty(writeFrameProperty(doc, "excalidraw-thumbnail", undefined)), undefined);
});
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import test from "node:test";
import { load } from "js-yaml";
import { sourceHarness } from "./sourceHarness.mjs";
test("frame navigation preserves search and mode, distinguishes unnamed frames and rejects retired owners", async () => {
const calls = [], graph = sourceHarness({ obsidian: { parseYaml: load, FuzzySuggestModal: class { setPlaceholder() {} onClose() {} } }, "src/lang/helpers": { t: key => key } });
try {
const { FrameNavigator } = await graph.importModule("src/shared/Dialogs/FrameNavigator.ts");
const elements = [{ type: "frame", id: "regular", name: null }, { type: "frame", frameRole: "marker", id: "marker", name: null }, { type: "rectangle", id: "other" }];
const view = { app: {}, file: {}, excalidrawAPI: {}, getViewElements: () => elements, isClosingOrMigrating: () => false, zoomToElementId: (...args) => calls.push(args), search: "existing search", mode: "edit" };
const picker = new FrameNavigator(view, () => calls.push("closed"));
assert.deepEqual(picker.getItems(), elements.slice(0, 2));
assert.equal(picker.getItemText(elements[0]), "FRAME_UNNAMED (regular)");
assert.equal(picker.getItemText(elements[1]), "FRAME_UNNAMED_MARKER (marker)");
picker.onChooseItem(elements[1]); assert.deepEqual(calls, [["marker", false]]);
assert.equal(view.search, "existing search"); assert.equal(view.mode, "edit");
view.excalidrawAPI = {}; picker.onChooseItem(elements[0]); assert.equal(calls.length, 1);
picker.onClose(); assert.equal(calls.at(-1), "closed");
} finally { graph.close(); }
});
@@ -0,0 +1,87 @@
/** Execute the full production template/export module with only host/export boundaries substituted. */
import assert from "node:assert/strict";
import test from "node:test";
import vm from "node:vm";
import { readFileSync } from "node:fs";
import ts from "typescript";
import { load } from "js-yaml";
function fixture(property = '"Main,padding=20"') {
let source = `---\nexcalidraw-plugin: parsed\nexcalidraw-thumbnail: ${property}\n---\n## Drawing\n`;
const frame = { id: "frame-id", type: "frame", name: "Main,padding=20", x: 10, y: 20, width: 120, height: 80, isDeleted: false };
let elements = [frame, { id: "in", type: "rectangle", x: 20, y: 30, width: 5, height: 5, frameId: "frame-id" }, { id: "out", type: "rectangle", x: 1000, y: 1000, width: 5, height: 5 }];
class TFile { path = "Drawing.md"; extension = "md"; }
const file = new TFile(), requests = []; let encode = async options => options;
const context = vm.createContext({ console, PLUGIN_VERSION: "test" });
const compile = (path, mocks) => {
const code = ts.transpileModule(readFileSync(new URL('../../' + path, import.meta.url), 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText;
const exports = {}; vm.runInContext(`(function(require,exports){${code}\n})`, context)(name => mocks[name] ?? {}, exports); return exports;
};
const parts = compile('src/utils/embeddedFilenameParts.ts', {});
const metadata = compile('src/utils/frameMetadata.ts', { obsidian: { parseYaml: load } });
const api = compile('src/utils/excalidrawAutomateUtils.ts', {
'./frameMetadata': metadata,
obsidian: { TFile, normalizePath: value => value },
'src/shared/TextMode': { getTextMode: () => 'parsed' },
'src/shared/ExcalidrawData': { ExcalidrawData: class {
scene = { elements: structuredClone(elements), appState: { theme: 'light' }, files: {} };
async loadData() {} destroy() {}
}, getExcalidrawMarkdownHeaderSection: value => value },
'src/utils/utils': { ...parts, getPNG: async (_scene, options) => { requests.push(options); return encode(options); }, getSVG: async (_scene, options) => { requests.push(options); return { viewBox: { baseVal: {} }, setAttribute() {} }; } },
'./excalidrawViewUtils': { getFrameBasedOnFrameNameOrId: name => elements.find(frame => frame.type === 'frame' && (frame.id === name || frame.name === name)) },
'./excalidrawElementUtils': { cloneElement: element => ({ ...element }) },
'src/constants/safeUrls': { URLs: {} },
});
const plugin = { app: { vault: { read: async () => source }, metadataCache: { getFirstLinkpathDest: () => file } }, settings: { exportPaddingSVG: 10 }, ea: { getElementsInFrame: frame => frame ? elements.filter(element => element.id === frame.id || element.frameId === frame.id) : [] } };
const loader = { loadSceneFiles: async () => {} }, options = { withBackground: false, withTheme: false, isMask: false, drawingThumbnail: true };
return { api, plugin, loader, options, requests, frame, encode: value => { encode = value; }, source: value => { source = value; }, elements: value => { elements = value; } };
}
test("default thumbnails resolve exact YAML names while explicit whole/frame and ordinary exports retain precedence", async () => {
const f = fixture();
const get = (target, preview) => f.api.getTemplate(f.plugin, target, false, f.loader, 0, false, undefined, preview);
assert.equal((await get('Drawing.md', true)).thumbnailFrame.id, 'frame-id');
assert.equal((await get('Drawing.md#^as-image', true)).thumbnailFrame.id, 'frame-id');
assert.equal((await get('Drawing.md', false)).thumbnailFrame, undefined);
const whole = await get('Drawing.md#^frame=', true);
assert.equal(whole.thumbnailFrame, undefined); assert.equal(whole.elements.length, 3);
const explicit = await get('Drawing.md#^frame=frame-id', true);
assert.equal(explicit.thumbnailFrame, undefined); assert.equal(explicit.elements.length, 2);
});
test("missing, ambiguous and invalid thumbnails fall back to the complete scene", async () => {
for (const value of ['Missing', 'null', '[]', '""']) {
const f = fixture(value), scene = await f.api.getTemplate(f.plugin, 'Drawing.md', false, f.loader, 0, false, undefined, true);
assert.equal(scene.thumbnailFrame, undefined); assert.equal(scene.elements.length, 3);
}
const f = fixture(); f.elements([f.frame, { ...f.frame, id: 'other', frameRole: 'marker' }]);
assert.equal((await f.api.getTemplate(f.plugin, 'Drawing.md', false, f.loader, 0, false, undefined, true)).thumbnailFrame, undefined);
});
test("PNG and SVG preview exports forward strict frame cropping without changing full-scene export defaults", async () => {
const f = fixture();
await f.api.createPNG('Drawing.md', 1, f.options, f.loader, 'light', undefined, undefined, [], f.plugin, 0);
await f.api.createSVG('Drawing.md', false, f.options, f.loader, 'light', undefined, undefined, [], f.plugin, 0);
assert.deepEqual(f.requests.map(options => options.exportingFrame.id), ['frame-id', 'frame-id']);
await f.api.createPNG('Drawing.md', 1, { ...f.options, drawingThumbnail: false }, f.loader, 'light', undefined, undefined, [], f.plugin, 0);
assert.equal(f.requests.at(-1).exportingFrame, undefined);
});
test("cancelled PNG exports stop before rasterization or discard a completed encoder result", async () => {
const f = fixture(), args = () => ['Drawing.md', 3, f.options, f.loader, 'light', undefined, undefined, [], f.plugin, 0];
f.loader.terminate = true;
await f.api.createPNG(...args()); assert.equal(f.requests.length, 0);
f.loader.terminate = false;
let release; const read = new Promise(resolve => { release = resolve; }); f.plugin.app.vault.read = () => read;
const pending = f.api.createPNG(...args()); f.loader.terminate = true; release('');
assert.equal(await pending, null); assert.equal(f.requests.length, 0);
f.loader.terminate = false; f.plugin.app.vault.read = async () => '';
f.loader.loadSceneFiles = async () => { queueMicrotask(() => { f.loader.terminate = true; }); };
assert.equal(await f.api.createPNG(...args()), null); assert.equal(f.requests.length, 0);
f.loader.terminate = false; f.loader.loadSceneFiles = async () => {};
let finishEncoding, started;
const encoding = new Promise(resolve => { finishEncoding = resolve; }), entered = new Promise(resolve => { started = resolve; });
f.encode(() => { started(); return encoding; });
const last = f.api.createPNG(...args()); await entered; f.loader.terminate = true; finishEncoding(new Blob(['png']));
assert.equal(await last, null); assert.equal(f.requests.length, 1);
});
@@ -0,0 +1,95 @@
import assert from "node:assert/strict";
import test from "node:test";
import { load } from "js-yaml";
import { sourceHarness } from "./sourceHarness.mjs";
async function fixture(policy = "always") {
const prompts = [], errors = [], settingsWrites = [];
class Prompt {
constructor(_plugin, message, buttons) { this.message = message; this.buttons = buttons; this.waitForClose = new Promise(resolve => { this.resolve = resolve; }); prompts.push(this); }
close() { this.resolve(null); } choose(value) { this.resolve(value); }
}
const graph = sourceHarness({ obsidian: { Notice: class {}, parseYaml: load },
"src/shared/Dialogs/FrameNavigator": { FrameNavigator: class { open() {} close() {} } },
"src/lang/helpers": { t: key => key }, "src/utils/coreUtils": { errorlog: value => errors.push(value) } });
const { FrameThumbnailController } = await graph.importModule("src/view/managers/FrameThumbnailController.ts");
const { readFrameProperty } = await graph.importModule("src/utils/frameMetadata.ts");
const file = { path: "Drawing.md" }, api = {};
let disk = '---\nexcalidraw-plugin: parsed\nexcalidraw-thumbnail: A\nunknown: sentinel\n---\nBody', closed = false, saves = 0;
let elements = [{ id: "frame-id", type: "frame", name: "A", x: 0, y: 0, width: 100, height: 80 }];
const view = { file, excalidrawAPI: api, data: disk, compatibilityMode: false,
app: { vault: { read: async () => disk, getFileByPath: path => path === file.path ? file : null } },
plugin: { _loaded: true, settings: { thumbnailRenamePolicy: policy, unknown: "sentinel" }, saveSettings: async () => settingsWrites.push(structuredClone(view.plugin.settings)) },
getViewElements: () => elements, isClosingOrMigrating: () => closed, setDirty() {},
forceSave: async () => { saves++; view.data = disk = controller.applyHeader(view.data, elements); },
};
const controller = new FrameThumbnailController(view, Prompt); controller.update(elements, true);
const flush = () => new Promise(resolve => setImmediate(resolve));
const rename = name => { elements = [{ ...elements[0], name }]; controller.update(elements); };
return { controller, view, file, api, prompts, errors, settingsWrites, rename, flush, yaml: () => readFrameProperty(disk), saves: () => saves,
scene: value => { elements = value; controller.update(elements); },
external: name => { disk = disk.replace(/excalidraw-thumbnail:.*\n/, 'excalidraw-thumbnail: ' + JSON.stringify(name) + '\n'); },
close: () => { closed = true; controller.reset(); graph.close(); } };
}
test("thumbnail rename follows always policy and undo/redo without replacing user hooks or unknown settings", async () => {
const f = await fixture();
try {
const hook = () => {}; f.view.onSceneChangeHook = hook;
f.rename("B"); await f.flush(); assert.equal(f.yaml(), "B");
f.rename("A"); await f.flush(); assert.equal(f.yaml(), "A");
f.rename("B"); await f.flush(); assert.equal(f.yaml(), "B");
assert.equal(f.prompts.length, 0); assert.equal(f.saves(), 3); assert.equal(f.view.onSceneChangeHook, hook);
assert.equal(f.view.plugin.settings.unknown, "sentinel");
} finally { f.close(); }
});
test("first rename persists a selected policy and ask allows a different decision on subsequent renames", async () => {
const f = await fixture("unset");
try {
f.rename("B"); assert.equal(f.prompts.length, 1); f.prompts[0].choose("ask"); await f.flush();
assert.equal(f.settingsWrites[0].thumbnailRenamePolicy, "ask"); assert.equal(f.settingsWrites[0].unknown, "sentinel");
f.prompts[1].choose(false); await f.flush(); assert.equal(f.yaml(), "A");
f.rename("C"); f.prompts[2].choose(true); await f.flush(); assert.equal(f.yaml(), "C");
} finally { f.close(); }
});
test("cancelling first-rename policy does not reopen a prompt on unchanged selection or scene updates", async () => {
const f = await fixture("unset");
try { f.rename("B"); f.prompts[0].close(); await f.flush(); f.rename("B"); await f.flush(); assert.equal(f.prompts.length, 1); assert.equal(f.yaml(), "A"); }
finally { f.close(); }
});
test("a rename reverted while its own YAML write settles keeps tracking the same frame", async () => {
const f = await fixture();
try {
const save = f.view.forceSave; let first = true;
f.view.forceSave = async () => { await save(); if (first) { first = false; f.rename("A"); } };
f.rename("B"); await f.flush(); await f.flush();
assert.equal(f.yaml(), "A"); assert.equal(f.saves(), 2);
} finally { f.close(); }
});
test("a context-menu thumbnail choice establishes identity before the next scene event renames it", async () => {
const f = await fixture();
try {
f.scene([{ id: "other", type: "frame", name: "Other", x: 0, y: 0, width: 100, height: 80 }]);
assert.equal(await f.controller.setThumbnail("Other"), true);
f.rename("Renamed"); await f.flush();
assert.equal(f.yaml(), "Renamed");
} finally { f.close(); }
});
test("external YAML changes, blank names and retired views cannot be overwritten by a pending rename", async () => {
for (const kind of ["external", "blank", "retired"]) {
const f = await fixture("ask");
try {
f.rename("B"); const prompt = f.prompts[0];
if (kind === "external") f.external("Manual");
if (kind === "blank") f.rename("");
if (kind === "retired") f.controller.reset();
prompt.choose(true); await f.flush();
assert.equal(f.yaml(), kind === "external" ? "Manual" : "A"); assert.equal(f.saves(), 0);
} finally { f.close(); }
}
});
+3
View File
@@ -4,6 +4,7 @@ import {existsSync,lstatSync,realpathSync} from 'node:fs';
import {dirname,resolve,sep} from 'node:path';
import {parseCLIJSON} from './inAppTask.mjs';
import {retryReadOnly} from './readOnlyTransport.mjs';
import {nativeReadyCode} from './hostReadiness.mjs';
/** Run once in the selected renderer; retain the outcome before returning it to CLI transport. */
export async function recordCLIResult(key, id, source) {
@@ -39,6 +40,8 @@ export function createAcknowledgedCLI(run, {token=randomUUID().replaceAll('-',''
const readOnly=['version','help','commands'].includes(name)
|| name==='vault'&&args.every(arg=>arg.startsWith('info='))
|| name==='dev:errors'&&args.length===0
// Only this exact probe can cross a renderer reload without a receipt.
|| name==='eval'&&args.length===1&&args[0]==='code='+nativeReadyCode
|| /^obsidian-excalidraw-plugin:(help|status|skill|list|schema|api|read|result)$/.test(name);
if(readOnly)return read(name,args);
if(name==='dev:errors'&&args.length===1&&args[0]==='clear') {
@@ -2,6 +2,26 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import vm from 'node:vm';
import {recordCLIResult,createAcknowledgedCLI} from './acknowledgedCLI.mjs';
import {nativeReadyCode,waitForNativeReady} from './hostReadiness.mjs';
test('reload readiness retries its exact read-only probe without a renderer receipt',async()=>{
let clock=0,reads=0,wrapped=0;
const transport=createAcknowledgedCLI(()=>{throw Error('Unexpected default path');},{token:'reload',timeoutMs:200,now:()=>clock,wait:ms=>clock+=ms,invoke:(name,args)=>{
assert.equal(name,'eval');
if(args[0]==='code='+nativeReadyCode){if(++reads===1)throw Error('ETIMEDOUT');return '=> {"ready":true,"runtime":true,"mobile":true}';}
if(args[0].startsWith('code=JSON.stringify(globalThis['))return '=> null';
wrapped++;throw Error('ETIMEDOUT');
}});
const result=await waitForNativeReady(transport.cli,{now:()=>clock,wait:async ms=>clock+=ms,timeoutMs:200});
assert.equal(result.mobile,true);assert.equal(reads,2);assert.equal(wrapped,0);assert.equal(transport.diagnostics.length,1);
});
test('a readiness lookalike remains receipted instead of becoming a retryable eval',()=>{
let source;
const transport=createAcknowledgedCLI(()=>{throw Error('Unexpected default path');},{invoke:(name,args)=>{source=args[0];return '=> true';}});
transport.cli('eval','code='+nativeReadyCode+'; mutate()');
assert.match(source,/recordCLIResult/);
});
test('renderer receipt records an actual async result once before acknowledging it',async()=>{
const context=vm.createContext({calls:0});
+118
View File
@@ -0,0 +1,118 @@
/** Native settings and interactive Markdown regressions; no real API credentials. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
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 aiAndEmbedsCaseIds = ["main", "popout"].flatMap(context => [
"native:markdown-embed-scroll-3055:" + context,
"native:ai-settings-preservation:" + context,
]);
export async function runAIAndEmbedsScenario({ cli, drawingPath }) {
const template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8");
const tests = [], consoleErrors = [], windowErrors = [];
for (const context of ["main", "popout"]) {
const execute = new Function(`return async function(c,path,context,template){
const env=await (${behaviorEnvironment.toString()})(c,path,{id:context,input:'mouse'},template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()});
await (${exerciseAIAndEmbeds.toString()})(c,env);
return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors};
}`)();
const result = await runInAppTask({ cli, execute, args:[drawingPath,context,template], timeoutMs:300000, cleanupMs:60000,
onRequest:behaviorInputDriver(cli), onProgress:phase=>{if(phase)process.stdout.write("AI/embeds: "+phase+"\n");},
}).catch(error=>{error.evidence=[...tests,...(error.evidence||[])];throw error;});
tests.push(...result.tests); consoleErrors.push(...result.consoleErrors); windowErrors.push(...result.windowErrors);
}
assert.equal(consoleErrors.length,0,"AI/embed scenarios emitted console errors");
assert.equal(splitWindowErrors(windowErrors).unexpected.length,0,"AI/embed scenarios emitted window errors");
return {id:"ai-and-embeds",status:"passed",tests,consoleErrors,windowErrors};
}
async function exerciseAIAndEmbeds(c,env) {
const {p,doc,win,check,openDrawing,create,geometry} = env;
const context=geometry().requested.id;
await c.case("native:markdown-embed-scroll-3055:"+context,["P03","P05"],async()=>{
const note=await create("scroll-note.md",Array.from({length:100},(_,i)=>"## Section "+i+"\n\nParagraph "+i+" with enough text to require scrolling.\n").join("\n"));
const view=await openDrawing("scroll-drawing"), api=view.excalidrawAPI;
p.settings.markdownNodeOneClickEditing=false;
const variants=[];
for(const locked of [true,false]) for(const viewMode of [false,true]) {
api.updateScene({elements:[],appState:{viewModeEnabled:viewMode},captureUpdate:"NEVER"});
const ea=p.ea.getAPI(view);
let id;
try {
id=ea.addEmbeddable(0,0,500,300,undefined,note);
ea.getElement(id).customData={mdProps:{useObsidianDefaults:true,lockedReadingMode:locked}};
await ea.addElementsToView(false,true,true);
} finally {ea.destroy();}
const element=api.getSceneElements().find(el=>el.id===id);api.zoomToFit([element],1,0.1);
let preview;
await c.waitFor(()=>{
preview=view.containerEl.querySelector('#embed-'+id+' .markdown-preview-view');
return preview?.clientHeight>0&&preview.scrollHeight>preview.clientHeight+100;
},"long embedded Markdown preview");
api.updateScene({appState:{activeEmbeddable:{element,state:"active"}},captureUpdate:"NEVER"});
await c.waitFor(()=>api.getAppState().activeEmbeddable?.state==="active","active reading embed");
c.observations={locked,viewMode,overflow:win.getComputedStyle(preview).overflowY,html:preview.outerHTML.slice(0,700),ancestors:[]};
for(let parent=preview.parentElement;parent&&parent!==doc.body;parent=parent.parentElement)c.observations.ancestors.push(parent.className);
let x,y;
await c.waitFor(()=>{
const r=preview.getBoundingClientRect();x=r.left+r.width/2;y=r.top+r.height/2;
return preview.contains(doc.elementFromPoint(x,y));
},"active preview receives wheel input after React renders the mode change");
const state={locked,viewMode,overflow:win.getComputedStyle(preview).overflowY,height:preview.clientHeight,scrollHeight:preview.scrollHeight,html:preview.parentElement.outerHTML.slice(0,700)};
c.observations={...c.observations,scroll:state};
await env.input("Input.dispatchMouseEvent",{type:"mouseMoved",x,y});
await env.input("Input.dispatchMouseEvent",{type:"mouseWheel",x,y,deltaX:0,deltaY:180});
await c.waitFor(()=>preview.scrollTop>0,"mouse wheel scrolls reading-mode Markdown");
check(api.getAppState().activeEmbeddable?.state==="active","scroll deactivated the embed");
variants.push({...state,scrollTop:preview.scrollTop});
api.updateScene({appState:{activeEmbeddable:null},captureUpdate:"NEVER"});
}
return {variants,assertions:["trusted wheel scrolls locked and unlocked Markdown without entering edit mode","drawing view mode does not prevent embedded scrolling"]};
});
await c.case("native:ai-settings-preservation:"+context,["P01","P07"],async()=>{
const profileId="Test AI source", modelId="Test reasoning model";
const originalSecret=app.secretStorage?.getSecret;
if(app.secretStorage) {
app.secretStorage.getSecret=function(id){return id==="excalidraw-native-fake-key"?"fake-device-key":originalSecret.call(this,id);};
c.defer(()=>{app.secretStorage.getSecret=originalSecret;});
}
p.settings.aiProviderProfiles[profileId]={provider:"openai",baseURL:"https://example.invalid/v1",apiKey:"fake-synced-key",apiKeySource:"secret",apiKeySecret:"excalidraw-native-fake-key",futureProfileProperty:17};
p.settings.aiTextModelConfigs[modelId]={providerId:profileId,model:"gpt-6.1-sol",reasoningEffort:"low",multimodalSupport:true,futureModelProperty:false};
p.settings.aiDefaultTextModel=modelId;p.settings.aiDefaultMultimodalModel=modelId;
p.settings.taskboneAPIKeySource="secret";p.settings.taskboneAPIKeySecret="excalidraw-native-fake-key";p.settings.taskboneAPIkey="fake-ocr-key";
p.settings.__behaviorFutureSetting={zero:0,flag:false};
await p.saveSettings();
const disk=await p.loadData();
check(disk.aiProviderProfiles[profileId].apiKey===""&&disk.taskboneAPIkey==="","secret source retained a synced key");
check(!JSON.stringify(disk).includes("fake-device-key"),"resolved secret leaked into settings");
const snapshot=p.ea.getAISettings();check(snapshot.providerProfiles[profileId].hasApiKey===!!app.secretStorage,"secret availability is wrong");
check(snapshot.textModels[modelId].reasoningEffort==="low","EA snapshot lost reasoning preference");
check(!JSON.stringify(snapshot).includes("fake-device-key"),"EA exposed a key");
if(context==="popout") {
check(disk.aiTextModelConfigs[modelId].reasoningEffort==="low"&&disk.aiTextModelConfigs[modelId].futureModelProperty===false,"popout save lost model settings");
check(disk.aiProviderProfiles[profileId].apiKeySecret==="excalidraw-native-fake-key"&&disk.aiProviderProfiles[profileId].futureProfileProperty===17,"popout save lost provider settings");
check(disk.taskboneAPIKeySecret==="excalidraw-native-fake-key"&&disk.__behaviorFutureSetting.zero===0,"popout save lost OCR or unknown settings");
return {assertions:["popout uses the shared credential source and reasoning snapshot","popout saves references and unknown settings without secret values"],reloadCoverage:"separate main-window case"};
}
const views=app.workspace.getLeavesOfType("excalidraw").map(leaf=>leaf.view);
for(const view of views)if(view.excalidrawAPI&&view.isDirty())check((await view.saveWithOutcome()).status==="persisted","pre-reload save failed");
await c.waitFor(()=>views.every(view=>!view.isSaveInProgress()&&!view.isSynchronizing),"pre-reload writes settle");
await app.plugins.disablePlugin("obsidian-excalidraw-plugin");
await c.waitFor(()=>views.every(view=>!view.excalidrawAPI),"old drawing roots unmount before reload");
await app.plugins.enablePlugin("obsidian-excalidraw-plugin");
let live;
await c.waitForCleanup(()=>(live=app.plugins.plugins["obsidian-excalidraw-plugin"])!==p&&live?.isReady,"fresh plugin instance becomes ready");
check(live!==p,"reload reused the plugin instance");
check(live.settings.aiDefaultTextModel===modelId&&live.settings.aiDefaultMultimodalModel===modelId,"reload changed defaults");
check(live.settings.aiTextModelConfigs[modelId].reasoningEffort==="low"&&live.settings.aiTextModelConfigs[modelId].futureModelProperty===false,"reload lost model settings");
check(live.settings.aiProviderProfiles[profileId].apiKeySecret==="excalidraw-native-fake-key"&&live.settings.aiProviderProfiles[profileId].futureProfileProperty===17,"reload lost provider settings");
check(live.settings.taskboneAPIKeySource==="secret"&&live.settings.taskboneAPIKeySecret==="excalidraw-native-fake-key","reload lost OCR source");
check(live.settings.__behaviorFutureSetting.zero===0&&live.settings.__behaviorFutureSetting.flag===false,"reload lost unknown keys");
return {assertions:["secret references and reasoning effort survive real plugin unload/reload","synced settings contain neither secret values nor discarded manual keys","unknown profile, model and settings keys survive"]};
});
}
+57 -4
View File
@@ -122,15 +122,15 @@ test("trusted click waits for a sliding mobile control to settle before dispatch
assert.equal(h.events[0].params.y,90);
});
function saveHarness({failed=false,mismatch=false}={}) {
function saveHarness({failed=false,mismatch=false,synchronizing=false}={}) {
const source=readFileSync(new URL('./behaviorEnvironment.mjs',import.meta.url),'utf8');
const file=ts.createSourceFile('behaviorEnvironment.mjs',source,ts.ScriptTarget.Latest,true);let initializer;
function visit(node){if(ts.isVariableDeclaration(node)&&node.name.getText(file)==='saveReopen')initializer=node.initializer;ts.forEachChild(node,visit);}visit(file);
assert.ok(initializer);let busy=true,saves=0,opens=0;
assert.ok(initializer);let busy=!synchronizing,saves=0,opens=0;
const drawing={path:'owned.md'},api={getSceneElements:()=>[{id:'a'}]};
const view={file:drawing,excalidrawAPI:api,isSaveInProgress:()=>busy,async saveWithOutcome(){saves++;return{status:busy?'skipped':failed?'failed':'persisted',requestedRevision:1,acknowledgedRevision:failed?null:1,currentRevision:1};}};
const view={file:drawing,excalidrawAPI:api,isSynchronizing:synchronizing,isSaveInProgress:()=>busy,async saveWithOutcome(){saves++;return{status:busy||this.isSynchronizing?'skipped':failed?'failed':'persisted',requestedRevision:1,acknowledgedRevision:failed?null:1,currentRevision:1};}};
const leaf={view,async setViewState(){},async openFile(value){assert.equal(value,drawing);opens++;}};view.leaf=leaf;
const c={caseTrace:{},async waitFor(predicate){if(!predicate())busy=false;assert.equal(predicate(),true);}};
const c={caseTrace:{},async waitFor(predicate){if(!predicate()){busy=false;view.isSynchronizing=false;}assert.equal(predicate(),true);}};
const saveReopen=vm.runInNewContext(`(${initializer.getText(file)})`,{c,leaf,context:{id:'main'},app:{workspace:{setActiveLeaf(value){assert.equal(value,leaf);}}},check:(condition,label)=>assert.ok(condition,label),ready:async()=>{},p:{ea:{getSceneFromFile:async()=>({elements:[{id:mismatch?'wrong':'a'}]})}}});
return{saveReopen,view,c,saves:()=>saves,opens:()=>opens};
}
@@ -139,8 +139,61 @@ test('native save/reopen waits for external synchronization before requiring phy
const h=saveHarness();assert.equal(await h.saveReopen(h.view),h.view);assert.equal(h.saves(),1);assert.equal(h.opens(),1);assert.equal(h.c.caseTrace.saveOutcome.status,'persisted');
});
test('native save/reopen waits for synchronization even when no save is in progress',async()=>{
const h=saveHarness({synchronizing:true});assert.equal(h.view.isSaveInProgress(),false);assert.equal(await h.saveReopen(h.view),h.view);assert.equal(h.saves(),1);assert.equal(h.opens(),1);assert.equal(h.c.caseTrace.saveOutcome.status,'persisted');
});
test('native save/reopen still refuses failed acknowledgements and mismatched physical scenes',async()=>{
for(const options of [{failed:true},{mismatch:true}]){
const h=saveHarness(options);await assert.rejects(h.saveReopen(h.view),/not physically acknowledged|scene IDs differ on disk/);assert.equal(h.saves(),1);assert.equal(h.opens(),0);
}
});
function extractionModalHarness(active='popout') {
const source=readFileSync(new URL('./workflowBundle.mjs',import.meta.url),'utf8');
const start=source.indexOf(' // Keep the selected image\'s drawing as the owner.');
const end=source.indexOf(' const normalize = path',start);
assert.ok(start>=0&&end>start);
let modal;
const createDocument=()=>({querySelector(){return modal?.ownerDocument===this?modal:null;}});
const main=createDocument(),popout=createDocument(),foreign=createDocument();
const current={main,popout,foreign}[active];
// Obsidian Modal uses the active document, even when a sidepanel button
// belongs to the main document and its selected drawing belongs to a popout.
const button={click(){modal={ownerDocument:current,querySelectorAll:()=>[]};}};
const tab={contentEl:{ownerDocument:main,querySelector:()=>({closest:()=>button})}};
const execute=vm.runInNewContext(`(async()=>{${source.slice(start,end)};return {doc,modal};})`,{tab,view:{ownerDocument:popout},activeDocument:current,check:(condition,label)=>assert.ok(condition,label),c:{waitFor:async(predicate,label)=>assert.ok(await predicate(),label)}});
return {execute,current};
}
test('native extraction follows the active modal document across main and popout ownership',async()=>{
for(const active of ['main','popout']){const h=extractionModalHarness(active),result=await h.execute();assert.equal(result.doc,h.current);assert.equal(result.modal.ownerDocument,h.current);}
});
test('native extraction rejects a modal in an unrelated document',async()=>{
await assert.rejects(extractionModalHarness('foreign').execute(),/unrelated document/);
});
test('native context-menu hit testing uses the integer point dispatched by Chromium', () => {
const source = readFileSync(new URL('./interactionBehavior.mjs', import.meta.url), 'utf8');
const file = ts.createSourceFile('interactionBehavior.mjs', source, ts.ScriptTarget.Latest, true);
let loop;
function visit(node) {
if (ts.isForOfStatement(node) && node.initializer.getText(file) === 'const [x, y]' &&
node.statement.getText(file).includes('menuPoint = point')) loop = node;
ts.forEachChild(node, visit);
}
visit(file);
assert.ok(loop);
const canvas = {}, toolbar = {};
// The narrow split puts the toolbar boundary between the fractional hit-test
// point and the integer coordinates used by the native contextmenu event.
const hit = (x, y) => y > 524.5 ? canvas : toolbar;
const point = vm.runInNewContext(`(() => { let menuPoint; ${loop.getText(file)} return menuPoint; })()`, {
r: { x: 337.5, y: 476.09375, width: 290.5, height: 323.90625 },
state: { zoom: { value: 1 }, scrollX: 0, scrollY: 0 }, scene: [],
doc: { elementFromPoint: hit }, canvas, Math,
});
assert.ok(Number.isInteger(point.x) && Number.isInteger(point.y));
assert.equal(hit(Math.trunc(point.x), Math.trunc(point.y)), canvas);
});
+15 -6
View File
@@ -56,8 +56,11 @@ export async function behaviorEnvironment(
c.phase = "behavior:" + context.id + ":cleanup";
const windows = new Map();
for (const leaf of [...owned].reverse()) {
const view = leaf.view,
owner = view.ownerWindow || view.containerEl.ownerDocument.defaultView;
const view = leaf.view;
// Plugin unload can detach its leaves entirely. Reload scenarios assert
// the captured roots unmounted before retiring those leaf identities.
if (!view) continue;
const owner = view.ownerWindow || view.containerEl.ownerDocument.defaultView;
if (!owner || owner.closed) {
await c.waitForCleanup(
() => !view.excalidrawAPI,
@@ -69,6 +72,10 @@ export async function behaviorEnvironment(
windows.get(owner).push({ leaf, view });
}
for (const [owner, entries] of windows) {
// Native Markdown autosave/reload can outlive setViewState(empty).
// Flush while the note exists, then let its update/render work settle.
for (const { view } of entries)
if (view.containerEl.isConnected && view.getViewType?.() === "markdown" && view.file) await view.save();
browserIdle.push(await settleBrowserDiagnostics(owner,windowErrors,'behavior:'+context.id));
for (const { view } of entries) view.exitFullscreen?.();
for (const { view } of entries)
@@ -102,9 +109,11 @@ export async function behaviorEnvironment(
});
const settings = structuredClone(p.settings);
c.defer(async () => {
delete p.settings.__behaviorFutureSetting;
Object.assign(p.settings, settings);
await p.saveSettings();
const live = app.plugins.plugins["obsidian-excalidraw-plugin"];
check(live?.isReady && live.settings, "Live plugin unavailable for behavior settings restoration");
delete live.settings.__behaviorFutureSetting;
Object.assign(live.settings, settings);
await live.saveSettings();
});
const ready = async (leaf) =>
c.waitFor(
@@ -382,7 +391,7 @@ export async function behaviorEnvironment(
// forced save that the view intentionally skips while it is still busy.
await c.waitFor(()=>{
check(view.leaf===leaf&&leaf.view===view&&view.file===file&&view.excalidrawAPI,"Save/reopen owner changed before persistence");
return !view.isSaveInProgress();
return !view.isSaveInProgress() && !view.isSynchronizing;
},"owned drawing save/synchronization readiness");
const saveOutcome=await view.saveWithOutcome();
c.caseTrace={...c.caseTrace,saveOutcome};
+2 -1
View File
@@ -1,6 +1,7 @@
/** Required core workflows across actual workspace contexts; no screenshots count as behavioral passes. */
import assert from "node:assert/strict";
import {viewportInput} from "./deviceViewport.mjs";
import {nativeKeyboardInput} from "./nativeKeyboard.mjs";
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { behavioralCases } from "../behaviorPlan.mjs";
@@ -80,7 +81,7 @@ export function behaviorInputDriver(cli, viewportScale=1) {
Number.isSafeInteger(request.params.contentsId),
);
const { contentsId, method, params } = request.params;
const sequence=(Array.isArray(params)?params:[params]).map(params=>viewportInput(method,params,viewportScale));
const sequence=(Array.isArray(params)?params:[params]).map(params=>viewportInput(method,method === "Input.dispatchKeyEvent" ? nativeKeyboardInput(params) : params,viewportScale));
assert.ok(sequence.length>0&&sequence.length<=4,'Bounded trusted input sequence required');
return parseCLIJSON(
cli(
@@ -15,6 +15,6 @@ test("stale installed converter fails before a producer can bundle it", () => {
}finally{rmSync(root,{recursive:true,force:true})}
});
test("incompatible live companion cannot be accepted as a prepared vault", () => {
assert.throws(()=>assertCompanionVersions(()=>JSON.stringify({ready:true,checks:{mermaid:{valid:false,currentVersion:"2.2.2",reqVersion:"3.0.0"}}})),/Prepared companion version mismatch/);
const result=assertCompanionVersions(()=>JSON.stringify({ready:true,versions:{mermaid:"3.0.0"},checks:{mermaid:{valid:true}}}));assert.equal(result.versions.mermaid,"3.0.0");
assert.throws(()=>assertCompanionVersions(()=>JSON.stringify({ready:true,checks:{mermaid:{valid:false,currentVersion:"2.2.2",reqVersion:"3.6.0"}}})),/Prepared companion version mismatch/);
const result=assertCompanionVersions(()=>JSON.stringify({ready:true,versions:{mermaid:"3.6.0"},checks:{mermaid:{valid:true}}}));assert.equal(result.versions.mermaid,"3.6.0");
});
+24 -3
View File
@@ -15,6 +15,8 @@ import { waitForNativeReady } from "./hostReadiness.mjs";
import { mainWindowExpression, restoreDeviceState } from "./deviceRecovery.mjs";
import { runBehaviorMatrix } from "./behaviorMatrix.mjs";
import { runKplexOntologyScenario } from "./kplexOntology.mjs";
import { runEmbedControlsScenario } from "./embedControls.mjs";
import { runFrameSemanticsScenario } from "./frameSemantics.mjs";
import {acquireBrowserDiagnostics,classifyCLIErrorText,splitWindowErrors} from './browserDiagnostics.mjs';
import { constrainedViewportMetrics, viewportInput } from "./deviceViewport.mjs";
import { retryReadOnly } from "./readOnlyTransport.mjs";
@@ -31,6 +33,8 @@ export async function runDeviceMatrix({
featureWorkflows = false,
featureCases,
kplexOntology = false,
embedControls = false,
frameSemantics = false,
}) {
reportDir = resolve(reportDir);
const target = validateTarget({
@@ -204,6 +208,16 @@ export async function runDeviceMatrix({
ontology=await runKplexOntologyScenario({cli,drawingPath:path,contexts:[profile.id.startsWith("phone-")?"phone":"tablet"],inputMode:"touch",viewportScale:viewportMetrics?.scale??1});
report.tests.push(...ontology.tests);
}
let embeds;
if (embedControls && ["phone-portrait-light", "tablet-portrait-full-light"].includes(profile.id)) {
embeds = await runEmbedControlsScenario({ cli, drawingPath: path, contexts: [profile.id.startsWith("phone-") ? "phone" : "tablet"], inputMode: "touch", viewportScale: viewportMetrics?.scale ?? 1 });
report.tests.push(...embeds.tests);
}
let frames;
if (frameSemantics && ["phone-portrait-light", "tablet-portrait-full-light"].includes(profile.id)) {
frames = await runFrameSemanticsScenario({ cli, drawingPath: path, contexts: [profile.id.startsWith("phone-") ? "phone" : "tablet"], inputMode: "touch", viewportScale: viewportMetrics?.scale ?? 1 });
report.tests.push(...frames.tests);
}
// Clearing viewport emulation resizes the real host again. Include that
// teardown in the quiet/error gate before starting the next profile.
if (viewportMetrics) {cli("dev:cdp", "method=Emulation.clearDeviceMetricsOverride", "params={}");viewportMetrics=null;}
@@ -212,13 +226,15 @@ export async function runDeviceMatrix({
...debuggerSession.read(),
...(workflows?.consoleErrors || []),
...(ontology?.consoleErrors || []),
...(embeds?.consoleErrors || []),
...(frames?.consoleErrors || []),
];
const unexpected = unexpectedConsoleErrors(errors, expectedConsoleErrors),
windowErrorText = cli("dev:errors").trim();
const windowEvents=browserSession.read(),classified=splitWindowErrors(windowEvents),cliErrors=classifyCLIErrorText(windowErrorText);
const errorGatePassed =
unexpected.length === 0 &&
classified.unexpected.length===0 && cliErrors.unexpected.length===0 && browserIdle.status==='passed' && (!workflows||workflows.status==='passed') && (!ontology||ontology.status==='passed');
classified.unexpected.length===0 && cliErrors.unexpected.length===0 && browserIdle.status==='passed' && (!workflows||workflows.status==='passed') && (!ontology||ontology.status==='passed') && (!embeds||embeds.status==='passed') && (!frames||frames.status==='passed');
browserSession.dispose();browserSession=null;
if(debuggerSession.transportDiagnostics?.length)report.transportDiagnostics.push(...debuggerSession.transportDiagnostics.map(item=>({profile:profile.id,...item})));
debuggerSession.dispose();
@@ -665,7 +681,7 @@ async function exerciseDevice(c, path, fixture, profile) {
const exit = view.containerEl.querySelector(".disable-zen-mode--visible");
return exit && doc.defaultView.getComputedStyle(exit).visibility === "visible" && Number(doc.defaultView.getComputedStyle(exit).opacity) > 0.99;
}, "device Zen exit control");
const exit = view.containerEl.querySelector(".disable-zen-mode--visible"), zoom = view.containerEl.querySelector(".reset-zoom-button");
const exit = view.containerEl.querySelector(".disable-zen-mode--visible"), zoom = view.containerEl.querySelector(".zoom-menu-trigger, .reset-zoom-button");
check(zoom, "Device Zen zoom indicator missing");
const a = rect(exit), b = rect(zoom), editor = rect(root);
check(!(Math.min(a.right, b.right) - Math.max(a.x, b.x) > 1 && Math.min(a.bottom, b.bottom) - Math.max(a.y, b.y) > 1), "Device Zen controls overlap");
@@ -683,7 +699,12 @@ async function exerciseDevice(c, path, fixture, profile) {
await input(profile.input === "touch" ? "touchStart" : "mousePressed", x, y);
await input(profile.input === "touch" ? "touchEnd" : "mouseReleased", x, y);
};
await tap(zoom); await c.waitFor(() => { c.observations.zenZoom = { zoom: api.getAppState().zoom.value, constraints: api.getAppState().scrollConstraints }; return api.getAppState().zoom.value === 1; }, "device Zen zoom action");
await tap(zoom);
if (zoom.classList.contains("zoom-menu-trigger")) {
await c.waitFor(() => doc.querySelector('[data-testid="zoom-menu-resetZoom"]'), "device Zen zoom menu");
await tap(doc.querySelector('[data-testid="zoom-menu-resetZoom"]'));
}
await c.waitFor(() => { c.observations.zenZoom = { zoom: api.getAppState().zoom.value, constraints: api.getAppState().scrollConstraints }; return api.getAppState().zoom.value === 1; }, "device Zen zoom action");
await tap(exit); await c.waitFor(() => !api.getAppState().zenModeEnabled, "device Zen exit action");
variants.push({ direction, exit: a, zoom: b });
}
@@ -0,0 +1,82 @@
/** 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;
let view = await env.openDrawing("Image-host", {}, template);
const ea = p.ea.getAPI(view); let first, variant;
try {
first = await ea.addImage(0, 500, drawing, false, false);
variant = await ea.addImage(500, 500, drawing.path + "#^frame=frame-marker,padding=20|100%", false, true);
await ea.addElementsToView(false, true, true);
} finally { ea.destroy(); }
const get = id => view.getViewElements().find(el => el.id === id);
const duplicate = { ...structuredClone(get(first)), id: "shared-copy", x: 300, width: get(first).width/2, height: get(first).height/2, index: null };
view.updateScene({ elements: [...view.getViewElements(), duplicate], captureUpdate: "IMMEDIATELY" });
const originalId = get(first).fileId;
const link = id => view.excalidrawData.getFile(get(id).fileId).linkParts.original;
const center = id => { const el=get(id); return [el.x+el.width/2,el.y+el.height/2]; };
const oldCenters = [first, "shared-copy", variant].map(center);
const oldAreas = [first,"shared-copy"].map(id=>get(id).width*get(id).height);
const open = async () => {
await view.zoomToElementId(first, false);
await c.waitFor(() => view.containerEl.querySelector('[data-excalidraw-element-action="configure-drawing-preview"]'), "drawing image settings action");
await click(view.containerEl.querySelector('[data-excalidraw-element-action="configure-drawing-preview"]'));
await c.waitFor(() => doc.querySelector(".excalidraw-drawing-preview-popover select"), "drawing preview popover opens in owner document");
return doc.querySelector(".excalidraw-drawing-preview-popover");
};
const chooseFrame = async popup => {
const select = popup.querySelector("select"), index = [...select.options].findIndex(option => option.value === "frame:frame-marker");
check(index>=0,"marker frame missing from image settings"); select.focus(); await key("Home","Home",36);
for(let i=0;i<index;i++) await key("ArrowDown","ArrowDown",40);
await key("Enter","Enter",13); check(select.value==="frame:frame-marker","native frame selection failed");
};
const choosePadding = async (popup, steps) => {
const slider=popup.querySelector('input[type="range"]'); slider.focus(); await key("Home","Home",36);
for(let i=0;i<steps;i++) await key("ArrowRight","ArrowRight",39);
check(Number(slider.value)===steps,"native padding selection failed");
};
const apply = async (popup, all) => {
c.caseTrace = { ...c.caseTrace, imageSettings: { all, html: popup.outerHTML, links: [first,"shared-copy",variant].map(link) } };
await click([...popup.querySelectorAll("button")].find(button=>button.textContent==="Apply"));
await c.waitFor(()=> {
c.caseTrace.imageSettings.after = { popover: popup.isConnected, disabled: popup.querySelector(".mod-cta")?.disabled,
currentLink: link(first), prompt: doc.querySelector(".modal-container")?.textContent };
return doc.querySelector(".excalidraw-multiOptionConfirmationPrompt-buttonContainer");
},"shared drawing scope prompt");
const buttons=[...doc.querySelectorAll(".excalidraw-multiOptionConfirmationPrompt-buttonContainer button")];
const body=doc.querySelector(".excalidraw-multiOptionConfirmationPrompt-message").textContent;
check(body.includes("3 images")&&!/fileId|file id/.test(body),"scope explanation exposes internal references or misses distinct-view copies");
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);
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");
check(Math.abs(get(first).width*get(first).height-oldAreas[0])<.01,"frame change did not retain image area");
check(JSON.stringify(center(first))===JSON.stringify(oldCenters[0]),"frame change moved image center");
view.containerEl.querySelector(".excalidraw").focus(); await key("z","KeyZ",90,modifier);
await c.waitFor(()=>get(first).fileId===originalId,"one undo restores old preview reference");
await key("z","KeyZ",90,modifier|8);
await c.waitFor(()=>link(first).includes("padding=3"),"redo restores preview reference");
popup=await open(); await choosePadding(popup,5); await apply(popup,true);
check(link(first).includes("frame=frame-marker,padding=5"),"apply-all lost chosen frame");
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);
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");
check(Math.abs(el.width-source.size.width)<.01&&Math.abs(el.height-source.size.height)<.01,"anchored copy does not use intrinsic size");
}
const before=JSON.stringify(view.getViewElements()), beforeLinks=[first,"shared-copy",variant].map(link);
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");
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"] };
}
+475
View File
@@ -0,0 +1,475 @@
/** #3036: trusted input against real Markdown widgets, exact source and history. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
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";
const casesFor = ids => ids.flatMap(id => [...["PNG", "SVGIMG", "SVG"].map(mode => `native:embed-controls:${id}:${mode}`), `native:embed-ownership:${id}`, `native:embed-table:${id}`, `native:embed-hybrid:${id}`]);
export const embedControlCaseIds = casesFor(["main", "split", "popout"]);
export const embedControlDeviceCaseIds = casesFor(["phone", "tablet"]);
export async function runEmbedControlsScenario({ cli, drawingPath, contexts = ["main", "split", "popout"], inputMode = "mouse", viewportScale = 1 }) {
const template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8");
const tests = [], consoleErrors = [], windowErrors = [], browserIdle = [];
for (const id of contexts) {
const execute = new Function(`return async function(c,path,context,template,modifier){
const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()});
const runCase=c.case.bind(c);c.case=async (...args)=>{c.phase=args[0];return runCase(...args);};
try {await (${exerciseEmbedControls.toString()})(c,env,template,modifier);}
catch(error){c.observations={...c.observations,diagnostics:env.diagnostics()};throw error;}
return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors,browserIdle:env.browserIdle};
}`)();
const result = await runInAppTask({ cli, execute, args: [drawingPath, { id, input: inputMode }, template, process.platform === "darwin" ? 4 : 2],
timeoutMs: 480000, cleanupMs: 60000, onRequest: behaviorInputDriver(cli, viewportScale),
onProgress: phase => { if (phase) process.stdout.write("Embed controls: " + phase + "\n"); },
}).catch(error => { error.evidence = [...tests, ...(error.evidence || [])]; throw error; });
tests.push(...result.tests); consoleErrors.push(...result.consoleErrors); windowErrors.push(...result.windowErrors); browserIdle.push(...result.browserIdle);
}
assert.equal(consoleErrors.length, 0, "Embed controls emitted console errors");
assert.equal(splitWindowErrors(windowErrors).unexpected.length, 0, "Embed controls emitted window errors");
assert.ok(browserIdle.every(item => item.status === "passed"), "Embed controls did not settle");
return { id: "drawing-embed-controls-3036", status: "passed", tests, consoleErrors, windowErrors, browserIdle };
}
async function exerciseEmbedControls(c, env, template, modifier) {
const { p, leaf, doc, win, create, check, click, key, input, geometry } = env;
const context = geometry().requested.id, touch = geometry().requested.input === "touch";
const browserWindow = win.require("@electron/remote").getCurrentWindow();
const wasMinimized = browserWindow.isMinimized();
if (wasMinimized) browserWindow.restore();
browserWindow.show(); browserWindow.focus();
if (wasMinimized) c.defer(() => { if (!browserWindow.isDestroyed()) browserWindow.minimize(); });
const mainWindow = context === "popout" ? app.workspace.containerEl.ownerDocument.defaultView.require("@electron/remote").getCurrentWindow() : null;
const mainWasMinimized = mainWindow?.isMinimized();
if (mainWindow && !mainWasMinimized) c.defer(() => { if (!mainWindow.isDestroyed()) mainWindow.restore(); });
const drawing = await create("Controls.excalidraw.md", template);
await c.waitFor(() => p.isExcalidrawFile(drawing), "embed drawing metadata");
const drawingBytes = await app.vault.read(drawing);
const holdDrawingRead = () => {
const read = app.vault.read; let release, entered = 0;
const gate = new Promise(resolve => { release = resolve; });
const held = async function(file, ...args) {
// Hold detail work only after the first image has mounted. A popout can
// also refresh its source during activation; blocking that read retires
// the source owner before its preview action can mount.
if (file === drawing && doc.querySelector(".excalidraw-embed-preview-modal .excalidraw-embedded-img")) { entered++; await gate; }
return read.call(this, file, ...args);
};
app.vault.read = held;
const restore = () => { if (app.vault.read === held) app.vault.read = read; release(); };
c.defer(restore);
return { restore, entered: () => entered };
};
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aL1sAAAAASUVORK5CYII="), char => char.charCodeAt(0));
const plain = await app.vault.createBinary(env.prefix + "/ordinary.png", png.buffer);
const token = `![[${drawing.path}|180]]`;
const markdown = `![Caption|200](${drawing.path}#^as-image "Keep title")`;
const content = `# Controls\n\n${token}\n\n${token}\n\n${markdown}\n\n![[${plain.path}|40]]\n\nFooter\n`;
const note = await create("Controls.md", content);
const open = async (mode = "source", file = note) => {
await leaf.setViewState({ type: "markdown", state: { file: file.path, mode, source: false } });
app.workspace.setActiveLeaf(leaf, { focus: true }); win.focus();
if (mode === "source") leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 });
await c.waitFor(() => activeRoot()?.querySelectorAll(".excalidraw-embed-toolbar").length === 3, "three active owned embed toolbars");
await c.waitFor(() => {
const previews = frames().map(frame => {
const image = frame.querySelector(".excalidraw-embedded-img");
return { tag: image?.tagName, bounds: image?.getBoundingClientRect().toJSON(), complete: image?.complete,
naturalWidth: image?.naturalWidth, source: image?.getAttribute("src")?.slice(0, 100),
display: image && win.getComputedStyle(image).display, frame: frame.getBoundingClientRect().toJSON(),
html: frame.outerHTML.slice(0, 700) };
});
c.observations = { ...c.observations, embedReadiness: previews };
return previews.every(image => image.bounds?.height > 0 && (image.tag !== "IMG" || image.complete && image.naturalWidth > 0));
}, "decoded drawing previews with positive dimensions");
};
const activeRoot = () => leaf.view.contentEl.querySelector(leaf.view.getMode?.() === "preview" ? ".markdown-preview-view" : ".markdown-source-view");
const frames = () => [...activeRoot()?.querySelectorAll(".excalidraw-embed-controls-frame") || []];
const action = async (index, name) => {
const frame = frames()[index];
check(frame, "missing embed frame " + index); frame.scrollIntoView({ block: "center" });
let rect, signature, stableSince;
await c.waitFor(() => {
rect = frames()[index]?.getBoundingClientRect();
if (!rect?.height) return false;
const current = [rect.x, rect.y, rect.width, rect.height].map(value => Math.round(value * 10)).join(":");
if (signature !== current) { signature = current; stableSince = Date.now(); }
return Date.now() - stableSince >= 120;
}, "embed scroll settled before hover");
if (!touch) await input("Input.dispatchMouseEvent", { type: "mouseMoved", x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 });
await click(() => frames()[index]?.querySelector(`[data-excalidraw-embed-action="${name}"]`));
};
const drag = async (index, delta, cancel = false, expectedSource = content) => {
let frame = frames()[index], handle = frame.querySelector('[data-excalidraw-embed-action="resize"]');
handle.focus(); handle.scrollIntoView({ block: "center" });
let r, x, y, signature, stableSince, scrollAttempts = 0;
await c.waitFor(() => {
const nextFrame = frames()[index], next = nextFrame?.querySelector('[data-excalidraw-embed-action="resize"]');
if (!next) return false;
if (next !== handle) { frame = nextFrame; handle = next; handle.focus(); handle.scrollIntoView({ block: "center" }); }
r = handle.getBoundingClientRect(); x = r.x + r.width / 2; y = r.y + r.height / 2;
const scroller = leaf.view.editor.cm.scrollDOM.getBoundingClientRect();
c.observations = { ...c.observations, dragPreparation: {
handle: r.toJSON(), frame: frame.getBoundingClientRect().toJSON(),
image: frame.querySelector(".excalidraw-embedded-img")?.getBoundingClientRect().toJSON(),
hit: doc.elementFromPoint(x, y)?.outerHTML.slice(0, 500),
focus: doc.activeElement?.outerHTML.slice(0, 300),
scroller: scroller.toJSON(), scrollTop: leaf.view.editor.cm.scrollDOM.scrollTop, scrollAttempts,
} };
if (!handle.contains(doc.elementFromPoint(x, y))) {
// CodeMirror can apply its pending caret scroll after focus/scrollIntoView
// and image measurement. Reposition an offscreen target, then still
// require a stable real hit; never scroll to bypass an obscuring overlay.
if (scrollAttempts < 3 && (x < scroller.left || x >= scroller.right || y < scroller.top || y >= scroller.bottom)) {
scrollAttempts++; handle.scrollIntoView({ block: "center", inline: "nearest" });
}
signature = null; return false;
}
const current = [r.x, r.y, r.width, r.height].map(value => Math.round(value * 10)).join(":");
if (signature !== current) { signature = current; stableSince = Date.now(); }
return Date.now() - stableSince >= 120;
}, "stable uncovered resize handle");
const image = frame.querySelector(".excalidraw-embedded-img"), visual = image.querySelector("svg") ?? image;
const initial = visual.getBoundingClientRect();
const events = [], eventNames = ["pointerdown", "pointermove", "pointerup", "pointercancel", "touchstart", "touchmove", "blur", "lostpointercapture"];
const observe = event => events.push({ type: event.type, target: event.target.className, trusted: event.isTrusted, x: event.clientX, y: event.clientY, prevented: event.defaultPrevented, cancelable: event.cancelable });
for (const name of eventNames) win.addEventListener(name, observe, true);
c.defer(() => { for (const name of eventNames) win.removeEventListener(name, observe, true); });
c.observations = { ...c.observations, drag: { handle: handle.outerHTML, bounds: r.toJSON(), image: frame.querySelector(".excalidraw-embedded-img").getBoundingClientRect().toJSON(), hit: doc.elementFromPoint(x, y)?.outerHTML.slice(0, 500), events } };
const touchRules = [];
const inspectRules = rules => { for (const rule of rules) {
if (rule.style?.touchAction && rule.selectorText && handle.matches(rule.selectorText)) touchRules.push({ selector: rule.selectorText, value: rule.style.touchAction, priority: rule.style.getPropertyPriority("touch-action") });
if (rule.cssRules) inspectRules(rule.cssRules);
} };
for (const sheet of doc.styleSheets) { try { inspectRules(sheet.cssRules); } catch { /* Cross-origin sheets cannot be inspected. */ } }
c.observations.drag.touchRules = touchRules;
const send = (phase, point) => touch ? input("Input.dispatchTouchEvent", { type: phase === "down" ? "touchStart" : phase === "move" ? "touchMove" : "touchEnd", touchPoints: phase === "up" ? [] : [{ x: point, y, id: 1 }] })
: input("Input.dispatchMouseEvent", { type: phase === "down" ? "mousePressed" : phase === "move" ? "mouseMoved" : "mouseReleased", x: point, y, button: "left", buttons: phase === "up" ? 0 : 1, clickCount: 1 });
try {
const states = c.observations.drag.states = [];
const snapshot = () => states.push({ connected: frame.isConnected, current: frame === frames()[index], classes: frame.className, handleAction: win.getComputedStyle(handle).touchAction, selection: leaf.view.editor.cm.state.selection.main.toJSON() });
await send("down", x); snapshot(); await send("move", x + delta / 2); snapshot(); await send("move", x + delta); snapshot();
check(leaf.view.editor.getValue() === expectedSource, "pointer movement wrote source before commit");
check(frame.hasClass("excalidraw-embed-resizing"), "real pointer did not start CSS resize preview");
const preview = visual.getBoundingClientRect();
check(Math.abs(preview.width - initial.width - delta) < 1 && Math.abs(preview.height - preview.width * initial.height / initial.width) < 1, "resize preview geometry lost its requested size or aspect ratio");
if (cancel) await key("Escape", "Escape", 27);
} finally { await send("up", x + delta); }
return initial.width + delta;
};
for (const mode of ["PNG", "SVGIMG", "SVG"]) await c.case(`native:embed-controls:${context}:${mode}`, ["P02", "P05"], async () => {
p.settings.previewImageType = mode;
await open();
if (mainWindow) { mainWindow.minimize(); browserWindow.focus(); check(mainWindow.isMinimized(), "main window was not minimized for popout input"); }
if (touch) {
const frame = frames()[0], image = frame.querySelector(".excalidraw-embedded-img").getBoundingClientRect(), toolbar = frame.querySelector(".excalidraw-embed-toolbar").getBoundingClientRect();
check(toolbar.top >= image.bottom && toolbar.bottom <= frame.getBoundingClientRect().bottom + 1, "touch toolbar overlaps image or following note content");
}
let cm = leaf.view.editor.cm;
const changed = content.replace(token + "\n\n" + token, token + "\n\n" + token.replace("|180", "|220"));
await drag(1, 40);
c.phase = `native:embed-controls:${context}:${mode}:history`;
await c.waitFor(() => cm.state.doc.toString() === changed, "only second repeated embed resized");
cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === content, "single undo restores exact original source");
await key("z", "KeyZ", 90, modifier | 8);
await c.waitFor(() => cm.state.doc.toString() === changed, "single redo restores exact resized source");
await c.waitFor(() => frames().length === 3 && frames()[1].querySelector('[data-excalidraw-embed-action="reset"]'), "resized controls remounted once");
await action(1, "reset");
await c.waitFor(() => cm.state.doc.toString() === content.replace(token + "\n\n" + token, token + "\n\n" + `![[${drawing.path}]]`), "reset removes only explicit dimensions");
cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === changed, "reset is one undo step");
await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === content, "original size restored");
await c.waitFor(() => frames().length === 3, "restored embeds");
await drag(1, 35, true);
check(cm.state.doc.toString() === content && !frames()[1].hasClass("excalidraw-embed-resizing"), "Escape committed or retained preview");
const cancelledFrame = frames()[1], cancelledImage = cancelledFrame.querySelector(".excalidraw-embedded-img");
const imageCorner = (cancelledImage.querySelector("svg") ?? cancelledImage).getBoundingClientRect(), handleCorner = cancelledFrame.querySelector('[data-excalidraw-embed-action="resize"]').getBoundingClientRect();
check(Math.abs(handleCorner.right - imageCorner.right + 2) < 2 && Math.abs(handleCorner.bottom - imageCorner.bottom + 2) < 2, "cancel left the resize handle away from the visible inside corner");
frames()[1].querySelector('[data-excalidraw-embed-action="resize"]').focus();
await key("ArrowRight", "ArrowRight", 39);
await c.waitFor(() => cm.state.doc.toString() === content.replace(token + "\n\n" + token, token + "\n\n" + token.replace("|180", "|188")), "keyboard resize commits on key release");
cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === content && frames().length === 3, "keyboard resize is one undo step");
await action(2, "edit");
check(cm.state.sliceDoc(cm.state.selection.main.from, cm.state.selection.main.to) === markdown, "edit source selected the wrong token");
check(cm.state.doc.toString() === content, "edit source rewrote Markdown");
leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 });
await c.waitFor(() => frames().length === 3, "source-edit rendering roundtrip");
const inline = frames()[0].querySelector(".excalidraw-embedded-img");
if (mode === "PNG") await c.waitFor(() => inline.complete && inline.naturalWidth > 0, "inline PNG decoded before fullscreen");
const inlinePNG = mode === "PNG" ? { src: inline.src, width: inline.naturalWidth, height: inline.naturalHeight,
bytes: new Uint8Array(await (await win.fetch(inline.src)).arrayBuffer()) } : null;
const detailGate = mode === "PNG" ? holdDrawingRead() : null;
const fullscreenStarted = win.performance.now();
await action(0, "preview");
c.phase = `native:embed-controls:${context}:${mode}:fullscreen`;
let modal, stage;
await c.waitFor(() => {
modal = doc.querySelector(".excalidraw-embed-preview-modal");
c.observations.viewerReadiness = { modal: !!modal, status: modal?.querySelector(".excalidraw-embed-preview-status")?.textContent,
mainModal: !!app.workspace.containerEl.ownerDocument.querySelector(".excalidraw-embed-preview-modal"), heldReads: detailGate?.entered() };
return modal && (stage = modal.querySelector(".excalidraw-embed-preview-stage")) && modal.querySelector(".excalidraw-embedded-img");
}, "fresh fullscreen payload");
check(modal.querySelector("[fileSource]")?.getAttribute("fileSource") === drawing.path, "fullscreen changed drawing identity");
let pngReuse;
if (mode === "PNG") {
const preview = modal.querySelector("img.excalidraw-embedded-img");
await c.waitFor(() => preview.complete && preview.naturalWidth > 0, "fullscreen PNG decoded");
c.observations.pngDimensions = { before: [inlinePNG.width, inlinePNG.height], preview: [preview.naturalWidth, preview.naturalHeight],
originalInline: [inline.naturalWidth, inline.naturalHeight], inlineRetired: !inline.isConnected, heldReads: detailGate.entered() };
check(preview.src !== inlinePNG.src, "fullscreen borrowed the inline PNG URL");
check(preview.naturalWidth === inlinePNG.width && preview.naturalHeight === inlinePNG.height, "fullscreen rerasterized PNG instead of reusing displayed pixels");
const before = inlinePNG.bytes;
const after = new Uint8Array(await (await win.fetch(preview.src)).arrayBuffer());
check(before.length === after.length && before.every((value, index) => value === after[index]), "fullscreen changed the encoded PNG payload");
pngReuse = { inlineWidth: inlinePNG.width, inlineHeight: inlinePNG.height, encodedBytes: before.length, independentURL: true, elapsedMs: win.performance.now() - fullscreenStarted };
}
const keys = [], recordKey = event => keys.push({ key: event.key, code: event.code, target: event.target.className, trusted: event.isTrusted });
doc.addEventListener("keydown", recordKey, true); c.defer(() => doc.removeEventListener("keydown", recordKey, true));
c.observations = { ...c.observations, fullscreen: { focus: doc.activeElement?.outerHTML.slice(0, 500), connected: modal.isConnected, keys, pngReuse } };
await key("+", "Equal", 187, 8);
c.observations.fullscreen.zoom = stage.getAttribute("data-zoom");
c.observations.fullscreen.stageConnected = stage.isConnected;
check(Number(stage.getAttribute("data-zoom")) > 1, "fullscreen keyboard zoom failed");
await key("ArrowRight", "ArrowRight", 39);
check(modal.querySelector(".excalidraw-embed-preview-surface").style.transform.includes("-24px"), "fullscreen keyboard pan failed");
if (detailGate) {
await c.waitFor(() => detailGate.entered() > 0, "background detail export started while initial PNG remained visible");
const surface = modal.querySelector(".excalidraw-embed-preview-surface"), initial = surface.querySelector("img"), transform = surface.style.transform, zoom = stage.getAttribute("data-zoom");
const initialWidth = initial.naturalWidth, initialHeight = initial.naturalHeight;
detailGate.restore();
let detail;
await c.waitFor(() => (detail = surface.querySelector("img")) !== initial && detail?.complete && detail.naturalWidth > 0, "decoded 3x detail replaces initial PNG");
pngReuse.detailWidth = detail.naturalWidth; pngReuse.detailHeight = detail.naturalHeight;
check(Math.abs(detail.naturalWidth - initialWidth * 3) <= 3 && Math.abs(detail.naturalHeight - initialHeight * 3) <= 3, "detail export did not use scale 3");
check(surface.style.transform === transform && stage.getAttribute("data-zoom") === zoom, "detail replacement reset zoom or pan");
check(detail.getAttribute("fileSource") === drawing.path, "detail replacement changed drawing identity");
pngReuse.zoomPanPreserved = true;
}
await key("0", "Digit0", 48);
check(Number(stage.getAttribute("data-zoom")) === 1, "fullscreen fit failed");
if (touch) {
const r = stage.getBoundingClientRect(), x = r.x + r.width / 2, y = r.y + r.height / 2;
const points = distance => [{ x: x - distance, y, id: 1 }, { x: x + distance, y, id: 2 }];
try {
await input("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: points(20) });
await input("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: points(40) });
check(Number(stage.getAttribute("data-zoom")) > 1.25, "fullscreen trusted pinch failed");
} finally { await input("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); }
await key("0", "Digit0", 48);
try {
await input("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y, id: 1 }] });
await input("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x: x + 20, y: y + 12, id: 1 }] });
check(modal.querySelector(".excalidraw-embed-preview-surface").style.transform.includes("20px, 12px"), "fullscreen trusted touch pan failed");
} finally { await input("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); }
await key("0", "Digit0", 48);
}
await key("Escape", "Escape", 27);
await c.waitFor(() => !modal.isConnected, "fullscreen closes on Escape");
doc.removeEventListener("keydown", recordKey, true);
check(doc.activeElement?.getAttribute("data-excalidraw-embed-action") === "preview", "fullscreen did not restore opener focus");
const currentInline = frames()[0]?.querySelector(".excalidraw-embedded-img");
check(currentInline?.isConnected && (mode === "SVG" ? !!currentInline.querySelector("svg") : currentInline.complete && currentInline.naturalWidth > 0), "closing fullscreen invalidated inline payload");
if (mode === "PNG") {
const cancelGate = holdDrawingRead();
await action(0, "preview");
let cancelledModal;
await c.waitFor(() => (cancelledModal = doc.querySelector(".excalidraw-embed-preview-modal"))?.querySelector("img")?.naturalWidth > 0 && cancelGate.entered() > 0, "reopened initial PNG while its new detail export is pending");
const surface = cancelledModal.querySelector(".excalidraw-embed-preview-surface"), first = surface.firstElementChild;
const changes = [], observer = new win.MutationObserver(records => changes.push(...records)); observer.observe(surface, { childList: true });
c.defer(() => observer.disconnect());
await key("Escape", "Escape", 27);
await c.waitFor(() => !cancelledModal.isConnected, "closing pending PNG export");
cancelGate.restore();
await new Promise(resolve => window.setTimeout(resolve, 150));
observer.disconnect();
check(surface.firstElementChild === first && changes.every(record => record.addedNodes.length === 0), "cancelled detail export mounted a late image");
const survivingInline = frames()[0]?.querySelector(".excalidraw-embedded-img");
check(survivingInline?.complete && survivingInline.naturalWidth > 0, "cancelled detail export invalidated inline PNG");
pngReuse.cancelledPendingUpgrade = true;
}
check(!leaf.view.contentEl.querySelector(`.internal-embed[src="${plain.path}"] [data-excalidraw-embed-action]`), "ordinary image acquired drawing controls");
await open("preview");
check(!activeRoot().querySelector('[data-excalidraw-embed-action="resize"], [data-excalidraw-embed-action="edit"], [data-excalidraw-embed-action="reset"]'), "Reading mode acquired source mutation controls");
check(!leaf.view.contentEl.querySelector('.markdown-source-view [data-excalidraw-embed-action="resize"]'), "hidden source retained editable controls after mode switch");
await action(2, "preview");
await c.waitFor(() => doc.querySelector(".excalidraw-embed-preview-modal [fileSource]")?.getAttribute("fileSource") === drawing.path + "#^as-image", "Reading fullscreen preserves reference");
await key("Escape", "Escape", 27);
await action(0, "open");
await c.waitFor(() => leaf.view.excalidrawAPI && leaf.view.file === drawing, "explicit Open drawing navigates to editor");
check(await app.vault.read(drawing) === drawingBytes, "embed actions changed drawing source");
// Retiring the source owner removes every control and cancels its dialogs.
check(!doc.querySelector(".excalidraw-embed-preview-modal"), "retired source left fullscreen modal");
return { assertions: ["trusted proportional resize previews without source writes", "only second identical token changed", "one-step undo/redo and reset", "Escape cancellation", "exact Markdown-image syntax selection and roundtrip", "independently owned fullscreen zoom/pan/fit/Escape/focus", ...(mode === "PNG" ? ["fullscreen PNG initially keeps exact encoded pixels and dimensions with an independent URL", "decoded 3x upgrade preserves zoom and pan", "close cancels pending upgrade without late image insertion"] : []), "inline payload survives modal cleanup", "Reading controls cannot write", "ordinary image unchanged", "Open drawing and drawing bytes unchanged"], actual: { ...geometry(), pngReuse } };
});
await c.case(`native:embed-ownership:${context}`, ["P03", "P04", "P05"], async () => {
const small = `![[${drawing.path}|100]]`;
const source = `# Source A\n\n${small} ${small}\n\n\`${small}\`\n\n\`\`\`md\n${small}\n\`\`\`\n\nFooter\n`;
const sourceB = "# Source B\n\n" + small + "\n\nFooter\n";
const a = await create("Ownership-A.md", source), b = await create("Ownership-B.md", sourceB);
await leaf.setViewState({ type: "markdown", state: { file: a.path, mode: "source", source: false } });
leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 });
await c.waitFor(() => frames().length === 2, "two same-line embeds; code examples have no controls");
const cm = leaf.view.editor.cm;
let other;
if (!touch) {
app.workspace.setActiveLeaf(leaf, { focus: true });
other = app.workspace.getLeaf("split", "vertical"); env.owned.add(other);
await other.setViewState({ type: "markdown", state: { file: b.path, mode: "source", source: false } });
check(other.parent !== leaf.parent, "ownership test needs independent visible panes");
app.workspace.setActiveLeaf(other, { focus: true });
}
const target = frames()[1].querySelector('[data-excalidraw-embed-action="resize"]');
target.focus(); await key("ArrowRight", "ArrowRight", 39);
const expected = source.replace(small + " " + small, small + " " + small.replace("|100", "|108"));
await c.waitFor(() => cm.state.doc.toString() === expected, "only second same-line token changed");
check(!other || other.view.editor.getValue() === sourceB, "another pane's note was edited");
check(await app.vault.read(b) === sourceB, "other note's persisted source changed");
cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === source && frames().length === 2, "same-line undo restores source");
const oldFrame = frames()[0], oldImage = oldFrame.querySelector(".excalidraw-embedded-img");
oldImage.dispatchEvent(new win.CustomEvent("excalidraw-embed-rerender"));
await c.waitFor(() => oldFrame.querySelector(".excalidraw-embedded-img") !== oldImage && frames().length === 2, "refresh preserves exactly one control set per embed");
await action(0, "preview");
await c.waitFor(() => doc.querySelector(".excalidraw-embed-preview-modal"), "ownership fullscreen opened");
await leaf.setViewState({ type: "markdown", state: { file: b.path, mode: "source", source: false } });
await c.waitFor(() => !doc.querySelector(".excalidraw-embed-preview-modal"), "switching source owner closes its viewer");
check(!oldFrame.isConnected && !target.isConnected, "retired owner retained controls");
check(leaf.view.editor.getValue() === sourceB && await app.vault.read(a) === source, "retired source or switched note changed");
check(await app.vault.read(drawing) === drawingBytes, "ownership tests changed drawing content");
return { assertions: ["same-line repeated embeds target only their own token", "inline/fenced examples have no controls", "independent note and pane stay unchanged", "one-step undo", "refresh remounts controls exactly once", "switching source unloads controls and fullscreen", "drawing bytes unchanged"], actual: geometry() };
});
await c.case(`native:embed-table:${context}`, ["P03", "P04", "P05"], async () => {
const token = `![[${drawing.path}\\|Caption\\|100\\|left]]`;
const markdown = `![Label\\|120\\|right](<${drawing.path}#^as-image> "Keep title")`;
const source = `# Table source\n\n| Drawing | Cell |\n| --- | --- |\n| ${token} | first |\n| ${token} | second |\n| ${markdown} | third |\n\nFooter\n`;
const file = await create("Table-source.md", source);
await leaf.setViewState({ type: "markdown", state: { file: file.path, mode: "source", source: false } });
app.workspace.setActiveLeaf(leaf, { focus: true });
leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 });
const cm = leaf.view.editor.cm;
const tableEvents = [], observeTableInput = event => tableEvents.push({ type: event.type, key: event.key, target: event.target.getAttribute?.("class"), activeLeaf: app.workspace.activeLeaf?.id, trusted: event.isTrusted });
for (const name of ["focusin", "keydown", "keyup"]) doc.addEventListener(name, observeTableInput, true);
c.defer(() => { for (const name of ["focusin", "keydown", "keyup"]) doc.removeEventListener(name, observeTableInput, true); });
c.observations.tableInput = { ownerLeaf: leaf.id, events: tableEvents };
const ready = () => {
const current = frames();
c.observations = { ...c.observations, table: { selection: cm.state.selection.main.toJSON(), frames: current.map(frame => ({ connected: frame.isConnected, bounds: frame.getBoundingClientRect().toJSON(), width: frame.querySelector(".excalidraw-embedded-img")?.getAttribute("w") })), html: cm.contentDOM.querySelector(".cm-table-widget")?.outerHTML.replace(/<svg\b[\s\S]*?<\/svg>/g, "<svg/>").slice(0, 10000) } };
return current.length === 3 && current.every((frame, i) => frame.querySelector(".excalidraw-embedded-img")?.getAttribute("w") === (i === 2 ? "120" : "100"));
};
await c.waitFor(ready, "three authoritative table cells and escaped display dimensions");
let other;
if (!touch) {
other = app.workspace.getLeaf("split", "vertical"); env.owned.add(other);
await other.setViewState({ type: "markdown", state: { file: file.path, mode: "source", source: false } });
other.view.editor.setCursor({ line: other.view.editor.lastLine(), ch: 0 });
app.workspace.setActiveLeaf(other, { focus: true });
}
// A second pane's asynchronous activation can reclaim programmatic focus.
// Use the same trusted click that a keyboard user uses to focus the handle.
await action(1, "resize");
await c.waitFor(() => doc.activeElement === frames()[1]?.querySelector('[data-excalidraw-embed-action="resize"]'), "owned table resize keyboard focus");
const keyboardImage = frames()[1].querySelector(".excalidraw-embedded-img"), keyboardVisual = keyboardImage.querySelector("svg") ?? keyboardImage;
const keyboardWidth = keyboardVisual.getBoundingClientRect().width;
check(keyboardWidth > 52, "table fixture is too narrow for measured shrinking");
await key("ArrowLeft", "ArrowLeft", 37);
c.observations.tableInput.afterKeyboard = { activeLeaf: app.workspace.activeLeaf?.id, activeElement: doc.activeElement?.getAttribute("class"), outerFocus: cm.hasFocus, source: cm.state.doc.toString() };
const changed = source.replace(token + " | second", token.replace("\\|100", "\\|" + Math.round(keyboardWidth - 8)) + " | second");
await c.waitFor(() => cm.state.doc.toString() === changed, "only the second identical physical table cell resized");
if (other) await c.waitFor(() => other.view.editor.getValue() === changed, "same-note split receives the exact table transaction");
cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === source && ready(), "one undo restores table source and rendered dimensions");
for (const [index, label, original, sourceWidth] of [[1, "left", token, 100], [2, "right", markdown, 120]]) {
c.phase = `native:embed-table:${context}:aligned-resize-${label}`;
const targetWidth = await drag(index, -20, false, source);
const resized = original.replace("\\|" + sourceWidth, "\\|" + Math.round(targetWidth));
const expected = index === 1 ? source.replace(token + " | second", resized + " | second") : source.replace(original, resized);
await c.waitFor(() => cm.state.doc.toString() === expected, "aligned table resize preserves exact source and other cells");
cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === source && ready(), "aligned resize is one undo step");
}
await action(2, "edit");
check(cm.state.sliceDoc(cm.state.selection.main.from, cm.state.selection.main.to) === markdown, "table source edit selected the wrong syntax or cell");
leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 });
// The table intentionally owns an inner cell editor while syntax is being
// edited. Moving the outer caret by API does not blur that editor. Exit it
// through trusted note input before counting/restoring its normal previews.
await click(() => [...cm.contentDOM.querySelectorAll(".cm-line")].find(line => line.closest(".cm-content") === cm.contentDOM && line.textContent.trim() === "Footer"));
await c.waitFor(ready, "table syntax edit roundtrip");
check(cm.state.doc.toString() === source, "table source editing roundtrip rewrote surrounding syntax");
await action(1, "reset");
const reset = source.replace(token + " | second", token.replace("\\|100", "") + " | second");
await c.waitFor(() => cm.state.doc.toString() === reset, "table reset preserves escaped aliases, style, title and other cells");
cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === source, "table reset is one undo step");
check(await app.vault.read(drawing) === drawingBytes, "table controls changed the drawing file");
return { assertions: ["native table widget public boundaries and physical cell ownership", "escaped wiki and Markdown-image dimensions render", "only second identical row changes", "same-note split synchronization", "left/right pointer previews retain measured size and aspect ratio", "one-step undo/reset", "exact Markdown syntax selection", "aliases/styles/title and other cells preserved", "drawing bytes unchanged"], actual: geometry() };
});
await c.case(`native:embed-hybrid:${context}`, ["P02", "P05"], async () => {
p.settings.previewImageType = "SVG";
const selfToken = "![[Hybrid|180]]", otherToken = `![[${drawing.path}|180]]`;
const fixture = template.replace("User Markdown retained.", `# Hybrid controls\n\n${selfToken}\n\n${otherToken}\n\nFooter\n`);
check(fixture !== template, "hybrid fixture Markdown marker missing");
const file = await create("Hybrid.md", fixture);
await c.waitFor(() => p.isExcalidrawFile(file), "hybrid drawing metadata");
await leaf.setViewState({ type: "markdown", state: { file: file.path, mode: "source", source: false } });
// Known drawings are routed back to Excalidraw. Use its public Markdown
// action, which also establishes the leaf-specific mode override.
await c.waitFor(() => leaf.view.excalidrawAPI && leaf.view.isLoaded && !leaf.view.semaphores.justLoaded, "hybrid drawing ready before opening Markdown");
await leaf.view.openAsMarkdown();
await c.waitFor(() => leaf.view.getViewType() === "markdown" && leaf.view.editor, "drawing opened through its Markdown action");
await leaf.view.setState({ ...leaf.view.getState(), mode: "source", source: false }, { history: false });
app.workspace.setActiveLeaf(leaf, { focus: true });
const editor = leaf.view.editor, cm = editor.cm;
// Opening a drawing as Markdown may first save/decompress its scene. The
// controls must preserve the complete content produced by that transition.
const source = editor.getValue();
check(source.includes(selfToken + "\n\n" + otherToken), "hybrid fixture embeds changed before interaction");
editor.setCursor({ line: editor.getValue().slice(0, editor.getValue().indexOf("Footer")).split("\n").length - 1, ch: 0 });
const ready = () => frames().length === 2 && frames().every(frame => frame.querySelector('[data-excalidraw-embed-action="resize"]'));
await c.waitFor(ready, "self and other drawing controls in drawing Markdown view");
check(frames()[0].querySelector(".excalidraw-embedded-img").getAttribute("fileSource") === file.path, "short self-link resolved to a different drawing");
check(frames()[1].querySelector(".excalidraw-embedded-img").getAttribute("fileSource") === drawing.path, "other drawing identity changed");
await action(0, "resize");
const image = frames()[0].querySelector(".excalidraw-embedded-img"), visual = image.querySelector("svg") ?? image;
const initialWidth = visual.getBoundingClientRect().width;
check(initialWidth > 52, "hybrid preview too narrow to shrink");
await key("ArrowLeft", "ArrowLeft", 37);
const changed = source.replace(selfToken, selfToken.replace("|180", "|" + Math.round(initialWidth - 8)));
await c.waitFor(() => cm.state.doc.toString() === changed, "hybrid resize changes only its exact self-embed token");
await leaf.view.save();
check(await app.vault.read(file) === changed, "hybrid resize changed serialized drawing data or failed to persist");
cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === source && ready(), "hybrid resize is one undo step");
await action(0, "reset");
await c.waitFor(() => cm.state.doc.toString() === source.replace(selfToken, "![[Hybrid]]"), "hybrid reset changes only self dimensions");
cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => cm.state.doc.toString() === source && ready(), "hybrid reset is one undo step");
await leaf.view.save();
check(await app.vault.read(file) === source, "hybrid undo did not restore exact persisted drawing content");
await action(0, "edit");
check(cm.state.sliceDoc(cm.state.selection.main.from, cm.state.selection.main.to) === selfToken, "hybrid source edit selected drawing metadata");
editor.setCursor({ line: source.slice(0, source.indexOf("Footer")).split("\n").length - 1, ch: 0 });
await c.waitFor(ready, "hybrid source selection roundtrip");
await action(0, "preview");
await c.waitFor(() => doc.querySelector(".excalidraw-embed-preview-modal [fileSource]")?.getAttribute("fileSource") === file.path, "hybrid self-preview uses its drawing");
await key("Escape", "Escape", 27);
await c.waitFor(() => !doc.querySelector(".excalidraw-embed-preview-modal"), "hybrid self-preview closes");
await leaf.view.setState({ ...leaf.view.getState(), mode: "preview" }, { history: false });
await c.waitFor(() => frames().length === 2 && frames().every(frame => !frame.querySelector('[data-excalidraw-embed-action="resize"]')), "hybrid Reading controls are preview-only");
await action(0, "preview");
await c.waitFor(() => doc.querySelector(".excalidraw-embed-preview-modal [fileSource]")?.getAttribute("fileSource") === file.path, "Reading self-preview uses its drawing");
await key("Escape", "Escape", 27);
await c.waitFor(() => !doc.querySelector(".excalidraw-embed-preview-modal"), "Reading self-preview closes");
check(await app.vault.read(file) === source && await app.vault.read(drawing) === drawingBytes, "hybrid controls changed drawing data or another drawing");
return { assertions: ["drawing opened as Markdown owns self and other drawing embeds", "short self-link identity", "exact resize/reset and single undo", "physical save preserves serialized drawing data", "exact source selection", "Live Preview and Reading fullscreen", "Reading controls do not edit source", "other drawing unchanged"], actual: geometry() };
});
}
+50 -3
View File
@@ -51,6 +51,42 @@ async function createHybridFixtures(control) {
const hybrid = source.replace(/^---\r?\n/, "---\nexcalidraw-open-md: true\n").replace("# Excalidraw Data", `${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]);
}
async function renderPDFEmbeds(control, imageType) {
const c = globalThis[control];
c.plugin.settings.previewImageType = imageType;
const deadline = Date.now() + 5000;
while (!c.plugin.isExcalidrawFile(app.vault.getFileByPath(c.paths[5]))) {
if (Date.now() > deadline) throw Error("PDF fixture metadata did not become ready");
await new Promise(resolve => window.setTimeout(resolve, 20));
}
const { Component, MarkdownRenderer } = c.plugin.ea.obsidian;
const component = new Component(); component.load();
const print = c.leaf.view.contentEl.ownerDocument.body.createDiv("print");
const root = print.createDiv("markdown-preview-view markdown-rendered");
try {
const markdown = [1, 2, 3].map(() => `![[${c.paths[5]}#^frame=PDF frame|100%]]`).join("\n\n") + `\n\n![[${c.paths[3]}|80]]`;
await MarkdownRenderer.render(app, markdown, root, c.paths[1], component);
const images = Array.from(root.querySelectorAll("[fileSource]"));
if (images.length !== 3 || images.some(image => image.getAttribute("fileSource") !== `${c.paths[5]}#^frame=PDF frame`)) throw Error("PDF lost drawing frame images");
for (const image of images) {
if (image.tagName === "IMG") await image.decode();
else if (!image.querySelector("svg")?.textContent.includes("Embed recovery")) throw Error("PDF frame lost its drawing text");
}
const native = root.querySelector(".internal-embed img");
if (!native) throw Error("PDF lost its native PNG embed");
await native.decode();
if (!native.naturalWidth) throw Error("PDF native PNG did not decode");
if (component._children?.some(child => child.file?.path === c.paths[5])) throw Error("Native Markdown renderer took ownership of a drawing frame");
return { images: images.length, nativePNG: true, popout: root.ownerDocument !== app.workspace.containerEl.ownerDocument };
} finally {
component.unload(); print.remove();
}
}
async function openHybrid(control, mode, nested) {
@@ -65,7 +101,9 @@ async function createFixtures(control) {
const view = app.workspace.getLeavesOfType("excalidraw").find(leaf => leaf.view.file?.path === c.drawingPath)?.view;
const ea = new c.plugin.ea.constructor(c.plugin, view);
try {
ea.addText(0, 0, "Embed recovery #2953");
const text = ea.addText(0, 0, "Embed recovery #2953");
const frame = ea.addFrame(-20, -20, 500, 150, "PDF frame");
ea.getElement(text).frameId = frame;
if (!await ea.addElementsToView(false, true)) throw Error("could not populate drawing fixture");
} finally { ea.destroy(); }
// Collapse the long note so all three drawing widgets remain in the viewport.
@@ -143,7 +181,7 @@ async function cleanup(control, expectedPaths) {
}
export async function runEmbedRecoveryScenario({ cli, drawingPath }) {
const paths = ["large.md", "note.md", "hybrid.excalidraw.md", "pixel.png", "nested.md"]
const paths = ["large.md", "note.md", "hybrid.excalidraw.md", "pixel.png", "nested.md", "pdf.excalidraw.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.
@@ -168,6 +206,11 @@ export async function runEmbedRecoveryScenario({ cli, drawingPath }) {
invoke(setup, drawingPath, paths);
try {
await act(createFixtures);
await act(createHybridFixtures);
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`);
}
for (const imageType of ["SVGIMG", "PNG", "SVG"]) {
await act(openNote, "source", imageType, true);
await poll(value => value.paused > 0, "embed did not enter image generation");
@@ -211,7 +254,11 @@ export async function runEmbedRecoveryScenario({ cli, drawingPath }) {
await poll(value => value.images.some(image => image.width === "280" && image.ready && image.decoded), "popout attribute refresh did not finish");
checks.push("popout: detached context, reattachment and width refresh in the owning document");
await act(closeNote);
await act(createHybridFixtures);
for (const imageType of ["SVGIMG", "PNG", "SVG"]) {
const result = await act(renderPDFEmbeds, imageType);
if (!result.popout) throw Error("PDF preparation did not use the popout document");
checks.push(`${imageType}: popout Markdown PDF preparation preserves drawing frames and the native PNG`);
}
for (const mode of ["source", "preview"]) {
for (const nested of [false, true]) {
await act(openHybrid, mode, nested);
+163
View File
@@ -0,0 +1,163 @@
/** Focused #3039/#3040 rendering and source-owned area padding, in real Obsidian. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
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 embedRegressionCaseIds = ["main", "popout"].flatMap(context => ["relative", "detached", "padding"].map(kind => `native:embed-regressions:${context}:${kind}`));
export async function runEmbedRegressionsScenario({ cli, drawingPath }) {
const template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8");
const tests = [], consoleErrors = [], windowErrors = [], browserIdle = [];
for (const id of ["main", "popout"]) {
const execute = new Function(`return async function(c,path,context,template,modifier){
const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()});
const runCase=c.case.bind(c);c.case=async (...args)=>{c.phase=args[0];return runCase(...args);};
await (${exercise.toString()})(c,env,template,modifier,context.id);
return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors,browserIdle:env.browserIdle};
}`)();
const result = await runInAppTask({ cli, execute, args: [drawingPath, { id, input: "mouse" }, template, process.platform === "darwin" ? 4 : 2],
timeoutMs: 180000, cleanupMs: 60000, onRequest: behaviorInputDriver(cli),
onProgress: phase => { if (phase) process.stdout.write("Embed regressions: " + phase + "\n"); },
});
tests.push(...result.tests); consoleErrors.push(...result.consoleErrors); windowErrors.push(...result.windowErrors); browserIdle.push(...result.browserIdle);
}
assert.equal(consoleErrors.length, 0); assert.equal(splitWindowErrors(windowErrors).unexpected.length, 0);
assert.ok(browserIdle.every(item => item.status === "passed"));
return { id: "drawing-embed-regressions", status: "passed", tests, consoleErrors, windowErrors, browserIdle };
}
async function exercise(c, env, template, modifier, context) {
const { p, leaf, doc, win, create, check, click, key } = env;
const nativeWindow = win.require("@electron/remote").getCurrentWindow();
const minimized = nativeWindow.isMinimized();
nativeWindow.restore(); nativeWindow.show(); nativeWindow.focus();
if (minimized) c.defer(() => { if (!nativeWindow.isDestroyed()) nativeWindow.minimize(); });
await app.vault.createFolder(env.prefix + "/assets/deep");
await app.vault.createFolder(env.prefix + "/notes");
const drawing = await create("assets/deep/Region.excalidraw.md", template);
await c.waitFor(() => p.isExcalidrawFile(drawing), "relative drawing metadata");
const bytes = await app.vault.read(drawing);
const relative = "../assets/deep/Region.excalidraw.md";
const note = await create("notes/Relative.md", `![[${relative}|200]]\n\n![[${drawing.path}|200]]\n\nEnd`);
const root = () => leaf.view.contentEl.querySelector(leaf.view.getMode?.() === "preview" ? ".markdown-preview-view" : ".markdown-source-view");
const images = () => [...root()?.querySelectorAll(".excalidraw-embedded-img") || []];
const decoded = image => image.getBoundingClientRect().height > 0 && (image.tagName !== "IMG" || image.complete && image.naturalWidth > 0);
const open = async (file, mode) => {
await leaf.setViewState({ type: "markdown", state: { file: file.path, mode, source: false } });
app.workspace.setActiveLeaf(leaf, { focus: true }); win.focus();
if (mode === "source") leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 });
};
await c.case(`native:embed-regressions:${context}:relative`, ["P05"], async () => {
for (const type of ["SVG", "SVGIMG", "PNG"]) {
p.settings.previewImageType = type;
await leaf.setViewState({ type: "empty", state: {} }); await open(note, "source");
await c.waitFor(() => images().length === 2 && images().every(decoded), "relative and vault-path embeds decode in Live Preview");
check(images().every(image => image.getAttribute("fileSource") === drawing.path), "relative embed selected a different drawing");
check(!root().querySelector(".markdown-embed-content"), "relative embed displayed raw drawing Markdown");
}
return { assertions: ["relative and vault-path Live Preview embeds decode in SVG, SVG image and PNG", "both images retain the canonical drawing identity", "no raw drawing Markdown remains"] };
});
await c.case(`native:embed-regressions:${context}:detached`, ["P05"], async () => {
const { Component, MarkdownRenderer } = p.ea.obsidian;
const markdown = ("A long paragraph about orbital mechanics. ".repeat(400) + "\n\n") + `![[${relative}|200]]\n\n`;
for (const type of ["SVG", "SVGIMG", "PNG"]) {
p.settings.previewImageType = type;
const component = new Component(); component.load();
const preview = doc.body.createDiv({ cls: "markdown-preview-view markdown-rendered" }); preview.remove();
try {
await MarkdownRenderer.render(app, markdown, preview, note.path, component);
doc.body.append(preview);
await c.waitFor(() => preview.querySelectorAll(".excalidraw-embedded-img").length === 1 && decoded(preview.querySelector(".excalidraw-embedded-img")), "claimed detached Reading section decodes after attachment");
check(preview.querySelector("[fileSource]").getAttribute("fileSource") === drawing.path, "detached rendering changed the destination");
} finally { component.unload(); preview.remove(); }
}
return { assertions: ["a long Reading section renders while detached in SVG, SVG image and PNG", "each image decodes after attachment with its original destination", "each render context is unloaded"] };
});
await c.case(`native:embed-regressions:${context}:padding`, ["P02", "P05"], async () => {
p.settings.previewImageType = "SVG";
const scene=JSON.parse(template.match(/```json\n([\s\S]*?)\n```/)[1]);
scene.elements.push({...scene.elements[0],id:"distant",x:5000,y:1000,width:100,height:100,index:"a2"});
const drawing=await create("assets/deep/Area.excalidraw.md",template.replace(/```json\n[\s\S]*?\n```/,"```json\n"+JSON.stringify(scene)+"\n```"));
await c.waitFor(()=>p.isExcalidrawFile(drawing),"area drawing metadata");
const bytes=await app.vault.read(drawing);
const token = `![[${drawing.path}#^area=fixture-0,padding=0|200]]`;
const source = token + "\n\n" + token + `\n\n![[${drawing.path}|200]]\n\nEnd`;
const paddingNote = await create("notes/Padding.md", source);
await leaf.setViewState({ type: "empty", state: {} }); await open(paddingNote, "source");
await c.waitFor(() => images().length === 3 && images().every(decoded), "padding images decoded");
const frames = () => [...root().querySelectorAll(".excalidraw-embed-controls-frame")];
await c.waitFor(() => frames().length === 3, "padding toolbar bindings");
check(frames()[2].querySelector('[data-excalidraw-embed-action="padding"] .lucide-box-select'), "whole drawing outer-padding icon absent");
const launch = async () => {
const frame = frames()[1]; frame.scrollIntoView({ block: "center" });
const button = frame.querySelector('[data-excalidraw-embed-action="padding"]'); button.focus();
await click(button);
await c.waitFor(() => doc.querySelector(".excalidraw-embed-padding-popover input"), "padding slider opens");
const popup=doc.querySelector(".excalidraw-embed-padding-popover"), row=popup.querySelector(".excalidraw-embed-padding-row"), help=popup.querySelector(".excalidraw-embed-padding-help");
check(row&&help&&!popup.querySelector(".excalidraw-embed-padding-heading"),"padding popup should have controls and a description without a visible label");
check(help.getBoundingClientRect().top>=row.getBoundingClientRect().bottom,"padding description is not below controls");
check(popup.querySelector("input").step==="1","compact padding slider does not use unit steps");
await c.waitFor(()=>!popup.querySelector("input").disabled,"saved-scene area range ready");
check(popup.querySelector("input").max==="5100","area range must reach the distant scene edge plus 100");
const readouts=[...popup.querySelectorAll("output,.slider-value")].filter(el=>el.getBoundingClientRect().width>0&&el.getBoundingClientRect().height>0);
check(readouts.length===1,"compact slider displays duplicate values");
check(readouts[0].getBoundingClientRect().top>=row.getBoundingClientRect().bottom,"compact value must be below the fixed slider row");
};
await launch();
const active=doc.querySelector(".excalidraw-embed-padding-popover input"), track=active.getBoundingClientRect(), y=track.top+track.height/2;
await env.input("Input.dispatchMouseEvent",{type:"mousePressed",x:track.left+track.width*.2,y,button:"left",buttons:1,clickCount:1});
for(const fraction of [.4,.6,.8]){
await env.input("Input.dispatchMouseEvent",{type:"mouseMoved",x:track.left+track.width*fraction,y,button:"left",buttons:1});
check(Math.abs(active.getBoundingClientRect().width-track.width)<.1,"dragging changed slider width");
check(active.max==="5100","dragging changed the snapshot range");
}
await env.input("Input.dispatchMouseEvent",{type:"mouseReleased",x:track.left+track.width*.8,y,button:"left",buttons:0,clickCount:1});
await key("Home", "Home", 36); await key("ArrowUp", "ArrowUp", 38); await key("ArrowUp", "ArrowUp", 38);
await c.waitFor(() => frames()[1].querySelector(".excalidraw-embed-padding-preview svg"), "padding export preview");
check(leaf.view.editor.getValue() === source, "padding preview wrote the note");
await key("Enter", "Enter", 13);
const changed = token + "\n\n" + token.replace("padding=0", "padding=2") + source.slice(2 * token.length + 2);
await c.waitFor(() => leaf.view.editor.getValue() === changed, "padding changed only the second occurrence");
leaf.view.editor.cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => leaf.view.editor.getValue() === source, "padding single undo");
await c.waitFor(() => frames().length === 3, "padding controls after undo");
await launch(); await key("End", "End", 35); await key("Escape", "Escape", 27);
check(leaf.view.editor.getValue() === source, "Escape changed padding source");
check(!doc.querySelector(".excalidraw-embed-padding-popover"), "padding popup leaked after Escape");
await leaf.view.save(); check(await app.vault.read(drawing) === bytes, "padding modified the destination drawing");
const view=await env.openDrawing("Preview-controls",{},template), ea=p.ea.getAPI(view);let imageId,areaId;
try{imageId=await ea.addImage(0,0,drawing.path+"#^frame=,padding=750",false,false);areaId=await ea.addImage(400,0,drawing.path+"#^area=fixture-0,padding=0",false,false);await ea.addElementsToView(false,true,true);}finally{ea.destroy();}
const original=JSON.stringify(view.getViewElements());
await view.drawingImagePreview.open(imageId);
await c.waitFor(()=>doc.querySelector(".excalidraw-drawing-preview-popover img")?.naturalWidth>0,"drawing settings preview image decoded");
const popup=doc.querySelector(".excalidraw-drawing-preview-popover"), preview=popup.querySelector("img"), slider=popup.querySelector('input[type="range"]');
check(popup.textContent.includes("frames or marker frames")&&popup.textContent.includes("default")&&popup.textContent.includes("Frame"),"view guidance must explain naming frames");
check(win.getComputedStyle(preview).borderTopStyle==="solid"&&parseFloat(win.getComputedStyle(preview).borderTopWidth)>0,"drawing preview outline absent");
check(preview.getBoundingClientRect().height<=preview.parentElement.getBoundingClientRect().height+.5,"preview exceeds its reserved height");
check(slider.step==="1","drawing settings padding slider does not use unit steps");
check(slider.max==="100","outer padding must be capped at 100");
const readouts=[...popup.querySelectorAll("output,.slider-value")].filter(el=>el.getBoundingClientRect().width>0&&el.getBoundingClientRect().height>0);
check(readouts.length===1&&readouts[0].textContent==="750","legacy padding must remain visible without duplicate values");
check(readouts[0].getBoundingClientRect().top>=slider.getBoundingClientRect().bottom,"drawing padding value must be below its slider");
const width=slider.getBoundingClientRect().width;
slider.focus();await key("Home","Home",36);await key("ArrowRight","ArrowRight",39);
check(slider.value==="1","one padding keypress did not produce one unit");
check(Math.abs(slider.getBoundingClientRect().width-width)<.1,"digit changes resized the drawing padding slider");
await key("Escape","Escape",27);
check(!doc.querySelector(".excalidraw-drawing-preview-popover")&&JSON.stringify(view.getViewElements())===original,"UI inspection changed the scene");
await view.drawingImagePreview.open(areaId);
await c.waitFor(()=>doc.querySelector('.excalidraw-drawing-preview-popover input[type="range"]')?.max==="5100","scene image area range");
const areaPopup=doc.querySelector(".excalidraw-drawing-preview-popover"), select=areaPopup.querySelector("select");
select.focus();await key("Home","Home",36);await key("ArrowDown","ArrowDown",40);await key("Enter","Enter",13);
check(areaPopup.querySelector('input[type="range"]').max==="100","switching to whole scene did not restore outer-padding cap");
select.focus();await key("End","End",35);await key("Enter","Enter",13);
check(areaPopup.querySelector('input[type="range"]').max==="5100","returning to the area lost its snapshot range");
await key("Escape","Escape",27);
check(JSON.stringify(view.getViewElements())===original,"area range inspection changed the scene");
return { assertions: ["whole drawing exposes the outer-padding icon", "one small readout below each slider keeps native drag geometry fixed", "area range uses saved scene bounds and stays at 5100 during dragging", "outer padding is capped at 100 and legacy 750 remains intact until edited", "both padding sliders use one-unit steps", "drawing settings explain named frames and outline the rendered image", "native slider keys create a live export preview without writing", "Enter changes only the second repeated area reference", "one native undo restores the complete original source", "Escape cancels and removes the popup", "the drawing bytes are unchanged"] };
});
}
+378
View File
@@ -0,0 +1,378 @@
/** PR #3046: exercise the real picker, section cards, SVG files and focused Save As. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
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 embedReliabilityCaseIds = ["main", "popout"].flatMap(context =>
["aliases", "headings", "svg", "nbsp", "save-as"].map(kind => `native:embed-reliability:${context}:${kind}`));
export async function runEmbedReliabilityScenario({ cli, drawingPath }) {
const template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8");
const original = readFileSync(new URL("../../../tests/fixtures/2389.excalidraw.md", import.meta.url), "utf8");
const tests = [], consoleErrors = [], windowErrors = [], browserIdle = [];
for (const id of ["main", "popout"]) {
const execute = new Function(`return async function(c,path,context,template,original,modifier){
const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()});
await (${exercise.toString()})(c,env,original,modifier,context.id);
return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors,browserIdle:env.browserIdle};
}`)();
const result = await runInAppTask({ cli, execute,
args: [drawingPath, { id, input: "mouse" }, template, original, process.platform === "darwin" ? 4 : 2],
timeoutMs: 240000, cleanupMs: 60000, onRequest: behaviorInputDriver(cli),
onProgress: phase => { if (phase) process.stdout.write("Embed reliability: " + phase + "\n"); },
}).catch(error => { error.evidence = [...tests, ...(error.evidence || [])]; throw error; });
tests.push(...result.tests); consoleErrors.push(...result.consoleErrors); windowErrors.push(...result.windowErrors); browserIdle.push(...result.browserIdle);
}
assert.equal(consoleErrors.length, 0); assert.equal(splitWindowErrors(windowErrors).unexpected.length, 0);
assert.ok(browserIdle.every(item => item.status === "passed"));
assert.ok(tests.every(item => item.status === "passed")), assert.equal(tests.length, embedReliabilityCaseIds.length);
return { id: "embed-reliability-3046", status: "passed", tests, consoleErrors, windowErrors, browserIdle };
}
async function exercise(c, env, original, modifier, context) {
const { p, doc, win, leaf, create, check, openDrawing, saveReopen, key } = env;
c.observations = {};
let view = await openDrawing("Reliability");
const failures = [];
const run = async (kind, features, body) => {
c.phase = `native:embed-reliability:${context}:${kind}`;
try { await c.case(c.phase, features, body); }
catch (error) { if (c.cancelled) throw error; failures.push(String(error)); }
};
// Capture the real modal before onOpen's fire-and-forget form creation, so
// baseline constructor failures are observed without leaking a rejected task.
const form = async file => {
const { Modal } = p.ea.obsidian, open = Modal.prototype.open;
let modal;
Modal.prototype.open = function () { modal = this; };
try { app.commands.executeCommandById("obsidian-excalidraw-plugin:universal-add-file"); }
finally { Modal.prototype.open = open; }
check(modal, "Insert file command did not construct a modal");
modal.file = file;
modal.onOpen = () => {};
open.call(modal);
try {
await modal.createForm();
if (file) await c.waitFor(() => modal.contentEl.querySelector("select")?.options.length > 0, "section picker initial update");
}
catch (error) { modal.close(); throw error; }
return modal;
};
await run("aliases", ["P03"], async () => {
const values = [undefined, null, "Whole alias", ["First", "Second"], { data: null }, 42, true, ["Good", null, {}, 8, ""]];
const files = [];
for (let i = 0; i < values.length; i++) files.push(await create("Alias-" + i + ".md", values[i] === undefined ? "Body" : "---\naliases: " + JSON.stringify(values[i]) + "\n---\nBody"));
await c.waitFor(() => files.every(file => app.metadataCache.getFileCache(file)), "alias metadata");
const bytes = await Promise.all(files.map(file => app.vault.read(file)));
let modal;
try {
modal = await form();
const input = modal.contentEl.querySelector("input");
for (const file of files) {
input.value = file.path; input.dispatchEvent(new win.Event("input", { bubbles: true }));
check([...doc.querySelectorAll(".suggestion-item")].some(item => item.textContent.includes(file.basename)), "File path disappeared from mixed picker");
}
input.value = "Whole alias"; input.dispatchEvent(new win.Event("input", { bubbles: true }));
check([...doc.querySelectorAll(".suggestion-item")].some(item => item.textContent.includes("Whole alias")), "Scalar alias split into characters");
} finally { modal?.close(); }
await app.fileManager.renameFile(files[0], env.prefix + "/Renamed.md");
modal = await form(); modal.close();
check((await Promise.all(files.map(file => app.vault.read(file)))).every((value, i) => value === bytes[i]), "Picker modified source YAML");
// Remove malformed fixtures before the independent heading tests.
for (const file of files) await app.vault.delete(file);
return { assertions: ["unsupported aliases do not block paths", "whole string and list aliases remain searchable", "rename/reopen and source YAML fidelity"] };
});
// Failed alias reproduction must not poison the other independent cases.
for (const file of app.vault.getFiles().filter(file => file.path.startsWith(env.prefix + "/Alias-") || file.path === env.prefix + "/Renamed.md")) await app.vault.delete(file);
await run("headings", ["P05"], async () => {
const wikiFile = await create("link to a file.md", "WIKI_DESTINATION_BODY");
const wikiBytes = await app.vault.read(wikiFile);
const headings = [
"Plain heading", "[H1 Header]", "[H1 Header with Links](http://www.google.com)",
"*Emphasis* and `code`", "[Nested](https://example.com/a_(b))", "[Escaped](https://example.com/a\\(b\\))",
"[First](https://example.com) and [Second](https://example.org)", "[[Target]] and [[Target|Alias]]",
"Literal [brackets] and (parentheses)", "Punctuation: # hash ^ caret | pipe", "Unicode Árvíz 中文 مرحبا שלום",
"[Looks like a file](https://example.com/Other.md#^block|alias)", "Duplicate", "Duplicate", "Last heading",
"[[link to a file]]", "[[link to a file|Friendly file label]]", "[[missing wiki heading target]]",
];
const wikiIndices = [15, 16, 17];
const source = headings.map((heading, i) => "#".repeat(wikiIndices.includes(i) ? 2 : i % 6 + 1) + " " + heading + "\n\nSECTION_TOKEN_" + i + "\n").join("\n") + "\nBlock body ^known-block\n";
const target = await create("Headings.md", source);
await c.waitFor(() => app.metadataCache.getFileCache(target)?.headings?.length === headings.length, "linked heading metadata");
await c.waitFor(() => app.metadataCache.getFirstLinkpathDest("link to a file", target.path) === wikiFile, "heading wikilink resolves to the existing local file");
check(!app.metadataCache.getFirstLinkpathDest("missing wiki heading target", target.path), "Missing heading wikilink unexpectedly resolves");
const { stripHeading, resolveSubpath } = p.ea.obsidian;
const cache = app.metadataCache.getFileCache(target);
const expected = cache.headings.map(heading => "#" + stripHeading(heading.heading));
c.observations.wikiHeadingCases = wikiIndices.map(i => ({ source: "## " + headings[i], subpath: expected[i], level: cache.headings[i].level }));
check(wikiIndices.every(i => cache.headings[i].level === 2), "Exact level-two wikilink headings changed");
const modal = await form(target);
try {
const options = [...modal.contentEl.querySelector("select").options];
const values = options.map(item => item.value);
c.observations = { ...c.observations, headings: cache.headings, expected, blocks: (await app.metadataCache.blockCache.getForFile({ isCancelled: () => false }, target)).blocks, options: options.map(item => ({ value: item.value, text: item.textContent })) };
const missing = expected.filter(subpath => !values.includes(subpath));
for (const subpath of expected) check(resolveSubpath(cache, subpath)?.type === "heading", "Obsidian canonical heading did not resolve: " + subpath);
check(missing.length === 0, "Headings missing from section picker: " + JSON.stringify(missing));
check(values[0] === "" && !values.includes("#^known-block"), "Whole-file and block choices changed");
} finally { modal.close(); }
const inserted = [], insertedImages = [];
for (let i = 0; i < expected.length; i++) {
const selected = expected[i], first = expected.indexOf(selected);
const transclusion = await view.excalidrawData.getTransclusion(target.path + selected);
check(transclusion.contents.includes("SECTION_TOKEN_" + first), "Image source resolved a different section: " + selected);
if (wikiIndices.includes(i)) check(transclusion.contents.includes(headings[i]), "Image transclusion changed the heading wikilink source");
const picker = await form(target);
picker.contentEl.querySelector("select").value = selected;
const before = new Set(view.excalidrawAPI.getSceneElements().map(element => element.id));
[...picker.contentEl.querySelectorAll("button")].find(button => button.textContent === "as Embeddable").click();
let element;
await c.waitFor(() => element = view.excalidrawAPI.getSceneElements().find(element => !before.has(element.id)), "interactive section inserted");
inserted.push({ id: element.id, token: "SECTION_TOKEN_" + first, link: element.link });
view.excalidrawAPI.zoomToFit([element], 1, 0.05);
await c.waitFor(() => {
const node = view.getEmbeddableLeafElementById(element.id)?.node;
c.observations.headingInsert = { i, selected, element: { id: element.id, type: element.type, link: element.link }, node: node && { keys: Object.keys(node), html: node.containerEl?.outerHTML.slice(0, 4000) } };
return node?.containerEl.textContent.includes("SECTION_TOKEN_" + first);
}, "interactive section body");
if ([0, 2, 7, 10].includes(i) || wikiIndices.includes(i)) {
const imagePicker = await form(target);
imagePicker.contentEl.querySelector("select").value = selected;
const before = new Set(view.excalidrawAPI.getSceneElements().map(element => element.id));
[...imagePicker.contentEl.querySelectorAll("button")].find(button => button.textContent === "as Image").click();
let image;
await c.waitFor(() => image = view.excalidrawAPI.getSceneElements().find(element => !before.has(element.id) && element.type === "image"), "section image inserted");
await c.waitFor(() => view.excalidrawAPI.getFiles()[image.fileId]?.dataURL, "section image payload");
await env.decode(view.excalidrawAPI.getFiles()[image.fileId].dataURL);
insertedImages.push({ id: image.id, fileId: image.fileId });
}
}
view = await saveReopen(view);
for (const entry of inserted) {
check(view.excalidrawAPI.getSceneElements().find(element => element.id === entry.id)?.link === entry.link, "Saved heading link changed");
view.excalidrawAPI.zoomToFit([view.excalidrawAPI.getSceneElements().find(element => element.id === entry.id)], 1, 0.05);
await c.waitFor(() => view.getEmbeddableLeafElementById(entry.id)?.node?.containerEl.textContent.includes(entry.token), "reopened section body");
}
for (const entry of insertedImages) {
check(view.excalidrawAPI.getSceneElements().find(element => element.id === entry.id)?.fileId === entry.fileId, "Saved section image identity changed");
await c.waitFor(() => view.excalidrawAPI.getFiles()[entry.fileId]?.dataURL, "reopened section image payload");
await env.decode(view.excalidrawAPI.getFiles()[entry.fileId].dataURL);
}
check(!resolveSubpath(cache, "#Nonexistent") && !resolveSubpath(cache, "#^missing-block"), "Missing sections unexpectedly resolved");
check(resolveSubpath(cache, "#^known-block")?.type === "block", "Existing block reference changed");
const renamed = source.replace("Plain heading", "Renamed heading");
try {
await app.vault.modify(target, renamed);
await c.waitFor(() => app.metadataCache.getFileCache(target)?.headings?.[0].heading === "Renamed heading", "renamed heading metadata");
check(!resolveSubpath(app.metadataCache.getFileCache(target), expected[0]), "Old heading silently resolved after rename");
check(view.excalidrawAPI.getSceneElements().find(element => element.id === inserted[0].id)?.link === inserted[0].link, "Source rename rewrote the existing drawing link");
const picker = await form(target);
try { check([...picker.contentEl.querySelector("select").options].some(option => option.value === "#Renamed heading"), "Reopened picker did not follow the rename"); }
finally { picker.close(); }
} finally {
await app.vault.modify(target, source);
await c.waitFor(() => app.metadataCache.getFileCache(target)?.headings?.[0].heading === "Plain heading", "restored heading metadata");
}
const drawingFile = view.file;
const referenceCases = [{ index: 2, label: "Linked heading" }, ...wikiIndices.map((index, i) => ({ index, label: "Wiki heading " + i }))];
const references = await create("References.md", referenceCases.map(({ index, label }) => `[[${target.path}${expected[index]}|${label}]]`).join("\n\n") + `\n\n[[${target.path}#^known-block|Known block]]\n\n[[${target.path}|Whole file]]\n\nEnd`);
for (const mode of ["preview", "source"]) for (const reference of referenceCases) {
await env.input("Input.dispatchMouseEvent", { type: "mouseMoved", x: win.innerWidth - 5, y: win.innerHeight - 5 });
await c.waitFor(() => ![...doc.querySelectorAll(".hover-popover")].some(popover => popover.getClientRects().length), "previous link hover preview closes after pointer leaves");
// Each navigation starts with a fresh Markdown view, independently of
// the preceding destination's renderer and section-reveal callbacks.
await leaf.setViewState({ type: "empty", state: {} });
await leaf.setViewState({ type: "markdown", state: { file: references.path, mode, source: false } });
app.workspace.setActiveLeaf(leaf, { focus: true }); win.focus();
if (mode === "source") leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 });
const findReferenceLink = () => {
const root = leaf.view.contentEl.querySelector(mode === "preview" ? ".markdown-preview-view" : ".markdown-source-view.is-live-preview");
return [...root?.querySelectorAll("a.internal-link,.cm-hmd-internal-link") || []].find(link => link.textContent === reference.label);
};
let link;
await c.waitFor(() => {
const root = leaf.view.contentEl.querySelector(mode === "preview" ? ".markdown-preview-view" : ".markdown-source-view.is-live-preview");
link = findReferenceLink();
c.observations.navigation = { mode, reference, actualMode: leaf.view.getMode(), html: root?.innerHTML.slice(0, 2500) };
return link && link.getBoundingClientRect().width > 0;
}, "ordinary heading link in " + mode);
link.scrollIntoView({ block: "center", inline: "nearest" });
let x, y, signature, stableSince = 0;
await c.waitFor(() => {
link = findReferenceLink();
if (!link) return false;
const rect = link.getBoundingClientRect(); x = rect.left + rect.width / 2; y = rect.top + rect.height / 2;
const current = [rect.x, rect.y, rect.width, rect.height].map(value => Math.round(value * 10)).join(":");
if (signature !== current) { signature = current; stableSince = Date.now(); }
c.observations.navigation.hit = { bounds: rect.toJSON(), target: doc.elementFromPoint(x, y)?.outerHTML.slice(0, 500) };
return Date.now() - stableSince >= 120 && link.contains(doc.elementFromPoint(x, y));
}, "visible uncovered heading link in " + mode);
const capturePointer = event => {
c.observations.navigation.event = { trusted: event.isTrusted, href: event.target.closest?.("a.internal-link,.cm-hmd-internal-link")?.getAttribute("data-href"), text: event.target.textContent };
};
doc.addEventListener("mousedown", capturePointer, true);
try {
// One bounded native sequence avoids CLI roundtrip delays between
// press/release. Live Preview requires Ctrl/Cmd to follow the link.
await env.input("Input.dispatchMouseEvent", ["mousePressed", "mouseReleased"].map(type => ({ type, x, y, button: "left", buttons: type === "mousePressed" ? 1 : 0, clickCount: 1, modifiers: mode === "source" ? modifier : 0 })));
} finally {
doc.removeEventListener("mousedown", capturePointer, true);
}
check(c.observations.navigation.event?.trusted && c.observations.navigation.event.text === reference.label, "Trusted pointer did not reach the intended section link");
let destination;
await c.waitFor(() => {
const candidates = app.workspace.getLeavesOfType("markdown").filter(candidate => candidate.view.containerEl.ownerDocument === doc);
for (const candidate of candidates) if (candidate.view.file?.path.startsWith(env.prefix + "/")) env.owned.add(candidate);
c.observations.navigation.leaves = candidates.map(candidate => ({ id: candidate.id, path: candidate.view.file?.path, mode: candidate.view.getMode() }));
// Ctrl/Cmd-click may open a new tab; preserve that host behavior.
return destination = candidates.find(candidate => candidate.view.file === target && candidate === app.workspace.activeLeaf);
}, "ordinary section link navigation in " + mode);
if (destination.view.getMode() === "source") await c.waitFor(() => {
c.observations.navigation.cursor = destination.view.editor.getCursor("from");
return c.observations.navigation.cursor.line === cache.headings[reference.index].position.start.line;
}, "ordinary section link reveals its source heading");
else await c.waitFor(() => {
const preview = destination.view.contentEl.querySelector(".markdown-preview-view");
c.observations.navigation.destination = { file: destination.view.file?.path, text: preview?.textContent.slice(-1200) };
return preview?.textContent.includes("SECTION_TOKEN_" + reference.index);
}, "ordinary section link renders its destination before the next navigation");
}
await leaf.openFile(drawingFile); await env.ready(leaf); view = leaf.view;
check(await app.vault.read(target) === source, "Heading picker modified Markdown");
check(await app.vault.read(wikiFile) === wikiBytes, "Heading insertion modified the wikilink destination");
return { assertions: ["formatted, linked, escaped, wikilink, duplicate, six-level and Unicode heading options match Obsidian", "exact level-two wikilink-only headings with existing, aliased and missing file targets", "interactive insertion, image source and decoded image insertion", "saved links, section bodies and decoded images survive reopen", "whole file, missing sections and block choices stay separate", "rename updates picker without rewriting existing links", "ordinary links to URL and wikilink headings navigate in Reading and Live Preview", "source and wikilink destination remain unchanged"], wikiHeadings: c.observations.wikiHeadingCases };
});
await run("svg", ["P04"], async () => {
const urls = ['http://google.com/search?q=<p>hello</p>', 'https://example.com/?a=1&b=2', 'https://example.com/?a=&amp;&b=%26%3C', 'https://example.com/?q="quoted"#hash', 'https://example.com/Árvíz/中文?x=<tag>&y=100%25'];
const target = await create("ExportTarget.md", "Internal export target");
await c.waitFor(() => app.metadataCache.getFileCache(target), "SVG internal destination");
const originalHook = p.ea.onUpdateElementLinkForExportHook, calls = [], pathCalls = [];
const originalPathHook = p.ea.onImageExportPathHook;
const originalAutoexportHook = p.ea.onTriggerAutoexportHook;
const rewritten = "https://example.com/internal?q=<tag>&value=1";
p.ea.onUpdateElementLinkForExportHook = data => { calls.push(data.originalLink); return rewritten; };
p.ea.onImageExportPathHook = data => { pathCalls.push({ path: data.exportFilepath, action: data.action, extension: data.exportExtension }); return data.exportFilepath.replace(/\.svg$/, ".hook.svg"); };
const parse = xml => {
const parsed = new win.DOMParser().parseFromString(xml, "image/svg+xml");
check(!parsed.querySelector("parsererror"), "Exported SVG is invalid XML: " + parsed.querySelector("parsererror")?.textContent);
return parsed;
};
try {
for (const includeInternalLinks of [true, false]) {
view = await openDrawing("SVG-" + includeInternalLinks, { "excalidraw-export-internal-links": includeInternalLinks });
const ea = p.ea.getAPI(view);
try {
view.excalidrawAPI.updateScene({ elements: [], captureUpdate: "NEVER" });
for (const [i, url] of [...urls, `[[${target.path}|Alias]]`].entries()) ea.getElement(ea.addText(0, i * 35, "Link " + i)).link = url;
await ea.addElementsToView(false, false);
const before = JSON.stringify(view.excalidrawAPI.getSceneElements());
for (const theme of ["light", "dark"]) {
const svg = await ea.createViewSVG({ theme, embedScene: true, skipInliningFonts: true });
const links = [...parse(svg.outerHTML).querySelectorAll("a")].map(link => link.getAttribute("href"));
c.observations.svgLinks = { theme, includeInternalLinks, urls, links };
// The fork deliberately normalizes literal quotes before SVG creation.
check(urls.every(url => links.includes(url.replaceAll('"', "&quot;"))), "External SVG destination escaped twice or changed");
check(links.includes(rewritten) === includeInternalLinks, "Internal-link removal or export hook changed");
check(svg.querySelector("metadata"), "SVG lost scene metadata");
const clipboardSVG = await view.getSVG(true, false);
check([...parse(clipboardSVG.outerHTML).querySelectorAll("a")].map(link => link.getAttribute("href")).join("\n") === links.join("\n"), "Clipboard SVG destinations differ");
await view.saveSVG({ autoexportConfig: { theme } });
const file = app.vault.getFileByPath(view.file.path.replace(/\.md$/, ".hook.svg"));
check(file, "Manual SVG export missing");
const parsed = parse(await app.vault.read(file));
check([...parsed.querySelectorAll("a")].map(link => link.getAttribute("href")).join("\n") === links.join("\n"), "Manual SVG and EA destinations differ");
const staged = await ea.createSVG(undefined, false, undefined, undefined, theme, 10, false, includeInternalLinks);
check(parse(staged.outerHTML).querySelectorAll("a").length === urls.length + Number(includeInternalLinks), "EA createSVG link-removal option changed");
}
check(JSON.stringify(view.excalidrawAPI.getSceneElements()) === before, "SVG export mutated source elements");
let autoexportCalls = 0;
p.ea.onTriggerAutoexportHook = data => {
check(data.excalidrawFile === view.file, "Autoexport hook file identity changed"); autoexportCalls++;
return { ...data.autoexportConfig, svg: true, png: false, excalidraw: false, theme: "both" };
};
check((await view.saveWithOutcome()).status === "persisted", "SVG fixture save did not persist");
for (const theme of ["light", "dark"]) {
const path = view.file.path.replace(/\.md$/, "." + theme + ".hook.svg");
await c.waitFor(() => app.vault.getFileByPath(path), "hook-controlled light/dark autoexport");
const links = [...parse(await app.vault.read(app.vault.getFileByPath(path))).querySelectorAll("a")].map(link => link.getAttribute("href"));
check(links.includes(rewritten) === includeInternalLinks && links.length === urls.length + Number(includeInternalLinks), "Autoexport link policy changed");
}
check(autoexportCalls > 0, "Autoexport hook was bypassed");
p.ea.onTriggerAutoexportHook = originalAutoexportHook;
} finally { ea.destroy(); }
}
check(calls.length > 0 && calls.every(link => link === `[[${target.path}|Alias]]`), "Link rewrite hook arguments changed");
check(pathCalls.length > 0 && pathCalls.every(call => call.action === "export" && call.extension.endsWith(".svg")), "Export path hook contract changed");
} finally { p.ea.onUpdateElementLinkForExportHook = originalHook; p.ea.onImageExportPathHook = originalPathHook; p.ea.onTriggerAutoexportHook = originalAutoexportHook; }
return { assertions: ["special-character URL matrix parses as XML without double escaping", "light/dark manual, clipboard, autoexport and EA SVG agree", "per-file and EA internal-link removal preserved", "link-rewrite, path and autoexport hooks retain their arguments and overrides", "scene metadata and source elements unchanged"] };
});
await run("nbsp", ["P05"], async () => {
const target = await create("NBSP.excalidraw.md", original);
await c.waitFor(() => p.isExcalidrawFile(target), "original NBSP fixture metadata");
const source = await app.vault.read(target);
const { Component, MarkdownRenderer } = p.ea.obsidian;
for (const type of ["SVGIMG", "SVG", "PNG"]) for (const warm of [false, true]) {
p.settings.previewImageType = type;
const component = new Component(); component.load();
const root = doc.body.createDiv({ cls: "markdown-preview-view markdown-rendered" });
try {
await MarkdownRenderer.render(app, `![[${target.path}]]`, root, view.file.path, component);
await c.waitFor(() => root.querySelector(".excalidraw-embedded-img"), "NBSP embed mounted");
const image = root.querySelector(".excalidraw-embedded-img");
if (image.tagName === "IMG") {
await image.decode(); check(image.naturalWidth > 0, "NBSP image did not decode");
if (type === "SVGIMG") {
const xml = await (await win.fetch(image.src)).text();
const parsed = new win.DOMParser().parseFromString(xml, "image/svg+xml");
check(!parsed.querySelector("parsererror") && parsed.querySelector("text")?.textContent.includes("\u00a0"), "SVG image/cache lost NBSP or valid XML");
}
}
else check(image.querySelector("text")?.textContent.includes("\u00a0"), "Native SVG lost NBSP");
} finally { component.unload(); root.remove(); }
}
check(await app.vault.read(target) === source, "NBSP source changed");
return { assertions: ["original issue drawing decodes as SVG image, native SVG and PNG on cold and warm renders", "SVG image XML and cache retain NBSP", "NBSP and drawing source preserved"] };
});
await run("save-as", ["P02", "P03"], async () => {
view = await saveReopen(view);
const api = view.excalidrawAPI, exports = [], restorers = [];
for (const owner of new Set([win, app.workspace.containerEl.ownerDocument.defaultView])) {
const descriptor = Object.getOwnPropertyDescriptor(owner, "showSaveFilePicker");
Object.defineProperty(owner, "showSaveFilePicker", { configurable: true, value: async () => {
exports.push("picker");
return { name: "negative-control.excalidraw", kind: "file", createWritable: async () => ({ write: async () => exports.push("write"), close: async () => exports.push("closed") }) };
} });
restorers.push(() => descriptor ? Object.defineProperty(owner, "showSaveFilePicker", descriptor) : delete owner.showSaveFilePicker);
const prototype = owner.HTMLAnchorElement.prototype, click = prototype.click;
prototype.click = function () {
if (this.download.endsWith(".excalidraw") && (this.href.startsWith("blob:") || this.href.startsWith("data:text/plain"))) { exports.push("download"); return; }
return click.call(this);
};
restorers.push(() => { prototype.click = click; });
}
try {
api.updateScene({ appState: { theme: "dark", viewModeEnabled: false }, captureUpdate: "NEVER" });
await c.waitFor(() => api.getAppState().theme === "dark", "dark canvas");
const theme = doc.body.className;
view.containerEl.querySelector(".excalidraw").focus();
await key("s", "KeyS", 83, modifier | 8);
await key("Escape", "Escape", 27);
check(exports.length === 0, "Focused Save As invoked standalone file picker");
check(api.getAppState().theme === "dark" && doc.body.className === theme, "Save As changed drawing or application theme");
const outside = doc.body.createEl("input"), received = [];
try {
outside.addEventListener("keydown", event => received.push(event.defaultPrevented)); outside.focus();
await key("s", "KeyS", 83, modifier | 8);
check(received.length === 1 && !received[0], "Drawing guard intercepted a different focused surface");
} finally { outside.remove(); }
await view.exportExcalidraw();
check(exports.length === 1 && exports[0] === "download", "Dedicated legacy export stopped working");
} finally { for (const restore of restorers.reverse()) restore(); }
return { assertions: ["trusted focused Ctrl/Cmd+Shift+S cannot invoke external Save As", "canvas and application themes preserved after dismissal and reopen", "other focused surfaces retain their shortcut", "dedicated legacy export still downloads"] };
});
if (failures.length) throw Error(failures.join("\n"));
}
+29
View File
@@ -138,6 +138,33 @@ async function exerciseExtras(c, prefix, fixtures, drawingPath) {
const service = await plugin.extrasGateway.getMermaid();
check(service, "plugin gateway did not obtain Mermaid");
const module = await service.getModule();
const elbowDiagram = await module.parseMermaidToExcalidraw(
"flowchart TD\n A[Start] --> B[End]",
{ elbow: { flowchart: true } },
);
check(
elbowDiagram.elements.some((e) => e.type === "arrow" && e.elbowed),
"Converter 3.6 elbow configuration was not applied",
);
const legacySource = "flowchart TD\n A --> B\n A --> C\n B --> D\n C --> D";
const bench = plugin.ea.getAPI();
const legacyEdges = [];
try {
for (const roundness of [null, { type: 3 }]) {
bench.clear();
bench.style.roundness = roundness;
const ids = await bench.addMermaid(legacySource);
check(Array.isArray(ids) && ids.length > 0, "EA Mermaid conversion failed");
const arrows = bench.getElements().filter((e) => e.type === "arrow");
check(arrows.length === 4, "EA Mermaid lost connectors");
legacyEdges.push(JSON.stringify(arrows.map((e) => ({
points: e.points, roundness: e.roundness, elbowed: e.elbowed,
}))));
}
} finally {
bench.destroy();
}
check(legacyEdges[0] !== legacyEdges[1], "EA straight/rounded curve preference was ignored");
const converted = await module.parseMermaidToExcalidraw(
"flowchart LR\n A[Start] --> B[End]",
);
@@ -217,6 +244,8 @@ async function exerciseExtras(c, prefix, fixtures, drawingPath) {
assertions: [
"real plugin gateway resolves Mermaid",
"actual converter returns editable labels and arrow",
"converter 3.6 applies elbow configuration",
"actual EA.addMermaid retains straight/rounded connector behavior",
"twelve diagram types load offline with finite normalized geometry and preserved representation",
"editable labels and decoded image dimensions survive lazy loading",
"syntax rejects and next diagram recovers",
+257
View File
@@ -0,0 +1,257 @@
/** Focused #3042 metadata, thumbnail rendering, source controls and navigation. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { runInAppTask } from "./inAppTask.mjs";
import { exerciseDrawingImagePreview } from "./drawingImagePreview.mjs";
import { behaviorEnvironment } from "./behaviorEnvironment.mjs";
import { behaviorInputDriver, collectBehaviorCases } from "./behaviorMatrix.mjs";
import { completeConsoleErrors } from "./debuggerSession.mjs";
import { settleBrowserDiagnostics, splitWindowErrors } from "./browserDiagnostics.mjs";
const kinds = ["metadata", "navigation", "previews", "controls", "outer-padding", "scene-images"];
export const frameSemanticsCaseIds = ["main", "popout"].flatMap(context => kinds.map(kind => `native:frames:${context}:${kind}`)).concat("native:frames:settings-reload");
export const frameSemanticsDeviceCaseIds = ["phone", "tablet"].flatMap(context => kinds.map(kind => `native:frames:${context}:${kind}`));
export async function runFrameSemanticsScenario({ cli, drawingPath, contexts = ["main", "popout"], inputMode = "mouse", viewportScale = 1 }) {
let template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8");
const scene = JSON.parse(template.match(/```json\n([\s\S]*?)\n```/)[1]), base = scene.elements[0];
scene.elements = [
{ ...base, id: "frame-main", type: "frame", name: "Main, α", width: 200, height: 120, index: "a0", customData: undefined },
{ ...base, id: "inside", x: 20, y: 20, width: 60, height: 40, frameId: "frame-main", index: "a1", backgroundColor: "#00ff00" },
{ ...base, id: "frame-marker", type: "frame", frameRole: "marker", name: "Marker,padding=50", x: 300, width: 100, height: 160, index: "a2" },
{ ...base, id: "frame-unnamed", type: "frame", name: null, x: 500, index: "a3" },
{ ...base, id: "frame-literal", type: "frame", name: "Frame", x: 650, index: "a4" },
{ ...base, id: "outside-crop", x: 210, y: 20, width: 10, height: 10, backgroundColor: "#ff0000", index: "a4V" },
{ ...base, id: "outside", x: 900, y: 300, index: "a5" },
];
template = template.replace(/```json\n[\s\S]*?\n```/, "```json\n" + JSON.stringify(scene, null, 2) + "\n```");
const tests = [], consoleErrors = [], windowErrors = [], browserIdle = [];
for (const id of contexts) {
const execute = new Function(`return async function(c,path,context,template,modifier){
const env=await (${behaviorEnvironment.toString()})(c,path,context,template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()});
c.diagnostics=env.diagnostics;
(${collectBehaviorCases.toString()})(c);
await (${exercise.toString()})(c,env,template,modifier,context.id,(${exerciseDrawingImagePreview.toString()}));
return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors,browserIdle:env.browserIdle};
}`)();
const result = await runInAppTask({ cli, execute, args: [drawingPath, { id, input: inputMode }, template, process.platform === "darwin" ? 4 : 2],
timeoutMs: 240000, cleanupMs: 60000, onRequest: behaviorInputDriver(cli, viewportScale),
onProgress: phase => { if (phase) process.stdout.write("Frames: " + phase + "\n"); },
});
tests.push(...result.tests); consoleErrors.push(...result.consoleErrors); windowErrors.push(...result.windowErrors); browserIdle.push(...result.browserIdle);
}
if (contexts.includes("main")) {
const result = await runInAppTask({ cli, execute: reloadSettings, args: [], timeoutMs: 90000, cleanupMs: 60000 });
tests.push(...result.tests);
}
assert.equal(consoleErrors.length, 0); assert.equal(splitWindowErrors(windowErrors).unexpected.length, 0);
assert.ok(browserIdle.every(item => item.status === "passed"));
if (tests.some(test => test.status !== "passed")) {
const error = Error("Focused frame cases failed: " + tests.filter(test => test.status !== "passed").map(test => test.testId).join(", "));
error.evidence = tests; throw error;
}
return { id: "frame-semantics", status: "passed", tests, consoleErrors, windowErrors, browserIdle };
}
async function reloadSettings(c) {
await c.case("native:frames:settings-reload", ["P01", "P02"], async () => {
const id = "obsidian-excalidraw-plugin", old = app.plugins.plugins[id], key = "__framePolicyFutureSetting";
const original = old.settings.thumbnailRenamePolicy;
const settingsPath = app.vault.configDir + "/plugins/" + id + "/data.json";
c.defer(async () => {
if (!app.plugins.plugins[id]) await app.plugins.enablePlugin(id);
await c.waitForCleanup(() => app.plugins.plugins[id]?.isReady, "restored plugin readiness");
const live = app.plugins.plugins[id]; live.settings.thumbnailRenamePolicy = original; delete live.settings[key]; await live.saveSettings();
});
old.settings.thumbnailRenamePolicy = "ask"; old.settings[key] = { zero: 0, enabled: false };
await old.saveSettings();
const before = JSON.parse(await app.vault.adapter.read(settingsPath));
if (before.thumbnailRenamePolicy !== "ask" || before[key]?.enabled !== false) throw Error("policy not persisted before unload");
await app.plugins.disablePlugin(id); await app.plugins.enablePlugin(id);
await c.waitFor(() => app.plugins.plugins[id]?.isReady, "replacement plugin readiness");
const live = app.plugins.plugins[id], after = JSON.parse(await app.vault.adapter.read(settingsPath));
if (live === old || live.settings.thumbnailRenamePolicy !== "ask" || live.settings[key]?.zero !== 0 || live.settings[key]?.enabled !== false || after.thumbnailRenamePolicy !== "ask") throw Error("reload lost non-default policy or unknown settings");
return { assertions: ["non-default rename policy saved on disk", "actual unload/startup creates new plugin instance", "new policy and unknown zero/false settings survive on disk and in memory"] };
});
return { tests: c.tests };
}
async function exercise(c, env, template, modifier, context, sceneExercise) {
const { p, leaf, doc, win, check, click, key } = env;
const nativeWindow = win.require("@electron/remote").getCurrentWindow();
const minimized = nativeWindow.isMinimized(); nativeWindow.restore(); nativeWindow.show(); nativeWindow.focus();
if (minimized) c.defer(() => { if (!nativeWindow.isDestroyed()) nativeWindow.minimize(); });
let view = await env.openDrawing("Frames", { "excalidraw-thumbnail": "Main, α", "excalidraw-export-padding": 0, "retained-property": "untouched" });
const drawing = view.file;
const customData = () => JSON.stringify(view.getViewElements().filter(element => element.type === "frame").map(element => [element.id, element.customData]).sort((a, b) => a[0].localeCompare(b[0])));
const yaml = async () => p.ea.obsidian.parseYaml((await app.vault.read(drawing)).match(/^---\n([\s\S]*?)\n---/)[1]);
const thumbnailIs = async name => {
const property = (await yaml())["excalidraw-thumbnail"];
c.caseTrace = { ...c.caseTrace, thumbnail: { property, tracked: view.frameThumbnail.tracked, patch: !!view.frameThumbnail.patch, running: view.frameThumbnail.running, scene: view.getViewElements().filter(element => element.type === "frame").map(element => [element.id, element.name]) } };
return property === name;
};
const rename = name => {
const api = view.excalidrawAPI;
api.updateScene({ elements: api.getSceneElements().map(element => element.id === "frame-main" ? { ...element, name, version: element.version + 1, versionNonce: element.versionNonce + 1 } : element), captureUpdate: "IMMEDIATELY" });
};
await c.case(`native:frames:${context}:metadata`, ["P02", "P05"], async () => {
view.setDirty(); await view.forceSave(true, true);
const originalCustomData = customData();
check(JSON.stringify((await yaml())["excalidraw-anchors"]) === JSON.stringify(["Main, α", "Marker,padding=50", "Frame"]), "actual frame names not saved as ordered YAML list");
check((await yaml())["retained-property"] === "untouched", "unrelated YAML changed");
check(await view.frameThumbnail.setThumbnail("Marker,padding=50"), "marker thumbnail write failed");
check((await yaml())["excalidraw-thumbnail"] === "Marker,padding=50", "thumbnail name parsed as padding");
await view.zoomToElementId("frame-main", false);
const state = view.excalidrawAPI.getAppState(), x = (100 + state.scrollX) * state.zoom.value + state.offsetLeft, y = state.scrollY * state.zoom.value + state.offsetTop + 1;
await env.input("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "right", buttons: 2, clickCount: 1 });
await env.input("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "right", buttons: 0, clickCount: 1 });
await c.waitFor(() => doc.querySelector('[data-testid="drawingThumbnail"] button'), "selected frame thumbnail context action");
const action = doc.querySelector('[data-testid="drawingThumbnail"] button');
check(action.title.includes("excalidraw-thumbnail"), "thumbnail context help absent"); await click(action);
await c.waitFor(async () => (await yaml())["excalidraw-thumbnail"] === "Main, α", "context action saves exact frame name");
p.settings.thumbnailRenamePolicy = "always"; await p.saveSettings();
rename("Renamed, β");
await c.waitFor(() => thumbnailIs("Renamed, β"), "rename policy saves YAML");
rename("Main, α");
await c.waitFor(() => thumbnailIs("Main, α"), "reverted frame name saves YAML");
check(customData() === originalCustomData, "thumbnail changed scene metadata: " + originalCustomData + " -> " + customData());
view = await env.saveReopen(view);
check((await yaml())["excalidraw-thumbnail"] === "Main, α", "thumbnail lost after reopen");
p.settings.autoexportSVG = true; p.settings.autoexportPNG = true; p.settings.displayExportedImageIfAvailable = true;
view.setDirty(); await view.forceSave(true, true);
const exportBase = drawing.path.slice(0, -3);
await c.waitFor(() => app.vault.getFileByPath(exportBase + ".svg") && app.vault.getFileByPath(exportBase + ".png"), "full-scene autoexports created");
const svg = new win.DOMParser().parseFromString(await app.vault.read(app.vault.getFileByPath(exportBase + ".svg")), "image/svg+xml").documentElement;
check(svg.viewBox.baseVal.width > 900, "SVG autoexport inherited thumbnail crop");
const png = new win.Blob([await app.vault.readBinary(app.vault.getFileByPath(exportBase + ".png"))], { type: "image/png" }), url = win.URL.createObjectURL(png);
try { const image = new win.Image(); image.src = url; await image.decode(); check(image.naturalWidth / image.naturalHeight > 2, "PNG autoexport inherited thumbnail crop"); } finally { win.URL.revokeObjectURL(url); }
p.settings.autoexportSVG = false; p.settings.autoexportPNG = false;
return { assertions: ["regular, marker and literal Frame names form an ordered YAML list; unnamed excluded", "unrelated YAML survives", "exact marker name with padding-looking suffix round trips", "always policy follows rename and revert", "no thumbnail customData", "save/reopen retains metadata"] };
});
await c.case(`native:frames:${context}:navigation`, ["P02"], async () => {
const api = view.excalidrawAPI, mode = api.getAppState().viewModeEnabled;
api.toggleSidebar({ name: "default", tab: "search", force: true });
await c.waitFor(() => view.contentEl.querySelector('.layer-ui__search-inputWrapper input'), "Search input opens");
const search = view.contentEl.querySelector('.layer-ui__search-inputWrapper input'); await click(search);
await key("a", "KeyA", 65, modifier);
await env.input("Input.insertText", { text: "retained needle" });
await c.waitFor(() => search.value === "retained needle", "Search sentinel entered");
const before = search.value, scene = JSON.stringify(api.getSceneElements());
app.commands.executeCommandById("obsidian-excalidraw-plugin:navigate-to-frame");
await c.waitFor(() => doc.querySelector(".prompt .suggestion-item"), "frame fuzzy picker opens in owner window");
const items = [...doc.querySelectorAll(".prompt .suggestion-item")];
check(items.length === 4 && items.some(item => item.textContent.includes("frame-unnamed")), "navigator omitted unnamed frame");
await click(items.find(item => item.textContent.includes("Marker,padding=50")));
await c.waitFor(() => !doc.querySelector(".prompt"), "frame picker closes");
check(api.getAppState().viewModeEnabled === mode, "navigation changed drawing mode");
check(JSON.stringify(api.getSceneElements()) === scene, "navigation mutated scene");
check(search.value === before, "navigation changed Search text");
check(api.getAppState().selectedElementIds["frame-marker"], "existing navigation did not select target frame");
api.toggleSidebar({ name: "default", tab: "search", force: false });
return { assertions: ["owner-window fuzzy picker contains regular, marker and unnamed frames", "native selection navigates to marker ID", "editing mode, scene and Search text unchanged"] };
});
const note = await env.create("Embeds.md", `![[${drawing.path}|240]]\n\n![[${drawing.path}#^frame=|240]]\n\n![[${drawing.path}#^frame=frame-marker,padding=0|240]]\n\nEnd`);
const readingNote = await env.create("Reading.md", `![[${drawing.path}|240]]\n\nEnd`);
const root = () => [...leaf.view.contentEl.querySelectorAll(leaf.view.getMode?.() === "preview" ? ".markdown-preview-view" : ".markdown-source-view")].find(element => element.getBoundingClientRect().height > 0 && !element.closest(".internal-embed"));
const images = () => [...root()?.querySelectorAll(".excalidraw-embedded-img") || []];
const decoded = image => image.getBoundingClientRect().height > 0 && (image.tagName !== "IMG" || image.complete && image.naturalWidth > 0);
const open = async mode => {
if (leaf.view === view) view.exitFullscreen();
await leaf.setViewState({ type: "empty", state: {} });
await leaf.setViewState({ type: "markdown", state: { file: mode === "preview" ? readingNote.path : note.path, mode, source: false } });
app.workspace.setActiveLeaf(leaf, { focus: true }); win.focus();
if (mode === "source") leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 });
await c.waitFor(() => {
if (mode === "preview" && root()) root().scrollTop = 0;
c.caseTrace = { ...c.caseTrace, format: p.settings.previewImageType, mode, images: images().map(image => ({ tag: image.tagName, bounds: image.getBoundingClientRect().toJSON(), html: image.outerHTML.slice(0, 300) })) };
return images().length === (mode === "preview" ? 1 : 3) && images().every(decoded);
}, mode + " thumbnail images decoded");
};
const ratio = image => {
if (image.tagName === "IMG") return image.naturalWidth / image.naturalHeight;
const svg = image.tagName.toLowerCase() === "svg" ? image : image.querySelector("svg");
return svg.viewBox.baseVal.width / svg.viewBox.baseVal.height;
};
await c.case(`native:frames:${context}:previews`, ["P05"], async () => {
for (const type of ["SVG", "SVGIMG", "PNG"]) {
p.settings.previewImageType = type;
await open("source");
check(Math.abs(ratio(images()[0]) - 200 / 120) < .01, type + " implicit thumbnail crop differs from frame rectangle");
check(ratio(images()[1]) > 2, type + " explicit whole scene retained thumbnail crop");
check(ratio(images()[2]) < 1, type + " explicit marker reference ignored");
await open("preview");
check(Math.abs(ratio(images()[0]) - 200 / 120) < .01, type + " Reading preview ignored thumbnail");
}
await app.fileManager.processFrontMatter(drawing, fm => { fm["excalidraw-thumbnail"] = "Missing frame"; });
await open("source");
check(ratio(images()[0]) > 2, "manual stale YAML did not fall back to full scene");
await app.fileManager.processFrontMatter(drawing, fm => { fm["excalidraw-thumbnail"] = "Main, α"; });
await open("source");
check(Math.abs(ratio(images()[0]) - 200 / 120) < .01, "manual YAML edit did not invalidate cached preview");
const { Component, MarkdownRenderer } = p.ea.obsidian, component = new Component(); component.load();
const hover = doc.body.createDiv({ cls: "hover-popover markdown-preview-view" });
try {
await MarkdownRenderer.render(app, `![[${drawing.path}]]`, hover, note.path, component);
await c.waitFor(() => hover.querySelector(".excalidraw-embedded-img") && decoded(hover.querySelector(".excalidraw-embedded-img")), "hover thumbnail decodes");
check(Math.abs(ratio(hover.querySelector(".excalidraw-embedded-img")) - 200 / 120) < .01, "hover ignored thumbnail");
} finally { component.unload(); hover.remove(); }
const ea = p.ea.getAPI();
try {
const id = await ea.addImage(0, 0, drawing, false, false), element = ea.getElement(id);
check(Math.abs(element.width / element.height - 200 / 120) < .01, "nested drawing ignored thumbnail");
ea.reset();
const svg = await ea.createSVG(drawing.path);
check(svg.viewBox.baseVal.width > 900, "ordinary full-scene export inherited thumbnail crop");
} finally { ea.destroy(); }
return { assertions: ["PNG, SVG image and native SVG use strict implicit frame bounds in Live Preview and Reading", "empty frame means whole scene and explicit marker overrides default", "hover and nested drawing use thumbnail", "ordinary SVG export remains whole scene"] };
});
await c.case(`native:frames:${context}:controls`, ["P02", "P05"], async () => {
p.settings.previewImageType = "SVG"; await open("source");
const drawingBytes = await app.vault.read(drawing);
const frames = () => [...root().querySelectorAll(".excalidraw-embed-controls-frame")];
await c.waitFor(() => frames().length === 3, "frame toolbars bound");
const source = leaf.view.editor.getValue();
const picker = frames()[1].querySelector('[data-excalidraw-embed-action="frame"]');
check(picker?.querySelector(".lucide-scan-eye"), "frame picker does not use scan-eye");
picker.focus(); await click(picker);
await c.waitFor(() => doc.querySelector(".menu .menu-item"), "frame dropdown opens");
const items = [...doc.querySelectorAll(".menu .menu-item")];
check(items.length === 6 && items.some(item => item.textContent.includes("frame-unnamed")), "frame menu omitted defaults or unnamed");
await click(items.find(item => item.textContent.includes("Marker,padding=50")));
const changed = source.replace("#^frame=|240", "#^frame=frame-marker|240");
await c.waitFor(() => leaf.view.editor.getValue() === changed, "frame picker writes exact source occurrence using ID");
leaf.view.editor.cm.focus(); await key("z", "KeyZ", 90, modifier);
await c.waitFor(() => leaf.view.editor.getValue() === source, "frame picker single undo");
await c.waitFor(() => frames()[2]?.querySelector('[data-excalidraw-embed-action="padding"]'), "frame padding control");
frames()[2].querySelector('[data-excalidraw-embed-action="padding"]').focus();
await click(frames()[2].querySelector('[data-excalidraw-embed-action="padding"]'));
await c.waitFor(() => doc.querySelector(".excalidraw-embed-padding-popover input"), "frame padding slider opens");
await key("Home", "Home", 36); await key("ArrowUp", "ArrowUp", 38);
await c.waitFor(() => frames()[2].querySelector(".excalidraw-embed-padding-preview svg"), "frame padding export preview");
await key("Escape", "Escape", 27);
check(leaf.view.editor.getValue() === source, "canceling frame padding changed source");
await leaf.view.save();
check(await app.vault.read(drawing) === drawingBytes, "embed controls mutated destination drawing");
check((await yaml())["excalidraw-thumbnail"] === "Main, α", "embed frame picker changed drawing thumbnail");
return { assertions: ["scan-eye dropdown has defaults and all frames including unnamed", "marker name generates unambiguous ID reference", "only owning occurrence changes with one Undo", "frame padding preview and cancel leave source unchanged", "destination thumbnail unchanged"] };
});
await c.case(`native:frames:${context}:outer-padding`, ["P02","P05"], async () => {
const outer = await env.create("Outer-padding.md", `![[${drawing.path}#^as-image,padding=0|200]]\n\n![[${drawing.path}#^as-image,padding=30|200]]\n\n![[${drawing.path}#^frame=,padding=30|200]]\n\nEnd`);
for(const type of ["SVG","SVGIMG","PNG"]){
p.settings.previewImageType=type;await leaf.setViewState({type:"empty",state:{}});
await leaf.setViewState({type:"markdown",state:{file:outer.path,mode:"source",source:false}});
app.workspace.setActiveLeaf(leaf,{focus:true});leaf.view.editor.setCursor({line:leaf.view.editor.lastLine(),ch:0});
await c.waitFor(()=>images().length===3&&images().every(decoded),"outer padding images decoded");
check(Math.abs(ratio(images()[0])-200/120)<.01,type+" zero padding changed frame bounds");
check(Math.abs(ratio(images()[1])-260/180)<.01,type+" thumbnail outer padding dimensions incorrect: "+ratio(images()[1]));
check(ratio(images()[2])>2,type+" padded whole-scene became a thumbnail");
const image=images()[1], svg=image.querySelector("svg");
const source=svg?"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(svg.outerHTML):image.src;
const pixels=await env.decode(source);
check(pixels.green>0&&pixels.red===0,type+" outer padding revealed the red element outside the frame");
}
return {assertions:["default-thumbnail and explicit whole-scene padding persist independently", "all three render formats add the requested outer dimensions", "frame contents remain clipped; outer padding never reveals neighboring elements"]};
});
await c.case(`native:frames:${context}:scene-images`, ["P02","P05"], () => sceneExercise(c,env,template,drawing,context,modifier));
}
+3 -1
View File
@@ -1,10 +1,12 @@
import { parseCLIJSON } from "./inAppTask.mjs";
/** Exact read-only probe; renderer reloads may erase operation receipts. */
export const nativeReadyCode = 'JSON.stringify((()=>{const p=app.plugins?.plugins?.["obsidian-excalidraw-plugin"];return p?.isReady?{ready:true,runtime:!!p.getCLIRuntime(),mobile:app.isMobile===true}:{ready:false};})())';
/** Mode changes reload the host, briefly removing its CLI command registry. */
export async function waitForNativeReady(cli, { timeoutMs = 60_000, now = () => Date.now(), wait = ms => new Promise(resolve => setTimeout(resolve, ms)), diagnostics = [] } = {}) {
const end = now() + timeoutMs;
for (;;) {
try {
const result = parseCLIJSON(cli("eval", 'code=JSON.stringify((()=>{const p=app.plugins?.plugins?.["obsidian-excalidraw-plugin"];return p?.isReady?{ready:true,runtime:!!p.getCLIRuntime(),mobile:app.isMobile===true}:{ready:false};})())'));
const result = parseCLIJSON(cli("eval", "code=" + nativeReadyCode));
if (result.ready && result.runtime) return result;
} catch (error) {
if (!/Command "eval" not found|Execution context was destroyed|Cannot find context with specified id/.test(error.message)) throw error;
+5 -1
View File
@@ -208,7 +208,11 @@ export async function exerciseInteractionBehavior(c, env, rows, modifier) {
for (const [x, y] of [0.1, 0.3, 0.5, 0.7, 0.9].flatMap((x) =>
[0.15, 0.3, 0.45, 0.6, 0.75, 0.9].map((y) => [x, y]),
)) {
const point = { x: r.x + r.width * x, y: r.y + r.height * y };
// Native contextmenu events use integer coordinates; hit-test that same point.
const point = {
x: Math.round(r.x + r.width * x),
y: Math.round(r.y + r.height * y),
};
const sx = (point.x - r.x) / state.zoom.value - state.scrollX,
sy = (point.y - r.y) / state.zoom.value - state.scrollY;
if (
+235
View File
@@ -0,0 +1,235 @@
/** Maintainer-selected creation, keyboard, companion-failure and video regressions. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
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 issue3052CaseIds = ["main", "popout"].flatMap(context => [
"native:creation-actions-3047:" + context, "native:pen-toggle-3044:" + context,
"native:youtube-fullscreen-3048:" + context, "native:extras-unavailable-3051:" + context,
]).concat("native:png-embed-window-migration:main");
export async function runIssue3052Scenario({ cli, drawingPath }) {
const template = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8");
const tests = [], consoleErrors = [], windowErrors = [];
for (const context of ["main", "popout"]) {
const execute = new Function(`return async function(c,path,context,template){
const env=await (${behaviorEnvironment.toString()})(c,path,{id:context,input:'mouse'},template,${completeConsoleErrors.toString()},${settleBrowserDiagnostics.toString()});
const runCase=c.case.bind(c);c.case=async(...args)=>{c.phase=args[0];return runCase(...args);};
try {await (${exerciseIssues.toString()})(c,env,template);}
catch(error){
try {c.observations={...c.observations,diagnostics:env.diagnostics()};}
catch(diagnosticError){c.observations={...c.observations,diagnosticError:String(diagnosticError)};}
throw error;
}
return {tests:c.tests,consoleErrors:c.externalConsoleErrors||[],windowErrors:env.windowErrors};
}`)();
const result = await runInAppTask({ cli, execute, args: [drawingPath, context, template], timeoutMs: 300000, cleanupMs: 60000,
onRequest: behaviorInputDriver(cli), onProgress: phase => { if (phase) process.stdout.write("Issue fixes: " + phase + "\n"); },
}).catch(error => { error.evidence = [...tests, ...(error.evidence || [])]; throw error; });
tests.push(...result.tests); consoleErrors.push(...result.consoleErrors); windowErrors.push(...result.windowErrors);
}
assert.equal(consoleErrors.length, 0, "Issue scenarios emitted console errors");
assert.equal(splitWindowErrors(windowErrors).unexpected.length, 0, "Issue scenarios emitted window errors");
return { id: "issue-fixes-3052", status: "passed", tests, consoleErrors, windowErrors };
}
async function exerciseIssues(c, env, template) {
c.observations ??= {};
const { doc, win, create, check, click, key, geometry } = env;
let leaf = env.leaf;
let p = env.p;
const context = geometry().requested.id;
const livePlugin = async () => {
if (!app.plugins.plugins["obsidian-excalidraw-plugin"]) await app.plugins.enablePlugin("obsidian-excalidraw-plugin");
await c.waitForCleanup(() => app.plugins.plugins["obsidian-excalidraw-plugin"]?.isReady, "live plugin after reload");
return app.plugins.plugins["obsidian-excalidraw-plugin"];
};
c.defer(livePlugin);
const disablePlugin = async () => {
// Reload tests change registration/settings, not save cancellation. Flush
// the owned edits before retiring the plugin (as deployment does).
const views = app.workspace.getLeavesOfType("excalidraw").map(leaf => leaf.view);
for (const view of views) {
if (view.excalidrawAPI && view.isDirty())
check((await view.saveWithOutcome()).status === "persisted", "pre-reload drawing flush failed");
}
await c.waitFor(() => views.every(view => !view.isSaveInProgress() && !view.isSynchronizing), "pre-reload saves settled");
await app.plugins.disablePlugin("obsidian-excalidraw-plugin");
await c.waitFor(() => views.every(view => !view.excalidrawAPI), "all reload source roots unmounted");
};
const drawing = await create("Issue-fixture.excalidraw.md", template);
await c.waitFor(() => p.isExcalidrawFile(drawing), "issue fixture metadata");
const open = async () => {
await leaf.setViewState({ type: "excalidraw", state: { file: drawing.path } });
app.workspace.setActiveLeaf(leaf, { focus: true });
await c.waitFor(() => leaf.view.excalidrawAPI && !leaf.view.excalidrawAPI.getAppState().isLoading, "issue fixture editor");
return leaf.view;
};
if (context === "main") await c.case("native:png-embed-window-migration:main", ["P05", "P08"], async () => {
const original = p.settings.previewImageType;
const restore = async () => { const current = await livePlugin(); current.settings.previewImageType = original; await current.saveSettings(); };
c.defer(restore);
p.settings.previewImageType = "PNG";
const source = `![[${drawing.path}|180]]\n\n![[${drawing.path}|220]]\n\nFooter\n`;
const note = await create("PNG-migration.md", source), destination = leaf.parent;
const images = () => [...leaf.view.containerEl.querySelectorAll("img.excalidraw-embedded-img")];
const decoded = async label => {
await c.waitFor(() => {
const nodes = images();
c.observations.pngMigration = { label, ownerMain: leaf.view.containerEl.ownerDocument === doc, images: nodes.map(img => ({ source: img.src, width: img.naturalWidth, complete: img.complete })) };
return nodes.length === 2 && nodes.every(img => img.complete && img.naturalWidth > 0);
}, label + " PNG images decode");
};
await leaf.setViewState({ type: "markdown", state: { file: note.path, mode: "source", source: false } });
leaf.view.editor.setCursor({ line: leaf.view.editor.lastLine(), ch: 0 });
await decoded("main");
app.workspace.moveLeafToPopout(leaf);
await c.waitFor(() => leaf.view.containerEl.ownerDocument !== doc, "PNG Markdown view moves to popout");
const popup = leaf.view.containerEl.ownerDocument.defaultView;
const observeError = event => env.windowErrors.push({ context: "png-migration", window: "popout", phase: c.activeCase,
message: event.message, hasError: event.error != null, isTrusted: event.isTrusted, stack: event.error?.stack });
popup.addEventListener("error", observeError);
c.defer(() => { if (!popup.closed) popup.removeEventListener("error", observeError); });
await decoded("popout");
leaf.parent.removeChild(leaf); leaf.setDimension(null); destination.insertChild(-1, leaf);
destination.selectTabIndex(destination.children.indexOf(leaf)); app.workspace.requestResize();
await c.waitFor(() => leaf.view.containerEl.ownerDocument === doc, "PNG Markdown view returns to main");
await decoded("returned main");
check(await app.vault.read(note) === source, "PNG window migration changed Markdown source");
await restore();
return { assertions: ["two PNG embeds decode in main", "decoded PNG embeds survive actual main-to-popout and popout-to-main Markdown migration", "Markdown source remains unchanged"] };
});
await c.case("native:pen-toggle-3044:" + context, ["P03", "P08"], async () => {
const view = await open(), api = view.excalidrawAPI;
const root = view.containerEl.querySelector(".excalidraw"); root.focus();
api.setActiveTool({ type: "selection" });
await key("p", "KeyP", 80); await c.waitFor(() => api.getAppState().activeTool.type === "freedraw", "P selects pen");
const penKey = { key: "p", code: "KeyP", windowsVirtualKeyCode: 80 };
await env.input("Input.dispatchKeyEvent", { type: "keyDown", ...penKey });
try {
await c.waitFor(() => api.getAppState().activeTool.type === "selection", "second P selects mouse");
await env.input("Input.dispatchKeyEvent", { type: "keyDown", ...penKey, autoRepeat: true });
} finally {
await env.input("Input.dispatchKeyEvent", { type: "keyUp", ...penKey });
}
check(api.getAppState().activeTool.type === "selection", "holding the second P returned to pen");
await key("p", "KeyP", 80);
await c.waitFor(() => api.getAppState().activeTool.type === "freedraw", "fresh P reenters pen");
const input = root.createEl("input"); c.defer(() => input.remove()); input.focus();
// The shortcut helper deliberately omits printable text. A real typing
// keyDown needs text as well as key/code to exercise the exclusion rule.
await env.input("Input.dispatchKeyEvent", { type: "keyDown", key: "p", code: "KeyP", windowsVirtualKeyCode: 80, text: "p" });
await env.input("Input.dispatchKeyEvent", { type: "keyUp", key: "p", code: "KeyP", windowsVirtualKeyCode: 80 });
c.observations.penInput = { value: input.value, tool: api.getAppState().activeTool.type, focused: doc.activeElement === input };
check(input.value === "p" && api.getAppState().activeTool.type === "freedraw", "P consumed text input");
input.remove(); root.focus(); await key("v", "KeyV", 86);
check(api.getAppState().activeTool.type === "selection", "existing selection shortcut changed");
return { assertions: ["native P enters pen and second P selects mouse", "holding the second P keeps selection after the API commits", "fresh P reenters pen", "text input retains P", "V still selects mouse", "owning main/popout keyboard"] };
});
await c.case("native:youtube-fullscreen-3048:" + context, ["P03", "P08"], async () => {
const view = await open(), api = view.excalidrawAPI;
const elements = view.packages.excalidrawLib.convertToExcalidrawElements([{ type: "embeddable", x: 50, y: 50, width: 480, height: 270, link: "https://www.youtube.com/watch?v=abcdefghijk" }]);
api.updateScene({ elements, appState: { scrollX: 0, scrollY: 0, zoom: { value: 0.75 }, activeEmbeddable: { element: elements[0], state: "active" } }, captureUpdate: "NEVER" });
await c.waitFor(() => view.containerEl.querySelector("iframe.excalidraw__embeddable"), "YouTube iframe transport");
check(!view.containerEl.querySelector("webview.excalidraw__embeddable"), "YouTube still uses guest webview fullscreen");
const iframe = view.containerEl.querySelector("iframe.excalidraw__embeddable");
check(iframe.src.startsWith("https://releases.obsidian.md/youtube?"), "YouTube wrapper routing changed");
// Replace the external player with a local fixture; exercise the actual
// Electron fullscreen boundary without requiring YouTube/network service.
iframe.srcdoc = "<!doctype html><html><body style='margin:0;background:#183048'>Offline fullscreen player<button id='exit' style='position:absolute;left:24px;top:24px'>Exit fullscreen</button></body></html>";
await c.waitFor(() => iframe.contentDocument?.querySelector("#exit"), "offline fullscreen fixture");
const exit = iframe.contentDocument.querySelector("#exit");
exit.addEventListener("click", () => { void iframe.contentDocument.exitFullscreen(); });
const trigger = doc.body.createEl("button", { text: "Test video fullscreen" });
trigger.setCssStyles({ position: "fixed", left: "100px", top: "100px", zIndex: "100000" });
c.defer(async () => { trigger.remove(); if (doc.fullscreenElement) await doc.exitFullscreen(); });
trigger.onClickEvent(() => { void iframe.contentDocument.documentElement.requestFullscreen(); });
await click(trigger); await c.waitFor(() => doc.fullscreenElement === iframe, "video owns fullscreen top layer");
const r = iframe.getBoundingClientRect();
c.observations.fullscreen = { bounds: r.toJSON(), viewport: { width: win.innerWidth, height: win.innerHeight } };
check(Math.abs(r.width - win.innerWidth) < 2 && Math.abs(r.height - win.innerHeight) < 2 && Math.abs(r.x) < 2 && Math.abs(r.y) < 2, "video did not fill owning window");
// CDP Escape is a renderer event, not Chromium's reserved browser shortcut
// (also reproduced in an unmodified browser). Exercise the player's own
// trusted exit control instead; physical Escape remains a manual check.
const b = exit.getBoundingClientRect(), x = b.x + b.width / 2, y = b.y + b.height / 2;
check(doc.elementFromPoint(x, y) === iframe && exit.contains(iframe.contentDocument.elementFromPoint(x, y)), "fullscreen exit target is covered");
for (const type of ["mousePressed", "mouseReleased"]) await env.input("Input.dispatchMouseEvent", { type, x, y, button: "left", buttons: type === "mousePressed" ? 1 : 0, clickCount: 1 });
await c.waitFor(() => !doc.fullscreenElement, "player exits fullscreen");
check(iframe.isConnected && iframe.getBoundingClientRect().width < win.innerWidth, "video embed identity/geometry not restored");
trigger.remove();
// Unlike the cross-origin provider, this same-origin fixture lets Obsidian
// capture a child element lacking its DOM extensions when opening a modal.
// Retire the player and restore native editor focus before the next case.
api.updateScene({ elements: [], captureUpdate: "NEVER" });
await c.waitFor(() => !iframe.isConnected, "offline player teardown");
view.containerEl.querySelector(".excalidraw").focus();
check(typeof doc.activeElement.instanceOf === "function", "editor focus not restored after local player");
return { assertions: ["YouTube iframe transport and existing wrapper URL", "trusted Electron HTML fullscreen fills owning window", "trusted player exit restores the same embedded player"], bounds: r.toJSON(), externalPlayback: "not exercised; offline fixture", physicalEscape: "separate manual check; CDP does not invoke the browser shortcut" };
});
await c.case("native:extras-unavailable-3051:" + context, ["P01", "P03"], async () => {
const extras = app.plugins.plugins["excalidraw-extras"], original = extras.api;
c.defer(() => { extras.api = original; });
for (const api of [undefined, {}, { versions: {} }]) {
extras.api = api;
if (api === undefined && context === "main") {
const retired = leaf.view;
await disablePlugin();
await c.waitFor(() => !retired.excalidrawAPI, "late-load source root unmounted");
if (!leaf.view) env.owned.delete(leaf);
leaf = app.workspace.getLeaf("tab"); env.owned.add(leaf);
await leaf.setViewState({ type: "markdown", state: { file: drawing.path } });
check(leaf.view.getViewType() === "markdown", "late-load fixture did not start as Markdown");
c.observations.lateLoad = { before: leaf.view.getViewType(), layoutReady: app.workspace.layoutReady, extrasApiMissing: true };
p = await livePlugin();
await c.waitFor(() => leaf.view.excalidrawAPI && !leaf.view.excalidrawAPI.getAppState().isLoading, "late load restores drawing from Markdown");
c.observations.lateLoad.after = { type: leaf.view.getViewType(), editorReady: true };
}
check(await p.extrasGateway.getMermaid() === null, "unavailable companion did not cancel gracefully");
const view = await open(); check(p.isReady && !!view.excalidrawAPI, "optional Extras API blocked drawing mode");
}
extras.api = original;
check(p.extrasGateway.getAPI() === original, "updated companion API could not recover");
return { assertions: ["absent/incomplete optional API produces cancellation without an exception", "drawings remain editable", ...(context === "main" ? ["main-window late plugin load restores a fallback Markdown drawing"] : []), "restored companion becomes available"], reporterCause: "reporter links failure to Lazy Loader's 20-second delay; exact third-party interaction remains unconfirmed" };
});
await c.case("native:creation-actions-3047:" + context, ["P01", "P02", "P08"], async () => {
// The editor fixture is deliberately mutated by the video case. Keep the
// creation template immutable so autosave cannot change this expectation.
const creationTemplate = await create("Creation-template.excalidraw.md", template);
await c.waitFor(() => p.isExcalidrawFile(creationTemplate), "creation template metadata");
const original = JSON.parse(JSON.stringify(p.settings));
c.defer(async () => {
const current = await livePlugin();
current.settings = original; await current.saveSettings(); current.drawingCreationUI.refresh();
});
p.settings.showRibbonIcon = false; p.settings.showNewDrawingInEmptyTab = true;
p.settings.folder = env.prefix; p.settings.templateFilePath = creationTemplate.path; p.settings.drawingFilenamePrefix = "New-action-";
p.settings.__issue3052Unknown = { preserved: true };
await p.saveSettings();
await leaf.setViewState({ type: "empty", state: {} }); app.workspace.setActiveLeaf(leaf, { focus: true });
p.drawingCreationUI.refresh();
await c.waitFor(() => leaf.view.containerEl.querySelector(".excalidraw-new-drawing"), "new-tab drawing action");
const list = leaf.view.containerEl.querySelector(".empty-state-action-list"), builtins = [...list.children].filter(el => !el.hasClass("excalidraw-new-drawing"));
check(builtins.length > 0, "empty-tab core actions disappeared");
check(p.drawingCreationUI.ribbon.hasClass("excalidraw-display-none"), "ribbon preference ignored");
await click(list.querySelector(".excalidraw-new-drawing"));
await c.waitFor(() => leaf.view.excalidrawAPI && leaf.view.file?.path.startsWith(env.prefix + "/New-action-"), "creation uses configured destination and format");
await env.ready(leaf);
check(leaf.view.file.extension === "md" && leaf.view.excalidrawAPI.getSceneElements().length > 0, "creation ignored template or file format");
check(await app.vault.read(creationTemplate) === template, "creation modified its template");
if (context === "main") {
const retired = leaf.view;
await disablePlugin();
await c.waitFor(() => !retired.excalidrawAPI, "creation source root unmounted");
if (!leaf.view) env.owned.delete(leaf);
const current = await livePlugin();
check(!current.settings.showRibbonIcon && current.settings.showNewDrawingInEmptyTab && current.settings.__issue3052Unknown?.preserved, "reload lost creation preferences or unknown settings");
const data = JSON.parse(await app.vault.adapter.read(app.vault.configDir + "/plugins/obsidian-excalidraw-plugin/data.json"));
check(data.showNewDrawingInEmptyTab && data.showRibbonIcon === false && data.__issue3052Unknown.preserved, "disk settings differ after reload");
}
return { assertions: ["empty-tab action retains core actions", "independent ribbon visibility", "configured destination, format and template", ...(context === "main" ? ["nondefault and unknown settings survive actual plugin reload and disk persistence"] : [])] };
});
}
+8
View File
@@ -0,0 +1,8 @@
/** CDP needs explicit browser editing commands for macOS shortcuts, as Playwright's Chromium driver does. */
export function nativeKeyboardInput(params, platform = process.platform) {
if (platform !== "darwin" || !["keyDown", "rawKeyDown"].includes(params.type) || params.commands) return params;
const command = params.modifiers === 4 && params.code === "KeyA" ? "selectAll"
: params.modifiers === 4 && params.code === "KeyZ" ? "undo"
: params.modifiers === 12 && params.code === "KeyZ" ? "redo" : null;
return command ? { ...params, commands: [command] } : params;
}
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import test from "node:test";
import { nativeKeyboardInput } from "./nativeKeyboard.mjs";
test("macOS native editing shortcuts carry browser commands while preserving trusted key parameters", () => {
for (const [code, modifiers, command] of [["KeyA", 4, "selectAll"], ["KeyZ", 4, "undo"], ["KeyZ", 12, "redo"]]) {
for (const type of ["keyDown", "rawKeyDown"]) {
const key = { type, code, key: code.slice(-1).toLowerCase(), modifiers, windowsVirtualKeyCode: code.charCodeAt(3) };
assert.deepEqual(nativeKeyboardInput(key, "darwin"), { ...key, commands: [command] });
assert.equal(Object.hasOwn(key, "commands"), false);
}
}
});
test("native keyboard transport preserves releases, app shortcuts, other platforms and explicit commands", () => {
for (const key of [{ type: "keyUp", code: "KeyA", modifiers: 4 }, { type: "keyDown", code: "KeyS", modifiers: 4 },
{ type: "keyDown", code: "KeyA", modifiers: 0 }, { type: "keyDown", code: "KeyA", modifiers: 5 },
{ type: "keyDown", code: "KeyA", modifiers: 4, commands: ["custom"] }]) assert.equal(nativeKeyboardInput(key, "darwin"), key);
const key = { type: "keyDown", code: "KeyA", modifiers: 2 };
for (const platform of ["win32", "linux"]) assert.equal(nativeKeyboardInput(key, platform), key);
});
+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 };
}
+3
View File
@@ -44,6 +44,9 @@ async function exerciseStability(c,path,fixture,cycles){
const observation={cycle};c.observations.push(observation);
let anchor;app.workspace.iterateAllLeaves(l=>{if(!anchor&&l.getRoot()===app.workspace.rootSplit)anchor=l;});
check(anchor,'No main-window anchor');app.workspace.setActiveLeaf(anchor,{focus:true});
// Vault persistence completes before Obsidian republishes frontmatter.
// The default-view router requires that metadata on every fresh open.
await c.waitFor(()=>!!app.metadataCache.getCache(path)?.frontmatter?.['excalidraw-plugin'],'large saved fixture frontmatter before open');
leaf=app.workspace.getLeaf('tab');await leaf.openFile(file);
observation.opened=loadState();
try{await c.waitFor(()=>leaf.view.excalidrawAPI&&leaf.view.isLoaded&&!leaf.view.semaphores.justLoaded&&!leaf.view.isClosingOrMigrating(),'large scene first commit',60000);}catch(error){observation.failed=loadState();throw error;}
+9 -2
View File
@@ -24,7 +24,7 @@ test("failed stability loading retires the owned leaf before deleting its file",
operations = [];
let detached = false,
closed = false,
removed = false;
removed = false, frontmatter;
const file = { path: "__excalidraw_cli_smoke_owned_stability.excalidraw.md" };
const doc = { querySelectorAll: () => [{}] };
const originalView = {
@@ -40,7 +40,7 @@ test("failed stability loading retires the owned leaf before deleting its file",
const leaf = {
id: "owned",
view: originalView,
async openFile() {},
async openFile() { assert.ok(frontmatter?.["excalidraw-plugin"], "Opening before metadata is ready can select Markdown mode"); },
async setViewState(state) {
assert.equal(state.type, "empty");
closed = true;
@@ -63,6 +63,7 @@ test("failed stability loading retires the owned leaf before deleting its file",
},
root = {};
const app = {
metadataCache: { getCache: () => ({ frontmatter }) },
plugins: {
plugins: {
"obsidian-excalidraw-plugin": { isExcalidrawFile: () => true },
@@ -110,6 +111,12 @@ test("failed stability loading retires the owned leaf before deleting its file",
assert.ok(predicate());
return;
}
if (label === "large saved fixture frontmatter before open") {
assert.equal(!!predicate(), false);
frontmatter = { "excalidraw-plugin": "parsed" };
assert.equal(predicate(), true);
return;
}
assert.equal(label, "large scene first commit");
throw Error("owned first commit failure");
},
+23 -12
View File
@@ -155,17 +155,28 @@ async function probePaint(c, path) {
["P03", "P09"],
async () => {
const converted = await converter.parseMermaidToExcalidraw(definition);
const image = converted.elements.find((e) => e.type === "image");
const dataURL = converted.files?.[image?.fileId]?.dataURL;
requireValue(
dataURL?.startsWith("data:image/svg+xml;base64,"),
name + " did not return an SVG image",
);
const svg = new TextDecoder().decode(
Uint8Array.from(atob(dataURL.split(",")[1]), (ch) =>
ch.charCodeAt(0),
),
);
const nativeOutput = ["gantt", "timeline", "quadrant"].includes(name);
let svg;
if (nativeOutput) {
requireValue(converted.elements.length > 0 && converted.elements.every((e) => e.type !== "image"), name + " lost native converter output");
// The paint case above reopens the drawing and retires its original view.
const currentView = app.workspace.getLeavesOfType("excalidraw").find((leaf) => leaf.view.file?.path === path)?.view;
requireValue(currentView?.excalidrawAPI, "Missing reopened SVG paint target");
const lib = currentView.packages.excalidrawLib;
const elements = lib.convertToExcalidrawElements(converted.elements);
const exported = await lib.exportToSvg({ elements, files: converted.files || {}, appState: currentView.excalidrawAPI.getAppState() });
svg = exported.outerHTML;
} else {
const image = converted.elements.find((e) => e.type === "image");
const dataURL = converted.files?.[image?.fileId]?.dataURL;
requireValue(
dataURL?.startsWith("data:image/svg+xml;base64,"),
name + " did not return an SVG image",
);
svg = new TextDecoder().decode(
Uint8Array.from(atob(dataURL.split(",")[1]), (ch) => ch.charCodeAt(0)),
);
}
const bench = plugin.ea.getAPI();
try {
requireValue(bench.importSVG(svg), name + " SVG import failed");
@@ -180,7 +191,7 @@ async function probePaint(c, path) {
requireValue(expected.every(label => labels.includes(label)), name + " lost native SVG labels");
return {
assertions: [
"real Extras returns SVG-backed image",
nativeOutput ? "real Extras editable output exports as SVG" : "real Extras returns SVG-backed image",
"actual SVG imports through EA",
"nonempty native geometry without an image fallback",
"expected SVG labels retained as editable text",
+3 -2
View File
@@ -107,7 +107,8 @@ async function exerciseTextSave(c, env, modifier) {
await enter();
const beforeShift = exports.length;
await key("s", "KeyS", 83, modifier | 8);
await c.waitFor(() => exports.length > beforeShift && exports.at(-1) === "closed" && !view.containerEl.querySelector("textarea.excalidraw-wysiwyg"), "Shift+S retains its standalone save route");
check(exports.length === beforeShift && doc.activeElement?.matches("textarea.excalidraw-wysiwyg"), "Shift+S must leave text editing intact without standalone Save As");
await key("Escape", "Escape", 27);
}
await key("s", "KeyS", 83, modifier);
await c.waitFor(async () => !view.isDirty() && !view.isSaveInProgress() &&
@@ -117,6 +118,6 @@ async function exerciseTextSave(c, env, modifier) {
check(restored?.rawText === source && Boolean(restored.containerId) === bound, "saved text/binding lost on reopen");
variants.push({ mode, bound, forcedDiskWrite: true, undoRedo: true, reopened: true });
}
return { assertions: ["trusted Ctrl/Cmd+S submits pending raw/parsed and bound/plain text", "forced physical write with autosave disabled", "no standalone dialog or download", "Shift+S retains its standalone save route", "undo/redo and canvas save", "source and binding survive reopen"], variants };
return { assertions: ["trusted Ctrl/Cmd+S submits pending raw/parsed and bound/plain text", "forced physical write with autosave disabled", "no standalone dialog or download", "Shift+S is blocked without ending text editing", "undo/redo and canvas save", "source and binding survive reopen"], variants };
});
}
+33
View File
@@ -10,6 +10,10 @@ import { obsidianCliExecutable, spawnNativeSync } from "./processTools.mjs";
import { runTextUndoScenario } from "./textUndo.mjs";
import { runNativeCLIScenario } from "./nativeCLI.mjs";
import { runEmbedRecoveryScenario } from "./embedRecovery.mjs";
import { runEmbedControlsScenario } from "./embedControls.mjs";
import { runEmbedRegressionsScenario } from "./embedRegressions.mjs";
import { runEmbedReliabilityScenario } from "./embedReliability.mjs";
import { runFrameSemanticsScenario } from "./frameSemantics.mjs";
import { runGroupedLinkClickScenario } from "./groupedLinkClick.mjs";
import { runLatexInputScenario } from "./latexInput.mjs";
import { runImageGeometryScenario } from "./imageGeometry.mjs";
@@ -24,6 +28,8 @@ import { runSVGEntryPointsScenario } from "./svgEntryPoints.mjs";
import { runLucideScenario } from "./lucideIcons.mjs";
import { runWorkflowFixesScenario } from "./workflowFixes.mjs";
import { runWorkflowBundleScenario } from "./workflowBundle.mjs";
import { runAIAndEmbedsScenario } from "./aiAndEmbeds.mjs";
import { runIssue3052Scenario } from "./issue3052.mjs";
import { runTextSaveShortcutScenario } from "./textSaveShortcut.mjs";
import { runCodeCardScenario } from "./codeCards.mjs";
import { runKplexOntologyScenario } from "./kplexOntology.mjs";
@@ -36,6 +42,7 @@ 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 { runPDFImportScenario } from "./pdfImport.mjs";
import { runDeviceMatrix } from "./devices.mjs";
import { deviceProfiles, breakpointProfiles } from "./deviceProfiles.mjs";
@@ -73,6 +80,7 @@ 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 migrationComparison = process.argv.includes("--migration-comparison");
const markdownMigrationControl = process.argv.includes("--markdown-migration-control");
if (fullProfile && migrationComparison)
@@ -87,6 +95,10 @@ const textUndo = coreScenarios || process.argv.includes("--text-undo");
const stability = coreScenarios || profile === "soak" || process.argv.includes("--stability");
const nativeCLI = coreScenarios || process.argv.includes("--native-cli");
const embedRecovery = coreScenarios || process.argv.includes("--embed-recovery");
const embedControls = coreScenarios || process.argv.includes("--embed-controls");
const embedRegressions = coreScenarios || process.argv.includes("--embed-regressions");
const embedReliability = coreScenarios || process.argv.includes("--embed-reliability");
const frameSemantics = coreScenarios || process.argv.includes("--frame-semantics");
const groupedLinkClick =
coreScenarios || process.argv.includes("--grouped-link-click");
const latexInput = coreScenarios || process.argv.includes("--latex-input");
@@ -106,6 +118,9 @@ const svgEntryPoints = process.argv.includes("--svg-entry-points");
const lucide = coreScenarios || process.argv.includes("--lucide");
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");
const issue3052 = coreScenarios || process.argv.includes("--issue-3052");
const minimapOnly = process.argv.includes("--minimap");
const textSaveShortcut = workflowBundle || process.argv.includes("--text-save-shortcut");
const codeCards = workflowBundle || process.argv.includes("--code-cards");
const kplexOntology = coreScenarios || profile === "devices" || process.argv.includes("--kplex-ontology");
@@ -145,6 +160,7 @@ const flags = [
"--prepare-only",
"--behavior-matrix",
"--lifecycle",
"--runtime-compaction",
"--migration-comparison",
"--markdown-migration-control",
"--extras-services",
@@ -152,6 +168,8 @@ const flags = [
"--data-integrity",
"--workflow-fixes",
"--workflow-bundle",
"--issue-3052",
"--minimap",
"--text-save-shortcut",
"--code-cards",
"--kplex-ontology",
@@ -160,6 +178,11 @@ const flags = [
"--stability",
"--native-cli",
"--embed-recovery",
"--ai-and-embeds",
"--embed-controls",
"--embed-regressions",
"--embed-reliability",
"--frame-semantics",
"--grouped-link-click",
"--latex-input",
"--latex-preview",
@@ -311,6 +334,7 @@ try {
}),
]
: []),
...(runtimeCompaction ? [runRuntimeCompactionScenario] : []),
...(lifecycle ? [runLifecycleScenario] : []),
...(migrationComparison ? [
context => runLifecycleScenario(context),
@@ -350,6 +374,10 @@ try {
...(textUndo ? [runTextUndoScenario] : []),
...(nativeCLI ? [runNativeCLIScenario] : []),
...(embedRecovery ? [runEmbedRecoveryScenario] : []),
...(embedControls ? [runEmbedControlsScenario] : []),
...(embedRegressions ? [runEmbedRegressionsScenario] : []),
...(embedReliability ? [runEmbedReliabilityScenario] : []),
...(frameSemantics ? [runFrameSemanticsScenario] : []),
...(groupedLinkClick ? [runGroupedLinkClickScenario] : []),
...(latexInput ? [runLatexInputScenario] : []),
...(latexPreview
@@ -371,6 +399,9 @@ try {
]
: []),
...(workflowBundle ? [runWorkflowBundleScenario] : []),
...(aiAndEmbeds ? [runAIAndEmbedsScenario] : []),
...(issue3052 ? [runIssue3052Scenario] : []),
...(minimapOnly ? [context => runWorkflowBundleScenario({ ...context, minimapOnly: true })] : []),
...(textSaveShortcut ? [runTextSaveShortcutScenario] : []),
...(codeCards ? [runCodeCardScenario] : []),
...(kplexOntology ? [runKplexOntologyScenario] : []),
@@ -413,6 +444,8 @@ try {
featureWorkflows: fullProfile || profile === "devices",
featureCases:focusedCases,
kplexOntology,
embedControls,
frameSemantics,
});
deviceReport.source = combination?.manifests.plugin || source;
deviceReport.artifacts = report.artifacts.installedHashes;
+105 -14
View File
@@ -2,22 +2,34 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { runInAppTask } from "./inAppTask.mjs";
import { settleBrowserDiagnostics } from "./browserDiagnostics.mjs";
export const workflowBundleCaseIds = ["native:workflow-markdown-extraction-3009", "native:workflow-zen-controls-3000"];
export const workflowBundleCaseIds = ["native:workflow-markdown-extraction-3009", "native:workflow-zen-controls-3000", "native:upstream-minimap-483"];
export async function runWorkflowBundleScenario({ cli, drawingPath }) {
export async function runWorkflowBundleScenario({ cli, drawingPath, minimapOnly = false }) {
assert.ok(drawingPath.startsWith("__excalidraw_cli_smoke_"));
const prefix = drawingPath.replace(/\.(excalidraw\.md|excalidraw|md)$/, "") + "_bundle";
const fixture = readFileSync(new URL("../../../tests/vault/Drawings/Uncompressed.excalidraw.md", import.meta.url), "utf8");
const result = await runInAppTask({ cli, execute: exerciseWorkflows, args: [prefix, fixture], timeoutMs: 180000, cleanupMs: 60000 });
return { id: "workflow-bundle-3030", status: "passed", ...result };
const execute = new Function(`return async function(c,prefix,fixture,minimapOnly){
if(minimapOnly){const runCase=c.case.bind(c);c.case=async(id,...args)=>id==='native:upstream-minimap-483'?runCase(id,...args):undefined;}
return (${exerciseWorkflows.toString()})(c,prefix,fixture,${settleBrowserDiagnostics.toString()});}`)();
const result = await runInAppTask({ cli, execute, args: [prefix, fixture, minimapOnly], timeoutMs: 300000, cleanupMs: 60000 });
return { id: minimapOnly ? "minimap-483" : "workflow-bundle-3030", status: "passed", ...result };
}
async function exerciseWorkflows(c, prefix, fixture) {
async function exerciseWorkflows(c, prefix, fixture, settleBrowserDiagnostics) {
const plugin = app.plugins.plugins["obsidian-excalidraw-plugin"];
const mainDocument = app.workspace.containerEl.ownerDocument;
const previous = app.workspace.activeLeaf, leaves = new Set(), tabs = new Set(), rootFiles = new Set();
const attachmentFolderPath = app.vault.getConfig("attachmentFolderPath");
const windowEvents = [], observedWindows = new Map();
const observeWindow = win => {
if (observedWindows.has(win)) return;
const listener = event => windowEvents.push({ message: event.message, at: Date.now() });
win.addEventListener("error", listener); observedWindows.set(win, listener);
};
observeWindow(mainDocument.defaultView);
c.defer(() => { for (const [win, listener] of observedWindows) if (!win.closed) win.removeEventListener("error", listener); });
c.observations = {};
const check = (condition, message) => { if (!condition) throw Error(message); };
const closeTab = async (tab, view) => {
@@ -64,6 +76,7 @@ async function exerciseWorkflows(c, prefix, fixture) {
const leaf = popout ? app.workspace.openPopoutLeaf() : app.workspace.getLeaf("tab"); leaves.add(leaf);
if (popout) await c.waitFor(() => leaf.view.containerEl.ownerDocument !== mainDocument, "empty workflow popout migration");
await leaf.openFile(file); await ready(leaf);
observeWindow(leaf.view.ownerWindow);
app.workspace.setActiveLeaf(leaf, { focus: true }); leaf.view.ownerWindow.focus();
return leaf;
};
@@ -87,11 +100,18 @@ async function exerciseWorkflows(c, prefix, fixture) {
await open(prefix + "/Other.excalidraw.md");
app.workspace.setActiveLeaf(leaf, { focus: true });
}
await c.waitFor(() => leaf.view === view && view.excalidrawData?.file === view.file && !view.isSaveInProgress() && !view.isSynchronizing, "extraction owner readiness");
const panel = await plugin.openSidepanel(false), beforeTabs = new Set(panel.tabs.keys());
await view.openMarkdownImageEditor();
const tab = [...panel.tabs.values()].find(tab => !beforeTabs.has(tab.id));
check(tab, "owned extraction editor tab missing"); const ownedTab = { tab, view }; tabs.add(ownedTab);
let tab;
await c.waitFor(() => {
tab = [...panel.tabs.values()].find(tab => !beforeTabs.has(tab.id));
c.observations.extractionOpen = { name: options.name, owner: view.file?.path, leafCurrent: leaf.view === view, dataFile: view.excalidrawData?.file?.path, api: !!view.excalidrawAPI, saving: view.isSaveInProgress(), synchronizing: view.isSynchronizing, panelCurrent: panel.leaf.view === panel, tabs: [...panel.tabs.values()].map(tab => ({ id: tab.id, owner: tab.contentEl.querySelector(".excalidraw-markdown-image-editor__owner")?.getAttribute("title") })) };
return tab;
}, "owned extraction editor tab");
const ownedTab = { tab, view }; tabs.add(ownedTab);
await c.waitFor(() => tab.contentEl.querySelector(".excalidraw-markdown-image-editor__markdown-view .cm-content"), "extraction source editor");
check(tab.contentEl.querySelector(".excalidraw-markdown-image-editor__owner")?.getAttribute("title")?.includes(view.file.path), "extraction editor attached to a different drawing");
const content = tab.contentEl.querySelector(".excalidraw-markdown-image-editor__markdown-view .cm-content");
const cm = content.cmTile?.view ?? content.cmView?.rootView?.view;
cm.dispatch({ changes: { from: 0, to: cm.state.doc.length, insert: markdown } });
@@ -104,9 +124,16 @@ async function exerciseWorkflows(c, prefix, fixture) {
// reattaches when another drawing becomes active, so arrange both drawings
// before opening this editor rather than invalidating it mid-operation.
tab.contentEl.querySelector("button .lucide-file-output").closest("button").click();
const doc = tab.contentEl.ownerDocument;
await c.waitFor(() => doc.querySelector(".excalidraw-file-and-folder-selector"), "extraction destination dialog");
const modal = doc.querySelector(".excalidraw-file-and-folder-selector"), inputs = modal.querySelectorAll("input");
// Obsidian Modal uses the active document; the shared sidepanel and its
// selected popout drawing can belong to different documents.
let modal;
await c.waitFor(() => {
const doc = activeDocument;
check(doc === tab.contentEl.ownerDocument || doc === view.ownerDocument, "Extraction modal targeted an unrelated document");
modal = doc.querySelector(".excalidraw-file-and-folder-selector");
return modal;
}, "extraction destination dialog");
const doc = modal.ownerDocument, inputs = modal.querySelectorAll("input");
const normalize = path => path.replace(/^\/+|\/+$/g, "");
const expectedFolder = normalize(view.file.parent.path), actualFolder = normalize(inputs[0].value);
c.observations.extraction = [...(c.observations.extraction || []), { name: options.name, expectedFolder, actualFolder }];
@@ -142,7 +169,7 @@ async function exerciseWorkflows(c, prefix, fixture) {
return { assertions: ["root/nested/Unicode owning folder defaults", "two simultaneous drawings retain the selected image's owner", "explicit selection and cancellation", "unique names and original content preserved", "external source links persist through save/reopen", "main/popout extraction"], variants };
});
await c.case("native:workflow-zen-controls-3000", ["P03", "P08"], async () => {
const variants = [];
const variants = [], zoomIdle = [];
for (const popout of [false, true]) {
const leaf = await open(prefix + "/Zen-" + popout + ".excalidraw.md", popout), view = leaf.view, api = view.excalidrawAPI;
const doc = view.ownerDocument, win = view.ownerWindow;
@@ -160,7 +187,7 @@ async function exerciseWorkflows(c, prefix, fixture) {
view.contentEl.setCssProps({ width: width + "px", "max-width": "100%" });
api.updateScene({ appState: { zenModeEnabled: true, zoom: { value: 1.7 } }, captureUpdate: "NEVER" });
await c.waitFor(() => api.getAppState().zenModeEnabled && view.containerEl.querySelector(".disable-zen-mode--visible"), "Zen exit control");
const exit = view.containerEl.querySelector(".disable-zen-mode--visible"), zoom = view.containerEl.querySelector(".reset-zoom-button");
const exit = view.containerEl.querySelector(".disable-zen-mode--visible"), zoom = view.containerEl.querySelector(".zoom-menu-trigger, .reset-zoom-button");
check(zoom, "Zen zoom indicator missing");
await c.waitFor(() => win.getComputedStyle(exit).visibility === "visible" && Number(win.getComputedStyle(exit).opacity) > 0.99, "Zen exit transition completes");
const a = exit.getBoundingClientRect(), b = zoom.getBoundingClientRect();
@@ -177,7 +204,12 @@ async function exerciseWorkflows(c, prefix, fixture) {
doc.elementFromPoint(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2)?.closest("button") === button,
"Zen control is clipped or covered");
}
zoom.click(); await c.waitFor(() => api.getAppState().zoom.value === 1, "Zen zoom action");
zoom.click();
if (zoom.classList.contains("zoom-menu-trigger")) {
await c.waitFor(() => doc.querySelector('[data-testid="zoom-menu-resetZoom"]'), "Zen zoom menu");
doc.querySelector('[data-testid="zoom-menu-resetZoom"]').click();
}
await c.waitFor(() => api.getAppState().zoom.value === 1, "Zen zoom action");
exit.click(); await c.waitFor(() => !api.getAppState().zenModeEnabled, "Zen exit action");
variants.push(record);
}
@@ -189,9 +221,68 @@ async function exerciseWorkflows(c, prefix, fixture) {
view.contentEl.setCssProps({ width: originalWidth, "max-width": originalMaxWidth });
api.updateScene({ appState: { zenModeEnabled: false }, captureUpdate: "NEVER" });
}
// Restoring Electron zoom schedules native status/resize work. Keep its
// owning popout alive until that work is quiet before destroying it.
const idle = await settleBrowserDiagnostics(win, windowEvents, "workflow restored zoom");
zoomIdle.push(idle); check(idle.status === "passed", "Restored workflow zoom did not settle");
await closeLeaf(leaf);
}
return { assertions: ["Zen exit and zoom indicator do not intersect", "both controls remain inside the editor and uncovered", "zoom and exit actions activate repeatedly", "LTR/RTL wide/narrow panes and UI scale", "main/popout document ownership"], variants };
return { assertions: ["Zen exit and zoom indicator do not intersect", "both controls remain inside the editor and uncovered", "zoom and exit actions activate repeatedly", "LTR/RTL wide/narrow panes and UI scale", "main/popout document ownership", "restored native zoom settles before popout teardown"], variants, zoomIdle };
});
await c.case("native:upstream-minimap-483", ["P01", "P03", "P08"], async () => {
const variants = [], oldLimits = { min: plugin.settings.zoomMin, max: plugin.settings.zoomMax, mode: plugin.settings.desktopUIMode };
try {
for (const popout of [false, true]) {
const leaf = await open(prefix + "/Minimap-" + popout + ".excalidraw.md", popout);
const view = leaf.view, api = view.excalidrawAPI, doc = view.ownerDocument, win = view.ownerWindow;
for (const mode of ["full", "compact", "tray"]) {
plugin.settings.desktopUIMode = mode;
view.setUIMode(mode);
api.updateScene({ appState: { zenModeEnabled: false, minimapEnabled: false, zoom: { value: 1 } }, captureUpdate: "NEVER" });
await c.waitFor(() => view.containerEl.querySelector('[data-testid="button-minimap"]'), "native minimap toggle " + mode);
const toggle = view.containerEl.querySelector('[data-testid="button-minimap"]');
toggle.click();
await c.waitFor(() => {
const canvas = view.containerEl.querySelector(".minimap__canvas");
return canvas && canvas.width > 0 && canvas.height > 0 && canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data.some(value => value !== 0);
}, "native minimap paints " + mode);
const map = view.containerEl.querySelector(".minimap"), bounds = map.getBoundingClientRect();
check(map.ownerDocument === doc && !!map.closest(".tray-zoom") === (mode === "tray"), "minimap footer owner");
check(bounds.width > 0 && bounds.height > 0 && map.contains(doc.elementFromPoint(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2)), "minimap clipped or covered");
const state = api.getAppState(), center = { x: state.width / (2 * state.zoom.value) - state.scrollX, y: state.height / (2 * state.zoom.value) - state.scrollY };
map.dispatchEvent(new win.WheelEvent("wheel", { deltaY: -100, bubbles: true, cancelable: true }));
await c.waitFor(() => api.getAppState().zoom.value > 1, "native minimap wheel");
const next = api.getAppState();
check(Math.abs(next.width / (2 * next.zoom.value) - next.scrollX - center.x) < 0.01 && Math.abs(next.height / (2 * next.zoom.value) - next.scrollY - center.y) < 0.01, "minimap zoom center changed");
plugin.settings.zoomMax = next.zoom.value;
const trigger = view.containerEl.querySelector('[data-testid="zoom-menu-trigger"]'); trigger.click();
await c.waitFor(() => doc.querySelector('[data-testid="zoom-menu-zoomIn"]'), "native zoom menu");
check(doc.querySelector('[data-testid="zoom-menu-zoomIn"]').disabled, "menu ignored live host zoom limit");
const reset = doc.querySelector('[data-testid="zoom-menu-resetZoom"]');
await c.waitFor(() => {
const r = reset.getBoundingClientRect();
return r.width > 0 && r.height > 0 && doc.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2)?.closest("button") === reset;
}, "popout zoom portal hit target");
reset.click(); await c.waitFor(() => api.getAppState().zoom.value === 1, "native menu reset");
plugin.settings.zoomMax = oldLimits.max;
const currentToggle = view.containerEl.querySelector('[data-testid="button-minimap"]');
c.observations.minimap = { popout, mode, originalToggleConnected: toggle.isConnected, sameToggle: currentToggle === toggle, before: api.getAppState().minimapEnabled, constraints: api.getAppState().scrollConstraints };
check(currentToggle?.isConnected, "current minimap toggle missing after zoom action");
currentToggle.click();
await c.waitFor(() => {
c.observations.minimap.after = api.getAppState().minimapEnabled;
return !view.containerEl.querySelector(".minimap");
}, "native minimap cleanup");
variants.push({ popout, mode, painted: true, ownerDocument: true, centeredWheel: true, liveLimit: true, reset: true });
}
await closeLeaf(leaf);
}
} finally {
plugin.settings.zoomMin = oldLimits.min; plugin.settings.zoomMax = oldLimits.max;
plugin.settings.desktopUIMode = oldLimits.mode;
for (const leaf of app.workspace.getLeavesOfType("excalidraw")) leaf.view.excalidrawAPI?.setDesktopUIMode(oldLimits.mode);
}
return { assertions: ["actual minimap pixels in full/compact/tray", "main/popout footer and portal ownership", "centered wheel navigation", "live host zoom limits", "zoom menu reset", "toggle cleanup and popout teardown"], variants };
});
return { tests: c.tests };
}
+236 -16
View File
@@ -1,7 +1,7 @@
/** Exercise the real postprocessor with deferred image generation, without Electron. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { resolve, posix } from "node:path";
import test from "node:test";
import vm from "node:vm";
import ts from "typescript";
@@ -13,8 +13,10 @@ const deferred = () => {
return { promise, resolve, reject };
};
function fixture() {
const observers = [], timers = new Map(), intervals = new Map(), jobs = [], requests = [], errors = [], released = [], loaders = [];
function fixture({ recognizeImages = true } = {}) {
const observers = [], timers = new Map(), intervals = new Map(), jobs = [], requests = [], errors = [], released = [], loaders = [], rasters = [], controls = [], controlInstances = [], pluginCleanups = [];
let cacheReady = false;
const actions = new WeakMap();
let timerId = 0;
class Observer {
constructor(callback) { this.callback = callback; observers.push(this); }
@@ -34,11 +36,17 @@ function fixture() {
class Element {
constructor(classes = "", tag = "div") {
this.classes = new Set(classes.split(" "));
this.classList = this.classes; this.style = {}; this.events = new Map();
this.tag = tag; this.attrs = new Map(); this.children = []; this.isConnected = true;
this.ownerDocument = { defaultView: ownerWindow };
this.ownerDocument.createElement = tag => {
const element = new Element("", tag); element.ownerDocument = this.ownerDocument; return element;
};
this.ownerDocument.adoptNode = element => { element.ownerDocument = this.ownerDocument; return element; };
this.ownerDocument.body = { querySelectorAll: () => [] };
}
hasClass(cls) { return this.classes.has(cls); }
addEventListener(name, callback) { this.events.set(name, callback); }
addClass(cls) { this.classes.add(cls); }
removeClass(cls) { this.classes.delete(cls); }
getAttribute(key) { return this.attrs.get(key) ?? null; }
@@ -49,7 +57,7 @@ function fixture() {
hasChildNodes() { return this.children.length > 0; }
closest(selector) {
let el = this;
while (el) { if (selector.startsWith(".") && el.hasClass(selector.slice(1))) return el; el = el.parentElement; }
while (el) { if (selector.split(",").some(part => part.trim().startsWith(".") && el.hasClass(part.trim().slice(1)))) return el; el = el.parentElement; }
return null;
}
empty() { for (const child of this.children) child.parentElement = null; this.children = []; }
@@ -81,30 +89,40 @@ function fixture() {
const frontmatters = new Map();
const plugin = {
_loaded: true,
register: callback => pluginCleanups.push(callback),
awaitInit: async () => {},
awaitSettings: async () => {},
settings: { width: "400", height: "", renderImageInMarkdownReadingMode: true, renderImageInMarkdownToPDF: true },
isExcalidrawFile: file => file.path.endsWith("excalidraw.md"),
app: {
vault: { getAbstractFileByPath: path => files.get(path), getFileByPath: path => files.get(path) },
metadataCache: { getFirstLinkpathDest: path => files.get(path), getFileCache: file => ({ frontmatter: frontmatters.get(file.path) }) },
metadataCache: { getFirstLinkpathDest: (path, source) => files.get(path.startsWith(".") ? posix.normalize(posix.join(posix.dirname(source), path)) : path), getFileCache: file => ({ frontmatter: frontmatters.get(file.path) }) },
},
};
const queue = { addTask: task => new Promise((resolve, reject) => jobs.push(async () => { try { await task(); resolve(); } catch (e) { reject(e); } })) };
const image = (name = "result") => {
const div = new Element(), img = new Element("", "img"); img.src = `blob:${name}`; div.appendChild(img); return div;
const div = new Element(), img = new Element("excalidraw-embedded-img", "img"); img.src = `blob:${name}`; div.appendChild(img); actions.set(img, { target: targetFile.path, isCurrent: () => plugin._loaded }); return div;
};
const createImage = async (attr, onCanvas, embedEl, isRenderActive) => {
const result = deferred(); requests.push({ ...result, attr, isRenderActive }); return result.promise;
};
const mocks = {
obsidian: { TFile, MarkdownRenderChild: RenderChild },
"./drawingEmbedActions": { getDrawingEmbedActions: element => actions.get(element), setDrawingEmbedActions: (element, value) => actions.set(element, value) },
"./DrawingEmbedControls": { DrawingEmbedControls: class extends RenderChild {
constructor(...args) { super(args[0]); controls.push(args); controlInstances.push(this); this.unloadCalls = 0; }
unload() { this.unloadCalls++; super.unload(); }
onload() {} onunload() {}
} },
"src/shared/GlobalTaskQueue": { getGlobalTaskQueue: () => queue },
"../../utils/debugHelper": { DEBUGGING: false },
"../../shared/ImageCache": { getImageCache: () => ({ isReady: () => false, releaseObsidianURL: url => released.push(url) }) },
"../../shared/ImageCache": { getImageCache: () => ({ isReady: () => cacheReady, releaseObsidianURL: url => released.push(url) }) },
"../../utils/ownedPNGImage": { hasOwnedPNGImageSource: element => element.tag === "img", discardOwnedPNGImage: () => false, registerOwnedPNGImageSources: () => () => {}, cloneOwnedPNGImage: element => {
const copy = new Element("excalidraw-embedded-img", "img"); copy.src = "blob:clone"; copy.ownerDocument = element.ownerDocument; return copy;
} },
"../../shared/EmbeddedFileLoader": { EmbeddedFilesLoader: class { constructor() { this.terminate = false; loaders.push(this); } } },
"../../types/utilTypes": { PreviewImageType: { PNG: "PNG", SVGIMG: "SVGIMG", SVG: "SVG" } },
"../../utils/typechecks": { isInstanceOfHTMLImageElement: el => el.tag === "img" },
"../../utils/typechecks": { isInstanceOfHTMLImageElement: el => recognizeImages && el.tag === "img" },
"../../utils/obsidianUtils": { getSafeFrontmatter: fm => fm ?? {}, getParentOfClass: () => null },
"src/utils/htmlUtils": { setElementDisplay: (el, display) => { if (display === "none") el.addClass("excalidraw-display-none"); else el.removeClass("excalidraw-display-none"); } },
"../../utils/utils": {
@@ -112,14 +130,20 @@ function fixture() {
getEmbeddedFilenameParts: src => ({ hasBlockref: src.includes("#^"), blockref: src.split("#^")[1] }),
},
};
mocks["../../utils/obsidianUtils"].getFileCSSClasses = () => [];
mocks["../../utils/excalidrawAutomateUtils"] = { getTemplate: async () => ({ elements: [] }) };
mocks["src/utils/frameMetadata"] = { getSceneFrames: () => [] };
mocks["./openDrawingEmbed"] = { getDrawingEmbedOpenTooltip: () => "Open drawing" };
mocks["../editor/embedPadding"] = { withAreaPadding: () => null };
const context = vm.createContext({ MutationObserver: Observer, window: ownerWindow, createEl: tag => new Element("", tag),
console: { error: (...args) => errors.push(args) }, __createImage: createImage, __createRaster: async () => null });
console: { error: (...args) => errors.push(args) }, __createImage: createImage, __createRaster: async args => { rasters.push(args); return args.img; } });
const compile = (source, require) => {
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText;
const exports = {};
vm.runInContext(`(function(require,exports){${code}\n})`, context)(require, exports);
return exports;
};
const dimensions = compile(readFileSync(resolve(root, "src/core/editor/embedDimensions.ts"), "utf8"), () => ({}));
const child = compile(readFileSync(resolve(root, "src/core/managers/MarkdownEmbedRenderChild.ts"), "utf8"), name => mocks[name]);
Object.assign(mocks["../../utils/utils"], compile(readFileSync(resolve(root, "src/utils/embeddedFilenameParts.ts"), "utf8"), () => ({})));
let source = readFileSync(resolve(root, "src/core/managers/MarkdownPostProcessor.ts"), "utf8");
@@ -132,8 +156,8 @@ function fixture() {
const name = statement.declarationList.declarations[0].name.getText(tree);
source = source.slice(0, statement.getStart(tree)) + `const ${name} = ${seams[name]};` + source.slice(statement.end);
}
source += "\nexport { tmpObsidianWYSIWYG, processReadingMode, getIMG };";
const processor = compile(source, name => name === "./MarkdownEmbedRenderChild" ? child : mocks[name] ?? {});
source += "\nexport { tmpObsidianWYSIWYG, processReadingMode, getIMG, createImgElement };";
const processor = compile(source, name => name === "./MarkdownEmbedRenderChild" ? child : name === "../editor/embedDimensions" ? dimensions : mocks[name] ?? {});
processor.initializeMarkdownPostProcessor(plugin);
const container = new Element("internal-embed markdown-embed"); container.setAttribute("src", targetFile.path);
const el = container.appendChild(new Element());
@@ -143,9 +167,169 @@ function fixture() {
const flushTimers = () => { for (const [id, callback] of timers) { timers.delete(id); callback(); } };
const start = () => { assert.ok(jobs.length); const done = jobs.shift()(); return done; };
const settle = async (name = "result", request = requests.at(-1)) => { const result = image(name); request.resolve(result); await Promise.resolve(); return result; };
return { processor, plugin, container, ctx, el, children, render, jobs, requests, errors, released, observers, timers, intervals, loaders, frontmatters, flushTimers, start, settle, image, Element };
return { processor, plugin, container, ctx, el, children, render, jobs, requests, errors, released, observers, timers, intervals, loaders, frontmatters, flushTimers, start, settle, image, Element, rasters, controls, controlInstances, cacheReady: value => cacheReady = value,
files, sourceFile, targetFile, actions,
unloadPlugin: () => { plugin._loaded = false; for (const callback of pluginCleanups.splice(0)) callback(); } };
}
test("PNG fullscreen routing opens the displayed raster without starting the high-resolution exporter", async () => {
const f = fixture(); f.plugin.settings.previewImageType = "PNG";
f.targetFile.stat = { mtime: 1 };
const image = await f.processor.createImgElement({ file: f.targetFile, fname: f.targetFile.path + "#^frame=crop,padding=20", fwidth: "180", fheight: "", imgstyle: [] }, false, undefined, () => true);
assert.equal(f.rasters.length, 1);
const preview = await f.actions.get(image).create(() => true);
assert.ok(preview); assert.notEqual(preview, image);
assert.equal(preview.ownerDocument, image.ownerDocument);
assert.equal(preview.getAttribute("fileSource"), f.targetFile.path + "#^frame=crop,padding=20");
assert.equal(f.rasters.length, 1, "fullscreen must not wait for a second 3x PNG export");
assert.equal(await f.actions.get(image).create(() => false), null);
assert.equal(f.intervals.size, 0);
});
test("PNG detail upgrade forces a fresh raster and abort immediately terminates its loader", async () => {
const f = fixture(); f.plugin.settings.previewImageType = "PNG"; f.targetFile.stat = { mtime: 1 };
const image = await f.processor.createImgElement({ file: f.targetFile, fname: f.targetFile.path, fwidth: "180", fheight: "", imgstyle: [] }, false, undefined, () => true);
const controller = new AbortController(), init = deferred(); f.plugin.awaitInit = () => init.promise;
const pending = f.actions.get(image).upgrade(() => true, controller.signal), loader = f.loaders.at(-1);
assert.equal(loader.terminate, false); controller.abort(); assert.equal(loader.terminate, true);
init.resolve(); assert.equal(await pending, null); assert.equal(f.rasters.length, 1); assert.equal(f.intervals.size, 0);
f.plugin.awaitInit = async () => {}; f.plugin.settings.previewImageType = "SVG";
const next = new AbortController(); const detail = await f.actions.get(image).upgrade(() => true, next.signal);
assert.ok(detail); assert.equal(f.rasters.at(-1).forceExport, true); assert.equal(f.rasters.at(-1).cacheReady, false);
assert.equal(f.rasters.at(-1).imgAttributes.fwidth, "1600"); assert.equal(detail.ownerDocument, image.ownerDocument);
next.abort(); assert.equal(f.loaders.at(-1).terminate, false, "completed request unregisters its abort listener");
});
test("adopted PNG images retain fast fullscreen detail and disposal when their owning-window instanceof check fails", async () => {
const f = fixture({ recognizeImages: false }); f.plugin.settings.previewImageType = "PNG"; f.targetFile.stat = { mtime: 1 };
const image = await f.processor.createImgElement({ file: f.targetFile, fname: f.targetFile.path, fwidth: "180", fheight: "", imgstyle: [] }, false, undefined, () => true);
const actions = f.actions.get(image), preview = await actions.create(() => true);
assert.equal(f.rasters.length, 1, "an adopted owned PNG must not take the fresh-export fallback");
assert.equal(typeof actions.upgrade, "function");
actions.discard(preview); assert.deepEqual(f.released, ["blob:clone"]); assert.equal(preview.src, "");
});
for (const context of ["inline", "preview"]) {
test(`PNG ${context} images are created in their owning document`, async () => {
const f = fixture(); f.plugin.settings.previewImageType = "PNG";
const doc = { defaultView: f.container.ownerDocument.defaultView, createElement(tag) {
const element = new f.Element("", tag); element.ownerDocument = doc; return element;
} };
doc.adoptNode = element => { element.ownerDocument = doc; return element; };
const anchor = new f.Element(); anchor.ownerDocument = doc;
await f.processor.getIMG({ fname: f.targetFile.path, fwidth: "180", fheight: "", imgstyle: [] },
false, context === "inline" ? anchor : undefined, () => true, context === "preview", context === "preview" ? doc : undefined);
assert.equal(f.rasters.length, 1);
assert.equal(f.rasters[0].img.ownerDocument, doc);
});
}
test("#3040 Live Preview uses the rendered drawing identity for a host-relative embed", async () => {
const f = fixture();
f.files.delete(f.sourceFile.path); f.sourceFile.path = "Excalidraw/Drawings/Test.excalidraw.md";
f.files.set(f.sourceFile.path, f.sourceFile); f.ctx.sourcePath = f.sourceFile.path;
f.container.setAttribute("src", "../Excalidraw/Drawings/Test.excalidraw.md#^area=abcdefgh,padding=20");
const rendered = f.render();
assert.equal(f.jobs.length, 1, "relative link is already resolved by the drawing render context");
const job = f.start();
assert.equal(f.requests[0].attr.fname, f.sourceFile.path + "#^area=abcdefgh,padding=20");
await f.settle(); await job; await rendered;
assert.equal(f.container.hasAttribute("ready"), true);
});
test("#3039 a claimed Reading section renders while detached and survives later attachment", async () => {
const f = fixture(), section = new f.Element(), embed = section.appendChild(new f.Element("internal-embed"));
section.isConnected = embed.isConnected = false; embed.setAttribute("src", "target.excalidraw.md");
const rendered = f.processor.markdownPostProcessor(section, f.ctx);
assert.equal(embed.hasClass("is-loaded"), true);
await new Promise(resolve => setImmediate(resolve));
assert.equal(f.jobs.length, 1, "claimed detached embeds must not be abandoned");
const job = f.start();
assert.equal(f.requests[0].isRenderActive(), true, "loader follows context lifetime, not temporary attachment");
const image = await f.settle(); await job; await rendered;
section.isConnected = embed.isConnected = true;
assert.equal(section.querySelector(".excalidraw-embedded-img"), image.firstElementChild);
});
test("Reading callbacks deduplicate deferred renders and retire controls when the image is replaced", async () => {
const f = fixture(), embed = new f.Element("internal-embed"); embed.setAttribute("src", "target.excalidraw.md");
const first = f.processor.processReadingMode([embed], f.ctx, true);
const duplicate = f.processor.processReadingMode([embed], f.ctx, true);
assert.equal(f.jobs.length, 1);
const job = f.start(); const image = await f.settle(); await job; await Promise.all([first, duplicate]);
assert.equal(embed.children[0], image); assert.equal(f.controlInstances.length, 1);
await f.processor.processReadingMode([embed], f.ctx, true); assert.equal(f.jobs.length, 0);
embed.setAttribute("width", "120"); f.observers.find(observer => observer.el === embed).fire("width"); f.flushTimers();
const refresh = f.start(); const resized = await f.settle("reading-resized"); await refresh;
assert.equal(embed.children[0], resized); assert.equal(f.controlInstances[0]._loaded, false);
assert.equal(f.controlInstances[1]._loaded, true); f.children[0].unload();
assert.equal(f.controlInstances[1]._loaded, false);
});
test("Reading context retirement cancels queued and in-flight detached images", async () => {
for (const duringExport of [false, true]) {
const f = fixture(), embed = new f.Element("internal-embed"); embed.setAttribute("src", "target.excalidraw.md"); embed.isConnected = false;
const render = f.processor.processReadingMode([embed], f.ctx, true);
const job = duringExport ? f.start() : null; f.children[0].unload();
if (duringExport) { assert.equal(f.requests[0].isRenderActive(), false); await f.settle("cancelled-reading"); }
await (job ?? f.start()); await render;
assert.equal(embed.children.length, 0); assert.equal(f.controls.length, 0);
if (duringExport) assert.ok(f.released.includes("blob:cancelled-reading"));
}
});
test("plugin unload releases Reading controls and context cleanup removes owners from its registry", async () => {
for (const contextFirst of [false, true]) {
const f = fixture(), parent = new f.Element(), embed = parent.appendChild(new f.Element("internal-embed"));
embed.setAttribute("src", "target.excalidraw.md");
const rendered = f.processor.processReadingMode([embed], f.ctx, true), job = f.start();
await f.settle(); await job; await rendered;
const controls = f.controlInstances[0]; assert.equal(controls._loaded, true);
if (contextFirst) controls.unload();
f.unloadPlugin(); assert.equal(controls._loaded, false); assert.equal(controls.unloadCalls, 1);
}
});
test("Reading export finishing after plugin unload is discarded without mounting controls", async () => {
const f = fixture(), parent = new f.Element(), embed = parent.appendChild(new f.Element("internal-embed"));
embed.setAttribute("src", "target.excalidraw.md");
const rendered = f.processor.processReadingMode([embed], f.ctx, true), job = f.start();
f.unloadPlugin(); await f.settle("retired-reading-export"); await job; await rendered;
assert.equal(parent.children[0], embed); assert.equal(f.controls.length, 0);
assert.ok(f.released.includes("blob:retired-reading-export"));
});
test("fullscreen image generation bypasses shared cache and cancels without an embed DOM node", async () => {
const f = fixture(); f.cacheReady(true); f.plugin.settings.previewImageType = "PNG";
const attr = { file: { path: "target.excalidraw.md" }, fname: "target.excalidraw.md#^area=abc,padding=2", imgstyle: [] };
await f.processor.getIMG({ ...attr }, false, undefined, () => true, true);
assert.equal(f.rasters[0].cacheReady, false); assert.equal(f.rasters[0].filenameParts.linkpartReference, "#^area=abc,padding=2");
assert.equal(f.intervals.size, 0);
await f.processor.getIMG({ ...attr }, false, undefined, () => true);
assert.equal(f.rasters[1].cacheReady, true);
await f.processor.getIMG({ ...attr }, false, undefined, () => false, true);
assert.equal(f.rasters.length, 2); assert.equal(f.intervals.size, 0);
});
test("Reading controls are read-only and absent in nested, print, hover, Canvas and editor contexts", async () => {
for (const ancestor of ["", "markdown-embed", "print", "hover-popover", "canvas-node-content", "cm-content"]) {
const f = fixture(), parent = new f.Element(ancestor), embed = parent.appendChild(new f.Element("internal-embed"));
embed.setAttribute("src", "target.excalidraw.md");
const rendered = f.processor.processReadingMode([embed], f.ctx, true), job = f.start();
await f.settle(); await job; await rendered;
assert.equal(f.controls.length, ancestor ? 0 : 1, ancestor);
if (!ancestor) assert.equal(f.controls[0].length, 2, "Reading mode has no source binding");
}
});
test("native table alt text retains escaped caption, size and style through image generation", async () => {
const f = fixture(), parent = new f.Element(), embed = parent.appendChild(new f.Element("internal-embed"));
embed.setAttribute("src", "target.excalidraw.md"); embed.setAttribute("alt", "Caption\\|100\\|left");
const rendered = f.processor.processReadingMode([embed], f.ctx), job = f.start();
assert.equal(f.requests[0].attr.fwidth, "100"); assert.deepEqual([...f.requests[0].attr.imgstyle], ["excalidraw-svg-left"]);
await f.settle(); await job; await rendered;
});
test("ready follows successful insertion; repeated callbacks preserve the image", async () => {
const f = fixture(); const first = f.render(); const repeat = f.render();
assert.equal(f.container.hasAttribute("ready"), false); assert.equal(f.jobs.length, 1); assert.equal(f.children.length, 1);
@@ -243,12 +427,12 @@ test("ordinary image embeds, text references and code blocks remain native", asy
}
});
test("Reading mode skips a detached candidate without suppressing a later live drawing", async () => {
test("Reading mode ignores an unrecognized detached candidate without suppressing a later drawing", async () => {
const f = fixture(); const detached = new f.Element(); detached.isConnected = false;
const parent = new f.Element(), live = parent.appendChild(new f.Element("internal-embed")); live.setAttribute("src", "target.excalidraw.md");
const rendered = f.processor.processReadingMode([detached, live], f.ctx);
assert.equal(f.jobs.length, 1); const job = f.start(); const result = await f.settle(); await job; await rendered;
assert.equal(parent.children[0], result);
assert.equal(live.children[0], result);
});
test("image loader cancellation follows context lifetime and always clears its interval", async () => {
@@ -280,7 +464,7 @@ test("Reading mode resolves explicit self-images, but ignores empty and ordinary
const rendered = f.processor.processReadingMode([embed], f.ctx);
if (src === "#^as-image") {
const job = f.start(); assert.equal(f.requests[0].attr.fname, `${f.ctx.sourcePath}#^as-image`);
const result = await f.settle(); await job; await rendered; assert.equal(parent.children[0], result);
const result = await f.settle(); await job; await rendered; assert.equal(embed.children[0], result);
} else { await rendered; assert.equal(f.jobs.length, 0); assert.equal(parent.children[0], embed); }
}
});
@@ -291,7 +475,7 @@ test("Reading mode preserves a target's Markdown side unless the link explicitly
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(); await f.settle(); await job; await rendered; assert.notEqual(parent.children[0], embed); }
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); }
}
}
@@ -311,3 +495,39 @@ test("nested Markdown-side drawings and PNGs remain visible; drawing metadata st
}
}
});
test("PDF postprocessing claims drawing images before native embed discovery", async () => {
const f = fixture();
const settings = deferred(); f.plugin.awaitSettings = () => settings.promise;
const section = new f.Element();
const draw = section.appendChild(new f.Element("internal-embed"));
draw.setAttribute("src", "target.excalidraw.md#^frame=Slide with spaces");
const plain = section.appendChild(new f.Element("internal-embed")); plain.setAttribute("src", "image.png");
section.ownerDocument.body.querySelectorAll = () => [section];
const rendered = f.processor.markdownPostProcessor(section, f.ctx);
// Obsidian's MarkdownRenderer.postProcess discovers native embeds synchronously,
// before awaiting any plugin promises. A frame reference is not a native block:
// its fallback would parse the entire drawing, including recursive transclusions.
const nativeEmbeds = section.querySelectorAll(".internal-embed").filter(el => !el.hasClass("is-loaded"));
assert.deepEqual(nativeEmbeds, [plain], "only the plain image reaches the native renderer");
assert.equal(f.requests.length, 0, "claiming an image does not bypass settings readiness");
settings.resolve(); await new Promise(resolve => setImmediate(resolve));
const job = f.start(); const image = await f.settle(); await job; await rendered;
assert.equal(draw.children[0], image, "PDF rendering awaits the actual drawing image");
assert.equal(section.children[1], plain, "native images remain untouched");
});
test("synchronous embed ownership preserves native text and hybrid Markdown", async () => {
for (const property of [null, "excalidraw-open-md", "excalidraw-embed-md"]) {
const f = fixture();
if (property) f.frontmatters.set("target.excalidraw.md", { [property]: true });
const section = new f.Element();
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]);
await new Promise(resolve => setImmediate(resolve));
while (f.jobs.length) { const job = f.start(); await f.settle(); await job; }
await rendered;
}
});
@@ -0,0 +1,43 @@
/** Obsidian's display labels are not link targets; retain cache-owned source identity. */
import assert from "node:assert/strict";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
const sourceHeading = "[Heading](http://www.google.com)", linkHeading = "Heading http www google com";
const harness = sourceHarness({
obsidian: {
stripHeading: heading => heading === sourceHeading ? linkHeading : heading,
resolveSubpath: (cache, subpath) => {
const current = cache.headings.find(heading => "#" + (heading.heading === sourceHeading ? linkHeading : heading.heading) === subpath);
return current ? { type: "heading", current } : null;
},
},
"src/constants/constants": { MD_EX_SECTIONS: ["# Excalidraw Data"], nanoid: () => "new-block" },
"src/lang/helpers": { t: key => key }, "src/shared/Scripts": { ScriptEngine: {} },
"src/utils/pathUtils": { cleanSectionHeading: heading => heading.replace(/[#:]/g, "").trim() },
});
const { getMarkdownHeadingSubpaths } = await harness.importModule("src/shared/Suggesters/markdownSubpathSuggester.ts");
test.after(() => harness.close());
function fixture(headings = ["Plain", sourceHeading, "Plain"]) {
const cache = { headings: headings.map((heading, i) => ({ heading, position: { start: { offset: i * 100 } } })) };
const blocks = headings.map((heading, i) => ({ display: heading === sourceHeading ? "# Heading" : "# " + heading,
node: { type: "heading", position: { start: { offset: i * 100 } } } }));
return { cache, blocks, app: { metadataCache: { getFileCache: () => cache, blockCache: { getForFile: async () => ({ blocks }) } } } };
}
test("heading suggestions retain formatted source targets, friendly labels and duplicate order", async () => {
const { app, cache, blocks } = fixture();
const before = structuredClone({ cache, blocks });
assert.deepEqual(await getMarkdownHeadingSubpaths(app, {}, false), [
{ display: "# Plain", subpath: "#Plain" }, { display: "# Heading", subpath: "#" + linkHeading }, { display: "# Plain", subpath: "#Plain" },
]);
assert.deepEqual({ cache, blocks }, before);
});
test("missing or unmatched cache cannot offer a section that Obsidian cannot resolve", async () => {
const f = fixture(); f.cache.headings = [];
assert.deepEqual(await getMarkdownHeadingSubpaths(f.app, {}, false), []);
f.app.metadataCache.getFileCache = () => null;
assert.deepEqual(await getMarkdownHeadingSubpaths(f.app, {}, false), []);
});
@@ -0,0 +1,47 @@
/** Canonical picker targets must also retain the existing image-transclusion source slice. */
import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
import vm from "node:vm";
import ts from "typescript";
class TFile {}
const raw = "[Heading](http://www.google.com)", canonical = "Heading http www google com";
const exports = {};
const clean = value => value?.replace(/[:#]/g, "");
vm.runInNewContext(ts.transpileModule(readFileSync(new URL("../../src/shared/ExcalidrawData.ts", import.meta.url), "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText, { exports, require: name => ({
obsidian: { TFile, stripHeading: value => value === raw ? canonical : value },
"../utils/pathUtils": { cleanSectionHeading: clean, cleanBlockRef: clean },
}[name] ?? {}) });
function fixture() {
const source = "# " + raw + "\n\nFIRST_BODY\n\n## Child\n\nCHILD_BODY\n\n# Other\n\nOTHER_BODY\n";
const headings = [raw, "Child", "Other"].map((heading, i) => {
const start = source.indexOf((i === 1 ? "## " : "# ") + heading);
const content = start + (i === 1 ? 3 : 2);
return { display: (i === 1 ? "## " : "# ") + (i ? heading : "Heading"), node: {
type: "heading", depth: i === 1 ? 2 : 1, data: { hProperties: { dataHeading: heading } },
position: { start: { offset: start, line: i * 4 + 1 } },
children: [{ value: i ? heading : undefined, children: i ? undefined : [{ value: "Heading" }], position: { start: { offset: content, line: i * 4 + 1 } } }],
} };
});
const file = new TFile();
const app = { vault: { read: async () => source }, metadataCache: { blockCache: { getForFile: async () => ({ blocks: headings }) } } };
const resolve = ref => exports.getTransclusion({ path: "Note.md", original: "Note.md#" + ref, ref, isBlockRef: false }, app, file);
return { source, resolve };
}
test("canonical linked-heading image targets retain the heading body and nested sections", async () => {
const f = fixture(), result = await f.resolve(canonical);
assert.equal(result.contents, raw + "\n\nFIRST_BODY\n\n## Child\n\nCHILD_BODY");
assert.equal(result.leadingHashes, "# "); assert.equal(result.lineNum, 1);
});
test("existing display-label targets, ordinary sections and missing-section fallback stay unchanged", async () => {
const f = fixture();
assert.equal((await f.resolve("Heading")).contents, raw + "\n\nFIRST_BODY\n\n## Child\n\nCHILD_BODY");
assert.equal((await f.resolve("Other")).contents, "Other\n\nOTHER_BODY");
assert.equal((await f.resolve("Missing")).contents, "Note.md#Missing");
});
@@ -0,0 +1,79 @@
import assert from "node:assert/strict";
import test, { after } from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
let promptResult, prompts = [];
const device = { isDesktop: true, isMacOS: false, isIOS: false };
const graph = sourceHarness({
"src/constants/constants": { DEVICE: device, VIEW_TYPE_EXCALIDRAW: "excalidraw" },
"src/lang/helpers": { t: key => ({ EMBED_OPEN_DRAWING: "Open drawing", EMBED_OPEN_MODIFIER: "{keys}+click: {action}" })[key] ?? key },
"src/utils/coreUtils": { errorlog: error => assert.fail(JSON.stringify(error)) },
"src/utils/obsidianUtils": { getNewOrAdjacentLeaf: plugin => plugin.app.workspace.getLeaf("split") },
"src/utils/modifierkeyHelper": {
linkClickModifierType: event => event.modifier,
labelCTRL: () => device.isMacOS ? "CMD" : "CTRL", labelMETA: () => device.isMacOS ? "CTRL" : "WIN", labelALT: () => "ALT", labelSHIFT: () => "SHIFT",
modifierKeyTooltipMessages: () => ({ LinkClickAction: { "new-tab": "New tab", "popout-window": "Popout", "active-pane": "Current pane" } }),
},
"src/utils/utils": { isMaskFile: (_plugin, file) => !!file.mask },
"src/utils/excalidrawViewUtils": { getExcalidrawFileForwardLinks: () => "[[Forward]]" },
"src/shared/Dialogs/Prompt": { linkPrompt: async text => { prompts.push(text); return promptResult; } },
});
const { openDrawingEmbed, getDrawingEmbedOpenTooltip } = await graph.importModule("src/core/managers/openDrawingEmbed.ts");
after(() => graph.close());
const flush = () => new Promise(resolve => setImmediate(resolve));
function fixture(mask = false) {
const drawing = { path: "Drawing.excalidraw.md", mask }, calls = [], links = [], saves = [], leaves = [], origin = {};
const createLeaf = (location, markdown = false) => {
const leaf = { id: "leaf-" + leaves.length, view: { file: markdown ? drawing : null, getViewType: () => markdown ? "markdown" : "empty", containerEl: { contains: element => markdown && element === origin }, save: async () => saves.push(location) },
async setViewState(state) {
const call = [drawing, location, state.active, ""]; calls.push(call);
assert.equal(state.type, "excalidraw"); assert.equal(state.state.file, drawing.path);
this.view = { file: drawing, getViewType: () => "excalidraw", containerEl: { contains: () => false }, setEphemeralState: state => { call[3] = state.subpath; } };
} };
leaves.push(leaf); return leaf;
};
const active = createLeaf("active-pane", true);
const workspace = { iterateAllLeaves: callback => leaves.forEach(callback), setActiveLeaf() {}, getLeaf: type => type ? createLeaf(type === "split" ? "new-pane" : "new-tab") : active,
openPopoutLeaf: () => createLeaf("popout-window"), openLinkText: async (...args) => links.push(args) };
const plugin = { _loaded: true, settings: { focusOnFileTab: true }, excalidrawFileModes: {}, app: { vault: { getFileByPath: path => path === drawing.path ? drawing : null }, workspace },
isExcalidrawFile: file => file?.path.endsWith("excalidraw.md") };
prompts = []; return { plugin, drawing, calls, links, saves, active, origin };
}
test("Open drawing preserves all modifier and complete reference semantics of existing gestures", async () => {
for (const modifier of ["active-pane", "new-pane", "popout-window", "new-tab", "md-properties"]) {
const f = fixture(), reference = "#^clippedframe=Frame name,padding=2";
openDrawingEmbed(f.plugin, f.drawing.path + reference, { modifier }, f.origin); await flush();
assert.deepEqual(f.calls, [[f.drawing, modifier === "md-properties" ? "new-tab" : modifier, true, reference]]);
if (modifier === "active-pane") { assert.deepEqual(f.saves, ["active-pane"]); assert.equal(f.active.view.getViewType(), "excalidraw"); }
openDrawingEmbed(f.plugin, "missing.excalidraw.md", { modifier }); assert.equal(f.calls.length, 1);
}
});
test("mask link prompts retain drawing selection, Markdown subpath routing and cancellation", async () => {
for (const [modifier, pane] of [["active-pane", false], ["new-pane", "split"], ["popout-window", "window"], ["new-tab", "tab"], ["md-properties", "tab"]]) {
const f = fixture(true), target = { path: "Note.md" };
promptResult = [target, "Note", "#Section"];
openDrawingEmbed(f.plugin, f.drawing.path, { modifier }); await flush();
assert.deepEqual(f.links, [["Note", "", pane, { eState: { subpath: "#Section" } }]]);
assert.match(prompts[0], /\[\[Forward\]\]/);
promptResult = [f.drawing, f.drawing.path, "#^group=abcdefgh"];
openDrawingEmbed(f.plugin, f.drawing.path, { modifier }); await flush();
assert.deepEqual(f.calls, [[f.drawing, modifier === "md-properties" ? "new-tab" : modifier, true, "#^group=abcdefgh"]]);
promptResult = null; openDrawingEmbed(f.plugin, f.drawing.path, { modifier }); await flush();
assert.equal(f.calls.length, 1); assert.equal(f.links.length, 1);
}
});
test("open tooltips follow live platform settings and omit unsupported mobile popouts", () => {
const rules = [
{ ctrl_cmd: true, result: "new-tab" },
{ ctrl_cmd: true, shift: true, result: "popout-window" },
{ ctrl_cmd: true, result: "active-pane" },
];
const settings = { modifierKeyConfig: { Win: { LinkClickAction: { rules } }, Mac: { LinkClickAction: { rules } } } };
assert.equal(getDrawingEmbedOpenTooltip(settings), "Open drawing\nCTRL+click: New tab\nCTRL+SHIFT+click: Popout");
rules[0].result = "active-pane";
assert.match(getDrawingEmbedOpenTooltip(settings), /CTRL\+click: Current pane/);
device.isDesktop = false; device.isMacOS = true;
try { assert.equal(getDrawingEmbedOpenTooltip(settings), "Open drawing\nCMD+click: Current pane"); }
finally { device.isDesktop = true; device.isMacOS = false; }
});
@@ -0,0 +1,30 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
test("P toggles freedraw to selection only for the owning canvas and ignores repeats", async () => {
const graph = sourceHarness();
try {
const { handlePenToggleShortcut: handle } = await graph.importModule("src/view/managers/penToggleShortcut.ts");
const selected = [], doc = {}, target = { ownerDocument: doc, closest: selector => selector === ".excalidraw" ? {} : null };
doc.activeElement = target;
const state = { activeTool: { type: "freedraw" } };
const view = { ownerDocument: doc, containerEl: { contains: el => el === target }, isClosingOrMigrating: () => false,
excalidrawAPI: { getAppState: () => state, setActiveTool: tool => { selected.push(tool); state.activeTool = tool; } } };
const event = extra => ({ key: "p", target, preventDefault() { this.prevented = true; }, stopPropagation() { this.stopped = true; }, ...extra });
const e = event(); assert.equal(handle(view, e), true); assert.equal(e.prevented, true); assert.equal(e.stopped, true);
assert.deepEqual(selected, [{ type: "selection" }]);
assert.equal(handle(view, event({ repeat: true })), true); assert.equal(selected.length, 1);
assert.equal(state.activeTool.type, "selection", "holding the second P must not return to pen");
assert.equal(handle(view, event()), false, "a fresh P still reaches the editor to select pen");
state.activeTool = { type: "freedraw" };
for (const flags of [{ ctrlKey: true }, { metaKey: true }, { altKey: true }, { shiftKey: true }, { isComposing: true }, { defaultPrevented: true }, { key: "v" }]) assert.equal(handle(view, event(flags)), false);
for (const flags of [{ activeTool: { type: "selection" } }, { newElement: {} }, { viewModeEnabled: true }, { openDialog: {} }]) {
const original = { ...state }; Object.assign(state, flags); assert.equal(handle(view, event()), false);
for (const key of Object.keys(state)) delete state[key]; Object.assign(state, original);
}
target.closest = () => ({}); assert.equal(handle(view, event()), false);
target.ownerDocument = {}; assert.equal(handle(view, event()), false);
assert.equal(selected.length, 1);
} finally { graph.close(); }
});
+388
View File
@@ -0,0 +1,388 @@
import assert from "node:assert/strict";
import test from "node:test";
import vm from "node:vm";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import ts from "typescript";
import { sourceHarness } from "./sourceHarness.mjs";
const root = resolve(import.meta.dirname, "../..");
async function fixture() {
const previousWindow = globalThis.window;
const previousCreateEl = globalThis.createEl;
globalThis.window = globalThis;
const graph = sourceHarness({
obsidian: { Notice: class {} },
"src/lang/helpers": { t: (key) => key },
"../utils/utils": { convertSVGStringToElement() {}, errorlog() {} },
"../utils/debugHelper": { log() {} },
"../types/utilTypes": {
PreviewImageType: { PNG: "PNG", SVGIMG: "SVGIMG", SVG: "SVG" },
},
"../utils/fileUtils": {
hasExcalidrawEmbeddedImagesTreeChanged: () => false,
},
"src/constants/constants": {
EXCALIDRAW_PLUGIN: { app: { appId: "owned-raster-regression" } },
},
"../utils/coreUtils": { blobToDataURL() {} },
"../utils/typechecks": { isInstanceOfSVGSVGElement: () => false },
"./BackupPersistenceQueue": {
BackupPersistenceQueue: class {
destroy() {}
},
},
});
const { getImageCache } = await graph.importModule(
"src/shared/ImageCache.ts",
);
const ownedPNG = await graph.importModule("src/utils/ownedPNGImage.ts");
const images = new Set();
const cache = getImageCache(),
stores = new Map(),
requests = [],
urls = new Set();
const store = (name) => {
if (!stores.has(name)) stores.set(name, new Map());
return stores.get(name);
};
const file = { path: "owned.excalidraw.md", stat: { mtime: 0 } };
const pluginCleanups = [];
const disposePlugin = () => {
for (const cleanup of pluginCleanups.splice(0).reverse()) cleanup();
};
const plugin = {
settings: { allowImageCache: true },
register: (cleanup) => pluginCleanups.push(cleanup),
app: {
vault: { getFileByPath: () => file },
metadataCache: {},
},
};
cache.app = plugin.app;
cache.plugin = plugin;
cache.db = {
close() {},
transaction: () => ({
objectStore: (name) => ({
put: (value, key) => store(name).set(key, value),
delete: (key) => store(name).delete(key),
}),
}),
};
cache.ensureCacheStoreReady = async () => {};
cache.getCacheData = async (key) => store("imageCacheV2").get(key);
class Image {
constructor() {
images.add(this);
}
value = "";
complete = false;
naturalWidth = 0;
ownerDocument = { adoptNode(image) { image.ownerDocument = this; return image; } };
classes = new Set();
hasClass(name) { return this.classes.has(name); }
set src(value) {
this.value = value;
this.complete = false;
this.naturalWidth = 0;
}
get src() {
return this.value;
}
listeners = new Map();
addEventListener(name, callback, options) {
this.listeners.set(name, { callback, options });
}
removeEventListener(name, callback) {
if (this.listeners.get(name)?.callback === callback)
this.listeners.delete(name);
}
fire(name, complete = true) {
this.complete = complete;
this.naturalWidth = name === "load" ? 1 : 0;
const entry = this.listeners.get(name);
if (entry?.options?.once) this.listeners.delete(name);
entry?.callback();
}
}
globalThis.createEl = (tag, options) => {
assert.equal(tag, "img");
const image = new Image();
image.classes = new Set((options?.cls ?? "").split(" ").filter(Boolean));
return image;
};
const mocks = {
"../../utils/ownedPNGImage": ownedPNG,
"../../shared/ImageCache": { getImageCache: () => cache },
"../../types/utilTypes": { PreviewImageType: { PNG: "PNG" } },
"../../utils/utils": {
getEmbeddedFilenameParts: () => ({}),
isImagePartRef: () => false,
getQuickImagePreview: async () => undefined,
getExportPadding: () => 10,
},
"../../utils/typechecks": {
isInstanceOfHTMLImageElement: (image) => image instanceof Image,
},
"../../utils/excalidrawAutomateUtils": {
createPNG: () => new Promise((resolve) => requests.push(resolve)),
},
};
const source =
readFileSync(
resolve(root, "src/core/managers/MarkdownPostProcessor.ts"),
"utf8",
) + "\nexport { _getPNG, discardImage };";
const code = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
},
}).outputText;
const context = vm.createContext({
MutationObserver: class {
observe() {}
disconnect() {}
},
URL: {
createObjectURL: (blob) => {
const url = URL.createObjectURL(blob);
urls.add(url);
return url;
},
revokeObjectURL: (url) => URL.revokeObjectURL(url),
},
});
const exports = {};
vm.runInContext(`(function(require,exports){${code}\n})`, context)(
(name) => mocks[name] ?? {},
exports,
);
exports.initializeMarkdownPostProcessor(plugin);
const key = {
filepath: file.path,
cacheId: "frame-thumbnail-v2",
previewImageType: "PNG",
scale: 1,
isDark: false,
isTransparent: false,
inlineFonts: true,
};
const render = (img, cacheReady = true) =>
exports._getPNG({
imgAttributes: { fname: file.path, fwidth: "180" },
filenameParts: { filepath: file.path },
theme: "light",
cacheReady,
img,
file,
exportSettings: { withBackground: true },
loader: {},
});
return {
cache,
key,
requests,
Image,
render,
discard: exports.discardImage,
disposePlugin,
ownedPNG,
close() {
disposePlugin();
for (const image of images) ownedPNG.discardOwnedPNGImage(image);
if (cache.isReady()) cache.destroy();
for (const url of urls) URL.revokeObjectURL(url);
graph.close();
if (previousWindow === undefined) delete globalThis.window;
else globalThis.window = previousWindow;
if (previousCreateEl === undefined) delete globalThis.createEl;
else globalThis.createEl = previousCreateEl;
},
};
}
const flush = () => new Promise((resolve) => setImmediate(resolve));
const blob = (text) => new Blob([text], { type: "image/png" });
test("fullscreen PNG copies reuse displayed pixels without another export and own independent URLs", async () => {
for (const cacheReady of [true, false]) {
const f = await fixture();
try {
const inline = new f.Image(), task = f.render(inline, cacheReady);
await flush(); f.requests[0](blob("displayed-frame-crop-theme")); await task;
inline.fire("load");
const preview = f.ownedPNG.cloneOwnedPNGImage(inline);
assert.ok(preview);
assert.equal(preview.ownerDocument, inline.ownerDocument);
assert.ok(preview.hasClass("excalidraw-embedded-img"));
assert.notEqual(preview.src, inline.src);
assert.equal(await (await fetch(preview.src)).text(), "displayed-frame-crop-theme");
assert.equal(f.requests.length, 1, "opening fullscreen must not export another raster");
const previewURL = preview.src; f.discard(preview);
await assert.rejects(fetch(previewURL));
assert.equal(await (await fetch(inline.src)).text(), "displayed-frame-crop-theme");
const reopened = f.ownedPNG.cloneOwnedPNGImage(inline);
assert.notEqual(reopened.src, previewURL);
f.discard(inline);
assert.equal(await (await fetch(reopened.src)).text(), "displayed-frame-crop-theme");
assert.equal(f.ownedPNG.cloneOwnedPNGImage(inline), null, "retired images cannot be copied");
f.disposePlugin(); await assert.rejects(fetch(reopened.src));
} finally { f.close(); }
}
});
test("loaded PNG URLs remain readable for independent pixel consumers", async () => {
const f = await fixture();
try {
const img = new f.Image(),
task = f.render(img);
await flush();
f.requests[0](blob("migrated"));
await task;
const first = img.src;
img.fire("load");
assert.equal(await (await fetch(first)).text(), "migrated");
img.fire("error", false);
assert.equal(await (await fetch(img.src)).text(), "migrated");
assert.equal(
f.requests.length,
1,
"pixel consumers reuse the payload without exporting again",
);
f.discard(img);
await assert.rejects(fetch(first));
} finally {
f.close();
}
});
test("concurrent cold PNG renders retain independent URLs until their images retire", async () => {
const f = await fixture();
try {
const a = new f.Image(),
b = new f.Image(),
first = f.render(a),
second = f.render(b);
await flush();
assert.equal(f.requests.length, 2);
f.requests[0](blob("first"));
await first;
f.requests[1](blob("second"));
await second;
assert.equal(await (await fetch(a.src)).text(), "first");
assert.equal(await (await fetch(b.src)).text(), "second");
assert.notEqual(a.src, b.src);
a.fire("load");
assert.equal(await (await fetch(a.src)).text(), "first");
const firstURL = a.src;
f.discard(a);
await assert.rejects(fetch(firstURL));
assert.equal(await (await fetch(b.src)).text(), "second");
assert.equal(a.listeners.size, 0, "both terminal listeners are removed");
b.fire("error");
await assert.rejects(fetch(b.src));
assert.equal(b.listeners.size, 0);
assert.equal(
(await f.cache.getImageCacheData(f.key)).blob.type,
"image/png",
);
} finally {
f.close();
}
});
test("warm PNG cache hits have independent URLs and discarding one preserves its sibling", async () => {
const f = await fixture();
try {
f.cache.addImageToCache(f.key, "", blob("cached"));
const a = new f.Image(),
b = new f.Image();
await Promise.all([f.render(a), f.render(b)]);
assert.equal(f.requests.length, 0, "warm hits never export again");
assert.notEqual(a.src, b.src);
const old = a.src;
f.discard(a);
await assert.rejects(fetch(old));
assert.equal(await (await fetch(b.src)).text(), "cached");
b.fire("load");
assert.equal(await (await fetch(b.src)).text(), "cached");
const remaining = b.src;
f.discard(b);
await assert.rejects(fetch(remaining));
} finally {
f.close();
}
});
test("uncached PNG payloads release on discard or decode failure without populating the cache", async () => {
for (const terminal of ["load", "error"]) {
const f = await fixture();
try {
const img = new f.Image(),
task = f.render(img, false);
await flush();
f.requests[0](blob(terminal));
await task;
assert.equal(await (await fetch(img.src)).text(), terminal);
img.fire(terminal);
const url = img.src;
if (terminal === "load") {
assert.equal(await (await fetch(url)).text(), terminal);
f.discard(img);
}
await assert.rejects(fetch(url));
assert.equal(await f.cache.getImageCacheData(f.key), undefined);
} finally {
f.close();
}
}
});
test("plugin retirement revokes PNG URLs and a stale disposer preserves its replacement", async () => {
const f = await fixture();
try {
const img = new f.Image(),
task = f.render(img);
await flush();
f.requests[0](blob("owned"));
await task;
img.fire("load");
const url = img.src;
f.disposePlugin();
await assert.rejects(fetch(url));
assert.equal(img.listeners.size, 0);
const late = new f.Image();
await f.render(late);
assert.equal(late.src, "");
const stale = f.ownedPNG.registerOwnedPNGImageSources();
const current = f.ownedPNG.registerOwnedPNGImageSources();
const replacement = new f.Image();
await f.render(replacement);
stale();
assert.equal(await (await fetch(replacement.src)).text(), "owned");
current();
await assert.rejects(fetch(replacement.src));
assert.equal(replacement.listeners.size, 0);
} finally {
f.close();
}
});
test("discarding a pending PNG after cache shutdown still releases its URL and listeners", async () => {
const f = await fixture();
try {
const img = new f.Image(),
task = f.render(img);
await flush();
f.requests[0](blob("pending"));
await task;
const url = img.src;
f.cache.destroy();
f.discard(img);
await assert.rejects(fetch(url));
assert.equal(img.listeners.size, 0);
} finally {
f.close();
}
});
+18 -2
View File
@@ -19,19 +19,33 @@ import { deviceProfiles, breakpointProfiles } from "./host/deviceProfiles.mjs";
import { behavioralCases } from "./behaviorPlan.mjs";
import { coverageChanges } from "./coverageChanges.mjs";
import { workflowBundleCaseIds } from "./host/workflowBundle.mjs";
import { aiAndEmbedsCaseIds } from "./host/aiAndEmbeds.mjs";
import { issue3052CaseIds } from "./host/issue3052.mjs";
import { textSaveShortcutCaseIds } from "./host/textSaveShortcut.mjs";
import { codeCardCaseIds } from "./host/codeCards.mjs";
import { embedControlCaseIds, embedControlDeviceCaseIds } from "./host/embedControls.mjs";
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";
export const requiredDeviceCases = [
...deviceProfiles(),
...breakpointProfiles(),
].map((profile) => "native:device:" + profile.id).concat(kplexOntologyDeviceCaseIds);
].map((profile) => "native:device:" + profile.id).concat(kplexOntologyDeviceCaseIds, embedControlDeviceCaseIds, frameSemanticsDeviceCaseIds);
export const requiredNativeCases = [
...runtimeCompactionCaseIds,
...workflowBundleCaseIds,
...issue3052CaseIds,
...aiAndEmbedsCaseIds,
...textSaveShortcutCaseIds,
...codeCardCaseIds,
...embedControlCaseIds,
...embedRegressionCaseIds,
...embedReliabilityCaseIds,
...frameSemanticsCaseIds,
...kplexOntologyCaseIds,
...behavioralCases().map((row) => row.testId),
...["image-url", "image-import"].flatMap((action) =>
@@ -188,7 +202,9 @@ async function main() {
},
stdio: ["ignore", fd, fd],
windowsHide: true,
timeout: 1800000,
// Full native/device workflows exceed the portable lane's 30-minute budget.
// Individual native task and cleanup deadlines remain enforced by their runner.
timeout: name === "build" && native ? 5400000 : 1800000,
});
} finally {
closeSync(fd);
+1
View File
@@ -21,6 +21,7 @@ const reportPath = join(reportDir, "report.json");
// Separate measured whole-module tests from historical VM/extraction harnesses.
const selected = coverage ? files.filter(file => file.endsWith(".source.test.mjs") || [
"scripts/testing/settings/settingsWriter.test.mjs", "tests/markdownImageGeometry.test.mjs", "tests/markdownImageCache.test.mjs", "tests/markdownImageMetadata.test.mjs",
"scripts/testing/pngEmbedLifetime.test.mjs", // Complete cache/owned-payload modules; the postprocessor VM earns no source credit.
].includes(file)) : files;
const args = ["--experimental-transform-types", "--enable-source-maps", "--test", "--test-concurrency=4",
"--test-reporter=dot", "--test-reporter=./scripts/testing/reporter.mjs", "--test-reporter-destination=stdout", `--test-reporter-destination=${reportPath}`,
+54
View File
@@ -0,0 +1,54 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import ts from "typescript";
// Exercise the view's scene capture and the model's Markdown payload serializer intact.
function loadMethods(path, className, names, dependencies = {}) {
const source = ts.createSourceFile(path, readFileSync(new URL(`../../${path}`, import.meta.url), "utf8"), ts.ScriptTarget.Latest, true);
const declaration = source.statements.find(node => ts.isClassDeclaration(node) && node.name?.text === className);
const methods = names.map(name => {
const method = declaration.members.find(node => node.name?.getText(source) === name);
assert.ok(method, `${className}.${name}`);
return method.getText(source);
});
const { outputText } = ts.transpileModule(`export class Loaded { ${methods.join("\n")} }`, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
});
const exports = {};
new Function("exports", ...Object.keys(dependencies), outputText)(exports, ...Object.values(dependencies));
return exports.Loaded.prototype;
}
const viewMethods = loadMethods("src/view/ExcalidrawView.ts", "ExcalidrawView", ["getScene", "getSceneWithAppState"], {
URLs: { GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG: "https://example.test/releases" },
PLUGIN_VERSION: "test",
getAppStateStrokeWidthEntry: () => ({}),
});
const dataMethods = loadMethods("src/shared/ExcalidrawData.ts", "ExcalidrawData", ["generateMDBase"]);
test("Markdown scene payload preserves both hint values and every input device", () => {
for (const showHints of [false, true]) {
for (const inputDevice of ["auto", "mouse", "trackpad"]) {
const view = Object.assign(Object.create(viewMethods), {
excalidrawAPI: {
getAppState: () => ({ showHints, inputDevice, activeTool: { type: "selection" } }),
getSceneElements: () => [], getFiles: () => ({}),
},
});
const model = {
scene: view.getScene(), plugin: { settings: {} }, textElements: new Map(),
elementLinks: new Map(), equations: new Map(), files: new Map(), markdownImages: new Map(),
};
const { sceneJSONstring } = dataMethods.generateMDBase.call(model);
const saved = JSON.parse(sceneJSONstring);
assert.equal(saved.appState.showHints, showHints);
assert.equal(saved.appState.inputDevice, inputDevice);
const snapshot = view.getSceneWithAppState(false, {
showHints: !showHints, inputDevice: "trackpad", activeTool: { type: "selection" },
});
assert.equal(snapshot.appState.showHints, !showHints);
assert.equal(snapshot.appState.inputDevice, "trackpad");
}
}
});
+37
View File
@@ -0,0 +1,37 @@
/** Exercise the actual vault export entry point and existing scene link filter. */
import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
import vm from "node:vm";
import ts from "typescript";
function compile(path, dependencies) {
const exports = {};
vm.runInNewContext(ts.transpileModule(readFileSync(new URL("../../" + path, import.meta.url), "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText, { exports, require: name => dependencies[name] ?? {} });
return exports;
}
const { sceneRemoveInternalLinks } = compile("src/utils/excalidrawViewUtils.ts", {
obsidian: { Modal: class {} },
"../shared/ExcalidrawData": { REG_LINKINDEX_HYPERLINK: /^\w+:\/\// },
});
const writes = [];
const { ViewExportManager } = compile("src/view/managers/ViewExportManager.ts", {
"../../utils/fileUtils": { getIMGFilename: path => path + ".svg", exportImageToFile: async (...args) => writes.push(args) },
});
for (const method of ["vault", "clipboard"]) for (const include of [true, false]) test(`${method} SVG honors internal links=${include} without changing the source scene`, async () => {
const scene = { elements: [{ id: "internal", link: "[[Target|Alias]]" }, { id: "external", link: "https://example.com/?q=<tag>&x=1" }], appState: {} };
const before = structuredClone(scene), rendered = [];
const view = { file: { path: "Drawing.md" }, excalidrawAPI: {}, getScene: () => scene, plugin: { settings: { autoExportLightAndDark: false } } };
const manager = new ViewExportManager(view, { getOrCreateExportDialog: () => null, getExportInternalLinks: () => include, sceneRemoveInternalLinks });
manager.svg = async source => { rendered.push(source); return { outerHTML: JSON.stringify(source.elements.map(element => element.link)) }; };
if (method === "vault") await manager.saveSVG({ scene }); else await manager.getSVG();
assert.deepEqual(scene, before);
assert.equal(rendered.length, 1);
assert.equal(rendered[0].elements[0].link, include ? "[[Target|Alias]]" : null);
assert.equal(rendered[0].elements[1].link, before.elements[1].link);
if (method === "vault") assert.equal(writes.at(-1)[2], JSON.stringify(rendered[0].elements.map(element => element.link)));
});
@@ -0,0 +1,40 @@
import assert from "node:assert/strict";
import test, { after } from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
const graph = sourceHarness();
const { readTableEmbedToken: locate } = await graph.importModule("src/core/editor/tableEmbedSource.ts");
const { rewriteEmbedDimensions, parseEmbedAlias } = await graph.importModule("src/core/editor/embedDimensions.ts");
after(() => graph.close());
test("physical table cells locate repeated escaped embeds without global occurrence matching", () => {
const token = "![[Drawings/Map.excalidraw.md#^frame=Frame name\\|Caption\\|100\\|left]]";
const table = `| Drawing | Note |\n| :--- | ---: |\n| ${token} | first |\n| ${token} | second |\n`;
const first = locate(table, 25, 1, 0, 3, 2), second = locate(table, 25, 2, 0, 3, 2);
assert.equal(first.from, 25 + table.indexOf(token)); assert.equal(second.from, 25 + table.lastIndexOf(token));
assert.equal(second.text, token); assert.equal(second.target, "Drawings/Map.excalidraw.md#^frame=Frame name");
const edited = rewriteEmbedDimensions(second.text, { width: 108 });
assert.equal(edited, token.replace("100", "108"));
assert.equal(table.slice(0, second.from - 25) + edited + table.slice(second.from - 25 + token.length), table.replace(token + " | second", edited + " | second"));
assert.deepEqual(parseEmbedAlias("Caption\\|100\\|left"), { alias: "Caption", width: "100", style: "left" });
});
test("Markdown titles, Unicode, optional outer pipes and escaped code pipes retain exact source", () => {
const token = '![图例\\|50%](<绘图/地图.excalidraw.md#^group=abcdefgh> "Keep title")';
const table = `Drawing | Code\n--- | ---\n ${token} | \`x\\|y\`\n`;
assert.equal(locate(table, 0, 1, 0, 2, 2).text, token);
const header = `| ![[Header\\|80]] | Name |\n| --- | --- |\n`;
assert.equal(locate(header, 10, 0, 0, 1, 2).from, 12);
const slashes = `| Code | Drawing |\n| --- | --- |\n| \\ | ![[Map\\|100]] |\n`;
assert.equal(locate(slashes, 0, 1, 1, 2, 2).text, "![[Map\\|100]]");
});
test("ragged, mismatched, ambiguous, nested and non-embed cells never acquire editable ranges", () => {
const table = "| Image | Note |\n| --- | --- |\n| ![[Map]] | keep |\n";
for (const args of [[0,1,0,3,2], [0,1,0,2,3], [0,2,0,2,2], [-1,1,0,2,2], [0,1,2,2,2]]) assert.equal(locate(table, ...args), null);
for (const source of [
table.replace("--- | ---", "text | ---"), table.replace("| keep |", "| keep | extra |"),
table.replace("![[Map]]", "![[Map]] ![[Map]]"), table.replace("![[Map]]", "`![[Map]]`"),
table.replaceAll("|", "> |"), table + "not part of the table\n",
]) assert.equal(locate(source, 0, 1, 0, 2, 2), null);
assert.equal(locate(table, 0, 1, 1, 2, 2), null);
});
@@ -0,0 +1,21 @@
import assert from "node:assert/strict";
import test,{after} from "node:test";
import {sourceHarness} from "./sourceHarness.mjs";
const requests=[],notices=[];
const graph=sourceHarness({
obsidian:{Notice:class{constructor(value){notices.push(value);}},requestUrl:async request=>{requests.push(request);return {status:200,json:{records:[{text:"recognized"}]}};}},
"src/lang/helpers":{t:key=>key},"src/shared/Frontmatter":{default:class{}},"../EmbeddedFileLoader":{EmbeddedFilesLoader:class{}},
"src/utils/fileUtils":{blobToBase64:async()=>"fake-image"},"src/core":{getEA:()=>{}},"src/utils/debugHelper":{log:()=>{}},
});
after(()=>graph.close());
const {default:Taskbone}=await graph.importModule("src/shared/OCR/Taskbone.ts");
test("Taskbone resolves selected secrets for OCR and does not create or sync replacement keys",async()=>{
requests.length=0;let secret="fake-ocr-secret";
const plugin={app:{secretStorage:{getSecret:()=>secret}},settings:{taskboneAPIkey:"fake-stale",taskboneAPIKeySource:"secret",taskboneAPIKeySecret:"ocr"}};
const taskbone=new Taskbone(plugin);
await taskbone.initialize();assert.equal(requests.length,0);
assert.equal(await taskbone.getTextForImage(new Blob()),"recognized");assert.equal(requests[0].headers.authorization,"Bearer fake-ocr-secret");
secret="rotated";assert.equal(taskbone.apiKey,"rotated");assert.equal(plugin.settings.taskboneAPIkey,"fake-stale");
secret=null;requests.length=0;assert.equal(await taskbone.getTextForImage(new Blob()),undefined);assert.equal(requests.length,0);assert.equal(notices.at(-1),"API_KEY_MISSING");
taskbone.destroy();
});
@@ -4,7 +4,7 @@ import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
const harness = sourceHarness();
const { handleTextSaveShortcut } = await harness.importModule("src/view/managers/textSaveShortcut.ts");
const { handleTextSaveShortcut, handleSaveAsShortcut } = await harness.importModule("src/view/managers/textSaveShortcut.ts");
test.after(() => harness.close());
function fixture() {
@@ -45,3 +45,27 @@ test("submission cannot save a replacement file, API or retiring view", () => {
assert.deepEqual(f.calls, ["preventDefault", "stopPropagation", "flush", "submit", "committed"]);
}
});
test("focused canvas and text editor block Ctrl/Cmd+Shift+S without submitting or saving", () => {
for (const modifier of ["ctrlKey", "metaKey"]) for (const tagName of ["DIV", "TEXTAREA"]) {
const f = fixture(); f.editable.tagName = tagName; f.editable.closest = () => null;
Object.assign(f.event, { ctrlKey: false, [modifier]: true, shiftKey: true, key: "S" });
assert.equal(handleSaveAsShortcut(f.view, f.event), true);
assert.deepEqual(f.calls, ["preventDefault", "stopPropagation"]);
}
});
test("Save As guard leaves other shortcuts, other documents, unfocused views and embedded notes alone", () => {
for (const mutate of [
f => f.event.shiftKey = false, f => f.event.altKey = true,
f => f.event.ctrlKey = false, f => f.event.key = "x",
f => f.editable.ownerDocument = {}, f => f.doc.activeElement = {},
f => f.view.containerEl.contains = () => false,
f => f.editable.closest = selector => selector === ".excalidraw__embeddable-container" ? {} : null,
f => f.view.file = null, f => f.view.excalidrawAPI = null,
f => f.view.isClosingOrMigrating = () => true,
]) {
const f = fixture(); f.event.shiftKey = true; f.editable.closest = () => null; mutate(f);
assert.equal(handleSaveAsShortcut(f.view, f.event), false); assert.deepEqual(f.calls, []);
}
});
+4
View File
@@ -107,6 +107,7 @@ export let {
getBoundTextMaxWidth,
exportToSvg,
exportToBlob,
exportScene,
mutateElement,
restoreElements,
restoreLibraryItems,
@@ -168,6 +169,7 @@ export function updateExcalidrawLib() {
getBoundTextMaxWidth,
exportToSvg,
exportToBlob,
exportScene,
mutateElement,
restoreElements,
restoreLibraryItems,
@@ -311,6 +313,8 @@ export const AUDIO_TYPES = [
export const CODE_TYPES = ["json", "css", "js"];
export const FRONTMATTER_KEYS = {
anchors: { name: "excalidraw-anchors", type: "multitext", depricated: false },
thumbnail: { name: "excalidraw-thumbnail", type: "text", depricated: false },
plugin: { name: "excalidraw-plugin", type: "text", depricated: false },
"export-transparent": {
name: "excalidraw-export-transparent",
+7
View File
@@ -1,6 +1,7 @@
import { Extension } from "@codemirror/state";
import ExcalidrawPlugin from "src/core/main";
import { HideTextBetweenCommentsExtension } from "./Fadeout";
import { createDrawingEmbedExtension } from "./drawingEmbedExtension";
export const EDITOR_FADEOUT = "fadeOutExcalidrawMarkup";
type TaggedExtension = Extension & { exID?: string };
@@ -11,14 +12,20 @@ const editorExtensions: { [key: string]: Extension } = {
export class EditorHandler {
private activeEditorExtensions: TaggedExtension[] = [];
private disposeDrawingEmbeds: (() => void) | null = null;
constructor(private plugin: ExcalidrawPlugin) {}
destroy(): void {
this.disposeDrawingEmbeds?.();
this.disposeDrawingEmbeds = null;
this.plugin = null;
}
setup(): void {
const drawingEmbeds = createDrawingEmbedExtension(this.plugin);
this.activeEditorExtensions.push(drawingEmbeds.extension);
this.disposeDrawingEmbeds = drawingEmbeds.dispose;
this.plugin.registerEditorExtension(this.activeEditorExtensions);
this.updateCMExtensionState(
EDITOR_FADEOUT,
+173
View File
@@ -0,0 +1,173 @@
import { EditorState, type Extension } from "@codemirror/state";
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { editorInfoField, editorLivePreviewField, MarkdownView } from "obsidian";
import type ExcalidrawPlugin from "../main";
import { DrawingEmbedControls } from "../managers/DrawingEmbedControls";
import { getDrawingEmbedActions } from "../managers/drawingEmbedActions";
import { DrawingEmbedSource } from "./embedSource";
import { readDrawingEmbedToken } from "./embedDimensions";
import { readTableEmbedToken } from "./tableEmbedSource";
import type { LocatedDrawingEmbed } from "src/types/drawingEmbedTypes";
interface OwnedEmbed {
image: HTMLElement;
source: DrawingEmbedSource;
controls: DrawingEmbedControls;
}
function isSourceMode(view: EditorView): boolean {
const info = view.state.field(editorInfoField, false);
return (!(info instanceof MarkdownView) || info.getMode() === "source") &&
view.dom.closest<HTMLElement>(".markdown-source-view")?.style.display !== "none";
}
function decodeTarget(target: string): string {
const unescaped = target.replace(/\\([\\[\]()<>!| ])/g, "$1");
try { return decodeURI(unescaped); } catch { return unescaped; }
}
function widgetRange(view: EditorView, element: HTMLElement): { from: number; to: number } | null {
const parent = element.parentNode;
if (!parent) return null;
let from: number, boundaryFrom: number, boundaryTo: number;
try {
const index = Array.from(parent.childNodes).indexOf(element);
from = view.posAtDOM(element, 0);
boundaryFrom = view.posAtDOM(parent, index);
boundaryTo = view.posAtDOM(parent, index + 1);
} catch {
// CodeMirror can retire a widget before its DOM is removed.
return null;
}
if (from !== boundaryFrom || boundaryTo <= from || boundaryTo - from > 16384) return null;
return { from, to: boundaryTo };
}
function readWidgetToken(view: EditorView, element: HTMLElement): LocatedDrawingEmbed | null {
const range = widgetRange(view, element);
if (!range) return null;
const { from, to } = range;
const rangeText = view.state.doc.sliceString(from, to), token = readDrawingEmbedToken(rangeText);
return token && !rangeText.slice(token.text.length).trim() ? { from, text: token.text, target: token.target } : null;
}
function readTableWidgetToken(view: EditorView, root: HTMLElement, table: HTMLTableElement, cell: HTMLTableCellElement): LocatedDrawingEmbed | null {
if (!cell || cell.closest("table") !== table || cell.colSpan !== 1 || cell.rowSpan !== 1) return null;
const row = cell.parentElement as HTMLTableRowElement;
if (row.parentElement?.parentElement !== table) return null;
const range = widgetRange(view, root);
if (!range) return null;
return readTableEmbedToken(view.state.doc.sliceString(range.from, range.to), range.from, row.rowIndex, cell.cellIndex, table.rows.length, table.rows[0]?.cells.length ?? 0);
}
/**
* Public CodeMirror DOM boundaries locate a complete parsed token. Both the
* source file/editor and the renderer's canonical drawing reference must agree.
* A filename match, active file, or document-wide occurrence index is never used.
*/
export function createDrawingEmbedExtension(plugin: ExcalidrawPlugin): { extension: Extension; dispose: () => void } {
let disposed = false;
const instances = new Set<EmbedEditor>();
class EmbedEditor {
private entries = new Map<HTMLElement, OwnedEmbed>();
private observer: MutationObserver;
private scheduled = false;
private active = true;
constructor(private view: EditorView) {
instances.add(this);
const win = view.dom.ownerDocument.defaultView;
this.observer = new win.MutationObserver(() => this.schedule());
this.observer.observe(view.contentDOM, { childList: true, subtree: true });
const source = view.dom.closest<HTMLElement>(".markdown-source-view");
if (source) this.observer.observe(source, { attributes: true, attributeFilter: ["class", "style"] });
this.schedule();
}
update(update: ViewUpdate): void {
if (update.docChanged) for (const entry of this.entries.values()) entry.source.map(update.changes);
if (update.docChanged || update.viewportChanged || update.selectionSet || update.geometryChanged) this.schedule();
}
private schedule(): void {
if (!this.active || disposed || this.scheduled) return;
this.scheduled = true;
// Read widget DOM after the editor's transaction/DOM update has finished.
queueMicrotask(() => { this.scheduled = false; if (this.active && !disposed) this.sync(); });
}
private clear(): void {
for (const entry of this.entries.values()) { entry.source.invalidate(); entry.controls.unload(); }
this.entries.clear();
}
private sync(): void {
const view = this.view, info = view.state.field(editorInfoField, false), sourceFile = info?.file;
if (!sourceFile || !isSourceMode(view) || !view.state.field(editorLivePreviewField, false) ||
view.state.facet(EditorState.readOnly) || !view.state.facet(EditorView.editable)) {
this.clear(); return;
}
const seen = new Set<HTMLElement>();
for (const image of view.contentDOM.querySelectorAll<HTMLElement>(".excalidraw-embedded-img")) {
const nativeEmbed = image.closest<HTMLElement>(".internal-embed"), frame = image.parentElement;
// Native table images also carry internal-embed. Map their physical
// cell through the whole table widget before considering ordinary embeds.
const table = image.closest<HTMLTableElement>("table.table-editor");
const cell = table && image.closest<HTMLTableCellElement>("td, th");
const root = table ? table.closest<HTMLElement>(".cm-table-widget") : nativeEmbed;
const key = table ? frame : nativeEmbed ?? frame;
const actions = getDrawingEmbedActions(image);
if (!root || !frame || !actions || !actions.isCurrent() || image.closest(".cm-content") !== view.contentDOM ||
root.closest(".markdown-embed, .hover-popover, .canvas-node-content, .print, .cm-preview-code-block")) continue;
seen.add(key);
const existing = this.entries.get(key);
if (existing?.image === image && existing.source.isCurrent()) continue;
if (existing) { existing.source.invalidate(); existing.controls.unload(); this.entries.delete(key); }
const token = table ? readTableWidgetToken(view, root, table, cell) : readWidgetToken(view, root);
if (!token) continue;
const from = token.from;
const target = decodeTarget(token.target), hash = target.indexOf("#");
const path = hash < 0 ? target : target.slice(0, hash), reference = hash < 0 ? "" : target.slice(hash);
const drawing = plugin.app.metadataCache.getFirstLinkpathDest(path, sourceFile.path);
if (!drawing || !plugin.isExcalidrawFile(drawing) || decodeTarget(drawing.path + reference) !== decodeTarget(actions.target)) continue;
const sourcePath = sourceFile.path, ownerDocument = view.dom.ownerDocument;
const row = cell?.parentElement as HTMLTableRowElement | undefined;
const rowIndex = row?.rowIndex, columnIndex = cell?.cellIndex;
const source = new DrawingEmbedSource(view, from, from + token.text.length, token.text, () =>
this.active && !disposed && sourceFile.path === sourcePath &&
view.state.field(editorInfoField, false)?.file === sourceFile &&
isSourceMode(view) &&
!!view.state.field(editorLivePreviewField, false) && !view.state.facet(EditorState.readOnly) && view.state.facet(EditorView.editable) &&
frame.isConnected && view.contentDOM.contains(frame) && root.contains(frame) &&
(!table || cell?.parentElement === row && row.rowIndex === rowIndex && cell.cellIndex === columnIndex) &&
frame.ownerDocument === ownerDocument && view.dom.ownerDocument === ownerDocument && actions.isCurrent(),
table ? (from, to) => {
const current = readTableWidgetToken(view, root, table, cell);
return current?.from === from && from + current.text.length === to && current.text === token.text;
} : undefined);
// A renderer may invalidate its generation before replacing the DOM.
// Do not mount a stale binding: mounting/unloading it would schedule
// another DOM sync and starve the renderer's debounce timer.
if (!source.isCurrent()) { source.invalidate(); continue; }
const controls = new DrawingEmbedControls(frame, actions, source);
try { controls.load(); }
catch (error) { source.invalidate(); controls.unload(); throw error; }
this.entries.set(key, { image, source, controls });
}
for (const [element, entry] of this.entries) if (!seen.has(element)) {
entry.source.invalidate(); entry.controls.unload(); this.entries.delete(element);
}
}
destroy(): void {
if (!this.active) return;
this.active = false; this.observer.disconnect(); this.clear(); instances.delete(this);
}
}
return {
extension: ViewPlugin.fromClass(EmbedEditor),
dispose: () => { disposed = true; for (const instance of [...instances]) instance.destroy(); },
};
}
+175
View File
@@ -0,0 +1,175 @@
/** Lossless dimension edits for a single, already-owned Markdown embed token. */
export interface EmbedDimensions {
width?: string;
height?: string;
}
/** Existing drawing aliases may combine a caption, dimensions and a CSS suffix. */
export interface EmbedAliasParts extends EmbedDimensions {
alias?: string;
style?: string;
}
/** A parsed token retains source offsets; its destination and title are never rewritten. */
export interface DrawingEmbedToken {
text: string;
target: string;
aliasFrom: number;
aliasTo: number;
wiki: boolean;
}
/** The renderer's established integer/percentage dimension grammar. */
export function getDimensionsFromAliasString(data: string): EmbedDimensions | null {
const match = data.match(/^(?<width>\d+%|\d+)(x(?<height>\d+%|\d+))?$/)
|| data.match(/^x(?<height>\d+%|\d+)$/);
if (!match) return null;
const { width, height } = match.groups;
if ((width && width.startsWith("0") && width !== "0") ||
(height && height.startsWith("0") && height !== "0")) return null;
return { width: width || undefined, height: height || undefined };
}
/** Preserve the existing renderer's alias/style precedence. */
export function parseEmbedAlias(input: string): EmbedAliasParts {
const parts = input.replace(/\\\|/g, "|").split("|").map(part => part.trim());
const first = getDimensionsFromAliasString(parts[0]);
const second = parts.length > 1 ? getDimensionsFromAliasString(parts[1]) : null;
let result: EmbedAliasParts;
switch (parts.length) {
case 1: return first ?? { style: parts[0] };
case 2:
result = second ? { alias: parts[0], ...second }
: first ? { ...first, style: parts[1] } : { alias: parts[0], style: parts[1] };
break;
default:
result = { alias: parts[0], ...(second ?? {}), style: parts.at(-1) };
}
return Object.fromEntries(Object.entries(result).filter(([, value]) => value !== undefined));
}
/** Parse one token at the start of a source range, leaving any following text alone. */
export function readDrawingEmbedToken(source: string): DrawingEmbedToken | null {
if (source.startsWith("![[")) {
const end = source.indexOf("]]");
if (end < 3 || /[\r\n]/.test(source.slice(0, end))) return null;
const inner = source.slice(3, end);
const pipe = inner.search(/\\?\|/);
const targetEnd = pipe < 0 ? end : 3 + pipe;
const separatorLength = source[targetEnd] === "\\" ? 2 : 1;
return {
text: source.slice(0, end + 2), target: source.slice(3, targetEnd),
aliasFrom: pipe < 0 ? end : targetEnd + separatorLength, aliasTo: end, wiki: true,
};
}
if (!source.startsWith("![")) return null;
let level = 1, close = -1;
for (let i = 2; i < source.length; i++) {
if (source[i] === "\\") { i++; continue; }
if (source[i] === "[") level++;
if (source[i] === "]" && --level === 0) { close = i; break; }
}
if (close < 0 || source[close + 1] !== "(") return null;
let depth = 1, quote = "", angle = false, end = -1;
for (let i = close + 2; i < source.length; i++) {
const char = source[i];
if (char === "\\") { i++; continue; }
if (quote) { if (char === quote) quote = ""; continue; }
if (angle) { if (char === ">") angle = false; continue; }
if (char === "<" && depth === 1) { angle = true; continue; }
if ((char === '"' || char === "'") && /\s/.test(source[i - 1])) { quote = char; continue; }
if (char === "(") depth++;
if (char === ")" && --depth === 0) { end = i; break; }
}
if (end < 0) return null;
const destination = source.slice(close + 2, end).trim();
let target: string;
if (destination.startsWith("<")) {
const angleEnd = destination.indexOf(">");
if (angleEnd < 0) return null;
target = destination.slice(1, angleEnd);
} else {
// Whitespace escaped in a destination belongs to the path, not its title.
const match = destination.match(/^(?:\\.|[^\s])+/);
if (!match) return null;
target = match[0];
}
return { text: source.slice(0, end + 1), target, aliasFrom: 2, aliasTo: close, wiki: false };
}
interface AliasSegment {
from: number;
to: number;
separator: number;
value: string;
}
function aliasSegments(token: DrawingEmbedToken): AliasSegment[] {
const result: AliasSegment[] = [];
let from = token.aliasFrom, separator = token.wiki ? token.aliasFrom - 1 : -1;
const alias = token.text.slice(token.aliasFrom, token.aliasTo);
const pipes = [...alias.matchAll(/\\?\|/g)];
for (const pipe of pipes) {
const to = token.aliasFrom + pipe.index;
result.push({ from, to, separator, value: token.text.slice(from, to).trim() });
separator = to;
from = to + pipe[0].length;
}
result.push({ from, to: token.aliasTo, separator, value: token.text.slice(from, token.aliasTo).trim() });
return result;
}
function dimensionSegment(segments: AliasSegment[]): AliasSegment | undefined {
if (segments.length > 1 && getDimensionsFromAliasString(segments[1].value)) return segments[1];
if (segments.length <= 2 && getDimensionsFromAliasString(segments[0].value)) return segments[0];
}
/** Read explicit sizing without altering aliases, table escapes or destination parameters. */
export function getEmbedDimensions(text: string): EmbedDimensions | null {
const token = readDrawingEmbedToken(text);
if (!token || token.text !== text) return null;
const segment = dimensionSegment(aliasSegments(token));
return segment ? getDimensionsFromAliasString(segment.value) : {};
}
/**
* Replace only the dimension slot. Reset removes that slot and its separator.
* Changed percentages become pixels; callers preserve the displayed aspect ratio.
*/
export function rewriteEmbedDimensions(
text: string,
dimensions: { width: number; height?: number } | null,
): string | null {
const token = readDrawingEmbedToken(text);
if (!token || token.text !== text) return null;
if (dimensions && [dimensions.width, dimensions.height].some(value =>
value !== undefined && (!Number.isInteger(value) || value < 1 || value > 100000))) return null;
const segments = aliasSegments(token), segment = dimensionSegment(segments);
const size = dimensions ? `${dimensions.width}${dimensions.height === undefined ? "" : `x${dimensions.height}`}` : null;
if (segment) {
if (size === segment.value) return text;
if (size === null) {
if (!token.wiki && segment.separator < 0) {
const next = segments[1];
return text.slice(0, segment.from) + text.slice(next ? next.from : segment.to);
}
// A table separator includes its backslash as well as the pipe.
let start = segment.separator;
if (start > 0 && text[start - 1] === "\\") start--;
return text.slice(0, start) + text.slice(segment.to);
}
const start = segment.from + text.slice(segment.from, segment.to).search(/\S/);
return text.slice(0, start) + size + text.slice(start + segment.value.length);
}
if (size === null) return text;
const alias = text.slice(token.aliasFrom, token.aliasTo);
const escaped = /\\\|/.test(text.slice(0, token.aliasTo));
const pipe = escaped ? "\\|" : "|";
if (!alias) {
return text.slice(0, token.aliasFrom) + (token.wiki && token.aliasFrom === 3 + token.target.length ? pipe : "") + size + text.slice(token.aliasTo);
}
// One field is the existing style suffix. With a caption and a suffix, size
// belongs between them; do not discard unknown additional alias fields.
const at = segments.length === 1 ? token.aliasFrom : segments[1].from;
return text.slice(0, at) + size + pipe + text.slice(at);
}
+12
View File
@@ -0,0 +1,12 @@
import { readDrawingEmbedToken } from "./embedDimensions";
import { rewriteDrawingPreviewLink } from "src/utils/drawingPreviewLink";
/** Rewrite only one embed's region override; paths, aliases, titles and table escapes stay byte-identical. */
export function rewriteEmbedFrame(text: string, reference: string | null): string | null {
const token = readDrawingEmbedToken(text);
if (!token || token.text !== text || reference !== null && reference !== "" && !/^[A-Za-z0-9_-]+$/.test(reference)) return null;
const target = token.target, next = rewriteDrawingPreviewLink(target, { frame: reference });
if (next === null) return null;
const from = token.wiki ? 3 : text.indexOf(target, token.aliasTo + 2);
return from < 0 ? null : text.slice(0, from) + next + text.slice(from + target.length);
}
+18
View File
@@ -0,0 +1,18 @@
import { readDrawingEmbedToken } from "./embedDimensions";
import { rewriteDrawingPreviewLink } from "src/utils/drawingPreviewLink";
/** Rewrite a drawing preview's padding; retained name supports existing callers. */
export function withAreaPadding(target: string, padding: number | null): string | null {
return rewriteDrawingPreviewLink(target, { padding });
}
/** Edit the destination parameter of one owned wiki/Markdown/table embed token. */
export function rewriteEmbedPadding(text: string, padding: number | null): string | null {
const token = readDrawingEmbedToken(text);
if (!token || token.text !== text) return null;
const target = withAreaPadding(token.target, padding);
if (target === null) return null;
const from = token.wiki ? 3 : text.indexOf(token.target, token.aliasTo + 2);
if (from < 0) return null;
return text.slice(0, from) + target + text.slice(from + token.target.length);
}
+91
View File
@@ -0,0 +1,91 @@
import { isolateHistory } from "@codemirror/commands";
import { ChangeDesc, EditorSelection, Transaction } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { readDrawingEmbedToken } from "./embedDimensions";
import { rewriteEmbedPadding } from "./embedPadding";
import { rewriteEmbedFrame } from "./embedFrame";
import type { EmbedSourceBinding } from "src/types/drawingEmbedTypes";
/**
* A mapped, validated editor range. The drawing destination never owns these
* writes. Invalidation is permanent so a retired gesture cannot recover by
* accidentally matching a different occurrence later.
*/
export class DrawingEmbedSource implements EmbedSourceBinding {
private valid = true;
constructor(
private readonly view: EditorView,
private from: number,
private to: number,
public readonly text: string,
private readonly ownsSource: () => boolean,
private readonly validateRange?: (from: number, to: number) => boolean,
) {}
/** Track edits before the token; edits inside it retire this binding. */
map(changes: ChangeDesc): void {
if (!this.valid) return;
changes.iterChangedRanges((from, to) => {
if ((from < this.to && to > this.from) ||
(from === to && from > this.from && from < this.to)) this.valid = false;
});
this.from = changes.mapPos(this.from, 1);
this.to = changes.mapPos(this.to, -1);
this.valid = this.isCurrent();
}
/** Revalidate the complete expected token against the current owning editor. */
isCurrent(): boolean {
return this.valid && this.ownsSource() && this.from >= 0 && this.to >= this.from &&
this.to <= this.view.state.doc.length &&
this.view.state.doc.sliceString(this.from, this.to) === this.text;
}
/** Commit a single isolated undoable transaction, retaining the destination. */
replace(text: string): boolean {
if (!this.isCurrent() || this.validateRange && !this.validateRange(this.from, this.to)) return false;
if (text === this.text) return true;
const original = readDrawingEmbedToken(this.text), next = readDrawingEmbedToken(text);
if (!original || !next || next.text !== text || next.target !== original.target || next.wiki !== original.wiki) return false;
return this.commit(text, "input.excalidraw-embed-resize");
}
/** A separate capability changes only padding; general replacement keeps its target guard. */
replacePadding(padding: number | null): boolean {
const text = rewriteEmbedPadding(this.text, padding);
if (!text || !this.isCurrent() || this.validateRange && !this.validateRange(this.from, this.to)) return false;
if (text === this.text) return true;
return this.commit(text, "input.excalidraw-embed-padding");
}
private commit(text: string, userEvent: string): boolean {
this.view.dispatch({
changes: { from: this.from, to: this.to, insert: text },
annotations: [Transaction.userEvent.of(userEvent), isolateHistory.of("full")],
});
this.valid = false;
return true;
}
/** Frame choices can change a region reference without exposing arbitrary destination writes. */
replaceFrame(reference: string | null): boolean {
const text = rewriteEmbedFrame(this.text, reference);
if (!text || !this.isCurrent() || this.validateRange && !this.validateRange(this.from, this.to)) return false;
if (text === this.text) return true;
return this.commit(text, "input.excalidraw-embed-frame");
}
/** Select the containing-note syntax, allowing Live Preview to reveal it. */
select(): boolean {
if (!this.isCurrent() || this.validateRange && !this.validateRange(this.from, this.to)) return false;
this.view.dispatch({ selection: EditorSelection.range(this.from, this.to), scrollIntoView: true });
this.view.focus();
return true;
}
/** Retire a view, widget or gesture without ever writing stale source. */
invalidate(): void {
this.valid = false;
}
}
+49
View File
@@ -0,0 +1,49 @@
import { readDrawingEmbedToken } from "./embedDimensions";
import type { LocatedDrawingEmbed } from "src/types/drawingEmbedTypes";
interface CellRange { from: number; to: number }
/** Table delimiters are unescaped pipes, including inside inline code. */
function cells(line: string): CellRange[] {
const result: CellRange[] = [];
let from = 0, slashes = 0, pipes = 0;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === "|" && slashes % 2 === 0) {
result.push({ from, to: i }); from = i + 1; pipes++;
}
slashes = char === "\\" ? slashes + 1 : 0;
}
if (!pipes) return [];
result.push({ from, to: line.length });
if (!line.slice(result[0].from, result[0].to).trim()) result.shift();
const last = result.at(-1);
if (last && !line.slice(last.from, last.to).trim()) result.pop();
return result;
}
/**
* Locate one complete token in a physical cell of a publicly mapped native
* table widget. Validate the entire rectangular table/DOM shape first; never
* infer the cell from a filename or a document-wide occurrence number.
*/
export function readTableEmbedToken(
source: string, tableFrom: number, row: number, column: number,
rowCount: number, columnCount: number,
): LocatedDrawingEmbed | null {
if (![tableFrom, row, column, rowCount, columnCount].every(Number.isInteger) ||
tableFrom < 0 || row < 0 || row >= rowCount || column < 0 || column >= columnCount ||
rowCount < 1 || columnCount < 1 || source.length > 16384) return null;
const lines = source.split("\n");
while (lines.length && !lines.at(-1).trim()) lines.pop();
if (lines.length !== rowCount + 1) return null;
const rows = lines.map(cells);
if (rows.some(cells => cells.length !== columnCount) ||
!rows[1].every(cell => /^:?-+:?$/.test(lines[1].slice(cell.from, cell.to).trim()))) return null;
const lineIndex = row === 0 ? 0 : row + 1, cell = rows[lineIndex][column];
const raw = lines[lineIndex].slice(cell.from, cell.to), text = raw.trim();
const token = readDrawingEmbedToken(text);
if (!token || token.text !== text) return null;
const offset = lines.slice(0, lineIndex).reduce((length, line) => length + line.length + 1, 0);
return { from: tableFrom + offset + cell.from + raw.search(/\S/), text, target: token.target };
}
+7 -3
View File
@@ -1,4 +1,5 @@
import { ExcalidrawExtrasGateway } from "../utils/ExcalidrawExtrasGateway";
import { DrawingCreationUI } from "./managers/DrawingCreationUI";
import { openSVGImportForEditor } from "src/shared/svgConversionActions";
import { ExcalidrawCLI } from "./managers/ExcalidrawCLI";
import type { ExcalidrawCLIRequest, ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
@@ -172,6 +173,7 @@ const EXCALIDRAW_EXTERNAL_GET_LABEL_KEY_SET = new Set<keyof typeof en>(
export default class ExcalidrawPlugin extends Plugin {
private cli: ExcalidrawCLI;
public extrasGateway: ExcalidrawExtrasGateway;
public drawingCreationUI: DrawingCreationUI;
private fileManager: PluginFileManager;
private observerManager: ObserverManager;
private packageManager: PackageManager;
@@ -452,9 +454,9 @@ export default class ExcalidrawPlugin extends Plugin {
addIcon(ICON_NAME, EXCALIDRAW_ICON);
addIcon(SCRIPTENGINE_ICON_NAME, SCRIPTENGINE_ICON);
addIcon(EXPORT_IMG_ICON_NAME, EXPORT_IMG_ICON);
this.addRibbonIcon(ICON_NAME, t("CREATE_NEW"), (e) =>
this.actionRibbonClick(e),
);
this.drawingCreationUI = this.addChild(new DrawingCreationUI(this, (event) => {
void this.actionRibbonClick(event);
}));
try {
void this.loadSettings().then(() =>
@@ -504,6 +506,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.settingsTab = new ExcalidrawSettingTab(this.app, this);
this.addSettingTab(this.settingsTab);
this.settingsReady = true;
this.drawingCreationUI.refresh();
}
private async onloadOnLayoutReady() {
@@ -1068,6 +1071,7 @@ export default class ExcalidrawPlugin extends Plugin {
const didLoadSettings = await this.settingsManager.loadSettings();
if (didLoadSettings) {
this.stencilLibraryManager?.invalidate();
this.drawingCreationUI?.refresh();
}
}
+11
View File
@@ -807,6 +807,17 @@ export class CommandManager {
},
});
this.addCommand({
id: "navigate-to-frame", name: t("FRAME_NAVIGATE"),
checkCallback: (checking: boolean) => {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
const available = !!view?.getViewElements().some(element => element.type === "frame" && !element.isDeleted);
if (checking) return available;
if (available) view.frameThumbnail.navigate();
return available;
},
});
this.addCommand({
id: "fullscreen",
name: t("TOGGLE_FULLSCREEN"),
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more