Compare commits

...
Author SHA1 Message Date
zsviczian 5f199c99d1 fix: use floating modal for drawing image preview settings 2026-11-22 09:33:52 +01:00
zsviczian 5ffd26c484 Merge pull request #3065 from zsviczian/codex/cli-extras-readiness
Preflight CLI Mermaid dependencies and report optional service readiness
2026-11-22 07:57:36 +01:00
zsviczian 13edf710b0 Merge master into CLI readiness branch and retain both regression suites 2026-11-22 07:49:06 +01:00
zsviczian 9cd48595ae Merge pull request #3066 from zsviczian/2026-11-22-cli-issues-3-6-7
Add CLI selection handoffs, drawing embeds and EA stroke tools
2026-11-22 07:47:52 +01:00
zsviczian 3318f21699 Verify staged stroke persistence and wrapped label read-back 2026-11-22 07:26:48 +01:00
zsviczian 30ac87ceda Validate closed polygon geometry before CLI publication 2026-11-22 07:23:05 +01:00
zsviczian 68e6744e4b Keep native render evidence and use explicit light-theme pixel fixtures 2026-11-22 07:17:57 +01:00
zsviczian e33df8410a Extend CLI authoring and add EA stroke conversion and joining 2026-11-22 07:14:33 +01:00
zsviczian b633803349 Preflight CLI Mermaid dependencies and report optional service readiness 2026-11-22 06:28:16 +01:00
zsviczian 5315636096 2.29.3 2026-11-21 14:08:29 +01:00
zsviczian 899e61a026 0.18.150 2026-11-21 13:20:37 +01:00
zsviczian 63bda424ba edited messages.ts 2026-11-21 11:15:43 +01:00
zsviczian 03e0ecd15f Merge pull request #3064: Fix tools panel and canvas keyboard shortcuts
fix: align tools panel and preserve canvas keyboard shortcuts
2026-11-21 11:06:16 +01:00
52 changed files with 1639 additions and 358 deletions

No files matched your search

+2 -1
View File
@@ -454,13 +454,14 @@ const containerEl = sceneElements.find(
## Validation requirements
- Before launching validation, classify the actual behavior change and state the smallest checks that address its risk. A task label such as "upstream merge", a touched editor file, or an available full-suite command is not sufficient justification for a full profile. State the concrete broad or unresolved risk before escalating. If an oversized run exposes an unrelated failure, preserve it without expanding a localized or mechanical task into its investigation; respect the maintainer's testing limit.
- Treat recoverable native failures as work to diagnose and resolve. Inspect the exact selected sources, locked dependencies, loaded companion versions, pending host requests, owning document/menu renderer and cleanup evidence; fix test infrastructure when it is wrong without weakening product assertions. Rebuild/deploy current workspace artifacts and rerun failed and blocked cases before returning. Preserve failed evidence. If progress actually requires human help (trust, permissions, foreground access or a safe restart), prompt the maintainer promptly instead of silently leaving the lane unfinished. Follow [native recovery](docs/OBSIDIAN_RUNTIME_TESTING.md#recovering-from-native-test-failures).
- Every behavior-changing feature, fix or refactor must add or extend executable tests for its intended behavior and the existing workflows it can affect. For a bug fix, preserve evidence that the regression fails before the fix and passes afterward. Assert observable outcomes; do not substitute registration, inventory, screenshots alone or an implementation-mirroring mock for behavioral evidence.
- Source tests under `scripts/testing/` and `tests/` named `*.test.mjs` are discovered by `test:fast`. Native helpers are not auto-discovered: wire new scenarios into the coordinator/profile and declared required-case/feature mappings. An unreferenced test file provides no executed coverage.
- During implementation, run the affected focused tests and required build after each independently testable checkpoint. Keep `tests/features.json` and `tests/inventory.json` current when coverage or discovery changes. Preserve existing assertions; report unexpected behavior instead of weakening tests or accepting new snapshots automatically.
- Settings/persistence changes need non-default configurations and unknown-key sentinels across actual plugin unload/reload and startup, with both on-disk data and loaded preferences asserted. Calling `loadSettings()` on an existing instance alone does not establish reload preservation. Include pending saves and externally changed data when those lifecycles are affected; preserve backup evidence if an unexpected replacement occurs.
- Select validation by risk and explain the selection. For a localized change, prefer the build, affected source tests and focused native scenarios for the workflows it can actually change. Do not automatically run complete portable or native regression merely because editor input, embeds or another native workflow is touched. Use complete profiles when the change has broad or uncertain impact (for example shared runtime, lifecycle, persistence, packaging or coordinated dependencies), or release acceptance requires them. Label focused and complete evidence accurately; a focused pass is not a complete native pass. Respect a maintainer's instruction to pause or limit testing and record what remains unverified.
- Run the complete portable and native profiles for coordinated release acceptance, after integrating upstream fork changes, and when validating a newly installed Obsidian version, including alphas. Record the actual host version; do not skip a case solely because the host is newer. Repeat complete matching-build runs when the acceptance plan requires them (including #3022); do not impose a new repeat count implicitly on unrelated changes.
- Run the complete portable and native profiles for coordinated release acceptance, upstream integrations with broad or unresolved behavioral impact, and validation of a newly installed Obsidian version, including alphas. An upstream merge that adopts executable code already present in the fork and only removes its fingerprint is mechanical: use the two-parent comparison, relevant inventory checks and required builds; do not start full portable/native profiles. Record the actual host version; do not skip a selected case solely because the host is newer. Repeat complete matching-build runs when the acceptance plan requires them (including #3022); do not impose a new repeat count implicitly on unrelated changes.
- Portable CI runs on pull requests and pushes to `master`. Native CI is an explicitly dispatched, exact-commit workflow on the isolated desktop runner; local native testing is invoked through the documented commands. Neither suite runs inside the shipped plugin during ordinary use. Review the pinned companion revisions in workflows for coordinated changes: a pinned CI combination does not automatically test another repository's latest branch.
- Documentation-only or demonstrably mechanical changes do not require invented behavioral tests. Run their relevant documentation/inventory checks and state why runtime validation is unnecessary. Record the commands, results, source/artifact identities and genuine limitations for every code handoff.
@@ -11,6 +11,7 @@ Put large requests in a visible vault-relative JSON file and pass input="<file>"
Requests in files include apiVersion:1; the native command supplies command. The in-process ea.executeCLI request also includes command.
Use exact drawing paths including extensions. Never assume an active drawing. :open explicitly creates a tab and can run configured drawing scripts.
Loop: :read source=live detail=elements (or detail=images to inventory) → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
For selected targets use :selection with an explicit path/view, or the drawing command Copy selected elements for agent. Retain packet IDs (including bound-label IDs), read those IDs at the packet revision, and apply only authorized targets. A stale packet needs inspection and a fresh revision, never guessed replacement IDs.
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY with the same requestId only when refused before execution; unknown outcomes require read-back.
New skeleton IDs are local labels; use returned idMap actual IDs for updates. Updates reject identity, bindings and asset internals.
Every write requires requestId. Repeat the identical effective request to retrieve its receipt; different content with the same ID fails.
@@ -18,6 +19,8 @@ Every write requires requestId. Repeat the identical effective request to retrie
:api surface=ea name=<method> gives existing EA signatures. :api surface=lib lists the supported installed Lib reference; advanced exports remain available to scripts.
:icons query=<name> discovers installed canonical Lucide names (paged); create icons / apply op=lucide insert editable native groups. groupMap maps logical icon aliases to groupId/elementIds; idMap remains single-element only. Defaults: size=96, strokeColor=#1e1e1e, roughness=1, opacity=100; optional strokeWidth is final scene units. No trusted script is required.
:script requires trusted=true and an explicit existing local script file. utils.input contains args; utils.excalidrawLib is the installed runtime. Await all work; completion does not imply saved drawing.
:status ready describes plugin startup. Inspect extras.components for optional service versions, active/compatible flags and requirements; extras may be null during startup. mindMapBuilder reports the resident script API's available/ready flags without starting it or selecting a view.
One-shot ea.addMermaid preflights Extras and rejects unavailable dependencies with DEPENDENCY_UNAVAILABLE instead of opening an activation modal. Inspect any earlier script writes before retrying.
One-shot EA is cleaned up; utility prompts fail INTERACTION_REQUIRED. Trusted code can still invoke other interactive APIs: this is not a sandbox, timeout cancellation or transaction.
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Disk exports require local Vault assets; use a loaded live source or placeholders for remote assets.
For cheap previews: :read detail=images, then :export imagePolicy={"default":"placeholder","rules":[{"ids":["wanted-id"],"mode":"original"}]}. This is lossless for the underlying drawing, not the preview.
+66 -2
View File
@@ -73,6 +73,38 @@ types are rectangle, ellipse, diamond, text, arrow, line, frame, and stickynote.
Arrow `start`/`end` bindings and frame `children` reference IDs in their batch.
Frames require children and cannot nest. Use `connect` for existing endpoints.
Line skeletons and line `update.set` accept boolean `polygon`. True requires
an explicitly closed contour: at least four points with the last equal to the
first. The CLI does not reshape the path. False retains ordinary line semantics;
a closed path can still fill from its background color. Use a transparent
background to remove fill. Other element types reject this field.
Line/arrow skeletons allow 2–1000 points, with at most 100000
points per batch. Use a request file for dense contours. Ordinary lines do not
accept `strokeLinecap`; custom free-draw styling belongs in an explicit EA script.
Text skeleton `x` is the left/center/right anchor according to `textAlign`;
an existing text element's `update.set.x` is its stored scene coordinate.
## Selected targets for agents
Select canvas objects and run **Excalidraw: Copy selected elements for agent**,
then paste the JSON packet with the requested edit. The read-only native
equivalent is `:selection path="Drawings/Flow.excalidraw.md" view="<view-id>"`.
It requires an open drawing and an explicit view when duplicate views exist;
it does not write the clipboard or drawing.
The packet includes `packetVersion`, `vault`, `path`, `view`, `revision`, and up
to 500 `elements` including bound labels. Entries contain `id`, `type`, `selected`,
`text`, `frameId`, `containerId`, `labelId`, and scene `bounds` as
`[minX,minY,maxX,maxY]`. Related labels have `selected: false` unless selected
directly. This identifies targets after selection changes; it creates no hidden
marks. Frame selection does not implicitly authorize edits to every descendant.
Read the exact IDs at the packet's live `revision` before editing, then use
`expectedRevision` and actual label IDs for text changes. A stale packet requires
fresh inspection of those IDs and their relationships. Never guess replacement
targets from text or position. A migrated/closed view requires explicit resolution
of the same drawing's current view ID.
## Native Lucide icons
Check `status` for `lucideIcons`, then use `icons query=database limit=50` to
@@ -137,18 +169,26 @@ not every later human edit. A handoff is not reported as durable.
| `group` | `ids`; returns a new group ID |
| `ungroup` | `ids`, `groupId`; preserves other groups |
| `imageMetadata` | `id`, `label` (1–80 characters or `null` to clear), `tags` (up to 12 unique short strings or `null`) |
| `image` | `asset`: exact vault PNG/JPEG/GIF/WebP/SVG; optional `id`, `x`, `y`, `scale` (boolean) |
| `image` | `asset`: exact vault PNG/JPEG/GIF/WebP/SVG or recognized Excalidraw drawing; optional `id`, `x`, `y`, `scale`, `anchor` (booleans) |
| `latex` | `text`; optional `id`, `x`, `y`, `scaleX`, `scaleY`; requires compatible enabled Extras MathJax |
| `lucide` | `id`, `icon`; optional `x`, `y`, `size`, `strokeColor`, `strokeWidth`, `roughness`, `opacity`; returns `groupMap` |
`update` accepts x/y/width/height/angle, strokeColor/backgroundColor/fillStyle,
strokeWidth/strokeStyle/roughness/opacity, locked/link, and text/fontSize/fontFamily/
textAlign/verticalAlign. Text fields require a text element; edit the bound label
textAlign/verticalAlign, and line-only boolean polygon. Text fields require a text element; edit the bound label
ID to change its text. Linear resizing and identity, version, binding, frame,
binary, or Markdown-image metadata edits require a trusted script. Unknown
requested fields are rejected; existing custom data is preserved. Delete uses
tombstones and binding cleanup and does not delete attachment files.
Drawing images use the existing EA loader and retain a source link; ordinary
Markdown notes and direct self-embeds are refused. `scale=true` fits the image to
the normal insertion size. With `scale=false`, `anchor=true` (default) retains
the source-size `100%` option; `anchor=false` allows later manual scaling to
survive refresh. Verify the source link, saved/reopened host, and rendered content.
The existing nested-drawing depth limit remains; source edits may need a host
reload to refresh their rendition. Arbitrary `customData` remains script-only.
## Read, render, and recover
`list` returns exact paths. `read` defaults to a summary without asset bodies;
@@ -246,3 +286,27 @@ results fail without claiming rollback. A terminal timeout cannot preempt
arbitrary synchronous code or undo side effects. PDF, Mermaid, SVG import, and
advanced Markdown-image workflows remain available through existing EA/Extras
APIs with their normal dependency and interaction requirements.
### Stroke conversion and concatenation
Discover `convertLineToFreedraw`, `convertFreedrawToLine`, and `concatenateLines`
with `api surface=ea name=...`. These operate only on copied workbench elements;
publish with `await ea.addElementsToView(false, false)` to mark the view dirty,
then `await ea.targetView.save(false)` and verify saved disk content.
They retain IDs, frame/groups and unrelated metadata, and reject unsupported
labels, bindings and arrowheads before mutation. They return JSON-safe results
with point counts and warnings.
Conversion samples rounded line curves in world coordinates instead of retagging
control points. `tolerance` defaults to 0.5 scene units, `maxPoints` to 10000;
`strokeWidth` overrides the nominal-width estimate. Line-to-free-draw accepts
the fork's full `penOptions`. **excalidraw.com ignores custom free-draw options**,
so appearance can differ. Reverse conversion simplifies the centerline to a
polyline and loses pressure, taper, custom caps and outlines. Compare an export.
Concatenation joins 2–100 compatible open lines by nearest endpoints, handles
reversal, rotation and sharp corners, and samples rounded sections. `maxGap`
defaults to 1 scene unit. The first ID survives; other input IDs are staged as
deleted. Styles, frame, groups and metadata must match; disconnected/branching
sets and exceeded budgets are refused without partial deletion. Keep actual
branches separate, then inspect and save the published result.
+10 -10
View File
@@ -5,7 +5,7 @@ Generate HTML, Mermaid, mind maps, editable SVG strokes and images from a canvas
Uses **Excalidraw AI** provider profiles and model preferences, including OpenAI reasoning effort. Configure keys in the plugin (obfuscated vault settings or device-local Obsidian SecretStorage); this script never stores API keys. Your chosen task sends its prompt and, when enabled, selected canvas image to that provider.
Requires Excalidraw 2.29.2 or newer. Open a drawing and run **ExcaliAI**. Preserve that script filename when replacing an older copy so its task library and preferences remain under the same Script Engine settings key.
Requires Excalidraw 2.29.3 or newer. Open a drawing and run **ExcaliAI**. Preserve that script filename when replacing an older copy so its task library and preferences remain under the same Script Engine settings key.
The migration preserves legacy settings and task IDs. Existing JavaScript modal/export orchestration remains in run.js, with import-safe task helpers and typed request helpers. New script UI strings and default prompts are in lang/en.ts; maintained locale files use English fallback for untranslated advanced content.
@@ -17,7 +17,7 @@ Tutorial: https://www.youtube.com/watch?v=A1vrSGBbWgo
Maintained source: https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/excali-ai
Build version: 2026-11-17T17:24:59.281Z
Build version: 2026-11-21T13:00:37.416Z
```javascript
*/
@@ -527,7 +527,7 @@ Build version: 2026-11-17T17:24:59.281Z
scriptFailed: "ExcaliAI could not start. Check that your drawing is open and the selected images are available.",
requestFailed: "ExcaliAI could not complete this task. Check your model settings and try again.",
errorTitle: "Error",
thisScriptRequiresExcalidrawOrLaterPlease: "This script requires Excalidraw 2.23.0 or later. Please update the plugin.",
thisScriptRequiresExcalidrawOrLaterPlease: "This script requires Excalidraw 2.29.3 or later. Please update the plugin.",
textResponse: "Text response",
usesTheTextOrMultimodalModelAnd: "Uses the text or multimodal model and returns structured output such as HTML, Mermaid, a mind map, or Excalidraw strokes.",
writePromptThenGenerateImage: "Write prompt, then generate image",
@@ -720,13 +720,13 @@ Build version: 2026-11-17T17:24:59.281Z
advancedPromptWarning: "Advanced: change this only if you know why.",
reasoningHelp: "Reasoning effort: {effort} (from Excalidraw AI settings).",
reasoningDefault: "API default",
requiresVersion: "This script requires Excalidraw 2.29.2 or later. Please update the plugin."
requiresVersion: "This script requires Excalidraw 2.29.3 or later. Please update the plugin."
};
// src/scripts/excali-ai/lang/de.ts
var de = {
noView: "\xD6ffne zuerst eine Excalidraw-Zeichnung.",
requiresVersion: "Dieses Skript erfordert Excalidraw 2.29.2 oder neuer. Bitte aktualisiere das Plugin.",
requiresVersion: "Dieses Skript erfordert Excalidraw 2.29.3 oder neuer. Bitte aktualisiere das Plugin.",
prompt: "Prompt",
advancedSettings: "{value1} <span>Erweiterte Einstellungen</span>",
systemPrompt: "System-Prompt",
@@ -740,7 +740,7 @@ Build version: 2026-11-17T17:24:59.281Z
// src/scripts/excali-ai/lang/es.ts
var es = {
noView: "Abre primero un dibujo de Excalidraw.",
requiresVersion: "Este script requiere Excalidraw 2.29.2 o posterior. Actualiza el complemento.",
requiresVersion: "Este script requiere Excalidraw 2.29.3 o posterior. Actualiza el complemento.",
prompt: "Instrucciones",
advancedSettings: "{value1} <span>Ajustes avanzados</span>",
systemPrompt: "Instrucciones del sistema",
@@ -754,7 +754,7 @@ Build version: 2026-11-17T17:24:59.281Z
// src/scripts/excali-ai/lang/fr.ts
var fr = {
noView: "Ouvrez d\u2019abord un dessin Excalidraw.",
requiresVersion: "Ce script n\xE9cessite Excalidraw 2.29.2 ou une version ult\xE9rieure. Mettez le plugin \xE0 jour.",
requiresVersion: "Ce script n\xE9cessite Excalidraw 2.29.3 ou une version ult\xE9rieure. Mettez le plugin \xE0 jour.",
prompt: "Instruction",
advancedSettings: "{value1} <span>Param\xE8tres avanc\xE9s</span>",
systemPrompt: "Instruction syst\xE8me",
@@ -768,7 +768,7 @@ Build version: 2026-11-17T17:24:59.281Z
// src/scripts/excali-ai/lang/ru.ts
var ru = {
noView: "\u0421\u043D\u0430\u0447\u0430\u043B\u0430 \u043E\u0442\u043A\u0440\u043E\u0439\u0442\u0435 \u0440\u0438\u0441\u0443\u043D\u043E\u043A Excalidraw.",
requiresVersion: "\u0414\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0441\u043A\u0440\u0438\u043F\u0442\u0430 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F Excalidraw 2.29.2 \u0438\u043B\u0438 \u043D\u043E\u0432\u0435\u0435. \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u0435 \u043F\u043B\u0430\u0433\u0438\u043D.",
requiresVersion: "\u0414\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0441\u043A\u0440\u0438\u043F\u0442\u0430 \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F Excalidraw 2.29.3 \u0438\u043B\u0438 \u043D\u043E\u0432\u0435\u0435. \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u0435 \u043F\u043B\u0430\u0433\u0438\u043D.",
prompt: "\u0417\u0430\u043F\u0440\u043E\u0441",
advancedSettings: "{value1} <span>\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438</span>",
systemPrompt: "\u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u0437\u0430\u043F\u0440\u043E\u0441",
@@ -782,7 +782,7 @@ Build version: 2026-11-17T17:24:59.281Z
// src/scripts/excali-ai/lang/zh-cn.ts
var zhCn = {
noView: "\u8BF7\u5148\u6253\u5F00 Excalidraw \u7ED8\u56FE\u3002",
requiresVersion: "\u6B64\u811A\u672C\u9700\u8981 Excalidraw 2.29.2 \u6216\u66F4\u65B0\u7248\u672C\u3002\u8BF7\u66F4\u65B0\u63D2\u4EF6\u3002",
requiresVersion: "\u6B64\u811A\u672C\u9700\u8981 Excalidraw 2.29.3 \u6216\u66F4\u65B0\u7248\u672C\u3002\u8BF7\u66F4\u65B0\u63D2\u4EF6\u3002",
prompt: "\u63D0\u793A\u8BCD",
advancedSettings: "{value1} <span>\u9AD8\u7EA7\u8BBE\u7F6E</span>",
systemPrompt: "\u7CFB\u7EDF\u63D0\u793A\u8BCD",
@@ -888,7 +888,7 @@ Build version: 2026-11-17T17:24:59.281Z
loadExcaliAISettings
} = createTaskHelpers(t);
let dirty = false;
if (!ea2.verifyMinimumPluginVersion || !ea2.verifyMinimumPluginVersion("2.29.2")) {
if (!ea2.verifyMinimumPluginVersion || !ea2.verifyMinimumPluginVersion("2.29.3")) {
new Notice(t("requiresVersion"));
return;
}
+1 -1
View File
@@ -537,7 +537,7 @@
},
{
"fname": "ExcaliAI.md",
"mtime": 1794869591004
"mtime": 1795266037499
},
{
"fname": "ExcaliAI.svg",
+1 -1
View File
@@ -467,7 +467,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/ExcaliAI.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/ExcaliAI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Generate HTML, diagrams, editable SVG strokes and images using your configured AI providers, including OpenAI reasoning effort. Maintained in <a href="https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/excali-ai">ea-scripts</a>.<br><a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:400px;"></a><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/ExcaliAI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Generate HTML, diagrams, editable SVG strokes and images using your configured AI providers, including OpenAI reasoning effort. Requires Excalidraw 2.29.3 or newer. Maintained in <a href="https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/excali-ai">ea-scripts</a>.<br><a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:400px;"></a><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
## Excalidraw Writing Machine
```excalidraw-script-install
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.29.2",
"version": "2.29.3",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.29.2",
"version": "2.29.3",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+4 -4
View File
@@ -13,7 +13,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.149",
"@zsviczian/excalidraw": "0.18.150",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -5039,9 +5039,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.149",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.149.tgz",
"integrity": "sha512-+jM4orS+L+vd2fN8EqxXpOL8x/lc+TOq0Hailbkyu2mg7bVqfsn/Abu+p4k2WYvTWCit/pR7WT858Os5PzJ6kg==",
"version": "0.18.150",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.150.tgz",
"integrity": "sha512-iHBp4hAVmHJTXpHFabMl9ruOQchMWQQ6cDX34EHHGcOczewg+7yeK/g3HnsDImzids7bPwEYmENQofqgZ/5GFw==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
+1 -1
View File
@@ -69,7 +69,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.149",
"@zsviczian/excalidraw": "0.18.150",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
+154 -3
View File
@@ -7,6 +7,7 @@ import { transpileModule, ModuleKind, createSourceFile, ScriptTarget, SyntaxKind
function harness({ supported = true, desktop = true, native = true } = {}) {
const cache = new Map(), registrations = new Map(), versionChecks = []; let nextId = 0;
const window = {};
class View {}
class File { constructor(path) { this.path = path; this.extension = path.split('.').at(-1); this.stat = { size: 1 }; } }
const files = [new File('a.excalidraw.md'), new File('Drawings/b.excalidraw.md')];
@@ -15,6 +16,7 @@ function harness({ supported = true, desktop = true, native = true } = {}) {
app: { vault: { getName: () => 'Test', getFileByPath: path => files.find(file => file.path === path), getFiles: () => files,
read: async file => file.content ?? '{}' }, workspace: { getLeavesOfType: () => [] } },
isExcalidrawFile: file => file.path.endsWith('.excalidraw.md'), getCLIRuntime: () => ({ convertToExcalidrawElements() {} }),
extrasGateway: { getStatus: () => ({ installed: false, enabled: false, pluginVersion: null, components: {} }) },
...(native ? { registerCliHandler: (name, desc, flags, fn) => { assert.ok(desc); assert.ok(flags); registrations.set(name, fn); } } : {}),
};
const mocks = {
@@ -32,20 +34,147 @@ function harness({ supported = true, desktop = true, native = true } = {}) {
if (cache.has(file)) return cache.get(file).exports;
const module = { exports: {} }; cache.set(file, module);
const compiled = transpileModule(readFileSync(file, 'utf8'), { compilerOptions: { module: ModuleKind.CommonJS, target: 9 } }).outputText;
new Function('require', 'exports', 'module', compiled)(specifier => load(specifier, resolve(file, '..')), module.exports, module);
new Function('require', 'exports', 'module', 'window', compiled)(specifier => load(specifier, resolve(file, '..')), module.exports, module, window);
return module.exports;
}
const protocol = load('src/core/cli/cliProtocol');
const { ExcalidrawCLI } = load('src/core/managers/ExcalidrawCLI');
return { manager: new ExcalidrawCLI(plugin), protocol, icons: load('src/core/cli/cliIcons'), elements: load('src/core/cli/cliElements'), apply: load('src/core/cli/cliApply'), exporting: load('src/core/cli/cliExport'), images: load('src/core/cli/cliImages'), dimensions: load('src/core/cli/cliImageDimensions'), dependencies: load('src/core/cli/cliDependencies'), customData: load('src/utils/elementCustomDataUtils'), plugin, registrations, versionChecks, files, View, mocks };
return { manager: new ExcalidrawCLI(plugin), protocol, scriptContext: load('src/core/cli/cliScriptContext'), window, icons: load('src/core/cli/cliIcons'), elements: load('src/core/cli/cliElements'), apply: load('src/core/cli/cliApply'), exporting: load('src/core/cli/cliExport'), images: load('src/core/cli/cliImages'), dimensions: load('src/core/cli/cliImageDimensions'), dependencies: load('src/core/cli/cliDependencies'), customData: load('src/utils/elementCustomDataUtils'), plugin, registrations, versionChecks, files, View, mocks };
}
const request = (command, values = {}) => ({ apiVersion: 1, command, ...values });
test('status reports optional services without activating Extras or starting Builder', async () => {
const h = harness();
assert.deepEqual((await h.manager.execute(request('status'))).data.mindMapBuilder, { available: false, ready: false });
h.window.MindMapBuilderAPI = { ready: () => true, setView: () => assert.fail('status retargeted Builder') };
const extras = { components: { mermaid: { version: '3.0.0', compatible: false, active: true } } };
h.plugin.extrasGateway.getStatus = () => extras;
const result = await h.manager.execute(request('status'));
assert.equal(result.ok, true); assert.equal(result.data.ready, true);
assert.deepEqual(result.data.extras, extras);
assert.deepEqual(result.data.mindMapBuilder, { available: true, ready: true });
assert.equal(result.mutation, 'not-applied');
h.window.MindMapBuilderAPI.ready = () => { throw Error('retired script'); };
assert.deepEqual((await h.manager.execute(request('status'))).data.mindMapBuilder, { available: true, ready: false });
h.plugin.isReady = false; delete h.plugin.extrasGateway;
const startup = await h.manager.execute(request('status'));
assert.equal(startup.ok, true); assert.equal(startup.data.ready, false); assert.equal(startup.data.extras, null);
});
test('CLI Mermaid dependency refusal preserves prior script uncertainty and clears invocation context', async () => {
const h = harness(), ea = { destroy() {} };
const file = h.files[0]; file.content = 'await ea.addMermaid(utils.input);';
h.plugin.ea = { getAPI: () => ea };
h.plugin.scriptEngine = { executeScriptFileForCLI: async (file, view, actualEA, input, lib, source, check) => {
check(); assert.equal(h.scriptContext.isCLIScript(actualEA), true);
throw new h.protocol.CLIError('DEPENDENCY_UNAVAILABLE', 'Mermaid 3.6.0 required', undefined, 'Update Extras');
} };
const result = await h.manager.execute(request('script', { script: file.path, trusted: true, requestId: 'missing-mermaid' }));
assert.equal(result.error.code, 'DEPENDENCY_UNAVAILABLE');
assert.equal(result.error.recovery, 'Update Extras');
assert.equal(result.mutation, 'unknown'); assert.equal(result.persistence, 'unknown');
assert.equal(h.scriptContext.isCLIScript(ea), false);
});
test('CLI script JSON return failures remain recoverable without repeating already executed work', async () => {
const h = harness(), file = h.files[0]; file.content = 'return an API result;';
h.plugin.ea = { getAPI: () => ({ destroy() {} }) };
let executions = 0;
h.plugin.scriptEngine = { executeScriptFileForCLI: async (f, v, ea, args, lib, source, check) => {
check(); executions++; return executions === 1 ? { arrowId: undefined, nodeId: 'saved' } : JSON.parse(JSON.stringify({ arrowId: undefined, nodeId: 'saved' }));
} };
const input = request('script', { script: file.path, trusted: true, requestId: 'undefined-result' });
const result = await h.manager.execute(input);
assert.equal(result.error.code, 'OUTCOME_UNKNOWN'); assert.equal(result.persistence, 'unknown');
assert.deepEqual(await h.manager.execute(input), result); assert.equal(executions, 1);
const safe = await h.manager.execute({ ...input, requestId: 'safe-result' });
assert.equal(safe.ok, true); assert.deepEqual(safe.data, { nodeId: 'saved' });
});
function authoringView(h, initial = []) {
let elements = structuredClone(initial), selected = {};
const model = { textElements: new Map(), markdownImages: new Map(), equations: new Map(), mermaids: new Map(),
getFileEntries: () => [], exportPreparedSaveData: () => ({ files: [] }) };
const view = Object.assign(new h.View(), { id: 'owned-view', file: h.files[0], plugin: h.plugin, excalidrawData: model,
isLoaded: true, isClosingOrMigrating: () => false, isSameFileEditingActive: () => false, isPersistenceBusy: () => false,
getScene: () => ({ elements, appState: {}, files: {} }), isDirty: () => false,
excalidrawAPI: { getSceneElements: () => elements, getSceneElementsIncludingDeleted: () => elements, getFiles: () => ({}), getAppState: () => ({ selectedElementIds: selected }) },
addElements: async options => { options.validateBeforePublish(); elements = structuredClone(options.newElements); return true; },
saveWithOutcome: async () => ({ requestedRevision: 1, acknowledgedRevision: 1, currentRevision: 1, status: 'persisted' }),
});
h.plugin.app.workspace.getLeavesOfType = () => [{ view }];
const lib = { getCommonBounds: ([e]) => [e.x, e.y, e.x + e.width, e.y + e.height],
mutateElement: (element, map, set) => { Object.assign(element, set); element.version++; },
convertToExcalidrawElements: skeletons => skeletons.map(e => ({ ...e, groupIds: [], version: 1 })) };
h.plugin.getCLIRuntime = () => lib;
const ea = { elementsDict: {}, imagesDict: {}, setView() {}, getElements() { return Object.values(this.elementsDict); },
copyViewElementsToEAforEditing(values) { for (const e of structuredClone(values)) this.elementsDict[e.id] = e; } };
return { view, ea, lib, select: value => { selected = value; } };
}
test('polygon skeletons and updates support dense bounded line contours without accepting foreign fields', async () => {
const h = harness(), points = Array.from({ length: 250 }, (_, i) => [i, i % 5]);
points[249] = [...points[0]];
assert.doesNotThrow(() => h.elements.validateBatch([{ type: 'line', points, polygon: true }]));
assert.throws(() => h.elements.validateBatch([{ type: 'arrow', polygon: true }]));
assert.throws(() => h.elements.validateBatch([{ type: 'line', polygon: 'yes' }]));
assert.throws(() => h.elements.validateBatch([{ type: 'line', points: Array(1001).fill([0, 0]) }]));
assert.throws(() => h.elements.validateBatch([{ type: 'line', strokeLinecap: 'round' }]));
assert.throws(() => h.elements.validateBatch([{ type: 'line', points: points.slice(0, -1), polygon: true }]), error => error.field === 'polygon');
assert.throws(() => h.elements.validateBatch([{ type: 'line', points: [[0, 0], [1, 1], [0, 0]], polygon: true }]));
assert.equal(h.apply.validateOperations([{ op: 'update', id: 'line', set: { polygon: false } }]).length, 1);
const a = authoringView(h, [{ id: 'line', type: 'line', points: [[0, 0], [50, 0], [50, 50]], x: 0, y: 0, width: 50, height: 50 }]);
const run = () => h.apply.applyDrawing(h.manager, { path: a.view.file.path, expectedRevision: h.manager.targets.revision(a.view), operations: [{ op: 'update', id: 'line', set: { polygon: true } }] }, a.ea);
await assert.rejects(run(), error => error.field === 'polygon');
});
test('selection packets capture exact targets and bound labels independently of later selection', async () => {
const h = harness(), a = authoringView(h, [
{ id: 'shape', type: 'rectangle', x: 10, y: 20, width: 100, height: 60, frameId: 'frame', boundElements: [{ id: 'label', type: 'text' }] },
{ id: 'label', type: 'text', text: 'Target', containerId: 'shape', x: 20, y: 30, width: 80, height: 20 },
{ id: 'other', type: 'rectangle', x: 300, y: 0, width: 40, height: 40 },
]);
a.select({ shape: true });
const result = await h.manager.execute(request('selection', { path: a.view.file.path, view: a.view.id }));
assert.equal(result.ok, true, JSON.stringify(result));
const packet = result.data;
assert.equal(packet.vault, 'Test'); assert.equal(packet.view, a.view.id);
assert.deepEqual(packet.elements.map(e => e.id), ['shape', 'label']);
assert.equal(packet.elements[0].labelId, 'label'); assert.equal(packet.elements[0].text, 'Target');
assert.deepEqual(packet.elements[0].bounds, [10, 20, 110, 80]);
assert.equal(packet.elements[1].selected, false);
a.select({});
const read = await h.manager.execute(request('read', { path: packet.path, view: packet.view, source: 'live', ids: packet.elements.map(e => e.id), revision: packet.revision, detail: 'elements' }));
assert.equal(read.ok, true); assert.equal(read.data.total, 2);
assert.equal((await h.manager.execute(request('selection', { path: packet.path }))).error.code, 'INVALID_INPUT');
});
test('drawing image insertion keeps links and anchor options while refusing ordinary Markdown and source races', async () => {
for (const mode of ['drawing', 'markdown', 'self', 'changed']) {
const h = harness(), a = authoringView(h);
const asset = new h.files[0].constructor(mode === 'markdown' ? 'Notes/Plain.md' : mode === 'self' ? a.view.file.path : 'Maps/Source.excalidraw.md');
if (mode !== 'self') h.files.push(asset);
let published = false, called = false;
a.view.addElements = async options => { options.validateBeforePublish(); published = true; return true; };
a.ea.addImage = async (x, y, file, scale, anchor) => {
called = true; assert.equal(file, asset); assert.equal(scale, false); assert.equal(anchor, false);
if (mode === 'changed') asset.stat.size++;
a.ea.elementsDict.image = { id: 'image', type: 'image', version: 1, groupIds: [] }; return 'image';
};
const revision = h.manager.targets.revision(a.view);
const run = () => h.apply.applyDrawing(h.manager, { path: a.view.file.path, expectedRevision: revision,
operations: [{ op: 'image', id: 'embed', asset: asset.path, scale: false, anchor: false }] }, a.ea);
if (mode === 'drawing') { const result = await run(); assert.equal(result.persistence, 'saved'); assert.equal(result.data.idMap.embed, 'image'); }
else { await assert.rejects(run(), error => error.code === (mode === 'changed' ? 'STALE_REVISION' : 'INVALID_INPUT')); assert.equal(published, false); }
assert.equal(called, mode === 'drawing' || mode === 'changed');
}
});
test('registration validates minimum API, optional method and desktop without bumping the baseline', () => {
for (const options of [{ supported: false }, { native: false }, { desktop: false }]) {
const h = harness(options); h.manager.initialize(); assert.equal(h.registrations.size, 0);
}
const h = harness(); h.manager.initialize(); assert.equal(h.registrations.size, 15);
const h = harness(); h.manager.initialize(); assert.equal(h.registrations.size, 16);
assert.deepEqual(h.versionChecks, ['1.12.2']);
});
@@ -192,6 +321,28 @@ function productionMethod(path, className, name, dependencies = {}) {
return exports.Loaded.prototype[name];
}
test('addMermaid rejects unavailable CLI dependencies before the interactive converter while manual calls retain it', async () => {
const h = harness(); let conversions = 0;
const convert = productionMethod('src/shared/ExcalidrawAutomate.ts', 'ExcalidrawAutomate', 'addMermaid', {
isCLIScript: h.scriptContext.isCLIScript, CLIError: h.protocol.CLIError,
mermaidToExcalidraw: async () => { conversions++; return { elements: [] }; },
});
const api = { features: { isActive: () => true } };
const gateway = { getAPI: () => api, checkVersion: () => ({ valid: true }) };
const ea = { plugin: { extrasGateway: gateway }, style: { fontSize: 20, roundness: null } };
for (const state of ['missing', 'incompatible', 'disabled']) {
gateway.getAPI = () => state === 'missing' ? null : api;
gateway.checkVersion = () => ({ valid: state !== 'incompatible' });
api.features.isActive = () => state !== 'disabled';
await assert.rejects(h.scriptContext.withCLIScriptContext(ea, () => convert.call(ea, 'graph TD; A-->B')), error => error.code === 'DEPENDENCY_UNAVAILABLE');
assert.equal(conversions, 0); assert.equal(h.scriptContext.isCLIScript(ea), false);
}
await convert.call(ea, 'graph TD; A-->B'); assert.equal(conversions, 1);
gateway.getAPI = () => api; gateway.checkVersion = () => ({ valid: true }); api.features.isActive = () => true;
await h.scriptContext.withCLIScriptContext(ea, () => convert.call(ea, 'graph TD; A-->B'));
assert.equal(conversions, 2);
});
test('delayed text preparation leaves concurrent metadata and the scene intact when publication is rejected', async () => {
let resume;
const waiting = new Promise(resolve => { resume = resolve; });
+18
View File
@@ -29,3 +29,21 @@ for (const [version, accepted] of [["2.2.2", false], ["3.0.0", false], ["3.1.0",
}
});
}
test('Extras status exposes component versions and compatibility without loading or enabling services', () => {
const api = { versions: { mermaid: '3.0.0', mathjax: '1.1.0', pdf: '1.0.0', filesystem: '1.0.0' },
features: { isActive: () => true, enable: () => assert.fail('status enabled a service') },
mermaid: { getModule: () => assert.fail('status loaded Mermaid') } };
const app = { plugins: { manifests: { 'excalidraw-extras': { version: '0.1.2' } }, plugins: { 'excalidraw-extras': { api } } } };
const gateway = new exports.ExcalidrawExtrasGateway(app, {});
let result = gateway.getStatus();
assert.equal(result.enabled, true); assert.equal(result.pluginVersion, '0.1.2');
assert.equal(result.components.mermaid.version, '3.0.0');
assert.equal(result.components.mermaid.requiredVersion, '3.6.0');
assert.equal(result.components.mermaid.exact, true); assert.equal(result.components.mermaid.compatible, false);
assert.equal(result.components.mathjax.compatible, true);
api.versions.mermaid = '3.6.0'; result = gateway.getStatus();
assert.equal(result.components.mermaid.compatible, true);
delete app.plugins.plugins['excalidraw-extras']; result = gateway.getStatus();
assert.equal(result.enabled, false); assert.equal(result.components.mermaid.version, null); assert.equal(result.components.mermaid.active, false);
});
@@ -0,0 +1,47 @@
import assert from "node:assert/strict";
import test from "node:test";
import { sourceHarness } from "./sourceHarness.mjs";
test("closing a floating modal before deferred setup cancels its listeners and positioning", async () => {
const previousWindow = globalThis.window, previousDocument = globalThis.mainDocument;
const pending = new Map(); let nextId = 0, setups = 0;
const win = {
innerWidth: 1000, innerHeight: 800,
setTimeout(callback) { const id = ++nextId; pending.set(id, callback); return id; },
clearTimeout(id) { pending.delete(id); },
};
const doc = Object.assign(new EventTarget(), { defaultView: win, body: {}, activeElement: null });
const element = () => Object.assign(new EventTarget(), {
ownerDocument: doc, style: {},
addClass() { setups++; }, setAttr() {}, querySelector() { return null; },
getBoundingClientRect() { return { width: 200, height: 100 }; },
});
class Modal {
constructor(app) { this.app = app; this.modalEl = element(); this.containerEl = element(); this.bgEl = element(); }
setDimBackground() {} open() {} close() {}
}
globalThis.window = win; globalThis.mainDocument = doc;
const graph = sourceHarness({
obsidian: { Modal },
"src/utils/styleUtils": { setStyle: (el, styles) => Object.assign(el.style, styles) },
"src/utils/coreUtils": { errorlog(error) { throw error; } },
"src/utils/typechecks": {
isInstanceOfHTMLButtonElement: () => false, isInstanceOfHTMLInputElement: () => false,
isInstanceOfHTMLSelectElement: () => false, isInstanceOfHTMLTextAreaElement: () => false,
},
});
try {
const { FloatingModal } = await graph.importModule("src/shared/Dialogs/FloatingModal.ts");
const modal = new FloatingModal({ keymap: { popScope() {} } });
modal.open(); assert.equal(pending.size, 1);
modal.close(); assert.equal(pending.size, 0);
for (const callback of pending.values()) callback();
assert.equal(setups, 0);
modal.close();
assert.equal(pending.size, 0);
} finally {
graph.close();
if (previousWindow === undefined) delete globalThis.window; else globalThis.window = previousWindow;
if (previousDocument === undefined) delete globalThis.mainDocument; else globalThis.mainDocument = previousDocument;
}
});
@@ -0,0 +1,173 @@
/** Real native packets, filled contours, drawing embeds and public EA stroke workflows. */
import assert from 'node:assert/strict';
import { createNativeCLIActions } from './nativeCLITransport.mjs';
import { runInAppTask } from './inAppTask.mjs';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
export async function runCLIAuthoringExtensions({ cli, drawingPath, reportDir }) {
const prefix = drawingPath.replace(/\.excalidraw\.md$/, '') + '_authoring';
assert.ok(prefix.split('/').at(-1).startsWith('__excalidraw_cli_smoke_'));
const files = { host: prefix + '.excalidraw.md', request: prefix + '_request.json', source: prefix + '_source.excalidraw.md', note: prefix + '_plain.md', filled: prefix + '_filled.png', open: prefix + '_open.png', embed: prefix + '_embed.png', overview: prefix + '_overview.png', svg: prefix + '.svg' };
const { action, recoveries } = createNativeCLIActions(cli);
const ok = r => { assert.equal(r.ok, true, JSON.stringify(r)); return r; };
const id = suffix => prefix.slice(-30) + '-' + suffix;
const evaluate = code => JSON.parse(cli('eval', 'code=' + code).trim().replace(/^=>\s*/, ''));
const read = () => ok(action('read', { path: files.host, source: 'live', detail: 'elements' })).data;
let strokeResults;
try {
ok(action('create', { requestId: id('source'), path: files.source, elements: [{ type: 'rectangle', x: 0, y: 0, width: 200, height: 90, backgroundColor: '#1971c2', fillStyle: 'solid', label: { text: 'Embedded mind map' } }] }));
const points = Array.from({ length: 250 }, (_, i) => [80 * (Math.cos(i / 249 * Math.PI * 2) - 1), 60 * Math.sin(i / 249 * Math.PI * 2)]);
points[249] = [...points[0]];
const hostRequest = { apiVersion: 1, requestId: id('host'), path: files.host, elements: [
{ id: 'contour', type: 'line', x: 240, y: 100, width: 160, height: 120, polygon: true, points, roughness: 0, strokeColor: '#ff0000', backgroundColor: '#ff0000', fillStyle: 'solid' },
{ id: 'target', type: 'rectangle', x: 400, y: 0, width: 180, height: 80, label: { text: 'Selected target' } },
{ id: 'unrelated', type: 'ellipse', x: 400, y: 200, width: 80, height: 80 },
{ id: 'frame', type: 'frame', children: ['target'], name: 'Packet frame' },
] };
evaluate(`(async()=>{await app.vault.create(${JSON.stringify(files.request)},${JSON.stringify(JSON.stringify(hostRequest))});return JSON.stringify({written:true})})()`);
const created = ok(action('create', hostRequest, files.request));
const opened = ok(action('open', { path: files.host })).data;
const targetId = created.data.idMap.target, polygonId = created.data.idMap.contour;
evaluate(`(()=>{const v=app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.id===${JSON.stringify(opened.viewId)}).view;v.updateScene({appState:{selectedElementIds:{[${JSON.stringify(targetId)}]:true}},captureUpdate:'NEVER'});return JSON.stringify({selected:true})})()`);
const packet = ok(action('selection', { path: files.host, view: opened.viewId })).data;
assert.equal(packet.elements.length, 2); assert.equal(packet.elements.find(e => e.id === targetId).frameId, created.data.idMap.frame);
const labelId = packet.elements.find(e => e.id === targetId).labelId;
assert.ok(labelId && packet.elements.some(e => e.id === labelId && e.containerId === targetId));
const copied = await runInAppTask({ cli, execute: copyAndClearSelection, args: [files.host, [targetId], false], timeoutMs: 30000 });
assert.deepEqual(copied.packet, packet);
const selectedRead = ok(action('read', { path: packet.path, view: packet.view, source: 'live', detail: 'elements', revision: packet.revision, ids: packet.elements.map(e => e.id) })).data;
assert.equal(selectedRead.total, 2);
const unrelatedBefore = read().elements.find(e => e.id === created.data.idMap.unrelated);
ok(action('apply', { requestId: id('targeted'), path: files.host, view: packet.view, expectedRevision: selectedRead.revision, operations: [{ op: 'update', id: labelId, set: { text: 'Packet label edited' } }] }));
// Existing EA publication bumps version metadata on staged copies; all unrelated content must remain identical.
const content = ({ version, versionNonce, updated, ...element }) => element;
assert.deepEqual(content(read().elements.find(e => e.id === created.data.idMap.unrelated)), content(unrelatedBefore));
assert.equal(action('apply', { requestId: id('stale-packet'), path: files.host, expectedRevision: packet.revision, operations: [{ op: 'update', id: targetId, set: { opacity: 20 } }] }).error.code, 'STALE_REVISION');
if (process.env.EXCALIDRAW_CLI_POPOUT === '1') {
const popout = await runInAppTask({ cli, execute: copyAndClearSelection, args: [files.host, [targetId], true], timeoutMs: 45000 });
assert.notEqual(popout.packet.view, packet.view); assert.equal(popout.packet.path, files.host);
assert.deepEqual(popout.packet.elements.map(e => e.id), packet.elements.map(e => e.id));
}
ok(action('apply', { requestId: id('embed'), path: files.host, expectedRevision: read().revision, operations: [{ op: 'image', id: 'embed', asset: files.source, x: 20, y: 300, scale: false, anchor: true }] }));
const embedded = evaluate(`(async()=>{const v=app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.id===${JSON.stringify(opened.viewId)}).view;const image=v.getViewElements().find(e=>e.type==='image'),ef=v.excalidrawData.getFile(image.fileId);await app.vault.create(${JSON.stringify(files.note)},'An ordinary note');return JSON.stringify({source:ef.file.path,text:await app.vault.read(v.file)})})()`);
assert.equal(embedded.source, files.source); assert.ok(embedded.text.includes('|100%'));
const image = read().elements.find(e => e.type === 'image');
ok(action('export', { requestId: id('embed-png'), path: files.host, source: 'live', out: files.embed, theme: 'light', area: { x: image.x, y: image.y, width: image.width, height: image.height }, padding: 0 }));
const embedPixels = await runInAppTask({ cli, execute: redPixels, args: [files.embed], timeoutMs: 30000 });
assert.ok(embedPixels.blue > embedPixels.total * 0.3, JSON.stringify(embedPixels));
for (const asset of [files.note, files.host]) assert.equal(action('apply', { requestId: id(asset === files.note ? 'plain-note' : 'self'), path: files.host, expectedRevision: read().revision, operations: [{ op: 'image', asset }] }).error.code, 'INVALID_INPUT');
const area = { x: 150, y: 90, width: 20, height: 20 };
ok(action('export', { requestId: id('filled'), path: files.host, source: 'live', out: files.filled, theme: 'light', area, padding: 0 }));
const filled = await runInAppTask({ cli, execute: redPixels, args: [files.filled], timeoutMs: 30000 });
assert.ok(filled.red > filled.total * 0.8, JSON.stringify(filled));
assert.equal(read().elements.find(e => e.id === polygonId).polygon, true);
ok(action('apply', { requestId: id('open-line'), path: files.host, expectedRevision: read().revision, operations: [{ op: 'update', id: polygonId, set: { polygon: false, backgroundColor: 'transparent' } }] }));
assert.equal(read().elements.find(e => e.id === polygonId).polygon, false);
ok(action('export', { requestId: id('open-png'), path: files.host, source: 'live', out: files.open, theme: 'light', area, padding: 0 }));
const unfilled = await runInAppTask({ cli, execute: redPixels, args: [files.open], timeoutMs: 30000 });
assert.equal(unfilled.red, 0);
strokeResults = await runInAppTask({ cli, execute: exerciseStrokeAuthoring, args: [files.host], timeoutMs: 90000 });
ok(action('export', { requestId: id('host-svg'), path: files.host, source: 'disk', out: files.svg }));
ok(action('export', { requestId: id('host-png'), path: files.host, source: 'disk', out: files.overview, theme: 'light' }));
const exported = evaluate(`(async()=>{const s=await app.vault.read(app.vault.getFileByPath(${JSON.stringify(files.svg)}));return JSON.stringify({hasImage:s.includes('<image'),hasSourceLabel:s.includes('Embedded mind map')})})()`);
assert.equal(exported.hasImage, true);
evaluate(`(async()=>{for(const l of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===${JSON.stringify(files.host)})){await l.setViewState({type:'empty',state:{}});l.detach()}return JSON.stringify({closed:true})})()`);
ok(action('open', { path: files.host }));
const reopened = read().elements;
assert.equal(reopened.find(e => e.id === labelId).rawText, 'Packet label edited');
assert.equal(reopened.find(e => e.id === labelId).text.replace(/\s+/g, ' '), 'Packet label edited');
assert.equal(reopened.find(e => e.id === strokeResults.convertedId).type, 'line');
assert.equal(reopened.some(e => e.id === strokeResults.removedId), false);
assert.ok(reopened.some(e => e.type === 'image'));
return { status: 'passed', assertions: ['250-point polygon fill and false update verified by decoded pixels', 'live packet and actual copy command retain bound labels after deselection', ...(process.env.EXCALIDRAW_CLI_POPOUT === '1' ? ['actual selection-copy command in a separate popout owner document'] : []), 'targeted label edit preserves unrelated content and refuses a stale packet', 'linked drawing embed/100% anchor and host SVG/PNG/save/reopen', 'ordinary Markdown and self-embed refusal', ...strokeResults.assertions], transportRecoveries: recoveries };
} finally {
try {
// Preserve available render evidence on failures too, before deleting owned fixtures.
if (reportDir) {
const target = join(reportDir, 'authoring-extensions'); mkdirSync(target, { recursive: true });
for (const [key, path] of Object.entries(files).filter(([key]) => ['filled', 'open', 'embed', 'overview', 'svg'].includes(key))) {
const data = evaluate(`(async()=>{const f=app.vault.getFileByPath(${JSON.stringify(path)});if(!f)return JSON.stringify(null);const b=new Uint8Array(await app.vault.readBinary(f));let s='';for(const n of b)s+=String.fromCharCode(n);return JSON.stringify({base64:btoa(s)})})()`);
if (data) writeFileSync(join(target, key + (key === 'svg' ? '.svg' : '.png')), Buffer.from(data.base64, 'base64'));
}
}
} finally {
evaluate(`(async()=>{for(const path of ${JSON.stringify(Object.values(files))}){if(!path.startsWith(${JSON.stringify(prefix)}))throw Error('Unsafe cleanup');for(const l of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await l.setViewState({type:'empty',state:{}});l.detach()}const f=app.vault.getFileByPath(path);if(f)await app.vault.delete(f)}return JSON.stringify({clean:true})})()`);
}
}
}
async function copyAndClearSelection(c, path, ids, popout) {
let view = app.workspace.getLeavesOfType('excalidraw').find(l => l.view.file?.path === path)?.view;
if (!view) throw Error('Owned view missing');
if (popout) {
const originalView = view, leaf = app.workspace.openPopoutLeaf();
c.defer(async () => { await leaf.setViewState({ type: 'empty', state: {} }); leaf.detach(); app.workspace.setActiveLeaf(originalView.leaf, { focus: false }); });
await leaf.setViewState({ type: 'excalidraw', state: { file: path }, active: true });
await c.waitFor(() => leaf.view?.isLoaded && leaf.view?.excalidrawAPI, 'popout editor');
view = leaf.view;
if (view.containerEl.ownerDocument === originalView.containerEl.ownerDocument) throw Error('Expected a separate owner document');
}
view.updateScene({ appState: { selectedElementIds: Object.fromEntries(ids.map(id => [id, true])) }, captureUpdate: 'NEVER' });
const clipboard = view.containerEl.ownerDocument.defaultView.navigator.clipboard;
const original = Object.getOwnPropertyDescriptor(clipboard, 'writeText'); let packet;
Object.defineProperty(clipboard, 'writeText', { configurable: true, value: async value => { packet = JSON.parse(value); } });
try {
app.workspace.setActiveLeaf(view.leaf, { focus: true });
app.commands.executeCommandById('obsidian-excalidraw-plugin:copy-selection-for-agent');
await c.waitFor(() => packet, 'clipboard packet');
view.updateScene({ appState: { selectedElementIds: {} }, captureUpdate: 'NEVER' });
return { packet };
} finally { if (original) Object.defineProperty(clipboard, 'writeText', original); else delete clipboard.writeText; }
}
async function redPixels(c, path) {
const file = app.vault.getFileByPath(path), blob = new Blob([await app.vault.readBinary(file)]);
const url = URL.createObjectURL(blob), image = new Image();
try {
image.src = url; await image.decode();
const canvas = createFragment().createEl('canvas'); canvas.width = image.naturalWidth; canvas.height = image.naturalHeight;
const context = canvas.getContext('2d'); context.drawImage(image, 0, 0);
const data = context.getImageData(0, 0, canvas.width, canvas.height).data; let red = 0, blue = 0;
for (let i = 0; i < data.length; i += 4) {
if (data[i] > 180 && data[i + 1] < 80 && data[i + 2] < 80 && data[i + 3] > 200) red++;
if (data[i] < 80 && data[i + 1] < 180 && data[i + 2] > 150 && data[i + 3] > 200) blue++;
}
const center = (Math.floor(canvas.height / 2) * canvas.width + Math.floor(canvas.width / 2)) * 4;
return { red, blue, total: data.length / 4, center: [...data.slice(center, center + 4)] };
} finally { URL.revokeObjectURL(url); }
}
async function exerciseStrokeAuthoring(c, path) {
const p = app.plugins.plugins['obsidian-excalidraw-plugin'], view = app.workspace.getLeavesOfType('excalidraw').find(l => l.view.file?.path === path)?.view;
const ea = p.ea.getAPI(view), check = (value, message) => { if (!value) throw Error(message); };
c.defer(() => ea.destroy());
ea.style.roughness = 0; ea.style.strokeWidth = 2;
const curve = ea.addLine([[650, 300], [700, 400], [750, 300]]);
ea.getElement(curve).roundness = { type: 2 }; ea.getElement(curve).angle = Math.PI / 6;
ea.getElement(curve).customData = { ownedStroke: 'preserved' };
await ea.addElementsToView(false, false);
let original = view.getViewElements().find(e => e.id === curve), before = p.getCLIRuntime().getCommonBounds([original]);
ea.clear(); ea.copyViewElementsToEAforEditing([original]);
const result = ea.convertLineToFreedraw(curve, { tolerance: 0.2 });
check(result.pointCount > original.points.length && result.warnings.some(w => w.includes('excalidraw.com')), 'Curve sampling or compatibility warning missing');
check(view.getViewElements().find(e => e.id === curve).type === 'line', 'Conversion changed live scene before publication');
await ea.addElementsToView(false, false);
const converted = view.getViewElements().find(e => e.id === curve), after = p.getCLIRuntime().getCommonBounds([converted]);
check(converted.type === 'freedraw' && converted.customData.ownedStroke === 'preserved', 'Free-draw conversion/metadata missing');
check(before.every((n, i) => Math.abs(n - after[i]) < 3), 'Rotated spline moved during conversion');
ea.clear(); ea.copyViewElementsToEAforEditing([converted]);
const back = ea.convertFreedrawToLine(curve, { tolerance: 0.2, strokeWidth: 2 });
check(back.warnings.length > 0, 'Pressure loss warning missing');
await ea.addElementsToView(false, false);
ea.clear();
const first = ea.addLine([[650, 500], [700, 500]]), second = ea.addLine([[700, 550], [700, 500]]);
await ea.addElementsToView(false, false);
const lines = view.getViewElements().filter(e => [first, second].includes(e.id));
ea.clear(); ea.copyViewElementsToEAforEditing(lines);
ea.concatenateLines([first, second], { maxGap: 0 });
check(view.getViewElements().some(e => e.id === second), 'Concatenation deleted live source before publication');
await ea.addElementsToView(false, false); await view.save(false);
check(!view.getViewElements().some(e => e.id === second), 'Concatenation did not remove second source');
return { convertedId: curve, removedId: second, assertions: ['actual rotated spline bounds retained through line/free-draw conversion', 'conversion/concatenation remain isolated until explicit EA publication', 'custom metadata and surviving IDs retained', 'sharp/reversed endpoint concatenation and saved tombstones'] };
}
+3 -2
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { runCLILargeIdentity } from './cliLargeIdentity.mjs';
import { createNativeCLIActions } from './nativeCLITransport.mjs';
export async function runCLIImagePreviewScenario({ cli, drawingPath, reportDir }) {
const prefix = drawingPath.replace(/\.(?:excalidraw\.md|excalidraw|md)$/, '') + '_images';
@@ -11,7 +12,7 @@ export async function runCLIImagePreviewScenario({ cli, drawingPath, reportDir }
const outputs = [], artifacts = []; let largeIdentity;
const control = '__excalidrawImagePreviewRegression';
const evaluate = code => JSON.parse(cli('eval', `code=${code}`).trim().replace(/^=>\s*/, ''));
const action = (command, values = {}) => JSON.parse(cli(`obsidian-excalidraw-plugin:${command}`, `json=${JSON.stringify({ apiVersion: 1, ...values })}`));
const { action, recoveries } = createNativeCLIActions(cli);
const ok = result => { assert.equal(result.ok, true, JSON.stringify(result)); return result; };
const id = suffix => `${prefix.split('/').at(-1).slice(-38)}-${suffix}`;
const viewCode = `app.workspace.getLeavesOfType('excalidraw').find(l=>l.view.file?.path===${JSON.stringify(paths.drawing)})?.view`;
@@ -120,7 +121,7 @@ export async function runCLIImagePreviewScenario({ cli, drawingPath, reportDir }
assert.equal(race?.error?.code, 'STALE_REVISION', JSON.stringify(race));
assert.equal(evaluate(`JSON.stringify({exists:!!app.vault.getFileByPath(${JSON.stringify(raced)})})`).exists, false);
evaluate(`(async()=>{const c=globalThis.${control};c.vault.read=c.read;await c.vault.adapter.writeBinary(c.source.path,c.bytes,{mtime:c.stat.mtime,ctime:c.stat.ctime});Object.assign(c.source.stat,c.stat);delete globalThis.${control};return JSON.stringify({restored:true})})()`);
return { status: 'passed', assertions: ['shared image original/thumbnail/placeholder identities', 'crop, mirroring, rotation, opacity, frame membership and title bounds', 'transparent PNG and SVG icon, light/dark', 'XML/Unicode labels', 'complete SVG omits original payloads', 'source text/elements/dirty unchanged', 'metadata clear preserves tags and customData', 'live/disk thumbnails', 'file transport and omitted-asset overwrite refusal', 'same-size same-mtime disk attachment race refuses publication'], artifacts, popoutCoverage: process.env.EXCALIDRAW_CLI_POPOUT === '1' ? 'passed' : 'not run (set EXCALIDRAW_CLI_POPOUT=1)', ...(largeIdentity ? { largeIdentity } : {}) };
return { status: 'passed', assertions: ['shared image original/thumbnail/placeholder identities', 'crop, mirroring, rotation, opacity, frame membership and title bounds', 'transparent PNG and SVG icon, light/dark', 'XML/Unicode labels', 'complete SVG omits original payloads', 'source text/elements/dirty unchanged', 'metadata clear preserves tags and customData', 'live/disk thumbnails', 'file transport and omitted-asset overwrite refusal', 'same-size same-mtime disk attachment race refuses publication'], artifacts, transportRecoveries: recoveries, popoutCoverage: process.env.EXCALIDRAW_CLI_POPOUT === '1' ? 'passed' : 'not run (set EXCALIDRAW_CLI_POPOUT=1)', ...(largeIdentity ? { largeIdentity } : {}) };
} finally {
evaluate(`(async()=>{const c=globalThis.${control};if(c){c.vault.read=c.read;c.release();if(c.bytes)await c.vault.adapter.writeBinary(c.source.path,c.bytes);delete globalThis.${control}}for(const path of ${JSON.stringify([...Object.values(paths), ...outputs])}){if(!path.startsWith(${JSON.stringify(prefix)}))throw Error('unsafe cleanup');for(const l of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await l.setViewState({type:'empty',state:{}});l.detach()}const f=app.vault.getFileByPath(path);if(f)await app.vault.delete(f)}return JSON.stringify({clean:true})})()`);
}
+35 -4
View File
@@ -1,6 +1,6 @@
/** Trusted in-scene controls, shared-source scope and persisted link/geometry behavior. */
export async function exerciseDrawingImagePreview(c, env, template, drawing, context, modifier) {
const { p, leaf, doc, check, click, key } = env;
const { p, leaf, doc, win, check, click, key } = env;
let view = await env.openDrawing("Image-host", {}, template);
const ea = p.ea.getAPI(view); let first, variant;
try {
@@ -48,7 +48,25 @@ export async function exerciseDrawingImagePreview(c, env, template, drawing, con
await click(buttons.find(button=>all?button.textContent.startsWith("All 3"):button.textContent==="Only this image"));
await c.waitFor(()=>!doc.querySelector(".excalidraw-drawing-preview-popover"),"image settings commit closes popover");
};
let popup=await open(); await chooseFrame(popup); await choosePadding(popup,3); await apply(popup,false);
let popup=await open();
await c.waitFor(()=>popup.closest(".mod-excalidraw-draggable"),"shared floating modal initialized");
check(win.getComputedStyle(popup).position === "absolute", "preview configuration is not a floating modal");
check(win.getComputedStyle(popup.parentElement).pointerEvents === "none", "floating modal blocks the workspace");
const start = popup.getBoundingClientRect(), x = start.left + 8, y = start.top + 8;
await env.input("Input.dispatchMouseEvent", {type:"mousePressed",x,y,button:"left",buttons:1,clickCount:1});
await env.input("Input.dispatchMouseEvent", {type:"mouseMoved",x:x+32,y:y+24,button:"left",buttons:1});
await env.input("Input.dispatchMouseEvent", {type:"mouseReleased",x:x+32,y:y+24,button:"left",buttons:0,clickCount:1});
await c.waitFor(()=>Math.abs(popup.getBoundingClientRect().left-start.left)>4,"native drag moves configuration modal");
const moved = popup.getBoundingClientRect();
await env.input("Input.dispatchMouseEvent", {type:"mousePressed",x:win.innerWidth-20,y:win.innerHeight-80,button:"left",buttons:1,clickCount:1});
await env.input("Input.dispatchMouseEvent", {type:"mouseReleased",x:win.innerWidth-20,y:win.innerHeight-80,button:"left",buttons:0,clickCount:1});
win.dispatchEvent(new win.Event("blur"));
check(popup.isConnected,"outside interaction or window blur closed the floating modal");
const imageBefore = popup.querySelector("img").src;
await chooseFrame(popup); await choosePadding(popup,3);
await c.waitFor(()=>popup.querySelector("img").src!==imageBefore&&popup.querySelector("img").naturalWidth>0,"floating modal live preview decoded");
check(Math.abs(popup.getBoundingClientRect().left-moved.left)<1&&Math.abs(popup.getBoundingClientRect().top-moved.top)<1,"preview rendering reset the dragged modal position");
await apply(popup,false);
check(get(first).fileId!==originalId && get("shared-copy").fileId===originalId,"only-this-image changed a shared copy");
check(link(first).includes("#^frame=frame-marker,padding=3"),"image settings not persisted to embedded link");
check(link(variant).includes("padding=20|100%"),"only-this-image changed a distinct view");
@@ -63,7 +81,15 @@ export async function exerciseDrawingImagePreview(c, env, template, drawing, con
check(link("shared-copy").includes("as-image,padding=5"),"apply-all pinned a default-thumbnail copy");
check(link(variant).includes("frame=frame-marker,padding=5|100%"),"apply-all lost another copy's anchor or frame");
for(let i=0;i<3;i++)check(JSON.stringify(center([first,"shared-copy",variant][i]))===JSON.stringify(oldCenters[i]),"apply-all changed a copy's center");
popup=await open(); await click(popup.querySelector(".checkbox-container")); await apply(popup,true);
popup=await open();
const toggle = popup.querySelector(".checkbox-container"), touch = toggle.getBoundingClientRect();
await env.input("Emulation.setTouchEmulationEnabled", {enabled:true,maxTouchPoints:1});
try {
await env.input("Input.dispatchTouchEvent", {type:"touchStart",touchPoints:[{x:touch.left+touch.width/2,y:touch.top+touch.height/2,id:1}]});
await env.input("Input.dispatchTouchEvent", {type:"touchEnd",touchPoints:[]});
await c.waitFor(()=>toggle.classList.contains("is-enabled"),"touch toggles anchoring without starting a drag");
} finally { await env.input("Emulation.setTouchEmulationEnabled", {enabled:false}); }
await apply(popup,true);
for(const id of [first,"shared-copy",variant]){
const el=get(id), source=view.excalidrawData.getFile(el.fileId);
check(link(id).endsWith("|100%")&&el.customData.isAnchored,"100% state absent from link or derived canvas flag");
@@ -73,10 +99,15 @@ export async function exerciseDrawingImagePreview(c, env, template, drawing, con
const savedLinks=beforeLinks.map(value=>value.replace(/^[^#|]*/,app.metadataCache.fileToLinktext(drawing,view.file.path)));
popup=await open(); await choosePadding(popup,9); await key("Escape","Escape",27);
check(!doc.querySelector(".excalidraw-drawing-preview-popover")&&JSON.stringify(view.getViewElements())===before,"Escape wrote draft image settings");
popup=await open(); await choosePadding(popup,11); await click(popup.querySelector(".modal-close-button, .modal-header-button"));
check(!popup.isConnected&&JSON.stringify(view.getViewElements())===before,"close button wrote draft settings");
await view.drawingImagePreview.open(first); view.drawingImagePreview.reset();
await new Promise(resolve=>window.setTimeout(resolve,30));
check(!doc.querySelector(".excalidraw-drawing-preview-popover"),"quick close left a deferred floating modal behind");
view=await env.saveReopen(view);
c.caseTrace.imageLinks = { expected: savedLinks, after: [first,"shared-copy",variant].map(link) };
check(JSON.stringify([first,"shared-copy",variant].map(link))===JSON.stringify(savedLinks),"reopen lost image preview links or anchoring");
for(const id of [first,"shared-copy",variant])check(view.excalidrawData.getFile(get(id).fileId).file===drawing&&get(id).customData.isAnchored,"reopen changed image source or anchoring");
check(view.getViewElements().filter(el=>el.type==='image').length===3,"settings created duplicate image elements");
return { assertions: ["selected drawing image opens owner-window configuration", "native frame/padding controls prompt once for all three source copies", "only-this-image isolates its link and preserves image area/center", "one native undo/redo restores references and geometry", "apply-all changes only edited fields across shared and distinct references", "100% persists in links and uses intrinsic dimensions", "Escape cancels drafts", "save/reopen preserves all links and three scene elements"] };
return { assertions: ["selected drawing image opens owner-window configuration", "native frame/padding controls prompt once for all three source copies", "only-this-image isolates its link and preserves image area/center", "one native undo/redo restores references and geometry", "apply-all changes only edited fields across shared and distinct references", "100% persists in links and uses intrinsic dimensions", "floating modal drags without blocking workspace or closing on blur", "live preview preserves dragged position", "Escape and close button cancel drafts", "quick close cancels deferred modal setup", "save/reopen preserves all links and three scene elements"] };
}
+29 -3
View File
@@ -1,6 +1,8 @@
/** Native authoring round-trip on fixtures owned by the guarded parent runner. */
import assert from 'node:assert/strict';
import { runCLIImagePreviewScenario } from './cliImagePreview.mjs';
import { runCLIAuthoringExtensions } from './cliAuthoringExtensions.mjs';
import { createNativeCLIActions } from './nativeCLITransport.mjs';
export async function runNativeCLIScenario({ cli, drawingPath, reportDir }) {
const prefix = drawingPath.replace(/\.(?:excalidraw\.md|excalidraw|md)$/, '') + '_native_cli';
@@ -9,15 +11,19 @@ export async function runNativeCLIScenario({ cli, drawingPath, reportDir }) {
const paths = { drawing: `${prefix}.excalidraw.md`, request: `${prefix}.json`, png: `${prefix}.png`, svg: `${prefix}.svg`, disk: `${prefix}_disk.png`,
script: `${prefix}_script.md`, template: `${prefix}_template.excalidraw.md`, invalid: `${prefix}_invalid.excalidraw.md` };
const evaluate = code => JSON.parse(cli('eval', `code=${code}`).trim().replace(/^=>\s*/, ''));
const action = (command, request = {}) => JSON.parse(cli(`obsidian-excalidraw-plugin:${command}`, `json=${JSON.stringify({ apiVersion: 1, ...request })}`));
const { action, recoveries } = createNativeCLIActions(cli);
const ok = (result) => { assert.equal(result.ok, true, JSON.stringify(result)); return result; };
const write = (path, text) => evaluate(`(async()=>{const path=${JSON.stringify(path)},file=app.vault.getFileByPath(path);if(file)await app.vault.modify(file,${JSON.stringify(text)});else await app.vault.create(path,${JSON.stringify(text)});return JSON.stringify({written:true})})()`);
const viewCode = `app.workspace.getLeavesOfType('excalidraw').find(leaf=>leaf.view.file?.path===${JSON.stringify(paths.drawing)})?.view`;
const control = '__excalidrawNativeCLIRegression';
const extrasControl = '__excalidrawCLIMermaidDependency';
let cleanup = false;
const artifacts = []; let imagePreviews;
const artifacts = []; let imagePreviews, authoringExtensions;
try {
for (const command of ['help', 'status', 'skill', 'list']) ok(action(command));
const status = ok(action('status')).data;
assert.equal(typeof status.mindMapBuilder.ready, 'boolean');
assert.equal(typeof status.extras.components.mermaid.compatible, 'boolean');
assert.equal(ok(action('schema', { action: 'apply' })).data.command, 'apply');
assert.equal(ok(action('api', { name: 'executeCLI' })).data.entries[0].name, 'executeCLI');
const create = { apiVersion: 1, requestId: `${idPrefix}-create`, path: paths.drawing, elements: [
@@ -88,6 +94,7 @@ export async function runNativeCLIScenario({ cli, drawingPath, reportDir }) {
live = read();
const image = ok(action('apply', { requestId: `${idPrefix}-image`, path: paths.drawing, expectedRevision: live.revision, operations: [{ op: 'image', id: 'preview', asset: paths.png, x: 0, y: 200 }] })); assert.ok(image.data.idMap.preview);
assert.equal(ok(action('read', { path: paths.drawing, source: 'disk' })).data.types.image, 1);
authoringExtensions = await runCLIAuthoringExtensions({ cli, drawingPath, reportDir });
imagePreviews = await runCLIImagePreviewScenario({ cli, drawingPath, reportDir });
write(paths.script, 'return {input:utils.input,source:utils.executionSource,converter:typeof utils.excalidrawLib.convertToExcalidrawElements};');
const scriptRequest = { requestId: `${idPrefix}-script`, script: paths.script, trusted: true, args: { x: 0, text: '${literal}' } };
@@ -96,14 +103,33 @@ export async function runNativeCLIScenario({ cli, drawingPath, reportDir }) {
write(paths.script, 'await utils.inputPrompt("must fail");');
assert.equal(action('script', scriptRequest).error.field, 'requestId');
assert.equal(action('script', { ...scriptRequest, requestId: `${idPrefix}-prompt` }).error.code, 'INTERACTION_REQUIRED');
write(paths.script, 'return {nodeId:"already-saved",arrowId:undefined};');
const unsafeResult = { ...scriptRequest, requestId: `${idPrefix}-undefined` };
assert.equal(action('script', unsafeResult).error.code, 'OUTCOME_UNKNOWN');
write(paths.script, 'return JSON.parse(JSON.stringify({nodeId:"already-saved",arrowId:undefined}));');
assert.deepEqual(ok(action('script', { ...scriptRequest, requestId: `${idPrefix}-json-safe` })).data, { nodeId: 'already-saved' });
write(paths.script, 'return await ea.addMermaid("flowchart TD; A-->B");');
evaluate(`(()=>{const g=app.plugins.plugins['obsidian-excalidraw-plugin'].extrasGateway;if(globalThis.${extrasControl})throw Error('Extras test already active');globalThis.${extrasControl}={gateway:g,descriptor:Object.getOwnPropertyDescriptor(g,'getAPI')};g.getAPI=()=>({versions:{mermaid:'3.0.0'},features:{isActive:()=>true,enable:()=>{throw Error('Unexpected activation')}}});return JSON.stringify({ready:true})})()`);
try {
const incompatible = ok(action('status')).data;
assert.equal(incompatible.ready, true);
assert.equal(incompatible.extras.components.mermaid.version, '3.0.0');
assert.equal(incompatible.extras.components.mermaid.compatible, false);
const refused = action('script', { ...scriptRequest, requestId: `${idPrefix}-mermaid-version` });
assert.equal(refused.error.code, 'DEPENDENCY_UNAVAILABLE');
assert.equal(refused.mutation, 'unknown'); assert.equal(refused.persistence, 'unknown');
} finally {
evaluate(`(()=>{const c=globalThis.${extrasControl};if(c.descriptor)Object.defineProperty(c.gateway,'getAPI',c.descriptor);else delete c.gateway.getAPI;delete globalThis.${extrasControl};return JSON.stringify({restored:true})})()`);
}
const close = evaluate(`(async()=>{for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===${JSON.stringify(paths.drawing)})){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}return JSON.stringify({closed:true})})()`); assert.equal(close.closed, true);
ok(action('open', { path: paths.drawing }));
await new Promise(resolve => setTimeout(resolve, 250));
assert.equal(read().elements.find(element => element.id === label.id).rawText, 'Recoverable edit');
} finally {
evaluate(`(()=>{const c=globalThis.${extrasControl};if(c){if(c.descriptor)Object.defineProperty(c.gateway,'getAPI',c.descriptor);else delete c.gateway.getAPI;delete globalThis.${extrasControl}}return JSON.stringify({restored:true})})()`);
const result = evaluate(`(async()=>{const c=globalThis.${control};if(c){if(c.original)c.model.addTextElement=c.original;if(c.originalSave)c.view.saveWithOutcome=c.originalSave;c.release?.();delete globalThis.${control}}const paths=${JSON.stringify(Object.values(paths))};for(const path of paths){if(!path.startsWith(${JSON.stringify(prefix)}))throw Error('unsafe fixture cleanup');for(const leaf of app.workspace.getLeavesOfType('excalidraw').filter(l=>l.view.file?.path===path)){await leaf.setViewState({type:'empty',state:{}});leaf.detach()}const file=app.vault.getFileByPath(path);if(file)await app.vault.delete(file)}return JSON.stringify({clean:true})})()`);
cleanup = result.clean;
}
assert.equal(cleanup, true);
return { id: 'native-cli-authoring', status: 'passed', assertions: ['native discovery/file input', 'stable labels, bindings and frames', 'template prose', 'collision and invalid-batch refusal', 'guarded text save/read-back', 'idempotent receipts', 'competing write BUSY', 'stale async text leaves metadata intact', 'failed save preserves recoverable edit', 'add/connect/group/ungroup/delete and frame child guard', 'live/disk SVG/PNG', 'vault image metadata round-trip', 'trusted script context/source identity/prompt refusal', 'save/reopen', 'owned fixture cleanup'], artifacts, imagePreviews };
return { id: 'native-cli-authoring', status: 'passed', assertions: ['native discovery/file input', 'stable labels, bindings and frames', 'template prose', 'collision and invalid-batch refusal', 'guarded text save/read-back', 'idempotent receipts', 'competing write BUSY', 'stale async text leaves metadata intact', 'failed save preserves recoverable edit', 'add/connect/group/ungroup/delete and frame child guard', 'live/disk SVG/PNG', 'vault image metadata round-trip', 'trusted script context/source identity/prompt refusal', 'save/reopen', 'owned fixture cleanup'], artifacts, imagePreviews, authoringExtensions, transportRecoveries: recoveries };
}
@@ -0,0 +1,18 @@
/** Recover only the exact native write receipt after lost stdout; never replay the write. */
export function createNativeCLIActions(cli) {
const recoveries = [];
const action = (command, request = {}, inputPath) => {
try {
return JSON.parse(cli(`obsidian-excalidraw-plugin:${command}`, inputPath ? `input=${inputPath}` : `json=${JSON.stringify({ apiVersion: 1, ...request })}`));
} catch (error) {
if (!request.requestId || !/\bETIMEDOUT\b/.test(error.message)) throw error;
let receipt;
try { receipt = JSON.parse(cli('obsidian-excalidraw-plugin:result', `requestId=${request.requestId}`)); }
catch { throw error; }
if (receipt.command !== command || receipt.requestId !== request.requestId || !['completed', 'failed'].includes(receipt.status)) throw error;
recoveries.push({ command, requestId: request.requestId, session: receipt.session, transportError: error.message });
return receipt;
}
};
return { action, recoveries };
}
@@ -0,0 +1,38 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createNativeCLIActions } from './nativeCLITransport.mjs';
test('native stdout timeout recovers only the exact settled receipt without replaying a write', () => {
const calls = [], receipt = { command: 'export', requestId: 'original', session: 'session', status: 'completed', ok: true };
const { action, recoveries } = createNativeCLIActions((command, flag) => {
calls.push([command, flag]);
if (command.endsWith(':export')) throw Error('spawnSync ETIMEDOUT');
return JSON.stringify(receipt);
});
assert.deepEqual(action('export', { requestId: 'original' }), receipt);
assert.equal(calls.length, 2); assert.equal(calls[1][0], 'obsidian-excalidraw-plugin:result');
assert.equal(calls[1][1], 'requestId=original');
assert.equal(recoveries.length, 1); assert.equal(recoveries[0].session, 'session');
});
test('pending, unknown and mismatched native receipts retain the original transport failure', () => {
for (const receipt of [
{ command: 'export', requestId: 'original', status: 'pending' },
{ command: 'result', requestId: 'original', status: 'failed', error: { code: 'OUTCOME_UNKNOWN' } },
{ command: 'export', requestId: 'different', status: 'completed' },
]) {
const failure = Error('spawnSync ETIMEDOUT'); let calls = 0;
const { action, recoveries } = createNativeCLIActions(() => { if (++calls === 1) throw failure; return JSON.stringify(receipt); });
assert.throws(() => action('export', { requestId: 'original' }), error => error === failure);
assert.equal(calls, 2); assert.equal(recoveries.length, 0);
}
});
test('native operation failures and unrelated transport errors are never converted into success', () => {
const receipt = { command: 'script', requestId: 'original', status: 'failed', ok: false, error: { code: 'OUTCOME_UNKNOWN' } };
let calls = 0;
const { action } = createNativeCLIActions(() => { if (++calls === 1) throw Error('ETIMEDOUT'); return JSON.stringify(receipt); });
assert.equal(action('script', { requestId: 'original' }).ok, false);
const other = Error('permission denied');
assert.throws(() => createNativeCLIActions(() => { throw other; }).action('export', { requestId: 'original' }), error => error === other);
});
+135
View File
@@ -0,0 +1,135 @@
/** Actual geometry/workbench helpers with the existing version-clone boundary isolated. */
import test from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { sourceHarness } from './sourceHarness.mjs';
const require = createRequire(import.meta.url), rough = require('roughjs');
const graph = sourceHarness({
'roughjs/bin/generator': { RoughGenerator: rough.generator().constructor },
'./excalidrawElementUtils': { cloneElement: e => ({ ...structuredClone(e), version: e.version + 1 }) },
});
const { convertWorkbenchStroke } = await graph.importModule('src/utils/strokeConversion.ts');
const { concatenateWorkbenchLines } = await graph.importModule('src/utils/strokeConcatenation.ts');
const { segmentDistance } = await graph.importModule('src/shared/svgToExcalidraw/pathGeometry.ts');
test.after(() => graph.close());
function line(id, points, extra = {}) {
const xs = points.map(p => p[0]), ys = points.map(p => p[1]);
return { id, type: 'line', x: 10, y: 20, angle: 0, points, width: Math.max(...xs) - Math.min(...xs), height: Math.max(...ys) - Math.min(...ys),
strokeWidth: 2, strokeColor: '#123456', backgroundColor: 'transparent', fillStyle: 'solid', roughness: 0, opacity: 100,
seed: 1, version: 1, groupIds: ['group'], frameId: 'frame', customData: { preserved: 'yes' }, boundElements: [], polygon: false, roundness: null, ...extra };
}
function workbench(elements) {
return { elementsDict: Object.fromEntries(elements.map(e => [e.id, e])), getElement(id) { return this.elementsDict[id]; },
plugin: { getCLIRuntime: () => ({ getCommonBounds: ([e]) => {
const xs = e.points.map(p => p[0] + e.x), ys = e.points.map(p => p[1] + e.y);
return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
} }) } };
}
const world = e => e.points.map(([x, y]) => [x + e.x, y + e.y]);
const near = (a, b, tolerance = 1e-7) => assert.ok(Math.hypot(a[0] - b[0], a[1] - b[1]) <= tolerance, `${a} != ${b}`);
test('line to free-draw retains world placement, identity and metadata for rotated strokes', () => {
const source = line('stroke', [[0, 0], [100, 0]], { angle: Math.PI / 2 });
const ea = workbench([source]);
const result = convertWorkbenchStroke(ea, 'stroke', 'freedraw');
const target = ea.getElement('stroke');
assert.equal(source.type, 'line'); assert.equal(target.type, 'freedraw'); assert.equal(target.angle, 0);
near(world(target)[0], [60, -30]); near(world(target)[1], [60, 70]);
assert.equal(target.version, 2); assert.deepEqual(target.groupIds, ['group']); assert.equal(target.frameId, 'frame');
assert.equal(target.customData.preserved, 'yes'); assert.equal(target.customData.strokeOptions.options.start.cap, true);
assert.equal(target.pressures.length, target.points.length); assert.equal(target.simulatePressure, false);
assert.equal('polygon' in target, false); assert.match(result.warnings[0], /excalidraw.com/);
});
test('rounded line conversion samples the actual spline within tolerance instead of retagging control points', () => {
const source = line('curve', [[0, 0], [50, 100], [100, 0]], { roundness: { type: 2 } });
const ea = workbench([source]), tolerance = 0.2;
convertWorkbenchStroke(ea, source.id, 'freedraw', { tolerance });
const sampled = world(ea.getElement(source.id)); assert.ok(sampled.length > source.points.length);
const ops = rough.generator().curve(source.points, { roughness: 0, preserveVertices: true, disableMultiStroke: true }).sets[0].ops.slice(0, source.points.length);
let start;
for (const op of ops) {
if (op.op === 'move') start = op.data;
else {
const [bx, by, cx, cy, dx, dy] = op.data;
for (let i = 0; i <= 100; i++) {
const t = i / 100, u = 1 - t;
const p = [u ** 3 * start[0] + 3 * u ** 2 * t * bx + 3 * u * t ** 2 * cx + t ** 3 * dx + source.x,
u ** 3 * start[1] + 3 * u ** 2 * t * by + 3 * u * t ** 2 * cy + t ** 3 * dy + source.y];
const error = Math.min(...sampled.slice(1).map((b, j) => segmentDistance(p, sampled[j], b)));
assert.ok(error <= tolerance ** 2 + 1e-8);
}
start = [dx, dy];
}
}
});
test('free-draw to line simplifies centerlines and explicitly removes custom pen and pressure semantics', () => {
const ea = workbench([line('stroke', Array.from({ length: 100 }, (_, i) => [i, i % 2 * 0.1]))]);
convertWorkbenchStroke(ea, 'stroke', 'freedraw');
const result = convertWorkbenchStroke(ea, 'stroke', 'line', { tolerance: 0.5, strokeWidth: 3 });
const target = ea.getElement('stroke');
assert.equal(target.points.length, 2); assert.equal(target.strokeWidth, 3); assert.equal(target.customData.preserved, 'yes');
assert.equal('strokeOptions' in target.customData, false); assert.equal('pressures' in target, false);
assert.match(result.warnings[0], /pressure/i);
});
test('custom free-draw tips/pressure configuration is copied without modifying caller settings', () => {
const ea = workbench([line('a', [[0, 0], [50, 0]]), line('b', [[0, 0], [50, 0]])]);
convertWorkbenchStroke(ea, 'a', 'freedraw');
const pen = structuredClone(ea.getElement('a').customData.strokeOptions);
pen.options.start.cap = false; pen.options.end.taper = 20; pen.options.thinning = 0.6;
pen.hasOutline = true; pen.outlineWidth = 2;
const before = structuredClone(pen);
convertWorkbenchStroke(ea, 'b', 'freedraw', { penOptions: pen });
assert.deepEqual(pen, before); assert.deepEqual(ea.getElement('b').customData.strokeOptions, pen);
ea.getElement('b').customData.strokeOptions.options.end.taper = 10;
assert.equal(pen.options.end.taper, 20);
});
test('conversion preserves closed fills and rejects unsupported relationships or budgets atomically', () => {
const ea = workbench([line('closed', [[0, 0], [50, 0], [0, 50]], { polygon: true, backgroundColor: '#ff0000' })]);
convertWorkbenchStroke(ea, 'closed', 'freedraw');
assert.deepEqual(ea.getElement('closed').points.at(-1), [0, 0]);
convertWorkbenchStroke(ea, 'closed', 'line'); assert.equal(ea.getElement('closed').polygon, true);
const ordinary = workbench([line('ordinary', [[0, 0], [50, 0], [0, 50], [0, 0]], { backgroundColor: '#ff0000' })]);
convertWorkbenchStroke(ordinary, 'ordinary', 'freedraw'); assert.equal(ordinary.getElement('ordinary').backgroundColor, '#ff0000');
const open = workbench([line('open', [[0, 0], [50, 0]], { type: 'freedraw', backgroundColor: '#ff0000' })]);
convertWorkbenchStroke(open, 'open', 'line'); assert.equal(open.getElement('open').polygon, false);
for (const extra of [{ startArrowhead: 'arrow' }, { startBinding: { elementId: 'shape' } }, { endBinding: { elementId: 'shape' } }, { boundElements: [{ id: 'label', type: 'text' }] }]) {
const e = line('bad', [[0, 0], [20, 30]], extra), target = workbench([e]), before = structuredClone(e);
assert.throws(() => convertWorkbenchStroke(target, 'bad', 'freedraw')); assert.deepEqual(target.getElement('bad'), before);
}
const target = workbench([line('curve', [[0, 0], [50, 100], [100, 0]], { roundness: { type: 2 } })]);
const before = structuredClone(target.getElement('curve'));
assert.throws(() => convertWorkbenchStroke(target, 'curve', 'freedraw', { maxPoints: 2 }));
assert.deepEqual(target.getElement('curve'), before);
});
test('concatenation chooses endpoint order, retains sharp corners and publishes no intermediate changes', () => {
const a = line('a', [[0, 0], [50, 0]]), b = line('b', [[50, 50], [50, 0]]), c = line('c', [[50, 50], [20, 80]]);
const ea = workbench([a, b, c]), result = concatenateWorkbenchLines(ea, ['a', 'c', 'b'], { maxGap: 0 });
assert.equal(result.id, 'a'); assert.deepEqual(result.removedIds, ['c', 'b']);
assert.equal(ea.getElement('b').isDeleted, true); assert.equal(ea.getElement('c').isDeleted, true);
assert.equal(a.isDeleted, undefined); assert.equal(b.isDeleted, undefined);
assert.deepEqual(world(ea.getElement('a')), [[10, 20], [60, 20], [60, 70], [30, 100]]);
});
test('concatenation refuses disconnected, conflicting and closed inputs without deleting any source', () => {
for (const extra of [{ x: 1000 }, { strokeColor: '#abcdef' }, { polygon: true }, { startBinding: { elementId: 'shape' } }, { endBinding: { elementId: 'shape' } }, { boundElements: [{ id: 'label', type: 'text' }] }]) {
const ea = workbench([line('a', [[0, 0], [50, 0]]), line('b', [[50, 0], [100, 0]], extra)]), before = structuredClone(ea.elementsDict);
assert.throws(() => concatenateWorkbenchLines(ea, ['a', 'b'])); assert.deepEqual(ea.elementsDict, before);
}
});
test('concatenation samples spline sections and normalizes rotation before endpoint matching', () => {
const rotated = workbench([line('a', [[0, 0], [100, 0]], { angle: Math.PI / 2 }), line('b', [[0, 0], [40, 0]], { x: 60, y: 70 })]);
concatenateWorkbenchLines(rotated, ['a', 'b'], { maxGap: 0.000001 });
const points = world(rotated.getElement('a'));
near(points[0], [60, -30]); near(points[1], [60, 70]); near(points[2], [100, 70]);
const curved = workbench([line('a', [[0, 0], [50, 100], [100, 0]], { roundness: { type: 2 } }), line('b', [[100, 0], [150, 50]])]);
const result = concatenateWorkbenchLines(curved, ['a', 'b'], { maxGap: 0 });
assert.ok(result.pointCount > 4); assert.equal(curved.getElement('a').roundness, null);
near(world(curved.getElement('a')).at(-1), [160, 70]);
});
+8 -5
View File
@@ -4,7 +4,7 @@ import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import type { ExcalidrawCLI } from "src/core/managers/ExcalidrawCLI";
import type { ConnectionPoint } from "src/types/types";
import { CLIError, boolean, number, object, string, vaultPath } from "./cliProtocol";
import { CLI_STYLE_FIELDS, constructBatch, fields, validateBatch, validateStyle } from "./cliElements";
import { CLI_STYLE_FIELDS, constructBatch, fields, validateBatch, validatePolygonPoints, validateStyle } from "./cliElements";
import { drawingFile, drawingView, liveIdentity } from "./cliTarget";
import { sameCLIIdentity } from "./cliIdentity";
import { cliImageMetadataPatch } from "src/utils/elementCustomDataUtils";
@@ -15,7 +15,7 @@ export const CLI_OPERATION_FIELDS: Record<string, string[]> = {
lucide: CLI_ICON_FIELDS,
add: ["elements"], update: ["id", "set"], delete: ["ids", "children"],
connect: ["id", "from", "to", "fromSide", "toSide"], group: ["ids"], ungroup: ["ids", "groupId"],
image: ["id", "asset", "x", "y", "scale"], imageMetadata: ["id", "label", "tags"], latex: ["id", "text", "x", "y", "scaleX", "scaleY"],
image: ["id", "asset", "x", "y", "scale", "anchor"], imageMetadata: ["id", "label", "tags"], latex: ["id", "text", "x", "y", "scaleX", "scaleY"],
};
function ids(value: unknown): string[] {
@@ -53,7 +53,7 @@ export function validateOperations(input: unknown): Record<string, unknown>[] {
if (op === "connect") { string(operation.from, "from"); string(operation.to, "to"); side(operation.fromSide); side(operation.toSide); }
if (["image", "latex"].includes(op)) {
number(operation.x, "x", 0, -1000000, 1000000); number(operation.y, "y", 0, -1000000, 1000000);
if (op === "image") { vaultPath(operation.asset, "asset"); boolean(operation.scale, "scale", true); }
if (op === "image") { vaultPath(operation.asset, "asset"); boolean(operation.scale, "scale", true); boolean(operation.anchor, "anchor", true); }
else { string(operation.text, "text"); number(operation.scaleX, "scaleX", 1, 0.1, 4); number(operation.scaleY, "scaleY", 1, 0.1, 4); }
}
if (operation.id !== undefined) string(operation.id, "id");
@@ -109,6 +109,8 @@ export async function applyDrawing(cli: ExcalidrawCLI, request: Record<string, u
for (const element of batch.elements) elementsMap.set(element.id, element);
} else if (op === "update") {
const element = resolve(operation.id), set = { ...object(operation.set) };
validateStyle(set, element.type);
if (set.polygon === true && element.type === "line") validatePolygonPoints(element.points);
if (element.type !== "text" && ["text", "fontSize", "fontFamily", "textAlign", "verticalAlign"].some(key => key in set)) throw new CLIError("INVALID_INPUT", "Text fields require a text element; edit its bound label ID.", "set");
if (["arrow", "line", "freedraw"].includes(element.type) && ["width", "height"].some(key => key in set)) throw new CLIError("INVALID_INPUT", "Linear resizing requires a trusted EA script.", "set");
if ("text" in set) { set.rawText = set.text; set.originalText = set.text; }
@@ -162,10 +164,11 @@ export async function applyDrawing(cli: ExcalidrawCLI, request: Record<string, u
}
} else if (op === "image") {
const path = vaultPath(operation.asset, "asset"), asset = plugin.app.vault.getFileByPath(path);
if (!asset || !["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(asset.extension.toLowerCase())) throw new CLIError("INVALID_INPUT", "Image requires an existing vault raster image or SVG.", "asset");
if (!asset || !(["png", "jpg", "jpeg", "gif", "webp", "svg"].includes(asset.extension.toLowerCase()) || plugin.isExcalidrawFile(asset))) throw new CLIError("INVALID_INPUT", "Image requires an existing vault raster image, SVG or recognized Excalidraw drawing.", "asset");
if (asset === file) throw new CLIError("INVALID_INPUT", "A drawing cannot embed itself.", "asset");
if (asset.stat.size > 16 * 1024 * 1024) throw new CLIError("INVALID_INPUT", "Image exceeds 16 MiB.", "asset");
const stat = JSON.stringify(asset.stat);
const actual = await ea.addImage(number(operation.x, "x", 0, -1000000, 1000000), number(operation.y, "y", 0, -1000000, 1000000), asset, boolean(operation.scale, "scale", true));
const actual = await ea.addImage(number(operation.x, "x", 0, -1000000, 1000000), number(operation.y, "y", 0, -1000000, 1000000), asset, boolean(operation.scale, "scale", true), boolean(operation.anchor, "anchor", true));
if (plugin.app.vault.getFileByPath(path) !== asset || JSON.stringify(asset.stat) !== stat) throw new CLIError("STALE_REVISION", "Image changed during preparation.", "asset");
recordId(operation.id, actual);
} else if (op === "latex") {
+4
View File
@@ -20,6 +20,7 @@ export const CLI_COMMANDS: Record<CLICommand, CommandDescriptor> = {
schema: { description: "Inspect one command's fields and side effects", fields: { action: "Command to describe" }, example: { action: "create" } },
api: { description: "Search EA documentation or the supported installed Lib reference", fields: { surface: "ea (default) or lib", name: "Exact method name", query: "Case-insensitive search" }, example: { surface: "ea", name: "addText" } },
list: { description: "List drawing paths without opening them", fields: { folder: "Optional exact folder", ...page }, example: { limit: 50 } },
selection: { description: "Capture up to 500 selected live elements and bound labels as a stable agent handoff packet; no clipboard or drawing writes", fields: { ...target }, example: { path: "Drawings/Flow.excalidraw.md", view: "from-open-or-read" } },
read: { description: "Read an explicit live or disk drawing; no base64 asset bodies", fields: { ...target, ...source, ...page, detail: "summary (default), elements, or images (asset metadata only)", selectedOnly: "Live selection only", ids: "JSON array of element IDs" }, example: { path: "Drawings/Flow.excalidraw.md", source: "live", detail: "elements" } },
open: { description: "Explicitly open a ready Excalidraw view; normal drawing scripts can run", fields: { ...target }, example: { path: "Drawings/Flow.excalidraw.md" } },
create: { description: "Create an exact new path using EA's serializer; never overwrite", fields: { ...write, path: target.path, template: "Optional exact drawing template; no picker", elements: "Validated batch of installed Excalidraw skeletons", icons: "Optional array of at most 100 grouped native Lucide icons with unique logical IDs" }, writes: true, example: { requestId: "flow-1", path: "Drawings/Flow.excalidraw.md", elements: [{ id: "a", type: "rectangle", x: 0, y: 0, width: 200, height: 80, label: { text: "Start" } }] } },
@@ -60,6 +61,7 @@ Put large requests in a visible vault-relative JSON file and pass input="<file>"
Requests in files include apiVersion:1; the native command supplies command. The in-process ea.executeCLI request also includes command.
Use exact drawing paths including extensions. Never assume an active drawing. :open explicitly creates a tab and can run configured drawing scripts.
Loop: :read source=live detail=elements (or detail=images to inventory) → :apply with expectedRevision and a unique requestId → check persistence=saved → :export → inspect the image file.
For selected targets use :selection with an explicit path/view, or the drawing command Copy selected elements for agent. Retain packet IDs (including bound-label IDs), read those IDs at the packet revision, and apply only authorized targets. A stale packet needs inspection and a fresh revision, never guessed replacement IDs.
For duplicate views use the view ID from :open or :read. Refresh after STALE_REVISION; retry BUSY with the same requestId only when refused before execution; unknown outcomes require read-back.
New skeleton IDs are local labels; use returned idMap actual IDs for updates. Updates reject identity, bindings and asset internals.
Every write requires requestId. Repeat the identical effective request to retrieve its receipt; different content with the same ID fails.
@@ -67,6 +69,8 @@ Every write requires requestId. Repeat the identical effective request to retrie
:api surface=ea name=<method> gives existing EA signatures. :api surface=lib lists the supported installed Lib reference; advanced exports remain available to scripts.
:icons query=<name> discovers installed canonical Lucide names (paged); create icons / apply op=lucide insert editable native groups. groupMap maps logical icon aliases to groupId/elementIds; idMap remains single-element only. Defaults: size=96, strokeColor=#1e1e1e, roughness=1, opacity=100; optional strokeWidth is final scene units. No trusted script is required.
:script requires trusted=true and an explicit existing local script file. utils.input contains args; utils.excalidrawLib is the installed runtime. Await all work; completion does not imply saved drawing.
:status ready describes plugin startup. Inspect extras.components for optional service versions, active/compatible flags and requirements; extras may be null during startup. mindMapBuilder reports the resident script API's available/ready flags without starting it or selecting a view.
One-shot ea.addMermaid preflights Extras and rejects unavailable dependencies with DEPENDENCY_UNAVAILABLE instead of opening an activation modal. Inspect any earlier script writes before retrying.
One-shot EA is cleaned up; utility prompts fail INTERACTION_REQUIRED. Trusted code can still invoke other interactive APIs: this is not a sandbox, timeout cancellation or transaction.
Export names an explicit out=.svg/.png; overwrite=true is required for existing outputs. Live exports never implicitly save. Disk exports require local Vault assets; use a loaded live source or placeholders for remote assets.
For cheap previews: :read detail=images, then :export imagePolicy={"default":"placeholder","rules":[{"ids":["wanted-id"],"mode":"original"}]}. This is lossless for the underlying drawing, not the preview.
+22 -5
View File
@@ -5,7 +5,8 @@ import { nanoid } from "src/constants/constants";
import { CLIError, boolean, number, object, string } from "./cliProtocol";
export const CLI_SHAPES = ["rectangle", "ellipse", "diamond", "text", "arrow", "line", "frame", "stickynote"];
export const CLI_STYLE_FIELDS = ["x", "y", "width", "height", "angle", "strokeColor", "backgroundColor", "fillStyle", "strokeWidth", "strokeStyle", "roughness", "opacity", "locked", "link", "text", "fontSize", "fontFamily", "textAlign", "verticalAlign"];
export const CLI_MAX_LINEAR_POINTS = 1000;
export const CLI_STYLE_FIELDS = ["x", "y", "width", "height", "angle", "strokeColor", "backgroundColor", "fillStyle", "strokeWidth", "strokeStyle", "roughness", "opacity", "locked", "link", "text", "fontSize", "fontFamily", "textAlign", "verticalAlign", "polygon"];
const skeletonFields = new Set([...CLI_STYLE_FIELDS, "id", "type", "roundness", "label", "points", "start", "end", "startArrowhead", "endArrowhead", "children", "name"]);
const arrowheads = ["arrow", "bar", "circle", "circle_outline", "triangle", "triangle_outline", "diamond", "diamond_outline"];
@@ -15,7 +16,7 @@ export function fields(value: Record<string, unknown>, allowed: readonly string[
}
/** Validates the finite assignable style/geometry surface shared by batches and updates. */
export function validateStyle(value: Record<string, unknown>): void {
export function validateStyle(value: Record<string, unknown>, type?: string): void {
for (const key of ["x", "y", "angle"]) if (value[key] !== undefined) number(value[key], key, 0, -1_000_000, 1_000_000);
for (const key of ["width", "height"]) if (value[key] !== undefined) number(value[key], key, 0, 0, 100_000);
for (const [key, min, max] of [["opacity", 0, 100], ["strokeWidth", 0, 100], ["roughness", 0, 3], ["fontSize", 1, 1000], ["fontFamily", 1, 10]] as const) {
@@ -29,6 +30,20 @@ export function validateStyle(value: Record<string, unknown>): void {
if (value.text !== undefined && (typeof value.text !== "string" || value.text.length > 10000)) throw new CLIError("INVALID_INPUT", "Text must be a string of at most 10000 characters.", "text");
if (value.link !== undefined && value.link !== null) string(value.link, "link");
if (value.locked !== undefined) boolean(value.locked, "locked");
if (value.polygon !== undefined) {
boolean(value.polygon, "polygon");
if (type !== undefined && type !== "line") throw new CLIError("INVALID_INPUT", "Polygon applies only to line elements.", "polygon");
}
}
/** Matches the fork's isValidPolygon contract; restoration resets an open path's flag. */
export function validatePolygonPoints(points: unknown): void {
const first: unknown = Array.isArray(points) ? points[0] : null;
const last: unknown = Array.isArray(points) ? points.at(-1) : null;
if (!Array.isArray(points) || points.length < 4 || !Array.isArray(first) || !Array.isArray(last) ||
first[0] !== last[0] || first[1] !== last[1]) {
throw new CLIError("INVALID_INPUT", "Polygon requires at least four points with the last point equal to the first. Close the contour explicitly.", "polygon");
}
}
/** Complete validation precedes conversion; relationship references are batch-local. */
@@ -36,7 +51,7 @@ export function validateBatch(input: unknown): Record<string, unknown>[] {
if (!Array.isArray(input) || input.length > 500) throw new CLIError("INVALID_INPUT", "Expected at most 500 skeletons.", "elements");
const batch = input.map((entry, index) => {
const element = object(entry, `elements[${index}]`);
fields(element, [...skeletonFields]); validateStyle(element);
fields(element, [...skeletonFields]); validateStyle(element, string(element.type, "type"));
if (!CLI_SHAPES.includes(string(element.type, "type"))) throw new CLIError("INVALID_INPUT", "Unsupported skeleton type.", "type");
if (element.type !== "frame") { number(element.x, "x", 0, -1_000_000, 1_000_000); number(element.y, "y", 0, -1_000_000, 1_000_000); }
if (element.type === "text" && typeof element.text !== "string") throw new CLIError("INVALID_INPUT", "Text skeleton requires text.", "text");
@@ -58,12 +73,13 @@ export function validateBatch(input: unknown): Record<string, unknown>[] {
if (roundness.value !== undefined) number(roundness.value, "roundness.value", 0, 0, 1000);
}
if (element.points !== undefined) {
if (!["line", "arrow"].includes(string(element.type, "type")) || !Array.isArray(element.points) || element.points.length < 2 || element.points.length > 100) throw new CLIError("INVALID_INPUT", "Expected 2–100 linear points.", "points");
if (!["line", "arrow"].includes(string(element.type, "type")) || !Array.isArray(element.points) || element.points.length < 2 || element.points.length > CLI_MAX_LINEAR_POINTS) throw new CLIError("INVALID_INPUT", `Expected 2–${CLI_MAX_LINEAR_POINTS} linear points.`, "points");
for (const point of element.points) {
if (!Array.isArray(point) || point.length !== 2) throw new CLIError("INVALID_INPUT", "Expected [x,y] point.", "points");
point.forEach(coordinate => number(coordinate, "points", 0, -100000, 100000));
}
}
if (element.polygon === true) validatePolygonPoints(element.points);
for (const key of ["startArrowhead", "endArrowhead"]) if (element[key] !== undefined) {
if (!["arrow", "line"].includes(string(element.type, "type"))) throw new CLIError("INVALID_INPUT", "Arrowheads require a linear element.", key);
if (element[key] !== null && !arrowheads.includes(string(element[key], key))) throw new CLIError("INVALID_INPUT", "Unknown arrowhead.", key);
@@ -89,6 +105,7 @@ export function validateBatch(input: unknown): Record<string, unknown>[] {
}
} else if (element.children !== undefined) throw new CLIError("INVALID_INPUT", "Children require a frame.", "children");
}
if (batch.reduce((sum, element) => sum + (Array.isArray(element.points) ? element.points.length : 0), 0) > 100000) throw new CLIError("INVALID_INPUT", "Batch exceeds 100000 linear points.", "points");
return batch;
}
@@ -113,7 +130,7 @@ export function constructBatch(input: unknown, lib: NonNullable<Packages["excali
const ids = new Set(elements.map(element => element.id));
if (ids.size !== elements.length || Object.values(idMap).some(id => !ids.has(id)) || elements.some(element => !CLI_SHAPES.includes(element.type) || element.id.length !== 8)) throw new CLIError("INVALID_INPUT", "Converter did not preserve the requested batch identities.", "elements");
for (const element of elements) {
validateStyle(element);
validateStyle(element, element.type);
const references = [...(element.boundElements ?? []).map(bound => bound.id), element.frameId,
...(element.type === "text" ? [element.containerId] : []),
...(element.type === "arrow" ? [element.startBinding?.elementId, element.endBinding?.elementId] : [])].filter(Boolean);
+7 -3
View File
@@ -2,11 +2,11 @@
import type { CLICommand } from "src/types/excalidrawCliTypes";
import { CLI_COMMANDS } from "./cliCommands";
import { CLI_OPERATION_FIELDS } from "./cliApply";
import { CLI_SHAPES, CLI_STYLE_FIELDS } from "./cliElements";
import { CLI_MAX_LINEAR_POINTS, CLI_SHAPES, CLI_STYLE_FIELDS } from "./cliElements";
import { CLI_ICON_FIELDS } from "./cliIcons";
const required: Partial<Record<CLICommand, string[]>> = {
schema: ["action"], read: ["path"], open: ["path"], create: ["requestId", "path"],
schema: ["action"], read: ["path"], selection: ["path"], open: ["path"], create: ["requestId", "path"],
apply: ["requestId", "path", "expectedRevision", "operations"], export: ["requestId", "path", "out"],
script: ["requestId", "script", "trusted"], result: ["requestId"],
};
@@ -16,6 +16,10 @@ const operationRequired: Record<string, string[]> = {
group: ["ids"], ungroup: ["ids", "groupId"], image: ["asset"], imageMetadata: ["id"], latex: ["text"],
};
function property(name: string): Record<string, unknown> {
if (name === "x") return { type: "number", description: "For text skeletons, x is the left/center/right alignment anchor according to textAlign. Existing-element updates use the scene element's x coordinate." };
if (name === "polygon") return { type: "boolean", description: "Line elements only. True requires at least four points, last equal to first; the CLI does not reshape the path. False retains regular line semantics; a closed path can still fill from backgroundColor." };
if (name === "anchor") return { type: "boolean", default: true, description: "With scale=false, anchor the image/drawing embed to 100% of its source size. With scale=true this option has no effect." };
if (name === "asset") return { type: "string", description: "Exact vault path of a raster image, SVG or plugin-recognized Excalidraw drawing (including .excalidraw.md). Ordinary Markdown notes and self-embeds are refused." };
if (["x", "y", "size", "width", "height", "angle", "fontSize", "fontFamily", "opacity", "strokeWidth", "roughness", "offset", "limit", "padding", "scale", "scaleX", "scaleY", "maxWidth", "maxHeight", "maxPixels", "maxArtifactBytes"].includes(name)) return { type: "number" };
if (name === "icons") return { type: "array", maxItems: 100, items: { type: "object", required: ["id", "icon"], additionalProperties: false, properties: Object.fromEntries(CLI_ICON_FIELDS.map(field => [field, property(field)])) } };
if (["overwrite", "trusted", "selectedOnly", "locked"].includes(name)) return { type: "boolean" };
@@ -45,7 +49,7 @@ function property(name: string): Record<string, unknown> {
};
if (name === "tags") return { anyOf: [{ type: "null" }, { type: "array", maxItems: 12, uniqueItems: true, items: { type: "string", maxLength: 32 } }] };
if (["area", "roundness", "label", "start", "end"].includes(name)) return { type: "object" };
if (name === "points") return { type: "array", minItems: 2, maxItems: 100, items: { type: "array", minItems: 2, maxItems: 2, items: { type: "number" } } };
if (name === "points") return { type: "array", minItems: 2, maxItems: CLI_MAX_LINEAR_POINTS, description: "Line/arrow contour points; up to 100000 points across a skeleton batch.", items: { type: "array", minItems: 2, maxItems: 2, items: { type: "number" } } };
if (name === "link") return { type: ["string", "null"] };
return { type: "string" };
}
+14
View File
@@ -0,0 +1,14 @@
/** Invocation identity stays with the one-shot EA, never a shared current-script flag. */
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
const cliScripts = new WeakSet<ExcalidrawAutomate>();
/** Whether an EA belongs to a currently executing native CLI script. */
export const isCLIScript = (ea: ExcalidrawAutomate): boolean => cliScripts.has(ea);
/** Releases the invocation marker even when execution or result serialization fails. */
export async function withCLIScriptContext<T>(ea: ExcalidrawAutomate, run: () => Promise<T>): Promise<T> {
cliScripts.add(ea);
try { return await run(); }
finally { cliScripts.delete(ea); }
}
+5 -1
View File
@@ -5,6 +5,7 @@ import type { ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
import { CLIError, boolean, jsonValue, vaultPath } from "./cliProtocol";
import { drawingFile, drawingView, liveIdentity } from "./cliTarget";
import { sameCLIIdentity } from "./cliIdentity";
import { withCLIScriptContext } from "./cliScriptContext";
/** Source content participates in the effective request identity, including cached scripts. */
export async function prepareScript(cli: ExcalidrawCLI, request: Record<string, unknown>) {
@@ -35,10 +36,13 @@ export async function executeScript(cli: ExcalidrawCLI, request: Record<string,
const outcome: Partial<ExcalidrawCLIResult> = { mutation: "unknown", persistence: "unknown", ...(view ? { target: { vault: plugin.app.vault.getName(), path: drawing.path, viewId: view.id } } : {}) };
let started = false;
try {
const value = await plugin.scriptEngine.executeScriptFileForCLI(prepared.file, view ?? undefined, ea, request.args ?? null, plugin.getCLIRuntime(), prepared.source, () => { check(); started = true; });
const value = await withCLIScriptContext(ea, () => plugin.scriptEngine.executeScriptFileForCLI(prepared.file, view ?? undefined, ea, request.args ?? null, plugin.getCLIRuntime(), prepared.source, () => { check(); started = true; }));
return { ...outcome, data: jsonValue(value === undefined ? null : value), warnings: ["Script completion does not verify drawing persistence. Trusted scripts must await their writes and saves."] };
} catch (error) {
if (!started && error instanceof CLIError) throw error;
if (error instanceof CLIError && error.code === "DEPENDENCY_UNAVAILABLE") {
throw new CLIError(error.code, error.message, error.field, error.recovery, outcome);
}
const interaction = error instanceof Error && error.message.startsWith("INTERACTION_REQUIRED:");
throw new CLIError(interaction ? "INTERACTION_REQUIRED" : started ? "OUTCOME_UNKNOWN" : "SCRIPT_FAILED", interaction ? error.message : "Script execution or result serialization failed.", undefined, "Inspect drawing/output before retrying; script side effects cannot be rolled back.", started ? outcome : {});
}
+41
View File
@@ -0,0 +1,41 @@
/** Stable selection handoff uses the existing live revision and never changes the scene. */
import type ExcalidrawPlugin from "src/core/main";
import type ExcalidrawView from "src/view/ExcalidrawView";
import type { ExcalidrawCLI } from "src/core/managers/ExcalidrawCLI";
import { CLIError } from "./cliProtocol";
/** Capture selected elements plus their bound labels before focus/selection can change. */
export function selectionPacket(cli: ExcalidrawCLI, view: ExcalidrawView) {
const revision = cli.targets.revision(view);
const all = view.excalidrawAPI.getSceneElements().filter(element => !element.isDeleted);
const byId = new Map(all.map(element => [element.id, element]));
const selected = view.excalidrawAPI.getAppState().selectedElementIds;
const included = new Set(all.filter(element => selected[element.id]).map(element => element.id));
if (!included.size) throw new CLIError("INVALID_INPUT", "Select elements in the requested live drawing first.");
for (const id of [...included]) {
for (const bound of byId.get(id).boundElements ?? []) {
if (bound.type === "text" && byId.get(bound.id)?.type === "text") included.add(bound.id);
}
}
if (included.size > 500) throw new CLIError("INVALID_INPUT", "Select at most 500 elements including bound labels.");
const lib = cli.plugin.getCLIRuntime();
const elements = all.filter(element => included.has(element.id)).map(element => {
const labelId = element.boundElements?.find(bound => bound.type === "text" && included.has(bound.id))?.id ?? null;
const label = labelId ? byId.get(labelId) : null;
const text = element.type === "text" ? element.originalText ?? element.text : label?.type === "text" ? label.originalText ?? label.text : null;
const bounds = lib.getCommonBounds([element]);
if (!bounds.every(Number.isFinite)) throw new CLIError("INVALID_INPUT", "Selection contains invalid bounds.");
return { id: element.id, type: element.type, selected: selected[element.id] === true, text,
frameId: element.frameId ?? null, containerId: element.type === "text" ? element.containerId ?? null : null, labelId, bounds };
});
return { packetVersion: 1, vault: cli.plugin.app.vault.getName(), path: view.file.path, view: view.id, revision, elements };
}
/** Copy only the packet captured for the command's original view, using its owning clipboard. */
export async function copySelectionPacket(plugin: ExcalidrawPlugin, view: ExcalidrawView): Promise<void> {
const clipboard = view.containerEl.ownerDocument.defaultView?.navigator.clipboard;
if (!clipboard) throw new Error("Clipboard unavailable");
const result = await plugin.executeCLI({ apiVersion: 1, command: "selection", path: view.file.path, view: view.id });
if (!result.ok) throw new Error("Selection could not be captured");
await clipboard.writeText(JSON.stringify(result.data, null, 2));
}
+9
View File
@@ -0,0 +1,9 @@
/** Optional script readiness is separate from plugin startup and never starts a script. */
export function mindMapBuilderStatus() {
// This separately installed script has no package declaration to import.
const api = Object.getOwnPropertyDescriptor(window, "MindMapBuilderAPI")?.value as
{ ready?: () => boolean } | undefined;
const available = typeof api?.ready === "function";
try { return { available, ready: available && api.ready() === true }; }
catch { return { available, ready: false }; }
}
+1
View File
@@ -23,6 +23,7 @@ export type { Point } from "src/types/types";
export type { MathJaxRenderOptions } from "src/types/mathJaxTypes";
export type { LucideIconOptions, LucideIconResult, LucideIconEntry } from "src/types/lucideTypes";
export type { ExcalidrawCLIRequest, ExcalidrawCLIResult, CLICommand, CLIJSON } from "src/types/excalidrawCliTypes";
export type { StrokeConversionOptions, StrokeConversionResult, ConcatenateLinesOptions, ConcatenateLinesResult } from "src/types/strokeConversionTypes";
export const getEA = (view?: ExcalidrawView): ExcalidrawAutomate | null => {
try {
return window.ExcalidrawAutomate.getAPI(view);
+12
View File
@@ -36,6 +36,7 @@ import { ExcalidrawAutomate } from "../../shared/ExcalidrawAutomate";
import { search } from "src/utils/excalidrawAutomateUtils";
import { selectDrawingTemplate } from "../../shared/Dialogs/TemplatePrompt";
import { t } from "../../lang/helpers";
import { copySelectionPacket } from "src/core/cli/cliSelection";
import {
createOrOverwriteFile,
getAliasWithSize,
@@ -912,6 +913,17 @@ export class CommandManager {
},
});
this.addCommand({
id: "copy-selection-for-agent",
name: t("CLI_COPY_SELECTION"),
checkCallback: (checking: boolean) => {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (!view?.excalidrawAPI || !view.getViewSelectedElements().length) return false;
if (!checking) void copySelectionPacket(this.plugin, view).catch(() => new Notice(t("CLI_COPY_SELECTION_ERROR")));
return true;
},
});
this.addCommand({
id: "disable-frameclipping",
name: t("TOGGLE_FRAME_CLIPPING"),
+8 -1
View File
@@ -14,6 +14,8 @@ import { commandSchema } from "src/core/cli/cliSchema";
import { imageInventory } from "src/core/cli/cliImages";
import { nanoid } from "src/constants/constants";
import { getLucideIcons } from "src/shared/lucideIcons";
import { mindMapBuilderStatus } from "src/core/cli/cliStatus";
import { selectionPacket } from "src/core/cli/cliSelection";
type Receipt = { fingerprint: string; result: ExcalidrawCLIResult; finishedAt?: number; preExecutionBusy?: boolean };
@@ -178,7 +180,7 @@ export class ExcalidrawCLI {
if (request.format !== undefined && !["json", "markdown"].includes(string(request.format, "format"))) throw new CLIError("INVALID_INPUT", "Expected json or markdown.", "format");
return { markdown: CLI_SKILL };
}
if (command === "status") return { apiVersion: 1, nativeCLI: Platform.isDesktop && requireApiVersion("1.12.2") && typeof (plugin as ExcalidrawPlugin & Partial<ObsidianCliRuntime>).registerCliHandler === "function", ready: plugin.isReady, vault: plugin.app.vault.getName(), version: plugin.manifest.version, converter: plugin.isReady && typeof plugin.getCLIRuntime().convertToExcalidrawElements === "function", lucideIcons: plugin.isReady, receiptTTLSeconds: 900, receiptCapacity: 128 };
if (command === "status") return { apiVersion: 1, nativeCLI: Platform.isDesktop && requireApiVersion("1.12.2") && typeof (plugin as ExcalidrawPlugin & Partial<ObsidianCliRuntime>).registerCliHandler === "function", ready: plugin.isReady, vault: plugin.app.vault.getName(), version: plugin.manifest.version, converter: plugin.isReady && typeof plugin.getCLIRuntime().convertToExcalidrawElements === "function", lucideIcons: plugin.isReady, extras: plugin.extrasGateway?.getStatus() ?? null, mindMapBuilder: mindMapBuilderStatus(), receiptTTLSeconds: 900, receiptCapacity: 128 };
if (command === "schema") {
const action = string(request.action, "action");
if (!Object.hasOwn(CLI_COMMANDS, action)) throw new CLIError("UNSUPPORTED_COMMAND", "Unknown action.", "action");
@@ -192,6 +194,11 @@ export class ExcalidrawCLI {
return { surface, subset: surface === "lib", entries: entries.filter(entry => request.name ? entry.name.toLowerCase() === query : `${entry.name} ${entry.description}`.toLowerCase().includes(query)).slice(0, 20) };
}
if (!plugin.isReady) throw new CLIError("NOT_READY", "Excalidraw is still initializing.", undefined, "Retry status after startup.");
if (command === "selection") {
const file = drawingFile(plugin, request.path), view = drawingView(plugin, file, request.view);
if (!view) throw new CLIError("NOT_READY", "Selection requires an open live drawing.", "path");
return selectionPacket(this, view);
}
if (command === "icons") {
const query = request.query === undefined ? "" : request.query;
if (typeof query !== "string" || query.length > 128) throw new CLIError("INVALID_INPUT", "Expected an icon query of at most 128 characters.", "query");
+2
View File
@@ -90,6 +90,8 @@ export default {
CLI_COPY_SKILL: "Copy agent instructions",
CLI_AGENT_INSTRUCTIONS: `Read: ${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<user instructions>>`,
CLI_DESCRIPTION: "Native Excalidraw CLI",
CLI_COPY_SELECTION: "Copy selected elements for agent",
CLI_COPY_SELECTION_ERROR: "Could not copy the selected elements. Select fewer elements and try again.",
INITIALIZATION_MESSAGE:
"Excalidraw is waiting for Obsidian to initialize all of your plugins...",
+2
View File
@@ -90,6 +90,8 @@ export default {
CLI_COPY_SKILL: "Copiar instrucciones para agentes",
CLI_AGENT_INSTRUCTIONS: `Lee: ${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<instrucciones del usuario>>`,
CLI_DESCRIPTION: "CLI nativa de Excalidraw",
CLI_COPY_SELECTION: "Copiar elementos seleccionados para el agente",
CLI_COPY_SELECTION_ERROR: "No se pudieron copiar los elementos seleccionados. Selecciona menos elementos e inténtalo de nuevo.",
// Sugester
SELECT_FILE_TO_INSERT: "Selecciona un archivo para insertar",
+2
View File
@@ -88,6 +88,8 @@ export default {
CLI_COPY_SKILL: "Копировать инструкции для агентов",
CLI_AGENT_INSTRUCTIONS: `Прочитай: ${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<инструкции пользователя>>`,
CLI_DESCRIPTION: "Нативный CLI Excalidraw",
CLI_COPY_SELECTION: "Копировать выбранные элементы для агента",
CLI_COPY_SELECTION_ERROR: "Не удалось скопировать выбранные элементы. Выберите меньше элементов и повторите попытку.",
// main.ts
SETTINGS_DATA_INVALID:
+2
View File
@@ -85,6 +85,8 @@ export default {
CLI_COPY_SKILL: "复制智能体说明",
CLI_AGENT_INSTRUCTIONS: `阅读:${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<用户指令>>`,
CLI_DESCRIPTION: "Excalidraw 原生 CLI",
CLI_COPY_SELECTION: "复制所选元素供智能体使用",
CLI_COPY_SELECTION_ERROR: "无法复制所选元素。请减少所选元素后重试。",
INITIALIZATION_MESSAGE: "等待所有插件就绪…",
// Sugester
+2
View File
@@ -85,6 +85,8 @@ export default {
CLI_COPY_SKILL: "複製代理程式說明",
CLI_AGENT_INSTRUCTIONS: `閱讀:${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_CLI}\n\n<<使用者指令>>`,
CLI_DESCRIPTION: "Excalidraw 原生 CLI",
CLI_COPY_SELECTION: "複製所選元素供代理程式使用",
CLI_COPY_SELECTION_ERROR: "無法複製所選元素。請減少所選元素後重試。",
INITIALIZATION_MESSAGE: "等待所有外掛就緒…",
// Sugester
@@ -3,12 +3,13 @@ import type { ExcalidrawFrameElement } from "@zsviczian/excalidraw/types/element
import type ExcalidrawView from "src/view/ExcalidrawView";
import type { EmbeddedFile } from "src/shared/EmbeddedFileLoader";
import { getDrawingPreviewParts, rewriteDrawingPreviewLink, type DrawingPreviewChanges } from "src/utils/drawingPreviewLink";
import { setStyle } from "src/utils/styleUtils";
import { FloatingModal } from "./FloatingModal";
import { t } from "src/lang/helpers";
import { OUTER_PADDING_MAX } from "src/utils/drawingPadding";
/** Draft image-link controls: preview locally, then commit once after choosing scope. */
export class DrawingImagePreviewPopover extends Component {
export class DrawingImagePreviewPopover extends FloatingModal {
private events: Component | null = null;
private popup: HTMLElement;
private image: HTMLImageElement;
private timer: number | null = null;
@@ -18,20 +19,27 @@ export class DrawingImagePreviewPopover extends Component {
private readonly original: string;
private readonly changes: DrawingPreviewChanges = {};
constructor(private readonly view: ExcalidrawView, private readonly source: EmbeddedFile,
constructor(view: ExcalidrawView, private readonly source: EmbeddedFile,
private readonly frames: readonly ExcalidrawFrameElement[], private readonly defaultPadding: number, private readonly areaPaddingMax: number,
private readonly isCurrent: () => boolean,
private readonly render: (link: string) => Promise<{ image: { dataURL: string } }>,
private readonly commit: (changes: DrawingPreviewChanges) => Promise<boolean>, private readonly closed: () => void) {
super(); this.original = source.linkParts.original;
super(view.app); this.original = source.linkParts.original;
}
/** Mount in the selected image's owning window, outside canvas paint containment. */
onload(): void {
protected shouldNotStartDrag(target: HTMLElement, event: PointerEvent | TouchEvent): boolean {
return !!target.closest(".setting-item-control") || super.shouldNotStartDrag(target, event);
}
/** Use the shared draggable modal without blocking interaction with the drawing. */
onOpen(): void {
this.active = true;
const doc = this.view.ownerDocument, win = doc.defaultView;
this.popup = doc.body.createDiv({ cls: "excalidraw-drawing-preview-popover", attr: { role: "dialog", "aria-label": t("PREVIEW_CONFIGURE") } });
this.popup.createEl("strong", { text: t("PREVIEW_CONFIGURE") });
this.events = new Component(); this.events.load();
const doc = this.modalEl.ownerDocument;
this.modalEl.addClass("excalidraw-drawing-preview-popover");
this.modalEl.setAttribute("aria-label", t("PREVIEW_CONFIGURE"));
this.setTitle(t("PREVIEW_CONFIGURE"));
this.popup = this.contentEl;
this.popup.createDiv({ cls: "setting-item-description", text: t("PREVIEW_CONFIGURE_HELP") });
this.image = this.popup.createDiv({ cls: "excalidraw-drawing-preview-image" }).createEl("img", { attr: { alt: t("PREVIEW_VIEW") } });
const parts = getDrawingPreviewParts(this.original), ref = parts.blockref ?? parts.sectionref;
@@ -86,36 +94,24 @@ export class DrawingImagePreviewPopover extends Component {
const buttons = this.popup.createDiv({ cls: "excalidraw-drawing-preview-buttons" });
const cancel = buttons.createEl("button", { text: t("PROMPT_BUTTON_CANCEL"), attr: { type: "button" } });
const apply = buttons.createEl("button", { text: t("PREVIEW_APPLY"), cls: "mod-cta", attr: { type: "button" } });
this.registerDomEvent(cancel, "click", () => { if (!this.applying) this.unload(); });
this.events.registerDomEvent(cancel, "click", () => { if (!this.applying) this.close(); });
const save = async () => {
if (this.applying || !this.current()) return;
if (!Object.keys(this.changes).length) { this.unload(); return; }
if (!Object.keys(this.changes).length) { this.close(); return; }
this.applying = true; apply.disabled = true;
try { if (await this.commit({ ...this.changes })) this.unload(); }
try { if (await this.commit({ ...this.changes })) this.close(); }
finally { this.applying = false; apply.disabled = false; }
};
this.registerDomEvent(apply, "click", () => { void save(); });
this.registerDomEvent(this.popup, "pointerdown", event => event.stopPropagation());
this.registerDomEvent(this.popup, "wheel", event => event.stopPropagation());
this.registerDomEvent(doc, "pointerdown", event => { if (!this.applying && !event.composedPath().includes(this.popup)) this.unload(); });
this.registerDomEvent(doc, "keydown", event => {
if (event.key === "Escape" && !this.applying) { event.preventDefault(); event.stopPropagation(); this.unload(); }
this.events.registerDomEvent(apply, "click", () => { void save(); });
this.events.registerDomEvent(this.popup, "wheel", event => event.stopPropagation());
this.events.registerDomEvent(doc, "keydown", event => {
if (event.key === "Escape" && !this.applying) { event.preventDefault(); event.stopPropagation(); this.close(); }
}, true);
this.registerDomEvent(win, "resize", () => this.place());
this.registerDomEvent(win, "blur", () => { if (!this.applying) this.unload(); });
this.place(); this.queuePreview(); this.popup.querySelector("select")?.focus();
this.queuePreview();
}
private current(): boolean { return this.active && this.isCurrent(); }
private place(): void {
if (!this.current()) { this.unload(); return; }
const anchor = this.view.excalidrawContainer.querySelector(".excalidraw-selected-element-menu") ?? this.view.excalidrawContainer;
const bounds = anchor.getBoundingClientRect(), popup = this.popup.getBoundingClientRect(), win = this.popup.ownerDocument.defaultView;
setStyle(this.popup, { left: `${Math.max(8, Math.min(bounds.left, win.innerWidth - popup.width - 8))}px`,
top: `${Math.max(8, Math.min(bounds.bottom + 4, win.innerHeight - popup.height - 8))}px` });
}
private queuePreview(): void {
const generation = ++this.generation;
if (this.timer !== null) window.clearTimeout(this.timer);
@@ -124,15 +120,17 @@ export class DrawingImagePreviewPopover extends Component {
if (!link || !this.current()) return;
try {
const result = await this.render(link);
if (this.current() && generation === this.generation) { this.image.src = result.image.dataURL; this.place(); }
if (this.current() && generation === this.generation) { this.image.src = result.image.dataURL; }
} catch { /* The owned controller reports apply failures; a stale draft never writes. */ }
})(); }, 300);
}
/** Cancel delayed renders and release this window's controls without a scene write. */
onunload(): void {
onClose(): void {
if (!this.active) return;
this.active = false; this.generation++;
if (this.timer !== null) window.clearTimeout(this.timer);
this.timer = null; this.popup?.remove(); this.closed();
this.timer = null; this.events?.unload(); this.events = null;
this.contentEl.empty(); this.closed();
}
}
+7 -1
View File
@@ -98,6 +98,7 @@ function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
export class FloatingModal extends Modal {
private dragging = false;
private openTimer: number | null = null;
private offsetX = 0;
private offsetY = 0;
private readonly pointerDownHandler: (e: PointerEvent | TouchEvent) => void;
@@ -270,7 +271,8 @@ export class FloatingModal extends Modal {
// prevent automatic selection / focus restoration
this.shouldRestoreSelection = false;
}
window.setTimeout(() => {
this.openTimer = window.setTimeout(() => {
this.openTimer = null;
const { containerEl, modalEl, bgEl } = this;
containerEl.addClass("mod-excalidraw-draggable");
@@ -336,6 +338,10 @@ export class FloatingModal extends Modal {
}
close(): void {
if (this.openTimer !== null) {
window.clearTimeout(this.openTimer);
this.openTimer = null;
}
// Optional: restore previous focus if body ended up focused
if (
this.disableKeyCapture &&
+17 -1
View File
@@ -17,6 +17,11 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.29.4": `
## New and improved
- Copy selected canvas elements for an agent to edit, including their bound labels and exact drawing targets. CLI agents can also insert linked drawing images and create longer filled line contours.
- Scripts can convert between lines and free-draw strokes while preserving curved paths, and join compatible line sections. Custom free-draw styling can look different on excalidraw.com.
`,
"2.29.3": `
## New and improved
- Choose OpenAI reasoning effort per text model and use updated AI model recommendations on new installs. ExcaliAI uses the selected model's effort. [#3056](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3056).
@@ -24,10 +29,21 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
- Create a **New Drawing** from empty tabs. Hide this action and the ribbon icon independently in settings. [#3047](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3047).
- PNG fullscreen previews open faster, then sharpen in the background while preserving zoom and pan.
- Press P again while using the pen to return to the selection tool. [#3044](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3044).
- Configure drawing images directly in the scene: choose a view, padding and original-size anchoring, then update one image or all copies of the same drawing.
- Configure nested excalidraw images directly in the scene: choose a view, padding and original-size anchoring, then update one image or all copies of the same drawing.
- Choose a named frame or marker frame as the drawing thumbnail, pick frames from embed controls, and use **Navigate to frame** to jump within a drawing. Named frames are listed in the document's \`excalidraw-anchors\` property. [#3042](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3042).
- Adjust outer padding for thumbnails, whole scenes and frames, or expand the captured area of \`area=\` drawing embeds from their Live Preview toolbar. Preview changes with the slider, then close it to save; Escape cancels. Inspired by 🙏[Evgene-Kopylov](${URLs.GITHUB_COM}/Evgene-Kopylov) [#2868](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2868).
## New and improved from Excalidraw.com
- **Keep editing across apps.** Switching to another app and back no longer ends text editing. [#12675](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12675).
- **Flowchart navigation.** Alt/Option+arrow keys choose nearby nodes more predictably, including in uneven layouts. [#12646](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12646).
- **Drawing minimap and zoom menu.** Navigate large drawings with the minimap beside the zoom level on desktop/tablet, or select the zoom level for zoom-to-fit and zoom-to-selection. [#12605](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12605).
- **Text wrapping.** Drag the sides of standalone text while editing to set its wrap width, or toggle auto-resize with Alt/Option+W. [#12634](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12634), [#12672](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12672).
- **Zoom while editing.** Keyboard zoom keeps the text cursor in place on screen. [#12622](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12622).
- **Steadier text.** Center- and right-aligned text no longer jumps while typing at different zoom levels. [#12623](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12623).
- **Wrap and unwrap.** W includes enclosed elements when framing a selection and keeps existing shapes when detaching their text. [#12638](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12638).
- **Smoother large drawings.** Pan large scenes and draw frames around large groups with less lag. [#12489](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12489), [#12692](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12692).
- **Toolbar hints.** Your **Preferences → Toolbar hints** choice is now saved with each drawing. [#12165](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/12165).
## Fixed
- Scroll embedded Markdown directly in reading mode, including when **Lock to reading mode** is enabled. [#3055](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3055).
- Drawing embed controls appear in Live Preview tables and remain reachable in phone Reading view. [#3049](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/3049).
+20 -1
View File
@@ -500,7 +500,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"Creates a mermaid diagram and returns the ids of the created elements as a string[]. " +
"The elements will be added to ea. To add them to the canvas you'll need to use addElementsToView. " +
"Depending on the diagram type the result will be either a single SVG image, or a number of excalidraw elements.<br>" +
"If there is an error, the function returns a string with the error message.",
"If there is an error, the function returns a string with the error message. " +
"In one-shot CLI scripts, unavailable, disabled or incompatible Excalidraw Extras Mermaid throws DEPENDENCY_UNAVAILABLE without opening an activation modal; inspect CLI status.extras before conversion.",
after: "",
},
{
@@ -527,6 +528,24 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Adds a text label to a line or arrow. Currently only works with a simple straight 2-point (start & end) line",
after: "",
},
{
field: "convertLineToFreedraw",
after: "",
code: "convertLineToFreedraw(id: string, options?: StrokeConversionOptions): StrokeConversionResult;",
desc: "Converts a line already copied into the EA workbench to free-draw, retaining its ID, frame, groups and unrelated metadata. Rounded curves are sampled within tolerance (default 0.5 scene units); maxPoints defaults to 10000. Options also accept strokeWidth and the fork's full penOptions. Returns id, type, pointCount and warnings. Custom options are ignored by excalidraw.com. Labels/arrowheads and exceeded budgets are refused without mutation. Publish and save explicitly.",
},
{
field: "convertFreedrawToLine",
after: "",
code: "convertFreedrawToLine(id: string, options?: StrokeConversionOptions): StrokeConversionResult;",
desc: "Fits a copied workbench free-draw centerline to an editable polyline, retaining its ID. tolerance bounds simplification error (default 0.5 scene units); maxPoints defaults to 10000. Pressure, taper and custom cap/outline behavior are removed. Nominal width is approximated unless strokeWidth is supplied. Returns JSON-safe id, type, pointCount and warnings. Does not publish/save; invalid input leaves the workbench unchanged.",
},
{
field: "concatenateLines",
after: "",
code: "concatenateLines(ids: string[], options?: ConcatenateLinesOptions): ConcatenateLinesResult;",
desc: "Joins 2–100 compatible open workbench lines by nearby endpoints, allowing reversed/rotated paths and sharp corners. maxGap defaults to 1 scene unit, tolerance to 0.5, maxPoints to 10000. Rounded segments are sampled before joining. The first ID survives and removedIds are staged as deleted. Styles, frame, groups and metadata must match; labels, arrowheads and disconnected/branching sets are refused without partial mutation. Returns id, removedIds, pointCount and warnings. Publish/save explicitly.",
},
{
field: "clear",
code: "clear(): void;",
+44
View File
@@ -4,6 +4,11 @@ import type { LucideIconOptions, LucideIconResult } from "src/types/lucideTypes"
import ExcalidrawPlugin from "src/core/main";
import LZString from "lz-string";
import type { ExcalidrawCLIRequest, ExcalidrawCLIResult } from "src/types/excalidrawCliTypes";
import { isCLIScript } from "src/core/cli/cliScriptContext";
import { CLIError } from "src/core/cli/cliProtocol";
import { convertWorkbenchStroke } from "src/utils/strokeConversion";
import { concatenateWorkbenchLines } from "src/utils/strokeConcatenation";
import type { ConcatenateLinesOptions, ConcatenateLinesResult, StrokeConversionOptions, StrokeConversionResult } from "src/types/strokeConversionTypes";
import {
FillStyle,
StrokeStyle,
@@ -1402,6 +1407,36 @@ export class ExcalidrawAutomate {
return this.elementsDict[id];
}
/**
* Convert a copied workbench line to a free-draw stroke, sampling rounded curves
* within tolerance (default 0.5 scene units). Retains its ID/frame/groups/metadata.
* Custom pen options are ignored by excalidraw.com. Returns warnings and point count;
* does not publish/save. Throws before mutation for unsupported relationships or budgets.
*/
public convertLineToFreedraw(id: string, options: StrokeConversionOptions = {}): StrokeConversionResult {
return convertWorkbenchStroke(this, id, "freedraw", options);
}
/**
* Fit a copied workbench free-draw centerline to an editable polyline, retaining ID.
* Default error tolerance is 0.5 scene units. Pressure/custom pen behavior is lost;
* nominal width is approximated unless strokeWidth is supplied. Does not publish/save.
* Throws without mutation on invalid input or exceeded geometry/work budgets.
*/
public convertFreedrawToLine(id: string, options: StrokeConversionOptions = {}): StrokeConversionResult {
return convertWorkbenchStroke(this, id, "line", options);
}
/**
* Join 2–100 compatible open workbench lines through nearby endpoints (default gap 1).
* Samples rounded segments, handles reversed/rotated paths and keeps sharp junctions.
* Retains the first ID; stages the other IDs as deleted. Rejects disconnected sets,
* incompatible styles/metadata and labels/arrowheads without any mutation. Publish/save explicitly.
*/
public concatenateLines(ids: string[], options: ConcatenateLinesOptions = {}): ConcatenateLinesResult {
return concatenateWorkbenchLines(this, ids, options);
}
/**
* Returns an object describing the bound text element.
*
@@ -2953,11 +2988,20 @@ export class ExcalidrawAutomate {
* @param {string} diagram - The mermaid diagram string.
* @param {boolean} [groupElements=true] - Whether to group the elements.
* @returns {Promise<string[]|string>} Promise resolving to the IDs of the created elements or an error message.
* @throws CLI dependency error when Extras Mermaid is unavailable, disabled or incompatible in a one-shot CLI invocation.
*/
async addMermaid(
diagram: string,
groupElements: boolean = true,
): Promise<string[] | string> {
if (isCLIScript(this)) {
const gateway = this.plugin.extrasGateway;
const api = gateway.getAPI();
if (!api || !gateway.checkVersion("mermaid", api).valid || !api.features.isActive("mermaid")) {
throw new CLIError("DEPENDENCY_UNAVAILABLE", "CLI Mermaid conversion requires compatible, enabled Excalidraw Extras Mermaid.", undefined,
"Inspect status.extras, update Excalidraw Extras and enable Mermaid before retrying. Read back any earlier script writes first.");
}
}
const result = await mermaidToExcalidraw(diagram, {
themeVariables: { fontSize: `${this.style.fontSize}` },
flowchart: { curve: this.style.roundness === null ? "linear" : "basis" },
+1 -1
View File
@@ -1,6 +1,6 @@
/** Versioned JSON protocol shared by native CLI and Excalidraw Automate. */
export type CLIJSON = null | boolean | number | string | CLIJSON[] | { [key: string]: CLIJSON };
export type CLICommand = "help" | "status" | "schema" | "api" | "icons" | "list" | "read" | "open" | "create" | "apply" | "export" | "script" | "skill" | "result";
export type CLICommand = "help" | "status" | "schema" | "api" | "icons" | "list" | "read" | "selection" | "open" | "create" | "apply" | "export" | "script" | "skill" | "result";
/** Command-specific fields are validated against the runtime `schema` action. */
export interface ExcalidrawCLIRequest {
+32
View File
@@ -0,0 +1,32 @@
import type { PenOptions } from "./penTypes";
/** Explicit geometric approximation limits in scene units, independent of zoom. */
export interface StrokeConversionOptions {
tolerance?: number;
maxPoints?: number;
strokeWidth?: number;
penOptions?: PenOptions;
}
/** Workbench-only conversion acknowledgment; publication and saving remain explicit. */
export interface StrokeConversionResult {
id: string;
type: "line" | "freedraw";
pointCount: number;
warnings: string[];
}
/** Join only neighboring open line endpoints; reject a disconnected selection atomically. */
export interface ConcatenateLinesOptions {
maxGap?: number;
tolerance?: number;
maxPoints?: number;
}
/** The first input ID survives; other joined IDs are staged as deleted. */
export interface ConcatenateLinesResult {
id: string;
removedIds: string[];
pointCount: number;
warnings: string[];
}
+21
View File
@@ -146,6 +146,27 @@ export class ExcalidrawExtrasGateway {
? api : null;
}
/** Read-only component readiness; never activates features, loads modules or opens a modal. */
public getStatus() {
const api = this.getAPI();
const components: ExtrasComponent[] = ["mathjax", "mermaid", "pdf", "filesystem"];
return {
installed: this.isInstalled(),
enabled: this.isPluginEnabled(),
pluginVersion: this.app.plugins.manifests[EXTRAS_PLUGIN_ID]?.version ?? null,
components: Object.fromEntries(components.map(component => {
const required = REQUIRED_EXTRAS_VERSIONS[component];
return [component, {
version: api?.versions[component] ?? null,
active: api?.features.isActive(component) === true,
compatible: api ? this.checkVersion(component, api).valid : false,
requiredVersion: required.exact ?? required.min,
exact: required.exact !== undefined,
}];
})),
};
}
public checkVersion(
component: string,
api: ExcalidrawExtrasAPI,
+6
View File
@@ -5,6 +5,12 @@ import type {
ExcalidrawImageElement,
} from "@zsviczian/excalidraw/types/element/src/types";
import type { PDFPageViewProps } from "src/types/embeddedFileLoaderTypes";
import type { PenOptions } from "src/types/penTypes";
/** Write/remove only the fork-owned custom-pen namespace, retaining unrelated metadata. */
export function setFreedrawPenOptions(element: Mutable<ExcalidrawElement>, options?: PenOptions): void {
addAppendUpdateCustomData(element, { strokeOptions: options ? structuredClone(options) : undefined });
}
export const MARKDOWN_IMAGE_CUSTOM_DATA_KEY = "markdownImage";
+54
View File
@@ -0,0 +1,54 @@
/** Join nearby open line centerlines without tangent restrictions or partial workbench mutations. */
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import type { ConcatenateLinesOptions, ConcatenateLinesResult } from "src/types/strokeConversionTypes";
import type { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import type { ExcalidrawLineElement } from "@zsviczian/excalidraw/types/element/src/types";
import { cloneElement } from "./excalidrawElementUtils";
import { simplifyStroke, strokeCenterline, strokeGeometry, strokeLimit } from "./strokeGeometry";
import type { StrokePoint } from "./strokeGeometry";
/** The first line's ID survives; all other joined copies become tombstones until explicit publication. */
export function concatenateWorkbenchLines(ea: ExcalidrawAutomate, ids: string[], options: ConcatenateLinesOptions = {}): ConcatenateLinesResult {
if (!Array.isArray(ids) || ids.length < 2 || ids.length > 100 || new Set(ids).size !== ids.length) throw Error("Choose 2–100 distinct line IDs");
const sources = ids.map(id => ea.getElement(id));
if (sources.some(el => !el || el.isDeleted || el.type !== "line" || el.polygon || el.boundElements?.length || el.startBinding || el.endBinding || el.startArrowhead || el.endArrowhead)) throw Error("Concatenation requires open workbench lines without labels, bindings or arrowheads");
const first = sources[0], compare = ["strokeColor", "backgroundColor", "fillStyle", "strokeWidth", "strokeStyle", "roughness", "opacity", "locked", "link", "frameId", "groupIds", "customData"];
if (sources.some(el => compare.some(key => JSON.stringify(el[key]) !== JSON.stringify(first[key])))) throw Error("Align line styles, groups, frame and metadata explicitly before concatenating");
const maxGap = strokeLimit(options.maxGap, 1, 0, 1000), tolerance = strokeLimit(options.tolerance, 0.5, 0.000001, 10), maxPoints = strokeLimit(options.maxPoints, 10000, 2, 100000);
if (!Number.isInteger(maxPoints)) throw Error("Point budget must be an integer");
const runtime = ea.plugin.getCLIRuntime();
let count = 0;
const paths = sources.map(el => {
if (el.type !== "line") throw Error("Expected line");
const points = strokeCenterline(el, runtime, tolerance / 2, maxPoints);
count += points.length; if (count > 100000) throw Error("Concatenation input point budget exceeded");
return points;
});
let chain = paths[0];
const pending = paths.slice(1);
while (pending.length) {
let best: { index: number; atStart: boolean; reverse: boolean; distance: number } | null = null;
pending.forEach((path, index) => {
for (const atStart of [false, true]) for (const reverse of [false, true]) {
const a = atStart ? chain[0] : chain.at(-1);
const b = atStart ? (reverse ? path[0] : path.at(-1)) : (reverse ? path.at(-1) : path[0]);
const distance = Math.hypot(a[0] - b[0], a[1] - b[1]);
if (distance <= maxGap && (!best || distance < best.distance)) best = { index, atStart, reverse, distance };
}
});
if (!best) throw Error("Selected lines do not form one continuous endpoint chain; leave branches separate");
const next: StrokePoint[] = pending.splice(best.index, 1)[0];
if (best.reverse) next.reverse();
chain = best.atStart ? [...next, ...chain.slice(best.distance < 1e-9 ? 1 : 0)] : [...chain, ...next.slice(best.distance < 1e-9 ? 1 : 0)];
}
chain = simplifyStroke(chain, tolerance / 2);
if (chain.length > maxPoints) throw Error("Stroke point budget exceeded");
const merged: Mutable<ExcalidrawLineElement> & Record<string, unknown> = { ...cloneElement(first), ...strokeGeometry(chain), type: "line", polygon: false, roundness: null,
startBinding: null, endBinding: null, startArrowhead: null, endArrowhead: null, lastCommittedPoint: null };
// No mutation occurs until all geometry/style/budget checks have succeeded.
const removed = sources.slice(1).map(el => ({ ...cloneElement(el), isDeleted: true }));
ea.elementsDict[first.id] = merged;
removed.forEach(el => { ea.elementsDict[el.id] = el; });
return { id: first.id, removedIds: ids.slice(1), pointCount: chain.length,
warnings: sources.some(el => el.roundness) ? ["Rounded segments were sampled into a polyline; rough ink and endpoint joins can render differently."] : [] };
}
+73
View File
@@ -0,0 +1,73 @@
/** Explicit workbench stroke conversion; source scene objects are never mutated. */
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import type { StrokeConversionOptions, StrokeConversionResult } from "src/types/strokeConversionTypes";
import type { PenOptions } from "src/types/penTypes";
import type { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import type { ExcalidrawFreeDrawElement, ExcalidrawLineElement } from "@zsviczian/excalidraw/types/element/src/types";
import { cloneElement } from "./excalidrawElementUtils";
import { setFreedrawPenOptions } from "./elementCustomDataUtils";
import { simplifyStroke, strokeCenterline, strokeGeometry, strokeLimit } from "./strokeGeometry";
/** Uniform default preserves a line's nominal width and sampled centerline in the fork. */
const uniformPen: PenOptions = {
highlighter: false, constantPressure: true, hasOutline: false, outlineWidth: 1,
options: { thinning: 0, smoothing: 0, streamline: 0, easing: "linear", simulatePressure: false,
start: { cap: true, taper: 0, easing: "linear" }, end: { cap: true, taper: 0, easing: "linear" } },
};
/** Validate custom Perfect Freehand values before they can reach the renderer. */
function validatePen(pen: PenOptions): void {
for (const key of ["highlighter", "constantPressure", "hasOutline"] as const) if (typeof pen[key] !== "boolean") throw Error(`Invalid pen ${key}`);
strokeLimit(pen.outlineWidth, 1, 0, 100);
if (!pen.options) throw Error("Pen options are required");
const opts = pen.options;
strokeLimit(opts.thinning, 0, -1, 1); strokeLimit(opts.smoothing, 0, 0, 1); strokeLimit(opts.streamline, 0, 0, 1);
if (typeof opts.easing !== "string" || (opts.simulatePressure !== undefined && typeof opts.simulatePressure !== "boolean")) throw Error("Invalid pen pressure/easing");
for (const tip of [opts.start, opts.end]) {
if (!tip || typeof tip.cap !== "boolean" || typeof tip.easing !== "string") throw Error("Invalid pen tip");
if (typeof tip.taper !== "boolean") strokeLimit(tip.taper, 0, 0, 100000);
}
}
/** Convert a copied workbench line/free-draw stroke, preserving ID, groups, frame and other metadata. */
export function convertWorkbenchStroke(ea: ExcalidrawAutomate, id: string, target: "line" | "freedraw", options: StrokeConversionOptions = {}): StrokeConversionResult {
const source = ea.getElement(id);
if (!source || source.isDeleted || !["line", "freedraw"].includes(source.type) || source.type === target) throw Error("Choose an existing workbench stroke of the opposite type");
if (source.type !== "line" && source.type !== "freedraw") throw Error("Only line/free-draw conversion is supported");
if (source.boundElements?.length || (source.type === "line" && (source.startBinding || source.endBinding || source.startArrowhead || source.endArrowhead))) throw Error("Detach stroke labels, bindings and arrowheads explicitly before conversion");
const tolerance = strokeLimit(options.tolerance, 0.5, 0.000001, 10), maxPoints = strokeLimit(options.maxPoints, 10000, 2, 100000);
if (!Number.isInteger(maxPoints)) throw Error("Point budget must be an integer");
if (target === "line" && options.penOptions !== undefined) throw Error("Custom pen options apply only to free-draw strokes");
const pen = options.penOptions ?? uniformPen;
if (target === "freedraw") validatePen(pen);
const centerline = strokeCenterline(source, ea.plugin.getCLIRuntime(), tolerance, 100000);
const points = target === "line" ? simplifyStroke(centerline, tolerance) : centerline;
if (points.length > maxPoints) throw Error("Stroke point budget exceeded; increase it or use a larger tolerance");
const closed = Math.hypot(points[0][0] - points.at(-1)[0], points[0][1] - points.at(-1)[1]) <= tolerance;
// Exact closure is required for the fork to retain a line's polygon flag on restoration.
if (target === "line" && closed) points[points.length - 1] = [...points[0]];
// cloneElement retains the discriminant; its general return type does not retain this narrowed stroke union.
const geometry = strokeGeometry(points), base = cloneElement(source) as typeof source, warnings: string[] = [];
// The fork renders nominal free-draw width at 4.25 times the element strokeWidth.
const strokeWidth = strokeLimit(options.strokeWidth, source.strokeWidth * (target === "line" ? 4.25 : 1 / 4.25), 0, 10000);
if (target === "freedraw") {
const converted: Mutable<ExcalidrawFreeDrawElement> & Record<string, unknown> = { ...base, ...geometry, type: "freedraw", strokeWidth, roughness: 0, roundness: null,
pressures: points.map(() => 0.5), simulatePressure: pen.options.simulatePressure ?? !pen.constantPressure,
strokeOptions: { variability: "constant" as const, streamline: 0 },
backgroundColor: source.type === "line" && !closed ? "transparent" : source.backgroundColor };
for (const key of ["polygon", "startArrowhead", "endArrowhead", "startBinding", "endBinding", "lastCommittedPoint"]) Reflect.deleteProperty(converted, key);
setFreedrawPenOptions(converted, pen);
ea.elementsDict[id] = converted;
warnings.push("excalidraw.com ignores custom free-draw options; appearance can differ there.");
if (source.roughness) warnings.push("Converted the ideal centerline, not the original rough ink jitter.");
} else {
const converted: Mutable<ExcalidrawLineElement> & Record<string, unknown> = { ...base, ...geometry, type: "line", strokeWidth, roughness: 0,
polygon: closed && points.length >= 4, roundness: null,
startArrowhead: null, endArrowhead: null, startBinding: null, endBinding: null, lastCommittedPoint: null };
for (const key of ["pressures", "simulatePressure", "strokeOptions"]) Reflect.deleteProperty(converted, key);
setFreedrawPenOptions(converted);
ea.elementsDict[id] = converted;
warnings.push("Line conversion removes pressure, taper and custom cap/outline behavior; stroke width is a nominal approximation. Supply strokeWidth to override it.");
}
return { id, type: target, pointCount: points.length, warnings };
}
+95
View File
@@ -0,0 +1,95 @@
/** Bounded centerline sampling uses the same Rough.js curve as the fork's collision geometry. */
import { RoughGenerator } from "roughjs/bin/generator";
import type { ExcalidrawElement, ExcalidrawLinearElement, ExcalidrawLineElement, ExcalidrawFreeDrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import type { Packages } from "src/types/types";
import { segmentDistance } from "src/shared/svgToExcalidraw/pathGeometry";
export type StrokePoint = Parameters<typeof segmentDistance>[0];
export type StrokeElement = ExcalidrawLinearElement | ExcalidrawFreeDrawElement;
/** Reject non-finite limits before allocating or changing any workbench element. */
export function strokeLimit(value: number | undefined, fallback: number, min: number, max: number): number {
const result = value ?? fallback;
if (!Number.isFinite(result) || result < min || result > max) throw Error(`Stroke option must be between ${min} and ${max}`);
return result;
}
/** Adaptive cubic subdivision also handles loops whose endpoints coincide. */
export function sampleStrokeCurve(points: [StrokePoint, StrokePoint, StrokePoint, StrokePoint], tolerance: number, push: (p: StrokePoint) => void): void {
const middle = (a: StrokePoint, b: StrokePoint): StrokePoint => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
const pending = [{ points, depth: 0 }];
while (pending.length) {
const { points: [a, b, c, d], depth } = pending.pop();
if (Math.max(segmentDistance(b, a, d), segmentDistance(c, a, d)) <= tolerance ** 2) push(d);
else {
if (depth >= 20) throw Error("Stroke curve subdivision limit exceeded");
const ab = middle(a, b), bc = middle(b, c), cd = middle(c, d), left = middle(ab, bc), right = middle(bc, cd), center = middle(left, right);
pending.push({ points: [center, right, cd, d], depth: depth + 1 }, { points: [a, ab, left, center], depth: depth + 1 });
}
}
}
/** World-space ideal centerline; rotation pivots come from the installed fork's actual bounds. */
export function strokeCenterline(element: StrokeElement, runtime: NonNullable<Packages["excalidrawLib"]>, tolerance: number, maxPoints: number): StrokePoint[] {
if (element.type !== "line" && element.type !== "freedraw") throw Error("Only line/free-draw centerlines are supported");
if (element.points.length < 2 || element.points.length > 100000 || element.points.some(p => p.length !== 2 || !p.every(Number.isFinite))) throw Error("Stroke requires 2–100000 finite points");
if (![element.x, element.y, element.angle].every(Number.isFinite)) throw Error("Invalid stroke geometry");
const unrotated = { ...element, angle: 0 } as ExcalidrawElement;
const [x1, y1, x2, y2] = runtime.getCommonBounds([unrotated]);
const cx = (x1 + x2) / 2, cy = (y1 + y2) / 2;
if (![cx, cy].every(Number.isFinite)) throw Error("Invalid stroke bounds");
const points: StrokePoint[] = [];
const push = (p: StrokePoint) => {
const x = p[0] + element.x - cx, y = p[1] + element.y - cy;
const next: StrokePoint = [cx + x * Math.cos(element.angle) - y * Math.sin(element.angle), cy + x * Math.sin(element.angle) + y * Math.cos(element.angle)];
const last = points.at(-1);
if (!last || last[0] !== next[0] || last[1] !== next[1]) points.push(next);
if (points.length > maxPoints) throw Error("Stroke point budget exceeded");
};
if (element.type === "line" && element.roundness) {
// Matches generateLinearCollisionShape: remove rough jitter, retain the exact spline model.
const ops = new RoughGenerator().curve(element.points.map((p): StrokePoint => [p[0], p[1]]), {
seed: element.seed, roughness: 0, preserveVertices: true, disableMultiStroke: true, disableMultiStrokeFill: true,
}).sets[0].ops.slice(0, element.points.length);
let previous: StrokePoint;
for (const op of ops) {
if (op.op === "move") { previous = [op.data[0], op.data[1]]; push(previous); }
else if (op.op === "bcurveTo" && previous) {
const end: StrokePoint = [op.data[4], op.data[5]];
sampleStrokeCurve([previous, [op.data[0], op.data[1]], [op.data[2], op.data[3]], end], tolerance, push); previous = end;
} else throw Error("Unsupported stroke curve operation");
}
} else element.points.forEach(p => push([p[0], p[1]]));
if (element.type === "line" && "polygon" in element && element.polygon === true && points.length > 1 && Math.hypot(points[0][0] - points.at(-1)[0], points[0][1] - points.at(-1)[1]) > 1e-9) {
points.push([...points[0]]);
if (points.length > maxPoints) throw Error("Stroke point budget exceeded");
}
return points;
}
/** Ramer–Douglas–Peucker preserves endpoints/corners and bounds centerline error. */
export function simplifyStroke(points: StrokePoint[], tolerance: number): StrokePoint[] {
if (points.length < 3) return points.map(p => [...p]);
const keep = new Set([0, points.length - 1]), pending = [[0, points.length - 1]]; let work = 0;
while (pending.length) {
const [start, end] = pending.pop(); let furthest = -1, distance = tolerance ** 2;
for (let i = start + 1; i < end; i++) {
if (++work > 8000000) throw Error("Stroke simplification work budget exceeded");
const next = segmentDistance(points[i], points[start], points[end]);
if (next > distance) { distance = next; furthest = i; }
}
if (furthest !== -1) { keep.add(furthest); pending.push([start, furthest], [furthest, end]); }
}
return [...keep].sort((a, b) => a - b).map(i => [...points[i]]);
}
/** Normalize around the first world-space point, retaining negative local coordinates. */
export function strokeGeometry(points: StrokePoint[]) {
if (points.length < 2) throw Error("Stroke has no nonzero centerline");
const [x, y] = points[0];
const bounds = points.reduce((b, p) => [Math.min(b[0], p[0]), Math.min(b[1], p[1]), Math.max(b[2], p[0]), Math.max(b[3], p[1])], [x, y, x, y]);
return { x, y, angle: 0 as ExcalidrawElement["angle"],
width: bounds[2] - bounds[0], height: bounds[3] - bounds[1],
// Coordinates were validated/sampled above; branding is added only at the canonical element boundary.
points: points.map(p => [p[0] - x, p[1] - y]) as unknown as ExcalidrawLineElement["points"] };
}
@@ -38,7 +38,7 @@ export class DrawingImagePreviewController {
return source?.file && !source.isMarkdownSection && this.view.plugin.isExcalidrawFile(source.file) ? source : null;
}
/** Open one selected-image popover, rechecking the view after reading frame names. */
/** Open one selected-image floating modal, rechecking the view after reading frame names. */
async open(elementId: string): Promise<void> {
if (this.busy) return;
this.reset();
@@ -56,13 +56,16 @@ export class DrawingImagePreviewController {
try {
const elements = await this.dependencies.readScene(view.plugin.app.vault, source.file);
if (!ownsImage()) return;
this.popover = new DrawingImagePreviewPopover(view, source, getSceneFrames(elements), this.dependencies.getExportPadding(view.plugin, source.file),
const popover = new DrawingImagePreviewPopover(view, source, getSceneFrames(elements), this.dependencies.getExportPadding(view.plugin, source.file),
getDrawingPaddingMax(elements, originalLink, getCommonBoundingBox),
ownsImage,
link => this.load(source, link),
changes => this.apply(elementId, source, changes, ownsImage),
() => { this.popover = null; });
this.popover.load();
() => {
if (this.popover !== popover) return;
this.popover = null; this.reset();
});
this.popover = popover; popover.open();
} catch (error: unknown) { if (current()) { errorlog({ where: "DrawingImagePreviewController.open", error }); new Notice(t("ERROR_TRY_AGAIN")); } }
}
@@ -136,7 +139,7 @@ export class DrawingImagePreviewController {
/** Retire pending renders, prompts and controls on file change, migration or unload. */
reset(): void {
this.generation++; this.popover?.unload(); this.popover = null;
this.generation++; const popover = this.popover; this.popover = null; popover?.close();
this.prompt?.close(); this.prompt = null;
for (const loader of this.loaders) loader.terminate = true;
this.loaders.clear();
+1 -9
View File
@@ -2664,18 +2664,10 @@ button.excalidraw-font-picker {
color: var(--text-muted);
font-size: var(--font-ui-smaller);
}
.excalidraw-drawing-preview-popover {
position: fixed;
z-index: var(--layer-popover);
.modal.excalidraw-drawing-preview-popover {
width: 340px;
max-width: calc(100vw - 16px);
max-height: calc(100vh - 16px);
overflow: auto;
padding: 12px;
border: 1px solid var(--background-modifier-border);
border-radius: var(--radius-m);
background: var(--background-primary);
box-shadow: var(--shadow-s);
}
.excalidraw-drawing-preview-image {
display: flex;
+58 -5
View File
@@ -15,6 +15,10 @@
{
"path": "src/core/managers/PluginSettingsManager.ts",
"symbol": "export class PluginSettingsManager"
},
{
"path": "src/shared/Dialogs/FloatingModal.ts",
"symbol": "export class FloatingModal"
}
],
"tests": [
@@ -81,6 +85,13 @@
"cases": [
"an enabled Extras plugin with an absent or incomplete API cancels service access cleanly"
]
},
{
"layer": "source",
"path": "scripts/testing/floatingModal.source.test.mjs",
"cases": [
"node:scripts/testing/floatingModal.source.test.mjs::closing a floating modal before deferred setup cancels its listeners and positioning"
]
}
],
"fixtures": [],
@@ -612,7 +623,7 @@
}
],
"fixtures": [
"Links/Árvíztűrő 测试.md"
"Links/\u00c1rv\u00edzt\u0171r\u0151 \u6d4b\u8bd5.md"
],
"platforms": [
"Windows desktop",
@@ -878,7 +889,16 @@
"node:scripts/testing/markdownEmbeds.test.mjs::PDF postprocessing claims drawing images before native embed discovery",
"node:scripts/testing/markdownEmbeds.test.mjs::synchronous embed ownership preserves native text and hybrid Markdown",
"node:scripts/testing/markdownEmbeds.test.mjs::plugin unload releases Reading controls and context cleanup removes owners from its registry",
"node:scripts/testing/markdownEmbeds.test.mjs::Reading export finishing after plugin unload is discarded without mounting controls"
"node:scripts/testing/markdownEmbeds.test.mjs::Reading export finishing after plugin unload is discarded without mounting controls",
"node:scripts/testing/markdownEmbeds.test.mjs::#3040 Live Preview uses the rendered drawing identity for a host-relative embed",
"node:scripts/testing/markdownEmbeds.test.mjs::#3039 a claimed Reading section renders while detached and survives later attachment",
"node:scripts/testing/markdownEmbeds.test.mjs::Reading callbacks deduplicate deferred renders and retire controls when the image is replaced",
"node:scripts/testing/markdownEmbeds.test.mjs::Reading context retirement cancels queued and in-flight detached images",
"node:scripts/testing/markdownEmbeds.test.mjs::PNG inline images are created in their owning document",
"node:scripts/testing/markdownEmbeds.test.mjs::PNG preview images are created in their owning document",
"node:scripts/testing/markdownEmbeds.test.mjs::PNG fullscreen routing opens the displayed raster without starting the high-resolution exporter",
"node:scripts/testing/markdownEmbeds.test.mjs::PNG detail upgrade forces a fresh raster and abort immediately terminates its loader",
"node:scripts/testing/markdownEmbeds.test.mjs::adopted PNG images retain fast fullscreen detail and disposal when their owning-window instanceof check fails"
]
},
{
@@ -1783,7 +1803,9 @@
"cases": [
"node:scripts/testing/svgImport.test.mjs::unsupported SVG colors use the SVG current color without aborting other geometry",
"node:scripts/testing/svgImport.test.mjs::unsupported current colors fall back to black while explicit none and zero alpha stay transparent",
"node:scripts/testing/svgImport.test.mjs::unsupported paint servers honor an explicit SVG fallback without fetching resources"
"node:scripts/testing/svgImport.test.mjs::unsupported paint servers honor an explicit SVG fallback without fetching resources",
"node:scripts/testing/svgImport.test.mjs::attached Mermaid mindmap retains local variable colors, alpha and labels",
"node:scripts/testing/svgImport.test.mjs::cyclic and missing SVG variables use their call-site fallback or inherited presentation"
]
},
{
@@ -2075,7 +2097,14 @@
"path": "scripts/testing/cli.test.mjs",
"cases": [
"node:scripts/testing/cli.test.mjs::registration validates minimum API, optional method and desktop without bumping the baseline",
"node:scripts/testing/cli.test.mjs::icon discovery is read-only, bounded and snapshot-paginated"
"node:scripts/testing/cli.test.mjs::icon discovery is read-only, bounded and snapshot-paginated",
"node:scripts/testing/cli.test.mjs::polygon skeletons and updates support dense bounded line contours without accepting foreign fields",
"node:scripts/testing/cli.test.mjs::selection packets capture exact targets and bound labels independently of later selection",
"node:scripts/testing/cli.test.mjs::drawing image insertion keeps links and anchor options while refusing ordinary Markdown and source races",
"node:scripts/testing/cli.test.mjs::status reports optional services without activating Extras or starting Builder",
"node:scripts/testing/cli.test.mjs::CLI Mermaid dependency refusal preserves prior script uncertainty and clears invocation context",
"node:scripts/testing/cli.test.mjs::CLI script JSON return failures remain recoverable without repeating already executed work",
"node:scripts/testing/cli.test.mjs::addMermaid rejects unavailable CLI dependencies before the interactive converter while manual calls retain it"
]
},
{
@@ -2156,6 +2185,29 @@
"all provider text pipelines normalize responses without OpenAI reasoning fields leaking",
"current image providers generate and edit through their actual payload and response adapters"
]
},
{
"layer": "source",
"path": "scripts/testing/strokeConversion.test.mjs",
"cases": [
"node:scripts/testing/strokeConversion.test.mjs::line to free-draw retains world placement, identity and metadata for rotated strokes",
"node:scripts/testing/strokeConversion.test.mjs::rounded line conversion samples the actual spline within tolerance instead of retagging control points",
"node:scripts/testing/strokeConversion.test.mjs::free-draw to line simplifies centerlines and explicitly removes custom pen and pressure semantics",
"node:scripts/testing/strokeConversion.test.mjs::custom free-draw tips/pressure configuration is copied without modifying caller settings",
"node:scripts/testing/strokeConversion.test.mjs::conversion preserves closed fills and rejects unsupported relationships or budgets atomically",
"node:scripts/testing/strokeConversion.test.mjs::concatenation chooses endpoint order, retains sharp corners and publishes no intermediate changes",
"node:scripts/testing/strokeConversion.test.mjs::concatenation refuses disconnected, conflicting and closed inputs without deleting any source",
"node:scripts/testing/strokeConversion.test.mjs::concatenation samples spline sections and normalizes rotation before endpoint matching"
]
},
{
"layer": "source",
"path": "scripts/testing/host/nativeCLITransport.test.mjs",
"cases": [
"node:scripts/testing/host/nativeCLITransport.test.mjs::native stdout timeout recovers only the exact settled receipt without replaying a write",
"node:scripts/testing/host/nativeCLITransport.test.mjs::pending, unknown and mismatched native receipts retain the original transport failure",
"node:scripts/testing/host/nativeCLITransport.test.mjs::native operation failures and unrelated transport errors are never converted into success"
]
}
],
"fixtures": [],
@@ -2201,7 +2253,8 @@
"layer": "native",
"path": "scripts/testing/host/extrasServices.mjs",
"cases": [
"native:extras-mathjax-gateway"
"native:extras-mathjax-gateway",
"native:extras-mermaid-gateway"
]
},
{
+291 -254
View File
File diff suppressed because it is too large. Load diff