Merge remote-tracking branch 'origin/master' into 2026-10-13-drawing-load-diagnostics

This commit is contained in:
zsviczian committed 2026-10-13 18:28:10 +02:00
commit 80cb935983
17 files changed
+15120 -15358

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
# Issue labels and triage
The central issue tracker for Obsidian Excalidraw and its related projects is [obsidian-excalidraw-plugin/issues](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues). Direct users here by default, including reports concerning the [Excalidraw fork](https://github.com/zsviczian/excalidraw), [Excalidraw Extras](https://github.com/zsviczian/obsidian-excalidraw-extras), and [EA Scripts](https://github.com/zsviczian/ea-scripts). Separate repositories may occasionally have their own issues, but this tracker is the main triage hub.
## Existing labels are authoritative
**Use only labels already present in the repository's [GitHub label list](https://github.com/zsviczian/obsidian-excalidraw-plugin/labels).** The live labels, their descriptions, and their configured colors are the source of truth, not a proposed label taxonomy in this document.
- **Do not create, rename, recolor, or delete labels during issue triage.** Repository label administration is a separate, explicitly authorized activity.
- **Do not use naming prefixes** such as `type:`, `area:`, or `status:`. The repository uses label **colors** to distinguish type, affected area, and status; the label names themselves are short and unprefixed.
- If the appropriate existing label is missing, leave that dimension unlabeled. Do not invent a substitute, apply a misleading label, or create a new one.
## Label dimensions
This table retains the label meanings and **suggested color convention**. During issue triage, apply only labels that **already exist** in GitHub with these exact unprefixed names. The table is not permission to create or recolor labels; if a listed label is unavailable, leave that dimension blank.
| Dimension | Label | Meaning | Suggested color |
| --- | --- | --- | --- |
| Type | `regression` | Previously working behavior broke | `#1D4ED8` |
| Type | `bug` | Incorrect existing behavior | `#2563EB` |
| Type | `enhancement` | Improve existing behavior | `#60A5FA` |
| Type | `feature` | New capability | `#93C5FD` |
| Type | `documentation` | Documentation change | `#DBEAFE` |
| Area | `plugin` | Main Obsidian plugin | `#6D28D9` |
| Area | `fork` | Customized Excalidraw component | `#7C3AED` |
| Area | `extras` | Excalidraw Extras | `#A78BFA` |
| Area | `script` | Excalidraw Automate / EA Scripts | `#DDD6FE` |
| Status | `confirmed` | Behavior verified or sufficiently established | `#15803D` |
| Status | `blocked` | Waiting on a dependency or decision | `#4D7C0F` |
| Status | `incomplete` | Report lacks required details, such as Obsidian debug information | `#A3A3A3` |
| Status | `needs-info` | Specific clarification requested from reporter | `#86EFAC` |
| Status | `cannot-reproduce` | Reproduction attempted without success | `#D4D4D4` |
| Criticality | `critical` | Confirmed bug causing data loss (potentially affecting many users), a serious information-security breach, or a violation of law (e.g. data privacy) | `#D1242F` |
Prefer one primary type and one primary area when an accurate existing label is available. Status labels describe evidence or workflow, not severity; they need not be assigned merely to fill a dimension. `confirmed` and `incomplete` may coexist when a verified behavior has an incomplete report. Use `critical` only after investigation establishes the impact through testing, code verification, or other substantiated evidence. A reporter's claim alone is not sufficient.
A dimension may remain blank. Avoid adding labels merely to fill a table. Keep useful special-purpose/historical labels such as `one day maybe`, `Solved with Excalidraw Script`, or `transfer to excalidraw.com` where relevant and already present. These are not automatically replacements for type, area, or status.
For an incomplete report, use the existing incomplete-report label if appropriate; if a specific answer is needed, use an existing question/needs-information label where available. Reproduction attempts and maintainer confirmations must be distinguished from a reporter's claim that a bug exists. Do not mark a suspected root cause as confirmed simply because the issue has a detailed explanation.
## Applying labels safely
1. Read the current [label list](https://github.com/zsviczian/obsidian-excalidraw-plugin/labels) and the issue's existing labels before editing. Use exact existing names and the repository's assigned colors; **do not attempt to synthesize label names from a dimension**.
2. Read the issue body and relevant discussion. Consider related fixes or PRs when they materially affect status. Handle the requested date range in **newest-to-oldest** order and stop at the specified cutoff.
3. Add only applicable, existing labels. Prefer additive label actions to replacing the entire label set. Preserve useful historical or special-purpose labels unless explicitly authorized to migrate them.
4. Read the issue back and verify the intended labels were applied. Do not silently alter the title, body, issue state, or other metadata.
5. Keep replies brief, and identify agent-authored comments as **Zsolt's Codex Agent**. Label-only triage normally does not need a comment.
**Examples using actual label names, only when those labels exist:**
- An ordinary verified bug: `bug` and an applicable existing status label; add an area label only if there is a specific matching one.
- An EA Scripts enhancement: `enhancement` and `ExcalidrawAutomate` or another appropriate existing script label, if available.
- An upstream-only issue: the applicable existing type and `transfer to excalidraw.com`, if appropriate.
Do not assign priorities with generic high/medium/low labels unless the maintainer has separately approved such a taxonomy. Issue priority can be assessed in discussion without inventing labels.
+4
View File
@@ -140,6 +140,10 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
## Issue Investigation And Resolution Templates
When triaging or updating issues across the plugin, Excalidraw fork, Extras, and EA Scripts, use the central [plugin issue tracker and label guidelines](.github/ISSUE_LABELS.md); this plugin repository is the default issue hub for all four projects.
- For source-based issue investigations, GitHub issue comments, and a prioritized shortlist, use [issue assessment](docs/agent-workflows/issue-assessment.md).
- Only after maintainer approval of specific issues, use [issue implementation handoff and resolution](docs/agent-workflows/issue-resolution.md) to prepare a dedicated branch and plan-only draft PR for the local implementation agent.
- The issue owns the technical assessment; the draft PR owns the implementation plan; the branch owns the code. Keep draft PRs open through implementation, link cross-repository dependencies, and do not merge without authorization.
+1
View File
@@ -41,6 +41,7 @@ dependency graph rather than suppressing the warning. Check with
- **Build the project:** Run `npm run build`
*(Note: Our Rollup build is non-trivial as it merges CSS, handles MathjaxToSVG dependencies, and embeds runtime payloads. Run this command frequently to validate your changes).*
- **Build readable development payloads:** Run `npm run dev`
- **Check production packaging:** Run `npm run test:bundle` after `npm run build` to verify the private React bootstrap, bundled font bytes, compressed locales, and release size target.
- **Build the public library API:** Run `npm run lib` when changing exports or ExcalidrawAutomate APIs
- **Run ESLint:** Run `npm run code`
- **Fix ESLint Warnings:** Run `node ./scripts/fix-eslint-warnings.mjs`
+35
View File
@@ -27,6 +27,9 @@ validated, and what remains uncertain.
| Phase | Status | Current outcome |
| --- | --- | --- |
| Assessment and baseline design | Complete | Initial architecture, risks, sequencing, and validation matrix documented |
| Attach native clipboard branches through the existing Mindmap Paste action (#2996) | Implemented; macOS main-window/floating/cross-drawing/popout paste and history validated | Script-only graph validation, native clipboard insertion, reference remapping and attachment preserve copied elements. Source-to-pasted markers have EA-owned cleanup across native Undo and reopened script sessions; input Undo stops at the pasted roots rather than assuming a history count. Windows and physical mobile remain manual gates |
| Release keyboard scopes for retired Mindmap inputs | Complete; native Markdown Enter validated | Inline suggesters now release detached scopes and invalidate pending reopen work. Mindmap Builder closes suggesters before replacing inputs, owns hotkey recording and root registrations per instance, and checks live focus before shadowing shortcuts. All 29 script and five suggester tests pass; native docking/close and Markdown Enter checks pass |
| Move Mindmap Builder into the EA Scripts authoring workspace | Complete; macOS main-window and direct-popout workflows validated | Extracted the script into 38 JavaScript subsystems including two modal factories, typed orchestration, and script-local catalogs. Per-invocation getters/setters preserve live closure state. The standard EA Scripts build supplies the existing publication paths without executable compression. All 23 focused tests pass; the action log records platform gaps and the detached-sidepanel callback fix |
| Retire legacy AI settings and fallbacks | Complete | Removed the retired migration, schema/default fields, GPT reset, and AI runtime fallbacks without filtering unknown persisted keys; manual testing found no issues |
| Extract settings implementation service | Implemented; awaiting manual validation | `PluginSettingsManager` now owns persistence, default assembly, remaining migrations, and API-key obfuscation; plugin methods and startup readiness remain intact, while temporary autosave enablement is now explicit plugin-instance state rather than persisted settings state |
| Migrate the settings tab to declarative settings with legacy fallback | Complete | Checkpoints 4A-4E migrated the full settings surface and passed focused manual validation. Checkpoints 5/6 finalized and activated the complete tree behind the persisted, restart-applied `useDeclarativeSettings` preference. The final checkpoint removed checkpoint-era names, dead adapter/type branches, unused declarations, and tab-lifetime references to controls owned by one rendered tree. Markdown export now rebuilds declarations without replacing the active control bindings. The supported legacy preference and empty-array fallback remain intentional. The final beta.5 production build is 4,798,339 bytes, 73,417 bytes above `master` and 2,450 bytes below the completed checkpoint-6 build; the Obsidian dependency/minimum remains `1.8.7` |
@@ -44,6 +47,7 @@ validated, and what remains uncertain.
| Retire obsolete Draw.io integration | Implemented; awaiting manual validation | Removed special Diagram-plugin routing and retired the Create DrawIO file script from the maintained library and generated reference catalogs; user-installed vault scripts remain untouched |
| Extract Excalidraw extension rendering | Implemented; awaiting manual validation | `ViewExcalidrawExtensionRenderer` now owns text-to-diagram, diagram-to-code, welcome screen, custom main menu, and embeddable rendering while the view retains its existing render delegates and package-managed React runtime |
| Audit production bundle size | Complete | Ranked packaging, dependency, dead-data, and static-payload reductions; translation extraction remains a last resort |
| Shorten production module bindings | Implemented; Windows authoring/export/script checks passed | Enabled Terser's module-level identifier mangling while retaining `React` for bootstrap insertion. The production bundle falls from 5,061,540 to 4,948,931 bytes, saving 112,609 bytes (2.22%) and leaving 293,949 bytes below the 5 MiB target. Compressed runtime/bootstrap bytes, external URL/data-URL values, and external dependencies are unchanged; property mangling and top-level dead-code elimination remain disabled. Packaging tests verify private React/JSX, exact published font bytes, locale inflation, and the size target. Popout, cold application startup, physical mobile/offline smoke, and hosted CodeScanner review remain pending |
| Use inflate-only Pako runtime | Complete | Replaced the full Pako distribution with its API-compatible inflate-only build; all existing Excalidraw and locale payloads retain their format and decompression path |
| Replace bundled YAML runtime | Implemented; awaiting manual validation | `mergeMarkdownFiles()` now uses Obsidian's public YAML APIs, and `yaml` is no longer a direct production dependency |
| Compress the shared React runtime payload | Implemented; awaiting focused runtime validation | Restored the official-entrypoint React/ReactDOM/JSX nested build after Obsidian CodeScanner exposed three dormant ReactDOM `createElement("script")` branches in the normally bundled production output. Production deflates the runtime at build time, then the bundle bootstrap inflates and indirectly evaluates it once before module-level React consumers run, releases the source string, and supplies the resulting private runtime to the one shared Excalidraw package. Popouts still lease that package rather than evaluating React per window |
@@ -219,6 +223,7 @@ final upstream work is merged into the fork and installed in the plugin.
| Date | Action | Outcome | Validation |
| --- | --- | --- | --- |
| 2026-10-13 | Reduced the production bundle through module-level identifier mangling | Measured the installed-package baseline on plugin revision `4acaf9e375e1dfb731faec9c2dd3439bd52cc4cb` with Node 22.22.3 and Excalidraw 0.18.143. The 2,818,384-byte compressed Excalidraw payload dominates the 5,061,540-byte baseline; plugin-code identifier mangling gives a small, isolated reduction without changing that payload. Only production Rollup/Terser configuration changes. The fork, dependencies/lockfile, manifests, CSS, assets, startup order, and runtime source are unchanged. Added `npm run test:bundle`. Candidate: 4,948,931 bytes, 112,609 bytes saved, 293,949 bytes headroom; SHA-256 `ff997ce2145c17e39b8311fa9ef588ed3543cfa3bb698a0a69e697d03b0c59c0`. Alternative runtime re-minification measured about 9.5 KiB of additional savings but was deferred because it transforms already compressed editor code and the current minifier deliberately disables `reduce_vars` for #2170. Increasing zlib memory level made the payload larger. No URLs were encoded, assembled, suppressed, or newly compressed for this checkpoint | Production builds and bundle syntax pass with the same 16 Rollup circular-dependency reports. All four packaging tests pass: private matching React/JSX without window globals or external runtime requires; every published embedded font's bytes; all four maintained locales; release size. Baseline/candidate bootstrap bytes, literal external URL/data-URL values, and external require values match. Windows Obsidian 1.14.4/installer 1.14.0 smoke and native CLI authoring pass in the guarded `excalidraw-test` vault: load, scene editing, save/read/reopen, SVG/PNG live and disk exports, image metadata, trusted scripts, zero captured JavaScript errors, exact deployed hashes, and fixture cleanup. Reports: `tmp/bundle-runtime/report.json` and `tmp/bundle-native-cli/report.json` (local, ignored). `npm run code` retains the same 120 pre-existing errors. Highest-probability regression: missed bootstrap insertion after future minifier changes, covered by the artifact test. Remaining manual gates: cold startup/reload, new/restored popout and main↔popout migration, offline drawing/font/export use on desktop and one physical mobile device; macOS/Linux are untested. Hosted CodeScanner acceptance requires the directory's branch review and is not claimed by the local lint run |
| 2026-09-16 | Fixed mixed-DPI popout selection alignment (#2940) | `InteractiveCanvas` now uses the `scale` supplied by its mounted `App`, which is derived from that editor's `ownerWindow.devicePixelRatio`, instead of reading the shared runtime's global `window.devicePixelRatio`. This preserves correct backing-store scaling for selection rectangles and other interactive-canvas overlays when a Windows popout uses a different display DPI. | Fork `yarn build:obsidian`, root `yarn test:typecheck`, and the plugin `npm run build` against the locally generated fork artifacts passed. The user confirmed the original #2940 reproduction is fixed. The focused selection suite remains blocked before test execution by the existing `createTestHook` test-harness error. |
| 2026-09-13 | Revised checkpoint 8 after Markdown-image force-save overtook a pending shape | Reacquiring Markdown-image ownership kept view B's shape pending in view A. **Render now** then deliberately bypassed the same-file save guard and wrote A's stale scene, deleting the shape. Save initiators now reconcile pending disk state through only their own gate record, preserve the actively edited Markdown-image source, resolve the current merged image element, and then persist. Render, close, handoff, post-flush, and Canvas-entry force-save paths share this boundary; accepted sync also advances the raw Markdown envelope | Owner-specific bypass was added to the deterministic gate check. All persistence/classifier/snapshot/routing scripts, focused and unused-symbol lint, production build, bundle syntax, and diff checks pass with established baselines. Revised bundle: 4,917,773 bytes, SHA-256 `55fb6a7a981e17b2445631f00d72438a441ed9c039a0c25d570141d893fbfbab`. First retest the exact Markdown-image A → shape B → reopen/render A sequence and verify both changes in both views and after reopen |
| 2026-09-13 | Revised checkpoint 8 after same-file edit → migration overwrite | Moving a large drawing immediately after exiting a back-of-note editor allowed migration to invalidate the pending synchronization and serialize the captured scene against stale view `data`, later deleting the newer paragraph from disk. The source unmount remains before the first await; affected Markdown migrations now wait only the established same-file grace and reread the Vault envelope before serialization. No claim is made about whether the exposed interleaving predates checkpoint 8 | Focused view lint retains 18 established findings with none in the migration change; unused-symbol lint, gate check, production build, bundle syntax, and diff checks pass with 33 established circular warnings. Revised bundle: 4,915,716 bytes, SHA-256 `a504f2bf5a822f5a361b944b101baaad5f89ba9589321a710cfcfd285be31667`. First retest the exact paragraph-edit, exit, immediate **Move to new window** sequence and require both durable text and no serious-error Notice |
@@ -2433,3 +2438,33 @@ Before continuing to 12b, a separate checkpoint-10 corrective increment resolves
| 2026-09-14 | Accepted checkpoint 12b own-write reload-guard extraction | The maintainer confirmed ordinary autosave/Ctrl+S, alternating multi-view editing, forced save, raw `.excalidraw` own-write suppression and external updates, back-of-note release synchronization, migration/close, and the remaining requested smoke tests all completed successfully | Checkpoint 12b is ready to commit. The branch-wide simplification and artifact audit follows as a separate review |
| 2026-09-14 | Committed checkpoint 12b own-write reload-guard extraction | Own-write suppression and its cleanup callback now have one tested view-owned state owner | Commit `b9481c32` (`refactor: own reload suppression state`) |
| 2026-09-14 | Completed the post-checkpoint file-persistence branch sanity review | Confirmed the new boundaries remain purpose-specific: save/revision/content identity, detached write ordering, automatic-output coalescing, same-file ownership, load generation, and raw compatibility suppression have distinct lifetimes and cannot be safely collapsed. Removed the uncalled `ViewSaveCoordinator.getLastSuccessfulPreparedSave()` and the test-only `ViewPersistenceQueue.flush()`, removed two extra end-of-file blank lines, corrected one obsolete checkpoint comment, and updated lifecycle documentation from superseded experimental descriptions to the accepted implementation. No temporary persistence instrumentation, tracked generated output, attachment, or diagnostic runtime log remains. Historical failed-5b rows and stashes remain as rejected evidence rather than executable guidance | All 12 focused persistence/lifecycle checks pass; unused-symbol validation and focused lint pass; production and library builds plus bundle syntax and cumulative `git diff --check` pass. Rollup retains the established 33 circular warnings. Final reproducible bundle: 4,936,617 bytes, SHA-256 `698e47581470b1e9a211c58bad05ed2000d56fd3097b4cb17be55856530fb73e`. `npm run madge` was attempted but its undeclared CLI is not installed in this checkout; this cleanup changes no imports, and the production graph result is unchanged |
### 2026-10-13 — Mindmap Builder authoring-workspace migration
Moved the 14,029-line source into the sibling EA Scripts workspace as 38 import-safe JavaScript subsystem modules, including separate palette/layout modal factories, with a typed launcher and script-local catalogs. Explicit invocation-scoped getters/setters retain live settings, control references, selection, transactions, and window ownership. The structural audit preserved all 243 extracted statements before a separate lifecycle correction; two failing regression tests then justified guarding the two hotkey functions against delayed callbacks after their owning sidepanel closes. The final 23 focused tests and focused lint pass. This is a module extraction, not a completed TypeScript conversion.
`npm run mindmap` now builds the authoring workspace and copies its standard Markdown/preview output into the existing published names. Removed the old source copy, kept the historical `.js` URL as a source pointer, and updated store/index source links, directory mtime, and release notes. Executable compression was removed because plugin 2.27.0+ already caches compilation: twenty live activations reused the same API/host with no additional script reads or compilations.
EA Scripts build, the plugin production build, script-store checks, and byte equality of the copied artifacts passed. The final script SHA-256 is `fc277266442fd9a451859cd09f974c6248e88536d31d0c0a7511bad59624fabe`. In the existing macOS `excalidraw-test` vault on Obsidian 1.14.4 / installed Excalidraw 2.29.0, cold launch, node creation, vertical/radial layout, folding, Markdown import/export, drawing switching, direct-popout editing/save, undo/redo, saved-drawing reopen, and sidepanel close/reopen passed with an empty error buffer and full fixture/hook cleanup. One focus-interrupted repeat required stopping only its owned CLI subprocess; cleanup and the final repeat passed. Full workspace diagnostics reproduce the same 365 type errors and nine Canvas Chat/slideshow test failures with the new script excluded; broad plugin lint reports 120 unrelated errors, while touched release-notes lint passes.
Risk-based follow-up: check undocked input dragging/docking and keyboard ownership during moved-tab migration in main-window/popout workflows. Persisted sidepanel restoration after application restart, Windows desktop, and physical mobile touch remain separate gates. The retained runtime's DOM styling and implicit globals require independent review. Detailed module ownership, compression rationale, and validation are in the sibling script's `CONTRIBUTING.md` and `Validation.md`.
### 2026-10-13 — Mindmap Builder Enter interception and keyboard ownership
Reproduced a pre-existing cleanup defect in the native test vault: detaching an inline link dropdown before `close()` left its keyboard scope active. Its empty Enter handler still returned false, explaining how ordinary Markdown typing could work while Enter was consumed. The original pre-module script also replaced inputs during docking without closing its previous suggester, and did not close it during sidepanel teardown. This establishes a matching failure mechanism, not proof of which scope was stuck in the maintainer's particular session.
`InlineLinkSuggester.close()` now pops its exact scope regardless of DOM attachment, invalidates awaited lookup work, and prevents old close timers from changing a newer session's key blocking. Script lifecycle paths close suggesters before DOM removal/replacement. The ontology input is invocation-scoped; `HotkeyRecorder` releases the exact recording scope on replacement, cancellation, exceptions, close, and EA destruction. Root overrides and DOM keyboard listeners have instance-owned cleanup, and a wildcard root handler checks live focus/dispatch eligibility before shadowing Obsidian shortcuts. It yields to original handlers outside Mindmap's context; using undefined from an explicit-key registration would still stop Obsidian's scope scan.
Twenty-nine script tests and five plugin suggester tests pass, along with focused lint, both builds, and script-store checks. The exact declared component package was restored with npm install (0.18.140 installed versus 0.18.143 declared), without dependency or lockfile edits. The guarded plugin-only smoke passed. Native macOS testing verified the detached-scope fix, successive recordings followed by close, open suggestions followed by docking, and real CDP Enter newlines in a disposable Markdown editor both before and after Mindmap closure. Existing main-window/direct-popout, drawing/history/save/reopen checks also passed with no captured JavaScript errors and full fixture cleanup. One initial drawing-creation CLI timeout cleaned up; the warmed retry passed. Final script SHA-256: `4fdd700d5480e0012c06e680cb633ef39f1e2bb863b8bc46af20cf6f9c00363e`.
Highest-probability remaining manual risk: focus and keymap ownership when recording or using link suggestions in an undocked/migrated popout. Validate Windows and physical mobile separately. Restart an already affected Obsidian session before retesting both rebuilt artifacts, because an old orphaned scope may have lost its cleanup handle. The sibling script's `HotkeyCleanup.md` records the investigation. Full EA check still encounters the same 365 unrelated type errors; the new script has none.
### 2026-10-13 — Native Mindmap branch paste (#2996)
Implemented in EA Scripts and rebuilt the published Mindmap Builder Markdown. The existing Paste action recognizes native clipboard branches, imports them through Excalidraw's normal paste event, remaps boundary/fold references, and attaches copied roots to the captured destination. Whole maps become submaps; independent paste initializes a master root. Styles, file data, group associations, pins and local submap settings are retained; disabled layout stays disabled. Unfolding a destination does not unlock copied notes. No plugin/component runtime or API changes were made for this feature.
Native completion and gesture/timeout cancellation are operation-owned. Scene subscriptions owned by the script EA repair transport metadata restored by native Undo, including recovery when Builder reopens. Input Undo stops at removal of the newly pasted roots and Redo replays the actual traversal; it does not assume a native capture count. Concurrent history replay and view/API retirement are guarded.
Validation: all 46 focused Mindmap tests pass; focused TypeScript/release-note lint and script build/store checks pass. The full workspace check still stops at 365 pre-existing type errors, with none in Mindmap Builder. Native macOS Obsidian 1.14.4 / Excalidraw 2.29.0 passed same-drawing attachment, boundary/fold reference remapping, grouped linked notes, images, cross-drawing/floating paste, disabled layout, grouped input Undo/Redo preserving preceding elements, native history metadata cleanup, and fresh-popout attachment. The final error buffer was empty and exact fixtures/controllers/read overrides were cleaned up. Test-driver iterations required asynchronous sidepanel readiness, correct clipboard realms and boxed-node container selection; failed iterations are not validation results.
Final native report: `/private/tmp/mindmap-branch-live-report.json`. Tested/published script SHA-256: `95937adf36fe21259a143b635e2a10e164d06b9c93a97e6fdf66fa2e00ffb43f`. The current build is installed at `Excalidraw/Scripts/Downloaded/Mindmap Builder.md` in the authorized `excalidraw-test` vault. Highest remaining manual risk: folded destinations with complete folded branches, pins/nested submaps and repeated dock/window migration. Windows modifiers and physical mobile clipboard/focus/touch need separate coverage.
+6 -2
View File
@@ -1,3 +1,7 @@
/*
Because of misleading code scanner results that incorrectly pick up the mindmap MindMap Builder.js script as a potential security risk due to "hard coded" :) URLs - yes, in the comments explaining how to use the script - I have decided to move the script to a separate file. I will not add the link here, becuase it will be picked up by scanners: look for "MindMap Builder.js.md" in the repo. Sorry for the inconvenience, but I want to ensure that false positives do not cause unnecessary alarm, and do not undermine the trust in the plugin that I have built with care and dedication.
*/
Mindmap Builder's maintained source has moved to the EA Scripts authoring workspace:
https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/mindmap-builder
Install the executable Markdown script from ea-scripts/Mindmap Builder.md.
This historical source URL remains as a pointer for existing documentation links.
*/
File diff suppressed because it is too large. Load diff
+14763 -1183
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -641,7 +641,7 @@
},
{
"fname": "Mindmap Builder.md",
"mtime": 1785045917003
"mtime": 1791905383390
},
{
"fname": "Mindmap Builder.svg",
+1 -1
View File
@@ -515,7 +515,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/Mindmap%20Builder.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/Mindmap%20Builder.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.Sign up for the <a href="https://visual-thinking-workshop.com/mindmap" target="_blank">MindMap Builder Self-Paced Course</a>!<br><a href="https://www.youtube.com/watch?v=qY66yoobaX4" target="_blank"><img src ="https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/qY66yoobaX4' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=5G9QF-u9w0Q" target="_blank"><img src ="https://i.ytimg.com/vi/5G9QF-u9w0Q/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/5G9QF-u9w0Q' target='_blank'>Link to video on YouTube</a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png'></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/ea-scripts/tree/main/src/scripts/mindmap-builder'>Modular source on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.Sign up for the <a href="https://visual-thinking-workshop.com/mindmap" target="_blank">MindMap Builder Self-Paced Course</a>!<br><a href="https://www.youtube.com/watch?v=qY66yoobaX4" target="_blank"><img src ="https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/qY66yoobaX4' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=5G9QF-u9w0Q" target="_blank"><img src ="https://i.ytimg.com/vi/5G9QF-u9w0Q/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/5G9QF-u9w0Q' target='_blank'>Link to video on YouTube</a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png'></td></tr></table>
## Mindmap connector
```excalidraw-script-install
+1 -1
View File
@@ -683,7 +683,7 @@
"iconUrl": "https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg",
"author": "@zsviczian",
"authorUrl": "https://github.com/zsviczian",
"sourceUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.md",
"sourceUrl": "https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/mindmap-builder",
"descriptionHtml": "Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.Sign up for the <a href=\"https://visual-thinking-workshop.com/mindmap\" target=\"_blank\">MindMap Builder Self-Paced Course</a>!<br><a href=\"https://www.youtube.com/watch?v=qY66yoobaX4\" target=\"_blank\"><img src =\"https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg\" style=\"width:400px;\"></a><br><a href='https://youtu.be/qY66yoobaX4' target='_blank'>Link to video on YouTube</a><br><a href=\"https://www.youtube.com/watch?v=5G9QF-u9w0Q\" target=\"_blank\"><img src =\"https://i.ytimg.com/vi/5G9QF-u9w0Q/maxresdefault.jpg\" style=\"width:400px;\"></a><br><a href='https://youtu.be/5G9QF-u9w0Q' target='_blank'>Link to video on YouTube</a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png'>",
"categories": [
"Editors Picks",
+2
View File
@@ -10,8 +10,10 @@
"scripts": {
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs",
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
"test:bundle": "node --test scripts/testing/bundle.test.mjs",
"test:obsidian:runner": "node --test scripts/testing/host/runner.test.mjs scripts/testing/host/processTools.test.mjs",
"test:markdown-embeds": "node --test scripts/testing/markdownEmbeds.test.mjs",
"test:inline-link-suggester": "node --test scripts/testing/inlineLinkSuggester.test.mjs",
"verify:obsidian": "node scripts/testing/host/verify.mjs",
"verify:obsidian:plugin": "node scripts/testing/host/verify.mjs --plugin-only",
"lib": "cross-env NODE_ENV=lib rollup --config rollup.config.mjs",
+4
View File
@@ -336,6 +336,10 @@ const BUILD_CONFIG = {
...(isProd ? [
terser({
toplevel: false,
// Shorten Rollup's module-level bindings without enabling top-level
// dead-code elimination or changing public object properties. React's
// require binding must retain its name for the bootstrap insertion below.
mangle: { toplevel: true, reserved: ['React'] },
compress: { passes: 2 },
format: {
comments: false, // Remove all comments
+33 -136
View File
@@ -1,142 +1,39 @@
import path from "path";
import fs from "fs/promises";
import { minify } from "terser";
import LZString from "lz-string";
import { fileURLToPath } from "url";
/** Build Mindmap Builder in its authoring workspace and copy the published artifacts. */
import path from "node:path";
import fs from "node:fs/promises";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { packageManagerInvocation } from "./testing/host/processTools.mjs";
// Construct __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const workspace = path.resolve(process.argv[2] ?? path.join(root, "..", "ea-scripts"));
const slug = "mindmap-builder";
const CHUNK_SIZE = 256;
const NEEDLE = "const removeKeydownHandlers";
async function deploy() {
const major = Number(process.versions.node.split(".")[0]);
if (major < 22) throw new Error("Mindmap Builder requires Node.js 22 or newer.");
await fs.access(path.join(workspace, "src", "scripts", slug, "main.ts"));
const root = path.resolve(__dirname, "..");
const sourcePath = path.join(root, "ea-scripts", "Mindmap Builder.js.md");
const outputPath = path.join(root, "ea-scripts", "Mindmap Builder.md");
const invocation = packageManagerInvocation("npm", ["run", "build"]);
const result = spawnSync(invocation.file, invocation.args, {
cwd: workspace,
stdio: "inherit",
// Both repositories' scripts must use the same supported Node installation.
env: { ...process.env, PATH: `${path.dirname(process.execPath)}${path.delimiter}${process.env.PATH ?? ""}` },
});
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(`EA Scripts build failed (exit ${result.status}).`);
const HEADER = `/*
# Mind Map Builder
![](https://youtu.be/5G9QF-u9w0Q)
## Overview
**Mind Map Builder** transforms the Obsidian-Excalidraw canvas into a rapid brainstorming environment, allowing users to build complex, structured, and visually organized mind maps using primarily keyboard shortcuts.
The script balances **automation** (auto-layout, recursive grouping, and contrast-aware coloring) with **explicit flexibility** (node pinning and redirection logic), ensuring that the mind map stays organized even as it grows to hundreds of nodes. It leverages the Excalidraw Sidepanel API to provide a persistent control interface utilizing the Obsidian sidepanel, that can also be undocked into a floating modal.
> [!Tip]
> 🚀 Become a MindMap Builder Pro with the Official [MindMap Builder Course](https://www.visual-thinking-workshop.com/mindmap)!
> [!Info]
> Mindmap Builder is Minified and compressed to reduce size and improve performance. You can find the source here: [Mindmap Builder.js](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.js)
> API documentation: [MindMapBuilderAPI.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/ea-script-docs/MindMapBuilderAPI.md)
## Show Your Love!
💖 **If you love MindMap Builder** say thank you, and [Buy me a Coffee](https://ko-fi.com/zsolt) 🍵
## The Script
\`\`\`js*/
`;
const FOOTER = `
const VERSION = "v${new Date().toISOString().slice(2, 10).replace(/-/g, ".")}";
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.4")) {
new Notice("Please update the Excalidraw Plugin to version 2.23.4 or higher.");
return;
const outputDir = path.join(workspace, "build", slug);
// Read both before replacing either published artifact. Copy the template wrapper intact.
const markdown = await fs.readFile(path.join(outputDir, `${slug}.md`));
const preview = await fs.readFile(path.join(outputDir, `${slug}.svg`));
await fs.writeFile(path.join(root, "ea-scripts", "Mindmap Builder.md"), markdown);
await fs.writeFile(path.join(root, "ea-scripts", "Mindmap Builder.svg"), preview);
console.log(`Mindmap Builder published artifacts copied from ${workspace}`);
}
ea.skipSidepanelScriptRestore();
const existingTab = ea.checkForActiveSidepanelTabForScript();
if (existingTab) {
const hostEA = existingTab.getHostEA();
if (hostEA && hostEA !== ea) {
hostEA.activateMindmap = true;
hostEA.setView(ea.targetView);
existingTab.open(false);
return;
}
};
const mmbSource = \`
`;
const FOOTER_TAIL = `\`;
const script = ea.decompressFromBase64(mmbSource.replace(/[\\s\\r\\n]+/g, ""));
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
await new AsyncFunction("ea", "utils", "VERSION", script)(ea, utils, VERSION);
`;
function chunkString(input, size) {
const chunks = [];
for (let i = 0; i < input.length; i += size) {
chunks.push(input.slice(i, i + size));
}
return chunks;
}
function stripHeader(source) {
const idx = source.indexOf(NEEDLE);
if (idx === -1) {
throw new Error(`Marker "${NEEDLE}" not found in Mindmap Builder.js`);
}
return source.slice(idx);
}
function wrapAsyncIIFE(body) {
return `(async()=>{\n${body}\n})()`;
}
async function minifyCode(source) {
const result = await minify(source, {
compress: { passes: 3 },
mangle: true,
output: { ascii_only: true }
});
if (result.error) {
throw result.error;
}
return result.code;
}
function unwrapAsyncIIFE(minified) {
const match = minified.match(/^\(async\s*\(\)\s*=>\s*\{([\s\S]*)\}\)\(\);?$/);
if (!match) {
throw new Error("Unable to strip async IIFE wrapper from minified output:\n" + minified.substring(0, 100) + "...");
}
return match[1];
}
function compressBase64(text) {
return LZString.compressToBase64(text);
}
function formatCompressed(compressed) {
return chunkString(compressed, CHUNK_SIZE).join("\n\n");
}
async function generate() {
const raw = await fs.readFile(sourcePath, "utf8");
const body = stripHeader(raw).trim();
const wrapped = wrapAsyncIIFE(body);
const minified = await minifyCode(wrapped);
const unwrapped = unwrapAsyncIIFE(minified);
const compressed = compressBase64(unwrapped);
const formatted = formatCompressed(compressed);
const output = `${HEADER}${FOOTER}${formatted}${FOOTER_TAIL}`;
await fs.writeFile(outputPath, output, "utf8");
console.log(`Mindmap Builder.md generated at ${outputPath}`);
}
generate().catch((err) => {
console.error(err);
process.exitCode = 1;
});
deploy().catch((error) => {
console.error(error);
process.exitCode = 1;
});
+96
View File
@@ -0,0 +1,96 @@
/** Checks the production artifact's runtime bootstrap and offline asset contract. Build first. */
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import { createContext, runInContext } from "node:vm";
import { parseAst } from "rollup/parseAst";
const root = new URL("../../", import.meta.url);
const read = (path) => readFileSync(new URL(path, root), "utf8");
const code = read("dist/main.js");
const ast = parseAst(code);
function visit(node, callback) {
if (!node || typeof node !== "object") return;
if (typeof node.type === "string") callback(node);
for (const value of Object.values(node)) {
if (Array.isArray(value)) value.forEach((child) => visit(child, callback));
else if (value && typeof value === "object") visit(value, callback);
}
}
function declaration(name) {
const matches = ast.body.filter((node) => node.type === "VariableDeclaration" &&
node.declarations.some((item) => item.id.name === name));
assert.equal(matches.length, 1, `Expected one injected ${name} declaration`);
return matches[0];
}
// Execute only the shipped bootstrap in a browser-like realm. No Obsidian or
// network is available: synchronous inflation must supply the private runtime.
const context = createContext({ atob, TextDecoder, Uint8Array, console, document: {} });
runInContext("window = globalThis;", context);
runInContext(code.slice(declaration("INITIAL_TIMESTAMP").start,
declaration("deliberateCreateElement").end), context);
const runtimeSource = runInContext("unpackExcalidraw()", context);
function fontAssets(source) {
const assets = new Set();
visit(parseAst(source), (node) => {
if (node.type === "Literal" && typeof node.value === "string" &&
/^data:(?:font\/|application\/(?:font|x-font))[^,]*;base64,[A-Za-z0-9+/]+=*$/.test(node.value)) {
// Compare font bytes, excluding MIME prefixes used by dynamic font loaders.
// Hashes also keep a failed assertion from printing megabytes of Base64.
const bytes = Buffer.from(node.value.slice(node.value.indexOf(",") + 1), "base64");
assets.add(createHash("sha256").update(bytes).digest("hex"));
}
});
return [...assets].sort();
}
test("production bootstrap supplies matching private React and JSX runtimes", () => {
const reactVersion = JSON.parse(read("node_modules/react/package.json")).version;
const domVersion = JSON.parse(read("node_modules/react-dom/package.json")).version;
assert.equal(runInContext("React.version", context), reactVersion);
assert.equal(runInContext("ReactDOM.version", context), domVersion);
for (const expression of ["React.createElement", "ReactDOM.createRoot", "ReactDOM.flushSync",
"ReactJSXRuntime.jsx", "ReactJSXRuntime.jsxs", "ReactJSXDevRuntime.jsxDEV"]) {
assert.equal(runInContext(`typeof ${expression}`, context), "function", expression);
}
assert.equal(runInContext("window.React", context), undefined);
assert.equal(runInContext("window.ReactDOM", context), undefined);
const dependencies = new Set();
visit(ast, (node) => {
if (node.type === "CallExpression" && node.callee.type === "Identifier" &&
node.callee.name === "require") dependencies.add(node.arguments[0]?.value);
});
for (const dependency of ["react", "react-dom", "react-dom/client", "@zsviczian/excalidraw"]) {
assert.ok(!dependencies.has(dependency), `Runtime dependency must be bundled: ${dependency}`);
}
});
test("compressed Excalidraw retains every published offline font asset", () => {
const original = read("node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.production.min.js");
const expected = fontAssets(original);
assert.ok(expected.length > 0, "Published artifact must contain offline fonts");
assert.deepEqual(fontAssets(runtimeSource), expected);
assert.ok(!runtimeSource.includes("//# sourceMappingURL="));
assert.ok(!code.includes("//# sourceMappingURL="));
});
test("all maintained language payloads inflate and parse synchronously", () => {
const languages = runInContext("Object.keys(PLUGIN_LANGUAGES).sort()", context);
assert.deepEqual(Array.from(languages), ["es", "ru", "zh-cn", "zh-tw"]);
for (const language of languages) {
const source = runInContext(`unpackBase64Deflate(PLUGIN_LANGUAGES[${JSON.stringify(language)}])`, context);
assert.ok(source.startsWith("x="), `Invalid locale payload: ${language}`);
assert.doesNotThrow(() => parseAst(source), `Invalid locale syntax: ${language}`);
}
});
test("production main.js remains below the release size target", () => {
const bytes = Buffer.byteLength(code);
assert.ok(bytes < 5 * 1024 * 1024, `${fileURLToPath(new URL("dist/main.js", root))}: ${bytes} bytes`);
});
@@ -0,0 +1,99 @@
/** Exercise the real close method with connected/detached dropdowns and nested scopes. */
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import test from "node:test";
import vm from "node:vm";
import ts from "typescript";
function fixture({ connected, nested = false, deferTimers = false }) {
const source = readFileSync(resolve(import.meta.dirname, "../../src/shared/Suggesters/InlineLinkSuggester.ts"), "utf8");
const javascript = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText;
const exports = {};
const timers = [];
vm.runInNewContext(javascript, {
exports,
require: name => name === "./SuggestionModal" ? { SuggestionModal: class {
onInputChanged() { this.openedCount = (this.openedCount ?? 0) + 1; }
} } : {},
window: { setTimeout: callback => deferTimers ? timers.push(callback) : callback() },
});
const root = {}, scope = {}, modal = {};
const stack = nested ? [root, scope, modal] : [root, scope];
const released = [];
const instance = Object.create(exports.InlineLinkSuggester.prototype);
Object.assign(instance, {
app: { keymap: { popScope(candidate) {
released.push(candidate);
const index = stack.indexOf(candidate);
if (index !== -1) stack.splice(index, 1);
} } },
scope,
suggestEl: { isConnected: connected, detach() { this.isConnected = false; } },
suggester: { setSuggestions(values) { instance.suggestions = values; } },
shouldNotOpen: true,
block: true,
suggestionGeneration: 0,
});
return { instance, scope, root, modal, stack, released, timers };
}
test("closing a detached dropdown releases its keyboard scope", () => {
const h = fixture({ connected: false });
h.instance.close();
assert.deepEqual(h.stack, [h.root]);
assert.equal(h.released[0], h.scope);
assert.equal(h.instance.block, false);
});
test("closing an inactive detached scope preserves the modal above it", () => {
const h = fixture({ connected: false, nested: true });
h.instance.close();
assert.deepEqual(h.stack, [h.root, h.modal]);
});
test("connected and repeated closes restore the original scope", () => {
const h = fixture({ connected: true });
h.instance.close();
h.instance.close();
assert.deepEqual(h.stack, [h.root]);
assert.equal(h.instance.shouldNotOpen, false);
});
test("an awaited lookup cannot reopen suggestions after closing the input", async () => {
const h = fixture({ connected: true });
let finishLookup;
const lookup = new Promise(resolve => { finishLookup = resolve; });
Object.assign(h.instance, {
inputEl: { value: "[[Target#]]", selectionStart: 9, selectionEnd: 9 },
findActiveLink: () => ({ open: 0, close: 9 }),
parseLinkContext: () => ({ mode: "heading", file: {}, searchTerm: "", alias: null }),
loadHeadings: () => lookup,
modifyInput: value => value,
});
h.instance.onInputChanged();
h.instance.close();
finishLookup();
await lookup;
await Promise.resolve();
assert.equal(h.instance.openedCount ?? 0, 0);
assert.equal(h.instance.block, false);
assert.deepEqual(h.stack, [h.root]);
});
test("a previous close timer does not unblock a newly opened suggestion session", async () => {
const h = fixture({ connected: true, deferTimers: true });
Object.assign(h.instance, {
inputEl: { value: "[[Target#]]", selectionStart: 9, selectionEnd: 9 },
findActiveLink: () => ({ open: 0, close: 9 }),
parseLinkContext: () => ({ mode: "heading", file: {}, searchTerm: "", alias: null }),
loadHeadings: async () => {},
modifyInput: value => value,
});
h.instance.close();
h.instance.onInputChanged();
await Promise.resolve();
assert.equal(h.instance.block, true);
h.timers.forEach(callback => callback());
assert.equal(h.instance.block, true);
});
+6
View File
@@ -17,6 +17,12 @@ 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.1": `
## Excalidraw Automate
- Mindmap Builder is now distributed as a readable script, with its modular source maintained in the EA Scripts workspace. Closing its sidepanel no longer lets delayed hotkey callbacks affect a newly opened instance.
- Mindmap Builder's existing Paste action can attach a natively copied branch while preserving its links, images, and grouped notes. [#2996](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2996)
- Closing or docking a script input with an open link suggester no longer leaves Enter intercepted in Markdown editors. Mindmap Builder also releases hotkey recording and overrides when it closes.
`,
"2.29.0": `
${getYouTubeDiv("H64AW1l-ae4")}
+13 -4
View File
@@ -89,6 +89,7 @@ export class InlineLinkSuggester
private frameItems: FrameSuggestion[] = [];
private tagItems: TagSuggestion[] = [];
private linkItemsLoaded = false;
private suggestionGeneration = 0;
constructor(
app: App,
@@ -227,6 +228,7 @@ export class InlineLinkSuggester
}
onInputChanged(): void {
const generation = ++this.suggestionGeneration;
const inputStr = this.modifyInput(this.inputEl.value);
this.caretPos = this.inputEl.selectionStart ?? inputStr.length;
@@ -279,6 +281,9 @@ export class InlineLinkSuggester
this.frameItems = [];
}
if (generation !== this.suggestionGeneration) {
return;
}
this.tagItems = [];
this.block = true;
super.onInputChanged();
@@ -891,9 +896,11 @@ export class InlineLinkSuggester
// Keep listeners so the suggester can trigger multiple times in the same input session.
close(): void {
if (this.suggestEl.isConnected) {
this.app.keymap.popScope(this.scope);
}
// A pending heading/block/frame lookup must not reopen a retired input's scope.
const generation = ++this.suggestionGeneration;
// Docking/closing a host can detach the dropdown before its scope is released.
// popScope is idempotent and uses the scope's acquisition window, not DOM visibility.
this.app.keymap.popScope(this.scope);
this.suggester.setSuggestions([]);
if (this.popper?.deref()) {
this.popper.deref().destroy();
@@ -901,7 +908,9 @@ export class InlineLinkSuggester
this.suggestEl.detach();
this.shouldNotOpen = false;
window.setTimeout(() => {
this.block = false;
if (generation === this.suggestionGeneration) {
this.block = false;
}
});
}