diff --git a/.github/ISSUE_LABELS.md b/.github/ISSUE_LABELS.md new file mode 100644 index 00000000..246a6727 --- /dev/null +++ b/.github/ISSUE_LABELS.md @@ -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. diff --git a/AGENTS.md b/AGENTS.md index 20811cf7..ffc82427 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 951c51f7..e898c87f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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` diff --git a/RefactorPlan.md b/RefactorPlan.md index 01612042..0430a11c 100644 --- a/RefactorPlan.md +++ b/RefactorPlan.md @@ -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. diff --git a/ea-scripts/Mindmap Builder.js b/ea-scripts/Mindmap Builder.js index 630b524c..cac34aaa 100644 --- a/ea-scripts/Mindmap Builder.js +++ b/ea-scripts/Mindmap Builder.js @@ -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. -*/ \ No newline at end of file +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. +*/ diff --git a/ea-scripts/Mindmap Builder.js.md b/ea-scripts/Mindmap Builder.js.md deleted file mode 100644 index 22c586bc..00000000 --- a/ea-scripts/Mindmap Builder.js.md +++ /dev/null @@ -1,14030 +0,0 @@ -/** -# Mind Map Builder: Technical Specification & User Guide - -## 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. - -## Technical notes - -### Sidepanel & Docking -- **Persistent UI**: The script utilizes `ea.createSidepanelTab` to maintain state and controls alongside the drawing canvas. -- **Floating Mode**: The UI can be "undocked" (Shift+Enter) into a `FloatingModal` for a focus-mode experience or to move controls closer to the active drawing area on large screens. - -### Map-Specific Persistence (customData) -The script uses `ea.addAppendUpdateCustomData` to store state on elements: -- `growthMode`: Stored on the Root node (Radial, Left, or Right). -- `autoLayoutDisabled`: Stored on the Root node to pause layout engine for specific maps (toggle from UI). -- `arrowType`, `fontsizeScale`, `multicolor`, `boxChildren`, `roundedCorners`, `maxWrapWidth`, `isSolidArrow`, `centerText`: Stored on the Root node to persist display preferences per map. -- `isPinned`: Stored on individual nodes (boolean) to bypass the layout engine. -- `isBranch`: Stored on arrows (boolean) to distinguish Mind Map connectors from standard annotations. -- `mindmapOrder`: Stored on nodes (number) to maintain manual sort order of siblings. -- `mindmapNew`: Stored on nodes (boolean) to tag freshly added items so new siblings append after existing order; cleared after layout. -- `isFolded`: Stored on nodes (boolean) to collapse a branch and hide its descendants. -- `foldIndicatorId`: Stored on nodes to track the ephemeral "…" indicator element that signals a folded branch. -- `foldState`: Stored on nodes and branch arrows to cache their opacity/lock state while hidden so it can be restored when unfolded. -- `boundaryId`: Stored on nodes to track the ID of the boundary element (a closed polygon line) that visually encompasses the node's subtree. -- `isBoundary`: Stored on the line polygon to mark it is a boundary for a node. - -### The "mindmapNew" Tag & Order Stability -When a Level 1 node is created, it is temporarily tagged with `mindmapNew: true`. The layout engine uses this to separate "Existing" nodes from "New" nodes. Existing nodes are sorted by their `mindmapOrder` (or visual angle/Y-position if order is missing), while new nodes are appended to the end. This prevents new additions from scrambling the visual order of existing branches. - -### Sidepanel Lifecycle Management -The script implements `SidepanelTab` hooks (`onFocus`, `onClose`, `onWindowMigrated`) to handle: -- **Context Switching**: Rebinding event listeners when the user switches between multiple Excalidraw views. -- **Window Migration**: Re-attaching keyboard handlers when the sidepanel moves between the main window and a popout window. -- **Auto-Docking**: Ensuring floating modals are docked back to the sidepanel when the view closes to prevent UI orphans. - -### Recursive Grouping -When enabled, the script groups elements from the "leaves" upward. A leaf node is grouped with its parent and the connecting arrow. That group is then nested into the grandparent's group. The **Root Exception**: The root node is never part of an L1 group, allowing users to move the central idea or detach whole branches easily. - -### Smart Decoration Scaling (Edge Anchoring) -When nodes resize (e.g. text edit), the script intelligently re-positions grouped elements: -- **Inside Elements**: Scale relative to the center (e.g. text inside a box). -- **Outside Elements**: Anchor to the nearest edge (e.g. icons above a node) to preserve visual gaps, preventing them from "flying away" during expansion. - -### Copy/Paste & Cross-linking -- **Hierarchy**: Markdown lists are parsed into the mind map structure. -- **Cross-links**: The script preserves non-structural connections by generating internal block references (`^blockId`) and valid wikilinks (`[[#^blockId]]`) when copying branches to markdown. - -### Link suggester keydown events (Enter, Escape) -- **Key-safe integration**: The suggester implements the `KeyBlocker` interface so the script's own key handlers pause while the suggester is active, preventing shortcut collisions during link insertion. - -**/ - -/* --- Initialization Logic --- */ -const VERSION = "test"; - -if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.4")) { - new Notice("Please update the Excalidraw Plugin to version 2.21.0 or higher."); - return; -} - -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); // I will handle revealing in - return; - } -} - -/** - * Cleans up previous keydown handlers to prevent duplicates. - */ -const removeKeydownHandlers = () => { - if (!window.MindmapBuilder) return; - window.MindmapBuilder.keydownHandlers.forEach((f) => { - try { - f(); - } catch (e) { - console.error("Mindmap Builder: Error removing keydown handler:", e); - } - }); - window.MindmapBuilder.keydownHandlers = []; -}; - -/** - * Removes all event listeners and specific hooks attached to the window or workspace. - */ -const removeEventListeners = () => { - removeKeydownHandlers(); - try { - window.MindmapBuilder?.popObsidianHotkeyScope?.(); - } catch (e) { - console.error("Mindmap Builder: Error popping hotkey scope:", e); - } - try { - window.MindmapBuilder?.removePointerDownHandler?.(); - } catch (e) { - console.error("Mindmap Builder: Error removing pointerdown handler:", e); - } - try { - window.MindmapBuilder?.removeActiveLeafListener?.(); - } catch (e) { - console.error("Mindmap Builder: Error removing active-leaf-change listener:", e); - } -}; - -if (!window.MindmapBuilder) { - window.MindmapBuilder = { - keydownHandlers: [], - } -} else { - removeEventListeners(); -} - -const api = () => ea?.getExcalidrawAPI(); -const getAppState = () => api()?.getAppState(); -const isViewSet = () => ea.targetView && ea.targetView._loaded; - -// --------------------------------------------------------------------------- -// LOCALIZATION -// --------------------------------------------------------------------------- -const LOCALE = (localStorage.getItem("language") || "en").toLowerCase(); - -const STRINGS = { - en: { - // Notices - NOTICE_SELECT_NODE_TO_COPY: "Select a node to copy.", - NOTICE_MAP_CUT: "Map cut to clipboard.", - NOTICE_BRANCH_CUT: "Branch cut to clipboard.", - NOTICE_MAP_COPIED: "Map copied as markdown.", - NOTICE_BRANCH_COPIED: "Branch copied as bullet list.", - NOTICE_CLIPBOARD_EMPTY: "Clipboard is empty.", - NOTICE_PASTE_ABORTED: "Paste aborted. Clipboard does not start with a Markdown list or header.", - NOTICE_NO_LIST: "No valid Markdown list found on clipboard.", - NOTICE_PASTE_START: "Pasiting, please wait, this can take a while...", - NOTICE_PASTE_COMPLETE: "Paste complete.", - NOTICE_ACTION_REQUIRES_ARROWS: "This action requires Arrow Keys. Only modifiers can be changed.", - NOTICE_CONFLICT_WITH_ACTION: "Conflict with \"{action}\"", - NOTICE_OBSIDIAN_HOTKEY_CONFLICT: "⚠️ Obsidian Hotkey Conflict!\n\nThis key overrides:\n\"{command}\"", - NOTICE_GLOBAL_HOTKEY_CONFLICT: "⚠️ Global Hotkey Conflict!\n\nThis key overrides:\n\"{command}\"", - NOTICE_NO_HEADINGS: "No headings found in the linked file.", - NOTICE_CANNOT_EDIT_MULTILINE: "Cannot edit multi-line nodes directly.\nDouble-click the element in Excalidraw to edit, then run auto re-arrange map to update the layout.", - NOTICE_CANNOT_MOVE_PINNED: "Cannot move pinned nodes. Unpin the node first.", - NOTICE_CANNOT_MOVE_ROOT: "Cannot move the root node.", - NOTICE_CANNOT_PRMOTE_L1: "Cannot promote Level 1 nodes.", - NOTICE_CANNOT_DEMOTE: "Cannot demote node. No previous sibling to attach to.", - NOTICE_SELECT_NODE_CONTAINING_LINK: "Select a node containing a link.", - NOTICE_CANNOT_DEMOTE_NO_SIBLING_TO_ACCEPT: "Cannot demote: No sibling found to accept this node.", - NOTICE_CANNOT_DEMOTE_NO_VALID_SIBLING: "Cannot demote: No valid sibling to attach to.", - NOTICE_CANNOT_DEMOTE_CROSS_SIDE_NOT_ALLOWED: "Cannot demote: Cross-side demotion is not allowed.", - NOTICE_CANNOT_MOVE_AUTO_LAYOUT_DISABLED: "Cannot move nodes when Auto-Layout is disabled. Enable Auto-Layout first.", - NOTICE_BRANCH_WIDTH_MANUAL_OVERRIDE: "Branch width were not updated because some branch widths were manually modified.", - NOTICE_CANNOT_CHANGE_MASTER_ROOT: "The master root cannot be converted.", - NOTICE_SUBMAP_ROOT_ADDED: "Submap root enabled.", - NOTICE_SUBMAP_ROOT_REMOVED: "Submap root removed. Children now follow the parent map layout.", - CONFIRM_REMOVE_SUBMAP_ROOT: "Change this submap root back to a normal node?\n\nIt will lose its local layout metadata, and its children will be rearranged by the parent root's layout logic.", - - // Action labels (display only) - ACTION_LABEL_ADD: "Add Child", - ACTION_LABEL_ADD_SIBLING_AFTER: "Add Next Sibling", - ACTION_LABEL_ADD_SIBLING_BEFORE: "Add Prev Sibling", - ACTION_LABEL_ADD_FOLLOW: "Add + follow", - ACTION_LABEL_ADD_FOLLOW_FOCUS: "Add + follow + focus", - ACTION_LABEL_ADD_FOLLOW_ZOOM: "Add + follow + zoom", - ACTION_LABEL_SORT_ORDER: "Change Order/Promote Node", - ACTION_LABEL_EDIT: "Edit node", - ACTION_LABEL_PIN: "Pin/Unpin", - ACTION_LABEL_BOX: "Box/Unbox", - ACTION_LABEL_TOGGLE_GROUP: "Group/Ungroup Single Branch", - ACTION_LABEL_COPY: "Copy", - ACTION_LABEL_CUT: "Cut", - ACTION_LABEL_PASTE: "Paste", - ACTION_LABEL_IMPORT_OUTLINE: "Import Outline", - ACTION_LABEL_ZOOM: "Cycle Zoom", - ACTION_LABEL_FOCUS: "Focus (center) node", - ACTION_LABEL_NAVIGATE: "Navigate", - ACTION_LABEL_NAVIGATE_ZOOM: "Navigate & zoom", - ACTION_LABEL_NAVIGATE_FOCUS: "Navigate & focus", - ACTION_LABEL_FOLD: "Fold/Unfold Branch", - ACTION_LABEL_FOLD_L1: "Fold/Unfold to Level 1", - ACTION_LABEL_FOLD_ALL: "Fold/Unfold Branch Recursively", - ACTION_LABEL_DOCK_UNDOCK: "Dock/Undock", - ACTION_LABEL_HIDE: "Dock & hide", - ACTION_LABEL_REARRANGE: "Rearrange Map", - ACTION_LABEL_TOGGLE_SUBMAP_ROOT: "Start/End Submap Root", - ACTION_LABEL_TOGGLE_CHECKBOX: "Toggle Checkbox Status", - ACTION_LABEL_CALENDAR: "Task Calendar & Priority", - ACTION_LABEL_TOGGLE_EMBED: "Toggle Embed/Link", - - // Tooltips (shared) - PIN_TOOLTIP_PINNED: "This element is pinned. Click to unpin the location of the selected element", - PIN_TOOLTIP_UNPINNED: "This element is not pinned. Click to pin the location of the selected element", - TOGGLE_GROUP_TOOLTIP_GROUP: "Group this branch. Only available if \"Group Branches\" is disabled", - TOGGLE_GROUP_TOOLTIP_UNGROUP: "Ungroup this branch. Only available if \"Group Branches\" is disabled", - TOOLTIP_EDIT_NODE: "Edit text of selected node", - TOOLTIP_PIN_INIT: "Pin/Unpin location of a node. When pinned nodes won't get auto-arranged", - TOOLTIP_REFRESH: "Auto rearrange map", - TOOLTIP_DOCK: "Dock to Sidepanel", - TOOLTIP_UNDOCK: "Undock to Floating Modal", - TOOLTIP_ZOOM_CYCLE: "Cycle element zoom", - TOOLTIP_TOGGLE_GROUP_BTN: "Toggle grouping/ungrouping of a branch. Only available if \"Group Branches\" is disabled.", - TOOLTIP_TOGGLE_BOX: "Toggle node box", - TOOLTIP_TOGGLE_BOUNDARY: "Toggle subtree boundary", - TOOLTIP_TOGGLE_FLOATING_EXTRAS: "Toggle extra controls", - TOOLTIP_CONFIGURE_PALETTE: "Configure custom color palette for branches", - TOOLTIP_CONFIGURE_LAYOUT: "Configure layout settings", - TOOLTIP_MOVE_UP: "Move Up", - TOOLTIP_MOVE_DOWN: "Move Down", - TOOLTIP_EDIT_COLOR: "Edit", - TOOLTIP_DELETE_COLOR: "Delete", - TOOLTIP_OPEN_PALETTE_PICKER: "Open Palette Picker", - TOOLTIP_FOLD_BRANCH: "Fold/Unfold selected branch", - TOOLTIP_FOLD_L1_BRANCH: "Fold/Unfold children (Level 1)", - TOOLTIP_FOLD_ALL: "Fold/Unfold Branch Recursively", - TOOLTIP_IMPORT_OUTLINE: "Import headings from linked file as child nodes", - TOOLTIP_RESET_TO_DEFAULT: "Reset to default", - TOOLTIP_SUBMAP_ROOT_ADD: "Start submap from selected node", - TOOLTIP_SUBMAP_ROOT_REMOVE: "Convert submap root back to a normal node", - TOOLTIP_TOGGLE_CHECKBOX: "Toggle task checkbox status", - TOOLTIP_CALENDAR: "Configure Task Date & Priority", - TOOLTIP_TOGGLE_EMBED: "Toggle node between Embed and Link", - - // Buttons and labels - DOCK_TITLE: "Mind Map Builder", - HELP_SUMMARY: "Help", - INPUT_PLACEHOLDER: "Concept... type [[ to insert link", - ONTOLOGY_PLACEHOLDER: "Ontology (Arrow Label)", - BUTTON_COPY: "Copy", - BUTTON_CUT: "Cut", - BUTTON_PASTE: "Paste", - TITLE_ADD_SIBLING: `Add sibling with ${ea.DEVICE.isMacOS || ea.DEVICE.isIOS ? "OPT" : "ALT"}+Enter`, - TITLE_ADD_FOLLOW: "Add and follow", - TITLE_COPY: "Copy branch as text", - TITLE_CUT: "Cut branch as text", - TITLE_PASTE: "Paste list from clipboard", - LABEL_ZOOM_LEVEL: "Zoom Level", - LABEL_GROWTH_STRATEGY: "Growth Strategy", - LABEL_FILL_SWEEP: "Fill Sweep Angle", - DESC_FILL_SWEEP: "Distribute nodes across the full Max Sweep Angle immediately, rather than growing the arc gradually as nodes are added.", - LABEL_ARROW_TYPE: "Curved Connectors", - LABEL_AUTO_LAYOUT: "Auto-Layout", - LABEL_GROUP_BRANCHES: "Group Branches", - LABEL_BOX_CHILD_NODES: "Box Child Nodes", - LABEL_ROUNDED_CORNERS: "Rounded Corners", - LABEL_USE_SCENE_STROKE: "Use scene stroke style", - DESC_USE_SCENE_STROKE: "Use the latest stroke style (solid, dashed, dotted) from the scene, or always use solid style for branches.", - LABEL_BRANCH_SCALE: "Branch Scale", - LABEL_BASE_WIDTH: "Base Thickness", - LABEL_MULTICOLOR_BRANCHES: "Multicolor Branches", - LABEL_MAX_WRAP_WIDTH: "Max Wrap Width", - LABEL_CENTER_TEXT: "Center text", - DESC_CENTER_TEXT: "Toggle off: align nodes to right/left depending; Toggle on: center the text.", - LABEL_FONT_SIZES: "Font Sizes", - HOTKEY_SECTION_TITLE: "Hotkey Configuration", - HOTKEY_HINT: "These hotkeys may override some Obsidian defaults. They're Local (⌨️) by default, active only when the MindMap input field is focused. Use the 🌐/🎨/⌨️ toggle to change hotkey scope: 🌐 Overrides Obsidian hotkeys whenever an Excalidraw tab is visible, 🎨 Overrides Obsidian hotkeys whenever Excalidraw is focused, ⌨️ Local (input focused).", - RECORD_HOTKEY_PROMPT: "Press hotkey...", - ARIA_SCOPE_INPUT: "Local: Active only when MindMap Input is focused", - ARIA_SCOPE_EXCALIDRAW: "Excalidraw: Active whenever MindMap Input or Excalidraw is focused", - ARIA_SCOPE_GLOBAL: "Global: Active everywhere in Obsidian, whenever the Excalidraw view is visible", - ARIA_RESTORE_DEFAULT: "Restore default", - ARIA_CUSTOMIZE_HOTKEY: "Customize this hotkey", - ARIA_OVERRIDE_COMMAND: "Overrides Obsidian command:\n{command}", - - // Palette manager - MODAL_PALETTE_TITLE: "Mindmap Branch Palette", - LABEL_ENABLE_CUSTOM_PALETTE: "Enable Custom Palette", - DESC_ENABLE_CUSTOM_PALETTE: "Use these colors instead of auto-generated ones.", - LABEL_RANDOMIZE_ORDER: "Randomize Order", - DESC_RANDOMIZE_ORDER: "Pick colors randomly instead of sequentially.", - HEADING_ADD_NEW_COLOR: "Add New Color", - HEADING_EDIT_COLOR: "Edit Color", - LABEL_SELECT_COLOR: "Select Color", - BUTTON_CANCEL_EDIT: "Cancel Edit", - BUTTON_ADD_COLOR: "Add Color", - BUTTON_UPDATE_COLOR: "Update Color", - - // Layout configuration - MODAL_LAYOUT_TITLE: "Layout Configuration", - // Section Headers - SECTION_GENERAL: "General Spacing", - SECTION_RADIAL: "Radial Layout (Clockwise)", - SECTION_DIRECTIONAL: "Directional Layout (Left/Right)", - SECTION_VERTICAL: "Vertical Maps (Up/Down)", - SECTION_VISUALS: "Visual Elements", - SECTION_MANUAL: "Manual Mode Behavior", - LAYOUT_RESET: "Reset All to Default", - LAYOUT_SAVE: "Save & Close", - // Radial Strings - RADIAL_ASPECT_RATIO: "Ellipse Aspect Ratio", - DESC_RADIAL_ASPECT_RATIO: "Controls the shape. < 1.0 is tall/narrow (0.7 = portrait). 1.0 is circular. > 1.0 is wide (landscape).", - RADIAL_POLE_GAP_BONUS: "Pole Gap Bonus", - DESC_RADIAL_POLE_GAP_BONUS: "Increases spacing between nodes at the Top and Bottom. Higher values push nodes further along the arc.", - RADIAL_START_ANGLE: "Start Angle", - DESC_RADIAL_START_ANGLE: "Where the first node appears (Degrees). 270 is North, 0 is East, 90 is South.", - RADIAL_MAX_SWEEP: "Max Sweep Angle", - DESC_RADIAL_MAX_SWEEP: "Total arc available to fill. 360 uses full circle. Lower values leave a gap between the first and last node.", - // Others - GAP_X: "Gap X", - DESC_LAYOUT_GAP_X: "Horizontal distance between parent and child nodes.", - GAP_Y: "Gap Y", - DESC_LAYOUT_GAP_Y: "Vertical distance between sibling nodes. Also used as the base gap for Radial layouts.", - GAP_MULTIPLIER: "Gap Multiplier", - DESC_LAYOUT_GAP_MULTIPLIER: "Vertical spacing for 'leaf' nodes (no children), relative to font size. Low: list-like stacking. High: standard tree spacing.", - DIRECTIONAL_ARC_SPAN_RADIANS: "Directional Arc-span Radians", - DESC_LAYOUT_ARC_SPAN: "Curvature of the child list. Low (0.5): Flatter, list-like. High (2.0): Curved, organic, but risk of overlap.", - ROOT_RADIUS_FACTOR: "Root Radius Factor", - DESC_LAYOUT_ROOT_RADIUS: "Multiplier for the Root node's bounding box to determine initial radius.", - MIN_RADIUS: "Minimum Radius", - DESC_LAYOUT_MIN_RADIUS: "The absolute minimum distance from the root center to the first level of nodes.", - RADIUS_PADDING_PER_NODE: "Radius Padding per Node", - DESC_LAYOUT_RADIUS_PADDING: "Extra radius added per child node to accommodate dense maps.", - GAP_MULTIPLIER_RADIAL: "Radial-layout Gap Multiplier", - DESC_LAYOUT_GAP_RADIAL: "Angular spacing multiplier for Radial mode.", - GAP_MULTIPLIER_DIRECTIONAL: "Vertical-layout Gap Multiplier", - DESC_LAYOUT_GAP_DIRECTIONAL: "Spacing multiplier for Right-facing and Left-facing top level branches", - INDICATOR_OFFSET: "Fold Indicator Offset", - DESC_LAYOUT_INDICATOR_OFFSET: "Distance of the '...' fold indicator from the node.", - INDICATOR_OPACITY: "Fold Indicator Opacity", - DESC_LAYOUT_INDICATOR_OPACITY: "Opacity of the '...' fold indicator (0-100).", - CONTAINER_PADDING: "Container Padding", - DESC_LAYOUT_CONTAINER_PADDING: "Padding inside the box when 'Box Child Nodes' or 'Box/Unbox' is used.", - MAX_SEGMENT_LENGTH: "Boundary Line Precision", - DESC_LAYOUT_BOUNDARY_LINE_PRECISION: "Boundary smoothing precision. Smaller values are more precise (30 = Precise), larger values are rougher (200 = Rough).", - VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "Subtree Width Blend (Single-sided)", - DESC_VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "How strongly one-sided submaps (Right-facing / Left-facing) reserve horizontal sibling space in vertical maps. High impact.", - VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "Subtree Width Blend (Dual-sided)", - DESC_VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "How strongly dual-sided submaps (Right-Left) reserve horizontal sibling space in vertical maps. High impact.", - VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "Subtree Smooth Threshold Multiplier", - DESC_VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "Starts smooth compression after this multiple of Gap Y to avoid spacing jumps when adding more children. Usually subtle unless the map is large.", - VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "Subtree Smooth Minimum Scale", - DESC_VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "Minimum compression scale used by the vertical subtree width smoother. Higher values preserve more width. Usually subtle unless the map is large.", - HORIZONTAL_L1_SOFTCAP_THRESHOLD: "Horizontal L1 Soft Cap Threshold", - DESC_HORIZONTAL_L1_SOFTCAP_THRESHOLD: "Soft cap (px) before Up/Down Level-1 subtree widths are compressed. Medium to high impact on large maps.", - HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "Horizontal L1 Compression Min Scale", - DESC_HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "Minimum compression scale for Up/Down Level-1 width compression. Higher values preserve more width. Medium impact after soft cap is reached.", - VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "Compact Parent-Child Gap Ratio", - DESC_VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "In compact vertical subtrees, uses this fraction of Gap X for parent-child distance. Very high visible impact.", - DIRECTIONAL_CROSS_AXIS_RATIO: "Directional Cross-axis Ratio", - DESC_DIRECTIONAL_CROSS_AXIS_RATIO: "Cross-axis radius ratio for directional arc layouts (0.2 = flatter arcs, 1.0 = rounder arcs). High visual impact on L1 spread.", - MANUAL_GAP_MULTIPLIER: "Manual-layout Gap Multiplier", - DESC_LAYOUT_MANUAL_GAP: "Spacing multiplier when adding nodes while Auto-Layout is disabled.", - MANUAL_JITTER_RANGE: "Manual-layout Jitter Range", - DESC_LAYOUT_MANUAL_JITTER: "Random position offset when adding nodes while Auto-Layout is disabled.", - - CALENDAR_DATE_INDEX: "Date {index} of {total}", - CALENDAR_DATE_LABEL: "Date", - CALENDAR_DATE_TYPE: "Date Type", - CALENDAR_PRIORITY: "Priority", - CALENDAR_RECURRENCE: "Recurrence", - CALENDAR_RECURRENCE_PLACEHOLDER: "every day", - CALENDAR_RECURRENCE_DESC: "e.g., 'every day', 'every 2 weeks'
Tasks recurrence docs", - CALENDAR_INJECT_LINK: "Inject node link", - CALENDAR_INJECT_LINK_DESC: "Adds a link to the node at the end of the task.", - CALENDAR_ALIAS_PLACEHOLDER: "Alias", - CALENDAR_BTN_CANCEL: "Cancel", - CALENDAR_BTN_TASK_ONLY: "Task Only", - CALENDAR_BTN_ADD_DATE_TASK: "Add Date & Task", - - CALENDAR_PRIORITY_HIGHEST: "Highest", - CALENDAR_PRIORITY_HIGH: "High", - CALENDAR_PRIORITY_MEDIUM: "Medium", - CALENDAR_PRIORITY_NORMAL: "Normal", - CALENDAR_PRIORITY_LOW: "Low", - CALENDAR_PRIORITY_LOWEST: "Lowest", - - CALENDAR_DATETYPE_DUE: "Due", - CALENDAR_DATETYPE_START: "Start", - CALENDAR_DATETYPE_SCHEDULED: "Scheduled", - CALENDAR_DATETYPE_CREATED: "Created", - CALENDAR_DATETYPE_DONE: "Done", - CALENDAR_DATETYPE_CANCELLED: "Cancelled", - - // Presets - PRESET_LABEL: "Preset", - PRESET_DEFAULT: "Default", - PRESET_UNSAVED: "Custom / Unlinked", - PRESET_BTN_SAVE: "Save to Preset", - PRESET_BTN_DELETE: "Delete Preset", - PRESET_BTN_NEW: "Create New Preset", - PRESET_BTN_APPLY: "Apply Preset to Map", - PRESET_WARNING_MODIFIED: "Map settings differ from preset.", - PROMPT_NEW_PRESET_NAME: "New preset name:", - NOTICE_PRESET_DELETED: "Preset deleted.", - NOTICE_PRESET_SAVED: "Preset saved.", - NOTICE_PRESET_APPLIED: "Preset applied.", - - // Misc - INPUT_TITLE_PASTE_ROOT: "Mindmap Builder Paste", - INSTRUCTIONS: "> [!Tip]\n" + - ">🚀 Become a MindMap Builder Pro with the Official [MindMap Builder Course](https://www.visual-thinking-workshop.com/mindmap)!\n" + - "\n" + - "- **ENTER**: Add a child node and stay on the current parent for rapid entry. " + - "If you press enter when the input field is empty the focus will move to the child node that was most recently added. " + - "Pressing enter subsequent times will iterate through the new child's siblings\n" + - "- **Hotkeys**: See configuration at the bottom of the sidepanel\n" + - "- **Dock/Undock**: You can dock/undock the input field using the dock/undock button or the configured hotkey\n" + - "- **Folding**: Fold/Unfold buttons only appear when the input is docked; when undocked, use the folding hotkeys.\n" + - "- **ESC**: Docks the floating input field without activating the side panel\n" + - "- **Coloring**: First level branches get unique colors (Multicolor mode). Descendants inherit parent's color.\n" + - "- **Grouping**:\n" + - " - Enabling \"Group Branches\" recursively groups sub-trees from leaves up to the first level.\n" + - "- **Copy/Paste**: Export/Import indented Markdown lists.\n" + - "\n" + - "😍 If you find this script helpful, please [buy me a coffee ☕](https://ko-fi.com/zsolt).", - }, -}; - -/** - * @param {String} lang {@link LOCALE} - * @param {Object} content - */ -function addLocale(lang, content) { - STRINGS[lang] = content -}; - -addLocale("zh", { - // Notices - NOTICE_SELECT_NODE_TO_COPY: "请选择要复制的节点。", - NOTICE_MAP_CUT: "导图已剪切到剪贴板。", - NOTICE_BRANCH_CUT: "分支已剪切到剪贴板。", - NOTICE_MAP_COPIED: "导图已复制为 Markdown 格式。", - NOTICE_BRANCH_COPIED: "分支已复制为列表格式。", - NOTICE_CLIPBOARD_EMPTY: "剪贴板为空。", - NOTICE_PASTE_ABORTED: "粘贴中止。剪贴板内容非 Markdown 列表或标题。", - NOTICE_NO_LIST: "剪贴板中未发现有效的 Markdown 列表。", - NOTICE_PASTE_START: "正在粘贴,请稍候,可能需要一些时间…", - NOTICE_PASTE_COMPLETE: "粘贴完成。", - NOTICE_ACTION_REQUIRES_ARROWS: "此操作需要方向键。仅可修改修饰键。", - NOTICE_CONFLICT_WITH_ACTION: "与“{action}”操作冲突", - NOTICE_OBSIDIAN_HOTKEY_CONFLICT: "⚠️ Obsidian 热键冲突!\n\n此按键将覆盖:\n“{command}”", - NOTICE_GLOBAL_HOTKEY_CONFLICT: "⚠️ 全局热键冲突!\n\n此按键将覆盖:\n“{command}”", - NOTICE_NO_HEADINGS: "链接文件中未发现小标题。", - NOTICE_CANNOT_EDIT_MULTILINE: "无法直接编辑多行节点。\n请在 Excalidraw 中双击元素进行编辑,然后运行“自动重排导图”来更新布局。", - NOTICE_CANNOT_MOVE_PINNED: "无法移动已锁定的节点。请先解锁。", - NOTICE_CANNOT_MOVE_ROOT: "无法移动根节点。", - NOTICE_CANNOT_PRMOTE_L1: "无法提升 1 级节点。", - NOTICE_CANNOT_DEMOTE: "无法降级节点。没有可依附的前置同级节点。", - NOTICE_SELECT_NODE_CONTAINING_LINK: "请选择包含链接的节点。", - NOTICE_CANNOT_DEMOTE_NO_SIBLING_TO_ACCEPT: "无法降级:未找到可接收此节点的同级节点。", - NOTICE_CANNOT_DEMOTE_NO_VALID_SIBLING: "无法降级:没有可附加的有效同级节点。", - NOTICE_CANNOT_DEMOTE_CROSS_SIDE_NOT_ALLOWED: "无法降级:不允许跨侧降级。", - NOTICE_CANNOT_MOVE_AUTO_LAYOUT_DISABLED: "禁用自动布局时无法移动节点。请先启用自动布局。", - NOTICE_BRANCH_WIDTH_MANUAL_OVERRIDE: "分支粗细未更新,因为部分分支粗细已被手动修改。", - NOTICE_CANNOT_CHANGE_MASTER_ROOT: "主根节点不能被转换。", - NOTICE_SUBMAP_ROOT_ADDED: "已启用子图根节点。", - NOTICE_SUBMAP_ROOT_REMOVED: "已移除子图根节点。其子节点将按亲代根节点布局重排。", - CONFIRM_REMOVE_SUBMAP_ROOT: "恢复为普通节点吗?\n\n它将失去本地布局元数据,其子节点将按亲代根节点布局重排。", - - // Action labels (display only) - ACTION_LABEL_ADD: "添加子节点", - ACTION_LABEL_ADD_SIBLING_AFTER: "添加后置同级节点", - ACTION_LABEL_ADD_SIBLING_BEFORE: "添加前置同级节点", - ACTION_LABEL_ADD_FOLLOW: "添加 + 跟随", - ACTION_LABEL_ADD_FOLLOW_FOCUS: "添加 + 跟随 + 聚焦", - ACTION_LABEL_ADD_FOLLOW_ZOOM: "添加 + 跟随 + 缩放", - ACTION_LABEL_SORT_ORDER: "更改顺序/提升节点", - ACTION_LABEL_EDIT: "编辑节点", - ACTION_LABEL_PIN: "锁定/解锁", - ACTION_LABEL_BOX: "添加/移除边框", - ACTION_LABEL_TOGGLE_GROUP: "编组/解除编组单分支", - ACTION_LABEL_COPY: "复制", - ACTION_LABEL_CUT: "剪切", - ACTION_LABEL_PASTE: "粘贴", - ACTION_LABEL_IMPORT_OUTLINE: "导入大纲", - ACTION_LABEL_ZOOM: "循环缩放", - ACTION_LABEL_FOCUS: "聚焦(并居中)节点", - ACTION_LABEL_NAVIGATE: "导航", - ACTION_LABEL_NAVIGATE_ZOOM: "导航 & 缩放", - ACTION_LABEL_NAVIGATE_FOCUS: "导航 & 聚焦", - ACTION_LABEL_FOLD: "折叠/展开分支", - ACTION_LABEL_FOLD_L1: "折叠/展开 L1 子节点", - ACTION_LABEL_FOLD_ALL: "递归折叠/展开分支", - ACTION_LABEL_DOCK_UNDOCK: "停靠/取消停靠", - ACTION_LABEL_HIDE: "停靠 & 隐藏", - ACTION_LABEL_REARRANGE: "重排导图", - ACTION_LABEL_TOGGLE_SUBMAP_ROOT: "开始/结束子图根节点", - ACTION_LABEL_TOGGLE_CHECKBOX: "切换复选框状态", - ACTION_LABEL_CALENDAR: "任务日历与优先级", - ACTION_LABEL_TOGGLE_EMBED: "切换嵌入/链接", - - // Tooltips (shared) - PIN_TOOLTIP_PINNED: "此元素已锁定。点击解锁所选元素的位置。", - PIN_TOOLTIP_UNPINNED: "此元素未锁定。点击锁定所选元素的位置。", - TOGGLE_GROUP_TOOLTIP_GROUP: "编组此分支。仅在“分支编组”禁用时可用。", - TOGGLE_GROUP_TOOLTIP_UNGROUP: "解除编组此分支。仅在“分支编组”禁用时可用。", - TOOLTIP_EDIT_NODE: "编辑所选节点的文本", - TOOLTIP_PIN_INIT: "锁定/解锁节点位置。锁定的节点不会被自动重排。", - TOOLTIP_REFRESH: "自动重排导图", - TOOLTIP_DOCK: "停靠到侧边面板", - TOOLTIP_UNDOCK: "转为浮动窗口", - TOOLTIP_ZOOM_CYCLE: "循环切换元素缩放级别", - TOOLTIP_TOGGLE_GROUP_BTN: "切换分支的编组状态。仅在“分支编组”禁用时可用。", - TOOLTIP_TOGGLE_BOX: "切换节点边框", - TOOLTIP_TOGGLE_BOUNDARY: "切换子树边界", - TOOLTIP_TOGGLE_FLOATING_EXTRAS: "切换额外控件", - TOOLTIP_CONFIGURE_PALETTE: "为分支配置自定义调色板", - TOOLTIP_CONFIGURE_LAYOUT: "配置布局设置", - TOOLTIP_MOVE_UP: "上移", - TOOLTIP_MOVE_DOWN: "下移", - TOOLTIP_EDIT_COLOR: "编辑", - TOOLTIP_DELETE_COLOR: "删除", - TOOLTIP_OPEN_PALETTE_PICKER: "打开颜色选择器", - TOOLTIP_FOLD_BRANCH: "折叠/展开所选分支", - TOOLTIP_FOLD_L1_BRANCH: "折叠/展开 L1 子节点", - TOOLTIP_FOLD_ALL: "递归折叠/展开分支", - TOOLTIP_IMPORT_OUTLINE: "从链接文件中导入小标题作为子节点数据", - TOOLTIP_RESET_TO_DEFAULT: "恢复默认", - TOOLTIP_SUBMAP_ROOT_ADD: "从所选节点开始子图", - TOOLTIP_SUBMAP_ROOT_REMOVE: "将子图根节点恢复为普通节点", - TOOLTIP_TOGGLE_CHECKBOX: "切换任务复选框状态", - TOOLTIP_CALENDAR: "配置任务日期与优先级", - TOOLTIP_TOGGLE_EMBED: "在嵌入和链接之间切换节点", - - // Buttons and labels - DOCK_TITLE: "MindMap Builder", - HELP_SUMMARY: "帮助", - INPUT_PLACEHOLDER: "输入概念… 输入 [[ 插入链接", - ONTOLOGY_PLACEHOLDER: "本体(箭头标签)", - BUTTON_COPY: "复制", - BUTTON_CUT: "剪切", - BUTTON_PASTE: "粘贴", - TITLE_ADD_SIBLING: `使用 ${ea.DEVICE.isMacOS || ea.DEVICE.isIOS ? "OPT" : "ALT"}+Enter 添加同级节点`, - TITLE_ADD_FOLLOW: "添加并跟随", - TITLE_COPY: "复制分支为文本", - TITLE_CUT: "剪切分支为文本", - TITLE_PASTE: "从剪贴板粘贴列表", - LABEL_ZOOM_LEVEL: "缩放级别", - LABEL_GROWTH_STRATEGY: "生长策略", - LABEL_FILL_SWEEP: "填充扫过角度", - DESC_FILL_SWEEP: "立即在整个“最大扫过角度”范围内分布节点,而不是随着节点数量增加逐渐扩大弧度。", - LABEL_ARROW_TYPE: "曲线连接", - LABEL_AUTO_LAYOUT: "自动布局", - LABEL_GROUP_BRANCHES: "分支编组", - LABEL_BOX_CHILD_NODES: "为子节点添加边框", - LABEL_ROUNDED_CORNERS: "圆角", - LABEL_USE_SCENE_STROKE: "使用场景线条样式", - DESC_USE_SCENE_STROKE: "使用场景中最新的线条样式(实线、虚线、点线),否则分支将始终使用实线。", - LABEL_BRANCH_SCALE: "分支粗细比例", - LABEL_BASE_WIDTH: "基础粗细", - LABEL_MULTICOLOR_BRANCHES: "多色分支", - LABEL_MAX_WRAP_WIDTH: "最大折行宽度", - LABEL_CENTER_TEXT: "文本居中", - DESC_CENTER_TEXT: "关闭:根据位置左/右对齐;开启:文本强制居中。", - LABEL_FONT_SIZES: "字体大小", - HOTKEY_SECTION_TITLE: "热键配置", - HOTKEY_HINT: "这些热键可能覆盖 Obsidian 默认设置。热键作用域默认为局部(⌨️),使用 🌐/🎨/⌨️ 切换作用域:🌐 Excalidraw 标签页可见即生效,🎨 Excalidraw 聚焦时生效,⌨️ 输入框聚焦时生效。", - RECORD_HOTKEY_PROMPT: "按下热键…", - ARIA_SCOPE_INPUT: "局部(Local):仅在输入框聚焦时生效", - ARIA_SCOPE_EXCALIDRAW: "Excalidraw:输入框或 Excalidraw 聚焦时生效", - ARIA_SCOPE_GLOBAL: "全局(Global):在 Obsidian 任何位置,Excalidraw 可见即生效", - ARIA_RESTORE_DEFAULT: "恢复默认", - ARIA_CUSTOMIZE_HOTKEY: "自定义此热键", - ARIA_OVERRIDE_COMMAND: "将覆盖 Obsidian 命令:\n{command}", - - // Palette manager - MODAL_PALETTE_TITLE: "导图分支调色板", - LABEL_ENABLE_CUSTOM_PALETTE: "启用自定义调色板", - DESC_ENABLE_CUSTOM_PALETTE: "使用以下颜色代替自动生成的颜色。", - LABEL_RANDOMIZE_ORDER: "随机顺序", - DESC_RANDOMIZE_ORDER: "随机选择颜色而非按顺序选择。", - HEADING_ADD_NEW_COLOR: "添加新颜色", - HEADING_EDIT_COLOR: "编辑颜色", - LABEL_SELECT_COLOR: "选择颜色", - BUTTON_CANCEL_EDIT: "取消编辑", - BUTTON_ADD_COLOR: "添加颜色", - BUTTON_UPDATE_COLOR: "更新颜色", - - // Layout configuration - MODAL_LAYOUT_TITLE: "布局配置", - // Section Headers - SECTION_GENERAL: "常规间距", - SECTION_RADIAL: "径向布局(顺时针)", - SECTION_DIRECTIONAL: "定向布局(左/右)", - SECTION_VERTICAL: "垂直导图(上/下)", - SECTION_VISUALS: "视觉元素", - SECTION_MANUAL: "手动模式行为", - LAYOUT_RESET: "重置所有为默认值", - LAYOUT_SAVE: "保存并关闭", - // Radial Strings - RADIAL_ASPECT_RATIO: "椭圆长宽比", - DESC_RADIAL_ASPECT_RATIO: "控制形状。< 1.0 为瘦长(0.7 为纵向),1.0 为正圆,> 1.0 为宽扁(横向)。", - RADIAL_POLE_GAP_BONUS: "极点间距补偿", - DESC_RADIAL_POLE_GAP_BONUS: "增加椭圆南北两极区域内节点的间距。值越大,节点沿弧线推得越远。", - RADIAL_START_ANGLE: "起始角度", - DESC_RADIAL_START_ANGLE: "第一个节点出现的位置(度数)。270 为北,0 为东,90 为南。", - RADIAL_MAX_SWEEP: "最大扫过角度", - DESC_RADIAL_MAX_SWEEP: "分支可填充的弧范围。360 为全圆。较小的值会使圆不完整。", - // Others - GAP_X: "水平间距(Gap X)", - DESC_LAYOUT_GAP_X: "亲代节点与子节点之间的水平距离。", - GAP_Y: "垂直间距(Gap Y)", - DESC_LAYOUT_GAP_Y: "同级节点之间的垂直距离。径向布局中的基础间距。", - GAP_MULTIPLIER: "间距倍数", - DESC_LAYOUT_GAP_MULTIPLIER: "叶节点(无子节点的节点)相对于字体大小的垂直间距。低:类似列表堆叠;高:标准树状间距。", - DIRECTIONAL_ARC_SPAN_RADIANS: "定向张开弧度(Arc-span Radians)", - DESC_LAYOUT_ARC_SPAN: "子节点排列的曲率。低(0.5):较平,类似列表。高(2.0):弯曲有机,但有重叠风险。", - ROOT_RADIUS_FACTOR: "根节点半径系数", - DESC_LAYOUT_ROOT_RADIUS: "相对于根节点边框的倍数,决定最初的半径。", - MIN_RADIUS: "最小半径", - DESC_LAYOUT_MIN_RADIUS: "从根节点中心到第一级节点的最小绝对距离。", - RADIUS_PADDING_PER_NODE: "单节点径向空白边距", - DESC_LAYOUT_RADIUS_PADDING: "每个子节点额外增加的半径,以适应密集型导图。", - GAP_MULTIPLIER_RADIAL: "径向布局间距倍数", - DESC_LAYOUT_GAP_RADIAL: "径向布局模式下的角度间距倍数。", - GAP_MULTIPLIER_DIRECTIONAL: "垂直方向间距倍数", - DESC_LAYOUT_GAP_DIRECTIONAL: "定向布局顶层分支之间的间距倍数。", - INDICATOR_OFFSET: "折叠指示符偏移", - DESC_LAYOUT_INDICATOR_OFFSET: "折叠指示符(三连点)距离节点的距离。", - INDICATOR_OPACITY: "折叠指示符不透明度", - DESC_LAYOUT_INDICATOR_OPACITY: "折叠指示符的不透明度(0-100)。", - CONTAINER_PADDING: "容器内边距", - DESC_LAYOUT_CONTAINER_PADDING: "使用边框样式时的内边距。", - MAX_SEGMENT_LENGTH: "边界线精度", - DESC_LAYOUT_BOUNDARY_LINE_PRECISION: "边界平滑精度。值越小越精细(30 = 精细),值越大越粗略(200 = 粗略)。", - VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "子树宽度参与度(单侧)", - DESC_VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "垂直导图中,单侧生长的子图占用(左/右)水平空间的强度。影响程度高。", - VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "子树宽度参与度(双侧)", - DESC_VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "垂直导图中,双侧生长的子图占用(左右)水平空间的强度。影响程度高。", - VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "子树平滑压缩触发倍数", - DESC_VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "超过 Gap Y 乘以该倍数后开始平滑压缩,避免新增子节点间距突变。通常在大导图中更明显。", - VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "子树平滑压缩下限", - DESC_VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "垂直子树宽度平滑压缩到的最小值。值越大越保留原宽度。通常在大导图中更明显。", - HORIZONTAL_L1_SOFTCAP_THRESHOLD: "L1 水平方向软上限", - DESC_HORIZONTAL_L1_SOFTCAP_THRESHOLD: "超过该 px 值后,上/下 L1 子树宽度开始压缩。对大导图影响程度中到高。", - HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "L1 水平方向压缩下限", - DESC_HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "上/下 L1 宽度压缩到的最小值。值越大越保留原宽度。软上限被达到(、开始压缩)后影响中等。", - VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "紧凑亲子间距比例", - DESC_VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "紧凑垂直子树中,亲子间距使用 Gap X 乘以该比例。极大影响视觉效果。", - DIRECTIONAL_CROSS_AXIS_RATIO: "正交轴之比", - DESC_DIRECTIONAL_CROSS_AXIS_RATIO: "与垂直于生长方向的轴(Cross-axis)的半径之比(0.2 = 扁,1.0 = 圆)。极大影响 L1 展开形态。", - MANUAL_GAP_MULTIPLIER: "手动布局间距倍数", - DESC_LAYOUT_MANUAL_GAP: "禁用自动布局时添加节点的间距倍数。", - MANUAL_JITTER_RANGE: "手动布局抖动范围", - DESC_LAYOUT_MANUAL_JITTER: "禁用自动布局时添加节点的随机位置偏移。", - - CALENDAR_DATE_INDEX: "第 {index} 个日期,共 {total} 个", - CALENDAR_DATE_LABEL: "日期", - CALENDAR_DATE_TYPE: "日期类型", - CALENDAR_PRIORITY: "优先级", - CALENDAR_RECURRENCE: "重复", - CALENDAR_RECURRENCE_PLACEHOLDER: "every day", - CALENDAR_RECURRENCE_DESC: "例如,'every day','every 2 weeks'
Tasks 插件重复任务文档", - CALENDAR_INJECT_LINK: "插入节点链接", - CALENDAR_INJECT_LINK_DESC: "在任务末尾添加指向该节点的链接。", - CALENDAR_ALIAS_PLACEHOLDER: "别名", - CALENDAR_BTN_CANCEL: "取消", - CALENDAR_BTN_TASK_ONLY: "仅任务", - CALENDAR_BTN_ADD_DATE_TASK: "添加日期和任务", - - CALENDAR_PRIORITY_HIGHEST: "最高", - CALENDAR_PRIORITY_HIGH: "高", - CALENDAR_PRIORITY_MEDIUM: "中", - CALENDAR_PRIORITY_NORMAL: "普通", - CALENDAR_PRIORITY_LOW: "低", - CALENDAR_PRIORITY_LOWEST: "最低", - - CALENDAR_DATETYPE_DUE: "截止", - CALENDAR_DATETYPE_START: "开始", - CALENDAR_DATETYPE_SCHEDULED: "计划", - CALENDAR_DATETYPE_CREATED: "创建", - CALENDAR_DATETYPE_DONE: "完成", - CALENDAR_DATETYPE_CANCELLED: "取消", - - // Presets - PRESET_LABEL: "预设", - PRESET_UNSAVED: "自定义 / 未关联", - PRESET_BTN_SAVE: "保存预设", - PRESET_BTN_DELETE: "删除预设", - PRESET_BTN_NEW: "新建预设", - PRESET_BTN_APPLY: "应用预设到导图", - PRESET_WARNING_MODIFIED: "导图设置与预设不符。", - PROMPT_NEW_PRESET_NAME: "新预设名称:", - NOTICE_PRESET_DELETED: "预设已删除。", - NOTICE_PRESET_SAVED: "预设已保存。", - NOTICE_PRESET_APPLIED: "预设已应用。", - - // Misc - INPUT_TITLE_PASTE_ROOT: "MindMap Builder 粘贴", - INSTRUCTIONS: "> [!Tip]\n" + - ">🚀 想要进阶?欢迎参加官方 [MindMap Builder 课程](https://www.visual-thinking-workshop.com/mindmap)!\n" + - "\n" + - "- **ENTER**:添加子节点并保留在当前亲代节点上,方便快速输入。" + - "若输入框为空时按回车,焦点将移动到最新添加的子节点。" + - "连续按回车将在该节点的同级节点间循环切换。\n" + - "- **热键**:见侧边面板底部的配置选项。\n" + - "- **停靠/取消停靠**:使用按钮或配置好的热键来切换输入框位置。\n" + - "- **折叠**:仅在输入框停靠时显示按钮;取消停靠时请使用热键。\n" + - "- **ESC**:将浮动输入框停靠,但不激活侧边面板。\n" + - "- **着色**:顶层分支拥有独立颜色(多色模式),后代节点继承亲代颜色。\n" + - "- **编组**:\n" + - " - 启用“分支编组”将递归地编组子树,从叶节点到顶层分支。\n" + - "- **复制/粘贴**:导出/导入含缩进的 Markdown 列表。\n" + - "\n" + - "😍 如果你觉得这个脚本有用,欢迎 [请我喝杯咖啡 ☕](https://ko-fi.com/zsolt)。", -}); - -addLocale("zh-tw", { - // Notices - NOTICE_SELECT_NODE_TO_COPY: "請選擇要複製的節點。", - NOTICE_MAP_CUT: "導圖已剪下到剪貼簿。", - NOTICE_BRANCH_CUT: "分支已剪下到剪貼簿。", - NOTICE_MAP_COPIED: "導圖已複製為 Markdown 格式。", - NOTICE_BRANCH_COPIED: "分支已複製為列表格式。", - NOTICE_CLIPBOARD_EMPTY: "剪貼簿為空。", - NOTICE_PASTE_ABORTED: "貼上中止。剪貼簿內容非 Markdown 列表或標題。", - NOTICE_NO_LIST: "剪貼簿中未發現有效的 Markdown 列表。", - NOTICE_PASTE_START: "正在貼上,請稍候,可能需要一些時間…", - NOTICE_PASTE_COMPLETE: "貼上完成。", - NOTICE_ACTION_REQUIRES_ARROWS: "此操作需要方向鍵。僅可修改修飾鍵。", - NOTICE_CONFLICT_WITH_ACTION: "與“{action}”操作衝突", - NOTICE_OBSIDIAN_HOTKEY_CONFLICT: "⚠️ Obsidian 熱鍵衝突!\n\n此按鍵將覆蓋:\n“{command}”", - NOTICE_GLOBAL_HOTKEY_CONFLICT: "⚠️ 全域性熱鍵衝突!\n\n此按鍵將覆蓋:\n“{command}”", - NOTICE_NO_HEADINGS: "連結檔案中未發現小標題。", - NOTICE_CANNOT_EDIT_MULTILINE: "無法直接編輯多行節點。\n請在 Excalidraw 中雙擊元素進行編輯,然後執行“自動重排導圖”來更新佈局。", - NOTICE_CANNOT_MOVE_PINNED: "無法移動已鎖定的節點。請先解鎖。", - NOTICE_CANNOT_MOVE_ROOT: "無法移動根節點。", - NOTICE_CANNOT_PRMOTE_L1: "無法提升 1 級節點。", - NOTICE_CANNOT_DEMOTE: "無法降級節點。沒有可依附的前置同級節點。", - NOTICE_SELECT_NODE_CONTAINING_LINK: "請選擇包含連結的節點。", - NOTICE_CANNOT_DEMOTE_NO_SIBLING_TO_ACCEPT: "無法降級:未找到可接收此節點的同級節點。", - NOTICE_CANNOT_DEMOTE_NO_VALID_SIBLING: "無法降級:沒有可附加的有效同級節點。", - NOTICE_CANNOT_DEMOTE_CROSS_SIDE_NOT_ALLOWED: "無法降級:不允許跨側降級。", - NOTICE_CANNOT_MOVE_AUTO_LAYOUT_DISABLED: "停用自動佈局時無法移動節點。請先啟用自動佈局。", - NOTICE_BRANCH_WIDTH_MANUAL_OVERRIDE: "分支粗細未更新,因為部分分支粗細已被手動修改。", - NOTICE_CANNOT_CHANGE_MASTER_ROOT: "主根節點不能被轉換。", - NOTICE_SUBMAP_ROOT_ADDED: "已啟用子圖根節點。", - NOTICE_SUBMAP_ROOT_REMOVED: "已移除子圖根節點。其子節點將按親代根節點佈局重排。", - CONFIRM_REMOVE_SUBMAP_ROOT: "恢復為普通節點嗎?\n\n它將失去本地佈局元資料,其子節點將按親代根節點佈局重排。", - - // Action labels (display only) - ACTION_LABEL_ADD: "新增子節點", - ACTION_LABEL_ADD_SIBLING_AFTER: "新增後置同級節點", - ACTION_LABEL_ADD_SIBLING_BEFORE: "新增前置同級節點", - ACTION_LABEL_ADD_FOLLOW: "新增 + 跟隨", - ACTION_LABEL_ADD_FOLLOW_FOCUS: "新增 + 跟隨 + 聚焦", - ACTION_LABEL_ADD_FOLLOW_ZOOM: "新增 + 跟隨 + 縮放", - ACTION_LABEL_SORT_ORDER: "更改順序/提升節點", - ACTION_LABEL_EDIT: "編輯節點", - ACTION_LABEL_PIN: "鎖定/解鎖", - ACTION_LABEL_BOX: "新增/移除邊框", - ACTION_LABEL_TOGGLE_GROUP: "編組/解除編組單分支", - ACTION_LABEL_COPY: "複製", - ACTION_LABEL_CUT: "剪下", - ACTION_LABEL_PASTE: "貼上", - ACTION_LABEL_IMPORT_OUTLINE: "匯入大綱", - ACTION_LABEL_ZOOM: "迴圈縮放", - ACTION_LABEL_FOCUS: "聚焦(並居中)節點", - ACTION_LABEL_NAVIGATE: "導航", - ACTION_LABEL_NAVIGATE_ZOOM: "導航 & 縮放", - ACTION_LABEL_NAVIGATE_FOCUS: "導航 & 聚焦", - ACTION_LABEL_FOLD: "摺疊/展開分支", - ACTION_LABEL_FOLD_L1: "摺疊/展開 L1 子節點", - ACTION_LABEL_FOLD_ALL: "遞迴摺疊/展開分支", - ACTION_LABEL_DOCK_UNDOCK: "停靠/取消停靠", - ACTION_LABEL_HIDE: "停靠 & 隱藏", - ACTION_LABEL_REARRANGE: "重排導圖", - ACTION_LABEL_TOGGLE_SUBMAP_ROOT: "開始/結束子圖根節點", - ACTION_LABEL_TOGGLE_CHECKBOX: "切換複選框狀態", - ACTION_LABEL_CALENDAR: "任務日曆與優先級", - ACTION_LABEL_TOGGLE_EMBED: "切換嵌入/連結", - - // Tooltips (shared) - PIN_TOOLTIP_PINNED: "此元素已鎖定。點選解鎖所選元素的位置。", - PIN_TOOLTIP_UNPINNED: "此元素未鎖定。點選鎖定所選元素的位置。", - TOGGLE_GROUP_TOOLTIP_GROUP: "編組此分支。僅在“分支編組”停用時可用。", - TOGGLE_GROUP_TOOLTIP_UNGROUP: "解除編組此分支。僅在“分支編組”停用時可用。", - TOOLTIP_EDIT_NODE: "編輯所選節點的文字", - TOOLTIP_PIN_INIT: "鎖定/解鎖節點位置。鎖定的節點不會被自動重排。", - TOOLTIP_REFRESH: "自動重排導圖", - TOOLTIP_DOCK: "停靠到側邊面板", - TOOLTIP_UNDOCK: "轉為浮動視窗", - TOOLTIP_ZOOM_CYCLE: "迴圈切換元素縮放級別", - TOOLTIP_TOGGLE_GROUP_BTN: "切換分支的編組狀態。僅在“分支編組”停用時可用。", - TOOLTIP_TOGGLE_BOX: "切換節點邊框", - TOOLTIP_TOGGLE_BOUNDARY: "切換子樹邊界", - TOOLTIP_TOGGLE_FLOATING_EXTRAS: "切換額外控制元件", - TOOLTIP_CONFIGURE_PALETTE: "為分支配置自定義調色盤", - TOOLTIP_CONFIGURE_LAYOUT: "配置佈局設定", - TOOLTIP_MOVE_UP: "上移", - TOOLTIP_MOVE_DOWN: "下移", - TOOLTIP_EDIT_COLOR: "編輯", - TOOLTIP_DELETE_COLOR: "刪除", - TOOLTIP_OPEN_PALETTE_PICKER: "開啟顏色選擇器", - TOOLTIP_FOLD_BRANCH: "摺疊/展開所選分支", - TOOLTIP_FOLD_L1_BRANCH: "摺疊/展開 L1 子節點", - TOOLTIP_FOLD_ALL: "遞迴摺疊/展開分支", - TOOLTIP_IMPORT_OUTLINE: "從連結檔案中匯入小標題作為子節點資料", - TOOLTIP_RESET_TO_DEFAULT: "恢復預設", - TOOLTIP_SUBMAP_ROOT_ADD: "從所選節點開始子圖", - TOOLTIP_SUBMAP_ROOT_REMOVE: "將子圖根節點恢復為普通節點", - TOOLTIP_TOGGLE_CHECKBOX: "切換任務複選框狀態", - TOOLTIP_CALENDAR: "配置任務日期與優先級", - TOOLTIP_TOGGLE_EMBED: "在嵌入和連結之間切換節點", - - // Buttons and labels - DOCK_TITLE: "MindMap Builder", - HELP_SUMMARY: "幫助", - INPUT_PLACEHOLDER: "輸入概念… 輸入 [[ 插入連結", - ONTOLOGY_PLACEHOLDER: "本體(箭頭標籤)", - BUTTON_COPY: "複製", - BUTTON_CUT: "剪下", - BUTTON_PASTE: "貼上", - TITLE_ADD_SIBLING: `使用 ${ea.DEVICE.isMacOS || ea.DEVICE.isIOS ? "OPT" : "ALT"}+Enter 新增同級節點`, - TITLE_ADD_FOLLOW: "新增並跟隨", - TITLE_COPY: "複製分支為文字", - TITLE_CUT: "剪下分支為文字", - TITLE_PASTE: "從剪貼簿貼上列表", - LABEL_ZOOM_LEVEL: "縮放級別", - LABEL_GROWTH_STRATEGY: "生長策略", - LABEL_FILL_SWEEP: "填充掃過角度", - DESC_FILL_SWEEP: "立即在整個“最大掃過角度”範圍內分佈節點,而不是隨著節點數量增加逐漸擴大弧度。", - LABEL_ARROW_TYPE: "曲線連線", - LABEL_AUTO_LAYOUT: "自動佈局", - LABEL_GROUP_BRANCHES: "分支編組", - LABEL_BOX_CHILD_NODES: "為子節點新增邊框", - LABEL_ROUNDED_CORNERS: "圓角", - LABEL_USE_SCENE_STROKE: "使用場景線條樣式", - DESC_USE_SCENE_STROKE: "使用場景中最新的線條樣式(實線、虛線、點線),否則分支將始終使用實線。", - LABEL_BRANCH_SCALE: "分支粗細比例", - LABEL_BASE_WIDTH: "基礎粗細", - LABEL_MULTICOLOR_BRANCHES: "多色分支", - LABEL_MAX_WRAP_WIDTH: "最大折行寬度", - LABEL_CENTER_TEXT: "文字居中", - DESC_CENTER_TEXT: "關閉:根據位置左/右對齊;開啟:文字強制居中。", - LABEL_FONT_SIZES: "字型大小", - HOTKEY_SECTION_TITLE: "熱鍵配置", - HOTKEY_HINT: "這些熱鍵可能覆蓋 Obsidian 預設設定。熱鍵作用域預設為區域性(⌨️),使用 🌐/🎨/⌨️ 切換作用域:🌐 Excalidraw 標籤頁可見即生效,🎨 Excalidraw 聚焦時生效,⌨️ 輸入框聚焦時生效。", - RECORD_HOTKEY_PROMPT: "按下熱鍵…", - ARIA_SCOPE_INPUT: "區域性(Local):僅在輸入框聚焦時生效", - ARIA_SCOPE_EXCALIDRAW: "Excalidraw:輸入框或 Excalidraw 聚焦時生效", - ARIA_SCOPE_GLOBAL: "全域性(Global):在 Obsidian 任何位置,Excalidraw 可見即生效", - ARIA_RESTORE_DEFAULT: "恢復預設", - ARIA_CUSTOMIZE_HOTKEY: "自定義此熱鍵", - ARIA_OVERRIDE_COMMAND: "將覆蓋 Obsidian 命令:\n{command}", - - // Palette manager - MODAL_PALETTE_TITLE: "導圖分支調色盤", - LABEL_ENABLE_CUSTOM_PALETTE: "啟用自定義調色盤", - DESC_ENABLE_CUSTOM_PALETTE: "使用以下顏色代替自動生成的顏色。", - LABEL_RANDOMIZE_ORDER: "隨機順序", - DESC_RANDOMIZE_ORDER: "隨機選擇顏色而非按順序選擇。", - HEADING_ADD_NEW_COLOR: "新增新顏色", - HEADING_EDIT_COLOR: "編輯顏色", - LABEL_SELECT_COLOR: "選擇顏色", - BUTTON_CANCEL_EDIT: "取消編輯", - BUTTON_ADD_COLOR: "新增顏色", - BUTTON_UPDATE_COLOR: "更新顏色", - - // Layout configuration - MODAL_LAYOUT_TITLE: "佈局配置", - // Section Headers - SECTION_GENERAL: "常規間距", - SECTION_RADIAL: "徑向佈局(順時針)", - SECTION_DIRECTIONAL: "定向佈局(左/右)", - SECTION_VERTICAL: "垂直導圖(上/下)", - SECTION_VISUALS: "視覺元素", - SECTION_MANUAL: "手動模式行為", - LAYOUT_RESET: "重置所有為預設值", - LAYOUT_SAVE: "儲存並關閉", - // Radial Strings - RADIAL_ASPECT_RATIO: "橢圓長寬比", - DESC_RADIAL_ASPECT_RATIO: "控制形狀。< 1.0 為瘦長(0.7 為縱向),1.0 為正圓,> 1.0 為寬扁(橫向)。", - RADIAL_POLE_GAP_BONUS: "極點間距補償", - DESC_RADIAL_POLE_GAP_BONUS: "增加橢圓南北兩極區域內節點的間距。值越大,節點沿弧線推得越遠。", - RADIAL_START_ANGLE: "起始角度", - DESC_RADIAL_START_ANGLE: "第一個節點出現的位置(度數)。270 為北,0 為東,90 為南。", - RADIAL_MAX_SWEEP: "最大掃過角度", - DESC_RADIAL_MAX_SWEEP: "分支可填充的弧範圍。360 為全圓。較小的值會使圓不完整。", - // Others - GAP_X: "水平間距(Gap X)", - DESC_LAYOUT_GAP_X: "親代節點與子節點之間的水平距離。", - GAP_Y: "垂直間距(Gap Y)", - DESC_LAYOUT_GAP_Y: "同級節點之間的垂直距離。徑向佈局中的基礎間距。", - GAP_MULTIPLIER: "間距倍數", - DESC_LAYOUT_GAP_MULTIPLIER: "葉節點(無子節點的節點)相對於字型大小的垂直間距。低:類似列表堆疊;高:標準樹狀間距。", - DIRECTIONAL_ARC_SPAN_RADIANS: "定向張開弧度(Arc-span Radians)", - DESC_LAYOUT_ARC_SPAN: "子節點排列的曲率。低(0.5):較平,類似列表。高(2.0):彎曲有機,但有重疊風險。", - ROOT_RADIUS_FACTOR: "根節點半徑係數", - DESC_LAYOUT_ROOT_RADIUS: "相對於根節點邊框的倍數,決定最初的半徑。", - MIN_RADIUS: "最小半徑", - DESC_LAYOUT_MIN_RADIUS: "從根節點中心到第一級節點的最小絕對距離。", - RADIUS_PADDING_PER_NODE: "單節點徑向空白邊距", - DESC_LAYOUT_RADIUS_PADDING: "每個子節點額外增加的半徑,以適應密集型導圖。", - GAP_MULTIPLIER_RADIAL: "徑向佈局間距倍數", - DESC_LAYOUT_GAP_RADIAL: "徑向佈局模式下的角度間距倍數。", - GAP_MULTIPLIER_DIRECTIONAL: "垂直方向間距倍數", - DESC_LAYOUT_GAP_DIRECTIONAL: "定向佈局頂層分支之間的間距倍數。", - INDICATOR_OFFSET: "摺疊指示符偏移", - DESC_LAYOUT_INDICATOR_OFFSET: "摺疊指示符(三連點)距離節點的距離。", - INDICATOR_OPACITY: "摺疊指示符不透明度", - DESC_LAYOUT_INDICATOR_OPACITY: "摺疊指示符的不透明度(0-100)。", - CONTAINER_PADDING: "容器內邊距", - DESC_LAYOUT_CONTAINER_PADDING: "使用邊框樣式時的內邊距。", - MAX_SEGMENT_LENGTH: "邊界線精度", - DESC_LAYOUT_BOUNDARY_LINE_PRECISION: "邊界平滑精度。值越小越精細(30 = 精細),值越大越粗略(200 = 粗略)。", - VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "子樹寬度參與度(單側)", - DESC_VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "垂直導圖中,單側生長的子圖佔用(左/右)水平空間的強度。影響程度高。", - VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "子樹寬度參與度(雙側)", - DESC_VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "垂直導圖中,雙側生長的子圖佔用(左右)水平空間的強度。影響程度高。", - VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "子樹平滑壓縮觸發倍數", - DESC_VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "超過 Gap Y 乘以該倍數後開始平滑壓縮,避免新增子節點間距突變。通常在大導圖中更明顯。", - VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "子樹平滑壓縮下限", - DESC_VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "垂直子樹寬度平滑壓縮到的最小值。值越大越保留原寬度。通常在大導圖中更明顯。", - HORIZONTAL_L1_SOFTCAP_THRESHOLD: "L1 水平方向軟上限", - DESC_HORIZONTAL_L1_SOFTCAP_THRESHOLD: "超過該 px 值後,上/下 L1 子樹寬度開始壓縮。對大導圖影響程度中到高。", - HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "L1 水平方向壓縮下限", - DESC_HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "上/下 L1 寬度壓縮到的最小值。值越大越保留原寬度。軟上限被達到(、開始壓縮)後影響中等。", - VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "緊湊親子間距比例", - DESC_VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "緊湊垂直子樹中,親子間距使用 Gap X 乘以該比例。極大影響視覺效果。", - DIRECTIONAL_CROSS_AXIS_RATIO: "正交軸之比", - DESC_DIRECTIONAL_CROSS_AXIS_RATIO: "與垂直於生長方向的軸(Cross-axis)的半徑之比(0.2 = 扁,1.0 = 圓)。極大影響 L1 展開形態。", - MANUAL_GAP_MULTIPLIER: "手動佈局間距倍數", - DESC_LAYOUT_MANUAL_GAP: "停用自動佈局時新增節點的間距倍數。", - MANUAL_JITTER_RANGE: "手動佈局抖動範圍", - DESC_LAYOUT_MANUAL_JITTER: "停用自動佈局時新增節點的隨機位置偏移。", - - CALENDAR_DATE_INDEX: "第 {index} 個日期,共 {total} 個", - CALENDAR_DATE_LABEL: "日期", - CALENDAR_DATE_TYPE: "日期類型", - CALENDAR_PRIORITY: "優先級", - CALENDAR_RECURRENCE: "重複", - CALENDAR_RECURRENCE_PLACEHOLDER: "every day", - CALENDAR_RECURRENCE_DESC: "例如,'every day','every 2 weeks'
Tasks 外掛重複任務文件", - CALENDAR_INJECT_LINK: "插入節點連結", - CALENDAR_INJECT_LINK_DESC: "在任務末尾新增指向該節點的連結。", - CALENDAR_ALIAS_PLACEHOLDER: "別名", - CALENDAR_BTN_CANCEL: "取消", - CALENDAR_BTN_TASK_ONLY: "僅任務", - CALENDAR_BTN_ADD_DATE_TASK: "新增日期和任務", - - CALENDAR_PRIORITY_HIGHEST: "最高", - CALENDAR_PRIORITY_HIGH: "高", - CALENDAR_PRIORITY_MEDIUM: "中", - CALENDAR_PRIORITY_NORMAL: "普通", - CALENDAR_PRIORITY_LOW: "低", - CALENDAR_PRIORITY_LOWEST: "最低", - - CALENDAR_DATETYPE_DUE: "截止", - CALENDAR_DATETYPE_START: "開始", - CALENDAR_DATETYPE_SCHEDULED: "計畫", - CALENDAR_DATETYPE_CREATED: "建立", - CALENDAR_DATETYPE_DONE: "完成", - CALENDAR_DATETYPE_CANCELLED: "取消", - - // Presets - PRESET_LABEL: "預設", - PRESET_UNSAVED: "自定義 / 未關聯", - PRESET_BTN_SAVE: "儲存預設", - PRESET_BTN_DELETE: "刪除預設", - PRESET_BTN_NEW: "新建預設", - PRESET_BTN_APPLY: "應用預設到導圖", - PRESET_WARNING_MODIFIED: "導圖設定與預設不符。", - PROMPT_NEW_PRESET_NAME: "新預設名稱:", - NOTICE_PRESET_DELETED: "預設已刪除。", - NOTICE_PRESET_SAVED: "預設已儲存。", - NOTICE_PRESET_APPLIED: "預設已應用。", - - // Misc - INPUT_TITLE_PASTE_ROOT: "MindMap Builder 貼上", - INSTRUCTIONS: "> [!Tip]\n" + - ">🚀 想要進階?歡迎參加官方 [MindMap Builder 課程](https://www.visual-thinking-workshop.com/mindmap)!\n" + - "\n" + - "- **ENTER**:新增子節點並保留在當前親代節點上,方便快速輸入。" + - "若輸入框為空時按回車,焦點將移動到最新新增的子節點。" + - "連續按回車將在該節點的同級節點間迴圈切換。\n" + - "- **熱鍵**:見側邊面板底部的配置選項。\n" + - "- **停靠/取消停靠**:使用按鈕或配置好的熱鍵來切換輸入框位置。\n" + - "- **摺疊**:僅在輸入框停靠時顯示按鈕;取消停靠時請使用熱鍵。\n" + - "- **ESC**:將浮動輸入框停靠,但不啟用側邊面板。\n" + - "- **著色**:頂層分支擁有獨立顏色(多色模式),後代節點繼承親代顏色。\n" + - "- **編組**:\n" + - " - 啟用“分支編組”將遞迴地編組子樹,從葉節點到頂層分支。\n" + - "- **複製/貼上**:匯出/匯入含縮排的 Markdown 列表。\n" + - "\n" + - "😍 如果你覺得這個指令碼有用,歡迎 [請我喝杯咖啡 ☕](https://ko-fi.com/zsolt)。", -}); - -const t = (key, params = {}) => { - const str = STRINGS[LOCALE]?.[key] ?? STRINGS.en[key] ?? key; - return Object.keys(params).reduce((acc, pKey) => acc.replace(new RegExp(`{${pKey}}`, "g"), params[pKey]), str); -}; - -// --------------------------------------------------------------------------- -// Settings -// --------------------------------------------------------------------------- -const VALUE_SETS = Object.freeze({ - SCOPE: Object.freeze({ - input: 3, - excalidraw: 2, - global: 1, - none: 0, - }), - FONT_SCALE: Object.freeze(["Use scene fontsize", "Fibonacci Scale", "Normal Scale"]), - GROWTH: Object.freeze(["Radial", "Right-facing", "Left-facing", "Right-Left", "Up-facing", "Down-facing", "Up-Down"]), - ZOOM: Object.freeze(["Low", "Medium", "High"]), - ARROW: Object.freeze(["curved", "straight"]), - BRANCH_SCALE: Object.freeze(["Hierarchical", "Uniform"]), -}); - -const FONT_SCALE_TYPES = VALUE_SETS.FONT_SCALE; -const GROWTH_TYPES = VALUE_SETS.GROWTH; -const ZOOM_TYPES = VALUE_SETS.ZOOM; -const SCOPE = VALUE_SETS.SCOPE; -const ARROW_TYPES = VALUE_SETS.ARROW; -const BRANCH_SCALE_TYPES = VALUE_SETS.BRANCH_SCALE; -const ZOOM_LEVELS = Object.freeze({ - Low: { desktop: 0.10, mobile: 0.20 }, - Medium: { desktop: 0.25, mobile: 0.35 }, - High: { desktop: 0.50, mobile: 0.60 }, -}); - -const getZoom = (level) => { - const target = ZOOM_LEVELS[level ?? zoomLevel] || ZOOM_LEVELS.Medium; - return ea.DEVICE.isMobile ? target.mobile : target.desktop; -}; - -const fontScale = (type) => { - switch (type) { - case "Use scene fontsize": - return Array(5).fill(getAppState().currentItemFontSize); - case "Fibonacci Scale": - return [68, 42, 26, 16, 10]; - default: // "Normal Scale" - return [36, 28, 20, 16, 12]; - } -}; - -const getFontScale = (type) => fontScale(type) ?? fontScale("Normal Scale"); - -let dirty = false; -const getVal = (key, def) => ea.getScriptSettingValue(key, typeof def === "object" ? def: { value: def }).value; -const saveSettings = async () => { - if (dirty) await ea.saveScriptSettings(); - dirty = false; -} -const setVal = (key, value, hidden = false) => { - const def = ea.getScriptSettingValue(key, {value, hidden}); - const isChanging = def.value !== value || def.hidden !== hidden; - def.value = value; - if (hidden) def.hidden = true; - ea.setScriptSettingValue(key, def); - if (isChanging) { - dirty = true; - } -} - -const K_WIDTH = "Max Text Width"; -const K_FONTSIZE = "Font Sizes"; -const K_BOX = "Box Children"; -const K_ROUND = "Rounded Corners"; -const K_BRANCH_SCALE = "Branch Scale Style"; -const K_BASE_WIDTH = "Base Stroke Width"; -const K_GROWTH = "Growth Mode"; -const K_MULTICOLOR = "Multicolor Mode"; -const K_UNDOCKED = "Is Undocked"; -const K_GROUP = "Group Branches"; -const K_ARROWSTROKE = "Arrow Stroke Style"; -const K_CENTERTEXT = "Center text in nodes?"; -const K_ZOOM = "Preferred Zoom Level"; -const K_HOTKEYS = "Hotkeys"; -const K_PALETTE = "Custom Palette"; -const K_LAYOUT = "Layout Config"; -const K_ARROW_TYPE = "Arrow Type"; -const K_FILL_SWEEP = "Fill Sweep"; -const K_INJECT_LINK = "Inject Node Link"; -const K_LINK_ALIAS = "Node Link Alias"; -const K_PRESETS = "Map Presets"; -const K_ACTIVE_PRESET = "Active Preset"; - -let injectNodeLink = getVal(K_INJECT_LINK, true); -let nodeLinkAlias = getVal(K_LINK_ALIAS, "(…)"); - -const isExcaliBrainView = () => { - if (!ea.targetView || !ea.targetView.file) return false; - const eb = app.plugins.plugins["excalibrain"]; - return eb && eb.settings?.excalibrainFilepath === ea.targetView.file.path; -}; - -// --------------------------------------------------------------------------- -// Layout & Geometry Settings -// --------------------------------------------------------------------------- -const LAYOUT_METADATA = { - // --- General --- - GAP_X: { - section: "SECTION_GENERAL", - def: 120, - min: 10, - max: 400, - step: 10, - desc: t("DESC_LAYOUT_GAP_X"), - name: t("GAP_X"), - }, - GAP_Y: { - section: "SECTION_GENERAL", - def: 25, - min: 5, - max: 150, - step: 5, - desc: t("DESC_LAYOUT_GAP_Y"), - name: t("GAP_Y"), - }, - GAP_MULTIPLIER: { - section: "SECTION_GENERAL", - def: 0.6, - min: 0.1, - max: 3.0, - step: 0.1, - desc: t("DESC_LAYOUT_GAP_MULTIPLIER"), - name: t("GAP_MULTIPLIER"), - }, - - // --- Radial (New & Updated) --- - ROOT_RADIUS_FACTOR: { - section: "SECTION_GENERAL", - def: 0.8, - min: 0.5, - max: 2.0, - step: 0.1, - desc: t("DESC_LAYOUT_ROOT_RADIUS"), - name: t("ROOT_RADIUS_FACTOR"), - }, - MIN_RADIUS: { - section: "SECTION_GENERAL", - def: 350, - min: 30, - max: 800, - step: 10, - desc: t("DESC_LAYOUT_MIN_RADIUS"), - name: t("MIN_RADIUS"), - }, - RADIAL_ASPECT_RATIO: { - section: "SECTION_RADIAL", - def: 0.7, - min: 0.5, - max: 2.0, - step: 0.1, - desc: t("DESC_RADIAL_ASPECT_RATIO"), - name: t("RADIAL_ASPECT_RATIO"), - }, - RADIAL_POLE_GAP_BONUS: { - section: "SECTION_RADIAL", - def: 2.0, - min: 0.0, - max: 5.0, - step: 0.1, - desc: t("DESC_RADIAL_POLE_GAP_BONUS"), - name: t("RADIAL_POLE_GAP_BONUS"), - }, - RADIAL_START_ANGLE: { - section: "SECTION_RADIAL", - def: 280, - min: 0, - max: 360, - step: 10, - desc: t("DESC_RADIAL_START_ANGLE"), - name: t("RADIAL_START_ANGLE"), - }, - RADIAL_MAX_SWEEP: { - section: "SECTION_RADIAL", - def: 340, - min: 90, - max: 360, - step: 10, - desc: t("DESC_RADIAL_MAX_SWEEP"), - name: t("RADIAL_MAX_SWEEP"), - }, - - // --- Directional --- - DIRECTIONAL_ARC_SPAN_RADIANS: { - section: "SECTION_DIRECTIONAL", - def: 1.0, - min: 0.1, - max: 3.14, - step: 0.1, - desc: t("DESC_LAYOUT_ARC_SPAN"), - name: t("DIRECTIONAL_ARC_SPAN_RADIANS"), - }, - GAP_MULTIPLIER_DIRECTIONAL: { - section: "SECTION_DIRECTIONAL", - def: 1.5, - min: 1.0, - max: 3.0, - step: 0.1, - desc: t("DESC_LAYOUT_GAP_DIRECTIONAL"), - name: t("GAP_MULTIPLIER_DIRECTIONAL"), - }, - RADIUS_PADDING_PER_NODE: { - section: "SECTION_DIRECTIONAL", - def: 7, - min: 0, - max: 20, - step: 1, - desc: t("DESC_LAYOUT_RADIUS_PADDING"), - name: t("RADIUS_PADDING_PER_NODE"), - }, - - // --- Vertical Maps (Up/Down) --- - VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: { - section: "SECTION_VERTICAL", - def: 0.35, - min: 0.05, - max: 1.2, - step: 0.05, - desc: t("DESC_VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE"), - name: t("VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE"), - }, - VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: { - section: "SECTION_VERTICAL", - def: 0.6, - min: 0.1, - max: 1.4, - step: 0.05, - desc: t("DESC_VERTICAL_SUBTREE_WIDTH_BLEND_DUAL"), - name: t("VERTICAL_SUBTREE_WIDTH_BLEND_DUAL"), - }, - VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: { - section: "SECTION_VERTICAL", - def: 6.0, - min: 0.5, - max: 20.0, - step: 0.5, - desc: t("DESC_VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER"), - name: t("VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER"), - }, - VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: { - section: "SECTION_VERTICAL", - def: 240, - min: 10, - max: 1600, - step: 10, - desc: t("DESC_VERTICAL_SUBTREE_SMOOTH_MIN_SCALE"), - name: t("VERTICAL_SUBTREE_SMOOTH_MIN_SCALE"), - }, - HORIZONTAL_L1_SOFTCAP_THRESHOLD: { - section: "SECTION_VERTICAL", - def: 560, - min: 20, - max: 3000, - step: 20, - desc: t("DESC_HORIZONTAL_L1_SOFTCAP_THRESHOLD"), - name: t("HORIZONTAL_L1_SOFTCAP_THRESHOLD"), - }, - HORIZONTAL_L1_COMPRESSION_MIN_SCALE: { - section: "SECTION_VERTICAL", - def: 240, - min: 10, - max: 1600, - step: 10, - desc: t("DESC_HORIZONTAL_L1_COMPRESSION_MIN_SCALE"), - name: t("HORIZONTAL_L1_COMPRESSION_MIN_SCALE"), - }, - VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: { - section: "SECTION_VERTICAL", - def: 0.55, - min: 0.05, - max: 1.3, - step: 0.05, - desc: t("DESC_VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO"), - name: t("VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO"), - }, - DIRECTIONAL_CROSS_AXIS_RATIO: { - section: "SECTION_VERTICAL", - def: 0.2, - min: 0.05, - max: 1.2, - step: 0.05, - desc: t("DESC_DIRECTIONAL_CROSS_AXIS_RATIO"), - name: t("DIRECTIONAL_CROSS_AXIS_RATIO"), - }, - - // --- Visuals --- - INDICATOR_OFFSET: { - section: "SECTION_VISUALS", - def: 10, - min: 5, - max: 50, - step: 5, - desc: t("DESC_LAYOUT_INDICATOR_OFFSET"), - name: t("INDICATOR_OFFSET"), - }, - INDICATOR_OPACITY: { - section: "SECTION_VISUALS", - def: 40, - min: 10, - max: 100, - step: 10, - desc: t("DESC_LAYOUT_INDICATOR_OPACITY"), - name: t("INDICATOR_OPACITY"), - }, - CONTAINER_PADDING: { - section: "SECTION_VISUALS", - def: 10, - min: 0, - max: 50, - step: 2, - desc: t("DESC_LAYOUT_CONTAINER_PADDING"), - name: t("CONTAINER_PADDING"), - }, - MAX_SEGMENT_LENGTH: { - section: "SECTION_VISUALS", - def: 80, - min: 30, - max: 200, - step: 10, - desc: t("DESC_LAYOUT_BOUNDARY_LINE_PRECISION"), - name: t("MAX_SEGMENT_LENGTH"), - }, - - // --- Manual Mode --- - MANUAL_GAP_MULTIPLIER: { - section: "SECTION_MANUAL", - def: 1.3, - min: 1.0, - max: 2.0, - step: 0.1, - desc: t("DESC_LAYOUT_MANUAL_GAP"), - name: t("MANUAL_GAP_MULTIPLIER"), - }, - MANUAL_JITTER_RANGE: { - section: "SECTION_MANUAL", - def: 300, - min: 0, - max: 400, - step: 10, - desc: t("DESC_LAYOUT_MANUAL_JITTER"), - name: t("MANUAL_JITTER_RANGE"), - } -}; - -let layoutSettings = getVal(K_LAYOUT, { - value: {}, - hidden: true -}); -let layoutSettingsDirty = false; - -Object.keys(LAYOUT_METADATA).forEach(k => { - const val = layoutSettings[k]; - const def = LAYOUT_METADATA[k].def; - if (val === undefined || val === null || typeof val !== "number" || !Number.isFinite(val)) { - layoutSettings[k] = def; - layoutSettingsDirty = true; - } -}); - -if (layoutSettingsDirty) { - setVal(K_LAYOUT, layoutSettings, true); -} - -// --------------------------------------------------------------------------- -// Constants -// --------------------------------------------------------------------------- -const COLOR_CONTRAST_MIN = 2.5; -const COLOR_DISTINCT_THRESHOLD = 40; -const HUE_STEP_BASE = 15; -const HUE_STEP_JITTER = 4; -const SAT_BASE = 75; -const SAT_JITTER = 10; -const LIGHT_BASE_DARK = 65; -const LIGHT_JITTER_DARK = 10; -const LIGHT_BASE_LIGHT = 36; -const LIGHT_JITTER_LIGHT = 8; - -// --------------------------------------------------------------------------- -// UI & Interaction Constants -// --------------------------------------------------------------------------- -const WRAP_WIDTH_MIN = 100; -const WRAP_WIDTH_MAX = 600; -const WRAP_WIDTH_STEP = 10; -const FLOAT_MODAL_OPACITY = 0.8; -const FLOAT_MODAL_OFFSET = 5; -const FLOAT_MODAL_MAX_HEIGHT = "calc(2 * var(--size-4-4) + 12px + var(--input-height))"; -const NOTICE_DURATION_CONFLICT = 6000; -const NOTICE_DURATION_GLOBAL_CONFLICT = 10000; - -let arrowType = getVal(K_ARROW_TYPE, { - value: "curved", - valueset: ARROW_TYPES -}); -let maxWidth = parseInt(getVal(K_WIDTH, 450)); -if (isNaN(maxWidth)) maxWidth = 450; -let fontsizeScale = getVal(K_FONTSIZE, { - value: "Normal Scale", - valueset: FONT_SCALE_TYPES -}); -let boxChildren = getVal(K_BOX, false); -let roundedCorners = getVal(K_ROUND, false); -let multicolor = getVal(K_MULTICOLOR, true); -let groupBranches = getVal(K_GROUP, false); -let currentModalGrowthMode = getVal(K_GROWTH, { - value: "Right-Left", - valueset: GROWTH_TYPES -}); -let isUndocked = getVal(K_UNDOCKED, false); -let isSolidArrow = getVal(K_ARROWSTROKE, true); -let centerText = getVal(K_CENTERTEXT, true); -let autoLayoutDisabled = false; -let zoomLevel = getVal(K_ZOOM, { - value: "Medium", - valueset: ZOOM_TYPES -}); -let customPalette = getVal(K_PALETTE, { - value: { - enabled: false, - random: false, - colors: [] - }, - hidden: true -}); -let fillSweep = getVal(K_FILL_SWEEP, false); -let editingNodeId = null; -let mostRecentlySelectedNodeID = null; - -// Undo/Redo tracking -let currentTransactionAccumulator = 0; -let lastCommittedTransaction = null; // { steps: number, version: number } -let redoAvailable = null; // { steps: number, version: number } - state after a batched undo - -// ----------------------------------------------------------- -// Cleanup an migration of old settings values -// ----------------------------------------------------------- -if (!ea.getScriptSettingValue(K_FONTSIZE, { - value: "Normal Scale", - valueset: FONT_SCALE_TYPES - }).hasOwnProperty("valueset")) { - ea.setScriptSettingValue(K_FONTSIZE, { - value: fontsizeScale, - valueset: FONT_SCALE_TYPES - }); - dirty = true; -} - -if (!ea.getScriptSettingValue(K_GROWTH, { - value: "Right-Left", - valueset: GROWTH_TYPES - }).hasOwnProperty("valueset")) { - ea.setScriptSettingValue(K_GROWTH, { - value: currentModalGrowthMode, - valueset: GROWTH_TYPES - }); - dirty = true; -} - -const settingsTemp = ea.getScriptSettings(); -if (settingsTemp && settingsTemp.hasOwnProperty("Is Minimized")) { - delete settingsTemp["Is Minimized"]; - dirty = true; -} - - -let branchScale = getVal(K_BRANCH_SCALE, { - value: "Hierarchical", - valueset: BRANCH_SCALE_TYPES -}); -let baseStrokeWidth = parseFloat(getVal(K_BASE_WIDTH, { - value: 6 -})); -if (isNaN(baseStrokeWidth)) baseStrokeWidth = 6; - - -// --------------------------------------------------------------------------- -// Map Presets State & Helpers -// --------------------------------------------------------------------------- - -const LAYOUT_DEFAULTS = {}; -Object.keys(LAYOUT_METADATA).forEach(k => LAYOUT_DEFAULTS[k] = LAYOUT_METADATA[k].def); - -const extractConfigFromGlobals = () => ({ - growthMode: currentModalGrowthMode, - arrowType, - fontsizeScale, - multicolor, - boxChildren, - roundedCorners, - maxWrapWidth: maxWidth, - isSolidArrow, - centerText, - fillSweep, - branchScale, - baseStrokeWidth, - customPalette: JSON.parse(JSON.stringify(customPalette || { enabled: false, random: false, colors: [] })), - layoutSettings: JSON.parse(JSON.stringify(layoutSettings || {})) -}); - -let mapPresets = getVal(K_PRESETS, { - value: { - "Default": extractConfigFromGlobals() - }, - hidden: true -}); - -// Safeguard against corrupted or undefined settings -if (!mapPresets || typeof mapPresets !== "object") { - mapPresets = {}; -} - -let activePresetName = getVal(K_ACTIVE_PRESET, "Default"); - -// Make sure Default is always available -if (!mapPresets["Default"]) { - mapPresets["Default"] = extractConfigFromGlobals(); - setVal(K_PRESETS, mapPresets, true); -} - -/** - * Normalizes a map configuration object, supplying standard defaults for any missing properties. - * Ensures that legacy presets or maps lacking newer schema keys are safely comparable. - * - * @param {Object} c - The configuration object to normalize. - * @returns {Object} A fully populated configuration object. - */ -const normalizeMapConfig = (c) => { - if (!c) { - return {}; - } - return { - growthMode: c.growthMode ?? "Right-Left", - arrowType: c.arrowType ?? "curved", - fontsizeScale: c.fontsizeScale ?? "Normal Scale", - multicolor: c.multicolor ?? true, - boxChildren: c.boxChildren ?? false, - roundedCorners: c.roundedCorners ?? false, - maxWrapWidth: c.maxWrapWidth ?? 450, - isSolidArrow: c.isSolidArrow ?? true, - centerText: c.centerText ?? true, - fillSweep: c.fillSweep ?? false, - branchScale: c.branchScale ?? "Hierarchical", - baseStrokeWidth: c.baseStrokeWidth ?? 6, - customPalette: c.customPalette ?? { enabled: false, random: false, colors: [] }, - layoutSettings: { ...LAYOUT_DEFAULTS, ...(c.layoutSettings || {}) } - }; -}; - -/** - * Compares two map configuration objects to determine if their visual settings differ. - * Accounts for missing legacy properties and floating point inaccuracies in layout metadata. - * - * @param {Object} c1 - The first configuration object (usually the preset). - * @param {Object} c2 - The second configuration object (usually the map's current state). - * @returns {boolean} True if the configurations differ, false otherwise. - */ -const diffMapConfig = (c1, c2) => { - if (!c1 || !c2) { - return true; - } - - const n1 = normalizeMapConfig(c1); - const n2 = normalizeMapConfig(c2); - - const keys = [ - "growthMode", "arrowType", "fontsizeScale", "multicolor", - "boxChildren", "roundedCorners", "maxWrapWidth", "isSolidArrow", - "centerText", "fillSweep", "branchScale", "baseStrokeWidth" - ]; - - for (let k of keys) { - if (n1[k] !== n2[k]) { - return true; - } - } - - if (JSON.stringify(n1.customPalette) !== JSON.stringify(n2.customPalette)) { - return true; - } - - for (let k of Object.keys(LAYOUT_DEFAULTS)) { - const v1 = n1.layoutSettings[k]; - const v2 = n2.layoutSettings[k]; - if (typeof v1 === "number" && typeof v2 === "number") { - if (Math.abs(v1 - v2) > 0.0001) { - return true; - } - } else if (v1 !== v2) { - return true; - } - } - - return false; -}; - -/** - * Applies the specified preset's configuration to the active global variables. - * - * @param {string} presetName - The name of the preset to apply. - */ -const applyPresetToGlobals = (presetName) => { - const p = mapPresets[presetName]; - if (!p) { - return; - } - - const n = normalizeMapConfig(p); - - currentModalGrowthMode = n.growthMode; - arrowType = n.arrowType; - fontsizeScale = n.fontsizeScale; - multicolor = n.multicolor; - boxChildren = n.boxChildren; - roundedCorners = n.roundedCorners; - maxWidth = n.maxWrapWidth; - isSolidArrow = n.isSolidArrow; - centerText = n.centerText; - fillSweep = n.fillSweep; - branchScale = n.branchScale; - baseStrokeWidth = n.baseStrokeWidth; - customPalette = JSON.parse(JSON.stringify(n.customPalette || { enabled: false, random: false, colors: [] })); - layoutSettings = JSON.parse(JSON.stringify(n.layoutSettings || {})); - - setVal(K_GROWTH, currentModalGrowthMode); - setVal(K_ARROW_TYPE, arrowType); - setVal(K_FONTSIZE, fontsizeScale); - setVal(K_MULTICOLOR, multicolor); - setVal(K_BOX, boxChildren); - setVal(K_ROUND, roundedCorners); - setVal(K_WIDTH, maxWidth); - setVal(K_ARROWSTROKE, isSolidArrow); - setVal(K_CENTERTEXT, centerText); - setVal(K_FILL_SWEEP, fillSweep); - setVal(K_BRANCH_SCALE, branchScale); - setVal(K_BASE_WIDTH, baseStrokeWidth); - setVal(K_PALETTE, customPalette, true); - setVal(K_LAYOUT, layoutSettings, true); -}; - -const applyPresetToMap = async (presetName, sel) => { - applyPresetToGlobals(presetName); - await updateRootNodeCustomData({ - presetName, - growthMode: currentModalGrowthMode, - arrowType, - fontsizeScale, - multicolor, - boxChildren, - roundedCorners, - maxWrapWidth: maxWidth, - isSolidArrow, - centerText, - fillSweep, - branchScale, - baseStrokeWidth, - layoutSettings: JSON.parse(JSON.stringify(layoutSettings)) - }, sel); - - await refreshMapLayout(sel); - updateUI(); -}; - -/** - * Refreshes the dropdown list of available map presets. - * Exclusively populates valid preset names without an ambiguous empty state. - */ -const refreshPresetDropdown = () => { - if (!presetDropdown) { - return; - } - presetDropdown.selectEl.innerHTML = ""; - Object.keys(mapPresets).forEach(k => presetDropdown.addOption(k, k)); - presetDropdown.setValue(activePresetName); -}; - -/** - * Pure calculation logic for stroke width. - */ -const calculateStrokeWidth = (depth, baseWidth, scaleMode) => { - const base = Number.isFinite(baseWidth) ? baseWidth : 6; - const clampedDepth = Math.max(0, Math.min(depth ?? 0, 4)); - - if (scaleMode === "Uniform") return base; - - const min = Math.max(0.1, base * 0.1); - const slope = (min - base) / 4; - const val = slope * clampedDepth + base; - return Math.round(val * 100) / 100; -} - -/** - * Calculates the stroke width for a branch based on depth and style. - * Uses global settings. - */ -const getStrokeWidthForDepth = (depth) => { - return calculateStrokeWidth(depth, baseStrokeWidth, branchScale); -}; - -const ownerWindow = ea.targetView?.ownerWindow; -const isMac = ea.DEVICE.isMacOS || ea.DEVICE.isIOS; -const IMAGE_TYPES = ["jpeg", "jpg", "png", "gif", "svg", "webp", "bmp", "ico", "jtif", "tif", "jfif", "avif"]; -const EMBEDED_OBJECT_WIDTH_ROOT = 400; -const EMBEDED_OBJECT_WIDTH_CHILD = 180; - -//special trim function that returns trimmed text, including trimming a bullet point of the bullet -const trimText = (text) => { - if (!text) return text; - return text.match(/^(?:[ \t]*[-\*][ \t])?(?:[ \t]*)(.*?)[ \t]*$/)[1]; -} - -const parseText = async (text) => { - const trimmed = trimText(text); - if (trimmed && (trimmed.startsWith("![[") || trimmed.match(/^[-*][ \t]+!\[\[/)) && trimmed.endsWith("]]")) { - return text; - } - return await ea.parseText(text); -} - -const parseImageInput = (input) => { - const trimmed = trimText(input); - - // Check for external/local markdown image link: ![](http...) or ![](file...) - const externalMatch = trimmed.match(/^!\[(.*?)\]\(((?:https?|file):\/\/[^)]+)\)$/i); - if (externalMatch) { - const altText = externalMatch[1]; - const url = externalMatch[2]; - - let width = null; - if (altText) { - const parts = altText.split("|"); - const last = parts[parts.length - 1]; - if (/^\d+$/.test(last)) { - width = parseInt(last); - } - } - - try { - const urlObj = new URL(url); - const pathname = urlObj.pathname.toLowerCase(); - // Heuristic: check if the URL points to a standard image file extension - const isImageUrl = IMAGE_TYPES.some(ext => pathname.endsWith("." + ext)); - - if (isImageUrl) { - return { - path: url, - width, - imageFile: null, - isImagePath: true, // This triggers image addition in addNode - file: null, - isExternalImage: true // Flag to help direct link assignments later - }; - } - } catch (e) {} - - // If not matching an image extension, return null so parseEmbeddableInput takes over - return null; - } - - if (!trimmed.startsWith("![[") || !trimmed.endsWith("]]")) return null; - - const content = trimmed.slice(3, -2); - const parts = content.split("|"); - const path = parts[0]; - - let width = null; - if (parts.length > 1) { - const last = parts[parts.length - 1]; - if (/^\d+$/.test(last)) { - width = parseInt(last); - } - } - - let imageFile = null, file = null; - let isImagePath = false; - - const PDF_RECT_LINK_REGEX = /^[^#]*#page=\d*/; //(&\w*=[^&]+){0,}&rect=\d*,\d*,\d*,\d* - if (path.match(PDF_RECT_LINK_REGEX)) { - isImagePath = true; - } else { - const pathParts = path.split("#"); - imageFile = file = app.metadataCache.getFirstLinkpathDest(pathParts[0], ea.targetView.file.path); - if (imageFile) { - const isEx = imageFile.extension === "md" && ea.isExcalidrawFile(imageFile); - if (!IMAGE_TYPES.includes(imageFile.extension.toLowerCase()) && !isEx) { - // Treat standard markdown files with an explicit width as an image path - if (file.extension === "md" && width !== null) { - isImagePath = true; - } - imageFile = null; - } - if (isEx && pathParts.length === 2) { - isImagePath = true; - imageFile = null; - } - } - } - - return { - path, - width, - imageFile, - isImagePath, - file - }; -}; - -const parseEmbeddableInput = (input, imageInfo) => { - const trimmed = input.trim(); - // Ensure we capture potential alt-text formatting so we gracefully match the pattern - const match = trimmed.match(/^!\[(.*?)\]\(((?:https?|file):\/\/[^)]+)\)$/i); - if (match) { - // If parseImageInput already claimed this as an external image, do not override - if (imageInfo && imageInfo.isExternalImage) return null; - return match[2]; - } - const dataURL = trimmed.match(/^!\[\[(data:text\/html;base64.*)]]$/i); - if (dataURL) { - return dataURL[1]; - } - - // If parseImageInput already claimed this as an image path (e.g. markdown with width), don't convert to embeddable - if (imageInfo && imageInfo.isImagePath && imageInfo.width !== null) { - return null; - } - - const pathSplit = imageInfo?.path?.split("#"); - if (imageInfo && imageInfo.file && imageInfo.file.extension === "md" && - // Not an Excalidraw File or maybe an Excalidraw file with a back-of-the-card note reference - (!ea.isExcalidrawFile(imageInfo.file) || pathSplit?.[1] && !pathSplit[1].startsWith("^")) - ) { - imageInfo.isImagePath = false; - return `[[${imageInfo.path}]]`; - } - return null; -}; - -// ------------------------------------------------ -// HOTKEY SUPPORT FUNCTIONS -// ------------------------------------------------ -const ACTION_ADD = "Add"; -const ACTION_ADD_SIBLING_AFTER = "Add Next Sibling"; -const ACTION_ADD_SIBLING_BEFORE = "Add Prev Sibling"; -const ACTION_ADD_FOLLOW = "Add + follow"; -const ACTION_ADD_FOLLOW_FOCUS = "Add + follow + focus"; -const ACTION_ADD_FOLLOW_ZOOM = "Add + follow + zoom"; -const ACTION_SORT_ORDER = "Change Order/Promote Node"; -const ACTION_EDIT = "Edit node"; -const ACTION_TOGGLE_CHECKBOX = "Toggle Checkbox"; -const ACTION_CALENDAR = "Calendar"; -const ACTION_PIN = "Pin/Unpin"; -const ACTION_BOX = "Box/Unbox"; -const ACTION_TOGGLE_GROUP = "Group/Ungroup Single Branch"; - -const ACTION_COPY = "Copy"; -const ACTION_CUT = "Cut"; -const ACTION_PASTE = "Paste"; -const ACTION_IMPORT_OUTLINE = "Import Outline from Linked File"; - -const ACTION_ZOOM = "Cycle Zoom"; -const ACTION_FOCUS = "Focus (center) node"; -const ACTION_NAVIGATE = "Navigate"; -const ACTION_NAVIGATE_ZOOM = "Navigate & zoom"; -const ACTION_NAVIGATE_FOCUS = "Navigate & focus"; -const ACTION_FOLD = "Fold/Unfold Branch"; -const ACTION_FOLD_L1 = "Fold/Unfold to Level 1"; -const ACTION_FOLD_ALL = "Fold/Unfold Branch Recursively"; -const ACTION_TOGGLE_BOUNDARY = "Toggle Boundary"; -const ACTION_TOGGLE_SUBMAP_ROOT = "Toggle Submap Root"; -const ACTION_TOGGLE_EMBED = "Toggle Embed/Link"; - -const ACTION_DOCK_UNDOCK = "Dock/Undock"; -const ACTION_HIDE = "Dock & hide"; -const ACTION_REARRANGE = "Rearrange Map"; -const ACTION_TOGGLE_FLOATING_EXTRAS = "Toggle Floating Extra Buttons"; - -const ACTION_UNDO = "Undo"; -const ACTION_REDO_Z = "Redo (Ctrl-Shift-Z)"; -const ACTION_REDO_Y = "Redo (Ctrl-Y)"; - -const ACTION_LABEL_KEYS = { - [ACTION_ADD]: "ACTION_LABEL_ADD", - [ACTION_ADD_SIBLING_AFTER]: "ACTION_LABEL_ADD_SIBLING_AFTER", - [ACTION_ADD_SIBLING_BEFORE]: "ACTION_LABEL_ADD_SIBLING_BEFORE", - [ACTION_ADD_FOLLOW]: "ACTION_LABEL_ADD_FOLLOW", - [ACTION_ADD_FOLLOW_FOCUS]: "ACTION_LABEL_ADD_FOLLOW_FOCUS", - [ACTION_ADD_FOLLOW_ZOOM]: "ACTION_LABEL_ADD_FOLLOW_ZOOM", - [ACTION_SORT_ORDER]: "ACTION_LABEL_SORT_ORDER", - [ACTION_EDIT]: "ACTION_LABEL_EDIT", - [ACTION_TOGGLE_CHECKBOX]: "ACTION_LABEL_TOGGLE_CHECKBOX", - [ACTION_CALENDAR]: "ACTION_LABEL_CALENDAR", - [ACTION_PIN]: "ACTION_LABEL_PIN", - [ACTION_BOX]: "ACTION_LABEL_BOX", - [ACTION_TOGGLE_GROUP]: "ACTION_LABEL_TOGGLE_GROUP", - [ACTION_COPY]: "ACTION_LABEL_COPY", - [ACTION_CUT]: "ACTION_LABEL_CUT", - [ACTION_PASTE]: "ACTION_LABEL_PASTE", - [ACTION_IMPORT_OUTLINE]: "ACTION_LABEL_IMPORT_OUTLINE", - [ACTION_ZOOM]: "ACTION_LABEL_ZOOM", - [ACTION_FOCUS]: "ACTION_LABEL_FOCUS", - [ACTION_NAVIGATE]: "ACTION_LABEL_NAVIGATE", - [ACTION_NAVIGATE_ZOOM]: "ACTION_LABEL_NAVIGATE_ZOOM", - [ACTION_NAVIGATE_FOCUS]: "ACTION_LABEL_NAVIGATE_FOCUS", - [ACTION_FOLD]: "ACTION_LABEL_FOLD", - [ACTION_FOLD_L1]: "ACTION_LABEL_FOLD_L1", - [ACTION_FOLD_ALL]: "ACTION_LABEL_FOLD_ALL", - [ACTION_TOGGLE_BOUNDARY]: "TOOLTIP_TOGGLE_BOUNDARY", - [ACTION_TOGGLE_SUBMAP_ROOT]: "ACTION_LABEL_TOGGLE_SUBMAP_ROOT", - [ACTION_TOGGLE_EMBED]: "ACTION_LABEL_TOGGLE_EMBED", - [ACTION_DOCK_UNDOCK]: "ACTION_LABEL_DOCK_UNDOCK", - [ACTION_HIDE]: "ACTION_LABEL_HIDE", - [ACTION_REARRANGE]: "ACTION_LABEL_REARRANGE", - [ACTION_TOGGLE_FLOATING_EXTRAS]: "TOOLTIP_TOGGLE_FLOATING_EXTRAS", - [ACTION_UNDO]: "Undo", - [ACTION_REDO_Z]: "Redo", - [ACTION_REDO_Y]: "Redo" -}; - -const getActionLabel = (action) => t(ACTION_LABEL_KEYS[action] ?? action); - -// Default configuration -// scope may be "input" | "excalidraw" | "global" -// - input: the hotkey only works if the inputEl has focus -// - excalidraw: the hotkey works when either the inputEl has focus or the sidepanelView leaf or the Excalidraw leaf is active -// - global: the hotkey works across obsidian, when ever the Excalidraw view in ea.targetView is visible, i.e. the hotkey works even if the user is active in a leaf like pdf viewer, markdown note, open next to Excalidraw. -// - none: ea.targetView not set or Excalidraw leaf not visible -const DEFAULT_HOTKEYS = [ - // Creation - Enter based - { action: ACTION_ADD, key: "Enter", modifiers: [], scope: SCOPE.input, isInputOnly: true, requiresNode: false }, - { action: ACTION_ADD_SIBLING_AFTER, key: "Enter", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: true, requiresNode: false }, - { action: ACTION_ADD_SIBLING_BEFORE, key: "Enter", modifiers: ["Alt", "Shift"], scope: SCOPE.input, isInputOnly: true, requiresNode: false }, - { action: ACTION_ADD_FOLLOW, key: "Enter", modifiers:["Mod", "Alt"], scope: SCOPE.input, isInputOnly: true, requiresNode: false }, - { action: ACTION_ADD_FOLLOW_FOCUS, key: "Enter", modifiers: ["Mod"], scope: SCOPE.input, isInputOnly: true, requiresNode: false }, - { action: ACTION_ADD_FOLLOW_ZOOM, key: "Enter", modifiers: ["Mod", "Shift"], scope: SCOPE.input, isInputOnly: true, requiresNode: false }, - - //Window - { action: ACTION_DOCK_UNDOCK, key: "Enter", modifiers: ["Shift"], scope: SCOPE.input, isInputOnly: true, requiresNode: false }, - { action: ACTION_HIDE, key: "Escape", modifiers:[], scope: SCOPE.excalidraw, isInputOnly: true, requiresNode: false }, - - // Edit - { action: ACTION_EDIT, code: "KeyE", modifiers: ["Mod"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - - // Structure Modifiers - { action: ACTION_TOGGLE_CHECKBOX, code: "KeyL", modifiers: ["Mod"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_CALENDAR, code: "KeyD", modifiers: ["Alt", "Mod"], scope: SCOPE.input, isInputOnly: false, requiresNode: false }, - { action: ACTION_PIN, code: "KeyP", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_BOX, code: "KeyB", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_TOGGLE_BOUNDARY, code: "KeyB", modifiers: ["Alt", "Shift"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_TOGGLE_SUBMAP_ROOT, code: "KeyJ", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_TOGGLE_GROUP, code: "KeyG", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_TOGGLE_EMBED, code: "KeyE", modifiers:["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - - // Clipboard (Alt to distinguish from text editing) - { action: ACTION_COPY, code: "KeyC", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_CUT, code: "KeyX", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_PASTE, code: "KeyV", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: false }, - { action: ACTION_IMPORT_OUTLINE, code: "KeyI", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - - // View Actions - { action: ACTION_REARRANGE, code: "KeyR", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_ZOOM, code: "KeyZ", modifiers:["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_FOCUS, code: "KeyF", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: false }, - - //Navigation - { action: ACTION_NAVIGATE, key: "ArrowKeys", modifiers: ["Alt"], isNavigation: true, scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_NAVIGATE_ZOOM, key: "ArrowKeys", modifiers: ["Alt", "Shift"], isNavigation: true, scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_NAVIGATE_FOCUS, key: "ArrowKeys", modifiers: ["Alt", "Mod"], isNavigation: true, scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_SORT_ORDER, code: "ArrowKeys", modifiers: ["Mod"], isNavigation: true, scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_FOLD, code: "Digit1", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_FOLD_L1, code: "Digit2", modifiers:["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - { action: ACTION_FOLD_ALL, code: "Digit3", modifiers: ["Alt"], scope: SCOPE.input, isInputOnly: false, requiresNode: true }, - - // Undo / Redo - { action: ACTION_UNDO, key: "z", modifiers: ["Mod"], scope: SCOPE.excalidraw, isInputOnly: false, hidden: true, requiresNode: false }, - { action: ACTION_REDO_Z, key: "z", modifiers: ["Mod", "Shift"], scope: SCOPE.excalidraw, isInputOnly: false, hidden: true, requiresNode: false }, - { action: ACTION_REDO_Y, key: "y", modifiers: ["Mod"], scope: SCOPE.excalidraw, isInputOnly: false, hidden: true, requiresNode: false }, -]; - -// Load hotkeys from settings or use default -// IMPORTANT: Use JSON.parse/stringify to create a deep copy of defaults. -// Otherwise, modifying userHotkeys modifies DEFAULT_HOTKEYS in memory, breaking the isModified check until restart. -let userHotkeys = getVal(K_HOTKEYS, { - value: JSON.parse(JSON.stringify(DEFAULT_HOTKEYS)), - hidden: true -}); -let isRecordingHotkey = false; -let cancelHotkeyRecording = null; - -const getObsidianConflict = (h) => { - if (!h) return null; - - const normalize = (s) => s.toLowerCase().replace("key", "").replace("digit", ""); - const sortMods = (m) => [...m].sort().join(","); - - const keysToCheck = h.isNavigation ? - ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"] : - [h.code ? h.code : h.key]; - - const targetMods = sortMods(h.modifiers); - - const commands = app.commands.listCommands(); - for (const cmd of commands) { - const hotkeys = app.hotkeyManager.getHotkeys(cmd.id) || app.hotkeyManager.getDefaultHotkeys(cmd.id); - if (!hotkeys) continue; - - for (const hk of hotkeys) { - const hkKey = normalize(hk.key); - const hkMods = sortMods(hk.modifiers); - - for (const targetKeyRaw of keysToCheck) { - if (normalize(targetKeyRaw) === hkKey && targetMods === hkMods) { - return cmd.name; - } - } - } - } - return null; -}; - -/** - * Sync userHotkeys to DEFAULT_HOTKEYS by action. - * - Drops user actions not in DEFAULT - * - Adds missing actions from DEFAULT - * - Structural attributes (isInputOnly, requiresNode, isNavigation, hidden) - * ALWAYS come from DEFAULT_HOTKEYS and are excluded from the saved state. - * - For existing actions: - * - keeps user values for configurable keys (modifiers, key, code, scope) - * - adds missing keys from DEFAULT - * - removes keys not in DEFAULT - **/ -function updateUserHotkeys() { - let dirty = false; - - const defaultByAction = new Map(DEFAULT_HOTKEYS.map(d => [d.action, d])); - // These properties dictate script logic and should never be overridden by user settings - const structuralKeys = ["isInputOnly", "requiresNode", "isNavigation", "hidden"]; - - const userByAction = new Map(); - for (const u of userHotkeys) { - if (u && typeof u.action === "string" && defaultByAction.has(u.action)) { - userByAction.set(u.action, u); - } else if (u && u.action) { - // user action no longer exists in DEFAULT => dropped - dirty = true; - } - } - - const next = []; - - for (const d of DEFAULT_HOTKEYS) { - const u = userByAction.get(d.action); - - if (!u) { - next.push(structuredClone ? structuredClone(d) : JSON.parse(JSON.stringify(d))); - dirty = true; - continue; - } - - const cleaned = { - action: d.action - }; - - for (const key of Object.keys(d)) { - if (key === "action") continue; - - // Always inherit structural properties directly from defaults - if (structuralKeys.includes(key)) { - cleaned[key] = d[key]; - continue; // Do NOT mark dirty just because this key is missing in the user config - } - - if (Object.prototype.hasOwnProperty.call(u, key)) { - cleaned[key] = u[key]; - } else { - cleaned[key] = d[key]; - dirty = true; - } - } - - for (const key of Object.keys(u)) { - if (key === "action") continue; - // If the user object has a structural key (e.g. from an older version's save), - // mark as dirty so we flush a cleaned version back to disk. - if (structuralKeys.includes(key)) { - dirty = true; - } else if (!Object.prototype.hasOwnProperty.call(d, key)) { - dirty = true; - break; - } - } - - next.push(cleaned); - } - - userHotkeys = next; - return dirty; -} - -dirty = updateUserHotkeys(); - -const getHotkeyDefByAction = (action) => userHotkeys.find((h) => h.action === action); - -const getHotkeyDisplayString = (h) => { - const parts = []; - if (h.modifiers.includes("Ctrl")) parts.push("Ctrl"); - if (h.modifiers.includes("Meta")) parts.push("Cmd"); - if (h.modifiers.includes("Mod")) parts.push(isMac ? "Cmd" : "Ctrl"); - if (h.modifiers.includes("Alt")) parts.push(isMac ? "Opt" : "Alt"); - if (h.modifiers.includes("Shift")) parts.push("Shift"); - - if (h.code) parts.push(h.code.replace("Key", "").replace("Digit", "")); - else if (h.key === "ArrowKeys") parts.push("Arrow"); - else if (h.key === " ") parts.push("Space"); - else parts.push(h.key); - - return parts.join(" + "); -}; - -const getActionHotkeyString = (action) => `(${getHotkeyDisplayString(getHotkeyDefByAction(action))})`; - -// Merge defaults in case new actions were added in an update -if (userHotkeys.length !== DEFAULT_HOTKEYS.length) { - const merged = [...userHotkeys]; - DEFAULT_HOTKEYS.forEach(d => { - if (!merged.find(u => u.action === d.action)) merged.push(JSON.parse(JSON.stringify(d))); - }); - userHotkeys = merged; -} - -// Generate the runtime HOTKEYS array used by getActionFromEvent -const generateRuntimeHotkeys = () => { - const runtimeKeys = []; - userHotkeys.forEach(h => { - if (h.isNavigation) { - ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].forEach(key => { - runtimeKeys.push({ - action: h.action, - key, - modifiers: h.modifiers, - scope: h.scope, - requiresNode: h.requiresNode, - isInputOnly: h.isInputOnly - }); - }); - } else { - runtimeKeys.push(h); - } - }); - return runtimeKeys; -}; - -let RUNTIME_HOTKEYS = generateRuntimeHotkeys(); - -/** - * Returns the current scope context for the hotkey - **/ -const getHotkeyContext = () => { - if (!isViewSet()) return SCOPE.none; - - const currentWindow = isUndocked && floatingInputModal ? - ea.targetView?.ownerWindow : - sidepanelWindow; - - if (currentWindow.document?.activeElement === inputEl || currentWindow.document?.activeElement === ontologyEl) { - return SCOPE.input; - } - - const leaf = app.workspace.activeLeaf; - if (!leaf) return SCOPE.none; - if ( - ea.targetView.leaf === leaf || - (ea.getSidepanelLeaf() === leaf && ea.sidepanelTab.isVisible()) - ) { - return SCOPE.excalidraw; - } - - if (ea.targetView.leaf.isVisible()) { - return SCOPE.global; - } - - return SCOPE.none; -} - -const getInstructions = () => ` -
- -${t("INSTRUCTIONS")} - -
Buy Me a Coffee at ko-fi.com
- - -`; - -// addElementsToView with different defaults compared to EA -const addElementsToView = async ({ - repositionToCursor = false, - save = false, - newElementsOnTop = true, - shouldRestoreElements = true, - captureUpdate = "IMMEDIATELY", -} = {}) => { - if (!isViewSet()) return; - - // Track transaction steps for Undo/Redo - if (["EVENTUALLY", "IMMEDIATELY"].includes(captureUpdate)) { - currentTransactionAccumulator++; - } - - await ea.addElementsToView(repositionToCursor, save, newElementsOnTop, shouldRestoreElements, captureUpdate); - const fileIds = new Set(ea.getElements().filter(el => el.fileId && !el.isDeleted).map(el => el.fileId)); - ea.clear(); - - // Commit transaction logic - if (captureUpdate === "IMMEDIATELY") { - // We only record the undo checkpoint when a visual commit happens - const currentSceneVersion = ExcalidrawLib.getSceneVersion(api().getSceneElements()); - lastCommittedTransaction = { - steps: currentTransactionAccumulator, - version: currentSceneVersion - }; - // Reset accumulator and clear redo availability since we pushed a new action - currentTransactionAccumulator = 0; - redoAvailable = null; - } - - if (fileIds.size === 0) return; - const checker = () => { - const loadedFiles = api().getFiles(); - const loadedKeys = Object.keys(loadedFiles).filter(f => loadedFiles[f].dataURL); - for (const fileId of fileIds) { - if (!loadedKeys.find(f => f.id === fileId)) return false; - } - return true; - } - - let watchdog = 0; - while (!checker() && watchdog++ < 20) { - await sleep(15); - } -} - -const selectNodeInView = (node) => { - if (!node) { - mostRecentlySelectedNodeID = null; - return; - } - const nodeId = typeof node === "string" ? node : node.id; - ea.selectElementsInView([nodeId]); - mostRecentlySelectedNodeID = nodeId; -}; - -const buildParentMap = (allElements, elementById) => { - const parentMap = new Map(); - const byId = elementById || buildElementMap(allElements); - - allElements.forEach((el) => { - if (el.type === "arrow" && el.customData?.isBranch && el.startBinding?.elementId && el.endBinding?.elementId) { - const parent = byId.get(el.startBinding.elementId); - const childId = el.endBinding.elementId; - - if (parent && childId) { - // Handle container nodes if applicable - const actualParent = parent.containerId ? byId.get(parent.containerId) : parent; - if (actualParent) parentMap.set(childId, actualParent); - } - } - }); - - return parentMap; -}; - -// --------------------------------------------------------------------------- -// 2. Traversal & Geometry Helpers -// --------------------------------------------------------------------------- - -const getBoundaryHost = (selectedElements) => { - if ( - selectedElements.length === 1 && selectedElements[0].type === "line" && - selectedElements[0].customData?.hasOwnProperty("isBoundary") - ) { - const sel = selectedElements[0]; - // Check if this line is referenced as a boundaryId by any other element - const allElements = ea.getViewElements(); - const owner = allElements.find(el => el.customData?.boundaryId === sel.id); - return owner; - } -} - -const getMindmapNodeFromSelection = () => { - if (!isViewSet()) return; - const selectedElements = ea.getViewSelectedElements().filter(el => el.customData && ( - el.customData.hasOwnProperty("mindmapOrder") || el.customData.hasOwnProperty("isBranch") || - el.customData.hasOwnProperty("growthMode") || el.customData.hasOwnProperty("isBoundary") - )); - if (selectedElements.length === 0) return; - - const owner = getBoundaryHost(selectedElements); - if (owner) { - mostRecentlySelectedNodeID = owner.id; - return owner; - } - - if ( - selectedElements.length === 1 && ( - selectedElements[0].customData.hasOwnProperty("mindmapOrder") || - selectedElements[0].customData.hasOwnProperty("growthMode") - )) { - if (selectedElements[0].type === "text" && selectedElements[0].boundElements.length === 0 && !!selectedElements[0].containerId) { - const node = ea.getViewElements().find((el) => el.id === selectedElements[0].containerId); - mostRecentlySelectedNodeID = node?.id; - return node; - } - mostRecentlySelectedNodeID = selectedElements?.[0]?.id; - return selectedElements[0]; - } - - // Handle Single Arrow Selection, deliberatly not filtering to el.customData?.isBranch - if (selectedElements.length === 1 && selectedElements[0].type === "arrow") { - const sel = selectedElements[0]; - const targetId = sel.startBinding?.elementId || sel.endBinding?.elementId; - if (targetId) { - const target = ea.getViewElements().find((el) => el.id === targetId); - mostRecentlySelectedNodeID = target?.id; - return target; - } - return; - } - - // Possibly Text + Container Selection - if (selectedElements.length === 2) { - const textEl = selectedElements.find((el) => el.type === "text"); - if (textEl && textEl.boundElements.length > 0 && textEl.customData.hasOwnProperty("mindmapOrder")) { - mostRecentlySelectedNodeID = textEl.id; - return textEl; - } else if (textEl) { - const containerId = textEl.containerId; - if (containerId) { - const container = selectedElements.find((el) => el.id === containerId); - if (container && container.boundElements.length > 0 && container.customData.hasOwnProperty("mindmapOrder")) { - mostRecentlySelectedNodeID = container.id; - return container; - } - } - } - } - - // Handle Group Selection (Find Highest Ranking Parent) - // deliberatly not filtering to el.customData?.isBranch - if (selectedElements.length > 1) { - const selectedIds = new Set(selectedElements.map((el) => el.id)); - const arrows = selectedElements.filter((el) => el.type === "arrow"); - - const sourceIds = new Set(); - const sinkIds = new Set(); - - // Analyze arrows that connect elements WITHIN the current selection - arrows.forEach((arrow) => { - const startId = arrow.startBinding?.elementId; - const endId = arrow.endBinding?.elementId; - - if (startId && selectedIds.has(startId)) sourceIds.add(startId); - if (endId && selectedIds.has(endId)) sinkIds.add(endId); - }); - - // The "Highest Ranking Parent" is a source within the group - // that is NOT a sink of any arrow within that same group. - const rootId = Array.from(sourceIds).find((id) => !sinkIds.has(id)); - - if (rootId) { - mostRecentlySelectedNodeID = rootId; - return selectedElements.find((el) => el.id === rootId); - } - } -} - -const ensureNodeSelected = () => { - const elementToSelect = getMindmapNodeFromSelection(); - if (elementToSelect) { - selectNodeInView(elementToSelect); - } -}; - -/** - * Retrieves the parent node of a specific element. - */ -const getParentNode = (id, allElements, parentMap = null) => { - if (parentMap && parentMap.has(id)) { - return parentMap.get(id); - } - - const arrow = allElements.find( - (el) => el.type === "arrow" && el.customData?.isBranch && el.endBinding?.elementId === id, - ); - if (!arrow) return null; - const parent = allElements.find((el) => el.id === arrow.startBinding?.elementId); - return parent?.containerId ? - allElements.find((el) => el.id === parent.containerId) : - parent; -}; - -const buildElementMap = (allElements) => { - const map = new Map(); - allElements.forEach((el) => map.set(el.id, el)); - return map; -}; - -const buildChildrenMap = (allElements, elementById) => { - const childrenByParent = new Map(); - const byId = elementById || buildElementMap(allElements); - - allElements.forEach((el) => { - if (el.type === "arrow" && el.customData?.isBranch && el.startBinding?.elementId) { - const parentId = el.startBinding.elementId; - const child = byId.get(el.endBinding?.elementId); - if (!child) return; - if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []); - childrenByParent.get(parentId).push(child); - } - }); - - return childrenByParent; -}; - -const getChildrenNodes = (id, allElements) => { - const arrows = allElements.filter( - (el) => el.type === "arrow" && el.customData?.isBranch && el.startBinding?.elementId === id, - ); - return arrows.map((a) => allElements.find((el) => el.id === a.endBinding?.elementId)).filter(Boolean); -}; - -const buildGroupToNodes = (branchIds, allElements) => { - const branchIdSet = new Set(branchIds); - const groupToNodes = new Map(); - - allElements.forEach(el => { - if (branchIdSet.has(el.id) && el.type !== "arrow" && el.groupIds) { - el.groupIds.forEach(gid => { - if (!groupToNodes.has(gid)) groupToNodes.set(gid, new Set()); - groupToNodes.get(gid).add(el); - }); - } - }); - - return groupToNodes; -}; - -/** - * Returns the IDs of root nodes in the scene - * - A root node is defined as a node with `growthMode` that has only outgoing branch arrows, or no branch arrows at all. - * @returns {string[]} An array of root node IDs. - */ -const getMasterRoots = () => { - const all = ea.getViewElements(); - const allMap = new Map(all.map((el) => [el.id, el])); - const maybeRoots = all.filter((el) => el.customData?.growthMode); - const roots = maybeRoots.filter((r) => { - const notRoot = r.boundElements.some((be) => { - if (be.type !== "arrow") return false; - const arrow = allMap.get(be.id); - if (!arrow) return false; - if (!arrow.customData?.isBranch) return false; - if (arrow.endBinding?.elementId === r.id) return true; - return false; - }); - return !notRoot; - }); - - return roots.map((r) => r.id); -}; - -/** - * Traverses up the tree to find the root and depth. - */ -const getHierarchy = (el, allElements, elementById = null, parentMap = null) => { - // Optimization: If we have an ID lookup, use it, otherwise perform search - if (elementById) { - el = getBoundaryHost([el]) ?? el; - } else { - // Legacy behavior for ad-hoc calls - el = getBoundaryHost([el]) ?? el; - } - - let depth = 0, - curr = el, - l1Id = el.id, - rootId = el.id; - const visited = new Set([el.id]); - - while (true) { - let p = getParentNode(curr.id, allElements, parentMap); - - if (!p || visited.has(p.id)) { - rootId = curr.id; - break; - } - visited.add(p.id); - l1Id = curr.id; - curr = p; - depth++; - } - return { - depth, - l1AncestorId: l1Id, - rootId - }; -}; - -/** - * Returns the nearest configuration root for the selected node. - * - Additional roots (`isAdditionalRoot`) act as local configuration roots. - * - If none is found on the path, the master root is returned. - */ -const getSettingsRootNode = (el, allElements, elementById = null, parentMap = null) => { - if (!el) return null; - - let curr = getBoundaryHost([el]) ?? el; - let last = curr; - const visited = new Set(); - - while (curr && !visited.has(curr.id)) { - visited.add(curr.id); - last = curr; - - if (curr.customData?.isAdditionalRoot === true) { - return curr; - } - - const p = getParentNode(curr.id, allElements, parentMap); - if (!p) { - return curr; // master root - } - curr = p; - } - - return last; -}; - -/** - * Returns depth from a specific ancestor. - * If the ancestor is not found, it safely falls back to absolute hierarchy depth. - */ -const getDepthFromAncestor = (nodeId, ancestorId, allElements, parentMap = null) => { - const byId = buildElementMap(allElements); - let curr = byId.get(nodeId); - if (!curr) return 0; - - let depth = 0; - const visited = new Set(); - while (curr && !visited.has(curr.id)) { - if (curr.id === ancestorId) return depth; - visited.add(curr.id); - curr = getParentNode(curr.id, allElements, parentMap); - depth++; - } - - const fallbackNode = byId.get(nodeId); - return fallbackNode ? getHierarchy(fallbackNode, allElements, byId, parentMap).depth : 0; -}; - -const MAP_ROOT_CUSTOMDATA_KEYS = [ - "isAdditionalRoot", - "growthMode", - "autoLayoutDisabled", - "arrowType", - "fontsizeScale", - "multicolor", - "boxChildren", - "roundedCorners", - "maxWrapWidth", - "isSolidArrow", - "centerText", - "fillSweep", - "branchScale", - "baseStrokeWidth", - "layoutSettings", -]; - -const inferDirectionalGrowthMode = (node, parent, sourceRoot = null, sourceMode = null) => { - if (!node || !parent) return "Right-facing"; - - const mode = sourceMode || sourceRoot?.customData?.growthMode || currentModalGrowthMode; - const nodeCenter = { - x: node.x + node.width / 2, - y: node.y + node.height / 2 - }; - - const ref = sourceRoot ? - { - x: sourceRoot.x + sourceRoot.width / 2, - y: sourceRoot.y + sourceRoot.height / 2 - } : - { - x: parent.x + parent.width / 2, - y: parent.y + parent.height / 2 - }; - - // Single-direction maps inherit their direction directly. - if (mode === "Up-facing") return "Up-facing"; - if (mode === "Down-facing") return "Down-facing"; - if (mode === "Right-facing") return "Right-facing"; - if (mode === "Left-facing") return "Left-facing"; - - // Dual-axis directional map: infer by vertical side relative to map root. - if (mode === "Up-Down") { - return nodeCenter.y < ref.y ? "Up-facing" : "Down-facing"; - } - - // Right-Left and Radial maps: infer by horizontal side relative to map root. - if (mode === "Right-Left" || mode === "Radial") { - return nodeCenter.x >= ref.x ? "Right-facing" : "Left-facing"; - } - - // Fallback to geometric heuristic. - const dx = nodeCenter.x - ref.x; - const dy = nodeCenter.y - ref.y; - if (Math.abs(dx) >= Math.abs(dy)) { - return dx >= 0 ? "Right-facing" : "Left-facing"; - } - return dy >= 0 ? "Down-facing" : "Up-facing"; -}; - -const getRootConfigForNode = (rootNode) => { - const cd = rootNode?.customData ?? {}; - const defaultLayout = layoutSettings || {}; - return { - growthMode: cd?.growthMode || currentModalGrowthMode, - autoLayoutDisabled: cd?.autoLayoutDisabled === true, - arrowType: cd?.arrowType ?? arrowType, - fontsizeScale: cd?.fontsizeScale ?? fontsizeScale, - multicolor: typeof cd?.multicolor === "boolean" ? cd.multicolor : multicolor, - boxChildren: typeof cd?.boxChildren === "boolean" ? cd.boxChildren : boxChildren, - roundedCorners: typeof cd?.roundedCorners === "boolean" ? cd.roundedCorners : roundedCorners, - maxWrapWidth: typeof cd?.maxWrapWidth === "number" ? cd.maxWrapWidth : maxWidth, - isSolidArrow: typeof cd?.isSolidArrow === "boolean" ? cd.isSolidArrow : isSolidArrow, - centerText: typeof cd?.centerText === "boolean" ? cd.centerText : centerText, - fillSweep: typeof cd?.fillSweep === "boolean" ? cd.fillSweep : fillSweep, - branchScale: cd?.branchScale ?? branchScale, - baseStrokeWidth: typeof cd?.baseStrokeWidth === "number" ? cd.baseStrokeWidth : baseStrokeWidth, - layoutSettings: JSON.parse(JSON.stringify(cd?.layoutSettings ?? defaultLayout)), - }; -}; - -/** - * Temporarily applies map/root settings for layout calculations, then restores globals. - * This allows nested additional roots to layout with their own strategy. - */ -const withRootLayoutContext = (rootNode, fn) => { - const previous = { - growthMode: currentModalGrowthMode, - arrowType, - centerText, - fillSweep, - layoutSettings: layoutSettings, - }; - - const cfg = getRootConfigForNode(rootNode); - currentModalGrowthMode = cfg.growthMode; - arrowType = cfg.arrowType; - centerText = cfg.centerText; - fillSweep = cfg.fillSweep; - layoutSettings = JSON.parse(JSON.stringify(cfg.layoutSettings)); - - try { - return fn(cfg); - } finally { - currentModalGrowthMode = previous.growthMode; - arrowType = previous.arrowType; - centerText = previous.centerText; - fillSweep = previous.fillSweep; - layoutSettings = previous.layoutSettings; - } -}; - -const getAngleFromCenter = (center, point) => { - let dx = point.x - center.x, - dy = point.y - center.y; - let angle = Math.atan2(dx, -dy) * (180 / Math.PI); - return angle < 0 ? angle + 360 : angle; -}; - -const randInt = (range) => Math.round(Math.random() * range); - -const getDynamicColor = (existingColors) => { - if (multicolor && customPalette.enabled && customPalette.colors.length > 0) { - if (customPalette.random) { - return customPalette.colors[Math.floor(Math.random() * customPalette.colors.length)]; - } - return customPalette.colors[existingColors.length % customPalette.colors.length]; - } - const st = getAppState(); - const bg = st.viewBackgroundColor === "transparent" ? "#ffffff" : st.viewBackgroundColor; - const bgCM = ea.getCM(bg); - const isDarkBg = bgCM.isDark(); - - // Heavier weight on Hue to ensure "different colors" rather than just "different shades" - const getDist = (c1, c2) => { - let dh = Math.abs(c1.hue - c2.hue); - if (dh > 180) dh = 360 - dh; - const hScore = (dh / 1.8); - return (hScore * 2) + Math.abs(c1.saturation - c2.saturation) + Math.abs(c1.lightness - c2.lightness); - }; - - let palette = st.colorPalette?.elementStroke || []; - if (Array.isArray(palette)) palette = palette.flat(Infinity); - - const candidates = []; - - new Set(palette).forEach(hex => { - if (hex && hex !== "transparent") candidates.push({ - hex, - isPalette: true - }); - }); - - for (let h = 0; h < 360; h += HUE_STEP_BASE + randInt(HUE_STEP_JITTER)) { - const c = ea.getCM({ - h, - s: SAT_BASE + randInt(SAT_JITTER), - l: isDarkBg ? - LIGHT_BASE_DARK + randInt(LIGHT_JITTER_DARK) : - LIGHT_BASE_LIGHT + randInt(LIGHT_JITTER_LIGHT), - a: 1 - }); - candidates.push({ - hex: c.stringHEX(), - isPalette: false - }); - } - - // Process Candidates - const scored = candidates.map(c => { - let cm = ea.getCM(c.hex); - if (!cm) return null; - - // Auto-adjust for contrast if necessary - // If yellow/orange is too light for white bg, darken it. - let contrast = cm.contrast({ - bgColor: bg - }); - if (contrast < 3) { - const originalL = cm.lightness; - // Try darkening/lightening to meet WCAG AA (3.0 for graphics) - const targetL = isDarkBg ? Math.min(originalL + 40, 90) : Math.max(originalL - 40, 20); - cm = cm.lightnessTo(targetL); - contrast = cm.contrast({ - bgColor: bg - }); - c.hex = cm.stringHEX({ - alpha: false - }); // Update the hex to the readable version - } - - // Calculate minimum distance to ANY existing color on canvas - let minDiff = 1000; - let closestColor = null; - - if (existingColors.length > 0) { - existingColors.forEach(exHex => { - const exCM = ea.getCM(exHex); - if (exCM) { - const d = getDist(cm, exCM); - if (d < minDiff) { - minDiff = d; - closestColor = exHex; - } - } - }); - } - - return { - ...c, - contrast, - minDiff - }; - }).filter(c => c && c.contrast >= COLOR_CONTRAST_MIN); // Filter out absolute invisible colors - - // Sort Logic - scored.sort((a, b) => { - // Threshold for "This color is effectively the same as one already used" - // Distance of ~30 usually means same Hue family and similar shade - const threshold = COLOR_DISTINCT_THRESHOLD; - const aIsDistinct = a.minDiff > threshold; - const bIsDistinct = b.minDiff > threshold; - - // 1. Priority: Distinctness from existing canvas elements - if (aIsDistinct && !bIsDistinct) return -1; - if (!aIsDistinct && bIsDistinct) return 1; - - // 2. Priority: If both are distinct (or both are duplicates), prefer Palette - if (a.isPalette !== b.isPalette) return a.isPalette ? -1 : 1; - - // 3. Priority: If both are palette (or both generated), pick the one most different from existing - return b.minDiff - a.minDiff; - }); - - return scored[0]?.hex || "#000000"; -}; - -// --------------------------------------------------------------------------- -// Folding Logic -// --------------------------------------------------------------------------- - -/** - * Manages the "..." fold indicator text element. - * Creates it if missing and show=true, hides it if show=false. - * Updates its position relative to the parent node. - * - * @param {ExcalidrawElement} node - The parent node. - * @param {boolean} show - Whether to show the fold indicator. - * @param {ExcalidrawElement[]} allElements - All elements in the scene. - */ -const manageFoldIndicator = (node, show, allElements) => { - if (show) { - const children = getChildrenNodes(node.id, allElements); - if (children.length === 0) show = false; - } - const existingId = node.customData?.foldIndicatorId; - - let side = 1; - const parent = getParentNode(node.id, allElements); - if (parent) { - const parentCenter = parent.x + parent.width / 2; - const nodeCenter = node.x + node.width / 2; - side = nodeCenter < parentCenter ? -1 : 1; - } - - if (show) { - let ind; - if (existingId) { - ind = allElements.find(el => el.id === existingId); - if (ind) { - ind.isDeleted = false; - ind.strokeColor = node.strokeColor; - ind.opacity = layoutSettings.INDICATOR_OPACITY; - } - } - - // Create new indicator if none exists or wasn't found - if (!ind) { - const fontSize = ea.getBoundTextElement(node).eaElement?.fontSize || 20; - const id = ea.addText(0, 0, "..."); - ind = ea.getElement(id); - ind.fontSize = fontSize; - ind.strokeColor = node.strokeColor; - ind.opacity = layoutSettings.INDICATOR_OPACITY; - ind.textVerticalAlign = "middle"; - - if (node.groupIds && node.groupIds.length > 0) { - ind.groupIds = [node.groupIds[0]]; - } else { - ea.addToGroup([node.id, id]); - } - ea.addAppendUpdateCustomData(node.id, { - foldIndicatorId: id - }); - } - - if (side === 1) { - ind.x = node.x + node.width + layoutSettings.INDICATOR_OFFSET; - ind.textAlign = "left"; - } else { - ind.x = node.x - layoutSettings.INDICATOR_OFFSET - ind.width; - ind.textAlign = "right"; - } - ind.y = node.y + node.height - ind.fontSize; - } else { - // Hide/Delete indicator - if (existingId) { - const ind = allElements.find(el => el.id === existingId); - if (ind) ind.isDeleted = true; - ea.addAppendUpdateCustomData(node.id, { - foldIndicatorId: undefined - }); - } - } -}; - -/** - * Toggles visibility of an element by manipulating opacity and locked state. - * Saves the original state to customData for restoration. - * - * @param {ExcalidrawElement} el - The element to update. - * @param {boolean} hide - Whether to hide the element. - */ -const setElementVisibility = (el, hide) => { - if (hide) { - // Only save state if not already saved to avoid overwriting original state with hidden state - if (!el.customData?.foldState) { - // Safety: If for some reason opacity is already 0, assume 100 to avoid locking it invisible forever - const safeOpacity = el.opacity === 0 ? 100 : el.opacity; - ea.addAppendUpdateCustomData(el.id, { - foldState: { - opacity: safeOpacity, - locked: el.locked - } - }); - } - el.opacity = 0; - el.locked = true; - } else { - // Restore original state - if (el.customData?.foldState) { - el.opacity = el.customData.foldState.opacity; - el.locked = el.customData.foldState.locked; - ea.addAppendUpdateCustomData(el.id, { - foldState: undefined - }); - } else { - // Default fallback if no state was saved but we need to show - if (el.opacity === 0) el.opacity = 100; - el.locked = false; - } - } - const boundTextElement = ea.getBoundTextElement(el); - if (boundTextElement.eaElement && boundTextElement.eaElement !== el) { - setElementVisibility(boundTextElement?.eaElement, hide); - } -}; - -/** - * Recursively updates the visibility of a branch based on fold state. - * Handles nodes, connectors, grouped decorations, cross-links, and boundaries. - * - * @param {string} nodeId - The ID of the current node. - * @param {boolean} parentHidden - Whether the parent is hidden (inherited visibility). - * @param {ExcalidrawElement[]} allElements - All elements in the scene. - * @param {boolean} isRootOfFold - Whether this node is the root of the fold operation (always visible itself). - */ -const updateBranchVisibility = (nodeId, parentHidden, allElements, isRootOfFold, rootId) => { - const node = allElements.find(el => el.id === nodeId); - if (!node) return; - - const isFolded = node.customData?.isFolded === true; - - // The root of the fold operation stays visible unless its parent was already hidden - const shouldHideThis = parentHidden && !isRootOfFold; - - setElementVisibility(node, shouldHideThis); - - // Set to track the ID of the main node AND any decorations grouped with it - // This allows us to detect crosslinks attached to decorations, not just the main node - const localNodeIds = new Set([node.id]); - - // Handle Decorations (Grouped elements like boxes, icons, stickers) - if (node.groupIds && node.groupIds.length > 0) { - - const groupElements = ea.getElementsInTheSameGroupWithElement(node, allElements); - - const childrenIds = getChildrenNodes(nodeId, allElements).map(c => c.id); - - groupElements.forEach(el => { - if (el.id === node.id) return; - if (el.customData?.isBranch) return; - if (el.customData?.isBoundary) return; - if (el.id === node.customData?.foldIndicatorId) return; - if (childrenIds.includes(el.id)) return; - - // Skip other structural elements (like parents or siblings in the same group). - // This prevents a hidden child node from hiding its visible parent/siblings - // when "Group Branches" is active. - if (isStructuralElement(el, allElements, rootId)) return; - - setElementVisibility(el, shouldHideThis); - localNodeIds.add(el.id); - }); - } - - // Handle Crosslinks (Non-structural arrows connected to this node OR its decorations) - const crossLinks = allElements.filter(el => - el.type === "arrow" && - !el.customData?.isBranch && - ( - (el.startBinding && localNodeIds.has(el.startBinding.elementId)) || - (el.endBinding && localNodeIds.has(el.endBinding.elementId)) - ) - ); - - crossLinks.forEach(arrow => { - if (shouldHideThis) { - setElementVisibility(arrow, true); - } else { - // Determine which end is the "other" node - const isStartLocal = arrow.startBinding && localNodeIds.has(arrow.startBinding.elementId); - - const otherId = isStartLocal ? - arrow.endBinding?.elementId : - arrow.startBinding?.elementId; - - const otherNode = allElements.find(e => e.id === otherId); - - if (otherNode && !otherNode.isDeleted && otherNode.opacity > 0) { - setElementVisibility(arrow, false); - } - } - }); - - // Handle Boundary Visibility - if (node.customData?.boundaryId) { - const boundEl = allElements.find(el => el.id === node.customData.boundaryId); - if (boundEl) { - if (shouldHideThis || isFolded) { - boundEl.opacity = 0; - boundEl.locked = true; - } else { - boundEl.opacity = 30; - boundEl.locked = false; - } - } - } - - // Manage Indicator - const showIndicator = !shouldHideThis && isFolded; - manageFoldIndicator(node, showIndicator, allElements); - - // Process Children - const childrenHidden = shouldHideThis || isFolded; - - const children = getChildrenNodes(nodeId, allElements); - - children.forEach(child => { - // Handle the connector arrow - const arrow = allElements.find( - a => a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === nodeId && - a.endBinding?.elementId === child.id - ); - - if (arrow) { - setElementVisibility(arrow, childrenHidden); - } - - // Recurse - updateBranchVisibility(child.id, childrenHidden, allElements, false, rootId); - }); -}; - -/** - * Toggles the folded state of the selected node's branch. - * Supports different modes: L0 (direct children), L1 (grandchildren), ALL (recursive). - * - * @param {string} mode - "L0" | "L1" | "ALL" - */ -const toggleFold = async (mode = "L0") => { - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - - const allViewElements = ea.getViewElements(); - const info = getHierarchy(sel, allViewElements); - - // Only target elements in the specific mindmap tree to avoid massive array loops - const projectElements = getMindmapProjectElements(info.rootId, allViewElements); - ea.copyViewElementsToEAforEditing(projectElements); - const wbElements = ea.getElements(); - - const targetNode = wbElements.find(el => el.id === sel.id); - if (!targetNode) return; - - const children = getChildrenNodes(targetNode.id, wbElements); - if (children.length === 0) return; - - if (mode === "L1") { - const hasGrandChildren = children.some(child => getChildrenNodes(child.id, wbElements).length > 0); - if (!hasGrandChildren) return; - } - - let isFoldAction = false; - - if (mode === "L0") { - const isCurrentlyFolded = targetNode.customData?.isFolded === true; - isFoldAction = !isCurrentlyFolded; - ea.addAppendUpdateCustomData(targetNode.id, { - isFolded: isFoldAction - }); - } else if (mode === "L1") { - ea.addAppendUpdateCustomData(targetNode.id, { - isFolded: false - }); - const anyChildFolded = children.some(child => child.customData?.isFolded === true); - isFoldAction = !anyChildFolded; - - children.forEach(child => { - ea.addAppendUpdateCustomData(child.id, { - isFolded: isFoldAction - }); - }); - } else if (mode === "ALL") { - ea.addAppendUpdateCustomData(targetNode.id, { - isFolded: false - }); - const nonLeafDescendants = []; - const stack = [...children]; - - while (stack.length) { - const node = stack.pop(); - const nodeChildren = getChildrenNodes(node.id, wbElements); - - if (nodeChildren.length > 0) { - nonLeafDescendants.push(node); - nodeChildren.forEach(child => stack.push(child)); - } - } - - const anyDescendantFolded = nonLeafDescendants.some(node => node.customData?.isFolded === true); - isFoldAction = !anyDescendantFolded; - - nonLeafDescendants.forEach(node => { - ea.addAppendUpdateCustomData(node.id, { - isFolded: isFoldAction - }); - }); - } - - updateBranchVisibility(targetNode.id, false, wbElements, true, info.rootId); - - await addElementsToView({ - captureUpdate: autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" - }); - - if (!autoLayoutDisabled) { - await triggerGlobalLayout(info.rootId); - } - - ea.viewUpdateScene({ - appState: { - selectedGroupIds: {} - } - }); - focusSelected(); -}; - -// --------------------------------------------------------------------------- -// 3. Layout & Grouping Engine -// --------------------------------------------------------------------------- -const moveCrossLinks = (allElements, originalPositions) => { - const crossLinkArrows = allElements.filter(el => - el.type === "arrow" && - !el.customData?.isBranch && - el.startBinding?.elementId && - el.endBinding?.elementId - ); - - const touched = new Set(); - - crossLinkArrows.forEach(arrow => { - const startId = arrow.startBinding.elementId; - const endId = arrow.endBinding.elementId; - const startNodeOld = originalPositions.get(startId); - const endNodeOld = originalPositions.get(endId); - const startNodeNew = ea.getElement(startId); - const endNodeNew = ea.getElement(endId); - - if (startNodeOld && endNodeOld && startNodeNew && endNodeNew) { - touched.add(arrow.id); - const dsX = startNodeNew.x - startNodeOld.x; - const dsY = startNodeNew.y - startNodeOld.y; - const deX = endNodeNew.x - endNodeOld.x; - const deY = endNodeNew.y - endNodeOld.y; - if (dsX === 0 && dsY === 0 && deX === 0 && deY === 0) return; - - const eaArrow = ea.getElement(arrow.id); - if (!eaArrow) return; - - eaArrow.x += dsX; - eaArrow.y += dsY; - - const diffX = deX - dsX; - const diffY = deY - dsY; - - const len = eaArrow.points.length; - if (len > 0) { - eaArrow.points = eaArrow.points.map((p, i) => { - const t = i / (len - 1); - return [ - p[0] + diffX * t, - p[1] + diffY * t - ]; - }); - } - } - }); - return touched; -}; - -const moveDecorations = (allElements, originalPositions, groupToNodes, rootId, elementById, parentMap) => { - const structuralIds = new Set(); - if (rootId) { - allElements.forEach(el => { - if (isStructuralElement(el, allElements, rootId, elementById, parentMap)) { - structuralIds.add(el.id); - } - }); - } - - const decorationsToUpdate = []; - - allElements.forEach(el => { - // Optimization: O(1) lookup instead of function call - const isStructural = structuralIds.has(el.id); - const isCrossLink = el.type === "arrow" && !el.customData?.isBranch && el.startBinding?.elementId && el.endBinding?.elementId; - - const isDecoration = !isStructural && !isCrossLink && el.groupIds && el.groupIds.length > 0; - - if (isDecoration) { - const hostNodes = new Set(); - el.groupIds.forEach(gid => { - const nodesInGroup = groupToNodes.get(gid); - if (nodesInGroup) { - nodesInGroup.forEach(node => hostNodes.add(node)); - } - }); - - if (hostNodes.size > 0) { - const nodesArray = Array.from(hostNodes); - - let minXOld = Infinity, - minYOld = Infinity, - maxXOld = -Infinity, - maxYOld = -Infinity; - let minXNew = Infinity, - minYNew = Infinity, - maxXNew = -Infinity, - maxYNew = -Infinity; - - let validHost = false; - - nodesArray.forEach(n => { - const oldPos = originalPositions.get(n.id); - const newEl = ea.getElement(n.id); - - if (oldPos && newEl) { - validHost = true; - minXOld = Math.min(minXOld, oldPos.x); - minYOld = Math.min(minYOld, oldPos.y); - maxXOld = Math.max(maxXOld, oldPos.x + n.width); - maxYOld = Math.max(maxYOld, oldPos.y + n.height); - - minXNew = Math.min(minXNew, newEl.x); - minYNew = Math.min(minYNew, newEl.y); - maxXNew = Math.max(maxXNew, newEl.x + newEl.width); - maxYNew = Math.max(maxYNew, newEl.y + newEl.height); - } - }); - - if (validHost) { - const oldCx = minXOld + (maxXOld - minXOld) / 2; - const oldCy = minYOld + (maxYOld - minYOld) / 2; - const newCx = minXNew + (maxXNew - minXNew) / 2; - const newCy = minYNew + (maxYNew - minYNew) / 2; - - decorationsToUpdate.push({ - elementId: el.id, - dx: newCx - oldCx, - dy: newCy - oldCy - }); - } - } - } - }); - - decorationsToUpdate.forEach(item => { - if (Math.abs(item.dx) > 0.01 || Math.abs(item.dy) > 0.01) { - const decoration = ea.getElement(item.elementId); - if (decoration) { - decoration.x += item.dx; - decoration.y += item.dy; - } - } - }); - return new Set(decorationsToUpdate.map(d => d.elementId)); -}; - -/** - * Intelligent scaling for decorations when a node changes size. - * Uses "Edge Anchoring": - * - Elements inside the node (like text in a box) scale relative to the center. - * - Elements outside the node (like stickers/icons above) anchor to the nearest edge - * to preserve the visual gap, preventing them from flying away when the node grows significantly. - */ -const scaleDecorations = (oldNode, newNode, allElements, rootId) => { - if (!oldNode.groupIds || oldNode.groupIds.length === 0) return; - - const groupElements = ea.getElementsInTheSameGroupWithElement(oldNode, allElements); - // Filter out the node itself and structural elements - const decorations = groupElements.filter(el => - el.id !== oldNode.id && - !isStructuralElement(el, allElements, rootId) - ); - - if (decorations.length === 0) return; - - const oldCx = oldNode.x + oldNode.width / 2; - const oldCy = oldNode.y + oldNode.height / 2; - const newCx = newNode.x + newNode.width / 2; - const newCy = newNode.y + newNode.height / 2; - - // Ratios for "Inside" elements - const ratioX = oldNode.width > 1 ? newNode.width / oldNode.width : 1; - const ratioY = oldNode.height > 1 ? newNode.height / oldNode.height : 1; - - ea.copyViewElementsToEAforEditing(decorations); - - decorations.forEach(dec => { - const el = ea.getElement(dec.id); - if (!el) return; - - const decCx = dec.x + dec.width / 2; - const decCy = dec.y + dec.height / 2; - - // Determine relative position (normalized -1 to 1) - const relX = (decCx - oldCx) / (oldNode.width / 2); - const relY = (decCy - oldCy) / (oldNode.height / 2); - - // Inside check: Scale relative to center if within bounds - const isInside = Math.abs(relX) <= 1.05 && Math.abs(relY) <= 1.05; - - if (isInside) { - const dx = decCx - oldCx; - const dy = decCy - oldCy; - const newDx = dx * ratioX; - const newDy = dy * ratioY; - el.x = (newCx + newDx) - el.width / 2; - el.y = (newCy + newDy) - el.height / 2; - } else { - // Outside: Anchor to nearest edge to preserve gap - // Determine primary axis of separation - if (Math.abs(relX) > Math.abs(relY)) { - // Horizontal (Left/Right) - const sign = Math.sign(relX); - const oldEdgeX = oldCx + (sign * oldNode.width / 2); - const gapX = decCx - oldEdgeX; // Preserve this gap - const newEdgeX = newCx + (sign * newNode.width / 2); - const newDecCx = newEdgeX + gapX; - - el.x = newDecCx - el.width / 2; - // For the minor axis (Y), scale relative to center to keep alignment - el.y = (newCy + (decCy - oldCy) * ratioY) - el.height / 2; - } else { - // Vertical (Top/Bottom) - const sign = Math.sign(relY); - const oldEdgeY = oldCy + (sign * oldNode.height / 2); - const gapY = decCy - oldEdgeY; // Preserve this gap - const newEdgeY = newCy + (sign * newNode.height / 2); - const newDecCy = newEdgeY + gapY; - - el.y = newDecCy - el.height / 2; - // For the minor axis (X), scale relative to center - el.x = (newCx + (decCx - oldCx) * ratioX) - el.width / 2; - } - } - }); -}; - -let storedZoom = { - elementID: undefined, - level: undefined -} -const nextZoomLevel = (current) => { - const idx = ZOOM_TYPES.indexOf(current); - return idx === -1 ? ZOOM_TYPES[0] : ZOOM_TYPES[(idx + 1) % ZOOM_TYPES.length]; -}; - -const zoomToFit = (mode) => { - if (!isViewSet()) return; - let sel = getMindmapNodeFromSelection(); - - // Fallback to most recently selected if nothing is currently selected - if (!sel && mostRecentlySelectedNodeID) { - const fallback = ea.getViewElements().find(el => el.id === mostRecentlySelectedNodeID); - if (fallback) { - sel = fallback; - selectNodeInView(sel); - focusInputEl(); - } else { - mostRecentlySelectedNodeID = null; - } - } - - if (sel) { - let nextLevel = zoomLevel; - if (typeof mode === "string") { - nextLevel = mode; - } else if (!!mode && storedZoom.elementID === sel.id) { - nextLevel = nextZoomLevel(storedZoom.level ?? zoomLevel); - } - storedZoom = { - elementID: sel.id, - level: nextLevel - } - - const targetZoom = getZoom(nextLevel); - - // Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API - if (!ea.verifyMinimumPluginVersion("2.26.0")) { - api().scrollToContent([sel], { - fitToViewport: true, - viewportZoomFactor: targetZoom, - animate: true - }); - } else { - // For the new API, we calculate a target rect centered on the element - // with dimensions that will force 'fit: "contain"' to reach our target zoom. - const appState = api().getAppState(); - const targetW = appState.width / targetZoom; - const targetH = appState.height / targetZoom; - const cx = sel.x + sel.width / 2; - const cy = sel.y + sel.height / 2; - - api().setViewport({ - target: { - x: cx - targetW / 2, - y: cy - targetH / 2, - width: targetW, - height: targetH - }, - fit: "contain", - animation: true - }); - } - } -} - -const focusSelected = () => { - if (!isViewSet()) return; - let sel = getMindmapNodeFromSelection(); - - // Fallback to most recently selected if nothing is currently selected - if (!sel) { - if (!mostRecentlySelectedNodeID) { - const roots = getMasterRoots(); - if (roots.length > 0) { - mostRecentlySelectedNodeID = roots[0]; - } - if (!mostRecentlySelectedNodeID) return; - } - const fallback = ea.getViewElements().find(el => el.id === mostRecentlySelectedNodeID); - if (fallback) { - sel = fallback; - selectNodeInView(sel); - focusInputEl(); - } else { - mostRecentlySelectedNodeID = null; - } - } - - if (!sel) return; - - // Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API - if (!ea.verifyMinimumPluginVersion("2.26.0")) { - api().scrollToContent(sel, { - fitToContent: false, - animate: true, - }); - } else { - // fit: "none" recenters at the current zoom without changing it - api().setViewport({ - target: [sel], - fit: "none", - animation: true - }); - } -}; - -const getMindmapOrder = (node) => { - const o = node?.customData?.mindmapOrder; - return typeof o === "number" && Number.isFinite(o) ? o : 0; -}; - -const getNodeBox = (node, allElements) => { - if (node.groupIds && node.groupIds.length > 0) { - const groupElements = ea.getElementsInTheSameGroupWithElement(node, allElements); - if (groupElements.length > 1) { - const box = ExcalidrawLib.getCommonBoundingBox(groupElements); - return { - ...box, - elements: groupElements, - isGroup: true - }; - } - } - return { - minX: node.x, - minY: node.y, - width: node.width, - height: node.height, - elements: [node], - isGroup: false - }; -}; - -const sortChildrenStable = (children, allElements) => { - children.sort((a, b) => { - const ao = getMindmapOrder(a), - bo = getMindmapOrder(b); - if (ao !== bo) return ao - bo; - // Fallback sort by Y position (visual order) - const ya = allElements ? getNodeBox(a, allElements).minY : a.y; - const yb = allElements ? getNodeBox(b, allElements).minY : b.y; - const dy = ya - yb; - if (dy !== 0) return dy; - return String(a.id).localeCompare(String(b.id)); - }); -}; - -const getSubtreeHeight = (nodeId, allElements, childrenByParent, heightCache, elementById) => { - if (heightCache?.has(nodeId)) return heightCache.get(nodeId); - - const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); - if (!node) return 0; - - if (node.customData?.isFolded) { - const foldedHeight = node.height; - if (heightCache) heightCache.set(nodeId, foldedHeight); - return foldedHeight; - } - - // Bypass calculation and use the true visual bounding box for manual submaps - if (node.customData?.isAdditionalRoot && node.customData?.autoLayoutDisabled) { - const branchIds = getBranchElementIds(nodeId, allElements); - const branchElements = allElements.filter(el => branchIds.includes(el.id) && el.opacity > 0 && !el.isDeleted); - const bbox = ea.getBoundingBox(branchElements); - const height = bbox.height; - if (heightCache) heightCache.set(nodeId, height); - return height; - } - - const children = childrenByParent?.get(nodeId) ?? getChildrenNodes(nodeId, allElements); - const unpinnedChildren = children.filter(child => !child.customData?.isPinned); - - let totalHeight = 0; - - if (unpinnedChildren.length === 0) { - totalHeight = node.height; - } else { - let childrenHeight = 0; - unpinnedChildren.forEach((child, index) => { - childrenHeight += getSubtreeHeight(child.id, allElements, childrenByParent, heightCache, elementById); - if (index < unpinnedChildren.length - 1) { - const childNode = elementById?.get(child.id) ?? allElements.find((el) => el.id === child.id); - - // Check if child behaves as a leaf (ignoring pinned descendants) - const grandChildren = childrenByParent?.get(child.id) ?? getChildrenNodes(child.id, allElements); - const hasUnpinnedGrandChildren = grandChildren.some(gc => !gc.customData?.isPinned); - - const fontSize = childNode.fontSize ?? 20; - const gap = !hasUnpinnedGrandChildren ? Math.round(fontSize * layoutSettings.GAP_MULTIPLIER) : layoutSettings.GAP_Y; - childrenHeight += gap; - } - }); - totalHeight = Math.max(node.height, childrenHeight); - } - - // Feature: Boundary Spacing - // If the node has a visual boundary, add padding to the total subtree height - // The boundary adds 15px padding on all sides (see updateNodeBoundary), so we add 2*15=30px - if (node.customData?.boundaryId) { - totalHeight += 30; - } - - if (heightCache) heightCache.set(nodeId, totalHeight); - return totalHeight; -}; - -const getSubtreeWidth = (nodeId, allElements, childrenByParent, widthCache, elementById) => { - if (widthCache?.has(nodeId)) return widthCache.get(nodeId); - - const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); - if (!node) return 0; - - if (node.customData?.isFolded) { - const foldedWidth = node.width; - if (widthCache) widthCache.set(nodeId, foldedWidth); - return foldedWidth; - } - - const children = childrenByParent?.get(nodeId) ?? getChildrenNodes(nodeId, allElements); - const unpinnedChildren = children.filter(child => !child.customData?.isPinned); - - let totalWidth = 0; - - if (unpinnedChildren.length === 0) { - totalWidth = node.width; - } else { - let childrenWidth = 0; - unpinnedChildren.forEach((child, index) => { - childrenWidth += getSubtreeWidth(child.id, allElements, childrenByParent, widthCache, elementById); - if (index < unpinnedChildren.length - 1) { - const childNode = elementById?.get(child.id) ?? allElements.find((el) => el.id === child.id); - - // Check if child behaves as a leaf (ignoring pinned descendants) - const grandChildren = childrenByParent?.get(child.id) ?? getChildrenNodes(child.id, allElements); - const hasUnpinnedGrandChildren = grandChildren.some(gc => !gc.customData?.isPinned); - - const fontSize = childNode.fontSize ?? 20; - // For vertical layouts, we reuse GAP_Y as the horizontal sibling gap to maintain proportion - const gap = !hasUnpinnedGrandChildren ? Math.round(fontSize * layoutSettings.GAP_MULTIPLIER) : layoutSettings.GAP_Y; - childrenWidth += gap; - } - }); - totalWidth = Math.max(node.width, childrenWidth); - } - - // Feature: Boundary Spacing - // If the node has a visual boundary, add padding to the total subtree height - // The boundary adds 15px padding on all sides (see updateNodeBoundary), so we add 2*15=30px - if (node.customData?.boundaryId) { - totalWidth += 30; - } - - if (widthCache) widthCache.set(nodeId, totalWidth); - return totalWidth; -}; - -const getVerticalPlacementWidth = (nodeId, allElements, childrenByParent, widthCache, elementById, placementWidthCache = null) => { - if (placementWidthCache?.has(nodeId)) return placementWidthCache.get(nodeId); - - const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); - if (!node) return 0; - - const baseWidth = getSubtreeWidth(nodeId, allElements, childrenByParent, widthCache, elementById); - - // Short-circuit if this is a manual submap - if (node.customData?.isAdditionalRoot !== true || node.customData?.autoLayoutDisabled === true) { - if (placementWidthCache) placementWidthCache.set(nodeId, baseWidth); - return baseWidth; - } - - const mode = node.customData?.growthMode; - if (!["Right-facing", "Left-facing", "Right-Left"].includes(mode)) { - if (placementWidthCache) placementWidthCache.set(nodeId, baseWidth); - return baseWidth; - } - - const children = childrenByParent?.get(nodeId) ?? getChildrenNodes(nodeId, allElements); - const unpinnedChildren = children.filter(child => !child.customData?.isPinned); - if (unpinnedChildren.length === 0) { - if (placementWidthCache) placementWidthCache.set(nodeId, baseWidth); - return baseWidth; - } - - const childWidths = unpinnedChildren.map((child) => - getVerticalPlacementWidth(child.id, allElements, childrenByParent, widthCache, elementById, placementWidthCache) - ); - - const primaryGap = layoutSettings.GAP_X; - const compactMinWidth = node.width + layoutSettings.GAP_Y * 2; - let projectedWidth; - - if (mode === "Right-facing" || mode === "Left-facing") { - const maxChildWidth = childWidths.reduce((max, width) => Math.max(max, width), 0); - const directionalRawWidth = Math.max(node.width, node.width + primaryGap + maxChildWidth); - // Single-sided directional submaps mostly expand away from siblings. - // Compress their reserved slot width to avoid over-spacing in vertical parent layout. - const singleSideBlend = layoutSettings.VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE ?? LAYOUT_METADATA.VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE.def; - projectedWidth = Math.max( - compactMinWidth, - node.width + (directionalRawWidth - node.width) * singleSideBlend, - ); - } else { - const nodeCenterX = node.x + node.width / 2; - let leftMax = 0; - let rightMax = 0; - - unpinnedChildren.forEach((child, index) => { - const childCenterX = child.x + child.width / 2; - if (childCenterX < nodeCenterX) { - leftMax = Math.max(leftMax, childWidths[index]); - } else { - rightMax = Math.max(rightMax, childWidths[index]); - } - }); - - const directionalRawWidth = node.width + - (leftMax > 0 ? primaryGap + leftMax : 0) + - (rightMax > 0 ? primaryGap + rightMax : 0); - // Dual-sided maps need more reserved width than single-sided ones, but still less than full bbox width. - const dualSideBlend = layoutSettings.VERTICAL_SUBTREE_WIDTH_BLEND_DUAL ?? LAYOUT_METADATA.VERTICAL_SUBTREE_WIDTH_BLEND_DUAL.def; - projectedWidth = Math.max( - compactMinWidth, - node.width + (Math.max(node.width, directionalRawWidth) - node.width) * dualSideBlend, - ); - } - - if (node.customData?.boundaryId) { - projectedWidth += 30; - } - - const effectiveWidth = Math.min(baseWidth, projectedWidth); - - // Smooth width growth so adding the 2nd/3rd child does not suddenly blow up sibling spacing. - const widthExtra = Math.max(0, effectiveWidth - node.width); - const smoothThresholdMultiplier = layoutSettings.VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER ?? LAYOUT_METADATA.VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER.def; - const softThreshold = Math.max( - layoutSettings.GAP_X, - layoutSettings.GAP_Y * smoothThresholdMultiplier, - ); - - let smoothedWidth = effectiveWidth; - if (widthExtra > softThreshold) { - const smoothMinScale = layoutSettings.VERTICAL_SUBTREE_SMOOTH_MIN_SCALE ?? LAYOUT_METADATA.VERTICAL_SUBTREE_SMOOTH_MIN_SCALE.def; - const compressionScale = Math.max(smoothMinScale, layoutSettings.GAP_X * 2); - const remaining = widthExtra - softThreshold; - const compressedRemaining = compressionScale * Math.log1p(remaining / compressionScale); - smoothedWidth = node.width + softThreshold + compressedRemaining; - } - - if (placementWidthCache) placementWidthCache.set(nodeId, smoothedWidth); - return smoothedWidth; -}; - -/** - * Determines if an element is part of the mindmap structure. - */ -const isStructuralElement = (el, allElements, rootId = null, elementById = null, parentMap = null) => { - const isStructuralType = el.customData?.isBranch || el.customData?.growthMode || el.customData?.isBoundary || typeof el.customData?.mindmapOrder !== "undefined"; - - if (rootId && isStructuralType) { - let targetEl = el; - - if (el.type === "arrow" && el.customData?.isBranch) { - const targetId = el.endBinding?.elementId || el.startBinding?.elementId; - if (targetId) { - targetEl = elementById?.get(targetId) || allElements.find(e => e.id === targetId); - } - } - - if (!targetEl) return false; - - // Pass maps to getHierarchy to prevent O(N) lookups - const info = getHierarchy(targetEl, allElements, elementById, parentMap); - if (info?.rootId === rootId) return true; - if (info?.rootId) return false; - } - - if (!rootId && isStructuralType) return true; - - const connectedArrow = allElements.find(a => - a.type === "arrow" && - a.customData?.isBranch && - (a.startBinding?.elementId === el.id || a.endBinding?.elementId === el.id) - ); - return !!connectedArrow; -}; - -const getViewGroupElements = (groupID) => { - return ea.getViewElements().filter(el => el.groupIds.includes(groupID)); -} - -const getCommonGroupForElements = (elements) => { - const groupIds = elements - .map(el => el.groupIds) - .reduce((prev, cur) => cur.filter(v => prev.includes(v))); - return groupIds; -}; - -/** - * A group is considered a "Mindmap Group" if it contains at least 2 structural elements. - * Groups with only 1 structural element (e.g. a Node grouped with a Sticker) are treated as decoration. - */ -const isMindmapGroup = (groupId, allElements) => { - const groupEls = allElements.filter(el => el.groupIds?.includes(groupId)); - const structuralCount = groupEls.filter(el => isStructuralElement(el, allElements)).length; - return structuralCount >= 2; -}; - -const collectCrosslinkIds = (allElements) => new Set( - allElements - .filter(el => el.type === "arrow" && !el.customData?.isBranch && el.startBinding?.elementId && el.endBinding?.elementId) - .map(el => el.id) -); - -const collectDecorationIds = (allElements, rootId) => new Set( - allElements - .filter(el => el.groupIds && el.groupIds.length > 0 && !isStructuralElement(el, allElements, rootId)) - .map(el => el.id) -); - -/** - * Finds the first group ID in the element's group stack that qualifies as a Mindmap Group. - */ -const getStructuralGroup = (element, allElements, rootId) => { - if (!element.groupIds || element.groupIds.length === 0) return null; - return element.groupIds.find(gid => isMindmapGroup(gid, allElements)); -}; - -const applyRecursiveGrouping = (nodeId, allElements) => { - const children = getChildrenNodes(nodeId, allElements); - const nodeIdsInSubtree = [nodeId]; - - const node = allElements.find(el => el.id === nodeId); - if (node?.customData?.boundaryId) { - nodeIdsInSubtree.push(node.customData.boundaryId); - } - - children.forEach((child) => { - const subtreeIds = applyRecursiveGrouping(child.id, allElements); - nodeIdsInSubtree.push(...subtreeIds); - - // Find the arrow connecting nodeId to child - const arrow = allElements.find( - (a) => - a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === nodeId && - a.endBinding?.elementId === child.id, - ); - if (arrow) { - nodeIdsInSubtree.push(arrow.id); - } - }); - - // Apply group in EA workbench - if (nodeIdsInSubtree.length > 1) { - ea.addToGroup(nodeIdsInSubtree); - } - - return nodeIdsInSubtree; -}; - -// Monotone Chain Convex Hull Algorithm -const getConvexHull = (points) => { - points.sort((a, b) => a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]); - - const n = points.length; - if (n <= 2) return points; - - const cross = (a, b, o) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); - - const lower = []; - for (let i = 0; i < n; i++) { - while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], points[i]) <= 0) { - lower.pop(); - } - lower.push(points[i]); - } - - const upper = []; - for (let i = n - 1; i >= 0; i--) { - while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], points[i]) <= 0) { - upper.pop(); - } - upper.push(points[i]); - } - - upper.pop(); - lower.pop(); - return lower.concat(upper); -}; - -const updateNodeBoundary = (node, allElements, rootId) => { - const boundaryId = node.customData?.boundaryId; - - if (!boundaryId) { - return; - } - - if (node.opacity === 0) return; - - const ids = getBranchElementIds(node.id, allElements); - - const branchElements = allElements.filter(el => - ids.includes(el.id) && - el.id !== boundaryId && - el.opacity > 0 && - !el.isDeleted - ); - - if (branchElements.length === 0) return; - - const root = allElements.find(el => el.id === rootId); - const growthMode = root?.customData?.growthMode || currentModalGrowthMode; - const isVerticalBoundaryMode = growthMode === "Up-facing" || growthMode === "Down-facing" || growthMode === "Up-Down"; - - const padding = 15; - let allPoints = []; - - branchElements.forEach(el => { - if (isVerticalBoundaryMode && el.type === "arrow" && Array.isArray(el.points) && el.points.length > 0) { - el.points.forEach(([px, py]) => { - const x = el.x + px; - const y = el.y + py; - allPoints.push([x - padding, y - padding]); - allPoints.push([x + padding, y - padding]); - allPoints.push([x + padding, y + padding]); - allPoints.push([x - padding, y + padding]); - }); - return; - } - - const x1 = el.x - padding; - const y1 = el.y - padding; - const x2 = el.x + el.width + padding; - const y2 = el.y + el.height + padding; - - allPoints.push([x1, y1]); - allPoints.push([x2, y1]); - allPoints.push([x2, y2]); - allPoints.push([x1, y2]); - }); - - const hullPoints = getConvexHull(allPoints); - - if (hullPoints.length < 3) return; - - // Subdivide long segments to tame the bezier curve over-extension - const subdividedPoints = []; - const MAX_SEGMENT_LENGTH = layoutSettings.MAX_SEGMENT_LENGTH ?? LAYOUT_METADATA.MAX_SEGMENT_LENGTH.def; - for (let i = 0; i < hullPoints.length; i++) { - const p1 = hullPoints[i]; - const p2 = hullPoints[(i + 1) % hullPoints.length]; - subdividedPoints.push(p1); - - const dist = Math.hypot(p2[0] - p1[0], p2[1] - p1[1]); - if (dist > MAX_SEGMENT_LENGTH) { - const steps = Math.ceil(dist / MAX_SEGMENT_LENGTH); - for (let j = 1; j < steps; j++) { - subdividedPoints.push([ - p1[0] + (p2[0] - p1[0]) * (j / steps), - p1[1] + (p2[1] - p1[1]) * (j / steps) - ]); - } - } - } - - let minX = Infinity, - minY = Infinity, - maxX = -Infinity, - maxY = -Infinity; - // Calculate bounding box using the original hull points - hullPoints.forEach(p => { - if (p[0] < minX) minX = p[0]; - if (p[1] < minY) minY = p[1]; - if (p[0] > maxX) maxX = p[0]; - if (p[1] > maxY) maxY = p[1]; - }); - - const w = maxX - minX; - const h = maxY - minY; - - let boundaryEl = ea.getElement(boundaryId); - - if (!boundaryEl) return; - - boundaryEl.x = minX; - boundaryEl.y = minY; - boundaryEl.width = w; - boundaryEl.height = h; - - // Use the newly subdivided points for the final path - const normalizedPoints = subdividedPoints.map(p => [p[0] - minX, p[1] - minY]); - normalizedPoints.push([normalizedPoints[0][0], normalizedPoints[0][1]]); // Close loop - boundaryEl.points = normalizedPoints; - - boundaryEl.roundness = arrowType === "curved" ? { - type: 2 - } : null; - boundaryEl.polygon = true; - boundaryEl.locked = false; - - if (node.groupIds.length > 0 && isMindmapGroup(node.groupIds[0], allElements)) { - if (!boundaryEl.groupIds || boundaryEl.groupIds.length === 0 || boundaryEl.groupIds[0] !== node.groupIds[0]) { - boundaryEl.groupIds = [node.groupIds[0]]; - } - } else { - boundaryEl.groupIds = []; - } -}; - -const addEmbeddableNode = ({ - px = 0, - py = 0, - url, - depth -}) => { - isWikiLink = url.startsWith("[["); - const width = isWikiLink ? - (depth === 0 ? EMBEDED_OBJECT_WIDTH_ROOT : EMBEDED_OBJECT_WIDTH_CHILD) : - EMBEDED_OBJECT_WIDTH_CHILD; - const height = isWikiLink ? - width / 2 : - 0; // Height 0 triggers auto-calculation based on aspect ratio - const embeddableId = ea.addEmbeddable(px, py, width, height, url); - if (isWikiLink) { - ea.getElement(embeddableId).scale = depth === 0 ? [0.5, 0.5] : [0.3, 0.3]; - } - return embeddableId; -} - -const updateRootNodeCustomData = async (data, sel) => { - if (!sel) sel = getMindmapNodeFromSelection(); - if (sel) { - const allElements = ea.getViewElements(); - const settingsRoot = getSettingsRootNode(sel, allElements); - if (!settingsRoot) return null; - - ea.copyViewElementsToEAforEditing(allElements.filter((e) => e.id === settingsRoot.id)); - ea.addAppendUpdateCustomData(settingsRoot.id, { - ...data - }); - await addElementsToView({ - captureUpdate: "NEVER" - }); - updateUI(); - const info = getHierarchy(settingsRoot, ea.getViewElements()); - return { - ...info, - rootId: settingsRoot.id, - settingsRootId: settingsRoot.id, - }; - } - return null; -} - -/** - * Recursively updates the stroke width of a subtree. - * Checks if the existing arrow matches the 'old' calculated width. - * If it does, updates to 'new' width. If not, assumes manual override and skips. - */ -const updateBranchStrokes = async (rootId, oldBaseWidth, oldScaleMode, newBaseWidth, newScaleMode) => { - if (!isViewSet()) return; - const allElements = ea.getViewElements(); - const root = allElements.find(el => el.id === rootId); - if (!root) return; - - const elementsToUpdate = []; - let manualOverrideFound = false; - - const traverse = (nodeId, depth) => { - const children = getChildrenNodes(nodeId, allElements); - - children.forEach(child => { - // Find the arrow connecting parent (nodeId) to child - const arrow = allElements.find( - a => a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === nodeId && - a.endBinding?.elementId === child.id - ); - - if (arrow) { - // Calculate what the width *should* have been under old settings - // Note: 'depth' is parent depth. Arrow depth in addNode logic was 'depth' (where parent is depth-1). - // In addNode: - // if !parent (root), depth=0. - // if parent, info=getHierarchy(parent), depth = info.depth + 1. - // strokeWidth = getStrokeWidthForDepth(depth). - // So the arrow leading TO the node at 'depth' uses 'depth' for calculation. - // Here, 'child' is at depth + 1 relative to 'nodeId' (which is at 'depth'). - const childDepth = depth + 1; - - const expectedOldWidth = calculateStrokeWidth(childDepth, oldBaseWidth, oldScaleMode); - - // Allow a small floating point tolerance - if (Math.abs(arrow.strokeWidth - expectedOldWidth) < 0.05) { - const newWidth = calculateStrokeWidth(childDepth, newBaseWidth, newScaleMode); - if (Math.abs(arrow.strokeWidth - newWidth) > 0.001) { - elementsToUpdate.push({ - id: arrow.id, - strokeWidth: newWidth - }); - } - } else { - // If it doesn't match old width, check if it matches new width (already updated?) - const expectedNewWidth = calculateStrokeWidth(childDepth, newBaseWidth, newScaleMode); - if (Math.abs(arrow.strokeWidth - expectedNewWidth) >= 0.05) { - manualOverrideFound = true; - } - } - } - - traverse(child.id, depth + 1); - }); - }; - - traverse(rootId, 0); - - if (elementsToUpdate.length > 0) { - ea.copyViewElementsToEAforEditing(elementsToUpdate.map(i => allElements.find(e => e.id === i.id))); - elementsToUpdate.forEach(item => { - const el = ea.getElement(item.id); - if (el) el.strokeWidth = item.strokeWidth; - }); - await addElementsToView({ - captureUpdate: "IMMEDIATELY" - }); - } - - if (manualOverrideFound) { - new Notice(t("NOTICE_BRANCH_WIDTH_MANUAL_OVERRIDE")); - } -}; - -const addUpdateArrowLabel = (arrow, text) => { - if (!arrow) { - return; - } - const maybeTextElement = ea.getBoundTextElement(arrow, true); - let textElement = maybeTextElement.eaElement; - if (!textElement && maybeTextElement.sceneElement) { - ea.copyViewElementsToEAforEditing([maybeTextElement.sceneElement]); - textElement = ea.getElement(maybeTextElement.sceneElement.id); - } - if (textElement) { - if (!text) { - textElement.isDeleted = true; - } else { - textElement.rawText = text; - textElement.text = text; - textElement.originalText = text; - } - return; - } - if (!text) { - return; - } - const x = arrow.x + arrow.width / 2; - const y = arrow.y + arrow.height / 2; - const textId = ea.addText(x, y, text); - const textEl = ea.getElement(textId); - - textEl.strokeColor = arrow.strokeColor; - textEl.containerId = arrow.id; - textEl.textAlign = "center"; - textEl.textVerticalAlign = "middle"; - textEl.fontSize = Math.floor(textEl.fontSize / 2); - - arrow.boundElements = [{ - type: "text", - id: textId - }]; -} - -const configureArrow = (context) => { - const { - arrowId, - isChildRight, - isChildBelow, - startId, - endId, - coordinates, - isRadial, - layoutDirection - } = context; - const { - sX, - sY, - eX, - eY - } = coordinates; - - const eaArrow = ea.getElement(arrowId); - const isVertical = layoutDirection === "vertical"; - - if (isVertical) { - // Configure Binding Points (using .0001/.9999 to avoid jumping effect) - // In Radial mode, bind to the center (0.5) of the root node - const startRatio = isRadial ? 0.50001 : (isChildBelow ? 0.9999 : 0.0001); - const endRatio = isChildBelow ? 0.0001 : 0.9999; - const centerRatio = 0.5001; - - eaArrow.startBinding = { - ...eaArrow.startBinding, - elementId: startId, - mode: "orbit", - fixedPoint: [centerRatio, startRatio] - }; - - eaArrow.endBinding = { - ...eaArrow.endBinding, - elementId: endId, - mode: "orbit", - fixedPoint: [centerRatio, endRatio] - }; - - eaArrow.x = sX; - eaArrow.y = sY; - - const dx = eX - sX; - const dy = eY - sY; - - if (arrowType === "straight") { - eaArrow.roundness = null; - eaArrow.points = [ - [0, 0], - [dx, dy] - ]; - } else { - eaArrow.roundness = { - type: 2 - }; - if (isRadial) { - // Swapped coefficients for vertical curve: Y progresses faster than X initially - eaArrow.points = [ - [0, 0], - [dx * 0.75, dy * 2 / 3], - [dx, dy] - ]; - } else { - // Swapped coefficients for vertical curve: Y progresses faster than X initially - // This ensures lines shoot out vertically first before fanning out horizontally - eaArrow.points = [ - [0, 0], - [dx * 0.25, dy / 3], - [dx * 0.75, dy * 2 / 3], - [dx, dy] - ]; - } - } - } else { - // Standard horizontal logic - // Configure Binding Points (using .0001/.9999 to avoid jumping effect) - // In Radial mode, bind to the center (0.5) of the root node - const startRatio = isRadial ? 0.50001 : (isChildRight ? 0.9999 : 0.0001); - const endRatio = isChildRight ? 0.0001 : 0.9999; - const centerYRatio = 0.5001; - - eaArrow.startBinding = { - ...eaArrow.startBinding, - elementId: startId, - mode: "orbit", - fixedPoint: [startRatio, centerYRatio] - }; - - eaArrow.endBinding = { - ...eaArrow.endBinding, - elementId: endId, - mode: "orbit", - fixedPoint: [endRatio, centerYRatio] - }; - - eaArrow.x = sX; - eaArrow.y = sY; - - const dx = eX - sX; - const dy = eY - sY; - - if (arrowType === "straight") { - eaArrow.roundness = null; - eaArrow.points = [ - [0, 0], - [dx, dy] - ]; - } else { - eaArrow.roundness = { - type: 2 - }; - if (isRadial) { - eaArrow.points = [ - [0, 0], - [dx * 2 / 3, dy * 0.75], - [dx, dy] - ]; - } else { - // Standard horizontal curve: X progresses faster than Y initially - eaArrow.points = [ - [0, 0], - [dx / 3, dy * 0.25], - [dx * 2 / 3, dy * 0.75], - [dx, dy] - ]; - } - } - } -}; - -/** - * Layout entrypoint for nodes marked as additional roots. - * The node position itself is controlled by the parent/root layout pass. - * Only its descendants are laid out using this node's local root settings. - */ -const layoutChildrenAsAdditionalRoot = (nodeId, allElements, hasGlobalFolds, childrenByParent, heightCache, widthCache, elementById, mustHonorMindmapOrder = false, parentMap = null) => { - const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); - if (!node || node.customData?.isAdditionalRoot !== true) return false; - - const l1Nodes = getChildrenNodes(nodeId, allElements); - if (l1Nodes.length === 0) return false; - - // Apply local submap settings for this subtree only. - withRootLayoutContext(node, (cfg) => { - const localHeightCache = heightCache ?? new Map(); - const localWidthCache = widthCache ?? new Map(); - const eaNode = ea.getElement(nodeId); - if (!eaNode) return; - - const rootBox = getNodeBox(eaNode, allElements); - const rootCenter = { - x: rootBox.minX + rootBox.width / 2, - y: rootBox.minY + rootBox.height / 2, - }; - - const mode = cfg.growthMode; - const layoutContext = { - allElements, - rootId: nodeId, - rootBox, - rootCenter, - hasGlobalFolds, - mode, - childrenByParent, - heightCache: localHeightCache, - widthCache: localWidthCache, - elementById, - parentMap, - }; - - // If order is not explicitly locked by an operation, sync to visual sequence. - if (!mustHonorMindmapOrder) { - sortL1NodesBasedOnVisualSequence(l1Nodes, mode, rootCenter); - } - - if (mode === "Radial") { - layoutL1Nodes(l1Nodes, { - sortMethod: "radial", - centerAngle: null, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_RADIAL, - fillSweep: cfg.fillSweep, - }, layoutContext, mustHonorMindmapOrder); - return; - } - - if (["Right-facing", "Left-facing", "Right-Left"].includes(mode)) { - const leftNodes = []; - const rightNodes = []; - - if (mode === "Right-Left") { - l1Nodes.forEach((child) => { - const childCX = child.x + child.width / 2; - if (childCX > rootCenter.x) rightNodes.push(child); - else leftNodes.push(child); - }); - - // If all children are on one side (e.g. after fresh conversion), balance using order. - if ((leftNodes.length === 0 || rightNodes.length === 0) && l1Nodes.length > 1) { - leftNodes.length = 0; - rightNodes.length = 0; - const splitIdx = Math.ceil(l1Nodes.length / 2); - l1Nodes.forEach((child, i) => { - if (i < splitIdx) rightNodes.push(child); - else leftNodes.push(child); - }); - } - } else if (mode === "Left-facing") { - l1Nodes.forEach((child) => leftNodes.push(child)); - } else { - l1Nodes.forEach((child) => rightNodes.push(child)); - } - - if (rightNodes.length > 0) { - layoutL1Nodes(rightNodes, { - sortMethod: "vertical", - centerAngle: 90, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_DIRECTIONAL - }, layoutContext, mustHonorMindmapOrder); - } - if (leftNodes.length > 0) { - layoutL1Nodes(leftNodes, { - sortMethod: "vertical", - centerAngle: 270, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_DIRECTIONAL - }, layoutContext, mustHonorMindmapOrder); - } - return; - } - - const upNodes = []; - const downNodes = []; - - if (mode === "Up-Down") { - l1Nodes.forEach((child) => { - const childCY = child.y + child.height / 2; - if (childCY > rootCenter.y) downNodes.push(child); - else upNodes.push(child); - }); - - if ((upNodes.length === 0 || downNodes.length === 0) && l1Nodes.length > 1) { - upNodes.length = 0; - downNodes.length = 0; - const splitIdx = Math.ceil(l1Nodes.length / 2); - l1Nodes.forEach((child, i) => { - if (i < splitIdx) downNodes.push(child); - else upNodes.push(child); - }); - } - } else if (mode === "Up-facing") { - l1Nodes.forEach((child) => upNodes.push(child)); - } else { - l1Nodes.forEach((child) => downNodes.push(child)); - } - - layoutContext.widthCache = new Map(); - - if (downNodes.length > 0) { - layoutL1Nodes(downNodes, { - sortMethod: "horizontal", - centerAngle: 90, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_DIRECTIONAL - }, layoutContext, mustHonorMindmapOrder); - } - if (upNodes.length > 0) { - layoutL1Nodes(upNodes, { - sortMethod: "horizontal", - centerAngle: 270, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_DIRECTIONAL - }, layoutContext, mustHonorMindmapOrder); - } - }); - - return true; -}; - -const layoutSubtree = (nodeId, targetX, targetCenterY, side, allElements, hasGlobalFolds, childrenByParent, heightCache, elementById, mustHonorMindmapOrder = false, rootId, parentMap = null) => { - const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); - const eaNode = ea.getElement(nodeId); - - const isPinned = node.customData?.isPinned === true; - let dx = 0, - dy = 0; - - if (!isPinned) { - const newX = side === 1 ? targetX : targetX - node.width; - const newY = targetCenterY - node.height / 2; - dx = newX - eaNode.x; - dy = newY - eaNode.y; - eaNode.x = newX; - eaNode.y = newY; - } - - if (node.customData?.isFolded) return; - - const currentX = eaNode.x; - const currentYCenter = eaNode.y + node.height / 2; - - let effectiveSide = side; - const parent = getParentNode(nodeId, allElements, parentMap); - - if (parent) { - const parentCenterX = parent.x + parent.width / 2; - const nodeCenterX = currentX + node.width / 2; - effectiveSide = nodeCenterX >= parentCenterX ? 1 : -1; - } - - // Handle Fold Indicator - if (node.customData?.foldIndicatorId) { - const ind = ea.getElement(node.customData.foldIndicatorId); - if (ind) { - if (effectiveSide === 1) { - ind.x = eaNode.x + eaNode.width + layoutSettings.INDICATOR_OFFSET; - ind.textAlign = "left"; - } else { - ind.x = eaNode.x - layoutSettings.INDICATOR_OFFSET - ind.width; - ind.textAlign = "right"; - } - ind.y = eaNode.y + eaNode.height / 2 - ind.height / 2; - } - } - - const textElement = ea.getBoundTextElement(eaNode).eaElement; - if (textElement && !centerText && textElement.textAlign !== "center") { - textElement.textAlign = effectiveSide === 1 ? "left" : "right"; - } - - const children = childrenByParent?.get(nodeId) ?? getChildrenNodes(nodeId, allElements); - - // Additional roots are laid out as independent local maps for their descendants. - // The additional-root node itself stays positioned by the parent layout pass. - if (node.customData?.isAdditionalRoot === true) { - if (node.customData?.autoLayoutDisabled) { - // Shift all descendants to maintain manual layout relative to this root - if (dx !== 0 || dy !== 0) { - const branchIds = getBranchElementIds(nodeId, allElements); - const descendants = branchIds.filter(id => id !== nodeId); - descendants.forEach(descId => { - const descNode = elementById?.get(descId) ?? allElements.find(e => e.id === descId); - // Do not shift pinned elements - if (descNode?.customData?.isPinned) return; - // Do not shift non-branch arrows because moveCrossLinks automatically handles them - if (descNode && descNode.type === "arrow" && !descNode.customData?.isBranch) return; - - if (!ea.getElement(descId)) { - if (descNode) ea.copyViewElementsToEAforEditing([descNode]); - } - const descEl = ea.getElement(descId); - if (descEl) { - descEl.x += dx; - descEl.y += dy; - } - }); - } - } else { - layoutChildrenAsAdditionalRoot(nodeId, allElements, hasGlobalFolds, childrenByParent, heightCache, null, elementById, mustHonorMindmapOrder, parentMap); - } - - if (node.customData?.boundaryId) { - updateNodeBoundary(node, ea.getElements(), rootId); - } - return; - } - - const unpinnedChildren = children.filter(child => !child.customData?.isPinned); - const pinnedChildren = children.filter(child => child.customData?.isPinned); - - if (unpinnedChildren.length > 0) { - // SORTING LOGIC: - // If mustHonorMindmapOrder is true: Explicitly sort by mindmapOrder to enforce the manual change. - // If mustHonorMindmapOrder is false: Fallback to visual Y-position to keep map strictly ordered by position (auto-layout). - unpinnedChildren.sort((a, b) => { - if (mustHonorMindmapOrder) { - return getMindmapOrder(a) - getMindmapOrder(b); - } - const dy = a.y - b.y; - if (dy !== 0) return dy; - return String(a.id).localeCompare(String(b.id)); - }); - - // Only update mindmapOrder to match visual reality if we are NOT in a manual sort operation - if (!mustHonorMindmapOrder) { - unpinnedChildren.forEach((child, i) => { - if (getMindmapOrder(child) !== i) { - ea.addAppendUpdateCustomData(child.id, { - mindmapOrder: i - }); - } - }); - } - - const subtreeHeight = getSubtreeHeight(nodeId, allElements, childrenByParent, heightCache, elementById); - let currentY = currentYCenter - subtreeHeight / 2; - const dynamicGapX = layoutSettings.GAP_X; - - unpinnedChildren.forEach((child) => { - const childH = getSubtreeHeight(child.id, allElements, childrenByParent, heightCache, elementById); - - layoutSubtree( - child.id, - effectiveSide === 1 ? currentX + node.width + dynamicGapX : currentX - dynamicGapX, - currentY + childH / 2, - effectiveSide, - allElements, - hasGlobalFolds, - childrenByParent, - heightCache, - elementById, - mustHonorMindmapOrder, - rootId, - parentMap, - ); - - const childNode = elementById?.get(child.id) ?? allElements.find((el) => el.id === child.id); - - const grandChildren = childrenByParent?.get(child.id) ?? getChildrenNodes(child.id, allElements); - const hasUnpinnedGrandChildren = grandChildren.some(gc => !gc.customData?.isPinned); - - const fontSize = childNode.fontSize ?? 20; - const gap = !hasUnpinnedGrandChildren ? Math.round(fontSize * layoutSettings.GAP_MULTIPLIER) : layoutSettings.GAP_Y; - - currentY += childH + gap; - }); - } - - pinnedChildren.forEach(child => layoutSubtree( - child.id, - child.x, - child.y + child.height / 2, - effectiveSide, - allElements, - hasGlobalFolds, - childrenByParent, - heightCache, - elementById, - mustHonorMindmapOrder, - rootId, - parentMap, - )); - - // Update Arrows - children.forEach(child => { - const arrow = allElements.find( - (a) => - a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === nodeId && - a.endBinding?.elementId === child.id, - ); - - if (arrow) { - const eaChild = ea.getElement(child.id); - const childCenterX = eaChild.x + eaChild.width / 2; - const parentCenterX = currentX + node.width / 2; - const isChildRight = childCenterX > parentCenterX; - - const sX = isChildRight ? currentX + node.width : currentX; - const sY = currentYCenter; - - const eX = isChildRight ? eaChild.x : eaChild.x + eaChild.width; - const eY = eaChild.y + eaChild.height / 2; - - configureArrow({ - arrowId: arrow.id, - isChildRight, - startId: node.id, - endId: child.id, - coordinates: { - sX, - sY, - eX, - eY - }, - }); - } - }); - - if (node.customData?.boundaryId) { - updateNodeBoundary(node, ea.getElements(), rootId); - } -}; - -const updateL1Arrow = (node, context, layoutDirection = "horizontal") => { - const { - rootId, - rootCenter, - mode - } = context; - - const arrow = ea.getElements().find( - (a) => - a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === rootId && - a.endBinding?.elementId === node.id, - ); - if (arrow) { - const childNode = ea.getElement(node.id); - const rootNode = ea.getElement(rootId); - - if (!childNode || !rootNode) return; - - const isRadial = mode === "Radial"; - - if (layoutDirection === "vertical") { - const childCenterY = childNode.y + childNode.height / 2; - const isChildBelow = childCenterY > rootCenter.y; - - // In Radial mode, start arrow from the center of the root node - const sX = rootCenter.x; - const sY = isRadial ? rootCenter.y : (isChildBelow ? rootNode.y + rootNode.height : rootNode.y); - - const eX = childNode.x + childNode.width / 2; - const eY = isChildBelow ? childNode.y : childNode.y + childNode.height; - - configureArrow({ - arrowId: arrow.id, - isChildBelow, - startId: rootId, - endId: node.id, - coordinates: { - sX, - sY, - eX, - eY - }, - isRadial, - layoutDirection - }); - } else { - const childCenterX = childNode.x + childNode.width / 2; - const isChildRight = childCenterX > rootCenter.x; - - // In Radial mode, start arrow from the center of the root node - const sX = isRadial ? rootCenter.x : (isChildRight ? rootNode.x + rootNode.width : rootNode.x); - const sY = rootCenter.y; - - const eX = isChildRight ? childNode.x : childNode.x + childNode.width; - const eY = childNode.y + childNode.height / 2; - - configureArrow({ - arrowId: arrow.id, - isChildRight, - startId: rootId, - endId: node.id, - coordinates: { - sX, - sY, - eX, - eY - }, - isRadial, - layoutDirection - }); - } - } -}; - -const layoutSubtreeVertical = (nodeId, targetCenterX, targetY, side, allElements, hasGlobalFolds, childrenByParent, widthCache, elementById, mustHonorMindmapOrder = false, rootId, parentMap = null) => { - const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); - const eaNode = ea.getElement(nodeId); - - const isPinned = node.customData?.isPinned === true; - let dx = 0, - dy = 0; - - if (!isPinned) { - const newX = targetCenterX - node.width / 2; - const newY = side === 1 ? targetY : targetY - node.height; - dx = newX - eaNode.x; - dy = newY - eaNode.y; - eaNode.x = newX; - eaNode.y = newY; - } - - if (node.customData?.isFolded) return; - - const currentXCenter = eaNode.x + node.width / 2; - const currentY = eaNode.y; - - let effectiveSide = side; - const parent = getParentNode(nodeId, allElements, parentMap); - - if (parent) { - const parentCenterY = parent.y + parent.height / 2; - const nodeCenterY = currentY + node.height / 2; - effectiveSide = nodeCenterY >= parentCenterY ? 1 : -1; - } - - // Handle Fold Indicator - if (node.customData?.foldIndicatorId) { - const ind = ea.getElement(node.customData.foldIndicatorId); - if (ind) { - ind.x = eaNode.x + eaNode.width / 2 - ind.width / 2; - if (effectiveSide === 1) { - ind.y = eaNode.y + eaNode.height + layoutSettings.INDICATOR_OFFSET; - ind.textAlign = "center"; - } else { - ind.y = eaNode.y - layoutSettings.INDICATOR_OFFSET - ind.height; - ind.textAlign = "center"; - } - } - } - - const textElement = ea.getBoundTextElement(eaNode).eaElement; - if (textElement && !centerText && textElement.textAlign !== "center") { - // In vertical mode, nodes usually look best centered, but we enforce it here - textElement.textAlign = "center"; - } - - const children = childrenByParent?.get(nodeId) ?? getChildrenNodes(nodeId, allElements); - - // Additional roots are laid out as independent local maps for their descendants. - // The additional-root node itself stays positioned by the parent layout pass. - if (node.customData?.isAdditionalRoot === true) { - if (node.customData?.autoLayoutDisabled) { - // Shift all descendants to maintain manual layout relative to this root - if (dx !== 0 || dy !== 0) { - const branchIds = getBranchElementIds(nodeId, allElements); - const descendants = branchIds.filter(id => id !== nodeId); - descendants.forEach(descId => { - const descNode = elementById?.get(descId) ?? allElements.find(e => e.id === descId); - // Do not shift pinned elements - if (descNode?.customData?.isPinned) return; - // Do not shift non-branch arrows because moveCrossLinks automatically handles them - if (descNode && descNode.type === "arrow" && !descNode.customData?.isBranch) return; - - if (!ea.getElement(descId)) { - if (descNode) ea.copyViewElementsToEAforEditing([descNode]); - } - const descEl = ea.getElement(descId); - if (descEl) { - descEl.x += dx; - descEl.y += dy; - } - }); - } - } else { - layoutChildrenAsAdditionalRoot(nodeId, allElements, hasGlobalFolds, childrenByParent, null, widthCache, elementById, mustHonorMindmapOrder, parentMap); - } - - if (node.customData?.boundaryId) { - updateNodeBoundary(node, ea.getElements(), rootId); - } - return; - } - - const unpinnedChildren = children.filter(child => !child.customData?.isPinned); - const pinnedChildren = children.filter(child => child.customData?.isPinned); - - if (unpinnedChildren.length > 0) { - // SORTING LOGIC: - // If mustHonorMindmapOrder is true: Explicitly sort by mindmapOrder to enforce the manual change. - // If mustHonorMindmapOrder is false: Fallback to visual X-position to keep map strictly ordered by position (auto-layout). - unpinnedChildren.sort((a, b) => { - if (mustHonorMindmapOrder) { - return getMindmapOrder(a) - getMindmapOrder(b); - } - const dx = a.x - b.x; - if (dx !== 0) return dx; - return String(a.id).localeCompare(String(b.id)); - }); - - // Only update mindmapOrder to match visual reality if we are NOT in a manual sort operation - if (!mustHonorMindmapOrder) { - unpinnedChildren.forEach((child, i) => { - if (getMindmapOrder(child) !== i) { - ea.addAppendUpdateCustomData(child.id, { - mindmapOrder: i - }); - } - }); - } - - const placementWidthCache = new Map(); - const childWidths = unpinnedChildren.map((child) => - getVerticalPlacementWidth(child.id, allElements, childrenByParent, widthCache, elementById, placementWidthCache) - ); - const childrenRowWidth = childWidths.reduce((sum, width, index) => { - const childNode = elementById?.get(unpinnedChildren[index].id) ?? allElements.find((el) => el.id === unpinnedChildren[index].id); - const grandChildren = childrenByParent?.get(unpinnedChildren[index].id) ?? getChildrenNodes(unpinnedChildren[index].id, allElements); - const hasUnpinnedGrandChildren = grandChildren.some(gc => !gc.customData?.isPinned); - const fontSize = childNode?.fontSize ?? 20; - const gap = index < unpinnedChildren.length - 1 ? - (!hasUnpinnedGrandChildren ? Math.round(fontSize * layoutSettings.GAP_MULTIPLIER) : layoutSettings.GAP_Y) : - 0; - return sum + width + gap; - }, 0); - - let currentX = currentXCenter - childrenRowWidth / 2; - // Primary layout gap used for Parent-Child spacing (vertical) - // Keep default spacing for larger branches, but tighten compact (1-2 child) subtrees. - const allChildrenCompact = unpinnedChildren.every((child) => { - const grandChildren = childrenByParent?.get(child.id) ?? getChildrenNodes(child.id, allElements); - return !grandChildren.some(gc => !gc.customData?.isPinned); - }); - const compactGap = Math.max( - layoutSettings.GAP_Y, - Math.round(layoutSettings.GAP_X * (layoutSettings.VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO ?? LAYOUT_METADATA.VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO.def)), - ); - const dynamicGapPrimary = (unpinnedChildren.length <= 2 && allChildrenCompact) ? - compactGap : - layoutSettings.GAP_X; - - unpinnedChildren.forEach((child, index) => { - const childW = childWidths[index]; - - layoutSubtreeVertical( - child.id, - currentX + childW / 2, - effectiveSide === 1 ? currentY + node.height + dynamicGapPrimary : currentY - dynamicGapPrimary, - effectiveSide, - allElements, - hasGlobalFolds, - childrenByParent, - widthCache, - elementById, - mustHonorMindmapOrder, - rootId, - parentMap, - ); - - const childNode = elementById?.get(child.id) ?? allElements.find((el) => el.id === child.id); - - const grandChildren = childrenByParent?.get(child.id) ?? getChildrenNodes(child.id, allElements); - const hasUnpinnedGrandChildren = grandChildren.some(gc => !gc.customData?.isPinned); - - const fontSize = childNode.fontSize ?? 20; - // Reusing GAP_Y for the cross-axis (sibling) gap to maintain spacing proportionality - const gap = !hasUnpinnedGrandChildren ? Math.round(fontSize * layoutSettings.GAP_MULTIPLIER) : layoutSettings.GAP_Y; - - currentX += childW + gap; - }); - } - - pinnedChildren.forEach(child => layoutSubtreeVertical( - child.id, - child.x + child.width / 2, - child.y + (effectiveSide === 1 ? 0 : child.height), - effectiveSide, - allElements, - hasGlobalFolds, - childrenByParent, - widthCache, - elementById, - mustHonorMindmapOrder, - rootId, - parentMap, - )); - - // Update Arrows - children.forEach(child => { - const arrow = allElements.find( - (a) => - a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === nodeId && - a.endBinding?.elementId === child.id, - ); - - if (arrow) { - const eaChild = ea.getElement(child.id); - const childCenterY = eaChild.y + eaChild.height / 2; - const parentCenterY = currentY + node.height / 2; - const isChildBelow = childCenterY > parentCenterY; - - const sX = currentXCenter; - const sY = isChildBelow ? currentY + node.height : currentY; - - const eX = eaChild.x + eaChild.width / 2; - const eY = isChildBelow ? eaChild.y : eaChild.y + eaChild.height; - - configureArrow({ - arrowId: arrow.id, - isChildBelow, - startId: node.id, - endId: child.id, - coordinates: { - sX, - sY, - eX, - eY - }, - layoutDirection: "vertical" - }); - } - }); - - if (node.customData?.boundaryId) { - updateNodeBoundary(node, ea.getElements(), rootId); - } -}; - -const radialL1Distribution = (nodes, context, l1Metrics, totalSubtreeHeight, options, mustHonorMindmapOrder = false) => { - const { - allElements, - rootBox, - rootCenter, - hasGlobalFolds, - childrenByParent, - heightCache, - elementById, - rootId, - parentMap - } = context; - const count = nodes.length; - - // --- CONFIGURATION FROM SETTINGS --- - const START_ANGLE = layoutSettings.RADIAL_START_ANGLE; - - // MODIFIED: Use options.fillSweep to force full sweep usage - const MAX_SWEEP_DEG = options.fillSweep ? - layoutSettings.RADIAL_MAX_SWEEP : - Math.min(layoutSettings.RADIAL_MAX_SWEEP / 8 * count, layoutSettings.RADIAL_MAX_SWEEP); - const ASPECT_RATIO = layoutSettings.RADIAL_ASPECT_RATIO; - const POLE_GAP_BONUS = layoutSettings.RADIAL_POLE_GAP_BONUS; - - const BASE_GAP = layoutSettings.GAP_Y * 2; - - // 1. Determine Minimum Radius Baseline based on root node size - // This avoids the previous hardcoded 1000px test radius which forced nodes too far out - const minRadiusY = Math.max( - Math.round(Math.max(rootBox.height, rootBox.width) * layoutSettings.ROOT_RADIUS_FACTOR * 1.5), - layoutSettings.MIN_RADIUS - ); - const minRadiusX = minRadiusY * ASPECT_RATIO; - - // 2. Simulation Pass: Calculate angular space needed at Minimum Radius - let simAngle = START_ANGLE; - let totalRequiredSpan = 0; - - // Temporary storage for node angular data calculated at minRadius - const nodeSimData = nodes.map((node, i) => { - const rad = simAngle * (Math.PI / 180); - // Local Radius at this angle for ellipse - const localR = (minRadiusX * minRadiusY) / Math.sqrt( - Math.pow(minRadiusY * Math.cos(rad), 2) + - Math.pow(minRadiusX * Math.sin(rad), 2) - ); - - const sinComp = Math.abs(Math.sin(rad)); - const cosComp = Math.abs(Math.cos(rad)); - // Projected size of node at this angle - const effSize = node.width * sinComp + l1Metrics[i] * cosComp; - - // Angular span of the node (degrees) - const nodeSpan = (effSize / localR) * (180 / Math.PI); - - // Dynamic Gap: Increases at Poles - const isLast = i === count - 1; - const dynamicGapPx = isLast ? 0 : BASE_GAP * (1 + sinComp * POLE_GAP_BONUS); - const gapSpan = (dynamicGapPx / localR) * (180 / Math.PI); - - const totalSpan = nodeSpan + gapSpan; - - // Advance simulation angle for next node - simAngle += totalSpan; - totalRequiredSpan += totalSpan; - - return { - node, - nodeSpan, - gapSpan - }; - }); - - // 3. Determine Layout Strategy: Expand Radius OR Expand Angles - let finalRadiusY = minRadiusY; - let angleExpansionFactor = 1.0; - - if (totalRequiredSpan > MAX_SWEEP_DEG) { - // Case A: Dense Map. Nodes don't fit in MAX_SWEEP at minRadius. - // Increase Radius to accommodate nodes within MAX_SWEEP. - // Logic: ArcLength = R * Theta. To reduce Theta sum to MAX_SWEEP, increase R proportionally. - const radiusScale = totalRequiredSpan / MAX_SWEEP_DEG; - finalRadiusY = minRadiusY * radiusScale; - - // Angles shrink proportionally to radius increase to maintain non-overlapping geometry - angleExpansionFactor = 1 / radiusScale; - } else { - // Case B: Sparse Map (e.g. < 8 nodes). Nodes fit easily. - // Keep Radius at Minimum to keep nodes close to root. - // Increase angular spacing to fill the MAX_SWEEP. - angleExpansionFactor = MAX_SWEEP_DEG / totalRequiredSpan; - } - - const finalRadiusX = finalRadiusY * ASPECT_RATIO; - - // --- FINAL PLACEMENT --- - let currentAngle = START_ANGLE; - - nodes.forEach((node, i) => { - const isPinned = node.customData?.isPinned === true; - const hasBoundary = !!node.customData?.boundaryId; - const data = nodeSimData[i]; - - // Apply the expansion/compression factor to spans - const realNodeSpan = data.nodeSpan * angleExpansionFactor; - const realGapSpan = data.gapSpan * angleExpansionFactor; - - // Center node in its slice - const placementAngle = currentAngle + (realNodeSpan / 2); - const normAngle = (placementAngle % 360 + 360) % 360; - - // Determine side for subtree layout direction - const dynamicSide = (normAngle > 90 && normAngle < 270) ? -1 : 1; - - // Recalculate exact Cartesian coordinates at final radius - const rad = placementAngle * (Math.PI / 180); - - const finalLocalR = (finalRadiusX * finalRadiusY) / Math.sqrt( - Math.pow(finalRadiusY * Math.cos(rad), 2) + - Math.pow(finalRadiusX * Math.sin(rad), 2) - ); - - const placeR = hasBoundary ? finalLocalR * 1.0 : finalLocalR; - - const tCX = rootCenter.x + placeR * Math.cos(rad); - const tCY = rootCenter.y + placeR * Math.sin(rad); - - if (isPinned) { - layoutSubtree(node.id, node.x, node.y + node.height / 2, dynamicSide, allElements, hasGlobalFolds, childrenByParent, heightCache, elementById, mustHonorMindmapOrder, rootId, parentMap); - } else { - layoutSubtree(node.id, tCX, tCY, dynamicSide, allElements, hasGlobalFolds, childrenByParent, heightCache, elementById, mustHonorMindmapOrder, rootId, parentMap); - } - - // Advance - currentAngle += realNodeSpan + realGapSpan; - - if (node.customData?.mindmapNew) { - ea.addAppendUpdateCustomData(node.id, { - mindmapNew: undefined - }); - } - updateL1Arrow(node, context); - if (groupBranches) applyRecursiveGrouping(node.id, allElements); - }); -}; - -const verticalL1Distribution = (nodes, context, l1Metrics, totalSubtreeHeight, isLeftSide, centerAngle, gapMultiplier, mustHonorMindmapOrder = false) => { - const { - allElements, - rootBox, - rootCenter, - hasGlobalFolds, - childrenByParent, - heightCache, - elementById, - rootId, - parentMap - } = context; - const count = nodes.length; - - // --- VERTICAL DIRECTIONAL LAYOUT (RIGHT/LEFT) --- - const totalContentHeight = totalSubtreeHeight + (count - 1) * layoutSettings.GAP_Y; - const radiusFromHeight = totalContentHeight / layoutSettings.DIRECTIONAL_ARC_SPAN_RADIANS; - const radiusY = Math.max(Math.round(rootBox.height * layoutSettings.ROOT_RADIUS_FACTOR), layoutSettings.MIN_RADIUS, radiusFromHeight) + count * layoutSettings.RADIUS_PADDING_PER_NODE; - const crossAxisRatio = layoutSettings.DIRECTIONAL_CROSS_AXIS_RATIO ?? LAYOUT_METADATA.DIRECTIONAL_CROSS_AXIS_RATIO.def; - const radiusX = Math.max(Math.round(rootBox.width * layoutSettings.ROOT_RADIUS_FACTOR), layoutSettings.MIN_RADIUS, radiusY * crossAxisRatio) + count * layoutSettings.RADIUS_PADDING_PER_NODE; - - const totalThetaDeg = (totalContentHeight / radiusY) * (180 / Math.PI); - let currentAngle = isLeftSide ? centerAngle + totalThetaDeg / 2 : centerAngle - totalThetaDeg / 2; - - nodes.forEach((node, i) => { - const nodeHeight = l1Metrics[i]; - const isPinned = node.customData?.isPinned === true; - const side = isLeftSide ? -1 : 1; - - const getAngularInfo = (targetNode, height) => { - const angleRad = Math.atan2((targetNode.y + targetNode.height / 2) - rootCenter.y, (targetNode.x + targetNode.width / 2) - rootCenter.x); - const angleDeg = (angleRad * (180 / Math.PI)) + 90; - const normAngle = angleDeg < 0 ? angleDeg + 360 : angleDeg; - const spanDeg = (height / radiusY) * (180 / Math.PI); - return { - center: normAngle, - span: spanDeg, - start: normAngle - spanDeg / 2, - end: normAngle + spanDeg / 2 - }; - }; - - const effectiveGap = layoutSettings.GAP_Y * gapMultiplier; - const gapSpanDeg = (effectiveGap / radiusY) * (180 / Math.PI); - const nodeSpanDeg = (nodeHeight / radiusY) * (180 / Math.PI); - - if (isPinned) { - layoutSubtree(node.id, node.x, node.y + node.height / 2, side, allElements, hasGlobalFolds, childrenByParent, heightCache, elementById, mustHonorMindmapOrder, rootId, parentMap); - const info = getAngularInfo(node, nodeHeight); - if (isLeftSide) { - if (currentAngle > info.start - gapSpanDeg) currentAngle = info.start - gapSpanDeg; - } else { - if (currentAngle < info.end + gapSpanDeg) currentAngle = info.end + gapSpanDeg; - } - } else { - const nextPinned = nodes.slice(i + 1).find(n => n.customData?.isPinned); - if (nextPinned) { - const nextInfo = getAngularInfo(nextPinned, getSubtreeHeight(nextPinned.id, allElements, childrenByParent, heightCache, elementById)); - if (isLeftSide) { - if (currentAngle - nodeSpanDeg < nextInfo.end + gapSpanDeg) currentAngle = nextInfo.start - gapSpanDeg; - } else { - if (currentAngle + nodeSpanDeg > nextInfo.start - gapSpanDeg) currentAngle = nextInfo.end + gapSpanDeg; - } - } - - let angleDeg = isLeftSide ? currentAngle - nodeSpanDeg / 2 : currentAngle + nodeSpanDeg / 2; - currentAngle = isLeftSide ? currentAngle - (nodeSpanDeg + gapSpanDeg) : currentAngle + (nodeSpanDeg + gapSpanDeg); - - const angleRad = (angleDeg - 90) * (Math.PI / 180); - const tCX = rootCenter.x + radiusX * Math.cos(angleRad); - const tCY = rootCenter.y + radiusY * Math.sin(angleRad); - layoutSubtree(node.id, tCX, tCY, side, allElements, hasGlobalFolds, childrenByParent, heightCache, elementById, mustHonorMindmapOrder, rootId, parentMap); - } - - if (node.customData?.mindmapNew) { - ea.addAppendUpdateCustomData(node.id, { - mindmapNew: undefined - }); - } - updateL1Arrow(node, context); - if (groupBranches) applyRecursiveGrouping(node.id, allElements); - }); -}; - -const horizontalL1Distribution = (nodes, context, l1Metrics, totalSubtreeWidth, isTopSide, centerAngle, gapMultiplier, mustHonorMindmapOrder = false) => { - const { - allElements, - rootBox, - rootCenter, - hasGlobalFolds, - childrenByParent, - widthCache, - elementById, - rootId, - parentMap - } = context; - const count = nodes.length; - - // --- HORIZONTAL DIRECTIONAL LAYOUT (UP/DOWN) --- - const compressDirectionalWidth = (node, rawWidth) => { - const nodeWidth = Math.max(node?.width ?? 0, 1); - if (rawWidth <= nodeWidth) return rawWidth; - - const extra = rawWidth - nodeWidth; - const softCapThreshold = layoutSettings.HORIZONTAL_L1_SOFTCAP_THRESHOLD ?? LAYOUT_METADATA.HORIZONTAL_L1_SOFTCAP_THRESHOLD.def; - if (extra <= softCapThreshold) return rawWidth; - - // Preserve small/medium maps, compress only very large subtree footprints. - const remaining = extra - softCapThreshold; - const compressionMinScale = layoutSettings.HORIZONTAL_L1_COMPRESSION_MIN_SCALE ?? LAYOUT_METADATA.HORIZONTAL_L1_COMPRESSION_MIN_SCALE.def; - const compressionScale = Math.max(compressionMinScale, (layoutSettings.GAP_X ?? LAYOUT_METADATA.GAP_X.def) * 2); - // log1p keeps growth monotonic while guaranteeing compressedRemaining <= remaining. - const compressedRemaining = compressionScale * Math.log1p(remaining / compressionScale); - return nodeWidth + softCapThreshold + compressedRemaining; - }; - - const effectiveWidths = nodes.map((node, i) => compressDirectionalWidth(node, l1Metrics[i])); - const effectiveWidthById = new Map(nodes.map((node, i) => [node.id, effectiveWidths[i]])); - - const totalEffectiveWidth = effectiveWidths.reduce((sum, width) => sum + width, 0); - const effectiveGap = layoutSettings.GAP_Y * gapMultiplier; - const totalContentWidth = totalEffectiveWidth + (count - 1) * effectiveGap; - - const baseArcSpan = layoutSettings.DIRECTIONAL_ARC_SPAN_RADIANS; - const baselineRadius = Math.max( - Math.round(rootBox.width * layoutSettings.ROOT_RADIUS_FACTOR), - layoutSettings.MIN_RADIUS, - ) + count * layoutSettings.RADIUS_PADDING_PER_NODE; - const pressure = totalContentWidth / Math.max(1, baselineRadius * baseArcSpan); - const adaptiveArcSpan = Math.min(Math.PI, Math.max(baseArcSpan, baseArcSpan * Math.sqrt(Math.max(1, pressure)))); - const radiusFromWidth = totalContentWidth / adaptiveArcSpan; - - // Notice axis swaps: Radius Y calculates based on Width - const radiusX = Math.max(Math.round(rootBox.width * layoutSettings.ROOT_RADIUS_FACTOR), layoutSettings.MIN_RADIUS, radiusFromWidth) + count * layoutSettings.RADIUS_PADDING_PER_NODE; - const crossAxisRatio = layoutSettings.DIRECTIONAL_CROSS_AXIS_RATIO ?? LAYOUT_METADATA.DIRECTIONAL_CROSS_AXIS_RATIO.def; - const radiusY = Math.max(Math.round(rootBox.height * layoutSettings.ROOT_RADIUS_FACTOR), layoutSettings.MIN_RADIUS, radiusX * crossAxisRatio) + count * layoutSettings.RADIUS_PADDING_PER_NODE; - - const totalThetaDeg = (totalContentWidth / radiusX) * (180 / Math.PI); - // Reversing the angle spread depending on side to maintain visual reading flow - let currentAngle = isTopSide ? centerAngle - totalThetaDeg / 2 : centerAngle + totalThetaDeg / 2; - - nodes.forEach((node, i) => { - const nodeWidth = effectiveWidths[i]; - const isPinned = node.customData?.isPinned === true; - const side = isTopSide ? -1 : 1; - - const getAngularInfo = (targetNode, width) => { - const angleRad = Math.atan2((targetNode.y + targetNode.height / 2) - rootCenter.y, (targetNode.x + targetNode.width / 2) - rootCenter.x); - const angleDeg = angleRad * (180 / Math.PI); - const normAngle = angleDeg < 0 ? angleDeg + 360 : angleDeg; - const spanDeg = (width / radiusX) * (180 / Math.PI); - return { - center: normAngle, - span: spanDeg, - start: normAngle - spanDeg / 2, - end: normAngle + spanDeg / 2 - }; - }; - - const gapSpanDeg = (effectiveGap / radiusX) * (180 / Math.PI); - const nodeSpanDeg = (nodeWidth / radiusX) * (180 / Math.PI); - - if (isPinned) { - layoutSubtreeVertical(node.id, node.x + node.width / 2, node.y, side, allElements, hasGlobalFolds, childrenByParent, widthCache, elementById, mustHonorMindmapOrder, rootId, parentMap); - const info = getAngularInfo(node, nodeWidth); - if (isTopSide) { - if (currentAngle < info.start - gapSpanDeg) currentAngle = info.start - gapSpanDeg; - } else { - if (currentAngle > info.end + gapSpanDeg) currentAngle = info.end + gapSpanDeg; - } - } else { - const nextPinned = nodes.slice(i + 1).find(n => n.customData?.isPinned); - if (nextPinned) { - const nextPinnedWidth = effectiveWidthById.get(nextPinned.id) ?? compressDirectionalWidth(nextPinned, getSubtreeWidth(nextPinned.id, allElements, childrenByParent, widthCache, elementById)); - const nextInfo = getAngularInfo(nextPinned, nextPinnedWidth); - if (isTopSide) { - if (currentAngle + nodeSpanDeg > nextInfo.start - gapSpanDeg) currentAngle = nextInfo.start - gapSpanDeg - nodeSpanDeg; - } else { - if (currentAngle - nodeSpanDeg < nextInfo.end + gapSpanDeg) currentAngle = nextInfo.end + gapSpanDeg + nodeSpanDeg; - } - } - - let angleDeg = isTopSide ? currentAngle + nodeSpanDeg / 2 : currentAngle - nodeSpanDeg / 2; - currentAngle = isTopSide ? currentAngle + (nodeSpanDeg + gapSpanDeg) : currentAngle - (nodeSpanDeg + gapSpanDeg); - - const angleRad = angleDeg * (Math.PI / 180); - const tCX = rootCenter.x + radiusX * Math.cos(angleRad); - const tCY = rootCenter.y + radiusY * Math.sin(angleRad); - layoutSubtreeVertical(node.id, tCX, tCY, side, allElements, hasGlobalFolds, childrenByParent, widthCache, elementById, mustHonorMindmapOrder, rootId, parentMap); - } - - if (node.customData?.mindmapNew) { - ea.addAppendUpdateCustomData(node.id, { - mindmapNew: undefined - }); - } - updateL1Arrow(node, context, "vertical"); - if (groupBranches) applyRecursiveGrouping(node.id, allElements); - }); -}; - -/** - * Unified layout function for Level 1 nodes. - * Uses a Vertical Ellipse for Radial mode. Ensures nodes are distributed across - * the ellipse to prevent wrap-around overlap and maintain correct facing. - * Returns true if layout logic was executed. - */ -const layoutL1Nodes = (nodes, options, context, mustHonorMindmapOrder = false) => { - if (nodes.length === 0) return false; - const { - allElements, - childrenByParent, - heightCache, - widthCache, - elementById - } = context; - const { - sortMethod, - centerAngle, - gapMultiplier - } = options; - - // SORTING: Respect the established mindmapOrder (0..N) - nodes.sort((a, b) => getMindmapOrder(a) - getMindmapOrder(b)); - - if (sortMethod === "radial") { - const l1Metrics = nodes.map(node => getSubtreeHeight(node.id, allElements, childrenByParent, heightCache, elementById)); - const totalSubtreeHeight = l1Metrics.reduce((sum, h) => sum + h, 0); - radialL1Distribution(nodes, context, l1Metrics, totalSubtreeHeight, options, mustHonorMindmapOrder); - } else if (sortMethod === "horizontal") { - const l1Metrics = nodes.map(node => getSubtreeWidth(node.id, allElements, childrenByParent, widthCache, elementById)); - const totalSubtreeWidth = l1Metrics.reduce((sum, w) => sum + w, 0); - // 270 degrees represents the Top (Up-facing), 90 degrees represents the Bottom (Down-facing) - const isTopSide = Math.abs((centerAngle ?? 0) - 270) < 1; - horizontalL1Distribution(nodes, context, l1Metrics, totalSubtreeWidth, isTopSide, centerAngle, gapMultiplier, mustHonorMindmapOrder); - } else { - const l1Metrics = nodes.map(node => getSubtreeHeight(node.id, allElements, childrenByParent, heightCache, elementById)); - const totalSubtreeHeight = l1Metrics.reduce((sum, h) => sum + h, 0); - const isLeftSide = sortMethod === "vertical" && Math.abs((centerAngle ?? 0) - 270) < 1; - verticalL1Distribution(nodes, context, l1Metrics, totalSubtreeHeight, isLeftSide, centerAngle, gapMultiplier, mustHonorMindmapOrder); - } - - return true; -}; - -/** - * Sorts Level 1 nodes based on their current visual position and updates their mindmapOrder. - * For Radial maps, sorting is done by angle. For others, by Y-coordinate. - * Newly added nodes (mindmapNew) are always appended to the end of the visual sequence. - * Returns true if any order was actually updated. - **/ -const sortL1NodesBasedOnVisualSequence = (l1Nodes, mode, rootCenter) => { - if (l1Nodes.length === 0) return false; - - let orderChanged = false; - const isVerticalMode = ["Up-facing", "Down-facing", "Up-Down"].includes(mode); - - /** - * Helper to sort by Reading Order: Right-side Top-to-Bottom, then Left-side Top-to-Bottom. - * This serves as our canonical sequence for all directional modes and mode-switching. - */ - const sortByReadingOrder = (a, b) => { - const aCX = a.x + a.width / 2; - const bCX = b.x + b.width / 2; - const aCY = a.y + a.height / 2; - const bCY = b.y + b.height / 2; - - if (isVerticalMode) { - // Vertical modes: Sort bottom-side (Left->Right) then top-side (Left->Right) - const aIsBottom = aCY > rootCenter.y; - const bIsBottom = bCY > rootCenter.y; - if (aIsBottom !== bIsBottom) return aIsBottom ? -1 : 1; - return aCX - bCX; - } else { - // Horizontal modes: Sort right-side (Top->Bottom) then left-side (Top->Bottom) - const aIsR = aCX > rootCenter.x; - const bIsR = bCX > rootCenter.x; - if (aIsR !== bIsR) return aIsR ? -1 : 1; - return a.y - b.y; - } - }; - - /** Helper to sort by Angle: Clockwise around the root center. */ - const sortByAngle = (a, b) => { - return getAngleFromCenter(rootCenter, { - x: a.x + a.width / 2, - y: a.y + a.height / 2 - }) - - getAngleFromCenter(rootCenter, { - x: b.x + b.width / 2, - y: b.y + b.height / 2 - }); - }; - - const sortFn = mode === "Radial" ? sortByAngle : sortByReadingOrder; - const existingNodes = l1Nodes.filter(n => !n.customData?.mindmapNew); - const newNodes = l1Nodes.filter(n => n.customData?.mindmapNew); - existingNodes.sort(sortFn); - - // Freeze logic mindmapOrder based on final sort - existingNodes.forEach((node, i) => { - if (node.customData?.mindmapOrder !== i) { - ea.addAppendUpdateCustomData(node.id, { - mindmapOrder: i - }); - orderChanged = true; - } - }); - - // New nodes always need an update since they lack established order or have a temp one - newNodes.forEach((node, i) => { - const newOrder = existingNodes.length + i; - ea.addAppendUpdateCustomData(node.id, { - mindmapOrder: newOrder - }); - orderChanged = true; - }); - - return orderChanged; -}; - -/** - * Main layout execution function. - * Calculates positions for a tree rooted at rootId and moves elements. - * - * @param {string} rootId - ID of the root node. - * @param {boolean} forceUngroup - Force ungrouping of branches before layout. - * @param {boolean} mustHonorMindmapOrder - If true, enforces the current mindmapOrder over visual position. - */ -const triggerGlobalLayout = async (rootId, forceUngroup = false, mustHonorMindmapOrder = false) => { - if (!isViewSet()) return; - const selectedElement = getMindmapNodeFromSelection(); - if (!selectedElement) return; - - const run = async (allElements, mindmapIds, root, doVisualSort, sharedSets, mustHonorMindmapOrder = false) => { - return withRootLayoutContext(root, () => { - const oldMode = root.customData?.growthMode; - const newMode = root.customData?.growthMode || currentModalGrowthMode; - - // Track if any meaningful changes occur - let orderChanged = false; - let modeChanged = false; - let visualChange = false; - - // Snapshot positions - const originalPositions = new Map(); - allElements.forEach(el => { - originalPositions.set(el.id, { - x: el.x, - y: el.y - }); - }); - - const elementById = buildElementMap(allElements); - const parentMap = buildParentMap(allElements, elementById); - const childrenByParent = buildChildrenMap(allElements, elementById); - - const heightCache = new Map(); - const widthCache = new Map(); - - const branchIds = new Set(mindmapIds); - const groupToNodes = buildGroupToNodes(branchIds, allElements); - - const hasGlobalFolds = allElements.some(el => el.customData?.isFolded === true); - const l1Nodes = getChildrenNodes(rootId, allElements); - if (l1Nodes.length === 0) return { - structuralChange: false, - visualChange: false - }; - - if (groupBranches || forceUngroup) { - mindmapIds.forEach((id) => { - const el = ea.getElement(id); - if (el && el.groupIds) { - el.groupIds = el.groupIds.filter(gid => !isMindmapGroup(gid, allElements)); - } - }); - } - - const rootBox = getNodeBox(root, allElements); - const rootCenter = { - x: rootBox.minX + rootBox.width / 2, - y: rootBox.minY + rootBox.height / 2 - }; - - const layoutContext = { - allElements, - rootId, - rootBox, - rootCenter, - hasGlobalFolds, - mode: newMode, - childrenByParent, - heightCache, - widthCache, - elementById, - parentMap, - }; - - const isModeSwitch = mustHonorMindmapOrder || (oldMode && oldMode !== newMode); - - if (!isModeSwitch && doVisualSort && !mustHonorMindmapOrder) { - orderChanged = sortL1NodesBasedOnVisualSequence(l1Nodes, newMode, rootCenter); - } else if (!mustHonorMindmapOrder) { - if (oldMode !== newMode) { - ea.addAppendUpdateCustomData(rootId, { - growthMode: newMode - }); - modeChanged = true; - } - } - - if (newMode === "Radial") { - layoutL1Nodes(l1Nodes, { - sortMethod: "radial", - centerAngle: null, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_RADIAL, - fillSweep: root.customData?.fillSweep ?? fillSweep, - }, layoutContext, mustHonorMindmapOrder); - } else if (["Right-facing", "Left-facing", "Right-Left"].includes(newMode)) { - const leftNodes = []; - const rightNodes = []; - - if (newMode === "Right-Left") { - if (isModeSwitch && !mustHonorMindmapOrder) { - const splitIdx = Math.ceil(l1Nodes.length / 2); - l1Nodes.forEach((node, i) => { - if (i < splitIdx) rightNodes.push(node); - else leftNodes.push(node); - }); - } else { - l1Nodes.forEach((node) => { - const nodeCX = node.x + node.width / 2; - if (nodeCX > rootCenter.x) rightNodes.push(node); - else leftNodes.push(node); - }); - } - } else if (newMode === "Left-facing") { - l1Nodes.forEach(node => leftNodes.push(node)); - } else { - l1Nodes.forEach(node => rightNodes.push(node)); - } - - if (rightNodes.length > 0) { - layoutL1Nodes(rightNodes, { - sortMethod: "vertical", - centerAngle: 90, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_DIRECTIONAL - }, layoutContext, mustHonorMindmapOrder); - } - if (leftNodes.length > 0) { - layoutL1Nodes(leftNodes, { - sortMethod: "vertical", - centerAngle: 270, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_DIRECTIONAL - }, layoutContext, mustHonorMindmapOrder); - } - } else if (["Up-facing", "Down-facing", "Up-Down"].includes(newMode)) { - const upNodes = []; - const downNodes = []; - - if (newMode === "Up-Down") { - if (isModeSwitch && !mustHonorMindmapOrder) { - const splitIdx = Math.ceil(l1Nodes.length / 2); - l1Nodes.forEach((node, i) => { - if (i < splitIdx) downNodes.push(node); - else upNodes.push(node); - }); - } else { - l1Nodes.forEach((node) => { - const nodeCY = node.y + node.height / 2; - if (nodeCY > rootCenter.y) downNodes.push(node); - else upNodes.push(node); - }); - } - } else if (newMode === "Up-facing") { - l1Nodes.forEach(node => upNodes.push(node)); - } else { - l1Nodes.forEach(node => downNodes.push(node)); - } - - // Initialize cache required for vertical mode width tracking - layoutContext.widthCache = new Map(); - - if (downNodes.length > 0) { - layoutL1Nodes(downNodes, { - sortMethod: "horizontal", - centerAngle: 90, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_DIRECTIONAL - }, layoutContext, mustHonorMindmapOrder); - } - if (upNodes.length > 0) { - layoutL1Nodes(upNodes, { - sortMethod: "horizontal", - centerAngle: 270, - gapMultiplier: layoutSettings.GAP_MULTIPLIER_DIRECTIONAL - }, layoutContext, mustHonorMindmapOrder); - } - } - - const { - mindmapIdsSet, - crosslinkIdSet, - decorationIdSet - } = sharedSets; - - moveCrossLinks(ea.getElements(), originalPositions); - moveDecorations(ea.getElements(), originalPositions, groupToNodes, rootId, elementById, parentMap); - - ea.getElements().filter(el => !mindmapIdsSet.has(el.id) && !crosslinkIdSet.has(el.id) && !decorationIdSet.has(el.id)).forEach(el => { - delete ea.elementsDict[el.id]; - }); - - // Detect Visual Changes - for (const el of ea.getElements()) { - const oldPos = originalPositions.get(el.id); - if (oldPos) { - if (Math.abs(el.x - oldPos.x) > 0.01 || Math.abs(el.y - oldPos.y) > 0.01) { - visualChange = true; - break; - } - } - } - - return { - structuralChange: orderChanged || modeChanged, - visualChange - }; - }); - }; - - const viewElements = ea.getViewElements(); - const projectElements = getMindmapProjectElements(rootId, viewElements); - - ea.copyViewElementsToEAforEditing(projectElements); - let allElements = ea.getElements(); - let root = allElements.find((el) => el.id === rootId); - if (!root) return; - - if (root.customData?.autoLayoutDisabled) return; - - const mindmapIds = getBranchElementIds(rootId, allElements); - const { - structuralGroupId, - groupedElementIds - } = getStructuralGroupForNode(mindmapIds, allElements, rootId); - if (structuralGroupId) { - removeGroupFromElements(structuralGroupId, allElements); - } - - const expandedMindmapIds = [...mindmapIds]; - mindmapIds.forEach(id => { - const el = allElements.find(e => e.id === id); - if (el && el.boundElements) { - el.boundElements.forEach(be => expandedMindmapIds.push(be.id)); - } - }); - - const mindmapIdsSet = new Set(expandedMindmapIds); - const crosslinkIdSet = collectCrosslinkIds(allElements); - const decorationIdSet = collectDecorationIds(allElements, rootId); - const sharedSets = { - mindmapIdsSet, - crosslinkIdSet, - decorationIdSet - }; - - // --- Snapshot boundary nodes before Run 1 --- - // We check for nodes that have a boundaryId defined - const boundaryNodeSnapshot = new Map(); - allElements.forEach(el => { - if (typeof el.customData?.mindmapOrder !== "undefined" && el.customData?.boundaryId) { - boundaryNodeSnapshot.set(el.id, { - x: el.x, - y: el.y, - width: el.width, - height: el.height - }); - } - }); - - const result1 = await run(allElements, mindmapIds, root, true, sharedSets, mustHonorMindmapOrder); - - // --- Check if any boundary node moved --- - let boundaryMoved = false; - if (boundaryNodeSnapshot.size > 0) { - for (const [id, oldSnapshot] of boundaryNodeSnapshot) { - const newEl = ea.getElement(id); - if (newEl) { - if (Math.abs(newEl.x - oldSnapshot.x) > 0.01 || - Math.abs(newEl.y - oldSnapshot.y) > 0.01 || - Math.abs(newEl.width - oldSnapshot.width) > 0.01 || - Math.abs(newEl.height - oldSnapshot.height) > 0.01) { - boundaryMoved = true; - break; - } - } - } - } - - if (result1.structuralChange || forceUngroup || boundaryMoved) { - await addElementsToView({ - captureUpdate: "EVENTUALLY" - }); - - // Isolate subset again for the second pass - const viewElementsRun2 = ea.getViewElements(); - const projectElementsRun2 = getMindmapProjectElements(rootId, viewElementsRun2); - - ea.copyViewElementsToEAforEditing(projectElementsRun2); - allElements = ea.getElements(); - root = allElements.find((el) => el.id === rootId); - - await run(allElements, mindmapIds, root, false, sharedSets, mustHonorMindmapOrder); - - if (structuralGroupId && !forceUngroup) { - // Restore the exact same group ID instead of creating a new one - // This prevents Excalidraw's editingGroupId from pointing to a deleted group, - // which causes the 0x0 rendering artifact at the origin. - groupedElementIds.forEach(id => { - const el = ea.getElement(id); - if (el && (!el.groupIds || !el.groupIds.includes(structuralGroupId))) { - el.groupIds = [...(el.groupIds || []), structuralGroupId]; - } - }); - } - await addElementsToView({ - captureUpdate: "IMMEDIATELY" - }); - - } else { - // If only visual change (no struct change, no boundary move), commit Run 1 - if (result1.visualChange) { - if (structuralGroupId && !forceUngroup) { - // Restore the exact same group ID instead of creating a new one - groupedElementIds.forEach(id => { - const el = ea.getElement(id); - if (el && (!el.groupIds || !el.groupIds.includes(structuralGroupId))) { - el.groupIds = [...(el.groupIds || []), structuralGroupId]; - } - }); - } - await addElementsToView({ - captureUpdate: "IMMEDIATELY" - }); - } else { - ea.clear(); - } - } - - selectNodeInView(selectedElement); -}; - -// --------------------------------------------------------------------------- -// 4. Add Node Logic -// --------------------------------------------------------------------------- -let mostRecentlyAddedNodeID; -const getMostRecentlyAddedNode = () => { - if (!mostRecentlyAddedNodeID) return null; - return ea.getViewElements().find((el) => el.id === mostRecentlyAddedNodeID); -} - -const getAdjustedMaxWidth = async (text, max) => { - const fontString = `${ea.style.fontSize.toString()}px ${ - ExcalidrawLib.getFontFamilyString({fontFamily: ea.style.fontFamily})}`; - - const parsedText = (await parseText(text)) ?? text; - - const wrappedText = ExcalidrawLib.wrapText(parsedText, fontString, max); - const metrics = ea.measureText(wrappedText); - const optimalWidth = Math.ceil(metrics.width); - return { - width: Math.min(max, optimalWidth), - height: metrics.height, - wrappedText - }; -} - -const addImage = async ({ - pathOrFile, - width, - leftFacing = false, - x = 0, - y = 0, - depth = 0 -} = {}) => { - const newNodeId = await ea.addImage(x, y, pathOrFile); - const el = ea.getElement(newNodeId); - const targetWidth = width || (depth === 0 ? EMBEDED_OBJECT_WIDTH_ROOT : EMBEDED_OBJECT_WIDTH_CHILD); - const ratio = el.width / el.height; - el.width = targetWidth; - el.height = targetWidth / ratio; - if (leftFacing) el.x = x - el.width; - return newNodeId; -} - -/** - * Initializes the customData for a new Root node with the current global settings. - */ -const initializeRootCustomData = (nodeId) => { - ea.addAppendUpdateCustomData(nodeId, { - presetName: activePresetName, - growthMode: currentModalGrowthMode, - autoLayoutDisabled: false, - arrowType: arrowType, - fontsizeScale, - multicolor, - boxChildren, - roundedCorners, - maxWrapWidth: maxWidth, - isSolidArrow, - centerText, - fillSweep, - branchScale, - baseStrokeWidth, - layoutSettings: JSON.parse(JSON.stringify(layoutSettings)), - }); -}; - -const addNode = async (text, follow = false, skipFinalLayout = false, batchModeAllElements = null, batchModeParent = null, pos = null, ontology = null) => { - if (!isViewSet()) return; - if (!text || text.trim() === "") return; - - const preGenTextId = ea.generateElementId(); - if (text.includes("__NODE_LINK_PLACEHOLDER__")) { - const file = app.workspace.getActiveFile(); - const fileName = file ? file.basename : ""; - const linkStr = `[[${fileName}#^group=${preGenTextId}|${nodeLinkAlias}]]`; - text = text.replace("__NODE_LINK_PLACEHOLDER__", linkStr); - } - - const st = getAppState(); - const isBatchMode = batchModeAllElements !== null; - - let allElements = batchModeAllElements || ea.getViewElements(); - let parent = batchModeParent; - - // custom parent is a non-mindmap node selected by the user to add a child to - // custom parents need to receive relevant mindmap customData later during the addNode process - let usingCustomParent = false; - - if (!isBatchMode) { - parent = getMindmapNodeFromSelection(); - if (!parent) { - parent = ea.getViewSelectedElement(); - usingCustomParent = !!parent; - } - if (parent?.containerId) { - parent = allElements.find((el) => el.id === parent.containerId); - } - - if (parent && parent.customData?.isFolded) { - await toggleFold("L0"); - allElements = ea.getViewElements(); - parent = allElements.find((el) => el.id === parent.id); - } - } - - let newNodeId; - let arrowId; - - // --- Image Detection --- - const imageInfo = parseImageInput(text); - const embeddableUrl = parseEmbeddableInput(text, imageInfo); - - const defaultNodeColor = ea.getCM(st.viewBackgroundColor).invert().stringHEX({ - alpha: false - }); - - let depth = 0, - nodeColor = defaultNodeColor, - rootId, nextSiblingOrder = 0; - let settingsRoot = null; - let rootCfgForAdd = null; - if (parent) { - const siblings = getChildrenNodes(parent.id, allElements); - nextSiblingOrder = Math.max(0, ...siblings.map(getMindmapOrder)) + 1; - settingsRoot = getSettingsRootNode(parent, allElements) || allElements.find((e) => e.id === getHierarchy(parent, allElements).rootId); - rootId = settingsRoot?.id; - rootCfgForAdd = getRootConfigForNode(settingsRoot); - const parentDepthFromSettingsRoot = getDepthFromAncestor(parent.id, rootId, allElements); - depth = parentDepthFromSettingsRoot + 1; - const rootEl = settingsRoot; - - if (depth === 1) { - if (rootCfgForAdd.multicolor) { - const existingColors = getChildrenNodes(parent.id, allElements).map((n) => n.strokeColor); - nodeColor = getDynamicColor(existingColors); - } else { - nodeColor = rootEl.strokeColor; - } - } else { - if (parent.type === "image" || parent.type === "embeddable") { - const incomingArrow = allElements.find( - (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === parent.id, - ); - nodeColor = incomingArrow ? - incomingArrow.strokeColor : - (parent.strokeColor && parent.strokeColor.toLowerCase() !== "transparent" ? parent.strokeColor : defaultNodeColor); - } else { - nodeColor = parent.strokeColor; - } - } - - const effectiveMulticolor = rootCfgForAdd?.multicolor ?? multicolor; - const effectiveIsSolidArrow = rootCfgForAdd?.isSolidArrow ?? isSolidArrow; - - // If multicolor is disabled AND "Use scene stroke style" is enabled (!effectiveIsSolidArrow) - if (!effectiveMulticolor && !effectiveIsSolidArrow) { - const parentStrokeColor = (parent.strokeColor || "transparent").toLowerCase(); - const isTransparent = parentStrokeColor === "transparent"; - - let isSameAsBg = false; - if (!isTransparent) { - const parentColorCM = ea.getCM(parent.strokeColor); - const bgColorCM = ea.getCM(st.viewBackgroundColor); - if (parentColorCM && bgColorCM && parentColorCM.stringHEX() === bgColorCM.stringHEX()) { - isSameAsBg = true; - } - } - - // If the parent's stroke is transparent or matches the view background, - // invert the scene color for the new node and branch - if (isTransparent || isSameAsBg) { - nodeColor = ea.getCM(st.viewBackgroundColor).invert().stringHEX({ alpha: false }); - } - } - } - - const fontScale = getFontScale(rootCfgForAdd?.fontsizeScale ?? fontsizeScale); - if (!isBatchMode) ea.clear(); - ea.style.fontFamily = st.currentItemFontFamily; - ea.style.fontSize = fontScale[Math.min(depth, fontScale.length - 1)]; - ea.style.roundness = (rootCfgForAdd?.roundedCorners ?? roundedCorners) ? { - type: 3 - } : null; - - const effectiveMaxWrap = rootCfgForAdd?.maxWrapWidth ?? maxWidth; - let curMaxW = depth === 0 ? Math.max(400, effectiveMaxWrap) : effectiveMaxWrap; - - let renderedText = text; - let metrics = { - w: 0, - h: 0 - }; - let shouldWrap = false; - let curMaxH = 0; - - if (!imageInfo?.isImagePath && !imageInfo?.imageFile && !embeddableUrl) { - renderedText = (await parseText(text)) ?? text; - metrics = ea.measureText(renderedText); - shouldWrap = metrics.width > curMaxW; - curMaxH = metrics.height; - - if (shouldWrap) { - const res = await getAdjustedMaxWidth(text, curMaxW); - curMaxW = res.width; - curMaxH = res.height; - } - } - - if (!parent) { - ea.style.strokeColor = multicolor ? defaultNodeColor : st.currentItemStrokeColor; - - if (imageInfo?.isImagePath) { - newNodeId = await addImage({ - pathOrFile: imageInfo.path, - width: imageInfo.width, - depth - }); - // Attach the URL to the element's link so we can trace it back - if (imageInfo.isExternalImage && newNodeId) { - const el = ea.getElement(newNodeId); - if (el && !el.link) el.link = imageInfo.path; - } - } else if (imageInfo?.imageFile) { - newNodeId = await addImage({ - pathOrFile: imageInfo.imageFile, - width: imageInfo.width, - depth - }); - } else if (embeddableUrl) { - newNodeId = addEmbeddableNode({ - url: embeddableUrl, - depth: 0 - }); - } else { - ea.style.fillStyle = "solid"; - ea.style.backgroundColor = st.viewBackgroundColor; - ea.style.strokeWidth = getStrokeWidthForDepth(0); - ea.style.roughness = getAppState().currentItemRoughness; - newNodeId = ea.addText(0, 0, text, { - box: "rectangle", - textAlign: "center", - textVerticalAlign: "middle", - // Use a distinct color representation so the frame can be recolored separately from text - boxStrokeColor: ea.getCM(ea.style.strokeColor).stringRGB(), - width: shouldWrap ? curMaxW : undefined, - height: shouldWrap ? curMaxH : undefined, - autoResize: !shouldWrap, - }, preGenTextId); - ea.style.backgroundColor = "transparent"; - } - - initializeRootCustomData(newNodeId); - rootId = newNodeId; - } else { - ea.style.strokeColor = nodeColor; - const rootEl = allElements.find((e) => e.id === rootId); - const rootBox = getNodeBox(rootEl, allElements); - const mode = rootCfgForAdd?.growthMode || rootEl.customData?.growthMode || currentModalGrowthMode; - const rootCenter = { - x: rootBox.minX + rootBox.width / 2, - y: rootBox.minY + rootBox.height / 2, - }; - - const parentBox = getNodeBox(parent, allElements); - - // Determine direction for initial offset to prevent visual jumping - const isVerticalMode = ["Up-facing", "Down-facing", "Up-Down"].includes(mode); - - let targetSide = 1; // 1 = Right/Down, -1 = Left/Up - if (depth === 1) { - if (mode === "Left-facing" || mode === "Up-facing") targetSide = -1; - else if (mode === "Right-facing" || mode === "Down-facing") targetSide = 1; - else if (mode === "Right-Left" || mode === "Up-Down") { - const siblings = getChildrenNodes(parent.id, allElements); - const idx = siblings.length; // Index of the new node being added - if (idx < 2) targetSide = 1; - else if (idx < 4) targetSide = -1; - else targetSide = idx % 2 === 0 ? 1 : -1; - } else { - // Default to parent side or Right for Radial/Fallback layouts - if (isVerticalMode) { - const parentCenterY = parentBox.minY + parentBox.height / 2; - targetSide = parentCenterY > rootCenter.y ? 1 : -1; - } else { - const parentCenterX = parentBox.minX + parentBox.width / 2; - targetSide = parentCenterX > rootCenter.x ? 1 : -1; - } - } - } else { - // Deep nodes follow parent's side - if (isVerticalMode) { - const parentCenterY = parentBox.minY + parentBox.height / 2; - targetSide = parentCenterY > rootCenter.y ? 1 : -1; - } else { - const parentCenterX = parentBox.minX + parentBox.width / 2; - targetSide = parentCenterX > rootCenter.x ? 1 : -1; - } - } - - let side = targetSide; - let px = parentBox.minX, - py = parentBox.minY; - - if (isVerticalMode) { - const offset = side === 1 ? rootBox.height * 2 : -rootBox.height; - px = parentBox.minX + parentBox.width / 2 - (shouldWrap ? curMaxW : metrics.width) / 2; - py = parentBox.minY + offset; - - // If pos is provided (e.g. from Add Sibling), override placement. - // This maintains the "same side" logic because the originator's X is used. - if (!autoLayoutDisabled && pos) { - px = pos.x; - py = pos.y; - side = (py + metrics.height / 2 > rootCenter.y) ? 1 : -1; - } else if (!autoLayoutDisabled) { - // Ensure new node is placed below existing siblings to preserve visual order - const siblings = getChildrenNodes(parent.id, allElements); - if (siblings.length > 0) { - const sortedSiblings = siblings.sort((a, b) => a.x - b.x); - const lastSibling = sortedSiblings[sortedSiblings.length - 1]; - const lastSiblingBox = getNodeBox(lastSibling, allElements); - px = lastSiblingBox.minX + lastSiblingBox.width + layoutSettings.GAP_Y; - py = parentBox.minY + (side === 1 ? parentBox.height + layoutSettings.GAP_X : -layoutSettings.GAP_X - metrics.height); - } - } else if (autoLayoutDisabled) { - const manualGapY = Math.round(parentBox.height * layoutSettings.MANUAL_GAP_MULTIPLIER); - const jitterX = (Math.random() - 0.5) * layoutSettings.MANUAL_JITTER_RANGE; - const jitterY = (Math.random() - 0.5) * layoutSettings.MANUAL_JITTER_RANGE; - px = parentBox.minX + parentBox.width / 2 - metrics.width / 2 + jitterX; - py = side === 1 ? - parentBox.minY + parentBox.height + manualGapY + jitterY : - parentBox.minY - manualGapY - metrics.height + jitterY; - } - } else { - const offset = (mode === "Radial" || side === 1) ? rootBox.width * 2 : -rootBox.width; - px = parentBox.minX + offset; - py = parentBox.minY; - - // If pos is provided (e.g. from Add Sibling), override placement. - if (!autoLayoutDisabled && pos) { - px = pos.x; - py = pos.y; - side = (px + (shouldWrap ? curMaxW : metrics.width) / 2 > rootCenter.x) ? 1 : -1; - } else if (!autoLayoutDisabled) { - // Ensure new node is placed below existing siblings to preserve visual order - const siblings = getChildrenNodes(parent.id, allElements); - if (siblings.length > 0) { - const sortedSiblings = siblings.sort((a, b) => a.y - b.y); - const lastSibling = sortedSiblings[sortedSiblings.length - 1]; - const lastSiblingBox = getNodeBox(lastSibling, allElements); - py = lastSiblingBox.minY + lastSiblingBox.height + layoutSettings.GAP_Y; - } - } else if (autoLayoutDisabled) { - const manualGapX = Math.round(parentBox.width * layoutSettings.MANUAL_GAP_MULTIPLIER); - const jitterX = (Math.random() - 0.5) * layoutSettings.MANUAL_JITTER_RANGE; - const jitterY = (Math.random() - 0.5) * layoutSettings.MANUAL_JITTER_RANGE; - const nodeW = shouldWrap ? curMaxW : metrics.width; - px = side === 1 ? - parentBox.minX + parentBox.width + manualGapX + jitterX : - parentBox.minX - manualGapX - nodeW + jitterX; - py = parentBox.minY + parentBox.height / 2 - metrics.height / 2 + jitterY; - } - } - - const effectiveCenterText = rootCfgForAdd?.centerText ?? centerText; - const effectiveBoxChildren = rootCfgForAdd?.boxChildren ?? boxChildren; - const effectiveArrowType = rootCfgForAdd?.arrowType ?? arrowType; - const effectiveIsSolidArrow = rootCfgForAdd?.isSolidArrow ?? isSolidArrow; - const effectiveBranchScale = rootCfgForAdd?.branchScale ?? branchScale; - const effectiveBaseStrokeWidth = rootCfgForAdd?.baseStrokeWidth ?? baseStrokeWidth; - - const textAlign = effectiveCenterText ? "center" : (isVerticalMode ? "center" : (side === 1 ? "left" : "right")); - - if (imageInfo?.isImagePath) { - newNodeId = await addImage({ - pathOrFile: imageInfo.path, - width: imageInfo.width, - leftFacing: side === -1 && !autoLayoutDisabled, - x: px, - y: py, - depth - }); - // Attach the URL to the element's link so we can trace it back - if (imageInfo.isExternalImage && newNodeId) { - const el = ea.getElement(newNodeId); - if (el && !el.link) el.link = imageInfo.path; - } - } else if (imageInfo?.imageFile) { - newNodeId = await addImage({ - pathOrFile: imageInfo.imageFile, - width: imageInfo.width, - leftFacing: side === -1 && !autoLayoutDisabled, - x: px, - y: py, - depth - }); - } else if (embeddableUrl) { - newNodeId = addEmbeddableNode({ - px, - py, - url: embeddableUrl, - depth - }); - const el = ea.getElement(newNodeId); - if (side === -1 && !autoLayoutDisabled) el.x = px - el.width; - } else { - ea.style.strokeWidth = calculateStrokeWidth(depth, effectiveBaseStrokeWidth, effectiveBranchScale); - ea.style.roughness = getAppState().currentItemRoughness; - newNodeId = ea.addText(px, py, text, { - box: effectiveBoxChildren ? "rectangle" : false, - textAlign, - textVerticalAlign: "middle", - width: shouldWrap ? curMaxW : undefined, - height: shouldWrap ? curMaxH : undefined, - autoResize: !shouldWrap, - }, preGenTextId); - } - - if (depth === 1) { - ea.addAppendUpdateCustomData(newNodeId, { - mindmapNew: !!pos ? false : true, // if position is provided a sibling is being added to a defined spot in the layout - mindmapOrder: nextSiblingOrder, - }); - } else { - ea.addAppendUpdateCustomData(newNodeId, { - mindmapOrder: nextSiblingOrder - }); - } - - if (!ea.getElement(parent.id)) { - ea.copyViewElementsToEAforEditing([parent]); - parent = ea.getElement(parent.id); - } - - // if the custom parent is already in a hierarchy, then formally make it the next sibling - if (depth > 1 && usingCustomParent && !parent.customData?.mindmapOrder) { - ea.addAppendUpdateCustomData(parent.id, { - mindmapOrder: nextSiblingOrder - }); - } - - // else make the customParent the root of the new mindmap - if ((depth === 0 || usingCustomParent) && !parent.customData?.growthMode && !parent.customData?.mindmapOrder) { - initializeRootCustomData(parent.id); - } - - if ((parent.type === "image" || parent.type === "embeddable") && typeof parent.customData?.mindmapOrder === "undefined") { - ea.addAppendUpdateCustomData(parent.id, { - mindmapOrder: 0 - }); - } - - ea.style.strokeWidth = calculateStrokeWidth(depth, effectiveBaseStrokeWidth, effectiveBranchScale); - ea.style.roughness = getAppState().currentItemRoughness; - ea.style.strokeStyle = effectiveIsSolidArrow ? "solid" : getAppState().currentItemStrokeStyle; - - // Initial arrow creation (placeholder points) - const startPoint = [parentBox.minX + parentBox.width / 2, parentBox.minY + parentBox.height / 2]; - arrowId = ea.addArrow([startPoint, startPoint], { - startObjectId: parent.id, - endObjectId: newNodeId, - startArrowHead: null, - endArrowHead: null, - }); - const eaArrow = ea.getElement(arrowId); - - // Initialize Roundness based on arrow type - if (effectiveArrowType === "curved") { - eaArrow.roundness = { - type: 2 - }; - } else { - eaArrow.roundness = null; - } - - ea.addAppendUpdateCustomData(arrowId, { - isBranch: true - }); - - if (ontology) { - addUpdateArrowLabel(eaArrow, ontology); - } - - if (!groupBranches && parent.groupIds?.length > 0) { - const mindmapIds = getBranchElementIds(parent.id, ea.getViewElements()); - const { - structuralGroupId - } = getStructuralGroupForNode(mindmapIds, allElements, rootId); - if (structuralGroupId) { - const newNode = ea.getElement(newNodeId); - const newArrow = ea.getElement(arrowId); - if (newNode) newNode.groupIds = [structuralGroupId]; - if (newArrow) newArrow.groupIds = [structuralGroupId]; - } - } - } - - if (isBatchMode) { - return ea.getElement(newNodeId); - } - - const hasImage = !!imageInfo?.imageFile || imageInfo?.isImagePath; - - await addElementsToView({ - repositionToCursor: !parent, - save: hasImage, - captureUpdate: "EVENTUALLY", - }); - - if (rootId && (autoLayoutDisabled || skipFinalLayout) && parent) { - const allEls = ea.getViewElements(); - const node = allEls.find((el) => el.id === newNodeId); - const arrow = allEls.find( - (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === newNodeId, - ); - - ea.copyViewElementsToEAforEditing(groupBranches ? allEls : arrow ? [arrow] : []); - - if (arrow) { - const parentCenterX = parent.x + parent.width / 2; - const childCenterX = node.x + node.width / 2; - const isChildRight = childCenterX > parentCenterX; - - const sX = isChildRight ? parent.x + parent.width : parent.x; - const sY = parent.y + parent.height / 2; - - const eX = isChildRight ? node.x : node.x + node.width; - const eY = node.y + node.height / 2; - - configureArrow({ - arrowId: arrow.id, - isChildRight, - startId: parent.id, - endId: node.id, - coordinates: { - sX, - sY, - eX, - eY - }, - }); - } - - if (groupBranches) { - ea.getElements().forEach((el) => { - if (el.groupIds) { - el.groupIds = el.groupIds.filter(gid => !isMindmapGroup(gid, allEls)); - } - }); - const l1Nodes = getChildrenNodes(rootId, allEls); - l1Nodes.forEach((l1) => applyRecursiveGrouping(l1.id, allEls)); - } else { - const { - l1AncestorId - } = getHierarchy(parent, allEls); - const bIds = getBranchElementIds(l1AncestorId, allEls); - - const existingGroupedEl = allEls.find(el => - bIds.includes(el.id) && - el.id !== newNodeId && - el.id !== arrowId && - getStructuralGroup(el, allEls, rootId) - ); - const commonGroupId = existingGroupedEl ? getStructuralGroup(existingGroupedEl, allEls, rootId) : null; - - if (commonGroupId) { - const newIds = [newNodeId, arrowId].filter(Boolean); - ea.copyViewElementsToEAforEditing(allEls.filter(el => newIds.includes(el.id))); - newIds.forEach(id => { - const el = ea.getElement(id); - if (el) el.groupIds = [commonGroupId]; - }); - } - } - - await addElementsToView({ - captureUpdate: "EVENTUALLY" - }); - } - const finalNode = ea.getViewElements().find((el) => el.id === newNodeId); - if (follow || !parent) { - selectNodeInView(finalNode); - } else if (parent) { - selectNodeInView(parent); - } - if (!parent) { - zoomToFit(); - } - - mostRecentlyAddedNodeID = finalNode.id; - focusInputEl(); - await triggerGlobalLayout(rootId); - return finalNode; -}; - -// --------------------------------------------------------------------------- -// 5. Copy & Paste Engine -// --------------------------------------------------------------------------- - -/** - * Checks if a node text contains exactly one wiki link to a markdown file and returns that TFile. - */ -const getNodeMarkdownFile = (nodeText) => { - if (!nodeText || !ea.targetView || !ea.targetView.file) return null; - // Match [[filename]] or [[filename|alias]] that takes up the whole string - const parts = nodeText.trim().match(/^\[\[([^#\|\]]+)[^\]]*]]$/); - if (!!parts?.[1]) { - const file = app.metadataCache.getFirstLinkpathDest(parts[1], ea.targetView.file.path); - return (file && file.extension === "md") ? file : null; - } - return null; -} - -/** - * Generates a hierarchy of links based on the headings in the target file. - */ -const importOutline = async () => { - if (!isViewSet()) return; - - const sel = getMindmapNodeFromSelection(); - if (!sel) { - new Notice(t("NOTICE_SELECT_NODE_CONTAINING_LINK")); - return; - } - - const allElements = ea.getViewElements(); - const nodeText = getTextFromNode(allElements, sel, true, false); // Get raw text - - const markdownFile = getNodeMarkdownFile(nodeText); - if (!markdownFile) { - new Notice(t("NOTICE_NO_LINKED_FILE")); - return; - } - - const cache = await app.metadataCache.blockCache.getForFile({ - isCancelled: () => false - }, markdownFile); - if (!cache || !cache.blocks) { - new Notice(t("NOTICE_NO_HEADINGS")); - return; - } - - const shortFilePath = app.metadataCache.fileToLinktext(markdownFile, ea.targetView.file.path, true); - const outlines = []; - - for (const block of cache.blocks) { - if (block.node.type === "heading") { - const depth = block.node.depth; - - // Strip markdown heading markers (# ) from display text - const rawHeadingText = block.display.replace(/^#+\s+/, ""); - - if (rawHeadingText === "Excalidraw Data") break; - - // Format Alias: Replace pipe with space to prevent broken links - const alias = rawHeadingText.replace(/\|/g, " "); - - // Format Anchor: replace specific chars (#|\:) with space for the link target - const anchor = rawHeadingText.replace(/[|#\\:]/g, " "); - - const indent = " ".repeat(Math.max(0, depth - 1)); - - outlines.push(`${indent}- [[${shortFilePath}#${anchor}|${alias}]]`); - } - } - - if (outlines.length === 0) { - new Notice(t("NOTICE_NO_HEADINGS")); - return; - } - - await importTextToMap(outlines.join("\n")); -}; - -/** -// Extracts text from a node, handling text elements, images, and embeddables. -**/ -const getTextFromNode = (all, node, getRaw = false, shortPath = false) => { - if (node.type === "embeddable") { - return node.link.startsWith("[[") ? `!${node.link}` : `![](${node.link})`; - } - if (node.type === "image") { - const embeddedFile = ea.targetView?.excalidrawData?.getFile(node.fileId); - if (!embeddedFile) return ""; - - const file = ea.getViewFileForImageElement(node); - - // Handle external image URLs or local file URIs saved in node.link - if (!file && node.link && node.link.match(/^(https?|file):\/\//i)) { - return `![image|${Math.round(node.width)}](${node.link})`; - } - - if (shortPath) { - const originalPath = embeddedFile.linkParts?.original; - return `![[${originalPath}|${Math.round(node.width)}]]`; - } - - if (file) { - if (file.extension === "pdf" && node.link?.startsWith("[[")) { - return `!${node.link.match(/^(.*?)\]\]/)[1]}|${Math.round(node.width)}]]`; - } - return `![[${file.path}${embeddedFile.filenameparts?.linkpartReference || ""}|${Math.round(node.width)}]]`; - } - return ""; - } - if (node.type === "text") { - return getRaw ? node.rawText : node.originalText; - } - const textId = node.boundElements?.find((be) => be.type === "text")?.id; - if (!textId) return ""; - const textEl = all.find((el) => el.id === textId); - return textEl ? (getRaw ? textEl.rawText : textEl.originalText) : ""; -}; - -/** -// Copies the selected tree or branch to the clipboard as Markdown text. -// Now supports extracting Submaps into separate ## Headings referenced by ![[#Links]] -**/ -const copyMapAsText = async (cut = false, toClipboard = true) => { - if (!isViewSet()) return; - ensureNodeSelected(); - const sel = getMindmapNodeFromSelection(); - if (!sel) { - new Notice(t("NOTICE_SELECT_NODE_TO_COPY")); - return; - } - const all = ea.getViewElements(); - const info = getHierarchy(sel, all); - - const isRootSelected = info.rootId === sel.id; - const parentNode = getParentNode(sel.id, all); - - // Retrieve root to determine growthMode for sorting logic - const root = all.find(el => el.id === info.rootId); - const defaultMode = root?.customData?.growthMode || currentModalGrowthMode; - - const elementsToDelete = []; - - const useTab = app.vault.getConfig("useTab"); - const tabSize = app.vault.getConfig("tabSize"); - const indentVal = useTab ? "\t" : " ".repeat(tabSize); - - // --- Crosslink & Block Reference Logic --- - const branchIds = new Set(getBranchElementIds(sel.id, all)); - - const nodeBlockRefs = new Map(); // NodeID -> "^blockId" - const nodeOutgoingLinks = new Map(); // NodeID -> ["text representation", ...] - - // Find arrows within this branch that are NOT structural branch arrows - const crossLinkArrows = all.filter(el => - el.type === "arrow" && - !el.customData?.isBranch && - branchIds.has(el.startBinding?.elementId) && - branchIds.has(el.endBinding?.elementId) - ); - - const hasCrosslinks = crossLinkArrows.length > 0; - // Use Loose List (empty lines) if crosslinks exist to support block refs, else Tight List - const lineSeparator = hasCrosslinks ? "\n\n" : "\n"; - - if (hasCrosslinks) { - crossLinkArrows.forEach(arrow => { - const startId = arrow.startBinding.elementId; - const endId = arrow.endBinding.elementId; - - // Generate block ref for destination if not exists - if (!nodeBlockRefs.has(endId)) { - nodeBlockRefs.set(endId, "^" + ea.generateElementId().substring(0, 8)); - } - - // Record outgoing link for source - if (!nodeOutgoingLinks.has(startId)) { - nodeOutgoingLinks.set(startId, []); - } - - // Check for label on the arrow - const boundTextId = arrow.boundElements?.find(be => be.type === "text")?.id; - const labelTextElement = boundTextId ? all.find(el => el.id === boundTextId) : null; - const refString = nodeBlockRefs.get(endId); - - let linkText; - if (labelTextElement && labelTextElement.rawText) { - // Replace newlines with spaces for inline dataview field compatibility - const label = labelTextElement.rawText.replace(/\n/g, " "); - linkText = `(${label}:: [[#${refString}|*]])`; - } else { - linkText = `[[#${refString}|*]]`; - } - - nodeOutgoingLinks.get(startId).push(linkText); - - if (cut) elementsToDelete.push(arrow); - }); - } - - const submapsQueue = []; - - const buildList = (nodeId, depth = 0, isSubmapChild = false, isPrintRoot = false) => { - const node = all.find((e) => e.id === nodeId); - if (!node) return ""; - - if (cut) { - elementsToDelete.push(node); - node.boundElements?.forEach((be) => { - const boundEl = all.find((e) => e.id === be.id); - if (boundEl) elementsToDelete.push(boundEl); - }); - - if (node.customData?.foldIndicatorId) { - const ind = all.find(e => e.id === node.customData.foldIndicatorId); - if (ind) elementsToDelete.push(ind); - } - - // Remove boundary if cutting - if (node.customData?.boundaryId) { - const boundary = all.find(e => e.id === node.customData.boundaryId); - if (boundary) elementsToDelete.push(boundary); - } - } - - let str = ""; - let text = getTextFromNode(all, node, true); - - let ontologyStr = ""; - // Fetch ontology if it's not the absolute root, or if it's a child within a submap layout - if ((!isRootSelected || depth > 0) || isSubmapChild) { - const incomingArrow = all.find( - (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === nodeId - ); - if (incomingArrow) { - const boundTextEl = ea.getBoundTextElement(incomingArrow, true).sceneElement; - if (boundTextEl && boundTextEl.rawText) { - // Replace newlines with spaces so it stays on one line - ontologyStr = boundTextEl.rawText.replace(/\n/g, " ") + ":: "; - if (cut) elementsToDelete.push(boundTextEl); - } - } - } - - // --- Append Metadata Suffixes --- - let refSuffixes = ""; - if (nodeOutgoingLinks.has(nodeId)) refSuffixes += ` ${nodeOutgoingLinks.get(nodeId).join(" ")}`; - if (node.customData?.boundaryId) refSuffixes += " #boundary"; - if (nodeBlockRefs.has(nodeId)) refSuffixes += ` ${nodeBlockRefs.get(nodeId)}`; - - // --- Extract Task Info --- - let isTask = false; - let taskPrefix = ""; - const taskMatch = text.match(/^- \[[ xX]\] /); - if (taskMatch) { - isTask = true; - taskPrefix = taskMatch[0]; // Retain "- [ ] " or "- [x] " - text = text.substring(taskPrefix.length); // Strip it temporarily for clean assembly - } - - // --- Submap Extraction Logic --- - // If this node is an additional root AND it's not the immediate element we are printing the section for - if (!isPrintRoot && node.customData?.isAdditionalRoot) { - let submapTitle = text; - // Clean up Image strings to use as clean anchor links - if (submapTitle.startsWith("![[") && submapTitle.endsWith("]]")) { - submapTitle = submapTitle.slice(3, -2).split("|")[0]; - } else if (submapTitle.startsWith("![") && submapTitle.endsWith(")")) { - submapTitle = "Submap " + nodeId.substring(0, 4); - } - - const linkText = `![[#${submapTitle}]]`; - const repeatCount = Math.max(0, depth - (isRootSelected ? 1 : 0)); - let currentIndent = isSubmapChild ? indentVal.repeat(depth) : indentVal.repeat(repeatCount); - - // Inject task prefix if available - if (isTask) { - str += `${currentIndent}${taskPrefix}${ontologyStr}${linkText}${refSuffixes}${lineSeparator}`; - } else { - str += `${currentIndent}- ${ontologyStr}${linkText}${refSuffixes}${lineSeparator}`; - } - submapsQueue.push({ - id: nodeId, - title: submapTitle - }); - - return str; // Do not recurse into children here; they belong in the ## section - } - - if (depth === 0 && isRootSelected && !isSubmapChild) { - str += `# ${taskPrefix}${ontologyStr}${text}${refSuffixes}${lineSeparator}`; - } else { - const repeatCount = Math.max(0, depth - (isRootSelected ? 1 : 0)); - let currentIndent = isSubmapChild ? indentVal.repeat(depth) : indentVal.repeat(repeatCount); - if (isTask) { - str += `${currentIndent}${taskPrefix}${ontologyStr}${text}${refSuffixes}${lineSeparator}`; - } else { - str += `${currentIndent}- ${ontologyStr}${text}${refSuffixes}${lineSeparator}`; - } - } - - // --- Visual Sorting Logic --- - let children = getChildrenNodes(nodeId, all); - const parentCenter = { - x: node.x + node.width / 2, - y: node.y + node.height / 2 - }; - - // Honor local submap modes - const mode = node.customData?.isAdditionalRoot ? node.customData.growthMode : defaultMode; - - if (mode === "Radial") { - children.sort((a, b) => { - const centerA = { - x: a.x + a.width / 2, - y: a.y + a.height / 2 - }; - const centerB = { - x: b.x + b.width / 2, - y: b.y + b.height / 2 - }; - return getAngleFromCenter(parentCenter, centerA) - getAngleFromCenter(parentCenter, centerB); - }); - } else if (mode === "Right-Left" && nodeId === info.rootId) { - const right = []; - const left = []; - children.forEach(child => { - const childCx = child.x + child.width / 2; - if (childCx > parentCenter.x) right.push(child); - else left.push(child); - }); - right.sort((a, b) => a.y - b.y); - left.sort((a, b) => a.y - b.y); - children = [...right, ...left]; - } else { - children.sort((a, b) => a.y - b.y); - } - - children.forEach((c) => { - if (cut) { - const arrow = all.find( - (a) => - a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === nodeId && - a.endBinding?.elementId === c.id, - ); - if (arrow) elementsToDelete.push(arrow); - } - // Children of a printRoot are not the printRoot - str += buildList(c.id, depth + 1, isSubmapChild, false); - }); - return str; - }; - - let md = buildList(sel.id, 0, false, true); - - // --- Process Queued Submaps --- - const processedSubmaps = new Set(); - - // Add divider if submaps exist - if (submapsQueue.length > 0) { - md += `\n---\n`; - } - - while (submapsQueue.length > 0) { - const submapObj = submapsQueue.shift(); - if (processedSubmaps.has(submapObj.id)) continue; - processedSubmaps.add(submapObj.id); - - md += `\n## ${submapObj.title}\n`; - - const submapNode = all.find(e => e.id === submapObj.id); - let children = getChildrenNodes(submapObj.id, all); - - const parentCenter = { - x: submapNode.x + submapNode.width / 2, - y: submapNode.y + submapNode.height / 2 - }; - const mode = submapNode.customData?.growthMode || defaultMode; - - if (mode === "Radial") { - children.sort((a, b) => { - const centerA = { - x: a.x + a.width / 2, - y: a.y + a.height / 2 - }; - const centerB = { - x: b.x + b.width / 2, - y: b.y + b.height / 2 - }; - return getAngleFromCenter(parentCenter, centerA) - getAngleFromCenter(parentCenter, centerB); - }); - } else if (mode === "Right-Left") { - const right = []; - const left = []; - children.forEach(child => { - const childCx = child.x + child.width / 2; - if (childCx > parentCenter.x) right.push(child); - else left.push(child); - }); - right.sort((a, b) => a.y - b.y); - left.sort((a, b) => a.y - b.y); - children = [...right, ...left]; - } else { - children.sort((a, b) => a.y - b.y); - } - - children.forEach((c) => { - if (cut) { - const arrow = all.find( - (a) => - a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === submapObj.id && - a.endBinding?.elementId === c.id, - ); - if (arrow) elementsToDelete.push(arrow); - } - md += buildList(c.id, 0, true, false); - }); - } - - if (toClipboard) await navigator.clipboard.writeText(md); - - if (cut) { - const incomingArrow = all.find( - (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === sel.id, - ); - if (incomingArrow) elementsToDelete.push(incomingArrow); - - ea.deleteViewElements(elementsToDelete); - - if (parentNode) { - const remainingChildren = getChildrenNodes(parentNode.id, ea.getViewElements()); - - if (remainingChildren.length === 0) { - ea.copyViewElementsToEAforEditing([parentNode]); - ea.addAppendUpdateCustomData(parentNode.id, { - isFolded: false, - foldIndicatorId: undefined - }); - - if (parentNode.customData?.foldIndicatorId) { - const indicator = ea.getViewElements().find(el => el.id === parentNode.customData.foldIndicatorId); - if (indicator) ea.deleteViewElements([indicator]); - } - - await addElementsToView({ - captureUpdate: "EVENTUALLY" - }); - } - selectNodeInView(parentNode); - } - - triggerGlobalLayout(info.rootId); - new Notice(isRootSelected ? t("NOTICE_MAP_CUT") : t("NOTICE_BRANCH_CUT")); - } else { - new Notice(isRootSelected ? t("NOTICE_MAP_COPIED") : t("NOTICE_BRANCH_COPIED")); - } - return md; -}; - -/** -// Core logic to parse a list string and add nodes to the map. -// Now dynamically links "## Submap" definitions to their "![[#Submap]]" embed nodes. -**/ -const importTextToMap = async (rawText) => { - if (!isViewSet()) return; - if (!rawText) return; - - let sel = getMindmapNodeFromSelection(); - let currentParent; - - // Filter out empty lines AND divider lines - const lines = rawText.split(/\r\n|\n|\r/).filter((l) => { - const trimmed = l.trim(); - return trimmed !== "" && !/^-{3,}$/.test(trimmed); - }); - - if (lines.length === 0) return; - - // Regex patterns - const boundaryRegex = /\s#boundary\b/; - const blockRefRegex = /\s\^([a-zA-Z0-9]{8})$/; - const crossLinkRegex = /(?:\(([^):]+)::\s*)?\[\[#\^([a-zA-Z0-9]{8})\|\*\]\](?:\))?/g; - const ontologyRegex = /^(.+?)::\s*(.*)$/; - const submapRefRegex = /^!\[\[#([^\]]+)\]\]$/; // Matches ![[#Submap Name]] - - if (lines.length === 1) { - let text = lines[0]; - const listMatch = text.match(/^(\s*)(?:-|\*|\d+\.)\s+(.*)$/); - if (listMatch) { - text = listMatch[2].trim(); - if (/^\[[ xX]\] /.test(text)) { - // Retain task syntax if it was an imported list item - text = "- " + text; - } - } else { - text = text.trim(); - } - - text = text.replace(boundaryRegex, ""); - text = text.replace(blockRefRegex, ""); - - const ontologyMatch = text.match(ontologyRegex); - let ontology = null; - if (ontologyMatch) { - ontology = ontologyMatch[1].trim(); - text = ontologyMatch[2].trim(); - } - - let isSubmapRef = false; - const submapRefMatch = text.match(submapRefRegex); - if (submapRefMatch) { - isSubmapRef = true; - text = submapRefMatch[1].trim(); - } - - if (text) { - currentParent = await addNode(text.trim(), true, false, null, null, null, ontology); - if (isSubmapRef) { - ea.addAppendUpdateCustomData(currentParent.id, { - isAdditionalRoot: true - }); - } - if (sel) { - selectNodeInView(sel); - } - return; - } - } - - let parsed = []; - let rootTextFromHeader = null; - - const isHeader = (l) => l.match(/^#+\s/); - const isListItem = (l) => l.match(/^(\s*)(?:-|\*|\d+\.)\s+(.*)$/); - - if (!isHeader(lines[0]) && !isListItem(lines[0])) { - new Notice(t("NOTICE_PASTE_ABORTED")); - return; - } - - const delta = isHeader(lines[0]) ? 1 : 0; - - const notice = new Notice(t("NOTICE_PASTE_START"), 0); - await sleep(10); - - // Maps for crosslink & submap reconstruction - const blockRefToNodeId = new Map(); // ^12345678 -> newNodeId - const nodeToOutgoingRefs = new Map(); // newNodeId -> [{ref: string, label: string}, ...] - - lines.forEach((line, index) => { - let text = ""; - let indent = 0; - let isSubmapDef = false; - - if (isHeader(line)) { - if (index === 0) { - indent = 0; - text = line.replace(/^#+\s/, "").trim(); - } else { - // Subsequent headers signify details of a Submap - isSubmapDef = true; - text = line.replace(/^#+\s/, "").trim(); - indent = -1; // Special indent pushes it strictly below its parent in stack validation - } - } else { - const match = isListItem(line); - if (match) { - indent = delta + match[1].length; - let extractedText = match[2].trim(); - // Check if list item has task bracket syntax - if (/^\[[ xX]\] /.test(extractedText)) { - extractedText = "- " + extractedText; - } - text = extractedText; - } else if (parsed.length > 0) { - // multiline handling - parsed[parsed.length - 1].text += "\n" + line.trim(); - return; - } - } - - if (text || isSubmapDef) { - const hasBoundary = boundaryRegex.test(text); - text = text.replace(boundaryRegex, ""); - - const refMatch = text.match(blockRefRegex); - let blockRef = null; - if (refMatch) { - blockRef = refMatch[1]; - text = text.replace(blockRefRegex, ""); - } - - const outgoingRefs = []; - crossLinkRegex.lastIndex = 0; - text = text.replace(crossLinkRegex, (_match, label, ref) => { - outgoingRefs.push({ - ref: ref, - label: label ? label.trim() : null - }); - return ""; - }); - - const ontologyMatch = text.match(ontologyRegex); - let ontology = null; - if (ontologyMatch) { - ontology = ontologyMatch[1].trim(); - text = ontologyMatch[2].trim(); - } - - let isSubmapRef = false; - text = text.trim(); - const submapRefMatch = text.match(submapRefRegex); - if (submapRefMatch) { - isSubmapRef = true; - text = submapRefMatch[1].trim(); - } - - parsed.push({ - indent, - text, - hasBoundary, - blockRef, - outgoingRefs, - ontology, - isSubmapDef, - isSubmapRef - }); - } - }); - - if (parsed.length === 0 && !rootTextFromHeader) { - new Notice(t("NOTICE_NO_LIST")); - return; - } - - ea.clear(); - - const rootSelected = !!sel; - const createdBoundaries = []; - - const createImportBoundary = (nodeId) => { - const node = ea.getElement(nodeId); - if (!node) return; - - const id = ea.generateElementId(); - const st = getAppState(); - const boundaryEl = { - id: id, - type: "line", - x: node.x, - y: node.y, - width: 1, - height: 1, - angle: 0, - roughness: st.currentItemRoughness, - strokeColor: node.strokeColor, - backgroundColor: node.strokeColor, - fillStyle: "solid", - strokeWidth: 2, - strokeStyle: "solid", - opacity: 30, - points: [ - [0, 0], - [1, 1], - [0, 0] - ], - polygon: true, - locked: false, - groupIds: node.groupIds || [], - customData: { - isBoundary: true - }, - roundness: arrowType === "curved" ? { - type: 2 - } : null, - }; - - ea.elementsDict[id] = boundaryEl; - ea.addAppendUpdateCustomData(nodeId, { - boundaryId: id - }); - createdBoundaries.push({ - nodeId, - boundaryId: id - }); - }; - - const submapNodesByName = new Map(); - - if (!sel) { - // Filter out submap definitions (-1 indent) to accurately find the true top-level items - const nonSubmapItems = parsed.filter((p) => !p.isSubmapDef); - const minIndent = Math.min(...nonSubmapItems.map((p) => p.indent)); - const topLevelItems = nonSubmapItems.filter((p) => p.indent === minIndent); - - const processRootMeta = (item, id) => { - if (item.blockRef) blockRefToNodeId.set(item.blockRef, id); - if (item.outgoingRefs.length > 0) nodeToOutgoingRefs.set(id, item.outgoingRefs); - if (item.hasBoundary) createImportBoundary(id); - if (item.isSubmapRef) { - ea.addAppendUpdateCustomData(id, { - isAdditionalRoot: true - }); - submapNodesByName.set(item.text, ea.getElement(id)); - } - }; - - // If there is exactly one top-level item, it becomes the new master root - if (topLevelItems.length === 1) { - const rootItem = topLevelItems[0]; - const rootIndex = parsed.indexOf(rootItem); - - sel = currentParent = await addNode(rootItem.text, true, true, [], null, null, rootItem.ontology); - processRootMeta(rootItem, currentParent.id); - - // Safely extract the root item from the array so it isn't rendered twice - if (rootIndex !== -1) { - parsed.splice(rootIndex, 1); - } - } else { - sel = currentParent = await addNode(t("INPUT_TITLE_PASTE_ROOT"), true, true, [], null); - } - } else { - currentParent = sel; - ea.copyViewElementsToEAforEditing([sel]); - currentParent = ea.getElement(sel.id); - } - - const stack = [{ - indent: -1, - node: currentParent - }]; - - if (rootSelected) { - const allViewElements = ea.getViewElements(); - const info = getHierarchy(sel, allViewElements); - const projectElements = getMindmapProjectElements(info.rootId, allViewElements); - ea.copyViewElementsToEAforEditing(projectElements.filter(el => !ea.getElement(el.id))); - } - - for (const item of parsed) { - // Relocate stack parser root when encountering a ## Submap Header - if (item.isSubmapDef) { - const targetNode = submapNodesByName.get(item.text); - if (targetNode) { - stack.length = 0; - stack.push({ - indent: -1, - node: targetNode - }); - } else { - // Edge case: Submap def without embed. Create at root to salvage data. - const currentAllElements = ea.getElements(); - const newNode = await addNode(item.text, false, true, currentAllElements, currentParent, null, null); - ea.addAppendUpdateCustomData(newNode.id, { - isAdditionalRoot: true - }); - submapNodesByName.set(item.text, newNode); - stack.length = 0; - stack.push({ - indent: -1, - node: newNode - }); - } - continue; - } - - while (stack.length > 1 && item.indent <= stack[stack.length - 1].indent) { - stack.pop(); - } - const parentNode = stack[stack.length - 1].node; - const currentAllElements = ea.getElements(); - const newNode = await addNode(item.text, false, true, currentAllElements, parentNode, null, item.ontology); - - // Process Metadata - if (item.blockRef) blockRefToNodeId.set(item.blockRef, newNode.id); - if (item.outgoingRefs.length > 0) nodeToOutgoingRefs.set(newNode.id, item.outgoingRefs); - if (item.hasBoundary) createImportBoundary(newNode.id); - if (item.isSubmapRef) { - ea.addAppendUpdateCustomData(newNode.id, { - isAdditionalRoot: true - }); - submapNodesByName.set(item.text, newNode); - } - - stack.push({ - indent: item.indent, - node: newNode - }); - } - - // ------------------------------------------------------------------------- - // Generate Crosslinks - // ------------------------------------------------------------------------- - nodeToOutgoingRefs.forEach((targetRefs, sourceId) => { - targetRefs.forEach(targetObj => { - const { - ref, - label - } = targetObj; - const targetId = blockRefToNodeId.get(ref); - - if (targetId) { - const arrowId = ea.connectObjects( - sourceId, null, - targetId, null, { - startArrowHead: null, - endArrowHead: "triangle" - } - ); - - const arrowEl = ea.getElement(arrowId); - if (arrowEl) { - arrowEl.strokeStyle = "dashed"; - addUpdateArrowLabel(arrowEl, label); - } - } - }); - }); - - // ------------------------------------------------------------------------- - // "Right-Left" Balanced Layout Adjustment for Imported L1 Nodes - // ------------------------------------------------------------------------- - const rootIdForImport = sel ? - getHierarchy(sel, ea.getElements()).rootId : - currentParent.id; - - const rootElForImport = sel ? - ea.getElement(rootIdForImport) : - currentParent; - - if (rootElForImport) { - const mode = rootElForImport.customData?.growthMode || currentModalGrowthMode; - if (mode === "Right-Left" && currentParent.id === rootIdForImport) { - - const eaElements = ea.getElements(); - const importedL1Nodes = eaElements.filter(el => - el.customData?.mindmapNew && - eaElements.some(arrow => - arrow.type === "arrow" && - arrow.customData?.isBranch && - arrow.startBinding?.elementId === currentParent.id && - arrow.endBinding?.elementId === el.id - ) - ); - - importedL1Nodes.sort((a, b) => (a.customData?.mindmapOrder || 0) - (b.customData?.mindmapOrder || 0)); - - if (importedL1Nodes.length > 0) { - const splitIndex = Math.ceil(importedL1Nodes.length / 2); - - importedL1Nodes.forEach((node, i) => { - ea.addAppendUpdateCustomData(node.id, { - mindmapNew: undefined - }); - - if (i < splitIndex) { - node.x = rootElForImport.x + rootElForImport.width + 100; - } else { - node.x = rootElForImport.x - node.width - 100; - } - }); - } - } - } - - await addElementsToView({ - repositionToCursor: !rootSelected, - captureUpdate: "EVENTUALLY" - }); - - // ------------------------------------------------------------------------- - // Fix Z-Index for Created Boundaries (Parents Below Children) - // ------------------------------------------------------------------------- - if (createdBoundaries.length > 0) { - const allEls = ea.getViewElements(); - - const boundariesWithDepth = createdBoundaries.map(b => { - const node = allEls.find(e => e.id === b.nodeId); - const depth = node ? getHierarchy(node, allEls).depth : 0; - return { - ...b, - depth - }; - }); - - boundariesWithDepth.sort((a, b) => a.depth - b.depth); - - for (const b of boundariesWithDepth) { - const currentEls = ea.getViewElements(); - - let parentBoundaryIndex = -1; - let curr = currentEls.find(e => e.id === b.nodeId); - - while (curr) { - const parent = getParentNode(curr.id, currentEls); - if (!parent) break; - if (parent.customData?.boundaryId) { - const pIndex = currentEls.findIndex(el => el.id === parent.customData.boundaryId); - if (pIndex !== -1) { - parentBoundaryIndex = pIndex; - break; - } - } - curr = parent; - } - - const targetIndex = parentBoundaryIndex !== -1 ? parentBoundaryIndex + 1 : 0; - ea.moveViewElementToZIndex(b.boundaryId, targetIndex); - } - } - - const allInView = ea.getViewElements(); - const targetToSelect = sel ? - allInView.find((e) => e.id === sel.id) : - allInView.find((e) => e.id === currentParent?.id); - - if (targetToSelect) { - selectNodeInView(targetToSelect); - } - - const rootId = sel ? - getHierarchy(sel, allInView).rootId : - currentParent.id; - await triggerGlobalLayout(rootId); - - notice.setMessage(t("NOTICE_PASTE_COMPLETE")); - notice.setAutoHide(4000); -}; - -/** -// Pastes a Markdown list from clipboard into the map, converting it to nodes. -**/ -const pasteListToMap = async (contentToPaste = null) => { - const rawText = contentToPaste || await navigator.clipboard.readText(); - if (!rawText) { - new Notice(t("NOTICE_CLIPBOARD_EMPTY")); - return; - } - await importTextToMap(rawText); -}; - -/** - * Intelligent paste dispatcher. Parses clipboard for Element JSON / Raw Images, - * translates them to Markdown strings, and passes them to `addNode()`. - */ -const pasteElementToMap = async () => { - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - - // Standard text-list paste handles root-level initialization better - if (!sel) { - await pasteListToMap(); - return; - } - - let rawText = ""; - try { - rawText = await navigator.clipboard.readText(); - } catch (e) {} - - const excalidrawClipboardPayload = rawText && rawText.includes('"type":"excalidraw/clipboard"'); - - // Scenario 1: Excalidraw Element JSON (Single Element or Container+Text) - if (excalidrawClipboardPayload) { - let clipboardData; - try { - clipboardData = JSON.parse(rawText); - } catch (e) {} - - if (clipboardData && clipboardData.elements) { - const els = clipboardData.elements.filter(e => !e.isDeleted); - const isSingleElement = els.length === 1 && ["embeddable", "text"].includes(els[0].type); - - const textEl = els.find(e => e.type === "text"); - const containerEl = els.find(e => ["rectangle", "ellipse", "diamond"].includes(e.type)); - const isContainerText = els.length === 2 && textEl && containerEl && textEl.containerId === containerEl.id; - - const isSingleImageJSON = els.length === 1 && els[0].type === "image"; - - if (isSingleImageJSON) { - const fileId = els[0].fileId; - const imagePathResolved = ea.getPathForImageFileId(fileId); - - if (imagePathResolved) { - if (app.vault.getFileByPath(imagePathResolved)) { - await pasteListToMap(`![[${imagePathResolved}]]`); - } else { - await pasteListToMap(`![pasted image](${imagePathResolved})`); - } - return; - } - } else if (isSingleElement || isContainerText) { - let textToPaste = ""; - let shapeToPaste = null; - - if (isContainerText) { - textToPaste = textEl.rawText; - shapeToPaste = containerEl.type; - } else if (els[0].type === "text") { - textToPaste = els[0].rawText; - } else if (els[0].type === "embeddable") { - const link = els[0].link; - if (link.match(/^https?:\/\//i)) { - textToPaste = `![](${link})`; - } else { - textToPaste = link.startsWith("[[") ? `!${link}` : `![[${link}]]`; - } - if (textToPaste) { - pasteListToMap(textToPaste); - return; - } - } - - if (textToPaste) { - // Add as a normal node using central logic - const newNode = await addNode(textToPaste, false, false, null, null, null, null); - - // Copy link from clipboard text element if present to preserve references - if (newNode && textEl && textEl.link) { - const freshNode = ea.getViewElements().find(el => el.id === newNode.id); - if (freshNode) { - ea.copyViewElementsToEAforEditing([freshNode]); - ea.getElement(freshNode.id).link = textEl.link; - await addElementsToView({ - captureUpdate: "EVENTUALLY" - }); - } - } - - // Recreate the shape if it was inside a container - if (shapeToPaste) { - const isContainer = ["rectangle", "ellipse", "diamond"].includes(newNode.type); - if (isContainer) { - if (newNode.type !== shapeToPaste) { - selectNodeInView(newNode); - await toggleBox(); // Removes auto-added box of the wrong shape - await toggleBox(shapeToPaste); // Re-adds correct shape box - } - } else { - selectNodeInView(newNode); - await toggleBox(shapeToPaste); - } - } - return; - } - } - } - } - - // Scenario 2: Native image payload intercepted from system clipboard (Blobs) - let hasImageBlob = false; - let blob = null; - let mimeType = null; - try { - const items = await navigator.clipboard.read(); - for (const item of items) { - const imageType = item.types.find(t => t.startsWith("image/")); - if (imageType) { - hasImageBlob = true; - mimeType = imageType; - blob = await item.getType(imageType); - break; - } - } - } catch (e) {} - - if (hasImageBlob) { - const beforeIds = new Set(ea.getViewElements().map(e => e.id)); - - // Trigger native paste via synthetic event so Excalidraw saves the file natively - const dt = new DataTransfer(); - if (hasImageBlob && blob) { - const file = new File([blob], `Pasted image.${mimeType.split("/")[1] || "png"}`, { - type: mimeType - }); - dt.items.add(file); - } - - const pasteEvent = new ClipboardEvent("paste", { - clipboardData: dt, - bubbles: true, - cancelable: true - }); - - const targetEl = ea.targetView.contentEl.querySelector(".excalidraw") || ea.targetView.contentEl; - const originallySelectedElement = ea.getViewSelectedElement(); - targetEl.dispatchEvent(pasteEvent); - - let newImageEl = null; - - // Poll to wait for Excalidraw to assign a fileId to the new image - for (let i = 0; i < 40; i++) { - await sleep(50); - const currentElements = ea.getViewElements(); - const added = currentElements.filter(e => !beforeIds.has(e.id) && e.type === "image"); - - if (added.length > 0) { - const tmpNewImageEl = added[added.length - 1]; - if (!tmpNewImageEl.fileId) continue; - - // Verify the image file path is resolved in the EA cache - const path = ea.getPathForImageFileId(tmpNewImageEl.fileId); - if (!path) continue; - - newImageEl = tmpNewImageEl; - break; - } - } - - if (newImageEl) { - // Silently delete the temporary pasted image - await sleep(200); // contingency to ensure Excalidraw has finished processing the new image - const imageID = newImageEl.id; - - const imagePathResolved = ea.getPathForImageFileId(newImageEl.fileId); - - ea.clear(); - ea.copyViewElementsToEAforEditing([newImageEl]); - ea.getElement(imageID).isDeleted = true; - await addElementsToView({ - captureUpdate: "EVENTUALLY", - shouldRestoreElements: false - }); - - if (originallySelectedElement) { - ea.selectElementsInView([originallySelectedElement.id]); // Reselect original node because paste image steals selection - } - - if (imagePathResolved) { - await pasteListToMap(`![pasted image](${imagePathResolved})`); - } - } - return; - } - - // Fallback to Outline parser - if (!excalidrawClipboardPayload) { - await pasteListToMap(); - } else { - new Notice(t("NOTICE_PASTE_ABORTED")); - } -}; - -// --------------------------------------------------------------------------- -// 6. Map Actions -// --------------------------------------------------------------------------- - -/** - * Reconnects an arrow from one element to another. - * Updates the arrow's binding (start or end) and maintains the boundElements arrays - * of both the old and new parent nodes to ensure consistency. - * - * @param {ExcalidrawElement} currentBindingElement - The node to disconnect from. - * @param {ExcalidrawElement} newBindingElement - The node to connect to. - * @param {ExcalidrawElement} arrow - The arrow element to rewire. - * @param {string} side - "start" or "end". Defaults to "start". - */ -const reconnectArrow = (currentBindingElement, newBindingElement, arrow, side = "start") => { - // 1. Ensure all involved elements are in the EA workbench - const elementsToCheck = [currentBindingElement, newBindingElement, arrow]; - const elementsToCopy = elementsToCheck.filter(el => !ea.getElement(el.id)); - - if (elementsToCopy.length > 0) { - ea.copyViewElementsToEAforEditing(elementsToCopy); - } - - // 2. Retrieve mutable references from EA - const oldNode = ea.getElement(currentBindingElement.id); - const newNode = ea.getElement(newBindingElement.id); - const targetArrow = ea.getElement(arrow.id); - - // 3. Update the Arrow's binding property - const bindingKey = side === "start" ? "startBinding" : "endBinding"; - targetArrow[bindingKey] = { - ...(targetArrow[bindingKey] || {}), - elementId: newNode.id - }; - - // 4. Remove arrow reference from the Old Node's boundElements - if (oldNode.boundElements) { - oldNode.boundElements = oldNode.boundElements.filter(be => be.id !== targetArrow.id); - } - - // 5. Add arrow reference to the New Node's boundElements - if (!newNode.boundElements) newNode.boundElements = []; - // Prevent duplicates - if (!newNode.boundElements.some(be => be.id === targetArrow.id)) { - newNode.boundElements.push({ - type: "arrow", - id: targetArrow.id - }); - } -}; - -/** - * Recursively updates the font size of a subtree based on the new depth level. - * Only updates if the current font size matches the default for its *previous* depth, - * preserving user customizations. - * Also updates the ontology label (if present) on the incoming arrow to be half the node's new size. - */ -const updateSubtreeFontSize = (nodeId, newDepth, oldDepth, allElements, newFontScaleType, oldFontScaleType) => { - const newFontScale = getFontScale(newFontScaleType); - const oldFontScale = getFontScale(oldFontScaleType); - - const node = allElements.find(el => el.id === nodeId); - if (!node) return; - if (!ea.getElement(nodeId)) { - ea.copyViewElementsToEAforEditing([node]); - } - - // Calculate standard sizes based on the old and new contexts - const oldStandardSize = oldFontScale[Math.min(oldDepth, oldFontScale.length - 1)]; - const newStandardSize = newFontScale[Math.min(newDepth, newFontScale.length - 1)]; - - // Update only if the user hasn't customized the font size - if (node.fontSize === oldStandardSize) { - const eaNode = ea.getElement(nodeId); - eaNode.fontSize = newStandardSize; - - // Refresh dimensions to fit new font size - if (eaNode.type === "text" || (eaNode.boundElements && eaNode.boundElements.some(b => b.type === "text"))) { - ea.refreshTextElementSize(eaNode.id); - } - } - - // Update Ontology (Arrow Label) size - // Find the arrow pointing TO this node - const incomingArrow = allElements.find( - (a) => a.type === "arrow" && - a.customData?.isBranch && - a.endBinding?.elementId === nodeId - ); - - if (incomingArrow) { - // Get the bound text element (ontology) - const maybeTextElement = ea.getBoundTextElement(incomingArrow, true); - let eaOntologyEl = maybeTextElement.eaElement; - - // If it exists in the scene but not yet in EA workbench, copy it - if (!eaOntologyEl && maybeTextElement.sceneElement) { - ea.copyViewElementsToEAforEditing([maybeTextElement.sceneElement]); - eaOntologyEl = ea.getElement(maybeTextElement.sceneElement.id); - } - - // Apply half-size logic - if (eaOntologyEl && eaOntologyEl.fontSize === Math.floor(oldStandardSize / 2)) { - eaOntologyEl.fontSize = Math.floor(newStandardSize / 2); - ea.refreshTextElementSize(eaOntologyEl.id); - } - } - - // Stop recursion if this node is an additional root (submap). - // Its own node size updates to match the parent, but its children scale relative to IT. - if (node.customData?.isAdditionalRoot === true) { - return; - } - - // Recurse to children - const children = getChildrenNodes(nodeId, allElements); - children.forEach(child => { - updateSubtreeFontSize(child.id, newDepth + 1, oldDepth + 1, allElements, newFontScaleType, oldFontScaleType); - }); -}; - -/** - * Recursively updates the stroke width of a subtree based on the new depth level. - * Only updates if the current width matches the default for its *previous* depth. - */ -const updateSubtreeStrokeWidth = (nodeId, newDepth, oldDepth, allElements, newBaseWidth, newBranchScale, oldBaseWidth, oldBranchScale) => { - const node = allElements.find(el => el.id === nodeId); - if (!node) return; - - // Ensure mutable element exists - if (!ea.getElement(nodeId)) { - ea.copyViewElementsToEAforEditing([node]); - } - - const oldStandardWidth = calculateStrokeWidth(oldDepth, oldBaseWidth, oldBranchScale); - const newStandardWidth = calculateStrokeWidth(newDepth, newBaseWidth, newBranchScale); - const tolerance = 0.05; - - // 1. Update the incoming arrow (the connector) - const incomingArrow = allElements.find( - (a) => a.type === "arrow" && - a.customData?.isBranch && - a.endBinding?.elementId === nodeId - ); - - if (incomingArrow) { - if (!ea.getElement(incomingArrow.id)) ea.copyViewElementsToEAforEditing([incomingArrow]); - const eaArrow = ea.getElement(incomingArrow.id); - - // Update if it matches old standard - if (Math.abs(eaArrow.strokeWidth - oldStandardWidth) < tolerance) { - eaArrow.strokeWidth = newStandardWidth; - } - } - - // 2. Update the Node itself (e.g. if it is a box) - // Text elements don't have stroke width, but containers do. - if (node.type !== "text" && Math.abs(node.strokeWidth - oldStandardWidth) < tolerance) { - const eaNode = ea.getElement(nodeId); - eaNode.strokeWidth = newStandardWidth; - } - - // Stop recursion if this node is an additional root (submap). - if (node.customData?.isAdditionalRoot === true) { - return; - } - - // Recurse to children - const children = getChildrenNodes(nodeId, allElements); - children.forEach(child => { - updateSubtreeStrokeWidth(child.id, newDepth + 1, oldDepth + 1, allElements, newBaseWidth, newBranchScale, oldBaseWidth, oldBranchScale); - }); -}; - -/** - * Recursively updates the color of a subtree. - * Acts as a flood-fill: only updates children that matched the old parent color. - * - * @param {string} nodeId - Current node ID - * @param {string} oldColor - The color we are replacing (the color the branch used to be) - * @param {string} newColor - The color we are applying - * @param {ExcalidrawElement[]} allElements - Scene elements - */ -const updateSubtreeColor = (nodeId, oldColor, newColor, allElements) => { - const node = allElements.find(el => el.id === nodeId); - if (!node) return; - - // If the node's color doesn't match the old branch color, - // it implies a manual override or a sub-branch with a different color. Stop recursion. - if (node.strokeColor !== oldColor) return; - - if (!ea.getElement(nodeId)) ea.copyViewElementsToEAforEditing([node]); - const eaNode = ea.getElement(nodeId); - eaNode.strokeColor = newColor; - - // Update boundary color to match if the node has one - if (node.customData?.boundaryId) { - const boundaryEl = allElements.find(e => e.id === node.customData.boundaryId); - if (boundaryEl) { - if (!ea.getElement(boundaryEl.id)) ea.copyViewElementsToEAforEditing([boundaryEl]); - const eaBoundary = ea.getElement(boundaryEl.id); - eaBoundary.strokeColor = newColor; - eaBoundary.backgroundColor = newColor; - } - } - - // Update incoming arrow (Ontology/Connector) - const incomingArrow = allElements.find( - (a) => a.type === "arrow" && - a.customData?.isBranch && - a.endBinding?.elementId === nodeId - ); - - if (incomingArrow && incomingArrow.strokeColor === oldColor) { - if (!ea.getElement(incomingArrow.id)) ea.copyViewElementsToEAforEditing([incomingArrow]); - const eaArrow = ea.getElement(incomingArrow.id); - eaArrow.strokeColor = newColor; - - // Update the Ontology label (bound text element) of the arrow - const maybeTextElement = ea.getBoundTextElement(incomingArrow, true); - let eaOntologyEl = maybeTextElement.eaElement; - if (!eaOntologyEl && maybeTextElement.sceneElement) { - ea.copyViewElementsToEAforEditing([maybeTextElement.sceneElement]); - eaOntologyEl = ea.getElement(maybeTextElement.sceneElement.id); - } - if (eaOntologyEl) { - eaOntologyEl.strokeColor = newColor; - } - } - - const children = getChildrenNodes(nodeId, allElements); - children.forEach(child => { - updateSubtreeColor(child.id, oldColor, newColor, allElements); - }); -}; - -/** - * Toggles whether the selected node acts as an additional local root (submap root). - * - Master root (no incoming isBranch connector) cannot be converted. - * - Enabling submap root copies current map settings and assigns a directional growth mode - * inferred from the node position relative to its parent. - * - Disabling submap root removes local layout metadata so descendants follow parent-root logic. - */ -const toggleSubmapRoot = async () => { - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - - const allElements = ea.getViewElements(); - const parent = getParentNode(sel.id, allElements); - - // Master root is the unique no-parent root and must remain a root. - if (!parent) { - new Notice(t("NOTICE_CANNOT_CHANGE_MASTER_ROOT")); - return; - } - - const isAdditionalRoot = sel.customData?.isAdditionalRoot === true; - - ea.copyViewElementsToEAforEditing([sel]); - - if (isAdditionalRoot) { - const ok = await utils.suggester( - ["Yes", "No"], - [true, false], - t("CONFIRM_REMOVE_SUBMAP_ROOT"), - ); - if (!ok) { - return; - } - - const clearData = {}; - MAP_ROOT_CUSTOMDATA_KEYS.forEach((key) => { - clearData[key] = undefined; - }); - - clearData.presetName = undefined; - - ea.addAppendUpdateCustomData(sel.id, clearData); - } else { - const sourceRoot = getSettingsRootNode(parent, allElements) || parent; - const sourceCfg = getRootConfigForNode(sourceRoot); - const inferredMode = inferDirectionalGrowthMode(sel, parent, sourceRoot, sourceCfg.growthMode); - - ea.addAppendUpdateCustomData(sel.id, { - isAdditionalRoot: true, - presetName: sourceRoot.customData?.presetName || activePresetName, - growthMode: inferredMode, - autoLayoutDisabled: sourceCfg.autoLayoutDisabled, - arrowType: sourceCfg.arrowType, - fontsizeScale: sourceCfg.fontsizeScale, - multicolor: sourceCfg.multicolor, - boxChildren: sourceCfg.boxChildren, - roundedCorners: sourceCfg.roundedCorners, - maxWrapWidth: sourceCfg.maxWrapWidth, - isSolidArrow: sourceCfg.isSolidArrow, - centerText: sourceCfg.centerText, - fillSweep: sourceCfg.fillSweep, - branchScale: sourceCfg.branchScale, - baseStrokeWidth: sourceCfg.baseStrokeWidth, - layoutSettings: JSON.parse(JSON.stringify(sourceCfg.layoutSettings)), - }); - } - - await addElementsToView({ - captureUpdate: "EVENTUALLY" - }); - const info = getHierarchy(sel, ea.getViewElements()); - await triggerGlobalLayout(info.rootId); - - new Notice(t(isAdditionalRoot ? "NOTICE_SUBMAP_ROOT_REMOVED" : "NOTICE_SUBMAP_ROOT_ADDED")); - updateUI(); -}; - -const changeNodeOrder = async (key) => { - if (!isViewSet()) return; - const allElements = ea.getViewElements(); - const current = getMindmapNodeFromSelection(); - if (!current) return; - - const parent = getParentNode(current.id, allElements); - if (!parent) { - new Notice(t("NOTICE_CANNOT_MOVE_ROOT")); - return; - } - - const info = getHierarchy(current, allElements); - const currentSettingsRoot = getSettingsRootNode(current, allElements); - const root = (current.customData?.isAdditionalRoot === true) ? - (getSettingsRootNode(parent, allElements) || currentSettingsRoot || allElements.find((e) => e.id === info.rootId)) : - (currentSettingsRoot || allElements.find((e) => e.id === info.rootId)); - if (!root) return; - - if (current.id === root.id) { - new Notice(t("NOTICE_CANNOT_MOVE_ROOT")); - return; // cannot reorder root - } - if (root.customData?.autoLayoutDisabled) { - new Notice(t("NOTICE_CANNOT_MOVE_AUTO_LAYOUT_DISABLED")); - return; // cannot reorder in auto-layout disabled maps - } - if (current.customData?.isPinned) { - new Notice(t("NOTICE_CANNOT_MOVE_PINNED")); - return; // cannot reorder pinned nodes - } - - const rootCenter = root.x + root.width / 2; - const curCenter = current.x + current.width / 2; - const rootCenterY = root.y + root.height / 2; - const curCenterY = current.y + current.height / 2; - - const mapMode = root.customData?.growthMode || currentModalGrowthMode; - const isVerticalMode = ["Up-facing", "Down-facing", "Up-Down"].includes(mapMode); - const isRadial = (mapMode === "Radial"); - - const isInPositive = isVerticalMode ? (curCenterY > rootCenterY) : (curCenter > rootCenter); - - // --- GET OLD SETTINGS ROOT AND OLD DEPTH --- - const oldSettingsRoot = getSettingsRootNode(parent, allElements) || allElements.find(e => e.id === info.rootId); - const oldDepth = getDepthFromAncestor(current.id, oldSettingsRoot.id, allElements); - const oldRootCfg = getRootConfigForNode(oldSettingsRoot); - - // --------------------------------------------------------- - // Feature: L1 Node Side Swap - // --------------------------------------------------------- - if (parent.id === root.id && ((!isVerticalMode && mapMode === "Right-Left") || (isVerticalMode && mapMode === "Up-Down"))) { - const movePos = isVerticalMode ? (!isInPositive && key === "ArrowDown") : (!isInPositive && key === "ArrowRight"); // Negative Side -> Positive Side - const moveNeg = isVerticalMode ? (isInPositive && key === "ArrowUp") : (isInPositive && key === "ArrowLeft"); // Positive Side -> Negative Side - - if (movePos || moveNeg) { - // Calculate Delta to mirror across root center - const delta = isVerticalMode ? 2 * (rootCenterY - curCenterY) : 2 * (rootCenter - curCenter); - - // Gather all elements in branch + decorations - const branchIds = getBranchElementIds(current.id, allElements); - - // Use the specialized function to get decorations and crosslinks - // to safely ignore structural groups that might encompass the entire map - const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches(branchIds, allElements, info.rootId); - - const elementsToMove = new Set(); - - branchIds.forEach(id => { - const el = allElements.find(x => x.id === id); - if (el) elementsToMove.add(el); - }); - - decorationAndCrossLinkIds.forEach(id => { - const el = allElements.find(x => x.id === id); - if (el) elementsToMove.add(el); - }); - - const arr = Array.from(elementsToMove); - ea.copyViewElementsToEAforEditing(arr); - arr.forEach(el => { - const eaEl = ea.getElement(el.id); - if (isVerticalMode) eaEl.y += delta; - else eaEl.x += delta; - }); - - await addElementsToView({ - captureUpdate: "EVENTUALLY" - }); - - // Trigger layout. mustHonorMindmapOrder=false ensures the engine sorts based on the NEW visual position - triggerGlobalLayout(root.id, false, false); - return; - } - } - - // 1. Structural Promotion / Demotion - const isPromote = isVerticalMode ? - ((isInPositive && key === "ArrowUp") || (!isInPositive && key === "ArrowDown")) : - ((isInPositive && key === "ArrowLeft") || (!isInPositive && key === "ArrowRight")); - - const isDemote = isVerticalMode ? - ((isInPositive && key === "ArrowDown") || (!isInPositive && key === "ArrowUp")) : - ((isInPositive && key === "ArrowRight") || (!isInPositive && key === "ArrowLeft")); - - if (isPromote) { - if (parent.id === root.id && root.customData?.isAdditionalRoot !== true) return; // Cannot promote L1 nodes under master map root - - const grandParent = getParentNode(parent.id, allElements); - if (!grandParent) return; - - // Find the arrow connecting Parent -> Current - const arrow = allElements.find( - (a) => a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === parent.id && - a.endBinding?.elementId === current.id - ); - - if (arrow) { - // Find new settings root and depth relative to the target parent - const newSettingsRoot = getSettingsRootNode(grandParent, allElements) || allElements.find(e => e.id === info.rootId); - const newRootCfg = getRootConfigForNode(newSettingsRoot); - const newDepth = getDepthFromAncestor(grandParent.id, newSettingsRoot.id, allElements) + 1; - - reconnectArrow(parent, grandParent, arrow, "start"); - const parentOrder = getMindmapOrder(parent); - const promoteTargetRoot = parent.customData?.isAdditionalRoot === true ? - newSettingsRoot : - root; - - ea.copyViewElementsToEAforEditing([current]); - ea.addAppendUpdateCustomData(current.id, { - mindmapOrder: isRadial && !isInPositive ? parentOrder - 0.5 : parentOrder + 0.5 - }); - - updateSubtreeFontSize(current.id, newDepth, oldDepth, allElements, newRootCfg.fontsizeScale, oldRootCfg.fontsizeScale); - updateSubtreeStrokeWidth(current.id, newDepth, oldDepth, allElements, newRootCfg.baseStrokeWidth, newRootCfg.branchScale, oldRootCfg.baseStrokeWidth, oldRootCfg.branchScale); - - // --- Update Colors (Promotion) --- - const isTargetL1 = (grandParent.id === promoteTargetRoot.id); - let targetColor; - - if (isTargetL1) { - if (newRootCfg.multicolor) { - targetColor = current.customData?.previousL1Color; - if (!targetColor) { - const existingL1Colors = getChildrenNodes(promoteTargetRoot.id, allElements).map(n => n.strokeColor); - targetColor = getDynamicColor(existingL1Colors); - } - } else { - targetColor = promoteTargetRoot.strokeColor; - } - } else { - targetColor = grandParent.strokeColor; - } - - updateSubtreeColor(current.id, current.strokeColor, targetColor, allElements); - - await addElementsToView({ - captureUpdate: "EVENTUALLY" - }); - triggerGlobalLayout(promoteTargetRoot.id, false, true); - return; - } - } - - if (isDemote) { - // Demotion: Selected node becomes child of sibling of current parent - const siblings = getChildrenNodes(parent.id, allElements); - - // Sort siblings to ensure we pick the correct visual neighbor based on mindmapOrder - siblings.sort((a, b) => getMindmapOrder(a) - getMindmapOrder(b)); - - if (siblings.length < 2) { - new Notice(t("NOTICE_CANNOT_DEMOTE_NO_SIBLING_TO_ACCEPT")); - return; - } - - const currentIndex = siblings.findIndex(s => s.id === current.id); - const mirrorBehavior = (isRadial && !isInPositive); - - let targetIndex = mirrorBehavior ? currentIndex + 1 : currentIndex - 1; - - // Prevent out-of-bounds demotion - if (targetIndex < 0 || targetIndex >= siblings.length) { - new Notice(t("NOTICE_CANNOT_DEMOTE_NO_VALID_SIBLING")); - return; - } - - const newParent = siblings[targetIndex]; - - // Prevent cross-side demotion for L1 nodes - if (parent.id === root.id) { - const targetIsPos = isVerticalMode ? (newParent.y + newParent.height / 2 > rootCenterY) : (newParent.x + newParent.width / 2 > rootCenter); - if (targetIsPos !== isInPositive) { - new Notice(t("NOTICE_CANNOT_DEMOTE_CROSS_SIDE_NOT_ALLOWED")); - return; - } - } - - // Find the arrow to update structural binding - const arrow = allElements.find( - (a) => a.type === "arrow" && - a.customData?.isBranch && - a.startBinding?.elementId === parent.id && - a.endBinding?.elementId === current.id - ); - - if (arrow) { - // Find new settings root and calculate depth using the demoted parent context - const newSettingsRoot = getSettingsRootNode(newParent, allElements) || allElements.find(e => e.id === info.rootId); - const newRootCfg = getRootConfigForNode(newSettingsRoot); - const newDepth = getDepthFromAncestor(newParent.id, newSettingsRoot.id, allElements) + 1; - - reconnectArrow(parent, newParent, arrow, "start"); - // Determine new order: Append as last child of new parent - const newParentChildren = getChildrenNodes(newParent.id, allElements); - const nextOrder = newParentChildren.length > 0 ? Math.max(...newParentChildren.map(getMindmapOrder)) + 1 : 0; - - ea.copyViewElementsToEAforEditing([current]); - - // Store previous L1 color if we are demoting from an L1 position - if (parent.id === oldSettingsRoot.id) { - ea.addAppendUpdateCustomData(current.id, { - mindmapOrder: nextOrder, - previousL1Color: current.strokeColor - }); - } else { - ea.addAppendUpdateCustomData(current.id, { - mindmapOrder: nextOrder - }); - } - - updateSubtreeFontSize(current.id, newDepth, oldDepth, allElements, newRootCfg.fontsizeScale, oldRootCfg.fontsizeScale); - updateSubtreeStrokeWidth(current.id, newDepth, oldDepth, allElements, newRootCfg.baseStrokeWidth, newRootCfg.branchScale, oldRootCfg.baseStrokeWidth, oldRootCfg.branchScale); - - // --- Update Colors (Demotion) --- - // If the node we are attaching to IS a settings root, we are becoming an L1 of a submap. - const isTargetL1 = (newParent.id === newSettingsRoot.id); - let targetColor; - - if (isTargetL1) { - if (newRootCfg.multicolor) { - const existingL1Colors = getChildrenNodes(newSettingsRoot.id, allElements).map(n => n.strokeColor); - targetColor = getDynamicColor(existingL1Colors); - } else { - targetColor = newSettingsRoot.strokeColor; - } - } else { - targetColor = newParent.strokeColor; - } - - updateSubtreeColor(current.id, current.strokeColor, targetColor, allElements); - - await addElementsToView({ - captureUpdate: "EVENTUALLY" - }); - triggerGlobalLayout(root.id, false, true); - } - return; - } - - // 2. Sibling Reordering (Up/Down/Left/Right Arrows) - const isReorderPos = isVerticalMode ? (key === "ArrowRight") : (key === "ArrowDown"); - const isReorderNeg = isVerticalMode ? (key === "ArrowLeft") : (key === "ArrowUp"); - - if (isReorderPos || isReorderNeg) { - const siblings = getChildrenNodes(parent.id, allElements); - if (siblings.length < 2) return; - - // Ensure siblings are sorted by current order before swapping - siblings.sort((a, b) => getMindmapOrder(a) - getMindmapOrder(b)); - - const currentIndex = siblings.findIndex(s => s.id === current.id); - if (currentIndex === -1) return; - - let swapIndex = -1; - - if (isVerticalMode) { - // Up/Down facing uses Left/Right keys for siblings - if (key === "ArrowRight") swapIndex = currentIndex + 1; - if (key === "ArrowLeft") swapIndex = currentIndex - 1; - } else { - // Radial Left flips the interpretation of Up/Down since it generates from Bottom to Top - if (isRadial && !isInPositive) { - if (key === "ArrowUp") swapIndex = currentIndex + 1; - if (key === "ArrowDown") swapIndex = currentIndex - 1; - } else { - if (key === "ArrowDown") swapIndex = currentIndex + 1; - if (key === "ArrowUp") swapIndex = currentIndex - 1; - } - } - - // Apply circular wrapping for Radial mode (Level 1 nodes only) - if (isRadial && parent.id === root.id) { - swapIndex = (swapIndex + siblings.length) % siblings.length; - } - - // Boundary checks - if (swapIndex >= 0 && swapIndex < siblings.length) { - const swapNode = siblings[swapIndex]; - - // Prevent cross-side swapping for L1 nodes (Except for Radial maps, where we just wrapped) - if (parent.id === root.id && !isRadial) { - const swapIsPos = isVerticalMode ? (swapNode.y + swapNode.height / 2 > rootCenterY) : (swapNode.x + swapNode.width / 2 > rootCenter); - if (swapIsPos !== isInPositive) { - return; // Silently block cross-side reordering - } - } - - // Re-normalize all orders to clean integers to prevent drift - ea.copyViewElementsToEAforEditing(siblings); - - siblings.forEach((sib, idx) => { - let newOrder = idx; - if (idx === currentIndex) newOrder = swapIndex; - if (idx === swapIndex) newOrder = currentIndex; - - ea.addAppendUpdateCustomData(sib.id, { - mindmapOrder: newOrder - }); - }); - - await addElementsToView({ - captureUpdate: "EVENTUALLY" - }); - // Trigger layout specifically honoring the new sort order - triggerGlobalLayout(root.id, false, true); - } - } -} - -/** - * Navigates the mindmap using arrow keys. - * Handles different layout modes (Radial, Directional) and folds. - * - * @param {object} params - * @param {string} params.key - "ArrowUp" | "ArrowDown" | "ArrowLeft" | "ArrowRight" - * @param {boolean} params.zoom - whether to zoom to the new node - * @param {boolean} params.focus - whether to focus the new node - */ -const navigateMap = async ({ - key, - zoom = false, - focus = false -} = {}) => { - if (!key) return; - if (!isViewSet()) return; - let allElements = ea.getViewElements(); - const current = getMindmapNodeFromSelection(); - if (!current) return; - - const info = getHierarchy(current, allElements); - const parent = getParentNode(current.id, allElements); - const currentSettingsRoot = getSettingsRootNode(current, allElements); - const root = (current.customData?.isAdditionalRoot === true && parent) ? - (getSettingsRootNode(parent, allElements) || currentSettingsRoot || allElements.find((e) => e.id === info.rootId)) : - (currentSettingsRoot || allElements.find((e) => e.id === info.rootId)); - if (!root) return; - const rootCenter = { - x: root.x + root.width / 2, - y: root.y + root.height / 2 - }; - - const mapMode = root.customData?.growthMode || currentModalGrowthMode; - const isVerticalLayout = ["Up-facing", "Down-facing", "Up-Down"].includes(mapMode); - - if (current.id === root.id) { - if (current.customData?.isFolded) { - await toggleFold("L0"); - allElements = ea.getViewElements(); - } - - const children = getChildrenNodes(root.id, allElements); - if (children.length) { - // Sort by order/index first to establish the visual list sequence - sortChildrenStable(children); - let targetChild = null; - - if (isVerticalLayout) { - if (key === "ArrowLeft") targetChild = children[0]; - else if (key === "ArrowRight") targetChild = children[children.length - 1]; - else { - // Left/Right Logic - // Calculate relative positions - const childrenWithPos = children.map(c => ({ - node: c, - dx: Math.abs((c.x + c.width / 2) - rootCenter.x), // distance from vertical centerline - dy: (c.y + c.height / 2) - rootCenter.y - })); - - if (key === "ArrowDown") { - // Find nodes below (dy > 0) - const downNodes = childrenWithPos.filter(c => c.dy > 0).sort((a, b) => a.dx - b.dx); - targetChild = downNodes.length > 0 ? downNodes[0].node : children[0]; - } else if (key === "ArrowUp") { - // Find nodes above (dy < 0) - const upNodes = childrenWithPos.filter(c => c.dy < 0).sort((a, b) => a.dx - b.dx); - targetChild = upNodes.length > 0 ? upNodes[0].node : children[children.length - 1]; - } - } - } else { - if (key === "ArrowUp") targetChild = children[0]; - else if (key === "ArrowDown") targetChild = children[children.length - 1]; - else { - // Left/Right Logic - // Calculate relative positions - const childrenWithPos = children.map(c => ({ - node: c, - dx: (c.x + c.width / 2) - rootCenter.x, - dy: Math.abs((c.y + c.height / 2) - rootCenter.y) // distance from horizontal centerline - })); - - if (key === "ArrowRight") { - // Find nodes to the right (dx > 0) - const rightNodes = childrenWithPos.filter(c => c.dx > 0).sort((a, b) => a.dy - b.dy); - targetChild = rightNodes.length > 0 ? rightNodes[0].node : children[0]; - } else if (key === "ArrowLeft") { - // Find nodes to the left (dx < 0) - const leftNodes = childrenWithPos.filter(c => c.dx < 0).sort((a, b) => a.dy - b.dy); - targetChild = leftNodes.length > 0 ? leftNodes[0].node : children[children.length - 1]; - } - } - } - - if (targetChild) { - selectNodeInView(targetChild); - if (zoom) zoomToFit(); - if (focus) focusSelected(); - } - } - return; - } - - const isHierarchyNav = isVerticalLayout ? (key === "ArrowUp" || key === "ArrowDown") : (key === "ArrowLeft" || key === "ArrowRight"); - const isSiblingNav = isVerticalLayout ? (key === "ArrowLeft" || key === "ArrowRight") : (key === "ArrowUp" || key === "ArrowDown"); - - if (isHierarchyNav) { - const curCenter = { - x: current.x + current.width / 2, - y: current.y + current.height / 2 - }; - const isInPositive = isVerticalLayout ? (curCenter.y > rootCenter.y) : (curCenter.x > rootCenter.x); - - let goIn = false; - if (isVerticalLayout) { - goIn = (key === "ArrowUp" && isInPositive) || (key === "ArrowDown" && !isInPositive); - } else { - goIn = (key === "ArrowLeft" && isInPositive) || (key === "ArrowRight" && !isInPositive); - } - - if (goIn) { - selectNodeInView(getParentNode(current.id, allElements)); - } else { - if (current.customData?.isFolded) { - await toggleFold("L0"); - allElements = ea.getViewElements(); - } - const ch = getChildrenNodes(current.id, allElements).sort((a, b) => (a.customData?.mindmapOrder ?? 100) - (b.customData?.mindmapOrder ?? 100)); - if (ch.length) selectNodeInView(ch[0]); - } - } else if (isSiblingNav) { - const parent = getParentNode(current.id, allElements); - if (!parent) return; - - const siblings = getChildrenNodes(parent.id, allElements); - - // Calculate the immediate parent's center to sort siblings clockwise around it - const parentCenter = { - x: parent.x + parent.width / 2, - y: parent.y + parent.height / 2 - }; - - // Always sort by angle from 12 o'clock (0 degrees) to ensure clockwise navigation - // regardless of layout mode or hierarchy level. - // We project the coordinates to neutralize width/height skewing the geometric center. - siblings.sort((a, b) => { - const aCX = a.x + a.width / 2; - const aCY = a.y + a.height / 2; - const bCX = b.x + b.width / 2; - const bCY = b.y + b.height / 2; - - let aPoint = { - x: aCX, - y: aCY - }; - let bPoint = { - x: bCX, - y: bCY - }; - - if (mapMode === "Radial") { - // Use the edge closest to the parent to neutralize text width/height skew in Radial - aPoint.x = aCX >= parentCenter.x ? a.x : a.x + a.width; - aPoint.y = aCY >= parentCenter.y ? a.y : a.y + a.height; - bPoint.x = bCX >= parentCenter.x ? b.x : b.x + b.width; - bPoint.y = bCY >= parentCenter.y ? b.y : b.y + b.height; - } else if (isVerticalLayout) { - // Neutralize Y distance to sort strictly by X sequentially on each side - aPoint.y = parentCenter.y + (aCY >= parentCenter.y ? 100000 : -100000); - bPoint.y = parentCenter.y + (bCY >= parentCenter.y ? 100000 : -100000); - } else { - // Neutralize X distance to sort strictly by Y sequentially on each side - aPoint.x = parentCenter.x + (aCX >= parentCenter.x ? 100000 : -100000); - bPoint.x = parentCenter.x + (bCX >= parentCenter.x ? 100000 : -100000); - } - - return getAngleFromCenter(parentCenter, aPoint) - getAngleFromCenter(parentCenter, bPoint); - }); - - const idx = siblings.findIndex((s) => s.id === current.id); - const startIndex = (idx === -1 ? 0 : idx); // Start at 0 if current isn't found - - const currentIsNegativeBranch = isVerticalLayout ? - (current.y + current.height / 2) < (parent.y + parent.height / 2) : - (current.x + current.width / 2) < (parent.x + parent.width / 2); - - // Reverse up/down for left-facing branches in directional modes - let navigateForward; // true for next sibling (clockwise), false for previous (counter-clockwise) - if (isVerticalLayout) { - navigateForward = currentIsNegativeBranch ? (key === "ArrowRight") : (key === "ArrowLeft"); - } else { - navigateForward = currentIsNegativeBranch ? (key === "ArrowUp") : (key === "ArrowDown"); - } - - let nIdx = navigateForward ? (startIndex + 1) % siblings.length : (startIndex - 1 + siblings.length) % siblings.length; - selectNodeInView(siblings[nIdx]); - } - - if (zoom) zoomToFit(); - if (focus) focusSelected(); -}; - -/** - * Triggers a layout refresh for the tree containing the selected element. - */ -const refreshMapLayout = async (sel) => { - if (!isViewSet()) return; - if (!sel) sel = getMindmapNodeFromSelection(); - if (sel) { - const allElements = ea.getViewElements(); - const settingsRoot = getSettingsRootNode(sel, allElements); - if (!settingsRoot) return; - if (settingsRoot.customData?.autoLayoutDisabled === true) return; - await triggerGlobalLayout(settingsRoot.id); - } -}; - -/** - * Collects all node IDs and arrow IDs belonging to a branch. - * Includes "isBranch" arrows and internal non-mindmap arrows. - **/ -const getBranchElementIds = (nodeId, allElements) => { - - const childMap = new Map(); - const allArrows = []; - - for (let i = 0; i < allElements.length; i++) { - const el = allElements[i]; - if (el.type === "arrow") { - allArrows.push(el); - if (el.customData?.isBranch && el.startBinding?.elementId && el.endBinding?.elementId) { - const start = el.startBinding.elementId; - const end = el.endBinding.elementId; - - if (!childMap.has(start)) { - childMap.set(start, []); - } - childMap.get(start).push(end); - } - } - } - - const branchNodes = new Set([nodeId]); - const queue = [nodeId]; - - while (queue.length > 0) { - const currentId = queue.shift(); - - const currentNode = allElements.find(el => el.id === currentId); - if (currentNode?.customData?.boundaryId) { - branchNodes.add(currentNode.customData.boundaryId); - } - - const children = childMap.get(currentId); - - if (children) { - for (let i = 0; i < children.length; i++) { - const childId = children[i]; - if (!branchNodes.has(childId)) { - branchNodes.add(childId); - queue.push(childId); - } - } - } - } - - const branchElementIds = Array.from(branchNodes); - - // 3. Identify all arrows (structural OR annotations) where BOTH ends are within the branch - for (let i = 0; i < allArrows.length; i++) { - const el = allArrows[i]; - const startId = el.startBinding?.elementId; - const endId = el.endBinding?.elementId; - // An arrow (isBranch or internal) is part of the group only if - // BOTH ends are nodes within the branch set. - if (startId && endId && branchNodes.has(startId) && branchNodes.has(endId)) { - branchElementIds.push(el.id); - } - } - - return branchElementIds; -}; - -/** - * - * @param {*} nodeId - * @param {*} workbenchEls ExcalidrawAutomate elements on the workbench - * @returns the group ID if a structural mindmap group exists for the branch, else null - */ -const getStructuralGroupForNode = (branchIds, workbenchEls, rootId) => { - const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches(branchIds, workbenchEls, rootId); - const elements = workbenchEls.filter(el => branchIds.includes(el.id) || decorationAndCrossLinkIds.includes(el.id)); - const commonGroupId = getCommonGroupForElements(elements)[0]; - const structuralGroupId = (commonGroupId && isMindmapGroup(commonGroupId, workbenchEls)) ? commonGroupId : null; - return { - structuralGroupId, - groupedElementIds: structuralGroupId ? elements.map(e => e.id) : [] - }; -}; - -/** - * - * @param {*} nodeId - * @param {*} workbenchEls ExcalidrawAutomate elements on the workbench - * @returns the group ID if a structural mindmap group exists for the branch, else null - */ -const getStructuralGroupsForNode = (branchIds, workbenchEls, rootId) => { - const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches(branchIds, workbenchEls, rootId); - const elements = workbenchEls.filter(el => branchIds.includes(el.id) || decorationAndCrossLinkIds.includes(el.id)); - const commonGroupIds = getCommonGroupForElements(elements); - const structuralGroupIds = commonGroupIds.filter(commonGroupId => isMindmapGroup(commonGroupId, workbenchEls)); - return { - structuralGroupIds, - groupedElementIds: elements.map(e => e.id) - }; -}; - -/** - * - * @param {*} groupId - * @param {*} workbenchEls ExcalidrawAutomate elements on the workbench - */ -const removeGroupFromElements = (groupId, workbenchEls) => { - workbenchEls.forEach(el => { - if (el.groupIds) { - el.groupIds = el.groupIds.filter(g => g !== groupId); - } - }); -} - -const getDecorationAndCrossLinkIdsForBranches = (branchIds, allElements, rootId) => { - const idsInBranch = new Set(branchIds); - const decorationsAndCrossLInks = new Set(); - - // Pre-index elements by ID and GroupID to avoid O(N*M) lookups - const elementMap = new Map(); - const groupMap = new Map(); - - for (const el of allElements) { - elementMap.set(el.id, el); - if (el.groupIds && el.groupIds.length > 0) { - for (const gid of el.groupIds) { - if (!groupMap.has(gid)) { - groupMap.set(gid, []); - } - groupMap.get(gid).push(el); - } - } - } - - // Track processed groups to avoid redundant checks if multiple branch nodes share a group - const processedGroups = new Set(); - - // Logic: Include elements that are grouped with our branch nodes, - // UNLESS that group also contains structural elements outside our branch (which would mean it's a parent group). - for (const id of branchIds) { - const el = elementMap.get(id); - - if (el && el.groupIds && el.groupIds.length > 0) { - for (const gid of el.groupIds) { - if (processedGroups.has(gid)) continue; - processedGroups.add(gid); - - const groupMembers = groupMap.get(gid) || []; - - // Check if this group belongs *exclusively* to the branch (or is a local decoration group) - // We do this by checking if any 'structural' member of the group is OUTSIDE our branch. - let hasOutsider = false; - const structuralMembers = []; - - for (const member of groupMembers) { - if (idsInBranch.has(member.id) || isStructuralElement(member, allElements, rootId)) { - structuralMembers.push(member); - if (!idsInBranch.has(member.id)) { - hasOutsider = true; - break; - } - } - } - - if (!hasOutsider) { - const structuralMemberIds = new Set(structuralMembers.map(e => e.id)); - for (const member of groupMembers) { - if (!structuralMemberIds.has(member.id)) { - decorationsAndCrossLInks.add(member.id); - } - } - } - } - } - } - - // 3. Include Arrows (Structural & Crosslinks) - // Condition: Start AND End are in the set. - for (const el of allElements) { - // Skip if already in branch or already identified as decoration - if (idsInBranch.has(el.id) || decorationsAndCrossLInks.has(el.id)) continue; - - if (el.type === "arrow" && !el.customData?.isBranch) { - if (el.startBinding?.elementId && el.endBinding?.elementId) { - if (idsInBranch.has(el.startBinding.elementId) && idsInBranch.has(el.endBinding.elementId)) { - decorationsAndCrossLInks.add(el.id); - - // Optimization: Check bound elements directly via elementMap instead of ea.getBoundTextElement (which might scan scene) - if (el.boundElements && el.boundElements.length > 0) { - for (const bound of el.boundElements) { - if (bound.type === "text") decorationsAndCrossLInks.add(bound.id); - } - } - } - } - } - } - - return Array.from(decorationsAndCrossLInks); -}; - -/** - * Identifies all elements belonging to a specific mindmap tree to optimize performance on large canvases. - * This includes nodes, branch arrows, crosslinks, decorations, boundaries, and bound text. - */ -const getMindmapProjectElements = (rootId, allViewElements) => { - // 1. Get core structural IDs - const branchIds = getBranchElementIds(rootId, allViewElements); - - // 2. Get decorations and cross-links (requires scanning allViewElements for groups/arrows) - const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches(branchIds, allViewElements, rootId); - - const projectElementIds = new Set([...branchIds, ...decorationAndCrossLinkIds]); - const projectElements = []; - const addedIds = new Set(); - - const addWithDependencies = (id) => { - if (addedIds.has(id)) return; - const el = allViewElements.find(e => e.id === id); - if (!el) return; - - projectElements.push(el); - addedIds.add(id); - - // Include text inside containers or arrows - if (el.boundElements) { - el.boundElements.forEach(be => addWithDependencies(be.id)); - } - // Include container of text - if (el.containerId) { - addWithDependencies(el.containerId); - } - // Include fold indicators - if (el.customData?.foldIndicatorId) { - addWithDependencies(el.customData.foldIndicatorId); - } - // Include boundaries - if (el.customData?.boundaryId) { - addWithDependencies(el.customData.boundaryId); - } - }; - - projectElementIds.forEach(id => addWithDependencies(id)); - - return projectElements; -}; - -/** - * Toggles a single flat group for the selected branch. - **/ -const toggleBranchGroup = async () => { - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - - const info = getHierarchy(sel, ea.getViewElements()); - if (!info || !info.rootId) return; - - const allElements = ea.getViewElements(); - const branchIds = getBranchElementIds(sel.id, allElements); - const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches(branchIds, allElements, info.rootId); - - if (branchIds.length <= 1) return; - - ea.copyViewElementsToEAforEditing(allElements.filter(el => branchIds.includes(el.id) || decorationAndCrossLinkIds.includes(el.id))); - const workbenchEls = ea.getElements(); - - let newGroupId; - let { - structuralGroupIds, - groupedElementIds - } = getStructuralGroupsForNode(branchIds, workbenchEls, info.rootId); - if (structuralGroupIds.length > 0) { - //normally there should only be one structural group, however do to a bug in earlier MinMap Builder versions, - //some branches may have multiple structural groups for the exact same set of nodes. - structuralGroupIds.forEach(structuralGroupId => { - if (getViewGroupElements(structuralGroupId).length === groupedElementIds.length) { - removeGroupFromElements(structuralGroupId, workbenchEls); - } - }); - } else { - newGroupId = ea.addToGroup([...branchIds, ...decorationAndCrossLinkIds]); - } - - await addElementsToView({ - captureUpdate: "IMMEDIATELY" - }); - - if (newGroupId) { - let selectedGroupIds = {}; - selectedGroupIds[newGroupId] = true; - ea.viewUpdateScene({ - appState: { - selectedGroupIds, - selectedElementIds: {} - } - }); - } else { - ea.viewUpdateScene({ - appState: { - selectedGroupIds: {}, - selectedElementIds: { - [sel.id]: true - } - } - }); - } - - updateUI(); -}; - -/** - * Toggles the pinned state of the selected node. - * Pinned nodes are not moved by auto-layout. - */ -const togglePin = async () => { - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - if (sel) { - const boundTextElement = ea.getBoundTextElement(sel, true)?.sceneElement; - const newPinnedState = !(sel.customData?.isPinned === true); - ea.copyViewElementsToEAforEditing(boundTextElement ? [sel, boundTextElement] : [sel]); - ea.addAppendUpdateCustomData(sel.id, { - isPinned: newPinnedState - }); - if (boundTextElement && !newPinnedState && boundTextElement.customData?.hasOwnProperty("isPinned")) { - ea.addAppendUpdateCustomData(boundTextElement.id, { - isPinned: undefined - }); - } - await addElementsToView({ - captureUpdate: autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" - }); - if (!autoLayoutDisabled) await refreshMapLayout(); - selectNodeInView(sel); - updateUI(); - } -}; - -const toggleCheckboxStatus = async () => { - if (!isViewSet()) return; - - let targetText = ""; - let isInputEl = false; - let textElId = null; - let sel = null; - - if (inputEl && inputEl.value.trim() !== "") { - targetText = inputEl.value; - isInputEl = true; - } else { - sel = getMindmapNodeFromSelection(); - if (!sel) return; - const all = ea.getViewElements(); - const info = getHierarchy(sel, all); - - if (info.rootId === sel.id) return; // General rule: no effect on root node - - textElId = sel.type === "text" ? sel.id : null; - if (!textElId && sel.boundElements) { - const boundText = sel.boundElements.find(be => be.type === "text"); - if (boundText) textElId = boundText.id; - } - if (!textElId) return; - - const textEl = all.find(el => el.id === textElId); - if (!textEl) return; - targetText = textEl.rawText; - } - - const taskRegex = /^- \[([ xX])\] (.*)/s; // Regex to catch '- [ ] ' or '- [x] ' including newlines - const match = targetText.match(taskRegex); - - let newText = ""; - if (match) { - const status = match[1]; - const content = match[2]; - if (status === " ") { - newText = `- [x] ${content}`; // Complete it - } else { - newText = `${content}`; // Remove task - } - } else { - newText = `- [ ] ${targetText}`; // Not a task -> make it a task - } - - if (isInputEl) { - inputEl.value = newText; - updateUI(); - } else { - const all = ea.getViewElements(); - const textEl = all.find(el => el.id === textElId); - ea.copyViewElementsToEAforEditing([textEl]); - const eaEl = ea.getElement(textEl.id); - eaEl.rawText = newText; - eaEl.text = newText; - eaEl.originalText = newText; - ea.refreshTextElementSize(eaEl.id); - - await addElementsToView({ - captureUpdate: autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" - }); - - if (eaEl.containerId) { - const updatedContainer = ea.getViewElements().find(el => el.id === eaEl.containerId); - if (updatedContainer) api().updateContainerSize([updatedContainer]); - } - - if (!autoLayoutDisabled) { - const info = getHierarchy(sel, ea.getViewElements()); - await triggerGlobalLayout(info.rootId); - } - } -}; -/** - * Toggles the selected node between an embed (![[...]]) and a link ([[...|alias]]). - * Cleans the markdown '# ' characters when mapping the section name to the alias. - */ -const toggleEmbedStatus = async () => { - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - - const all = ea.getViewElements(); - const visualNode = sel.containerId ? all.find(el => el.id === sel.containerId) : sel; - const nodeText = getTextFromNode(all, visualNode, true, true).trim(); - - // Match: ! (optional) | [[ | NoteName#SectionName | | Alias (optional) | ]] - const linkRegex = /^(!?)\[\[([^\]]+?#([^\]|]+))(?:\|[^\]]*)?\]\]$/; - const match = nodeText.match(linkRegex); - - if (!match) return; - - const isEmbed = match[1] === "!"; - const linkCore = match[2]; - const sectionRef = match[3]; - - let newText = ""; - if (isEmbed) { - // Strip leading markdown heading characters (e.g. '### ') for the alias - const alias = sectionRef.replace(/^#+\s*/, "").trim(); - newText = `[[${linkCore}|${alias}]]`; - } else { - newText = `![[${linkCore}]]`; - } - - // Hack into the established edit flow - editingNodeId = sel.id; - inputEl.value = newText; - - // Preserve ontology - const incomingArrow = all.find(a => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === sel.id); - ontologyEl.value = incomingArrow ? (ea.getBoundTextElement(incomingArrow, true)?.sceneElement?.rawText || "") : ""; - - // Delegate the heavy lifting of completely recreating elements & mappings to commitEdit() - await commitEdit(); -}; - -const padding = layoutSettings.CONTAINER_PADDING; -/** - * Toggles a bounding box around the selected text element (node). - * Creates a container if one doesn't exist, or removes it if it does. - * @param {string} shape - "rectangle" | "ellipse" | "diamond" - */ -const toggleBox = async (shape = "rectangle") => { - if (!isViewSet()) return; - let sel = getMindmapNodeFromSelection(); - if (!sel) return; - sel = ea.getBoundTextElement(sel, true).sceneElement; - if (!sel) return; - let oldBindId, newBindId, finalElId; - - const hasContainer = !!sel.containerId; - const ids = hasContainer ? [sel.id, sel.containerId] : [sel.id]; - const allElements = ea.getViewElements(); - const arrowsToUpdate = allElements.filter( - (el) => - el.type === "arrow" && - (ids.includes(el.startBinding?.elementId) || ids.includes(el.endBinding?.elementId)), - ); - - if (hasContainer) { - const containerId = (oldBindId = sel.containerId); - finalElId = newBindId = sel.id; - const container = allElements.find((el) => el.id === containerId); - ea.copyViewElementsToEAforEditing(arrowsToUpdate.concat(sel, container)); - const textEl = ea.getElement(sel.id); - - // Transfer all custom data from the container back to the text element - const dataToCopy = { - ...(container.customData || {}) - }; - ea.addAppendUpdateCustomData(textEl.id, dataToCopy); - - textEl.containerId = null; - textEl.boundElements = []; //not null because I will add bound arrows a bit further down - ea.getElement(containerId).isDeleted = true; - } else { - ea.copyViewElementsToEAforEditing(arrowsToUpdate.concat(sel)); - const depth = getHierarchy(sel, allElements)?.depth || 0; - - oldBindId = sel.id; - - let rectId; - if (shape === "ellipse") { - rectId = ea.addEllipse(sel.x - padding, sel.y - padding, sel.width + padding * 2, sel.height + padding * 2); - } else if (shape === "diamond") { - rectId = ea.addDiamond(sel.x - padding, sel.y - padding, sel.width + padding * 2, sel.height + padding * 2); - } else { - rectId = ea.addRect(sel.x - padding, sel.y - padding, sel.width + padding * 2, sel.height + padding * 2); - } - - finalElId = newBindId = rectId; - const rect = ea.getElement(rectId); - - // Transfer all custom data from the text element to the new container - const dataToCopy = { - ...(sel.customData || {}) - }; - ea.addAppendUpdateCustomData(rectId, dataToCopy); - - rect.strokeColor = ea.getCM(sel.strokeColor).stringRGB(); - rect.strokeWidth = getStrokeWidthForDepth(depth); - rect.roughness = getAppState().currentItemRoughness; - rect.roundness = (roundedCorners) ? { - type: 3 - } : null; - rect.backgroundColor = "transparent"; - - const textEl = ea.getElement(sel.id); - textEl.containerId = rectId; - textEl.boundElements = null; - rect.boundElements = [{ - type: "text", - id: sel.id - }]; - rect.groupIds = sel.groupIds ? [...sel.groupIds] : []; - } - ea.getElements() - .filter((el) => el.type === "arrow") - .forEach((a) => { - if (a.startBinding?.elementId === oldBindId) { - a.startBinding.elementId = newBindId; - ea.getElement(newBindId).boundElements.push({ - type: "arrow", - id: a.id - }); - } - if (a.endBinding?.elementId === oldBindId) { - a.endBinding.elementId = newBindId; - ea.getElement(newBindId).boundElements.push({ - type: "arrow", - id: a.id - }); - } - }); - - ea.getElement(oldBindId).boundElements = []; - delete ea.getElement(oldBindId).customData; - - await addElementsToView({ - captureUpdate: autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" - }); - - if (!hasContainer) { - const textElement = ea.getViewElements().find((el) => el.id === sel.id); - const idx = ea.getViewElements().indexOf(textElement); - ea.moveViewElementToZIndex(textElement.containerId, idx); - } - - if (!hasContainer) { - api().updateContainerSize([ea.getViewElements().find((el) => el.id === newBindId)]); - } - selectNodeInView(finalElId); - if (!autoLayoutDisabled) await refreshMapLayout(); - updateUI(); -}; - -/** - * Toggles a visual boundary polygon around the selected node's subtree. - */ -const toggleBoundary = async () => { - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - if (sel) { - const info = getHierarchy(sel, ea.getViewElements()); - ea.copyViewElementsToEAforEditing([sel]); - const eaSel = ea.getElement(sel.id); - let newBoundaryId = null; - - if (eaSel.customData?.boundaryId) { - const b = ea.getViewElements().find(el => el.id === eaSel.customData.boundaryId); - if (b) { - ea.copyViewElementsToEAforEditing([b]); - ea.getElement(b.id).isDeleted = true; - } - ea.addAppendUpdateCustomData(sel.id, { - boundaryId: undefined - }); - } else { - const id = ea.generateElementId(); - newBoundaryId = id; - const st = getAppState(); - const boundaryEl = { - id: id, - type: "line", - x: sel.x, - y: sel.y, - width: 1, - height: 1, - angle: 0, - roughness: st.currentItemRoughness, - strokeColor: sel.strokeColor, - backgroundColor: sel.strokeColor, - fillStyle: "solid", - strokeWidth: 2, - strokeStyle: "solid", - opacity: 30, - points: [ - [0, 0], - [1, 1], - [0, 0] - ], - polygon: true, - locked: false, - groupIds: sel.groupIds || [], - customData: { - isBoundary: true - }, - roundness: arrowType === "curved" ? { - type: 2 - } : null, - }; - - if (sel.groupIds.length > 0 && isMindmapGroup(sel.groupIds[0], ea.getViewElements())) { - boundaryEl.groupIds = [sel.groupIds[0]]; - } else { - boundaryEl.groupIds = []; - } - - ea.elementsDict[id] = boundaryEl; - ea.addAppendUpdateCustomData(sel.id, { - boundaryId: id - }); - } - - await addElementsToView({ - newElementsOnTop: false, - captureUpdate: "EVENTUALLY" - }); - - if (newBoundaryId) { - const els = ea.getViewElements(); - let parentBoundaryIndex = -1; - let curr = sel; - - while (curr) { - const parent = getParentNode(curr.id, els); - if (!parent) break; - if (parent.customData?.boundaryId) { - const pIndex = els.findIndex(el => el.id === parent.customData.boundaryId); - if (pIndex !== -1) { - parentBoundaryIndex = pIndex; - break; - } - } - curr = parent; - } - const targetIndex = parentBoundaryIndex !== -1 ? parentBoundaryIndex + 1 : 0; - ea.moveViewElementToZIndex(newBoundaryId, targetIndex); - } - - await triggerGlobalLayout(info.rootId); - } - updateUI(); -}; - -// --------------------------------------------------------------------------- -// 7. UI Modal & Sidepanel Logic -// --------------------------------------------------------------------------- - -let detailsEl, inputEl, inputRow, bodyContainer, strategyDropdown; -let lastFocusedInput = null; -let isOntologyFocused = false; -let ignoreFocusChanges = false; -let autoLayoutToggle, linkSuggester, arrowTypeToggle; -let fontSizeDropdown, boxToggle, roundToggle, strokeToggle; -let branchScaleDropdown, baseWidthSlider; -let colorToggle, widthSlider, centerToggle; -let fillSweepToggleSetting, fillSweepToggle; -let pinBtn, refreshBtn, cutBtn, copyBtn, boxBtn, dockBtn, editBtn; -let toggleGroupBtn, zoomBtn, focusBtn, boundaryBtn, calendarBtn; -let submapRootBtn; -let foldBtnL0, foldBtnL1, foldBtnAll; -let floatingGroupBtn, floatingBoxBtn, floatingZoomBtn; -let panelExpandBtn, importOutlineBtn, toggleCheckboxBtn, toggleEmbedBtn; -let isFloatingPanelExpanded = false; -let toggleFloatingExtras = null; -let inputContainer; -let helpContainer; -let floatingInputModal = null; -let sidepanelWindow; -let recordingScope = null; -let disableTabEvents = false; -let presetDropdown, presetWarningEl, presetSaveBtn, presetTrashBtn, presetPlusBtn, presetApplyBtn; -// --------------------------------------------------------------------------- -// Focus Management & UI State -// --------------------------------------------------------------------------- -const registerKeydownHandler = (host, handler) => { - removeKeydownHandlers(); - if (!window.MindmapBuilder) return; //Mindmap Builder has closed - if (!window.MindmapBuilder.keydownHandlers) { - window.MindmapBuilder.keydownHandlers = []; - } - host.addEventListener("keydown", handler, true); - window.MindmapBuilder.keydownHandlers.push(() => host.removeEventListener("keydown", handler, true)) -}; - -const registerObsidianHotkeyOverrides = () => { - window.MindmapBuilder?.popObsidianHotkeyScope?.(); - const keymapScope = app.keymap.getRootScope(); - const handlers = []; - const context = getHotkeyContext(); - - if (context === SCOPE.none) return; - const reg = (mods, key) => { - const handler = keymapScope.register(mods, key, (e) => true); - handlers.push(handler); - keymapScope.keys.unshift(keymapScope.keys.pop()); - }; - - RUNTIME_HOTKEYS.forEach(h => { - if (context < h.scope) return; - if (h.key) reg(h.modifiers, h.key); - if (h.code) { - const char = h.code.replace("Key", "").replace("Digit", "").toLowerCase(); - reg(h.modifiers, char); - } - }); - - if (handlers.length === 0) return; - - window.MindmapBuilder.popObsidianHotkeyScope = () => { - handlers.forEach(h => keymapScope.unregister(h)); - delete window.MindmapBuilder.popObsidianHotkeyScope; - }; -}; - -const revealInputEl = () => { - const undockPreference = getVal(K_UNDOCKED, false); - if (undockPreference && !isUndocked) { - toggleDock({ - saveSetting: false - }); - return true; - } else if (!undockPreference && !isUndocked && ea.sidepanelTab && !ea.sidepanelTab.isVisible()) { - ea.sidepanelTab.reveal(); - } - return false; -} - -const focusInputEl = () => { - revealInputEl(); - setTimeout(() => { - if (isRecordingHotkey) return; - const target = isOntologyFocused ? - (ontologyEl.style.display === "none" ? inputEl : ontologyEl) : - inputEl; - if (!target || target.disabled) { - return; - } - target.focus(); - if (!window.MindmapBuilder?.popObsidianHotkeyScope) registerObsidianHotkeyOverrides(); - }, 200); -} - -const setButtonDisabled = (btn, disabled) => { - if (!btn) return; - btn.disabled = disabled; - const btnEl = btn.extraSettingsEl ?? btn.buttonEl ?? btn.toggleEl; - if (!btnEl) return; - btnEl.tabIndex = disabled ? -1 : 0; - btnEl.style.opacity = disabled ? "0.5" : ""; - btnEl.style.cursor = disabled ? "not-allowed" : ""; - if (disabled && btn.buttonEl) { - btn.buttonEl.style.pointerEvents = "auto"; - btn.buttonEl.style.cursor = "not-allowed"; - } -}; - -const disableUI = () => { - if (pinBtn) pinBtn.setIcon("pin-off"); - setButtonDisabled(pinBtn, true); - setButtonDisabled(refreshBtn, true); - setButtonDisabled(copyBtn, true); - setButtonDisabled(cutBtn, true); - setButtonDisabled(importOutlineBtn, true); - setButtonDisabled(boxBtn, true); - setButtonDisabled(foldBtnL0, true); - setButtonDisabled(foldBtnL1, true); - setButtonDisabled(foldBtnAll, true); - setButtonDisabled(editBtn, true); - setButtonDisabled(toggleGroupBtn, true); - setButtonDisabled(zoomBtn, true); - setButtonDisabled(focusBtn, true); - setButtonDisabled(boundaryBtn, true); - setButtonDisabled(submapRootBtn, true); - setButtonDisabled(toggleCheckboxBtn, true); - setButtonDisabled(calendarBtn, true); // Added calendarBtn to default disabled state - setButtonDisabled(toggleEmbedBtn, true); - setButtonDisabled(floatingGroupBtn, true); - setButtonDisabled(floatingBoxBtn, true); - setButtonDisabled(floatingZoomBtn, true); - setButtonDisabled(autoLayoutToggle, true); - editingNodeId = null; - if (editBtn) editBtn.extraSettingsEl.style.color = ""; -}; - -/** - * Synchronizes the sidepanel UI elements with the state of the currently selected map node, - * or the active global variables if no node is selected. - * - * Unconditionally sets the values on the Obsidian UI components to ensure that preset - * applications and external script changes are immediately and accurately reflected in the panel. - * - * @param {ExcalidrawElement} [sel] - The currently selected node element. If omitted, attempts to find the active mindmap node from the current canvas selection. - */ -const updateUI = (sel) => { - if (!isViewSet()) { - if (inputEl) { - inputEl.disabled = true; - } - if (ontologyEl) { - ontologyEl.style.display = "none"; - } - disableUI(); - return; - } - - if (inputEl) { - inputEl.disabled = false; - } - - const all = ea.getViewElements(); - sel = sel ?? getMindmapNodeFromSelection(); - - if (ontologyEl) { - ontologyEl.style.display = sel ? "" : "none"; - } - - let cd = {}; - const isMapSelected = !!sel; - - // Track structural hierarchies and map logic if a node is selected - if (isMapSelected) { - disableTabEvents = true; - - const info = getHierarchy(sel, all); - const isMasterRootSelected = info.rootId === sel.id; - const root = getSettingsRootNode(sel, all) || all.find((e) => e.id === info.rootId); - const isPinned = sel.customData?.isPinned === true; - const isAdditionalRoot = sel.customData?.isAdditionalRoot === true; - const isMasterRoot = !getParentNode(sel.id, all); - const isEditing = editingNodeId && editingNodeId === sel.id; - const branchIds = getBranchElementIds(sel.id, all); - const children = getChildrenNodes(sel.id, all); - const hasChildren = children.length > 0; - const hasGrandChildren = hasChildren && children.some(child => getChildrenNodes(child.id, all).length > 0); - const nodeText = getTextFromNode(all, sel, true, false); - const isLinkedFile = !!getNodeMarkdownFile(nodeText); - - cd = root?.customData ?? {}; - - // --- Node-Specific UI Controls --- - if (toggleCheckboxBtn) { - const isTextNode = sel.type === "text" || (sel.boundElements && sel.boundElements.some(be => be.type === "text")); - const canEditTask = (isTextNode && !isMasterRootSelected) || (inputEl && inputEl.value.trim() !== ""); - setButtonDisabled(toggleCheckboxBtn, !canEditTask); - } - - if (calendarBtn) { - const isTextNode = sel.type === "text" || (sel.boundElements && sel.boundElements.some(be => be.type === "text")); - const canEditTask = (isTextNode && !isMasterRootSelected) || (inputEl && inputEl.value.trim() !== ""); - setButtonDisabled(calendarBtn, !canEditTask); - } - - if (toggleEmbedBtn) { - const visualNode = sel.containerId ? all.find(el => el.id === sel.containerId) : sel; - const nodeTextForEmbed = getTextFromNode(all, visualNode, true, true).trim(); - // Regex matches only exact format: [[NoteName#SectionName]] or ![[NoteName#SectionName]] with optional alias - const linkRegex = /^!?\[\[([^\]]+?#[^\]|]+)(?:\|[^\]]*)?\]\]$/; - setButtonDisabled(toggleEmbedBtn, !linkRegex.test(nodeTextForEmbed)); - } - - if (pinBtn) { - pinBtn.setIcon(isPinned ? "pin" : "pin-off"); - pinBtn.setTooltip(`${isPinned ? t("PIN_TOOLTIP_PINNED") : t("PIN_TOOLTIP_UNPINNED")} ${getActionHotkeyString(ACTION_PIN)}`); - setButtonDisabled(pinBtn, false); - } - - if (submapRootBtn) { - submapRootBtn.setIcon(isAdditionalRoot ? "map-pin-minus-inside" : "map-pin-plus-inside"); - submapRootBtn.setTooltip(`${isAdditionalRoot ? t("TOOLTIP_SUBMAP_ROOT_REMOVE") : t("TOOLTIP_SUBMAP_ROOT_ADD")} ${getActionHotkeyString(ACTION_TOGGLE_SUBMAP_ROOT)}`); - setButtonDisabled(submapRootBtn, isMasterRoot); - } - - if (editBtn) { - setButtonDisabled(editBtn, false); - if (isEditing) { - editBtn.extraSettingsEl.style.color = "var(--interactive-accent)"; - } else { - editingNodeId = null; - editBtn.extraSettingsEl.style.color = ""; - } - } - - const updateGroupBtn = (btn) => { - if (!btn) { - return; - } - const isGrouped = branchIds.length > 1 && !!getCommonGroupForElements(all.filter(el => branchIds.includes(el.id)))[0]; - btn.setIcon(isGrouped ? "ungroup" : "group"); - btn.setTooltip(`${isGrouped ? t("TOGGLE_GROUP_TOOLTIP_UNGROUP") : t("TOGGLE_GROUP_TOOLTIP_GROUP")} ${getActionHotkeyString(ACTION_TOGGLE_GROUP)}`); - setButtonDisabled(btn, groupBranches || branchIds.length <= 1); - } - updateGroupBtn(toggleGroupBtn); - updateGroupBtn(floatingGroupBtn); - - setButtonDisabled(boxBtn, false); - setButtonDisabled(floatingBoxBtn, false); - setButtonDisabled(foldBtnL0, !hasChildren); - setButtonDisabled(foldBtnL1, !hasGrandChildren); - setButtonDisabled(foldBtnAll, !hasGrandChildren); - setButtonDisabled(zoomBtn, false); - setButtonDisabled(focusBtn, false); - setButtonDisabled(floatingZoomBtn, false); - - if (boundaryBtn) { - boundaryBtn.setIcon(sel.customData?.boundaryId ? "cloud-off" : "cloud"); - } - - setButtonDisabled(boundaryBtn, isMasterRootSelected); - setButtonDisabled(cutBtn, isMasterRootSelected); - setButtonDisabled(copyBtn, false); - setButtonDisabled(importOutlineBtn, !isLinkedFile); - - if (refreshBtn) { - setButtonDisabled(refreshBtn, cd.autoLayoutDisabled === true); - refreshBtn.setTooltip(`${t("TOOLTIP_REFRESH")} ${getActionHotkeyString(ACTION_REARRANGE)}`); - } - } else { - disableUI(); - if (mostRecentlySelectedNodeID) { - setButtonDisabled(zoomBtn, false); - setButtonDisabled(focusBtn, false); - setButtonDisabled(floatingZoomBtn, false); - } - if (inputEl && inputEl.value.trim() !== "") { - if (toggleCheckboxBtn) { - setButtonDisabled(toggleCheckboxBtn, false); - } - if (calendarBtn) { - setButtonDisabled(calendarBtn, false); - } - } - // AutoLayoutToggle should be allowed to be configured for the NEXT map - setButtonDisabled(autoLayoutToggle, false); - } - - // --- Preset Detection & UI Warning Logic --- - const mapPresetName = cd?.presetName; - - if (isMapSelected) { - activePresetName = mapPresetName || "Default"; - setVal(K_ACTIVE_PRESET, activePresetName); - } else { - activePresetName = getVal(K_ACTIVE_PRESET, "Default"); - } - - if (presetDropdown) { - presetDropdown.setValue(activePresetName); - } - - let showWarning = false; - if (isMapSelected) { - const presetConfig = mapPresets[activePresetName]; - const currentMapConfig = { - growthMode: cd?.growthMode ?? currentModalGrowthMode, - arrowType: cd?.arrowType ?? arrowType, - fontsizeScale: cd?.fontsizeScale ?? fontsizeScale, - multicolor: typeof cd?.multicolor === "boolean" ? cd.multicolor : multicolor, - boxChildren: typeof cd?.boxChildren === "boolean" ? cd.boxChildren : boxChildren, - roundedCorners: typeof cd?.roundedCorners === "boolean" ? cd.roundedCorners : roundedCorners, - maxWrapWidth: typeof cd?.maxWrapWidth === "number" ? cd.maxWrapWidth : maxWidth, - isSolidArrow: typeof cd?.isSolidArrow === "boolean" ? cd.isSolidArrow : isSolidArrow, - centerText: typeof cd?.centerText === "boolean" ? cd.centerText : centerText, - fillSweep: typeof cd?.fillSweep === "boolean" ? cd.fillSweep : fillSweep, - branchScale: cd?.branchScale ?? branchScale, - baseStrokeWidth: typeof cd?.baseStrokeWidth === "number" ? cd.baseStrokeWidth : baseStrokeWidth, - customPalette: cd?.customPalette ?? customPalette, - layoutSettings: cd?.layoutSettings ?? layoutSettings - }; - showWarning = diffMapConfig(presetConfig, currentMapConfig); - } - - if (presetWarningEl) { - presetWarningEl.style.display = showWarning ? "block" : "none"; - } - - if (presetApplyBtn) { - setButtonDisabled(presetApplyBtn, !isMapSelected); - } - - if (presetTrashBtn) { - setButtonDisabled(presetTrashBtn, activePresetName === "Default"); - } - - if (presetSaveBtn) { - setButtonDisabled(presetSaveBtn, false); - } - - // --- Sync Globals if Map Selected --- - // Using explicit fallback to getVal() if property is missing prevents state leakage - // from previously selected maps onto legacy maps lacking these properties. - // The variables are committed to global storage to ensure continuity if user deselects to start a new map. - if (isMapSelected) { - currentModalGrowthMode = (typeof cd.growthMode === "string" && GROWTH_TYPES.includes(cd.growthMode)) ? cd.growthMode : getVal(K_GROWTH, "Right-Left"); - setVal(K_GROWTH, currentModalGrowthMode); - - autoLayoutDisabled = cd.autoLayoutDisabled === true; - - arrowType = (typeof cd.arrowType === "string" && ARROW_TYPES.includes(cd.arrowType)) ? cd.arrowType : getVal(K_ARROW_TYPE, "curved"); - setVal(K_ARROW_TYPE, arrowType); - - fontsizeScale = cd.fontsizeScale ?? getVal(K_FONTSIZE, "Normal Scale"); - setVal(K_FONTSIZE, fontsizeScale); - - multicolor = typeof cd.multicolor === "boolean" ? cd.multicolor : getVal(K_MULTICOLOR, true); - setVal(K_MULTICOLOR, multicolor); - - boxChildren = typeof cd.boxChildren === "boolean" ? cd.boxChildren : getVal(K_BOX, false); - setVal(K_BOX, boxChildren); - - roundedCorners = typeof cd.roundedCorners === "boolean" ? cd.roundedCorners : getVal(K_ROUND, false); - setVal(K_ROUND, roundedCorners); - - maxWidth = typeof cd.maxWrapWidth === "number" ? cd.maxWrapWidth : parseInt(getVal(K_WIDTH, 450)) || 450; - setVal(K_WIDTH, maxWidth); - - isSolidArrow = typeof cd.isSolidArrow === "boolean" ? cd.isSolidArrow : getVal(K_ARROWSTROKE, true); - setVal(K_ARROWSTROKE, isSolidArrow); - - centerText = typeof cd.centerText === "boolean" ? cd.centerText : getVal(K_CENTERTEXT, true); - setVal(K_CENTERTEXT, centerText); - - fillSweep = typeof cd.fillSweep === "boolean" ? cd.fillSweep : getVal(K_FILL_SWEEP, false); - setVal(K_FILL_SWEEP, fillSweep); - - branchScale = (cd.branchScale && BRANCH_SCALE_TYPES.includes(cd.branchScale)) ? cd.branchScale : getVal(K_BRANCH_SCALE, "Hierarchical"); - setVal(K_BRANCH_SCALE, branchScale); - - baseStrokeWidth = typeof cd.baseStrokeWidth === "number" ? cd.baseStrokeWidth : parseFloat(getVal(K_BASE_WIDTH, 6)) || 6; - setVal(K_BASE_WIDTH, baseStrokeWidth); - - if (cd.customPalette) { - customPalette = JSON.parse(JSON.stringify(cd.customPalette)); - } else { - customPalette = getVal(K_PALETTE, { enabled: false, random: false, colors: [] }) || { enabled: false, random: false, colors: [] }; - } - setVal(K_PALETTE, customPalette, true); - - if (cd.layoutSettings && typeof cd.layoutSettings === "object") { - layoutSettings = { ...layoutSettings, ...cd.layoutSettings }; - } else { - const globalDefaults = getVal(K_LAYOUT, {}); - Object.keys(LAYOUT_METADATA).forEach(k => { - layoutSettings[k] = globalDefaults[k] !== undefined ? globalDefaults[k] : LAYOUT_METADATA[k].def; - }); - } - setVal(K_LAYOUT, layoutSettings, true); - } - - // --- Unconditionally Sync Visual UI Components to Current Globals --- - if (strategyDropdown) { - strategyDropdown.setValue(currentModalGrowthMode); - } - if (autoLayoutToggle) { - autoLayoutToggle.setValue(!autoLayoutDisabled); - } - if (arrowTypeToggle) { - arrowTypeToggle.setValue(arrowType === "curved"); - } - if (fontSizeDropdown) { - fontSizeDropdown.setValue(fontsizeScale); - } - if (colorToggle) { - colorToggle.setValue(multicolor); - } - if (boxToggle) { - boxToggle.setValue(boxChildren); - } - if (roundToggle) { - roundToggle.setValue(roundedCorners); - } - if (widthSlider) { - widthSlider.setValue(maxWidth); - if (widthSlider.valLabelEl) { - widthSlider.valLabelEl.setText(`${maxWidth}px`); - } - } - if (strokeToggle) { - strokeToggle.setValue(!isSolidArrow); - } - if (centerToggle) { - centerToggle.setValue(centerText); - } - if (fillSweepToggle) { - fillSweepToggle.setValue(fillSweep); - } - if (branchScaleDropdown) { - branchScaleDropdown.setValue(branchScale); - } - if (baseWidthSlider) { - baseWidthSlider.setValue(baseStrokeWidth); - if (baseWidthSlider.valLabelEl) { - baseWidthSlider.valLabelEl.setText(`${baseStrokeWidth}`); - } - } - if (fillSweepToggleSetting && fillSweepToggleSetting.settingEl) { - fillSweepToggleSetting.settingEl.style.display = currentModalGrowthMode === "Radial" ? "" : "none"; - } - - disableTabEvents = false; -}; - -const startEditing = () => { - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - const all = ea.getViewElements(); - const text = getTextFromNode(all, sel, true, true); - if (text.match(/\n/)) { - new Notice(`${t("NOTICE_CANNOT_EDIT_MULTILINE")} ${getActionHotkeyString(ACTION_REARRANGE)}`, 7000); - return; - } - const didToggle = revealInputEl(); - - setTimeout(() => { - inputEl.value = text; - - // Populate Ontology (Arrow Label) - // Find incoming arrow - const incomingArrow = all.find( - (a) => a.type === "arrow" && - a.customData?.isBranch && - a.endBinding?.elementId === sel.id - ); - - ontologyEl.value = ea.getBoundTextElement(incomingArrow, true)?.sceneElement?.rawText || ""; - - editingNodeId = sel.id; - updateUI(); - inputEl.focus(); - }, didToggle ? 200 : 0); -}; - -const commitEdit = async () => { - if (!editingNodeId) return; - const all = ea.getViewElements(); - - let targetNode = all.find(el => el.id === editingNodeId); - if (!targetNode) return; - - // Identify visual node (container or element) for positioning - const visualNode = targetNode.containerId ? - all.find(el => el.id === targetNode.containerId) : - targetNode; - - // Identify text element within container - let textElId = targetNode.id; - if (targetNode.boundElements) { - const boundText = targetNode.boundElements.find(be => be.type === "text"); - if (boundText) textElId = boundText.id; - } - const textEl = all.find(el => el.id === textElId && el.type === "text"); - - // Get values from BOTH inputs - const textInput = inputEl.value; - const ontologyInput = ontologyEl.value; - - // Retrieve current text representation (raw, short path for images) to compare against input - const currentText = getTextFromNode(all, visualNode, true, true); - - // Find arrow pointing TO this node to check current ontology - // We need this for diffing, and potentially for updating later - const incomingArrow = all.find( - (a) => a.type === "arrow" && - a.customData?.isBranch && - a.endBinding?.elementId === targetNode.id // Target node might be container - ); - - const currentOntology = incomingArrow ? - (ea.getBoundTextElement(incomingArrow, true)?.sceneElement?.rawText || "") : - ""; - - const textChanged = textInput !== currentText; - const ontologyChanged = ontologyInput !== currentOntology; - - // If nothing changed, exit early without modifying scene - if (!textChanged && !ontologyChanged) { - editingNodeId = null; - inputEl.value = ""; - ontologyEl.value = ""; - updateUI(); - return; - } - - const imageInfo = parseImageInput(textInput); - const embeddableUrl = parseEmbeddableInput(textInput, imageInfo); - - let newType = "text"; - if (imageInfo?.isImagePath || imageInfo?.imageFile) newType = "image"; - else if (embeddableUrl) newType = "embeddable"; - - // Check for type conversion (e.g. Text -> Image) or non-text update - const isTypeChange = (textEl && newType !== "text") || (!textEl && newType !== targetNode.type); - - // Only consider it a non-text update (which requires recreation) if the text/path actually changed. - // If only ontology changed on an image node, we treat it as a standard update (else block). - const isNonTextUpdate = !textEl && newType === targetNode.type && textChanged; - let containerToUpdate = null; - if (isTypeChange || isNonTextUpdate) { - // --------------------------------------------------------- - // Path A: Recreate Element (Type change or Image path change) - // --------------------------------------------------------- - - // 1. Calculate center position - const cx = visualNode.x + visualNode.width / 2; - const cy = visualNode.y + visualNode.height / 2; - - const info = getHierarchy(visualNode, all); - const depth = info.depth; - - let newNodeId; - - // 2. Create new element based on type - // store/restore strokeColor (even if element type doesn't normally have a stroke color) - const st = getAppState(); - ea.style.strokeColor = targetNode.strokeColor ?? st.currentItemStrokeColor; - if (newType === "image") { - if (imageInfo?.isImagePath) { - newNodeId = await addImage({ - pathOrFile: imageInfo.path, - width: imageInfo.width, - depth, - }); - // Check for external image flag and append to link to preserve routing - if (imageInfo.isExternalImage && newNodeId) { - const el = ea.getElement(newNodeId); - if (el && !el.link) el.link = imageInfo.path; - } - } else { - newNodeId = await addImage({ - pathOrFile: imageInfo.imageFile, - width: imageInfo.width, - depth, - }); - } - const el = ea.getElement(newNodeId); - el.x = cx - el.width / 2; - el.y = cy - el.height / 2; - } else if (newType === "embeddable") { - newNodeId = addEmbeddableNode({ - url: embeddableUrl, - depth - }); - const el = ea.getElement(newNodeId); - el.x = cx - el.width / 2; - el.y = cy - el.height / 2; - } else { - // Back to Text - if (ea.style.strokeColor === "transparent") ea.style.strokeColor = "black"; - ea.style.fontFamily = st.currentItemFontFamily; - const fontScale = getFontScale(fontsizeScale); - ea.style.fontSize = fontScale[Math.min(depth, fontScale.length - 1)]; - ea.style.backgroundColor = "transparent"; - ea.style.strokeWidth = getStrokeWidthForDepth(depth); - if (incomingArrow) { - ea.style.strokeColor = incomingArrow.strokeColor; - } - ea.style.roughness = getAppState().currentItemRoughness; - - const renderedText = await parseText(textInput); - const metrics = ea.measureText(renderedText); - const shouldWrap = metrics.width > maxWidth; - - let finalWidth = Math.ceil(metrics.width); - let finalHeight = metrics.height; - let finalWrappedText = renderedText; - - if (shouldWrap) { - const res = await getAdjustedMaxWidth(textInput, maxWidth); - finalWidth = res.width; - finalHeight = res.height; - finalWrappedText = res.wrappedText; - } - - newNodeId = ea.addText(cx, cy, renderedText, { - textAlign: "center", - textVerticalAlign: "middle", - box: boxChildren ? "rectangle" : false, - width: shouldWrap ? finalWidth : undefined, - height: shouldWrap ? finalHeight : undefined, - autoResize: boxChildren ? false : !shouldWrap - }); - - const newElement = ea.getElement(newNodeId); - containerToUpdate = boxChildren ? newElement : null; - - // Explicitly overwrite raw, original and text properties to handle links correctly - newTextElement = boxChildren ? ea.getElement(containerToUpdate.boundElements[0].id) : newElement; - newTextElement.rawText = textInput; - newTextElement.originalText = renderedText; - newTextElement.text = finalWrappedText; - if (!shouldWrap) { - newTextElement.width = finalWidth; - newTextElement.height = finalHeight; - } - } - - const newNode = ea.getElement(newNodeId); - - // Scale decorations before deleting the old visual node - scaleDecorations(visualNode, newNode, all, info.rootId); - - // 3. Migrate custom data fields - const keysToCopy = [ - "mindmapOrder", "isPinned", "growthMode", "autoLayoutDisabled", - "isFolded", "foldIndicatorId", "foldState", "boundaryId", - "fontsizeScale", "multicolor", "boxChildren", "roundedCorners", - "maxWrapWidth", "isSolidArrow", "centerText", "arrowType", - "fillSweep", "branchScale", "baseStrokeWidth", "layoutSettings" - ]; - const dataToCopy = {}; - keysToCopy.forEach(k => { - if (visualNode.customData && visualNode.customData.hasOwnProperty(k)) { - dataToCopy[k] = visualNode.customData[k]; - } - }); - ea.addAppendUpdateCustomData(newNodeId, dataToCopy); - - // 4. Migrate Decorations - if (visualNode.groupIds && visualNode.groupIds.length > 0) { - newNode.groupIds = [...visualNode.groupIds]; - } - - // 5. Rewire arrows and adjust cross-links - const idsToReplace = [visualNode.id]; - if (textEl) idsToReplace.push(textEl.id); - - const connectedArrows = all.filter(el => - el.type === "arrow" && - (idsToReplace.includes(el.startBinding?.elementId) || idsToReplace.includes(el.endBinding?.elementId)) - ); - - if (connectedArrows.length > 0) { - ea.copyViewElementsToEAforEditing(connectedArrows); - const newBoundElements = []; - - connectedArrows.forEach(arrow => { - const eaArrow = ea.getElement(arrow.id); - let isConnected = false; - - // Calculate scale ratios for updating manual arrow points - const ratioX = visualNode.width > 1 ? newNode.width / visualNode.width : 1; - const ratioY = visualNode.height > 1 ? newNode.height / visualNode.height : 1; - - if (idsToReplace.includes(eaArrow.startBinding?.elementId)) { - eaArrow.startBinding = { - ...eaArrow.startBinding, - elementId: newNodeId - }; - isConnected = true; - // Scale start point relative to center - if (eaArrow.points.length > 0) { - const absX = arrow.x + arrow.points[0][0]; - const absY = arrow.y + arrow.points[0][1]; - const dx = absX - cx; - const dy = absY - cy; - const newAbsX = cx + dx * ratioX; - const newAbsY = cy + dy * ratioY; - eaArrow.points[0] = [eaArrow.points[0][0] + (newAbsX - absX), eaArrow.points[0][1] + (newAbsY - absY)]; - } - } - - if (idsToReplace.includes(eaArrow.endBinding?.elementId)) { - eaArrow.endBinding = { - ...eaArrow.endBinding, - elementId: newNodeId - }; - isConnected = true; - - // --- Update Ontology for incoming arrow --- - // Since we are rewiring, this is the arrow pointing TO the new node - addUpdateArrowLabel(eaArrow, ontologyInput); - - // Scale end point relative to center - if (eaArrow.points.length > 0) { - const lastIdx = eaArrow.points.length - 1; - const absX = arrow.x + arrow.points[lastIdx][0]; - const absY = arrow.y + arrow.points[lastIdx][1]; - const dx = absX - cx; - const dy = absY - cy; - const newAbsX = cx + dx * ratioX; - const newAbsY = cy + dy * ratioY; - eaArrow.points[lastIdx] = [eaArrow.points[lastIdx][0] + (newAbsX - absX), eaArrow.points[lastIdx][1] + (newAbsY - absY)]; - } - } - - if (isConnected) { - newBoundElements.push({ - type: "arrow", - id: arrow.id - }); - } - }); - - if (newBoundElements.length > 0) { - newNode.boundElements = [...(newNode.boundElements || []), ...newBoundElements]; - } - } - - // 6. Remove old elements - ea.copyViewElementsToEAforEditing([visualNode]); - ea.getElement(visualNode.id).isDeleted = true; - if (textEl && textEl.id !== visualNode.id) { - ea.copyViewElementsToEAforEditing([textEl]); - ea.getElement(textEl.id).isDeleted = true; - } - - await addElementsToView({ - captureUpdate: autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" - }); - - // Trigger global layout if enabled - if (!autoLayoutDisabled) { - const newViewElements = ea.getViewElements(); - const newViewNode = newViewElements.find(el => el.id === newNodeId); - if (newViewNode) { - selectNodeInView(newViewNode); - const newInfo = getHierarchy(newViewNode, newViewElements); - await triggerGlobalLayout(newInfo.rootId, false, true); - } - } - - } else { - // --------------------------------------------------------- - // Path B: Modify Existing Element - // --------------------------------------------------------- - - // 1. Update Ontology (Incoming Arrow) - // Only perform if ontology has changed and arrow exists - if (ontologyChanged && incomingArrow) { - ea.copyViewElementsToEAforEditing([incomingArrow]); - addUpdateArrowLabel(ea.getElement(incomingArrow.id), ontologyInput); - } - - // 2. Update Text Element Properties - // Only perform if text has changed and it is a Text element (images/embeddables handled in Path A if content changes) - if (textChanged && textEl) { - ea.copyViewElementsToEAforEditing([textEl]); - const eaEl = ea.getElement(textEl.id); - - const renderedText = await parseText(textInput); - - eaEl.rawText = textInput; - eaEl.originalText = renderedText; - - // Refresh family/size in case global settings changed, though this is optional - ea.style.fontFamily = eaEl.fontFamily; - ea.style.fontSize = eaEl.fontSize; - - const metrics = ea.measureText(renderedText); - const shouldWrap = metrics.width > maxWidth; - - if (!shouldWrap) { - eaEl.autoResize = true; - eaEl.width = Math.ceil(metrics.width); - eaEl.height = metrics.height; - eaEl.text = renderedText; - } else { - eaEl.autoResize = false; - const res = await getAdjustedMaxWidth(textInput, maxWidth); - eaEl.width = res.width; - eaEl.height = res.height; - eaEl.text = res.wrappedText; - } - - ea.refreshTextElementSize(eaEl.id); - } - - // 3. Save Changes - const hierarchyNode = targetNode.containerId ? all.find(el => el.id === targetNode.containerId) : textEl; - - await addElementsToView({ - captureUpdate: !hierarchyNode || autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" - }); //in case text was changed to image - - // 4. Update Container Size (if text changed and container exists) - if (textChanged && textEl && textEl.containerId) { - const container = ea.getViewElements().find(el => el.id === textEl.containerId); - if (container) { - api().updateContainerSize([container]); - } - } - - if (containerToUpdate) { - api().updateContainerSize([containerToUpdate]); - } - - // 5. Trigger Layout (only if text changed, as that affects dimensions) - if (textChanged && hierarchyNode && !autoLayoutDisabled) { - const info = getHierarchy(hierarchyNode, ea.getViewElements()); - await triggerGlobalLayout(info.rootId); - } - } - - editingNodeId = null; - inputEl.value = ""; - ontologyEl.value = ""; -}; - -const renderHelp = (container) => { - helpContainer = container.createDiv(); - detailsEl = helpContainer.createEl("details"); - const summary = detailsEl.createEl("summary", { - attr: { - style: "cursor: pointer;" - } - }); - - // Title - summary.createSpan({ - text: t("HELP_SUMMARY"), - attr: { - style: "font-weight: bold;" - } - }); - - // Version Number - summary.createSpan({ - text: VERSION, - attr: { - style: "float: right; color: var(--text-muted); font-size: 0.8em;" - } - }); - - ea.obsidian.MarkdownRenderer.render(app, getInstructions(), detailsEl.createDiv(), "", ea.plugin); -}; - -// --------------------------------------------------------------------------- -// 8. Custom Colors: Palette Manager Modal -// --------------------------------------------------------------------------- -class PaletteManagerModal extends ea.FloatingModal { - constructor(app, settings, onUpdate) { - super(app); - this.settings = JSON.parse(JSON.stringify(settings)); - this.onUpdate = onUpdate; - this.editIndex = -1; // -1 means adding new, >=0 means editing existing - this.tempColor = "#000000"; - } - - onOpen() { - this.display(); - } - - display() { - const { - contentEl - } = this; - contentEl.empty(); - contentEl.createEl("h2", { - text: t("MODAL_PALETTE_TITLE") - }); - - /* --- Global Toggles --- */ - new ea.obsidian.Setting(contentEl) - .setName(t("LABEL_ENABLE_CUSTOM_PALETTE")) - .setDesc(t("DESC_ENABLE_CUSTOM_PALETTE")) - .addToggle(t => t - .setValue(this.settings.enabled) - .onChange(v => { - this.settings.enabled = v; - this.save(); - this.display(); - })); - - if (this.settings.enabled) { - new ea.obsidian.Setting(contentEl) - .setName(t("LABEL_RANDOMIZE_ORDER")) - .setDesc(t("DESC_RANDOMIZE_ORDER")) - .addToggle(t => t - .setValue(this.settings.random) - .onChange(v => { - this.settings.random = v; - this.save(); - })); - - contentEl.createEl("hr"); - - /* --- Color List --- */ - const listContainer = contentEl.createDiv(); - this.settings.colors.forEach((color, index) => { - const row = new ea.obsidian.Setting(listContainer); - - // Color Preview & Name - const nameEl = row.nameEl; - nameEl.style.display = "flex"; - nameEl.style.alignItems = "center"; - nameEl.style.gap = "10px"; - - const preview = nameEl.createDiv(); - preview.style.width = "20px"; - preview.style.height = "20px"; - preview.style.backgroundColor = color; - preview.style.border = "1px solid var(--background-modifier-border)"; - preview.style.borderRadius = "4px"; - - nameEl.createSpan({ - text: color - }); - - // Actions - row - .addExtraButton(btn => btn - .setIcon("arrow-big-up") - .setTooltip(t("TOOLTIP_MOVE_UP")) - .setDisabled(index === 0) - .onClick(() => { - if (index === 0) return; - [this.settings.colors[index - 1], this.settings.colors[index]] = [this.settings.colors[index], this.settings.colors[index - 1]]; - this.save(); - this.display(); - })) - .addExtraButton(btn => btn - .setIcon("arrow-big-down") - .setTooltip(t("TOOLTIP_MOVE_DOWN")) - .setDisabled(index === this.settings.colors.length - 1) - .onClick(() => { - if (index === this.settings.colors.length - 1) return; - [this.settings.colors[index + 1], this.settings.colors[index]] = [this.settings.colors[index], this.settings.colors[index + 1]]; - this.save(); - this.display(); - })) - .addExtraButton(btn => btn - .setIcon("pencil") - .setTooltip(t("TOOLTIP_EDIT_COLOR")) - .onClick(() => { - this.editIndex = index; - this.tempColor = color; - this.display(); - })) - .addExtraButton(btn => btn - .setIcon("trash-2") - .setTooltip(t("TOOLTIP_DELETE_COLOR")) - .onClick(() => { - this.settings.colors.splice(index, 1); - if (this.editIndex === index) this.editIndex = -1; - this.save(); - this.display(); - })); - }); - - contentEl.createEl("hr"); - - // --- Add/Edit Area --- - contentEl.createEl("h4", { - text: this.editIndex === -1 ? t("HEADING_ADD_NEW_COLOR") : t("HEADING_EDIT_COLOR") - }); - - const getHex = (val) => { - const cm = ea.getCM(val); - return cm ? cm.stringHEX({ - alpha: false - }) : "#000000"; - }; - - const updateEditorState = (val, textComp, pickerComp) => { - this.tempColor = val; - if (textComp) textComp.inputEl.value = val; - if (pickerComp) pickerComp.setValue(getHex(val)); - }; - - let textComponent, pickerComponent; - - new ea.obsidian.Setting(contentEl) - .setName(t("LABEL_SELECT_COLOR")) - .addText(text => { - textComponent = text; - text - .setValue(this.tempColor) - .onChange(value => { - this.tempColor = value; - pickerComponent.setValue(getHex(value)); - }); - }) - .addColorPicker(picker => { - pickerComponent = picker; - picker - .setValue(getHex(this.tempColor)) - .onChange(value => { - this.tempColor = value; - textComponent.setValue(value); - }); - }) - .addButton(btn => btn - .setIcon("swatch-book") - .setTooltip(t("TOOLTIP_OPEN_PALETTE_PICKER")) - .onClick(async () => { - const selected = await ea.showColorPicker(btn.buttonEl, "elementStroke"); - if (selected) { - updateEditorState(selected, textComponent, pickerComponent); - } - })); - - const actionContainer = contentEl.createDiv(); - actionContainer.style.display = "flex"; - actionContainer.style.justifyContent = "flex-end"; - actionContainer.style.gap = "10px"; - actionContainer.style.marginTop = "10px"; - - if (this.editIndex !== -1) { - const cancelBtn = actionContainer.createEl("button", { - text: t("BUTTON_CANCEL_EDIT") - }); - cancelBtn.onclick = () => { - this.editIndex = -1; - this.tempColor = "#000000"; - this.display(); - }; - } - - const saveBtn = actionContainer.createEl("button", { - text: this.editIndex === -1 ? t("BUTTON_ADD_COLOR") : t("BUTTON_UPDATE_COLOR"), - cls: "mod-cta" - }); - saveBtn.onclick = () => { - if (this.editIndex === -1) { - this.settings.colors.push(this.tempColor); - } else { - this.settings.colors[this.editIndex] = this.tempColor; - this.editIndex = -1; - } - this.save(); - this.display(); - }; - } - } - - save() { - this.onUpdate(this.settings); - } -} - -// --------------------------------------------------------------------------- -// 9. Layout Configuration Manager -// --------------------------------------------------------------------------- -class LayoutConfigModal extends ea.FloatingModal { - constructor(app, currentSettings, onUpdate) { - super(app); - this.settings = this.normalizeSettings(currentSettings); - this.onUpdate = onUpdate; - this.updateTimer = null; - this.focusRefreshHandler = (evt) => this.handleFocusRefresh(evt); - this.focusDoc = null; - } - - normalizeSettings(settingsLike) { - const normalized = {}; - Object.keys(LAYOUT_METADATA).forEach((key) => { - const meta = LAYOUT_METADATA[key]; - const candidate = settingsLike?.[key]; - normalized[key] = typeof candidate === "number" && Number.isFinite(candidate) ? candidate : meta.def; - }); - return normalized; - } - - onOpen() { - this.display({ - preserveSectionState: false - }); - this.focusDoc = this.contentEl?.ownerDocument ?? document; - this.focusDoc.addEventListener("focusin", this.focusRefreshHandler, true); - } - - onClose() { - if (this.focusDoc) { - this.focusDoc.removeEventListener("focusin", this.focusRefreshHandler, true); - this.focusDoc = null; - } - if (this.updateTimer) clearTimeout(this.updateTimer); - this.settings = this.normalizeSettings(this.settings); - this.onUpdate(this.settings); - } - - handleFocusRefresh(evt) { - if (!isViewSet()) { - this.close(); - return; - } - if (!this.contentEl || !(this.contentEl.contains(evt.target) || this.modalEl.contains(evt.target))) return; - - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - - const allElements = ea.getViewElements(); - const settingsRoot = getSettingsRootNode(sel, allElements) ?? sel; - const rootCfg = getRootConfigForNode(settingsRoot); - const nextSettings = this.normalizeSettings(rootCfg?.layoutSettings); - if (!nextSettings) return; - - const currentSig = JSON.stringify(this.settings); - const nextSig = JSON.stringify(nextSettings); - if (currentSig === nextSig) return; - - this.settings = nextSettings; - this.display({ - preserveSectionState: true - }); - } - - triggerUpdate() { - if (this.updateTimer) clearTimeout(this.updateTimer); - this.updateTimer = setTimeout(() => { - this.settings = this.normalizeSettings(this.settings); - this.onUpdate(this.settings); - this.updateTimer = null; - }, 500); - } - - display({ - preserveSectionState = true - } = {}) { - const { - contentEl - } = this; - - let lastScrollPosition = 0; - const previousSectionState = {}; - const existingContainer = contentEl.querySelector(".layout-settings-container"); - if (existingContainer) { - lastScrollPosition = existingContainer.scrollTop; - if (preserveSectionState) { - existingContainer.querySelectorAll("details[data-layout-section]").forEach((detailsEl) => { - const sectionKey = detailsEl.getAttribute("data-layout-section"); - if (sectionKey) previousSectionState[sectionKey] = detailsEl.open; - }); - } - } - - contentEl.empty(); - contentEl.createEl("h2", { - text: t("MODAL_LAYOUT_TITLE") - }); - - const container = contentEl.createDiv(); - container.addClass("layout-settings-container"); - container.style.maxHeight = "70vh"; - container.style.overflowY = "auto"; - container.style.paddingRight = "10px"; - - const groupedKeys = {}; - Object.keys(LAYOUT_METADATA).forEach(key => { - const section = LAYOUT_METADATA[key].section; - if (!groupedKeys[section]) groupedKeys[section] = []; - groupedKeys[section].push(key); - }); - - const renderSection = (sectionKey, title) => { - if (!groupedKeys[sectionKey]) return; - - const details = container.createEl("details", { - attr: { - "data-layout-section": sectionKey - } - }); - details.open = preserveSectionState ? (previousSectionState[sectionKey] ?? false) : false; - details.style.marginBottom = "10px"; - details.style.border = "1px solid var(--background-modifier-border)"; - details.style.borderRadius = "5px"; - - const summary = details.createEl("summary"); - summary.style.padding = "10px"; - summary.style.fontWeight = "bold"; - summary.style.cursor = "pointer"; - summary.style.backgroundColor = "var(--background-secondary)"; - summary.innerText = title; - - const content = details.createDiv(); - content.style.padding = "10px"; - - groupedKeys[sectionKey].forEach(key => { - const meta = LAYOUT_METADATA[key]; - const setting = new ea.obsidian.Setting(content) - .setName(meta.name) - .setDesc(meta.desc); - - let valLabel; - let resetButtonComp; - - const updateResetButton = (val) => { - if (!resetButtonComp) return; - const isModified = Math.abs(val - meta.def) > 0.0001; - const el = resetButtonComp.extraSettingsEl; - - el.style.opacity = isModified ? "1" : "0"; - el.style.pointerEvents = isModified ? "auto" : "none"; - el.style.cursor = isModified ? "pointer" : "default"; - if (isModified) el.setAttribute("tabindex", "0"); - else el.setAttribute("tabindex", "-1"); - }; - - setting.addSlider(slider => slider - .setLimits(meta.min, meta.max, meta.step) - .setValue(this.settings[key] ?? meta.def) - .onChange(value => { - this.settings[key] = value; - valLabel.setText(String(value.toFixed(meta.step < 1 ? 1 : 0))); - updateResetButton(value); - this.triggerUpdate(); - }) - ); - - setting.settingEl.createDiv("", el => { - valLabel = el; - el.style.minWidth = "3em"; - el.style.textAlign = "right"; - el.innerText = String(this.settings[key].toFixed(meta.step < 1 ? 1 : 0)); - }); - - setting.addExtraButton(btn => { - resetButtonComp = btn; - btn - .setIcon("rotate-ccw") - .setTooltip(t("TOOLTIP_RESET_TO_DEFAULT")) - .onClick(() => { - this.settings[key] = meta.def; - this.triggerUpdate(); - this.display(); - }); - updateResetButton(this.settings[key]); - }); - }); - }; - - // Render Sections in Order - renderSection("SECTION_GENERAL", t("SECTION_GENERAL")); - renderSection("SECTION_RADIAL", t("SECTION_RADIAL")); - renderSection("SECTION_DIRECTIONAL", t("SECTION_DIRECTIONAL")); - renderSection("SECTION_VERTICAL", t("SECTION_VERTICAL")); - renderSection("SECTION_VISUALS", t("SECTION_VISUALS")); - renderSection("SECTION_MANUAL", t("SECTION_MANUAL")); - - const footer = contentEl.createDiv(); - footer.style.marginTop = "20px"; - footer.style.display = "flex"; - footer.style.justifyContent = "space-between"; - - new ea.obsidian.Setting(footer) - .addButton(btn => btn - .setButtonText(t("LAYOUT_RESET")) - .setWarning() - .onClick(() => { - Object.keys(LAYOUT_METADATA).forEach(k => { - this.settings[k] = LAYOUT_METADATA[k].def; - }); - this.triggerUpdate(); - this.display(); - }) - ) - .addButton(btn => btn - .setButtonText(t("LAYOUT_SAVE")) - .setCta() - .onClick(() => { - if (this.updateTimer) clearTimeout(this.updateTimer); - this.onUpdate(this.settings); - this.close(); - }) - ); - container.scrollTop = lastScrollPosition; - } -} - -// --------------------------------------------------------------------------- -// 10. Render Functions -// --------------------------------------------------------------------------- -const renderInput = (container, isFloating = false) => { - ignoreFocusChanges = true; - setTimeout(() => { - ignoreFocusChanges = false; - if (lastFocusedInput) lastFocusedInput.focus(); - }, 200); - container.empty(); - - pinBtn = submapRootBtn = refreshBtn = dockBtn = inputEl = ontologyEl = null; - foldBtnL0 = foldBtnL1 = foldBtnAll = null; - boundaryBtn = panelExpandBtn = null; - floatingGroupBtn = floatingBoxBtn = floatingZoomBtn = null; - importOutlineBtn = toggleCheckboxBtn = null; - calendarBtn = null; - - inputRow = new ea.obsidian.Setting(container); - let secondaryButtonContainer = null; - - if (!isFloating) { - inputRow.settingEl.style.display = "block"; - inputRow.controlEl.style.display = "block"; - inputRow.controlEl.style.width = "100%"; - inputRow.controlEl.style.marginTop = "8px"; - } else { - container.style.width = "85vw"; - container.style.maxWidth = "calc((var(--icon-size) + 2 * var(--size-2-3)) * 18)"; - inputRow.settingEl.style.border = "none"; - inputRow.settingEl.style.padding = "0"; - inputRow.infoEl.style.display = "none"; - - // Expandable container for floating mode - secondaryButtonContainer = container.createDiv(); - secondaryButtonContainer.style.display = isFloatingPanelExpanded ? "flex" : "none"; - secondaryButtonContainer.style.justifyContent = "flex-end"; - secondaryButtonContainer.style.flexWrap = "wrap"; - secondaryButtonContainer.style.gap = "0px"; - secondaryButtonContainer.style.marginTop = "6px"; - } - - // Clear default control element to build custom two-input layout - inputRow.controlEl.empty(); - const wrapper = inputRow.controlEl.createDiv("mindmap-input-wrapper"); - - ontologyEl = wrapper.createEl("input", { - type: "text", - cls: "mindmap-input-ontology", - placeholder: t("ONTOLOGY_PLACEHOLDER") - }); - - inputEl = wrapper.createEl("input", { - type: "text", - cls: "mindmap-input-main", - placeholder: t("INPUT_PLACEHOLDER") - }); - - inputEl.addEventListener("input", () => updateUI()); - ontologyEl.addEventListener("input", () => updateUI()); - - const updateFocusState = (focusedElement) => { - if (ignoreFocusChanges) return; - isOntologyFocused = (focusedElement === ontologyEl); - lastFocusedInput = focusedElement; - if (isOntologyFocused) { - ontologyEl.addClass("is-focused"); - inputEl.addClass("is-shrunk"); - } else { - ontologyEl.removeClass("is-focused"); - inputEl.removeClass("is-shrunk"); - } - }; - - const onFocus = (el) => { - if (ignoreFocusChanges) return; - updateFocusState(el); - registerObsidianHotkeyOverrides(); - ensureNodeSelected(); - updateUI(); - } - - // --- Restore State to New DOM Elements --- - // Apply the tracked focus state to the newly created elements immediately. - // This ensures that when focusInputEl() runs (via setTimeout in toggleDock), - // lastFocusedInput points to a valid, live DOM element. - if (isOntologyFocused) { - ontologyEl.addClass("is-focused"); - inputEl.addClass("is-shrunk"); - lastFocusedInput = ontologyEl; - } else { - ontologyEl.removeClass("is-focused"); - inputEl.removeClass("is-shrunk"); - lastFocusedInput = inputEl; - } - - ontologyEl.addEventListener("focus", () => onFocus(ontologyEl)); - inputEl.addEventListener("focus", () => onFocus(inputEl)); - - const onBlur = () => { - if (ignoreFocusChanges) return; - window.MindmapBuilder?.popObsidianHotkeyScope?.(); - saveSettings(); - }; - - ontologyEl.addEventListener("blur", onBlur); - inputEl.addEventListener("blur", onBlur); - - // Initialize Link Suggester on Main Input - linkSuggester = ea.attachInlineLinkSuggester(inputEl, inputRow.settingEl); - // Override modifyInput to replace dots with spaces, allowing fuzzy matcher to locate files correctly. - if (linkSuggester) { - linkSuggester.modifyInput = (input) => input.replace(/\./g, " "); - } - - const ariaHelp = [ - `${getActionLabel(ACTION_ADD)} (Enter)`, - `${getActionLabel(ACTION_ADD_FOLLOW)} ${getActionHotkeyString(ACTION_ADD_FOLLOW)}`, - `${getActionLabel(ACTION_ADD_FOLLOW_FOCUS)} ${getActionHotkeyString(ACTION_ADD_FOLLOW_FOCUS)}`, - `${getActionLabel(ACTION_ADD_FOLLOW_ZOOM)} ${getActionHotkeyString(ACTION_ADD_FOLLOW_ZOOM)}`, - ].join("\n"); - - inputEl.ariaLabel = ariaHelp; - - let dockedButtonContainer; - if (!isFloating) { - dockedButtonContainer = inputRow.controlEl.createDiv(); - dockedButtonContainer.style.display = "flex"; - dockedButtonContainer.style.justifyContent = "flex-end"; - dockedButtonContainer.style.flexWrap = "wrap"; - dockedButtonContainer.style.gap = "2px"; - dockedButtonContainer.style.marginTop = "6px"; - } - - const addButton = (cb, moveToSecondary = false) => { - inputRow.addExtraButton((btn) => { - cb(btn); - if (btn.buttonEl) btn.buttonEl.tabIndex = 0; - if (btn.extraSettingsEl) btn.extraSettingsEl.tabIndex = 0; - - const el = btn.extraSettingsEl; - if (!el) return; - - if (!isFloating && dockedButtonContainer) { - dockedButtonContainer.appendChild(el); - } else if (isFloating && moveToSecondary && secondaryButtonContainer) { - secondaryButtonContainer.appendChild(el); - } - }); - }; - - addButton((btn) => { - editBtn = btn; - btn.setIcon("pencil"); - btn.setTooltip(`${t("TOOLTIP_EDIT_NODE")} ${getActionHotkeyString(ACTION_EDIT)}`); - btn.extraSettingsEl.setAttr("action", ACTION_EDIT); - btn.onClick(() => performAction(ACTION_EDIT)); - }, false); - - addButton((btn) => { - pinBtn = btn; - btn.setTooltip(`${t("TOOLTIP_PIN_INIT")} ${getActionHotkeyString(ACTION_PIN)}`) - btn.extraSettingsEl.setAttr("action", ACTION_PIN); - btn.onClick(() => performAction(ACTION_PIN)); - }, false); - - addButton((btn) => { - toggleCheckboxBtn = btn; - btn.setIcon("square-check-big"); - btn.setTooltip(`${t("TOOLTIP_TOGGLE_CHECKBOX")} ${getActionHotkeyString(ACTION_TOGGLE_CHECKBOX)}`); - btn.extraSettingsEl.setAttr("action", ACTION_TOGGLE_CHECKBOX); - btn.onClick(() => performAction(ACTION_TOGGLE_CHECKBOX)); - }, true); - - addButton((btn) => { - calendarBtn = btn; - btn.setIcon("calendar"); - btn.setTooltip(`${t("TOOLTIP_CALENDAR")} ${getActionHotkeyString(ACTION_CALENDAR)}`); - btn.extraSettingsEl.setAttr("action", ACTION_CALENDAR); - btn.onClick(() => performAction(ACTION_CALENDAR)); - }, true); - - addButton((btn) => { - toggleEmbedBtn = btn; - btn.setIcon("file-sliders"); - btn.setTooltip(`${t("TOOLTIP_TOGGLE_EMBED")} ${getActionHotkeyString(ACTION_TOGGLE_EMBED)}`); - btn.extraSettingsEl.setAttr("action", ACTION_TOGGLE_EMBED); - btn.onClick(() => performAction(ACTION_TOGGLE_EMBED)); - }, true); - - toggleFloatingExtras = null; - - if (isFloating) { - toggleFloatingExtras = () => { - isFloatingPanelExpanded = !isFloatingPanelExpanded; - panelExpandBtn.setIcon(isFloatingPanelExpanded ? "panel-bottom-open" : "panel-top-open"); - - if (secondaryButtonContainer) { - secondaryButtonContainer.style.display = isFloatingPanelExpanded ? "flex" : "none"; - if (floatingInputModal && floatingInputModal.modalEl) { - floatingInputModal.modalEl.style.maxHeight = isFloatingPanelExpanded ? "unset" : FLOAT_MODAL_MAX_HEIGHT; - } - } - }; - - addButton((btn) => { - panelExpandBtn = btn; - btn.setIcon(isFloatingPanelExpanded ? "panel-bottom-open" : "panel-top-open"); - btn.setTooltip(t("TOOLTIP_TOGGLE_FLOATING_EXTRAS")); - btn.extraSettingsEl.setAttr("action", ACTION_TOGGLE_FLOATING_EXTRAS); - btn.onClick(() => performAction(ACTION_TOGGLE_FLOATING_EXTRAS)); - }, false); - - addButton((btn) => { - floatingGroupBtn = btn; - btn.setIcon("group"); - btn.extraSettingsEl.setAttr("action", ACTION_TOGGLE_GROUP); - btn.onClick(() => performAction(ACTION_TOGGLE_GROUP)); - }, true); - - addButton((btn) => { - floatingBoxBtn = btn; - btn.setIcon("rectangle-horizontal"); - btn.setTooltip(`${t("TOOLTIP_TOGGLE_BOX")} ${getActionHotkeyString(ACTION_BOX)}`); - btn.extraSettingsEl.setAttr("action", ACTION_BOX); - btn.onClick(() => performAction(ACTION_BOX)); - }, true); - - addButton((btn) => { - floatingZoomBtn = btn; - btn.setIcon("scan-search"); - btn.setTooltip(`${t("TOOLTIP_ZOOM_CYCLE")} ${getActionHotkeyString(ACTION_ZOOM)}`); - btn.extraSettingsEl.setAttr("action", ACTION_ZOOM); - btn.onClick(() => performAction(ACTION_ZOOM)); - }, true); - } - - addButton((btn) => { - focusBtn = btn; - btn.setIcon("scan-eye"); - btn.setTooltip(`${t("ACTION_LABEL_FOCUS")} ${getActionHotkeyString(ACTION_FOCUS)}`); - btn.extraSettingsEl.setAttr("action", ACTION_FOCUS); - btn.onClick(() => performAction(ACTION_FOCUS)); - }, true); - - addButton((btn) => { - boundaryBtn = btn; - btn.setIcon("cloud"); - btn.setTooltip(`${t("TOOLTIP_TOGGLE_BOUNDARY")} ${getActionHotkeyString(ACTION_TOGGLE_BOUNDARY)}`); - btn.extraSettingsEl.setAttr("action", ACTION_TOGGLE_BOUNDARY); - btn.onClick(() => performAction(ACTION_TOGGLE_BOUNDARY)); - }, true); - - addButton((btn) => { - submapRootBtn = btn; - btn.setIcon("map-pin-plus-inside"); - btn.extraSettingsEl.setAttr("action", ACTION_TOGGLE_SUBMAP_ROOT); - btn.onClick(() => performAction(ACTION_TOGGLE_SUBMAP_ROOT)); - }, true); - - addButton((btn) => { - foldBtnL0 = btn; - btn.setIcon("wifi-low"); - btn.setTooltip(`${t("TOOLTIP_FOLD_BRANCH")} ${getActionHotkeyString(ACTION_FOLD)}`); - btn.extraSettingsEl.setAttr("action", ACTION_FOLD); - btn.onClick(() => performAction(ACTION_FOLD)); - }, true); - - addButton((btn) => { - foldBtnL1 = btn; - btn.setIcon("wifi-high"); - btn.setTooltip(`${t("TOOLTIP_FOLD_L1_BRANCH")} ${getActionHotkeyString(ACTION_FOLD_L1)}`); - btn.extraSettingsEl.setAttr("action", ACTION_FOLD_L1); - btn.onClick(() => performAction(ACTION_FOLD_L1)); - }, true); - - addButton((btn) => { - foldBtnAll = btn; - btn.setIcon("wifi"); - btn.setTooltip(`${t("TOOLTIP_FOLD_ALL")} ${getActionHotkeyString(ACTION_FOLD_ALL)}`); - btn.extraSettingsEl.setAttr("action", ACTION_FOLD_ALL); - btn.onClick(() => performAction(ACTION_FOLD_ALL)); - }, true); - - addButton((btn) => { - refreshBtn = btn; - btn.setIcon("refresh-ccw"); - btn.setTooltip(`${t("TOOLTIP_REFRESH")} ${getActionHotkeyString(ACTION_REARRANGE)}`); - btn.extraSettingsEl.setAttr("action", ACTION_REARRANGE); - btn.onClick(() => performAction(ACTION_REARRANGE)); - }, true); - - addButton((btn) => { - copyBtn = btn; - btn.setIcon("copy"); - btn.setTooltip(`${t("ACTION_LABEL_COPY")} ${getActionHotkeyString(ACTION_COPY)}`); - btn.extraSettingsEl.setAttr("action", ACTION_COPY); - btn.onClick(() => performAction(ACTION_COPY)); - }, true); - - addButton((btn) => { - cutBtn = btn; - btn.setIcon("scissors"); - btn.setTooltip(`${t("ACTION_LABEL_CUT")} ${getActionHotkeyString(ACTION_CUT)}`); - btn.extraSettingsEl.setAttr("action", ACTION_CUT); - btn.onClick(() => performAction(ACTION_CUT)); - }, true); - - addButton((btn) => { - btn.setIcon("clipboard"); - btn.setTooltip(`${t("ACTION_LABEL_PASTE")} ${getActionHotkeyString(ACTION_PASTE)}`); - btn.extraSettingsEl.setAttr("action", ACTION_PASTE); - btn.onClick(() => performAction(ACTION_PASTE)); - }, true); - - addButton((btn) => { - importOutlineBtn = btn; - btn.setIcon("list-tree"); - btn.setTooltip(`${t("TOOLTIP_IMPORT_OUTLINE")} ${getActionHotkeyString(ACTION_IMPORT_OUTLINE)}`); - btn.extraSettingsEl.setAttr("action", ACTION_IMPORT_OUTLINE); - btn.onClick(() => performAction(ACTION_IMPORT_OUTLINE)); - }, true); - - addButton((btn) => { - dockBtn = btn; - btn.setIcon(isFloating ? "dock" : "external-link"); - btn.extraSettingsEl.setAttr("action", ACTION_DOCK_UNDOCK); - btn.setTooltip( - `${isFloating ? t("TOOLTIP_DOCK") : t("TOOLTIP_UNDOCK")} ${getActionHotkeyString(ACTION_DOCK_UNDOCK)}` - ); - btn.onClick(() => performAction(ACTION_DOCK_UNDOCK)); - }, true); - - updateUI(); -}; - -/** - * Renders the main settings body and UI actions for the sidepanel. - * Includes the preset dropdown block for saving, deleting, applying, and creating named configurations. - * - * @param {HTMLElement} contentEl - The parent DOM element to render into. - */ -const renderBody = (contentEl) => { - bodyContainer = contentEl.createDiv(); - bodyContainer.style.width = "100%"; - - bodyContainer.createEl("hr"); - - // --- Map Preset Manager UI --- - const presetSetting = new ea.obsidian.Setting(bodyContainer) - .setName(t("PRESET_LABEL")) - .addDropdown(d => { - presetDropdown = d; - refreshPresetDropdown(); - d.onChange(async (v) => { - activePresetName = v; - setVal(K_ACTIVE_PRESET, v); - const sel = getMindmapNodeFromSelection(); - if (sel) { - await applyPresetToMap(v, sel); - new Notice(t("NOTICE_PRESET_APPLIED")); - } else { - applyPresetToGlobals(v); - updateUI(); - } - }); - }); - - presetSetting.addExtraButton(btn => { - presetSaveBtn = btn; - btn.setIcon("save").setTooltip(t("PRESET_BTN_SAVE")).onClick(async () => { - if (!activePresetName) return; - mapPresets[activePresetName] = extractConfigFromGlobals(); - setVal(K_PRESETS, mapPresets, true); - new Notice(t("NOTICE_PRESET_SAVED")); - updateUI(); - }); - }); - - presetSetting.addExtraButton(btn => { - presetTrashBtn = btn; - btn.setIcon("trash-2").setTooltip(t("PRESET_BTN_DELETE")).onClick(async () => { - if (!activePresetName || activePresetName === "Default") return; - delete mapPresets[activePresetName]; - activePresetName = "Default"; - setVal(K_PRESETS, mapPresets, true); - setVal(K_ACTIVE_PRESET, activePresetName); - new Notice(t("NOTICE_PRESET_DELETED")); - refreshPresetDropdown(); - updateUI(); - }); - }); - - presetSetting.addExtraButton(btn => { - presetPlusBtn = btn; - btn.setIcon("plus").setTooltip(t("PRESET_BTN_NEW")).onClick(async () => { - const name = await utils.inputPrompt(t("PROMPT_NEW_PRESET_NAME")); - if (name && name.trim()) { - const trimmed = name.trim(); - mapPresets[trimmed] = extractConfigFromGlobals(); - activePresetName = trimmed; - setVal(K_PRESETS, mapPresets, true); - setVal(K_ACTIVE_PRESET, activePresetName); - refreshPresetDropdown(); - - const sel = getMindmapNodeFromSelection(); - if (sel) { - await updateRootNodeCustomData({ presetName: activePresetName }, sel); - } - new Notice(t("NOTICE_PRESET_SAVED")); - updateUI(); - } - }); - }); - - presetSetting.addExtraButton(btn => { - presetApplyBtn = btn; - btn.setIcon("refresh-cw").setTooltip(t("PRESET_BTN_APPLY")).onClick(async () => { - const sel = getMindmapNodeFromSelection(); - if (sel && activePresetName) { - await applyPresetToMap(activePresetName, sel); - new Notice(t("NOTICE_PRESET_APPLIED")); - } - }); - }); - - presetWarningEl = bodyContainer.createEl("div", { - text: t("PRESET_WARNING_MODIFIED"), - cls: "mod-warning", - attr: { style: "font-size: 0.85em; margin-top: -10px; margin-bottom: 10px; display: none; text-align: right;" } - }); - - bodyContainer.createEl("hr"); - // --- End Map Preset Manager UI --- - - const zoomSetting = new ea.obsidian.Setting(bodyContainer); - zoomSetting.setName(t("LABEL_ZOOM_LEVEL")).addDropdown((d) => { - ZOOM_TYPES.forEach((key) => d.addOption(key, key)); - d.setValue(zoomLevel); - d.onChange((v) => { - zoomLevel = v; - if (disableTabEvents) return; - - setVal(K_ZOOM, v); - zoomToFit(); - }); - }); - zoomSetting.addExtraButton(btn => { - zoomBtn = btn; - btn.setIcon("scan-search") - .setTooltip(`${t("TOOLTIP_ZOOM_CYCLE")} ${getActionHotkeyString(ACTION_ZOOM)}`) - .onClick(() => performAction(ACTION_ZOOM)); - }); - - new ea.obsidian.Setting(bodyContainer).setName(t("LABEL_GROWTH_STRATEGY")).addDropdown((d) => { - strategyDropdown = d; - GROWTH_TYPES.forEach((key) => d.addOption(key, key)); - d.setValue(currentModalGrowthMode); - d.onChange(async (v) => { - currentModalGrowthMode = v; - if (disableTabEvents) return; - - setVal(K_GROWTH, v); - if (fillSweepToggleSetting) { - fillSweepToggleSetting.settingEl.style.display = v === "Radial" ? "" : "none"; - } - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - await updateRootNodeCustomData({ - growthMode: v - }, sel); - await refreshMapLayout(sel); - }); - }); - - fillSweepToggleSetting = new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_FILL_SWEEP")) - .setDesc(t("DESC_FILL_SWEEP")) - .addToggle((t) => { - fillSweepToggle = t; - t.setValue(fillSweep) - .onChange(async (v) => { - fillSweep = v; - if (disableTabEvents) return; - - setVal(K_FILL_SWEEP, v); - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - await updateRootNodeCustomData({ - fillSweep: v - }, sel); - await refreshMapLayout(sel); - }) - }); - if (currentModalGrowthMode !== "Radial") { - fillSweepToggleSetting.settingEl.style.display = "none"; - } - - new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_AUTO_LAYOUT")) - .addToggle((t) => { - autoLayoutToggle = t; - t.setValue(!autoLayoutDisabled) - .onChange(async (v) => { - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - autoLayoutDisabled = !v; - if (disableTabEvents) return; - await updateRootNodeCustomData({ - autoLayoutDisabled - }, sel); - await refreshMapLayout(sel); - }); - }) - .addExtraButton(btn => btn - .setIcon("pencil-ruler") - .setTooltip(t("TOOLTIP_CONFIGURE_LAYOUT")) - .onClick(() => { - const modal = new LayoutConfigModal(app, layoutSettings, async (newSettings) => { - layoutSettings = newSettings; - setVal(K_LAYOUT, layoutSettings, true); - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - await updateRootNodeCustomData({ - layoutSettings: newSettings - }, sel); - const allElements = ea.getViewElements(); - const hierarchy = getHierarchy(sel, allElements); - const masterRoot = allElements.find((el) => el.id === hierarchy.rootId) ?? sel; - await refreshMapLayout(masterRoot); - }); - modal.open(); - }) - ) - - new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_GROUP_BRANCHES")) - .addToggle((t) => t - .setValue(groupBranches) - .onChange(async (v) => { - if (!isViewSet()) return; - groupBranches = v; - if (disableTabEvents) return; - setVal(K_GROUP, v); - await refreshMapLayout(); - updateUI(); - })) - .addExtraButton((btn) => { - toggleGroupBtn = btn; - btn.setIcon("group"); - btn.setTooltip(`${t("TOOLTIP_TOGGLE_GROUP_BTN")} ${getActionHotkeyString(ACTION_TOGGLE_GROUP)}`); - btn.onClick(() => performAction(ACTION_TOGGLE_GROUP)); - }); - - bodyContainer.createEl("hr"); - - new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_BOX_CHILD_NODES")) - .addToggle((t) => { - boxToggle = t; - t.setValue(boxChildren) - .onChange(async (v) => { - boxChildren = v; - if (disableTabEvents) return; - setVal(K_BOX, v); - await updateRootNodeCustomData({ - boxChildren: v - }); - }) - }) - .addExtraButton((btn) => { - boxBtn = btn; - btn.setIcon("rectangle-horizontal"); - btn.setTooltip(`${t("TOOLTIP_TOGGLE_BOX")} ${getActionHotkeyString(ACTION_BOX)}`); - btn.onClick(() => performAction(ACTION_BOX)); - }); - - new ea.obsidian.Setting(bodyContainer).setName(t("LABEL_ROUNDED_CORNERS")).addToggle((t) => { - roundToggle = t; - t.setValue(roundedCorners) - .onChange(async (v) => { - roundedCorners = v; - if (disableTabEvents) return; - setVal(K_ROUND, v); - await updateRootNodeCustomData({ - roundedCorners: v - }); - }) - }); - - bodyContainer.createEl("hr"); - - new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_ARROW_TYPE")) - .addToggle((t) => { - arrowTypeToggle = t; - t.setValue(arrowType === "curved") - .onChange(async (v) => { - arrowType = v ? "curved" : "straight"; - if (disableTabEvents) return; - - setVal(K_ARROW_TYPE, arrowType); - if (!isViewSet()) return; - const sel = getMindmapNodeFromSelection(); - if (!sel) return; - await updateRootNodeCustomData({ - arrowType - }, sel); - await refreshMapLayout(sel); - }) - }) - - new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_USE_SCENE_STROKE")) - .setDesc( - t("DESC_USE_SCENE_STROKE"), - ) - .addToggle((t) => { - strokeToggle = t; - t.setValue(!isSolidArrow).onChange(async (v) => { - isSolidArrow = !v; - if (disableTabEvents) return; - - setVal(K_ARROWSTROKE, !v); - await updateRootNodeCustomData({ - isSolidArrow: !v - }); - }) - }); - - new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_BRANCH_SCALE")) - .addDropdown((d) => { - branchScaleDropdown = d; - BRANCH_SCALE_TYPES.forEach((key) => d.addOption(key, key)); - d.setValue(branchScale); - d.onChange(async (v) => { - const oldScale = branchScale; - branchScale = v; - if (disableTabEvents) return; - - setVal(K_BRANCH_SCALE, v); - const info = await updateRootNodeCustomData({ - branchScale: v - }); - if (info) { - await updateBranchStrokes(info.rootId, baseStrokeWidth, oldScale, baseStrokeWidth, branchScale); - } - }); - }); - - let baseWidthDisplay; - let baseWidthUpdateTimer = null; - let baseWidthSnapshot = null; - - const baseWidthSetting = new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_BASE_WIDTH")) - .addSlider((s) => { - baseWidthSlider = s; - s.setLimits(0.2, 16, 0.1) - .setValue(baseStrokeWidth) - .onChange((v) => { - if (baseWidthUpdateTimer) clearTimeout(baseWidthUpdateTimer); - if (!disableTabEvents && baseWidthSnapshot === null) baseWidthSnapshot = baseStrokeWidth; - baseStrokeWidth = v; - baseWidthDisplay.setText(`${v}`); - if (disableTabEvents) return; - - setVal(K_BASE_WIDTH, v); - baseWidthUpdateTimer = setTimeout(async () => { - const info = await updateRootNodeCustomData({ - baseStrokeWidth: v - }); - if (info) { - await updateBranchStrokes(info.rootId, baseWidthSnapshot, branchScale, baseStrokeWidth, branchScale); - } - baseWidthSnapshot = null; - baseWidthUpdateTimer = null; - }, 500); - }); - }); - baseWidthDisplay = baseWidthSetting.descEl.createSpan({ - text: `${baseStrokeWidth}`, - attr: { - style: "margin-left:10px; font-weight:bold;" - }, - }); - if (baseWidthSlider) baseWidthSlider.valLabelEl = baseWidthDisplay; - - new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_MULTICOLOR_BRANCHES")) - .addToggle((t) => { - colorToggle = t; - t.setValue(multicolor) - .onChange(async (v) => { - multicolor = v; - if (disableTabEvents) return; - - setVal(K_MULTICOLOR, v); - await updateRootNodeCustomData({ - multicolor: v - }); - }) - }) - .addExtraButton((btn) => btn - .setIcon("palette") - .setTooltip(t("TOOLTIP_CONFIGURE_PALETTE")) - .onClick(() => { - const modal = new PaletteManagerModal(app, customPalette, (newSettings) => { - customPalette = newSettings; - setVal(K_PALETTE, customPalette, true); - }); - modal.open(); - }) - ); - - bodyContainer.createEl("hr"); - - let sliderValDisplay; - const sliderSetting = new ea.obsidian.Setting(bodyContainer).setName(t("LABEL_MAX_WRAP_WIDTH")).addSlider((s) => { - widthSlider = s; - s.setLimits(WRAP_WIDTH_MIN, WRAP_WIDTH_MAX, WRAP_WIDTH_STEP) - .setValue(maxWidth) - .onChange(async (v) => { - maxWidth = v; - sliderValDisplay.setText(`${v}px`); - if (disableTabEvents) return; - - setVal(K_WIDTH, v); - await updateRootNodeCustomData({ - maxWrapWidth: v - }); - }) - }); - sliderValDisplay = sliderSetting.descEl.createSpan({ - text: `${maxWidth}px`, - attr: { - style: "margin-left:10px; font-weight:bold;" - }, - }); - - if (widthSlider) widthSlider.valLabelEl = sliderValDisplay; - - new ea.obsidian.Setting(bodyContainer) - .setName(t("LABEL_CENTER_TEXT")) - .setDesc(t("DESC_CENTER_TEXT")) - .addToggle((t) => { - centerToggle = t; - t.setValue(centerText) - .onChange(async (v) => { - centerText = v; - if (disableTabEvents) return; - - setVal(K_CENTERTEXT, v); - await updateRootNodeCustomData({ - centerText: v - }); - }) - }); - - new ea.obsidian.Setting(bodyContainer).setName(t("LABEL_FONT_SIZES")).addDropdown((d) => { - fontSizeDropdown = d; - FONT_SCALE_TYPES.forEach((key) => d.addOption(key, key)); - d.setValue(fontsizeScale); - d.onChange(async (v) => { - fontsizeScale = v; - if (disableTabEvents) return; - - setVal(K_FONTSIZE, v); - await updateRootNodeCustomData({ - fontsizeScale: v - }); - }); - }); - - // ------------------------------------ - // Hotkey Configuration Section - // ------------------------------------ - bodyContainer.createEl("hr"); - - const hkDetails = bodyContainer.createEl("details", { - attr: { - style: "margin-right: 5px; margin-left: 5px;" - } - }); - hkDetails.createEl("summary", { - text: t("HOTKEY_SECTION_TITLE"), - attr: { - style: "cursor: pointer; font-weight: bold;" - } - }); - - const hkContainer = hkDetails.createDiv(); - const hint = hkContainer.createEl("p", { - text: t("HOTKEY_HINT"), - attr: { - style: "color: var(--text-muted); font-size: 0.85em; margin-bottom: 10px;" - } - }); - - const refreshHotkeys = () => { - RUNTIME_HOTKEYS = generateRuntimeHotkeys(); - // Re-register scope if currently active - registerObsidianHotkeyOverrides(); - // Ensure event listeners are attached to the correct window - updateKeyHandlerLocation(); - }; - - const saveHotkeys = () => { - // Strip out structural keys before saving to settings to maintain a single source of truth - const hotkeysToSave = userHotkeys.map(h => { - const { - isInputOnly, - requiresNode, - isNavigation, - hidden, - ...configurableProps - } = h; - return configurableProps; - }); - - setVal(K_HOTKEYS, hotkeysToSave, true); - refreshHotkeys(); - }; - - const isModified = (current) => { - const def = DEFAULT_HOTKEYS.find(d => d.action === current.action); - if (!def) return false; - - const k1 = current.code || current.key; - const k2 = def.code || def.key; - if (k1 !== k2) return true; - - if (current.modifiers.length !== def.modifiers.length) return true; - // Check if every modifier in current exists in def - return !current.modifiers.every(m => def.modifiers.includes(m)); - }; - - const recordHotkey = (btn, hIndex, onUpdate) => { - const originalText = btn.innerHTML; - const label = btn.parentElement.querySelector(".setting-hotkey"); - - btn.innerHTML = t("RECORD_HOTKEY_PROMPT"); - btn.addClass("is-recording"); - isRecordingHotkey = true; - - recordingScope = new ea.obsidian.Scope(); - app.keymap.pushScope(recordingScope); - - const cleanup = () => { - if (recordingScope) { - app.keymap.popScope(recordingScope); - recordingScope = null; - } - - btn.innerHTML = originalText; - btn.removeClass("is-recording"); - - isRecordingHotkey = false; - cancelHotkeyRecording = null; - }; - - cancelHotkeyRecording = cleanup; - - const handler = (e) => { - if (e.key === "Escape") { - cleanup(); - return false; - } - - // Ignore modifier-only presses (but return false to block them from bubbling) - if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return false; - - const mods = []; - if (e.ctrlKey) mods.push("Ctrl"); - if (e.metaKey) mods.push("Meta"); - if (e.altKey) mods.push("Alt"); - if (e.shiftKey) mods.push("Shift"); - - let key = e.key; - let code = e.code; - - if (key === " ") key = "Space"; - - const targetConfig = userHotkeys[hIndex]; - const isNav = targetConfig.isNavigation; - - // Validation - if (isNav && !["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(key)) { - new Notice(t("NOTICE_ACTION_REQUIRES_ARROWS")); - cleanup(); - return false; - } - - // Check conflicts - const conflict = userHotkeys.find((h, i) => { - if (i === hIndex) return false; - - const sameMods = h.modifiers.length === mods.length && h.modifiers.every(m => mods.includes(m)); - if (!sameMods) return false; - - if (h.isNavigation && isNav) return true; - if (h.isNavigation && key.startsWith("Arrow")) return true; - - const hKey = h.code ? h.code.replace("Key", "").replace("Digit", "") : h.key; - const eKey = code ? code.replace("Key", "").replace("Digit", "") : key; - return hKey.toLowerCase() === eKey.toLowerCase(); - }); - - if (conflict) { - label.style.color = "var(--text-error)"; - new Notice(t("NOTICE_CONFLICT_WITH_ACTION", { - action: getActionLabel(conflict.action) - }), NOTICE_DURATION_CONFLICT); - setTimeout(() => label.style.color = "", 4000); - } else { - if (isNav) { - targetConfig.modifiers = mods.map(m => m === "Ctrl" || m === "Meta" ? "Mod" : m); - } else { - targetConfig.modifiers = mods.map(m => m === "Ctrl" || m === "Meta" ? "Mod" : m); - if (code && (code.startsWith("Key") || code.startsWith("Digit"))) { - targetConfig.code = code; - delete targetConfig.key; - } else { - targetConfig.key = key; - delete targetConfig.code; - } - } - saveHotkeys(); - - if (targetConfig.scope === SCOPE.global) { - const obsConflict = getObsidianConflict(targetConfig); - if (obsConflict) { - new Notice(t("NOTICE_OBSIDIAN_HOTKEY_CONFLICT", { - command: obsConflict - }), NOTICE_DURATION_GLOBAL_CONFLICT); - } - } - - if (onUpdate) onUpdate(); - } - - cleanup(); - // Return false to preventDefault and stop propagation within Obsidian's keymap - return false; - }; - - recordingScope.register(null, null, handler); - }; - - userHotkeys.forEach((h, index) => { - if (h.hidden) return; - const setting = new ea.obsidian.Setting(hkContainer) - .setName(getActionLabel(h.action)); - setting.settingEl.style.paddingRight = "0"; - setting.settingEl.style.paddingLeft = "0"; - - const controlDiv = setting.controlEl; - controlDiv.addClass("setting-item-control"); - - let scopeBtn = null; - let updateScopeUI = null; - - const hotkeyDisplay = controlDiv.createDiv("setting-command-hotkeys"); - const span = hotkeyDisplay.createSpan("setting-hotkey"); - const restoreBtn = controlDiv.createSpan("clickable-icon setting-restore-hotkey-button"); - - const updateRowUI = () => { - span.textContent = getHotkeyDisplayString(userHotkeys[index]); - restoreBtn.style.display = isModified(userHotkeys[index]) ? "" : "none"; - if (updateScopeUI) updateScopeUI(); - - const existingAlert = hotkeyDisplay.querySelector(".hotkey-conflict-icon"); - if (existingAlert) existingAlert.remove(); - span.removeClass("has-conflict"); - span.style.color = ""; - - if (userHotkeys[index].scope === SCOPE.global) { - const conflict = getObsidianConflict(userHotkeys[index]); - if (conflict) { - span.addClass("has-conflict"); - - const alert = hotkeyDisplay.createSpan("hotkey-conflict-icon"); - alert.innerHTML = ea.obsidian.getIcon("octagon-alert").outerHTML; - alert.style.color = "var(--text-error)"; - alert.style.marginRight = "calc(-1 * var(--size-2-2))"; - alert.style.display = "inline-flex"; // Ensure it sits nicely next to text - alert.style.cursor = "pointer"; - alert.ariaLabel = t("ARIA_OVERRIDE_COMMAND", { - command: conflict - }); - alert.onclick = (e) => { - e.preventDefault(); - e.stopPropagation(); - new Notice(t("NOTICE_GLOBAL_HOTKEY_CONFLICT", { - command: conflict - }), NOTICE_DURATION_GLOBAL_CONFLICT); - }; - } - } - }; - - if (!h.isInputOnly) { - scopeBtn = controlDiv.createSpan("clickable-icon setting-global-hotkey-button"); - scopeBtn.style.marginRight = "calc(-1 * var(--size-2-2))"; - - updateScopeUI = () => { - const scope = userHotkeys[index].scope; - switch (scope) { - case SCOPE.input: - scopeBtn.innerHTML = ea.obsidian.getIcon("keyboard").outerHTML; - scopeBtn.ariaLabel = t("ARIA_SCOPE_INPUT"); - scopeBtn.style.color = "var(--text-muted)"; - break; - case SCOPE.excalidraw: - scopeBtn.innerHTML = ea.obsidian.getIcon("excalidraw-icon").outerHTML; - scopeBtn.ariaLabel = t("ARIA_SCOPE_EXCALIDRAW"); - scopeBtn.style.color = "var(--interactive-accent)"; - break; - case SCOPE.global: - scopeBtn.innerHTML = ea.obsidian.getIcon("globe").outerHTML; - scopeBtn.ariaLabel = t("ARIA_SCOPE_GLOBAL"); - scopeBtn.style.color = "var(--text-error)"; - break; - } - }; - - scopeBtn.onclick = () => { - const current = userHotkeys[index].scope; - let next = SCOPE.input; - if (current === SCOPE.input) next = SCOPE.excalidraw; - else if (current === SCOPE.excalidraw) next = SCOPE.global; - else if (current === SCOPE.global) next = SCOPE.input; - - userHotkeys[index].scope = next; - saveHotkeys(); - - if (next === SCOPE.global) { - const conflict = getObsidianConflict(userHotkeys[index]); - if (conflict) { - new Notice(t("NOTICE_GLOBAL_HOTKEY_CONFLICT", { - command: conflict - }), NOTICE_DURATION_GLOBAL_CONFLICT); - } - } - updateRowUI(); - }; - updateScopeUI(); - } - - restoreBtn.innerHTML = ea.obsidian.getIcon("rotate-ccw").outerHTML; - restoreBtn.ariaLabel = t("ARIA_RESTORE_DEFAULT"); - restoreBtn.onclick = () => { - const def = DEFAULT_HOTKEYS.find(d => d.action === userHotkeys[index].action); - if (def) { - userHotkeys[index] = JSON.parse(JSON.stringify(def)); - saveHotkeys(); - updateRowUI(); - } - }; - - updateRowUI(); - - const addBtn = controlDiv.createSpan("clickable-icon setting-add-hotkey-button"); - addBtn.innerHTML = ea.obsidian.getIcon("plus-circle").outerHTML; - if (h.key === "Escape") { - addBtn.style.opacity = 0; - return; - } - addBtn.ariaLabel = t("ARIA_CUSTOMIZE_HOTKEY"); - addBtn.onclick = () => recordHotkey(addBtn, index, updateRowUI); - }); - - // Spacer to avoid overlap with Obsidian's status bar - bodyContainer.createDiv({ - attr: { - style: "height: 40px;" - } - }); -}; - -const MINDMAP_FOCUS_STYLE_ID = "excalidraw-mindmap-focus-style"; - -const registerStyles = () => { - // Remove existing styles first to ensure updates are applied immediately - const existing = document.getElementById(MINDMAP_FOCUS_STYLE_ID); - if (existing) existing.remove(); - - const styleEl = document.createElement("style"); - styleEl.id = MINDMAP_FOCUS_STYLE_ID; - styleEl.textContent = [ - ".modal.excalidraw-mindmap-ui {", - " overflow: hidden;", - " scrollbar-width: none;", - "}", - ".excalidraw-mindmap-ui .modal-header-button {display: none;}", - // Focus styles - ".excalidraw-mindmap-ui button:focus,", - ".excalidraw-mindmap-ui .clickable-icon:focus,", - ".excalidraw-mindmap-ui [tabindex]:focus,", - ".excalidraw-mindmap-ui button:focus-visible,", - ".excalidraw-mindmap-ui .clickable-icon:focus-visible,", - ".excalidraw-mindmap-ui [tabindex]:focus-visible {", - " outline: 2px solid var(--interactive-accent) !important;", - " outline-offset: 2px;", - "}", - ...ea.DEVICE.isDesktop ? - [".excalidraw-mindmap-ui hr {margin: 5px;}"] : - [".excalidraw-mindmap-ui hr {margin: 15px 5px;}"], - ".excalidraw-mindmap-ui .clickable-icon:focus svg,", - ".excalidraw-mindmap-ui .clickable-icon:focus-visible svg {", - " color: inherit;", - "}", - // New Flex Input Styles - ".mindmap-input-wrapper { display: flex; gap: 8px; width: 100%; transition: all 0.3s ease; }", - ".mindmap-input-ontology { flex: 1; transition: flex-grow 0.3s ease; min-width: 0; }", - ".mindmap-input-main { flex: 17; transition: flex-grow 0.3s ease; min-width: 0; }", - ".mindmap-input-ontology.is-focused { flex: 17; }", - ".mindmap-input-main.is-shrunk { flex: 1; }", - // Drag Handle Styles - ".excalidraw-mindmap-ui .mindmap-drag-handle {", - " position: absolute;", - " right: 0;", - " top: 0;", - " bottom: 0;", - " width: 20px;", - " cursor: grab;", - " display: flex;", - " align-items: center;", - " justify-content: center;", - " opacity: 0.4;", - " color: var(--text-muted);", - " transition: opacity 0.2s ease, color 0.2s ease;", - " background: var(--background-secondary);", - " border-left: 1px solid var(--background-modifier-border);", - " border-top-right-radius: 6px;", - " border-bottom-right-radius: 6px;", - "}", - ".excalidraw-mindmap-ui:focus-within .mindmap-drag-handle,", - ".excalidraw-mindmap-ui .mindmap-drag-handle:hover,", - ".excalidraw-mindmap-ui .mindmap-drag-handle:active {", - " opacity: 1;", - " color: var(--text-normal);", - "}", - ".excalidraw-mindmap-ui.is-dragging .mindmap-drag-handle {", - " cursor: grabbing;", - "}" - ].join("\n"); - document.head.appendChild(styleEl); -}; - -const removeStyles = () => { - const styleEl = document.getElementById(MINDMAP_FOCUS_STYLE_ID); - if (styleEl) styleEl.remove(); -}; - -const updateKeyHandlerLocation = () => { - // Attach to the appropriate window based on state - if (isUndocked) { - // Floating: Input is reparented to targetView's window - if (ea.targetView && ea.targetView.ownerWindow) { - registerKeydownHandler(ea.targetView.ownerWindow, handleKeydown); - } - } else { - // Docked: Input is in the sidepanel's window - if (sidepanelWindow) { - registerKeydownHandler(sidepanelWindow, handleKeydown); - } - } -}; - -// --------------------------------------------------------------------------- -// Docking & Floating Input Management -// --------------------------------------------------------------------------- -/** - * silent === true: sidepanel is not revealed after docking - * forceDock === true: if input is undocked, docking happens even if no ExcalidrawView is present - * saveSetting === true: the dock/undock status is saved to settings. When input is docked because - * the ExcalidrawView was closed or when the user presses ESC to finish mindmapping, next time - * Mindmap Builder is started it should remember the user preference - * - **/ -const toggleDock = async ({ - silent = false, - forceDock = false, - saveSetting = false -} = {}) => { - editingNodeId = null; - if (!ea.targetView && !(forceDock && isUndocked)) return; - - // Check visibility if not silent - if (!silent) { - const isSidepanelVisible = ea.getSidepanelLeaf().isVisible(); - // Manage sidepanel visibility based on docking state - if (isUndocked && !isSidepanelVisible) { - const leaf = ea.getSidepanelLeaf(); - if (leaf) app.workspace.revealLeaf(leaf); - } else if (isSidepanelVisible && !isUndocked) { - ea.toggleSidepanelView(); - } - - if (isUndocked) { - // If we were undocked (now docking), focus the sidepanel - app.workspace.setActiveLeaf(ea.getSidepanelLeaf(), { - focus: true - }); - } else { - // If we were docked (now undocking), focus the main view - app.workspace.setActiveLeaf(ea.targetView.leaf, { - focus: true - }); - } - } - - isUndocked = !isUndocked; - if (saveSetting) { - setVal(K_UNDOCKED, isUndocked); - } - - // Update keyboard event routing - updateKeyHandlerLocation(); - - if (isUndocked) { - // UNDOCK: Initialize floating modal - floatingInputModal = new ea.FloatingModal(ea.plugin.app); - const { - contentEl, - titleEl, - modalEl, - headerEl, - bgEl - } = floatingInputModal; - modalEl.classList.add("excalidraw-mindmap-ui"); - if (bgEl) { - bgEl.style.display = "none"; - } - floatingInputModal.onOpen = () => { - // Reparent modal to target view window - if (ea.targetView && modalEl.ownerDocument !== ea.targetView.ownerDocument) { - ea.targetView.ownerDocument.body.appendChild(modalEl); - } - - const { - x, - y - } = ea.targetView.contentEl.getBoundingClientRect(); - contentEl.empty(); - - const closeEl = modalEl.querySelector(".modal-close-button"); - if (closeEl) closeEl.style.display = "none"; - titleEl.style.display = "none"; - headerEl.style.display = "none"; - modalEl.style.opacity = `${FLOAT_MODAL_OPACITY}`; - modalEl.style.padding = "6px"; - modalEl.style.paddingRight = "26px"; // Make room for the drag handle - modalEl.style.minHeight = "0px"; - modalEl.style.width = "fit-content"; - modalEl.style.height = "auto"; - modalEl.style.maxHeight = FLOAT_MODAL_MAX_HEIGHT; - - if (isExcaliBrainView()) { - modalEl.style.display = "none"; - } - - const container = floatingInputModal.contentEl.createDiv(); - renderInput(container, true); - - // Setup Drag Handle - const dragHandle = modalEl.createDiv("mindmap-drag-handle"); - dragHandle.innerHTML = ea.obsidian.getIcon("grip-vertical").outerHTML; - - let isDragging = false; - let startX, startY, initialLeft, initialTop; - - dragHandle.addEventListener("pointerdown", (e) => { - isDragging = true; - startX = e.clientX; - startY = e.clientY; - const rect = modalEl.getBoundingClientRect(); - initialLeft = rect.left; - initialTop = rect.top; - dragHandle.setPointerCapture(e.pointerId); - modalEl.classList.add("is-dragging"); - e.preventDefault(); - }); - - dragHandle.addEventListener("pointermove", (e) => { - if(!isDragging) return; - const dx = e.clientX - startX; - const dy = e.clientY - startY; - modalEl.style.left = `${initialLeft + dx}px`; - modalEl.style.top = `${initialTop + dy}px`; - }); - - dragHandle.addEventListener("pointerup", (e) => { - isDragging = false; - dragHandle.releasePointerCapture(e.pointerId); - modalEl.classList.remove("is-dragging"); - }); - - dragHandle.addEventListener("dblclick", (e) => { - const { x, y } = ea.targetView.contentEl.getBoundingClientRect(); - const desktopShift = !!ea.targetView.contentEl.querySelector(".App-bottom-bar .App-toolbar") ? - 0 : - (ea.targetView.contentEl.clientWidth < 1200 ? 36 : 0); - modalEl.style.top = `${y + FLOAT_MODAL_OFFSET + desktopShift}px`; - modalEl.style.left = `${x + FLOAT_MODAL_OFFSET}px`; - }); - - setTimeout(() => { - //the modalEl is repositioned after a delay - //otherwise the event handlers in FloatingModal would override the move - //leaving modalEl in the center of the view - //modalEl.style.top and left must stay in the timeout call - const { - x, - y - } = ea.targetView.contentEl.getBoundingClientRect(); - const desktopShift = !!ea.targetView.contentEl.querySelector(".App-bottom-bar .App-toolbar") ? - 0 : - (ea.targetView.contentEl.clientWidth < 1200 ? 36 : 0); - modalEl.style.top = `${ y + FLOAT_MODAL_OFFSET + desktopShift}px`; - modalEl.style.left = `${ x + FLOAT_MODAL_OFFSET }px`; - }, ea.DEVICE.isMobile ? 400 : 150); - }; - - floatingInputModal.onClose = () => { - window.MindmapBuilder?.popObsidianHotkeyScope?.(); - floatingInputModal = null; - if (isUndocked) { - // If closed manually (e.g. unexpected close), dock back silently - isUndocked = false; - setVal(K_UNDOCKED, false); - updateKeyHandlerLocation(); // Restore listeners to sidepanel - if (ea.sidepanelTab && inputContainer) renderInput(inputContainer, false); - } - }; - - // Clear sidepanel input - inputContainer.empty(); - floatingInputModal.open(); - } else { - if (floatingInputModal) { - if (floatingInputModal.modalEl && floatingInputModal.modalEl.parentElement) { - floatingInputModal.modalEl.remove(); - } - floatingInputModal.close(); - floatingInputModal = null; - } - renderInput(inputContainer, false); - if (forceDock) return; - if (!silent) { - focusInputEl(); - } - } -}; - -/** - * Resolves a keyboard event to a configured action depending on modifier keys and settings. - * - * @param {KeyboardEvent} e - The keyboard event. - * @returns {object} - { action, scope, requiresNode } or empty object if no match. - */ -const getActionFromEvent = (e) => { - const isMod = e.ctrlKey || e.metaKey; - - const match = RUNTIME_HOTKEYS.find(h => { - const keyMatch = h.code ? (e.code === h.code) : (e.key === h.key); - if (!keyMatch) return false; - - const hasMod = h.modifiers.includes("Mod") || h.modifiers.includes("Ctrl") || h.modifiers.includes("Meta"); - const hasShift = h.modifiers.includes("Shift"); - const hasAlt = h.modifiers.includes("Alt"); - - return (isMod === hasMod) && - (e.shiftKey === hasShift) && - (e.altKey === hasAlt); - }); - - return match ? { - action: match.action, - scope: match.scope ?? SCOPE.none, - requiresNode: match.requiresNode - } : {}; -}; - -/** - * Main keydown handler. - * Dispatches actions (add, edit, navigate, fold, etc.) based on hotkey settings. - * - * @param {KeyboardEvent} e - */ -const handleKeydown = (e) => { - // Fix for IME (Korean, Chinese, Japanese, etc.) composition issues - // Prevents "Enter" from triggering actions when it's just confirming a character selection - if (e.isComposing || e.keyCode === 229) return; - - if (isRecordingHotkey) return; - if (!ea.targetView || !ea.targetView.leaf.isVisible()) return; - - const currentWindow = isUndocked && floatingInputModal ? - ea.targetView?.ownerWindow : - sidepanelWindow; - - if (!currentWindow) return; - - const st = getAppState(); - if (!st || !!st.editingTextElement || !!st.selectedLinearElement?.isEditing || (st.showHyperlinkPopup === "editor")) return; - - if (linkSuggester?.isBlockingKeys()) { - if (e.key === "Escape") { - e.preventDefault(); - e.stopPropagation(); - } - return; - } - - if ( - e.key === "Escape" && !isUndocked && - inputEl.ownerDocument.activeElement !== inputEl - ) { - return; - } - - let { - action, - scope, - requiresNode - } = getActionFromEvent(e); - if (!action && !["Tab", "Enter"].includes(e.key)) return; - - let context = getHotkeyContext(); - - // Local Tab handling for floating modal to keep focus cycling inside - if (!action && isUndocked && floatingInputModal && e.key === "Tab") { - const modalEl = floatingInputModal.modalEl; - if (!modalEl) return; - const activeEl = modalEl.ownerDocument.activeElement; - if (!modalEl.contains(activeEl)) return; - const selector = [ - "input:not([disabled])", - "div:not([style*='not-allowed'])", - ].join(","); - - const focusables = Array.from(modalEl.querySelectorAll(selector)).filter((el) => { - if (el.tabIndex === -1 || el.hidden) return false; - return el.offsetParent !== null || el.getClientRects().length > 0; - }); - - if (focusables.length > 0) { - e.preventDefault(); - e.stopPropagation(); - const active = modalEl.ownerDocument.activeElement; - let idx = focusables.indexOf(active); - if (idx === -1) idx = 0; - idx = e.shiftKey ? - (idx === 0 ? focusables.length - 1 : idx - 1) : - (idx === focusables.length - 1 ? 0 : idx + 1); - focusables[idx].focus(); - } - return; - } - - if ( - e.key === "Enter" && context === SCOPE.excalidraw && - ((isUndocked && floatingInputModal) || !isUndocked) - ) { - const modalEl = isUndocked ? floatingInputModal.modalEl : ea.sidepanelTab.containerEl; - const activeEl = modalEl?.ownerDocument.activeElement; - action = activeEl?.getAttribute("action"); - if (!action) return; - context = SCOPE.input; - } - - if (!action || context < scope) return; - - // Verify active node requirement - if (requiresNode && !getMindmapNodeFromSelection()) { - return; - } - - // Verify transaction state for Undo - if (action === ACTION_UNDO && lastCommittedTransaction === null) { - return; - } - - // Verify transaction state for Redo - if ((action === ACTION_REDO_Z || action === ACTION_REDO_Y) && redoAvailable === null) { - return; - } - - e.preventDefault(); - e.stopPropagation(); - - performAction(action, e); -} - -const addSibling = async (event, insertAfter = true) => { - if (!inputEl.value) return; - const dir = insertAfter ? 1 : -1; - const allElementsForSibling = ea.getViewElements(); - const selectedForSibling = getMindmapNodeFromSelection(); - - if (!selectedForSibling) { - await addNode(inputEl.value, true, false, null, null, null, ontologyEl.value); - } else { - const info = getHierarchy(selectedForSibling, allElementsForSibling); - const root = allElementsForSibling.find(el => el.id === info.rootId); - const parentOfSelected = getParentNode(selectedForSibling.id, allElementsForSibling); - const rootMode = root.customData?.growthMode || currentModalGrowthMode; - const isVertical = ["Up-facing", "Down-facing", "Up-Down"].includes(rootMode); - - // If parent exists, add to that parent (Sibling). - // If no parent (Root was selected), add to selected (Child). - const targetParent = parentOfSelected ?? selectedForSibling; - - // Default position: slightly lower to ensure correct Y-sort order in directional maps - let pos = { - x: selectedForSibling.x + (isVertical && insertAfter ? selectedForSibling.width : 0) + (isVertical ? dir : 0), - y: selectedForSibling.y + (!isVertical && insertAfter ? selectedForSibling.height : 0) + (!isVertical ? dir : 0), - }; - - // Specific logic for Radial L1 nodes: - // Position must be calculated via angle offset because triggerGlobalLayout sorts - // L1 nodes in Radial maps clockwise by angle, not by Y-coordinate. - if (parentOfSelected && parentOfSelected.id === root.id && root.customData?.growthMode === "Radial") { - const rb = getNodeBox(root, allElementsForSibling); - const rc = { - x: rb.minX + rb.width / 2, - y: rb.minY + rb.height / 2 - }; - const sc = { - x: selectedForSibling.x + selectedForSibling.width / 2, - y: selectedForSibling.y + selectedForSibling.height / 2 - }; - - // Calculate the current angle and distance, then increment angle slightly (~5.7 degrees) - const angle = Math.atan2(sc.y - rc.y, sc.x - rc.x) + dir * 0.2; - const dist = Math.hypot(sc.x - rc.x, sc.y - rc.y); - - pos = { - x: rc.x + Math.cos(angle) * dist - selectedForSibling.width / 2, - y: rc.y + Math.sin(angle) * dist - selectedForSibling.height / 2 - }; - } - - selectNodeInView(targetParent); - await addNode(inputEl.value, false, false, null, null, pos, ontologyEl.value); - } - inputEl.value = ""; - ontologyEl.value = ""; - updateUI(); - await performAction(ACTION_ADD, event); // Move selection to new node -} - -// Helper for retrieving Tasks plugin configuration and formats -const getTasksUiOptions = () => { - const tasksPlugin = app.plugins.getPlugin('obsidian-tasks-plugin'); - const mode = tasksPlugin?.configuration?.taskFormat || 'emoji'; - let dateFields = []; - if (mode === 'dataview') { - dateFields = [ - "📅 [due:: ]", - "🛫 [start:: ]", - "⏳ [scheduled:: ]", - "➕ [created:: ]", - "✅ [done:: ]", - "❌ [cancelled:: ]" - ]; - } else { - dateFields = [ - "📅 Due", - "🛫 Start", - "⏳ Scheduled", - "➕ Created", - "✅ Done", - "❌ Cancelled" - ]; - } - const priorities = [ - "🔺 Highest", - "⏫ High", - "🔼 Medium", - " Normal", - "🔽 Low", - "⏬ Lowest" - ]; - return { - mode, - dateFields, - priorities - }; -}; - -// Parses an existing task string into dates, priority, and recurrence -const parseTasksData = (text, mode) => { - const priorityMap = { - '🔺': 'highest', - '⏫': 'high', - '🔼': 'medium', - '🔽': 'low', - '⏬': 'lowest' - }; - let priority = 'normal'; - for (const [emoji, val] of Object.entries(priorityMap)) { - if (text.includes(emoji)) { - priority = val; - break; - } - } - - let recurrence = ""; - let dates = []; - - if (mode === 'dataview') { - const recMatch = text.match(/\[recurrence:: ([^\]]+)\]/i); - if (recMatch) recurrence = recMatch[1]; - - const dateFields = ['due', 'start', 'scheduled', 'created', 'done', 'cancelled']; - for (const field of dateFields) { - const regex = new RegExp(`\\[${field}:: (\\d{4}-\\d{2}-\\d{2})\\]`, 'gi'); - let match; - while ((match = regex.exec(text)) !== null) { - dates.push({ - type: field, - date: match[1] - }); - } - } - } else { - const recMatch = text.match(/🔁\s*([a-zA-Z0-9 ,]+)/i); - if (recMatch) recurrence = recMatch[1].trim(); - - const emojiFields = { - '📅': 'due', - '🛫': 'start', - '⏳': 'scheduled', - '➕': 'created', - '✅': 'done', - '❌': 'cancelled' - }; - for (const [emoji, field] of Object.entries(emojiFields)) { - const regex = new RegExp(`${emoji}\\s*(\\d{4}-\\d{2}-\\d{2})`, 'g'); - let match; - while ((match = regex.exec(text)) !== null) { - dates.push({ - type: field, - date: match[1] - }); - } - } - } - - return { - priority, - recurrence, - dates - }; -}; - -// Helper to remove any existing Tasks/Dataview fields and priority/date emojis -const cleanTasksString = (text) => { - let cleaned = text; - // Strip Dataview-styled bracket dates/fields - cleaned = cleaned.replace(/\[(due|start|scheduled|created|done|cancelled|recurrence)::\s*[^\]]+\]/gi, ""); - // Strip Emoji-styled dates - cleaned = cleaned.replace(/[📅🛫⏳➕✅❌]\s*\d{4}-\d{2}-\d{2}/g, ""); - // Strip Recurrence emoji and standard text rules (stops at next emoji or bracket) - cleaned = cleaned.replace(/🔁\s*[a-zA-Z0-9 ,]+/g, ""); - // Strip Priorities - cleaned = cleaned.replace(/[🔺⏫🔼🔽⏬]/g, ""); - // Normalize spacing - cleaned = cleaned.replace(/ +/g, " ").trim(); - return cleaned; -}; - -// Open standard Obsidian modal configuration interface for calendar mapping -const openCalendarModal = async () => { - let targetText = ""; - let isInputEl = false; - let textElId = null; - let sel = null; - - // Mode 1: Edit from Input Box - if (inputEl && inputEl.value.trim() !== "") { - targetText = inputEl.value; - isInputEl = true; - } else { - // Mode 2: Edit from selected Node - sel = getMindmapNodeFromSelection(); - if (!sel) return; - const all = ea.getViewElements(); - const info = getHierarchy(sel, all); - - if (info.rootId === sel.id) return; // General rule: no effect on root node - - textElId = sel.type === "text" ? sel.id : null; - if (!textElId && sel.boundElements) { - const boundText = sel.boundElements.find(be => be.type === "text"); - if (boundText) textElId = boundText.id; - } - if (!textElId) return; - - const textEl = all.find(el => el.id === textElId); - if (!textEl) return; - targetText = textEl.rawText; - } - - const uiOpts = getTasksUiOptions(); - const parsed = parseTasksData(targetText, uiOpts.mode); - - let dates = parsed.dates.length > 0 ? parsed.dates : [{ - type: 'due', - date: window.moment().format('YYYY-MM-DD') - }]; - let activeDateIndex = 0; - let priority = parsed.priority; - let recurrence = parsed.recurrence; - - const modal = new ea.obsidian.Modal(app); - modal.titleEl.setText(t("ACTION_LABEL_CALENDAR")); - - let dateInputComp, typeDropdownComp; - - const renderContent = () => { - const { - contentEl - } = modal; - contentEl.empty(); - - // Navigation Row for multi-date handling - const navRow = contentEl.createDiv({ - attr: { - style: "display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;" - } - }); - - const leftNav = navRow.createDiv({ - attr: { - style: "display: flex; align-items: center; gap: 10px;" - } - }); - - const prevBtn = leftNav.createEl("button"); - prevBtn.innerHTML = ea.obsidian.getIcon("chevron-left").outerHTML; - prevBtn.disabled = activeDateIndex === 0; - prevBtn.onclick = () => { - activeDateIndex--; - renderContent(); - }; - - leftNav.createSpan({ - text: t("CALENDAR_DATE_INDEX", { index: activeDateIndex + 1, total: dates.length }) - }); - - const nextBtn = leftNav.createEl("button"); - nextBtn.innerHTML = ea.obsidian.getIcon("chevron-right").outerHTML; - nextBtn.onclick = () => { - if (activeDateIndex === dates.length - 1) { - dates.push({ - type: 'due', - date: window.moment().format('YYYY-MM-DD') - }); - } - activeDateIndex++; - renderContent(); - }; - - const delBtn = navRow.createEl("button"); - delBtn.innerHTML = ea.obsidian.getIcon("trash-2").outerHTML; - delBtn.disabled = dates.length === 1 && !dates[0].date; // Can't delete if it's just the empty default - delBtn.onclick = () => { - dates.splice(activeDateIndex, 1); - if (dates.length === 0) { - dates.push({ - type: 'due', - date: window.moment().format('YYYY-MM-DD') - }); - } - if (activeDateIndex >= dates.length) activeDateIndex = dates.length - 1; - renderContent(); - }; - - // Active Date Object - const activeDateObj = dates[activeDateIndex]; - - // 1) Date picker input (Focus First) - new ea.obsidian.Setting(contentEl) - .setName(t("CALENDAR_DATE_LABEL")) - .addText(text => { - dateInputComp = text; - text.inputEl.type = "date"; - text.setValue(activeDateObj.date); - text.onChange(val => { - activeDateObj.date = val; - }); - - text.inputEl.addEventListener("keydown", (e) => { - if (e.key === "Enter") { - e.preventDefault(); - if (typeDropdownComp && typeDropdownComp.selectEl) { - typeDropdownComp.selectEl.focus(); - } - } - }); - - text.inputEl.addEventListener("change", (e) => { - if (document.activeElement === text.inputEl && typeDropdownComp && typeDropdownComp.selectEl) { - typeDropdownComp.selectEl.focus(); - } - }); - }); - - // 2) Field type configuration selector matching active schema ontology - new ea.obsidian.Setting(contentEl) - .setName(t("CALENDAR_DATE_TYPE")) - .addDropdown(dropdown => { - typeDropdownComp = dropdown; - if (uiOpts.mode === 'dataview') { - dropdown.addOption("due", "📅 [due:: ]"); - dropdown.addOption("start", "🛫 [start:: ]"); - dropdown.addOption("scheduled", "⏳ [scheduled:: ]"); - dropdown.addOption("created", "➕ [created:: ]"); - dropdown.addOption("done", "✅ [done:: ]"); - dropdown.addOption("cancelled", "❌ [cancelled:: ]"); - } else { - dropdown.addOption("due", `📅 ${t("CALENDAR_DATETYPE_DUE")}`); - dropdown.addOption("start", `🛫 ${t("CALENDAR_DATETYPE_START")}`); - dropdown.addOption("scheduled", `⏳ ${t("CALENDAR_DATETYPE_SCHEDULED")}`); - dropdown.addOption("created", `➕ ${t("CALENDAR_DATETYPE_CREATED")}`); - dropdown.addOption("done", `✅ ${t("CALENDAR_DATETYPE_DONE")}`); - dropdown.addOption("cancelled", `❌ ${t("CALENDAR_DATETYPE_CANCELLED")}`); - } - dropdown.setValue(activeDateObj.type); - dropdown.onChange(val => { - activeDateObj.type = val; - }); - }); - - // 3) Priority selector mapped to native Tasks emojis - new ea.obsidian.Setting(contentEl) - .setName(t("CALENDAR_PRIORITY")) - .addDropdown(dropdown => { - dropdown.addOption("highest", `🔺 ${t("CALENDAR_PRIORITY_HIGHEST")}`); - dropdown.addOption("high", `⏫ ${t("CALENDAR_PRIORITY_HIGH")}`); - dropdown.addOption("medium", `🔼 ${t("CALENDAR_PRIORITY_MEDIUM")}`); - dropdown.addOption("normal", ` ${t("CALENDAR_PRIORITY_NORMAL")}`); - dropdown.addOption("low", `🔽 ${t("CALENDAR_PRIORITY_LOW")}`); - dropdown.addOption("lowest", `⏬ ${t("CALENDAR_PRIORITY_LOWEST")}`); - dropdown.setValue(priority); - dropdown.onChange(val => { - priority = val; - }); - }); - - // 4) Recurrence free text input - const recSetting = new ea.obsidian.Setting(contentEl) - .setName(t("CALENDAR_RECURRENCE")) - .addText(text => { - text.setPlaceholder(t("CALENDAR_RECURRENCE_PLACEHOLDER")) - .setValue(recurrence) - .onChange(val => { - recurrence = val; - }); - }); - recSetting.descEl.innerHTML = t("CALENDAR_RECURRENCE_DESC"); - - // 5) Inject Node Link toggle - const linkSettingsRow = new ea.obsidian.Setting(contentEl) - .setName(t("CALENDAR_INJECT_LINK")) - .setDesc(t("CALENDAR_INJECT_LINK_DESC")); - - let aliasTextComp; - linkSettingsRow.addToggle(toggle => { - toggle.setValue(injectNodeLink) - .onChange(val => { - injectNodeLink = val; - setVal(K_INJECT_LINK, val); - aliasTextComp.inputEl.style.display = val ? "" : "none"; - }); - }); - linkSettingsRow.addText(text => { - aliasTextComp = text; - text.setPlaceholder(t("CALENDAR_ALIAS_PLACEHOLDER")) - .setValue(nodeLinkAlias) - .onChange(val => { - nodeLinkAlias = val || "link"; - setVal(K_LINK_ALIAS, nodeLinkAlias); - }); - text.inputEl.style.display = injectNodeLink ? "" : "none"; - text.inputEl.style.width = "100px"; - text.inputEl.style.marginLeft = "10px"; - }); - - // Controls button block - const btnContainer = contentEl.createDiv({ - attr: { - style: "display: flex; gap: 10px; justify-content: flex-end; margin-top: 15px;" - } - }); - - const cancelBtn = btnContainer.createEl("button", { - text: t("CALENDAR_BTN_CANCEL") - }); - cancelBtn.onclick = () => modal.close(); - - const taskOnlyBtn = btnContainer.createEl("button", { - text: t("CALENDAR_BTN_TASK_ONLY") - }); - taskOnlyBtn.onclick = () => handleSave(false); - - const saveBtn = btnContainer.createEl("button", { - text: t("CALENDAR_BTN_ADD_DATE_TASK"), - cls: "mod-cta" - }); - saveBtn.onclick = () => handleSave(true); - - // Date picker auto-open / focus - setTimeout(() => { - if (dateInputComp && dateInputComp.inputEl) { - dateInputComp.inputEl.focus(); - if (typeof dateInputComp.inputEl.showPicker === 'function') { - try { - dateInputComp.inputEl.showPicker(); - } catch (e) {} - } - } - }, 50); - }; - - const handleSave = async (includeDate = true) => { - modal.close(); - - let tasksString = ""; - - if (includeDate) { - const validDates = dates.filter(d => d.date); - if (uiOpts.mode === 'dataview') { - let priorityStr = ""; - const priorityMap = { - 'highest': '🔺', - 'high': '⏫', - 'medium': '🔼', - 'normal': '', - 'low': '🔽', - 'lowest': '⏬' - }; - if (priority !== 'normal') priorityStr = priorityMap[priority]; - - let dateStrs = validDates.map(d => `[${d.type}:: ${d.date}]`); - let recStr = recurrence ? `[recurrence:: ${recurrence}]` : ""; - - const parts = [priorityStr, ...dateStrs, recStr].filter(Boolean); - if (parts.length > 0) tasksString = " " + parts.join(" "); - } else { - let priorityStr = ""; - const priorityMap = { - 'highest': ' 🔺', - 'high': ' ⏫', - 'medium': ' 🔼', - 'normal': '', - 'low': ' 🔽', - 'lowest': ' ⏬' - }; - priorityStr = priorityMap[priority] || ""; - - const emojiMap = { - 'due': '📅', - 'start': '🛫', - 'scheduled': '⏳', - 'created': '➕', - 'done': '✅', - 'cancelled': '❌' - }; - let dateStrs = validDates.map(d => ` ${emojiMap[d.type]} ${d.date}`); - let recStr = recurrence ? ` 🔁 ${recurrence}` : ""; - - tasksString = `${priorityStr}${dateStrs.join("")}${recStr}`; - } - } - - const taskRegex = /^- \[([ xX])\] (.*)/s; - const match = targetText.match(taskRegex); - - let cleanText = cleanTasksString(match ? match[2] : targetText); - - // Ensure we don't duplicate an existing auto-generated link at the end - const linkRegex = /\s*\(\[\[[^\]]+#\^group=[a-zA-Z0-9_-]+\|[^\]]+\]\]\)$/; - if (linkRegex.test(cleanText)) { - cleanText = cleanText.replace(linkRegex, ""); - } - - let finalPrefix = match ? `- [${match[1]}] ` : "- [ ] "; - let newText = `${finalPrefix}${cleanText}`; - - if (injectNodeLink) { - if (isInputEl) { - newText += ` __NODE_LINK_PLACEHOLDER__`; - } else { - const file = app.workspace.getActiveFile(); - const fileName = file ? file.basename : ""; - newText += ` ([[${fileName}#^group=${textElId}|${nodeLinkAlias}]])`; - } - } - newText += tasksString; - - if (isInputEl) { - inputEl.value = newText; - updateUI(); - } else { - const all = ea.getViewElements(); - const textEl = all.find(el => el.id === textElId); - ea.copyViewElementsToEAforEditing([textEl]); - const eaEl = ea.getElement(textEl.id); - eaEl.rawText = newText; - eaEl.text = newText; - eaEl.originalText = newText; - ea.refreshTextElementSize(eaEl.id); - - await addElementsToView({ - captureUpdate: autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" - }); - - if (eaEl.containerId) { - const updatedContainer = ea.getViewElements().find(el => el.id === eaEl.containerId); - if (updatedContainer) api().updateContainerSize([updatedContainer]); - } - - if (!autoLayoutDisabled) { - const info = getHierarchy(sel, ea.getViewElements()); - await triggerGlobalLayout(info.rootId); - } - updateUI(); - } - }; - - modal.onOpen = () => { - renderContent(); - - // Add Ctrl+Enter / Meta+Enter listener - modal.modalEl.addEventListener("keydown", (e) => { - if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { - e.preventDefault(); - e.stopPropagation(); - handleSave(true); - } - // Prevent Escape from propagating to the underlying floating modal or canvas - if (e.key === "Escape") { - e.preventDefault(); - e.stopPropagation(); - modal.close(); - } - }); - }; - - modal.open(); -}; - -const performAction = async (action, event) => { - if (!action || !ea.targetView) return; - switch (action) { - case ACTION_CALENDAR: - await openCalendarModal(); - break; - case ACTION_TOGGLE_FLOATING_EXTRAS: - toggleFloatingExtras?.(); - break; - case ACTION_REARRANGE: - await refreshMapLayout(); - break; - case ACTION_TOGGLE_GROUP: - await toggleBranchGroup(); - break; - case ACTION_HIDE: - if (editingNodeId) { - editingNodeId = null; - updateUI(); - } else if (isUndocked) { - toggleDock({ - silent: true, - forceDock: true, - saveSetting: false - }); - } - break; - - case ACTION_PIN: - await togglePin(); - break; - - case ACTION_TOGGLE_CHECKBOX: - await toggleCheckboxStatus(); - updateUI(); - break; - - case ACTION_TOGGLE_EMBED: - await toggleEmbedStatus(); - updateUI(); - break; - - case ACTION_TOGGLE_SUBMAP_ROOT: - await toggleSubmapRoot(); - break; - - case ACTION_BOX: - await toggleBox(); - break; - - case ACTION_TOGGLE_BOUNDARY: - await toggleBoundary(); - break; - - case ACTION_FOLD: - await toggleFold("L0"); - updateUI(); - break; - - case ACTION_FOLD_L1: - await toggleFold("L1"); - updateUI(); - break; - - case ACTION_FOLD_ALL: - await toggleFold("ALL"); - updateUI(); - break; - - case ACTION_COPY: - copyMapAsText(false); - break; - - case ACTION_CUT: - copyMapAsText(true); - updateUI(); - break; - - case ACTION_PASTE: - await pasteElementToMap(); - updateUI(); - break; - - case ACTION_IMPORT_OUTLINE: - await importOutline(); - updateUI(); - break; - - case ACTION_ZOOM: - zoomToFit(true); - break; - - case ACTION_FOCUS: - focusSelected(); - break; - - case ACTION_SORT_ORDER: - changeNodeOrder(event?.key); - updateUI(); - break; - - case ACTION_NAVIGATE: - await navigateMap({ - key: event?.key, - zoom: false, - focus: false - }); - updateUI(); - break; - - case ACTION_NAVIGATE_ZOOM: - await navigateMap({ - key: event?.key, - zoom: true, - focus: false - }); - updateUI(); - break; - - case ACTION_NAVIGATE_FOCUS: - await navigateMap({ - key: event?.key, - zoom: false, - focus: true - }); - updateUI(); - break; - - case ACTION_DOCK_UNDOCK: - toggleDock({ - saveSetting: true - }); - break; - - case ACTION_EDIT: - startEditing(); - break; - - case ACTION_ADD_SIBLING_AFTER: - addSibling(event, true); - break; - - case ACTION_ADD_SIBLING_BEFORE: - addSibling(event, false); - break; - - case ACTION_ADD_FOLLOW: - case ACTION_ADD_FOLLOW_FOCUS: - case ACTION_ADD_FOLLOW_ZOOM: - if (!inputEl.value) return; - await addNode(inputEl.value, true, false, null, null, null, ontologyEl.value); - inputEl.value = ""; - ontologyEl.value = ""; - updateUI(); - if (action === ACTION_ADD_FOLLOW_FOCUS) focusSelected(); - if (action === ACTION_ADD_FOLLOW_ZOOM) zoomToFit(); - break; - case ACTION_ADD: - const currentSel = getMindmapNodeFromSelection() ?? ea.getViewSelectedElement(); - if ( - editingNodeId && currentSel && - (currentSel.id === editingNodeId || currentSel.containerId === editingNodeId) - ) { - await commitEdit(); - } else { - if (editingNodeId) { - editingNodeId = null; - } - if (inputEl.value) { - await addNode(inputEl.value, false, false, null, null, null, ontologyEl.value); - inputEl.value = ""; - ontologyEl.value = ""; - } else { - const sel = getMindmapNodeFromSelection(); - const allElements = ea.getViewElements(); - - let handledRecent = false; - if (mostRecentlyAddedNodeID) { - const mostRecentNode = getMostRecentlyAddedNode(); - if (mostRecentNode && sel) { - const selParent = getParentNode(sel.id, allElements); - const recentParent = getParentNode(mostRecentNode.id, allElements); - const isSameOrSibling = (sel.id === mostRecentNode.id) || - (selParent && recentParent && selParent.id === recentParent.id); - if (!isSameOrSibling) { - selectNodeInView(mostRecentNode); - handledRecent = true; - } - } else { - mostRecentlyAddedNodeID = null; - } - } - if (!handledRecent && sel) { - const parent = getParentNode(sel.id, allElements); - const siblings = parent ? getChildrenNodes(parent.id, allElements) : []; - - if (siblings.length > 1) { - siblings.sort((a, b) => getMindmapOrder(a) - getMindmapOrder(b)); - const idx = siblings.findIndex(s => s.id === sel.id); - const nextIdx = (idx + 1) % siblings.length; - selectNodeInView(siblings[nextIdx]); - } else { - const children = getChildrenNodes(sel.id, allElements); - if (children.length > 0) { - children.sort((a, b) => getMindmapOrder(a) - getMindmapOrder(b)); - selectNodeInView(children[0]); - } else if (parent) { - selectNodeInView(parent); - } - } - } - } - } - updateUI(); - break; - - case ACTION_UNDO: - if (ea.targetView) { - const currentVer = ExcalidrawLib.getSceneVersion(api().getSceneElements()); - if (lastCommittedTransaction && currentVer === lastCommittedTransaction.version && lastCommittedTransaction.steps > 0) { - for (let i = 0; i <= lastCommittedTransaction.steps; i++) { - api().history.undo(); - } - const afterUndoVer = ExcalidrawLib.getSceneVersion(api().getSceneElements()); - redoAvailable = { - steps: lastCommittedTransaction.steps, - version: afterUndoVer - }; - lastCommittedTransaction = null; - } else { - api().history.undo(); - lastCommittedTransaction = null; - redoAvailable = null; - } - } - break; - - case ACTION_REDO_Z: - case ACTION_REDO_Y: - if (ea.targetView) { - const currentVer = ExcalidrawLib.getSceneVersion(api().getSceneElements()); - if (redoAvailable && currentVer === redoAvailable.version && redoAvailable.steps > 0) { - for (let i = 0; i <= redoAvailable.steps; i++) { - api().history.redo(); - } - const afterRedoVer = ExcalidrawLib.getSceneVersion(api().getSceneElements()); - lastCommittedTransaction = { - steps: redoAvailable.steps, - version: afterRedoVer - }; - redoAvailable = null; - } else { - api().history.redo(); - lastCommittedTransaction = null; - redoAvailable = null; - } - } - break; - } -}; - -// --------------------------------------------------------------------------- -// 11. Public Puppeteering API (minimal-impact wrappers) -// --------------------------------------------------------------------------- -(() => { - // Note: ACTION_CALENDAR is deliberately not published in the MindMap Builder API. - // It is a UI-driven feature meant for quick manual input. Programmatic scripts - // can simply author or modify the text element's rawText directly rather than - // invoking the Calendar UI dialog. - const MMError = { - NOT_READY: "NOT_READY", - NO_VIEW: "NO_VIEW", - INVALID_VIEW: "INVALID_VIEW", - INVALID_NODE: "INVALID_NODE", - NO_SELECTION: "NO_SELECTION", - NO_ROOT: "NO_ROOT", - AUTO_LAYOUT_DISABLED: "AUTO_LAYOUT_DISABLED", - INVALID_ACTION: "INVALID_ACTION", - INVALID_ARGUMENT: "INVALID_ARGUMENT", - OPERATION_FAILED: "OPERATION_FAILED", - }; - - const mmOk = (data) => ({ - ok: true, - data - }); - const mmErr = (code, message, details) => ({ - ok: false, - error: details === undefined ? { - code, - message - } : { - code, - message, - details - }, - }); - - const requireView = () => { - if (!isViewSet()) return mmErr(MMError.NO_VIEW, "No active ExcalidrawView"); - return null; - }; - - const findNodeById = (nodeId) => { - const all = ea.getViewElements(); - return all.find((el) => el.id === nodeId); - }; - - const resolveNode = (nodeId) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - - if (nodeId) { - const node = findNodeById(nodeId); - if (!node) return mmErr(MMError.INVALID_NODE, `Node not found: ${nodeId}`); - return mmOk(node); - } - - const sel = getMindmapNodeFromSelection(); - if (!sel) return mmErr(MMError.NO_SELECTION, "No mindmap node selected"); - return mmOk(sel); - }; - - const getNodeOntology = (node, allElements) => { - const incomingArrow = allElements.find( - (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === node.id, - ); - return incomingArrow ? - (ea.getBoundTextElement(incomingArrow, true)?.sceneElement?.rawText || "") : - ""; - }; - - const extractMapConfig = (rootNode) => ({ - growthMode: rootNode.customData?.growthMode || currentModalGrowthMode, - autoLayoutDisabled: rootNode.customData?.autoLayoutDisabled === true, - arrowType: rootNode.customData?.arrowType ?? arrowType, - fontsizeScale: rootNode.customData?.fontsizeScale ?? fontsizeScale, - multicolor: typeof rootNode.customData?.multicolor === "boolean" ? rootNode.customData.multicolor : multicolor, - boxChildren: typeof rootNode.customData?.boxChildren === "boolean" ? rootNode.customData.boxChildren : boxChildren, - roundedCorners: typeof rootNode.customData?.roundedCorners === "boolean" ? rootNode.customData.roundedCorners : roundedCorners, - maxWrapWidth: typeof rootNode.customData?.maxWrapWidth === "number" ? rootNode.customData.maxWrapWidth : maxWidth, - isSolidArrow: typeof rootNode.customData?.isSolidArrow === "boolean" ? rootNode.customData.isSolidArrow : isSolidArrow, - centerText: typeof rootNode.customData?.centerText === "boolean" ? rootNode.customData.centerText : centerText, - fillSweep: typeof rootNode.customData?.fillSweep === "boolean" ? rootNode.customData.fillSweep : fillSweep, - branchScale: rootNode.customData?.branchScale ?? branchScale, - baseStrokeWidth: typeof rootNode.customData?.baseStrokeWidth === "number" ? rootNode.customData.baseStrokeWidth : baseStrokeWidth, - layoutSettings: JSON.parse(JSON.stringify(rootNode.customData?.layoutSettings ?? layoutSettings)), - }); - - const API_ACTIONS = { - ADD: ACTION_ADD, - ADD_SIBLING_AFTER: ACTION_ADD_SIBLING_AFTER, - ADD_SIBLING_BEFORE: ACTION_ADD_SIBLING_BEFORE, - ADD_FOLLOW: ACTION_ADD_FOLLOW, - ADD_FOLLOW_FOCUS: ACTION_ADD_FOLLOW_FOCUS, - ADD_FOLLOW_ZOOM: ACTION_ADD_FOLLOW_ZOOM, - EDIT: ACTION_EDIT, - TOGGLE_CHECKBOX: ACTION_TOGGLE_CHECKBOX, - PIN: ACTION_PIN, - BOX: ACTION_BOX, - TOGGLE_EMBED: ACTION_TOGGLE_EMBED, - TOGGLE_BOUNDARY: ACTION_TOGGLE_BOUNDARY, - TOGGLE_SUBMAP_ROOT: ACTION_TOGGLE_SUBMAP_ROOT, - TOGGLE_GROUP: ACTION_TOGGLE_GROUP, - FOLD: ACTION_FOLD, - FOLD_L1: ACTION_FOLD_L1, - FOLD_ALL: ACTION_FOLD_ALL, - COPY: ACTION_COPY, - CUT: ACTION_CUT, - PASTE: ACTION_PASTE, - ZOOM: ACTION_ZOOM, - FOCUS: ACTION_FOCUS, - NAVIGATE: ACTION_NAVIGATE, - NAVIGATE_ZOOM: ACTION_NAVIGATE_ZOOM, - NAVIGATE_FOCUS: ACTION_NAVIGATE_FOCUS, - SORT_ORDER: ACTION_SORT_ORDER, - REARRANGE: ACTION_REARRANGE, - DOCK_UNDOCK: ACTION_DOCK_UNDOCK, - HIDE: ACTION_HIDE, - UNDO: ACTION_UNDO, - REDO_Z: ACTION_REDO_Z, - REDO_Y: ACTION_REDO_Y, - }; - - const API_ERROR_DOC = { - [MMError.NOT_READY]: "MindMapBuilder runtime is not initialized", - [MMError.NO_VIEW]: "No active ExcalidrawView is set", - [MMError.INVALID_VIEW]: "The provided view is missing or not an ExcalidrawView", - [MMError.INVALID_NODE]: "The provided node id does not exist in the active view", - [MMError.NO_SELECTION]: "No mindmap node is currently selected", - [MMError.NO_ROOT]: "Unable to resolve a root/settings root for the selected node", - [MMError.AUTO_LAYOUT_DISABLED]: "The map has auto-layout disabled", - [MMError.INVALID_ACTION]: "The provided action is unknown", - [MMError.INVALID_ARGUMENT]: "One or more arguments are invalid", - [MMError.OPERATION_FAILED]: "The underlying operation failed at runtime", - }; - - const API_METHOD_SPEC = { - ready: { - summary: "Returns whether the API runtime is initialized", - params: [], - returns: "boolean", - }, - listMethods: { - summary: "Returns the list of public method names", - params: [], - returns: "MMResult<{methods:string[]}>", - }, - getErrorCodes: { - summary: "Returns known error codes and their meaning", - params: [], - returns: "MMResult<{errors:Record}>", - }, - spec: { - summary: "Returns machine-readable API metadata for agents", - params: [], - returns: "MMResult<{version:string,actions:string[],errors:Record,methods:object}>", - }, - help: { - summary: "Returns method docs for one method or the full API", - params: [{ - name: "method", - type: "string", - required: false - }, - { - name: "format", - type: "string", - required: false, - enum: ["object", "text"] - }, - ], - returns: "MMResult", - }, - validate: { - summary: "Validates arguments against the API method contract", - params: [{ - name: "method", - type: "string", - required: true - }, - { - name: "args", - type: "any", - required: false - }, - ], - returns: "MMResult<{valid:boolean,errors:string[],normalizedArgs:object}>", - }, - getCapabilities: { - summary: "Returns available actions and methods", - params: [], - returns: "{actions:string[],methods:string[]}", - }, - setView: { - summary: "Sets the active ExcalidrawView context", - params: [{ - name: "view", - type: "object", - required: true - }], - returns: "MMResult<{view:ExcalidrawView|null,filePath:string|null}>", - }, - getView: { - summary: "Gets the current ExcalidrawView and filepath", - params: [], - returns: "MMResult<{view:ExcalidrawView|null,filePath:string|null}>", - }, - getSelection: { - summary: "Returns selected node id and selected element ids", - params: [], - returns: "MMResult<{nodeId:string|null,elementIds:string[]}>", - }, - selectNode: { - summary: "Selects a node by id or current selected node when omitted", - params: [{ - name: "nodeId", - type: "string", - required: false - }], - returns: "MMResult<{nodeId:string}>", - }, - setInputFieldDockStatus: { - summary: "Forces docked/undocked input mode and applies matching sidepanel visibility", - params: [{ - name: "isDocked", - type: "boolean", - required: true - }], - returns: "Promise>", - }, - getMindMapRoots: { - summary: "Returns top-level mindmap root node ids", - params: [], - returns: "MMResult<{rootIds:string[]}>", - }, - getMapInfo: { - summary: "Returns hierarchy info for a node or current selection", - params: [{ - name: "nodeId", - type: "string", - required: false - }], - returns: "MMResult<{nodeId:string,rootId:string,settingsRootId:string,depth:number}>", - }, - getNodeText: { - summary: "Returns node text and ontology", - params: [{ - name: "nodeId", - type: "string", - required: false - }], - returns: "MMResult<{nodeId:string,text:string,ontology:string}>", - }, - performAction: { - summary: "Runs one built-in mindmap action", - params: [{ - name: "action", - type: "string", - required: true, - enum: Object.values(API_ACTIONS) - }, - { - name: "event", - type: "object", - required: false - }, - ], - returns: "Promise>", - }, - refreshMapLayout: { - summary: "Refreshes map layout from the selected node or provided node id", - params: [{ - name: "nodeId", - type: "string", - required: false - }], - returns: "Promise>", - }, - addNode: { - summary: "Adds a node under selected node or a provided parent", - params: [{ - name: "text", - type: "string", - required: true - }, - { - name: "parentId", - type: "string", - required: false - }, - { - name: "ontology", - type: "string", - required: false - }, - { - name: "follow", - type: "boolean", - required: false - }, - { - name: "position", - type: "string", - required: false - }, - ], - returns: "Promise>", - }, - importMarkdown: { - summary: "Imports markdown bullet hierarchy into map", - params: [{ - name: "markdown", - type: "string", - required: true - }, - { - name: "parentId", - type: "string", - required: false - }, - ], - returns: "Promise>", - }, - exportMarkdown: { - summary: "Exports selected branch to markdown through clipboard", - params: [{ - name: "nodeId", - type: "string", - required: false - }, - { - name: "cut", - type: "boolean", - required: false - }, - ], - returns: "Promise>", - }, - toggleSubmapRoot: { - summary: "Toggles or forces additional-root state on node", - params: [{ - name: "nodeId", - type: "string", - required: false - }, - { - name: "enabled", - type: "boolean", - required: false - }, - ], - returns: "Promise>", - }, - getMapConfig: { - summary: "Returns effective map config for node/root", - params: [{ - name: "nodeId", - type: "string", - required: false - }], - returns: "MMResult<{rootId:string,settingsRootId:string,config:object}>", - }, - setMapConfig: { - summary: "Patches map config and optionally relayouts", - params: [{ - name: "patch", - type: "object", - required: true - }, - { - name: "nodeId", - type: "string", - required: false - }, - { - name: "relayout", - type: "boolean", - required: false - }, - ], - returns: "Promise>", - }, - getBranchElementIds: { - summary: "Returns branch element ids with optional decorations/crosslinks", - params: [{ - name: "nodeId", - type: "string", - required: true - }, - { - name: "includeDecorations", - type: "boolean", - required: false - }, - { - name: "includeCrosslinks", - type: "boolean", - required: false - }, - ], - returns: "MMResult<{ids:string[]}>", - }, - getProjectElementIds: { - summary: "Returns all project element ids for a root", - params: [{ - name: "rootId", - type: "string", - required: true - }], - returns: "MMResult<{ids:string[]}>", - }, - getElementIdsByRole: { - summary: "Returns role-based element id groups for a root", - params: [{ - name: "rootId", - type: "string", - required: true - }], - returns: "MMResult<{nodes:string[],branchArrows:string[],crossLinks:string[],boundaries:string[],decorations:string[],boundTexts:string[]}>", - }, - getGlobalConfig: { - summary: "Returns the global map and layout configurations, including custom color palette", - params: [], - returns: "MMResult<{config:object}>", - }, - setGlobalConfig: { - summary: "Updates the global map and layout configurations and persists them", - params: [{ - name: "patch", - type: "object", - required: true - }], - returns: "Promise>", - }, - getConfigSchema: { - summary: "Returns the schema, allowed values, and definitions for map configurations", - params: [], - returns: "MMResult<{schema:object}>", - }, - }; - - const cloneJSON = (value) => JSON.parse(JSON.stringify(value)); - - const normalizeValidationArgs = (method, args) => { - const spec = API_METHOD_SPEC[method]; - if (!spec) return null; - if (args === undefined || args === null) return {}; - if (Array.isArray(args)) { - const out = {}; - spec.params.forEach((p, idx) => { - if (idx < args.length) out[p.name] = args[idx]; - }); - return out; - } - if (typeof args === "object") return { - ...args - }; - if (spec.params.length === 1) return { - [spec.params[0].name]: args - }; - return null; - }; - - const isTypeMatch = (value, type) => { - if (type === "any") return true; - if (type === "array") return Array.isArray(value); - if (type === "object") return value !== null && typeof value === "object" && !Array.isArray(value); - return typeof value === type; - }; - - const validateMethodArgs = (method, args) => { - const spec = API_METHOD_SPEC[method]; - if (!spec) { - return { - valid: false, - errors: [`Unknown method: ${method}`], - normalizedArgs: {} - }; - } - - const normalizedArgs = normalizeValidationArgs(method, args); - if (normalizedArgs === null) { - return { - valid: false, - errors: ["Arguments must be an object, an array of positional values, or a single value for single-parameter methods"], - normalizedArgs: {}, - }; - } - - const errors = []; - spec.params.forEach((p) => { - const v = normalizedArgs[p.name]; - if (p.required && (v === undefined || v === null || (p.type === "string" && v === ""))) { - errors.push(`Missing required parameter: ${p.name}`); - return; - } - if (v !== undefined && v !== null && !isTypeMatch(v, p.type)) { - errors.push(`Invalid type for ${p.name}: expected ${p.type}, got ${Array.isArray(v) ? "array" : typeof v}`); - } - if (p.enum && v !== undefined && v !== null && !p.enum.includes(v)) { - errors.push(`Invalid value for ${p.name}: ${v}`); - } - }); - - return { - valid: errors.length === 0, - errors, - normalizedArgs - }; - }; - - const buildHelpText = (methodName, doc) => { - const params = doc.params.map((p) => { - const req = p.required ? "required" : "optional"; - const enumValues = p.enum ? ` | enum: ${p.enum.join(", ")}` : ""; - return `- ${p.name}: ${p.type} (${req})${enumValues}`; - }); - const paramsText = params.length ? params.join("\n") : "- (none)"; - return [ - `${methodName}`, - `${doc.summary}`, - "Parameters:", - paramsText, - `Returns: ${doc.returns}`, - ].join("\n"); - }; - - const API = { - version: "1.0.0", - Actions: Object.freeze(API_ACTIONS), - Errors: Object.freeze(MMError), - - ready: () => !!ea, - - listMethods: () => mmOk({ - methods: Object.keys(API_METHOD_SPEC) - }), - - getErrorCodes: () => mmOk({ - errors: cloneJSON(API_ERROR_DOC) - }), - - spec: () => - mmOk({ - version: API.version, - actions: Object.values(API_ACTIONS), - errors: cloneJSON(API_ERROR_DOC), - methods: cloneJSON(API_METHOD_SPEC), - }), - - help: (method, format = "object") => { - if (method !== undefined && (typeof method !== "string" || method.trim() === "")) { - return mmErr(MMError.INVALID_ARGUMENT, "help expects method to be a non-empty string when provided"); - } - if (!["object", "text"].includes(format)) { - return mmErr(MMError.INVALID_ARGUMENT, "help format must be 'object' or 'text'"); - } - - if (!method) { - if (format === "text") { - const lines = Object.keys(API_METHOD_SPEC).map((name) => `${name}: ${API_METHOD_SPEC[name].summary}`); - return mmOk([`MindMapBuilder API v${API.version}`, ...lines].join("\n")); - } - return mmOk({ - version: API.version, - methods: cloneJSON(API_METHOD_SPEC), - actions: Object.values(API_ACTIONS), - errors: cloneJSON(API_ERROR_DOC), - }); - } - - const doc = API_METHOD_SPEC[method]; - if (!doc) { - return mmErr(MMError.INVALID_ARGUMENT, `Unknown method: ${method}`); - } - - if (format === "text") return mmOk(buildHelpText(method, doc)); - return mmOk({ - method, - ...cloneJSON(doc) - }); - }, - - validate: (method, args) => { - if (typeof method !== "string" || method.trim() === "") { - return mmErr(MMError.INVALID_ARGUMENT, "validate requires a method name"); - } - const result = validateMethodArgs(method, args); - return mmOk(result); - }, - - getCapabilities: () => ({ - actions: Object.values(API_ACTIONS), - methods: Object.keys(API), - }), - - setView: (view) => { - if (!view) return mmErr(MMError.INVALID_VIEW, "setView expects an ExcalidrawView object"); - - const isValid = !!ea?.isExcalidrawView(view); - - if (!isValid) return mmErr(MMError.INVALID_VIEW, "setView expects an ExcalidrawView object"); - - try { - ea.setView(view); - ea.clear(); - ensureNodeSelected(); - updateUI(); - return mmOk({ - view: ea.targetView, - filePath: ea.targetView?.file?.path || null - }); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "Failed to set view", e); - } - }, - - getView: () => mmOk({ - view: ea.targetView || null, - filePath: ea.targetView?.file?.path || null - }), - - getSelection: () => { - const viewErr = requireView(); - if (viewErr) return viewErr; - return mmOk({ - nodeId: getMindmapNodeFromSelection()?.id || null, - elementIds: ea.getViewSelectedElements().map((e) => e.id), - }); - }, - - selectNode: (nodeId) => { - const nodeRes = resolveNode(nodeId); - if (!nodeRes.ok) return nodeRes; - selectNodeInView(nodeRes.data); - performAction(ACTION_FOCUS); - updateUI(nodeRes.data); - return mmOk({ - nodeId: nodeRes.data.id - }); - }, - - setInputFieldDockStatus: async ({ - isDocked - } = {}) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - if (typeof isDocked !== "boolean") { - return mmErr(MMError.INVALID_ARGUMENT, "setInputFieldDockStatus requires a boolean isDocked"); - } - - try { - const sidepanelLeaf = ea.getSidepanelLeaf?.(); - const isSidepanelVisible = !!sidepanelLeaf?.isVisible?.(); - - if (isDocked) { - if (isUndocked) { - await performAction(ACTION_DOCK_UNDOCK); - } else if (!isSidepanelVisible && sidepanelLeaf) { - app.workspace.revealLeaf(sidepanelLeaf); - } - } else { - if (!isUndocked) { - await performAction(ACTION_DOCK_UNDOCK); - } else if (isSidepanelVisible) { - ea.toggleSidepanelView(); - } - } - - const finalSidepanelLeaf = ea.getSidepanelLeaf?.(); - const sidepanelVisible = !!finalSidepanelLeaf?.isVisible?.(); - return mmOk({ - isDocked: !isUndocked, - isUndocked, - sidepanelVisible - }); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "setInputFieldDockStatus failed", e); - } - }, - - getMindMapRoots: () => { - const viewErr = requireView(); - if (viewErr) return viewErr; - return mmOk({ - rootIds: getMasterRoots() - }); - }, - - getMapInfo: (nodeId) => { - const nodeRes = resolveNode(nodeId); - if (!nodeRes.ok) return nodeRes; - const node = nodeRes.data; - const all = ea.getViewElements(); - const info = getHierarchy(node, all); - const settingsRoot = getSettingsRootNode(node, all); - return mmOk({ - nodeId: node.id, - rootId: info.rootId, - settingsRootId: settingsRoot?.id || info.rootId, - depth: info.depth, - }); - }, - - getNodeText: (nodeId) => { - const nodeRes = resolveNode(nodeId); - if (!nodeRes.ok) return nodeRes; - const node = nodeRes.data; - const all = ea.getViewElements(); - return mmOk({ - nodeId: node.id, - text: getTextFromNode(all, node, true, true), - ontology: getNodeOntology(node, all), - }); - }, - - performAction: async (action, event = {}) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - if (!action || !Object.values(API_ACTIONS).includes(action)) { - return mmErr(MMError.INVALID_ACTION, `Unknown action: ${action}`); - } - try { - await performAction(action, event); - return mmOk(undefined); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "performAction failed", e); - } - }, - - refreshMapLayout: async (nodeId) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - - let sel = null; - if (nodeId) { - const node = findNodeById(nodeId); - if (!node) return mmErr(MMError.INVALID_NODE, `Node not found: ${nodeId}`); - sel = node; - } - - try { - await refreshMapLayout(sel); - const target = sel || getMindmapNodeFromSelection(); - if (!target) return mmErr(MMError.NO_SELECTION, "No selected node for layout refresh"); - const info = getHierarchy(target, ea.getViewElements()); - return mmOk({ - rootId: info.rootId - }); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "refreshMapLayout failed", e); - } - }, - - addNode: async ({ - text, - parentId, - ontology, - follow = false, - position - } = {}) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - if (!text || typeof text !== "string") { - return mmErr(MMError.INVALID_ARGUMENT, "addNode requires non-empty text"); - } - - if (parentId) { - const parent = findNodeById(parentId); - if (!parent) return mmErr(MMError.INVALID_NODE, `Parent node not found: ${parentId}`); - selectNodeInView(parent); - } - - try { - const node = await addNode(text, follow, false, null, null, position || null, ontology ?? null); - if (!node) return mmErr(MMError.OPERATION_FAILED, "Failed to create node"); - - const all = ea.getViewElements(); - const info = getHierarchy(node, all); - const arrow = all.find( - (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === node.id, - ); - return mmOk({ - nodeId: node.id, - arrowId: arrow?.id, - rootId: info.rootId - }); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "addNode failed", e); - } - }, - - importMarkdown: async ({ - markdown, - parentId - } = {}) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - if (typeof markdown !== "string" || markdown.trim() === "") { - return mmErr(MMError.INVALID_ARGUMENT, "importMarkdown requires a non-empty markdown string"); - } - - if (parentId) { - const parent = findNodeById(parentId); - if (!parent) return mmErr(MMError.INVALID_NODE, `Parent node not found: ${parentId}`); - selectNodeInView(parent); - } - - const beforeIds = new Set(ea.getViewElements().map((e) => e.id)); - try { - await importTextToMap(markdown); - const after = ea.getViewElements(); - const addedNodeIds = after - .filter((e) => !beforeIds.has(e.id) && e.type !== "arrow" && !e.customData?.isBoundary) - .map((e) => e.id); - - let rootId = null; - if (parentId) { - const parent = after.find((e) => e.id === parentId); - rootId = parent ? getHierarchy(parent, after).rootId : null; - } else if (addedNodeIds.length > 0) { - const n = after.find((e) => e.id === addedNodeIds[0]); - rootId = n ? getHierarchy(n, after).rootId : null; - } - - return mmOk({ - addedNodeIds, - rootId - }); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "importMarkdown failed", e); - } - }, - - exportMarkdown: async ({ - nodeId, - cut = false - } = {}) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - - if (nodeId) { - const node = findNodeById(nodeId); - if (!node) return mmErr(MMError.INVALID_NODE, `Node not found: ${nodeId}`); - selectNodeInView(node); - } - - try { - const markdown = await copyMapAsText(!!cut, false); - return mmOk({ - markdown - }); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "exportMarkdown failed", e); - } - }, - - toggleSubmapRoot: async ({ - nodeId, - enabled - } = {}) => { - const nodeRes = resolveNode(nodeId); - if (!nodeRes.ok) return nodeRes; - const node = nodeRes.data; - - const current = node.customData?.isAdditionalRoot === true; - if (typeof enabled === "boolean" && enabled === current) { - return mmOk({ - nodeId: node.id, - enabled: current - }); - } - - selectNodeInView(node); - try { - await toggleSubmapRoot(); - const updated = findNodeById(node.id); - return mmOk({ - nodeId: node.id, - enabled: updated?.customData?.isAdditionalRoot === true - }); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "toggleSubmapRoot failed", e); - } - }, - - getMapConfig: (nodeId) => { - const nodeRes = resolveNode(nodeId); - if (!nodeRes.ok) return nodeRes; - const node = nodeRes.data; - const all = ea.getViewElements(); - const info = getHierarchy(node, all); - const settingsRoot = getSettingsRootNode(node, all); - if (!settingsRoot) return mmErr(MMError.NO_ROOT, "Could not resolve settings root"); - - return mmOk({ - rootId: info.rootId, - settingsRootId: settingsRoot.id, - config: extractMapConfig(settingsRoot), - }); - }, - - setMapConfig: async ({ - patch, - nodeId, - relayout = true - } = {}) => { - const nodeRes = resolveNode(nodeId); - if (!nodeRes.ok) return nodeRes; - const node = nodeRes.data; - if (!patch || typeof patch !== "object") { - return mmErr(MMError.INVALID_ARGUMENT, "setMapConfig requires a patch object"); - } - - try { - selectNodeInView(node); - const info = await updateRootNodeCustomData({ - ...patch - }, node); - if (!info) return mmErr(MMError.OPERATION_FAILED, "Failed to update map config"); - if (relayout) await refreshMapLayout(node); - return mmOk({ - rootId: info.rootId, - settingsRootId: info.settingsRootId - }); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "setMapConfig failed", e); - } - }, - - getBranchElementIds: ({ - nodeId, - includeDecorations = true, - includeCrosslinks = true - } = {}) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - if (!nodeId) return mmErr(MMError.INVALID_ARGUMENT, "getBranchElementIds requires nodeId"); - - const node = findNodeById(nodeId); - if (!node) return mmErr(MMError.INVALID_NODE, `Node not found: ${nodeId}`); - - const all = ea.getViewElements(); - let ids = getBranchElementIds(nodeId, all); - if (includeDecorations || includeCrosslinks) { - const info = getHierarchy(node, all); - const extras = getDecorationAndCrossLinkIdsForBranches(ids, all, info.rootId); - if (!includeDecorations || !includeCrosslinks) { - const extraEls = extras.map((id) => all.find((e) => e.id === id)).filter(Boolean); - const filteredExtra = extraEls.filter((e) => { - if (e.type === "arrow") return includeCrosslinks; - return includeDecorations; - }); - ids = ids.concat(filteredExtra.map((e) => e.id)); - } else { - ids = ids.concat(extras); - } - } - return mmOk({ - ids: Array.from(new Set(ids)) - }); - }, - - getProjectElementIds: (rootId) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - if (!rootId) return mmErr(MMError.INVALID_ARGUMENT, "getProjectElementIds requires rootId"); - - const all = ea.getViewElements(); - const root = all.find((e) => e.id === rootId); - if (!root) return mmErr(MMError.INVALID_NODE, `Root not found: ${rootId}`); - - const project = getMindmapProjectElements(rootId, all); - return mmOk({ - ids: project.map((e) => e.id) - }); - }, - - getElementIdsByRole: (rootId) => { - const viewErr = requireView(); - if (viewErr) return viewErr; - if (!rootId) return mmErr(MMError.INVALID_ARGUMENT, "getElementIdsByRole requires rootId"); - - const all = ea.getViewElements(); - const root = all.find((e) => e.id === rootId); - if (!root) return mmErr(MMError.INVALID_NODE, `Root not found: ${rootId}`); - - const branchIds = getBranchElementIds(rootId, all); - const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches(branchIds, all, rootId); - const project = getMindmapProjectElements(rootId, all); - - const nodes = branchIds - .map((id) => all.find((e) => e.id === id)) - .filter((e) => e && e.type !== "arrow" && !e.customData?.isBoundary) - .map((e) => e.id); - - const boundaries = project.filter((e) => e.customData?.isBoundary).map((e) => e.id); - const branchArrows = project.filter((e) => e.type === "arrow" && e.customData?.isBranch).map((e) => e.id); - const crossLinks = project.filter((e) => e.type === "arrow" && !e.customData?.isBranch).map((e) => e.id); - - const boundTexts = project - .filter((e) => e.type === "text") - .filter((t) => { - if (t.containerId) return true; - return project.some((el) => el.boundElements?.some((be) => be.id === t.id)); - }) - .map((e) => e.id); - - const decorationSet = new Set(decorationAndCrossLinkIds); - const roleSet = new Set([...nodes, ...boundaries, ...branchArrows, ...crossLinks, ...boundTexts]); - const decorations = project - .filter((e) => decorationSet.has(e.id) || (!roleSet.has(e.id) && !branchIds.includes(e.id))) - .filter((e) => !crossLinks.includes(e.id) && !boundaries.includes(e.id)) - .map((e) => e.id); - - return mmOk({ - nodes: Array.from(new Set(nodes)), - branchArrows: Array.from(new Set(branchArrows)), - crossLinks: Array.from(new Set(crossLinks)), - boundaries: Array.from(new Set(boundaries)), - decorations: Array.from(new Set(decorations)), - boundTexts: Array.from(new Set(boundTexts)), - }); - }, - - getGlobalConfig: () => { - return mmOk({ - config: { - growthMode: currentModalGrowthMode, - autoLayoutDisabled: autoLayoutDisabled, - arrowType: arrowType, - fontsizeScale: fontsizeScale, - multicolor: multicolor, - boxChildren: boxChildren, - roundedCorners: roundedCorners, - maxWrapWidth: maxWidth, - isSolidArrow: isSolidArrow, - centerText: centerText, - fillSweep: fillSweep, - branchScale: branchScale, - baseStrokeWidth: baseStrokeWidth, - customPalette: cloneJSON(customPalette), - layoutSettings: cloneJSON(layoutSettings) - } - }); - }, - - setGlobalConfig: async ({ patch } = {}) => { - if (!patch || typeof patch !== "object") { - return mmErr(MMError.INVALID_ARGUMENT, "setGlobalConfig requires a patch object"); - } - try { - let requiresSave = false; - - if (patch.growthMode && GROWTH_TYPES.includes(patch.growthMode)) { - currentModalGrowthMode = patch.growthMode; - setVal(K_GROWTH, patch.growthMode); - requiresSave = true; - } - if (typeof patch.autoLayoutDisabled === "boolean") { - // This is a session-level global setting, it does not persist across restarts - autoLayoutDisabled = patch.autoLayoutDisabled; - } - if (patch.arrowType && ARROW_TYPES.includes(patch.arrowType)) { - arrowType = patch.arrowType; - setVal(K_ARROW_TYPE, patch.arrowType); - requiresSave = true; - } - if (patch.fontsizeScale && FONT_SCALE_TYPES.includes(patch.fontsizeScale)) { - fontsizeScale = patch.fontsizeScale; - setVal(K_FONTSIZE, patch.fontsizeScale); - requiresSave = true; - } - if (patch.branchScale && BRANCH_SCALE_TYPES.includes(patch.branchScale)) { - branchScale = patch.branchScale; - setVal(K_BRANCH_SCALE, patch.branchScale); - requiresSave = true; - } - if (typeof patch.multicolor === "boolean") { - multicolor = patch.multicolor; - setVal(K_MULTICOLOR, patch.multicolor); - requiresSave = true; - } - if (typeof patch.boxChildren === "boolean") { - boxChildren = patch.boxChildren; - setVal(K_BOX, patch.boxChildren); - requiresSave = true; - } - if (typeof patch.roundedCorners === "boolean") { - roundedCorners = patch.roundedCorners; - setVal(K_ROUND, patch.roundedCorners); - requiresSave = true; - } - if (typeof patch.maxWrapWidth === "number") { - maxWidth = patch.maxWrapWidth; - setVal(K_WIDTH, patch.maxWrapWidth); - requiresSave = true; - } - if (typeof patch.isSolidArrow === "boolean") { - isSolidArrow = patch.isSolidArrow; - setVal(K_ARROWSTROKE, patch.isSolidArrow); - requiresSave = true; - } - if (typeof patch.centerText === "boolean") { - centerText = patch.centerText; - setVal(K_CENTERTEXT, patch.centerText); - requiresSave = true; - } - if (typeof patch.fillSweep === "boolean") { - fillSweep = patch.fillSweep; - setVal(K_FILL_SWEEP, patch.fillSweep); - requiresSave = true; - } - if (typeof patch.baseStrokeWidth === "number") { - baseStrokeWidth = patch.baseStrokeWidth; - setVal(K_BASE_WIDTH, patch.baseStrokeWidth); - requiresSave = true; - } - if (patch.customPalette && typeof patch.customPalette === "object") { - customPalette = { ...customPalette, ...patch.customPalette }; - setVal(K_PALETTE, customPalette, true); - requiresSave = true; - } - if (patch.layoutSettings && typeof patch.layoutSettings === "object") { - // Additional layer of merging to ensure we don't accidentally erase other layout keys - layoutSettings = { ...layoutSettings, ...patch.layoutSettings }; - setVal(K_LAYOUT, layoutSettings, true); - requiresSave = true; - } - - if (requiresSave) { - await saveSettings(); - updateUI(); // Reflect changes in the sidepanel - } - return mmOk({ success: true }); - } catch (e) { - return mmErr(MMError.OPERATION_FAILED, "setGlobalConfig failed", e); - } - }, - - getConfigSchema: () => { - const schema = { - growthMode: { type: "string", valueset: GROWTH_TYPES }, - autoLayoutDisabled: { type: "boolean" }, - arrowType: { type: "string", valueset: ARROW_TYPES }, - fontsizeScale: { type: "string", valueset: FONT_SCALE_TYPES }, - branchScale: { type: "string", valueset: BRANCH_SCALE_TYPES }, - multicolor: { type: "boolean" }, - boxChildren: { type: "boolean" }, - roundedCorners: { type: "boolean" }, - maxWrapWidth: { type: "number" }, - isSolidArrow: { type: "boolean" }, - centerText: { type: "boolean" }, - fillSweep: { type: "boolean" }, - baseStrokeWidth: { type: "number" }, - customPalette: { - type: "object", - properties: { - enabled: { type: "boolean" }, - random: { type: "boolean" }, - colors: { type: "array", items: "string (hex color)" } - } - }, - layoutSettings: {} - }; - - // Auto-extract boundaries and descriptions from internal layout metadata - Object.keys(LAYOUT_METADATA).forEach(key => { - const meta = LAYOUT_METADATA[key]; - schema.layoutSettings[key] = { - type: "number", - default: meta.def, - min: meta.min, - max: meta.max, - step: meta.step, - description: meta.desc - }; - }); - - return mmOk({ schema }); - }, - }; - - window.MindMapBuilderAPI = API; - console.log("window.MindMapBuilderAPI initialized. For documentation visit: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/ea-script-docs/MindMapBuilderAPI.md", API); -})(); - -let uiUpdateTimer = null; - -/** - * Throttled handler for canvas clicks (pointer down). - * Updates the UI to reflect the new selection. - * - * @param {PointerEvent} e - */ -const handleCanvasPointerDown = (e) => { - if (!isViewSet()) return; - if (floatingInputModal && floatingInputModal.modalEl.contains(e.target)) return; - - if (uiUpdateTimer) { - clearTimeout(uiUpdateTimer); - } - - uiUpdateTimer = setTimeout(() => { - if (!isViewSet()) return; - const selection = getMindmapNodeFromSelection(); - updateUI(selection); - uiUpdateTimer = null; - }, 50); -}; - -/* --- Initialization Logic --- */ -/* --- Initialization Logic --- */ -ea.createSidepanelTab(t("DOCK_TITLE"), true, true).then((tab) => { - - if (!tab) return; - registerStyles(); - tab.onWindowMigrated = (newWin) => { - sidepanelWindow = newWin; - // If we are docked, re-attach to the new window immediately - if (!isUndocked && sidepanelWindow) { - registerKeydownHandler(sidepanelWindow, handleKeydown); - } - }; - - // When the view closes, ensure we dock the input back so it's not lost in floating limbo - tab.onExcalidrawViewClosed = () => { - if (isUndocked) { - toggleDock({ - silent: true, - forceDock: true, - saveSetting: false - }); - } - }; - - tab.onOpen = () => { - const contentEl = tab.contentEl; - contentEl.classList.add("excalidraw-mindmap-ui"); - if (!contentEl.hasChildNodes()) { - renderHelp(contentEl); - inputContainer = contentEl.createDiv(); - renderBody(contentEl); - - sidepanelWindow = contentEl.ownerDocument.defaultView; - - if (isUndocked) { - toggleDock({ - silent: true, - forceDock: true, - saveSetting: false - }); - } else { - renderInput(inputContainer, false); - } - } - - ensureNodeSelected(); - updateUI(); - focusInputEl(); - - if (ea.activateMindmap) { - ea.activateMindmap = false; - const undockPreference = getVal(K_UNDOCKED, false); - if (undockPreference && !isUndocked) { - setTimeout(() => toggleDock({ - saveSetting: false - })); - } else if (!undockPreference && isUndocked) { - setTimeout(() => toggleDock({ - saveSetting: false - })); - tab.reveal(); - } else if (!undockPreference) { - tab.reveal(); - } - } else { - setupEventListeners(ea.targetView); - if (!window.MindmapBuilder?.popObsidianHotkeyScope) registerObsidianHotkeyOverrides(); - } - }; - - const setupEventListeners = (view) => { - if (!view || !view.ownerWindow) return; - window.MindmapBuilder?.removePointerDownHandler?.(); - const win = view.ownerWindow; - - win.addEventListener("pointerdown", handleCanvasPointerDown); - window.MindmapBuilder.removePointerDownHandler = () => { - if (win) win.removeEventListener("pointerdown", handleCanvasPointerDown); - delete window.MindmapBuilder.removePointerDownHandler; - } - updateKeyHandlerLocation(); - - if (!window.MindmapBuilder?.removeActiveLeafListener) { - const leafChangeRef = app.workspace.on("active-leaf-change", onActiveLeafChange); - window.MindmapBuilder.removeActiveLeafListener = () => { - app.workspace.offref(leafChangeRef); - delete window.MindmapBuilder.removeActiveLeafListener; - }; - } - }; - - const onFocus = (view) => { - if (!view) return; - - if (ea.targetView !== view) { - mostRecentlySelectedNodeID = null; - if (ea.targetView) removeEventListeners(ea.targetView); - ea.setView(view); - ea.clear(); - } - - setupEventListeners(view); - - ensureNodeSelected(); - updateUI(); - }; - - tab.onFocus = (view) => onFocus(view); - - const onActiveLeafChange = (leaf) => { - if (cancelHotkeyRecording) cancelHotkeyRecording(); - - if (ea.targetView !== leaf.view && ea.isExcalidrawView(leaf.view)) { - mostRecentlySelectedNodeID = null; - if (ea.targetView) removeEventListeners(ea.targetView); - ea.setView(leaf.view); - ea.clear(); - setupEventListeners(leaf.view); - } - registerObsidianHotkeyOverrides(); - - if (!isUndocked || !floatingInputModal || !leaf) { - return; - } - - if (ea.isExcalidrawView(leaf.view)) { - ensureNodeSelected(); - updateUI(); - const { - modalEl - } = floatingInputModal - - if (isExcaliBrainView()) { - modalEl.style.display = "none"; - } else { - if (modalEl.style.display === "none") { - modalEl.style.display = ""; - } - } - - if (ea.targetView && modalEl.ownerDocument !== ea.targetView.ownerDocument) { - ea.targetView.ownerDocument.body.appendChild(modalEl); - linkSuggester?.close(); - linkSuggester = ea.attachInlineLinkSuggester(inputEl, inputRow?.settingEl); - } - const { - x, - y - } = ea.targetView.contentEl.getBoundingClientRect(); - modalEl.style.top = `${ y + 5 }px`; - modalEl.style.left = `${ x + 5 }px`; - } else { - if (leaf.view?.getViewType() === "excalidraw-sidepanel") return; - const { - modalEl - } = floatingInputModal; - if (modalEl.style.display !== "none") { - modalEl.style.display = "none"; - } - } - }; - - tab.onClose = async () => { - removeEventListeners(); - delete window.MindmapBuilder; - delete window.MindMapBuilderAPI; - removeStyles(); - if (floatingInputModal) { - if (floatingInputModal.modalEl && floatingInputModal.modalEl.parentElement) { - floatingInputModal.modalEl.remove(); - } - floatingInputModal.close(); - floatingInputModal = null; - } - await saveSettings(); - }; - - // Initial setup if a view is already active - if (ea.targetView) { - setupEventListeners(ea.targetView); - } - tab.open(); -}); \ No newline at end of file diff --git a/ea-scripts/Mindmap Builder.md b/ea-scripts/Mindmap Builder.md index 4e8ab2d2..f2b65e5f 100644 --- a/ea-scripts/Mindmap Builder.md +++ b/ea-scripts/Mindmap Builder.md @@ -1,1191 +1,14771 @@ /* - # 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. +Mind Map Builder turns the Obsidian Excalidraw canvas into a keyboard-driven brainstorming environment. Add children and siblings, arrange branches, pin nodes, fold subtrees, customize colors and grouping, and copy or paste Markdown outlines. Controls live in a persistent sidepanel and can be undocked into a floating input. -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. +To reuse a branch with its links, images, and grouped notes, select the complete branch on the canvas and use native Excalidraw copy. Select a destination Mindmap node, then use the existing Builder **Paste** button or hotkey. The branch attaches as a child; with no destination selected, it becomes an independent map. Builder **Copy** continues to export Markdown outlines. + +Pasted branches retain their styles, folds, pinned nodes, and nested submap settings. Copied whole maps become submaps when attached. Auto-layout remains disabled where you disabled it. Builder's input Undo/Redo groups a completed branch paste; the canvas Undo/Redo controls follow native paste, attachment, and layout history steps. > [!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 VERSION = "v26.07.26"; - -if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.4")) { -new Notice("Please update the Excalidraw Plugin to version 2.23.4 or higher."); -return; -} - -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 = ` -MYewdgzgLgBApgXgBQEoED4DeB3AlmAExGwDoBZfAgWwEMAHAIQFdcAbAuAJwDJuk9CxcpVqMW7LiQDWcAJ5FsYABI1CrLhBIAzEJwCiNYAAskiLFE6zMcVAF9gNKMdMpMoSCHUkunXUgBEFISiMMxsHJwAXDB6nL6cMJxwVCAAbvgA5jAy8sRgMEaqBOpR/gA0cCi2tihlAgrCwfRhEpzScgrKRSUQCADaALpVZVDIaFg2KADcFlb1QkHUzeIRA - -PwkdCB0APIARhC4BLiqSiBQOQDKoHRw63YOTiaVbuAQnnDecX6BIvShK1xorF4jBNnQ6JkCmccjAINc4JFypVbLMcJQFr8xOEuOskilUnAAAogfBQLgAETyKjUOJI90czme7jeXh830WIRaESBXwSeLSkM2pK4nQK3UBSKqqPmpA5y2xnFxyTScAAgsAoLgCQAZOA0LTa3DQOBgWn0x4uF4eVm8gJyuj/BU8kH89JgLKGTUEgC06n13uMqgycBgr - -CNZNNpQqVVsUxljSWWNaqygqEi8ftXK4CEwOU61OKGkig1jzNgYDGGD162DUD0AA8HGGCJwaNhVYSAJKoMq4SvoMCoGtwKCq8EXKCOSZlED9vUkSecWsANVwcGwvHni5Xa9IAH1WCAaBwCGUaMhD02J7oaMGSLXO2SqAFWEGmLe4P4UAAfb/+E1fguIDasQXAAMI0BA069NYYCRJgABy2wACqdmBeh7hcejanoYHIXuSHkhhyHbHuYHbISACaiIX - -HA6gajANAwGAIAcDAUAgDA1yyCQ5RIah6F7mQHZkQAqshiJ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5ON1oOu1l1e0D8j+3U9uWGfcLcQl8mgAkZ9jvbmk9XOx9T3XDtuDoAa3n4U5OH - -W8vimkIlB3qjoLmrANoBmhz+0s9mpEuu6hF2x8QUS96uEMIywXGhy3Vmh5UfBJ24dn1r6iZto01PDgzD314gBH8t4cRxr4cutn4fL1r+sAj5xGQNprEwNuBuJtyEe4x5l1/1rcQ38sNTANvzGEo8ps75izOWj/TNqjlUPcF3Ucqh/UdtARoNtAcOMFjk2mX2/CnUI20d5ji0cVZrDNKji1ttB50ef0t0ciMD0fhAa+vNDsyjchioCv1gMciMX4fB - -jreChjy2nhj+CmRjhBvRjmSm60/+tAD7x1MqCVk4dxOGyh2lN9+h7s9ZoAeCU17utpyaufd2VN627od014f0j5uVtUjp/u1AEHsN9gDMQ9yZFQ90bPapueBw92XnI99YfVw2cAI9jgdrGZns2yKYDY970B09/Hu/jl1249sBuGN0ntXcuEeE2zKNU95Vu09izPi9/TP09wxts9gXlzsrnsgJ/fkHV2rn898w2Nls0M9llntBx0YClZz8duxqXsy9 - -8X2RAeXtgTxXuhh5XvhhwGQrmk8epgcCdcmpXu69uifhW6k0m9izPm9q0de9q0clIkLv8coPuM90Pss9sUPghq3tRlel6296UN+9/wCZ9p3utlwxvegN3vtlDUOe9q4eASGSe6huScKTyPugkS/1HBk2sa9hPvnBmwgp9tPvgezPvI6nPv29vPu2ThEPyTkevzGyvu7jgNOimOvvRMi8fMt88Nt92e2d9260pJ7x299lB0D95ivldkfu/939PymS - -fv1Wkwez9tyfBD6luHjqHWNFqgtN90q3YDwGTr9+r2b99s2FWnftH5pkf79uJn8jlwAn90r2OBpyvn98muX9ymsXhw41zsg4PwDjXvP9wb0WZtsvxwowtf923W4tjycPdk3lPd4AfidsAfAFiMiEppEewD/kfJGpAdzslAdoDy8dRp0yR4D0gPoDiCdYDjVOPm0gcwR8gdA+lIMWpkvgN66QeVABgfJMh/sBFpUNsD+XMcDrgeeVngdKYfgeIIQQ - -e3T2/srD5nXiD0gcIdqQd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uOay1rCWpja4lq2rKcGDRBqyA/jUVr7irysuNr2rNba4agOk01Aaus5OElQVthDcHaoX9AHZKOsiiyWmuypevURgBGDTUBktRjpbOUT6RBs3IC2WBIANpjBSPza7pM+gGso7YBUwAJAIly3qwg - -MAAiygD3a1MBZqFLczABy3MvaofCz2oso1MB8hSva8tyn2rva89qkAHKFZ9rUwE/aofDCVXe1clUxaPkoqYBUWqYIGgACgpQbYytTeXWayL1lmq2anDKma14cpJrO6uYyjZcv8syaiukB6pyawAq8mtEUZKrgGSKa1JgSmrKa1DqNILAKtuAZMrw6ztklwCbq5Br/AEaasnA7JMWRevCVYTcaprLWwGHy2cBQrKJ/ExTZ7M4co/LHDCts4uzLWji - -zWaqTXNZRa3kjXJNckjFdgBLs/1iC2ok611yTXJqS1lFSZMVAZ/SCI3WUUy1rkT0tSfl11TUixd0DMFMtXGs2NScRQBzG8qXcg+zRCLYAFNzQcpnyzNzDaqDWU0InkB/c69rUwG6FKty1A0U691y2k2uqpwYsNTxdRaRBeLXy+mlOwD91dzrhgE7ckzqVYXoa3CNbOrFc99yHOpxc7+QHiEIK1tRf3IDJZEBzyM864sQpOpeqiwAAgH86slzJtRh - -y/jBlstC6jLqS2Ui6iS0hzXM6gHKz40WNfWBiMB+UbAhusps6/rK7OoS609BjthjIU7YOxS/apAB+hQ860TrvOry6vzr5NV0MwLqFst3q07M/dUG6iLquUSi6rAApGti6urryVWsYSYUktXa6+LqMXMS6vYhexX66yI0vyJoarzr5qrmC3zqCuvG6yI1iuppyr+rxgHK6yI15usY9CS1UHNq69WrfMvEoM1BAaq08zbrp8u26iVyuuoLIYFZuCBc - -68tz2RSG6yTqRupHAc7q5NSUqqhE3WSC66bryurB6x7q6yWcs90MvLJvRDyzpkQ8sh2koXP3sjyyuaHqMUzKV+CoAGzcfyF6iInrpETJ6gCAO1Lw1EXykmoJ65DqycD0c9+M9hVw1SPVktQVKvuyOevlKzZq2aqSYNCrAJGSarmhrrNF0SIALRWGARbqYvRU9bPK3ur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Opd9J7GlbuWy9JPZsZl - -G7JO21f1Yb6AN42WW20blbLsAMAmEZqu3U47S2oVAQOyabMuAMOyrOXbm3fD5Y4fRduPqRretqI0PZrLaiErVpvJ4L4q7xcQtPpPwrNBCsqaWrO7apwZnJpKslIAGk5La2KyFQF5jkZOMrJpAEEm0g2i1CErxIYxa9qyFk6JOpZPgsVupQZO1k+GT1KbRk8Ssx7mTcNqQxpPVk+TAXmO1np1AB0aDk4QfKSKPxcCA+rqbXN6EH5QLMHKAGrlzk8x - -siEqXk+71N5O5k5vRCMbPxcpQAjRiJGQ0allybIeT1Ky4rNBTmMb9QHeTyi0XV3AAdkrBK1fYnC6na3jGpv1ryNFEj9l4xqnVCfH/1sFQh3DqWX1F3395MWpZY1qugfwPJH95Y7tFXgA7RVCTolP1TU3dRfUa+RFFqUXN8d3AHcjSU4RmilP6k5/AmlOhU6nx1bjoofjhUVVN3UNal0OIrVWNyoBOzP5T/pUeDWlTrCDXACZT1ULLHz5e+sbfHz7 - -Gu7AhwB0ayJqOmrNs40O7zWEm8jAspPoypDqU3J+m0pNzlrPG7caZ5pdwzJaKZOJrXmavU6qi5SALxoetzTqbSysTS16lrMDrCVBjABHa6RAx2ugxYMBJ2rqZGRrFBVaalO94mTum1yDGZt5mv6akSbYDUKbPpuiIH8aNHKGm6yjihwpmxgPzU66m02bShzLT/qbym1k1S03CGZJIO81N3T6TL9E7wcF+26bDU5rQvsaEJtx9W1OgkHZktCaRJrn - -G/kwEer+KzVa6ct9MjhPgU4iAU5Or32yNymyuADYpz583I8QAGE3WZNBNwlNwTckQp0OVQBL++cbc5vWNrnrC5tAmkuaXBDLm9FarbKhNtnqDwJdutnqF+Wl/V/WMbedT0l6JU5fK+I0agCAAA==`; -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); +> Become a MindMap Builder Pro with the official [MindMap Builder course](https://www.visual-thinking-workshop.com/mindmap)! + +Requires Excalidraw 2.23.4 or newer. Excalidraw 2.27.0 or newer caches compiled scripts, so repeated hotkey activation reuses compiled code and the existing sidepanel without rereading the script. This script is distributed as readable JavaScript, with no compressed executable payload. + +[Modular source and authoring instructions](https://github.com/zsviczian/ea-scripts/tree/main/src/scripts/mindmap-builder) · [API documentation](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/ea-script-docs/MindMapBuilderAPI.md) + +If you find MindMap Builder helpful, [buy me a coffee](https://ko-fi.com/zsolt). + +Build version: 2026-10-13T15:29:25.764Z + +```javascript +*/ + +// Configuration constants +const VERSION = "v26.10.13"; + +// Script bundle +/* EA Script — mindmap-builder | ea-scripts v1.0.0 */ +(() => { + // src/sharedUtils/i18n.ts + function interpolateTranslation(template, params = {}) { + return Object.entries(params).reduce( + (result, [key, value]) => result.split(`{${key}}`).join(String(value)), + template + ); + } + function createTranslator(requestedLocale, catalogs, fallbackLocale = "en") { + const locale = requestedLocale.toLowerCase().replaceAll("_", "-"); + const baseLocale = locale.split("-")[0] ?? locale; + return (key, params = {}) => { + const template = catalogs[locale]?.[key] ?? catalogs[baseLocale]?.[key] ?? catalogs[fallbackLocale]?.[key] ?? key; + return interpolateTranslation(template, params); + }; + } + + // src/scripts/mindmap-builder/lang/de.ts + var de = {}; + + // src/scripts/mindmap-builder/lang/en.ts + var en = { + requiresNewerVersion: "Please update the Excalidraw plugin to version {version} or higher.", + launchFailed: "Mindmap Builder could not start. See the developer console for details.", + // Notices + NOTICE_SELECT_NODE_TO_COPY: "Select a node to copy.", + NOTICE_MAP_CUT: "Map cut to clipboard.", + NOTICE_BRANCH_CUT: "Branch cut to clipboard.", + NOTICE_MAP_COPIED: "Map copied as markdown.", + NOTICE_BRANCH_COPIED: "Branch copied as bullet list.", + NOTICE_CLIPBOARD_EMPTY: "Clipboard is empty.", + NOTICE_PASTE_ABORTED: "Paste aborted. Clipboard does not start with a Markdown list or header.", + NOTICE_NO_LIST: "No valid Markdown list found on clipboard.", + NOTICE_PASTE_START: "Pasiting, please wait, this can take a while...", + NOTICE_PASTE_COMPLETE: "Paste complete.", + NOTICE_BRANCH_PASTE_INVALID: "Cannot paste this branch: its Mindmap connections are invalid.", + NOTICE_BRANCH_PASTE_FAILED: "Branch paste could not finish. Any pasted elements remain in the drawing. Check the drawing before retrying.", + NOTICE_ACTION_REQUIRES_ARROWS: "This action requires Arrow Keys. Only modifiers can be changed.", + NOTICE_CONFLICT_WITH_ACTION: 'Conflict with "{action}"', + NOTICE_OBSIDIAN_HOTKEY_CONFLICT: '\u26A0\uFE0F Obsidian Hotkey Conflict!\n\nThis key overrides:\n"{command}"', + NOTICE_GLOBAL_HOTKEY_CONFLICT: '\u26A0\uFE0F Global Hotkey Conflict!\n\nThis key overrides:\n"{command}"', + NOTICE_NO_HEADINGS: "No headings found in the linked file.", + NOTICE_CANNOT_EDIT_MULTILINE: "Cannot edit multi-line nodes directly.\nDouble-click the element in Excalidraw to edit, then run auto re-arrange map to update the layout.", + NOTICE_CANNOT_MOVE_PINNED: "Cannot move pinned nodes. Unpin the node first.", + NOTICE_CANNOT_MOVE_ROOT: "Cannot move the root node.", + NOTICE_CANNOT_PRMOTE_L1: "Cannot promote Level 1 nodes.", + NOTICE_CANNOT_DEMOTE: "Cannot demote node. No previous sibling to attach to.", + NOTICE_SELECT_NODE_CONTAINING_LINK: "Select a node containing a link.", + NOTICE_CANNOT_DEMOTE_NO_SIBLING_TO_ACCEPT: "Cannot demote: No sibling found to accept this node.", + NOTICE_CANNOT_DEMOTE_NO_VALID_SIBLING: "Cannot demote: No valid sibling to attach to.", + NOTICE_CANNOT_DEMOTE_CROSS_SIDE_NOT_ALLOWED: "Cannot demote: Cross-side demotion is not allowed.", + NOTICE_CANNOT_MOVE_AUTO_LAYOUT_DISABLED: "Cannot move nodes when Auto-Layout is disabled. Enable Auto-Layout first.", + NOTICE_BRANCH_WIDTH_MANUAL_OVERRIDE: "Branch width were not updated because some branch widths were manually modified.", + NOTICE_CANNOT_CHANGE_MASTER_ROOT: "The master root cannot be converted.", + NOTICE_SUBMAP_ROOT_ADDED: "Submap root enabled.", + NOTICE_SUBMAP_ROOT_REMOVED: "Submap root removed. Children now follow the parent map layout.", + CONFIRM_REMOVE_SUBMAP_ROOT: "Change this submap root back to a normal node?\n\nIt will lose its local layout metadata, and its children will be rearranged by the parent root's layout logic.", + // Action labels (display only) + ACTION_LABEL_ADD: "Add Child", + ACTION_LABEL_ADD_SIBLING_AFTER: "Add Next Sibling", + ACTION_LABEL_ADD_SIBLING_BEFORE: "Add Prev Sibling", + ACTION_LABEL_ADD_FOLLOW: "Add + follow", + ACTION_LABEL_ADD_FOLLOW_FOCUS: "Add + follow + focus", + ACTION_LABEL_ADD_FOLLOW_ZOOM: "Add + follow + zoom", + ACTION_LABEL_SORT_ORDER: "Change Order/Promote Node", + ACTION_LABEL_EDIT: "Edit node", + ACTION_LABEL_PIN: "Pin/Unpin", + ACTION_LABEL_BOX: "Box/Unbox", + ACTION_LABEL_TOGGLE_GROUP: "Group/Ungroup Single Branch", + ACTION_LABEL_COPY: "Copy", + ACTION_LABEL_CUT: "Cut", + ACTION_LABEL_PASTE: "Paste", + ACTION_LABEL_IMPORT_OUTLINE: "Import Outline", + ACTION_LABEL_ZOOM: "Cycle Zoom", + ACTION_LABEL_FOCUS: "Focus (center) node", + ACTION_LABEL_NAVIGATE: "Navigate", + ACTION_LABEL_NAVIGATE_ZOOM: "Navigate & zoom", + ACTION_LABEL_NAVIGATE_FOCUS: "Navigate & focus", + ACTION_LABEL_FOLD: "Fold/Unfold Branch", + ACTION_LABEL_FOLD_L1: "Fold/Unfold to Level 1", + ACTION_LABEL_FOLD_ALL: "Fold/Unfold Branch Recursively", + ACTION_LABEL_DOCK_UNDOCK: "Dock/Undock", + ACTION_LABEL_HIDE: "Dock & hide", + ACTION_LABEL_REARRANGE: "Rearrange Map", + ACTION_LABEL_TOGGLE_SUBMAP_ROOT: "Start/End Submap Root", + ACTION_LABEL_TOGGLE_CHECKBOX: "Toggle Checkbox Status", + ACTION_LABEL_CALENDAR: "Task Calendar & Priority", + ACTION_LABEL_TOGGLE_EMBED: "Toggle Embed/Link", + // Tooltips (shared) + PIN_TOOLTIP_PINNED: "This element is pinned. Click to unpin the location of the selected element", + PIN_TOOLTIP_UNPINNED: "This element is not pinned. Click to pin the location of the selected element", + TOGGLE_GROUP_TOOLTIP_GROUP: 'Group this branch. Only available if "Group Branches" is disabled', + TOGGLE_GROUP_TOOLTIP_UNGROUP: 'Ungroup this branch. Only available if "Group Branches" is disabled', + TOOLTIP_EDIT_NODE: "Edit text of selected node", + TOOLTIP_PIN_INIT: "Pin/Unpin location of a node. When pinned nodes won't get auto-arranged", + TOOLTIP_REFRESH: "Auto rearrange map", + TOOLTIP_DOCK: "Dock to Sidepanel", + TOOLTIP_UNDOCK: "Undock to Floating Modal", + TOOLTIP_ZOOM_CYCLE: "Cycle element zoom", + TOOLTIP_TOGGLE_GROUP_BTN: 'Toggle grouping/ungrouping of a branch. Only available if "Group Branches" is disabled.', + TOOLTIP_TOGGLE_BOX: "Toggle node box", + TOOLTIP_TOGGLE_BOUNDARY: "Toggle subtree boundary", + TOOLTIP_TOGGLE_FLOATING_EXTRAS: "Toggle extra controls", + TOOLTIP_CONFIGURE_PALETTE: "Configure custom color palette for branches", + TOOLTIP_CONFIGURE_LAYOUT: "Configure layout settings", + TOOLTIP_MOVE_UP: "Move Up", + TOOLTIP_MOVE_DOWN: "Move Down", + TOOLTIP_EDIT_COLOR: "Edit", + TOOLTIP_DELETE_COLOR: "Delete", + TOOLTIP_OPEN_PALETTE_PICKER: "Open Palette Picker", + TOOLTIP_FOLD_BRANCH: "Fold/Unfold selected branch", + TOOLTIP_FOLD_L1_BRANCH: "Fold/Unfold children (Level 1)", + TOOLTIP_FOLD_ALL: "Fold/Unfold Branch Recursively", + TOOLTIP_IMPORT_OUTLINE: "Import headings from linked file as child nodes", + TOOLTIP_RESET_TO_DEFAULT: "Reset to default", + TOOLTIP_SUBMAP_ROOT_ADD: "Start submap from selected node", + TOOLTIP_SUBMAP_ROOT_REMOVE: "Convert submap root back to a normal node", + TOOLTIP_TOGGLE_CHECKBOX: "Toggle task checkbox status", + TOOLTIP_CALENDAR: "Configure Task Date & Priority", + TOOLTIP_TOGGLE_EMBED: "Toggle node between Embed and Link", + // Buttons and labels + DOCK_TITLE: "Mind Map Builder", + HELP_SUMMARY: "Help", + INPUT_PLACEHOLDER: "Concept... type [[ to insert link", + ONTOLOGY_PLACEHOLDER: "Ontology (Arrow Label)", + BUTTON_COPY: "Copy", + BUTTON_CUT: "Cut", + BUTTON_PASTE: "Paste", + TITLE_ADD_SIBLING: `Add sibling with {modifier}+Enter`, + TITLE_ADD_FOLLOW: "Add and follow", + TITLE_COPY: "Copy branch as text", + TITLE_CUT: "Cut branch as text", + TITLE_PASTE: "Paste Markdown or a copied Mindmap branch", + LABEL_ZOOM_LEVEL: "Zoom Level", + LABEL_GROWTH_STRATEGY: "Growth Strategy", + LABEL_FILL_SWEEP: "Fill Sweep Angle", + DESC_FILL_SWEEP: "Distribute nodes across the full Max Sweep Angle immediately, rather than growing the arc gradually as nodes are added.", + LABEL_ARROW_TYPE: "Curved Connectors", + LABEL_AUTO_LAYOUT: "Auto-Layout", + LABEL_GROUP_BRANCHES: "Group Branches", + LABEL_BOX_CHILD_NODES: "Box Child Nodes", + LABEL_ROUNDED_CORNERS: "Rounded Corners", + LABEL_USE_SCENE_STROKE: "Use scene stroke style", + DESC_USE_SCENE_STROKE: "Use the latest stroke style (solid, dashed, dotted) from the scene, or always use solid style for branches.", + LABEL_BRANCH_SCALE: "Branch Scale", + LABEL_BASE_WIDTH: "Base Thickness", + LABEL_MULTICOLOR_BRANCHES: "Multicolor Branches", + LABEL_MAX_WRAP_WIDTH: "Max Wrap Width", + LABEL_CENTER_TEXT: "Center text", + DESC_CENTER_TEXT: "Toggle off: align nodes to right/left depending; Toggle on: center the text.", + LABEL_FONT_SIZES: "Font Sizes", + HOTKEY_SECTION_TITLE: "Hotkey Configuration", + HOTKEY_HINT: "These hotkeys may override some Obsidian defaults. They're Local (\u2328\uFE0F) by default, active only when the MindMap input field is focused. Use the \u{1F310}/\u{1F3A8}/\u2328\uFE0F toggle to change hotkey scope: \u{1F310} Overrides Obsidian hotkeys whenever an Excalidraw tab is visible, \u{1F3A8} Overrides Obsidian hotkeys whenever Excalidraw is focused, \u2328\uFE0F Local (input focused).", + RECORD_HOTKEY_PROMPT: "Press hotkey...", + ARIA_SCOPE_INPUT: "Local: Active only when MindMap Input is focused", + ARIA_SCOPE_EXCALIDRAW: "Excalidraw: Active whenever MindMap Input or Excalidraw is focused", + ARIA_SCOPE_GLOBAL: "Global: Active everywhere in Obsidian, whenever the Excalidraw view is visible", + ARIA_RESTORE_DEFAULT: "Restore default", + ARIA_CUSTOMIZE_HOTKEY: "Customize this hotkey", + ARIA_OVERRIDE_COMMAND: "Overrides Obsidian command:\n{command}", + // Palette manager + MODAL_PALETTE_TITLE: "Mindmap Branch Palette", + LABEL_ENABLE_CUSTOM_PALETTE: "Enable Custom Palette", + DESC_ENABLE_CUSTOM_PALETTE: "Use these colors instead of auto-generated ones.", + LABEL_RANDOMIZE_ORDER: "Randomize Order", + DESC_RANDOMIZE_ORDER: "Pick colors randomly instead of sequentially.", + HEADING_ADD_NEW_COLOR: "Add New Color", + HEADING_EDIT_COLOR: "Edit Color", + LABEL_SELECT_COLOR: "Select Color", + BUTTON_CANCEL_EDIT: "Cancel Edit", + BUTTON_ADD_COLOR: "Add Color", + BUTTON_UPDATE_COLOR: "Update Color", + // Layout configuration + MODAL_LAYOUT_TITLE: "Layout Configuration", + // Section Headers + SECTION_GENERAL: "General Spacing", + SECTION_RADIAL: "Radial Layout (Clockwise)", + SECTION_DIRECTIONAL: "Directional Layout (Left/Right)", + SECTION_VERTICAL: "Vertical Maps (Up/Down)", + SECTION_VISUALS: "Visual Elements", + SECTION_MANUAL: "Manual Mode Behavior", + LAYOUT_RESET: "Reset All to Default", + LAYOUT_SAVE: "Save & Close", + // Radial Strings + RADIAL_ASPECT_RATIO: "Ellipse Aspect Ratio", + DESC_RADIAL_ASPECT_RATIO: "Controls the shape. < 1.0 is tall/narrow (0.7 = portrait). 1.0 is circular. > 1.0 is wide (landscape).", + RADIAL_POLE_GAP_BONUS: "Pole Gap Bonus", + DESC_RADIAL_POLE_GAP_BONUS: "Increases spacing between nodes at the Top and Bottom. Higher values push nodes further along the arc.", + RADIAL_START_ANGLE: "Start Angle", + DESC_RADIAL_START_ANGLE: "Where the first node appears (Degrees). 270 is North, 0 is East, 90 is South.", + RADIAL_MAX_SWEEP: "Max Sweep Angle", + DESC_RADIAL_MAX_SWEEP: "Total arc available to fill. 360 uses full circle. Lower values leave a gap between the first and last node.", + // Others + GAP_X: "Gap X", + DESC_LAYOUT_GAP_X: "Horizontal distance between parent and child nodes.", + GAP_Y: "Gap Y", + DESC_LAYOUT_GAP_Y: "Vertical distance between sibling nodes. Also used as the base gap for Radial layouts.", + GAP_MULTIPLIER: "Gap Multiplier", + DESC_LAYOUT_GAP_MULTIPLIER: "Vertical spacing for 'leaf' nodes (no children), relative to font size. Low: list-like stacking. High: standard tree spacing.", + DIRECTIONAL_ARC_SPAN_RADIANS: "Directional Arc-span Radians", + DESC_LAYOUT_ARC_SPAN: "Curvature of the child list. Low (0.5): Flatter, list-like. High (2.0): Curved, organic, but risk of overlap.", + ROOT_RADIUS_FACTOR: "Root Radius Factor", + DESC_LAYOUT_ROOT_RADIUS: "Multiplier for the Root node's bounding box to determine initial radius.", + MIN_RADIUS: "Minimum Radius", + DESC_LAYOUT_MIN_RADIUS: "The absolute minimum distance from the root center to the first level of nodes.", + RADIUS_PADDING_PER_NODE: "Radius Padding per Node", + DESC_LAYOUT_RADIUS_PADDING: "Extra radius added per child node to accommodate dense maps.", + GAP_MULTIPLIER_RADIAL: "Radial-layout Gap Multiplier", + DESC_LAYOUT_GAP_RADIAL: "Angular spacing multiplier for Radial mode.", + GAP_MULTIPLIER_DIRECTIONAL: "Vertical-layout Gap Multiplier", + DESC_LAYOUT_GAP_DIRECTIONAL: "Spacing multiplier for Right-facing and Left-facing top level branches", + INDICATOR_OFFSET: "Fold Indicator Offset", + DESC_LAYOUT_INDICATOR_OFFSET: "Distance of the '...' fold indicator from the node.", + INDICATOR_OPACITY: "Fold Indicator Opacity", + DESC_LAYOUT_INDICATOR_OPACITY: "Opacity of the '...' fold indicator (0-100).", + CONTAINER_PADDING: "Container Padding", + DESC_LAYOUT_CONTAINER_PADDING: "Padding inside the box when 'Box Child Nodes' or 'Box/Unbox' is used.", + MAX_SEGMENT_LENGTH: "Boundary Line Precision", + DESC_LAYOUT_BOUNDARY_LINE_PRECISION: "Boundary smoothing precision. Smaller values are more precise (30 = Precise), larger values are rougher (200 = Rough).", + VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "Subtree Width Blend (Single-sided)", + DESC_VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "How strongly one-sided submaps (Right-facing / Left-facing) reserve horizontal sibling space in vertical maps. High impact.", + VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "Subtree Width Blend (Dual-sided)", + DESC_VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "How strongly dual-sided submaps (Right-Left) reserve horizontal sibling space in vertical maps. High impact.", + VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "Subtree Smooth Threshold Multiplier", + DESC_VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "Starts smooth compression after this multiple of Gap Y to avoid spacing jumps when adding more children. Usually subtle unless the map is large.", + VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "Subtree Smooth Minimum Scale", + DESC_VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "Minimum compression scale used by the vertical subtree width smoother. Higher values preserve more width. Usually subtle unless the map is large.", + HORIZONTAL_L1_SOFTCAP_THRESHOLD: "Horizontal L1 Soft Cap Threshold", + DESC_HORIZONTAL_L1_SOFTCAP_THRESHOLD: "Soft cap (px) before Up/Down Level-1 subtree widths are compressed. Medium to high impact on large maps.", + HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "Horizontal L1 Compression Min Scale", + DESC_HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "Minimum compression scale for Up/Down Level-1 width compression. Higher values preserve more width. Medium impact after soft cap is reached.", + VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "Compact Parent-Child Gap Ratio", + DESC_VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "In compact vertical subtrees, uses this fraction of Gap X for parent-child distance. Very high visible impact.", + DIRECTIONAL_CROSS_AXIS_RATIO: "Directional Cross-axis Ratio", + DESC_DIRECTIONAL_CROSS_AXIS_RATIO: "Cross-axis radius ratio for directional arc layouts (0.2 = flatter arcs, 1.0 = rounder arcs). High visual impact on L1 spread.", + MANUAL_GAP_MULTIPLIER: "Manual-layout Gap Multiplier", + DESC_LAYOUT_MANUAL_GAP: "Spacing multiplier when adding nodes while Auto-Layout is disabled.", + MANUAL_JITTER_RANGE: "Manual-layout Jitter Range", + DESC_LAYOUT_MANUAL_JITTER: "Random position offset when adding nodes while Auto-Layout is disabled.", + CALENDAR_DATE_INDEX: "Date {index} of {total}", + CALENDAR_DATE_LABEL: "Date", + CALENDAR_DATE_TYPE: "Date Type", + CALENDAR_PRIORITY: "Priority", + CALENDAR_RECURRENCE: "Recurrence", + CALENDAR_RECURRENCE_PLACEHOLDER: "every day", + CALENDAR_RECURRENCE_DESC: `e.g., 'every day', 'every 2 weeks'
Tasks recurrence docs`, + CALENDAR_INJECT_LINK: "Inject node link", + CALENDAR_INJECT_LINK_DESC: "Adds a link to the node at the end of the task.", + CALENDAR_ALIAS_PLACEHOLDER: "Alias", + CALENDAR_BTN_CANCEL: "Cancel", + CALENDAR_BTN_TASK_ONLY: "Task Only", + CALENDAR_BTN_ADD_DATE_TASK: "Add Date & Task", + CALENDAR_PRIORITY_HIGHEST: "Highest", + CALENDAR_PRIORITY_HIGH: "High", + CALENDAR_PRIORITY_MEDIUM: "Medium", + CALENDAR_PRIORITY_NORMAL: "Normal", + CALENDAR_PRIORITY_LOW: "Low", + CALENDAR_PRIORITY_LOWEST: "Lowest", + CALENDAR_DATETYPE_DUE: "Due", + CALENDAR_DATETYPE_START: "Start", + CALENDAR_DATETYPE_SCHEDULED: "Scheduled", + CALENDAR_DATETYPE_CREATED: "Created", + CALENDAR_DATETYPE_DONE: "Done", + CALENDAR_DATETYPE_CANCELLED: "Cancelled", + // Presets + PRESET_LABEL: "Preset", + PRESET_DEFAULT: "Default", + PRESET_UNSAVED: "Custom / Unlinked", + PRESET_BTN_SAVE: "Save to Preset", + PRESET_BTN_DELETE: "Delete Preset", + PRESET_BTN_NEW: "Create New Preset", + PRESET_BTN_APPLY: "Apply Preset to Map", + PRESET_WARNING_MODIFIED: "Map settings differ from preset.", + PROMPT_NEW_PRESET_NAME: "New preset name:", + NOTICE_PRESET_DELETED: "Preset deleted.", + NOTICE_PRESET_SAVED: "Preset saved.", + NOTICE_PRESET_APPLIED: "Preset applied.", + // Misc + INPUT_TITLE_PASTE_ROOT: "Mindmap Builder Paste", + INSTRUCTIONS: `> [!Tip] +>\u{1F680} Become a MindMap Builder Pro with the Official [MindMap Builder Course](https://www.visual-thinking-workshop.com/mindmap)! + +- **ENTER**: Add a child node and stay on the current parent for rapid entry. If you press enter when the input field is empty the focus will move to the child node that was most recently added. Pressing enter subsequent times will iterate through the new child's siblings +- **Hotkeys**: See configuration at the bottom of the sidepanel +- **Dock/Undock**: You can dock/undock the input field using the dock/undock button or the configured hotkey +- **Folding**: Fold/Unfold buttons only appear when the input is docked; when undocked, use the folding hotkeys. +- **ESC**: Docks the floating input field without activating the side panel +- **Coloring**: First level branches get unique colors (Multicolor mode). Descendants inherit parent's color. +- **Grouping**: + - Enabling "Group Branches" recursively groups sub-trees from leaves up to the first level. +- **Copy/Paste**: Builder Copy exports Markdown. To preserve links, images, and grouped notes, use native canvas copy, select the destination parent, then use Builder Paste. With no parent selected, the copied branch becomes an independent map. + +\u{1F60D} If you find this script helpful, please [buy me a coffee \u2615](https://ko-fi.com/zsolt).` + }; + + // src/scripts/mindmap-builder/lang/es.ts + var es = {}; + + // src/scripts/mindmap-builder/lang/fr.ts + var fr = {}; + + // src/scripts/mindmap-builder/lang/ru.ts + var ru = {}; + + // src/scripts/mindmap-builder/lang/zh-cn.ts + var zhCn = { + // Notices + NOTICE_SELECT_NODE_TO_COPY: "\u8BF7\u9009\u62E9\u8981\u590D\u5236\u7684\u8282\u70B9\u3002", + NOTICE_MAP_CUT: "\u5BFC\u56FE\u5DF2\u526A\u5207\u5230\u526A\u8D34\u677F\u3002", + NOTICE_BRANCH_CUT: "\u5206\u652F\u5DF2\u526A\u5207\u5230\u526A\u8D34\u677F\u3002", + NOTICE_MAP_COPIED: "\u5BFC\u56FE\u5DF2\u590D\u5236\u4E3A Markdown \u683C\u5F0F\u3002", + NOTICE_BRANCH_COPIED: "\u5206\u652F\u5DF2\u590D\u5236\u4E3A\u5217\u8868\u683C\u5F0F\u3002", + NOTICE_CLIPBOARD_EMPTY: "\u526A\u8D34\u677F\u4E3A\u7A7A\u3002", + NOTICE_PASTE_ABORTED: "\u7C98\u8D34\u4E2D\u6B62\u3002\u526A\u8D34\u677F\u5185\u5BB9\u975E Markdown \u5217\u8868\u6216\u6807\u9898\u3002", + NOTICE_NO_LIST: "\u526A\u8D34\u677F\u4E2D\u672A\u53D1\u73B0\u6709\u6548\u7684 Markdown \u5217\u8868\u3002", + NOTICE_PASTE_START: "\u6B63\u5728\u7C98\u8D34\uFF0C\u8BF7\u7A0D\u5019\uFF0C\u53EF\u80FD\u9700\u8981\u4E00\u4E9B\u65F6\u95F4\u2026", + NOTICE_PASTE_COMPLETE: "\u7C98\u8D34\u5B8C\u6210\u3002", + NOTICE_ACTION_REQUIRES_ARROWS: "\u6B64\u64CD\u4F5C\u9700\u8981\u65B9\u5411\u952E\u3002\u4EC5\u53EF\u4FEE\u6539\u4FEE\u9970\u952E\u3002", + NOTICE_CONFLICT_WITH_ACTION: "\u4E0E\u201C{action}\u201D\u64CD\u4F5C\u51B2\u7A81", + NOTICE_OBSIDIAN_HOTKEY_CONFLICT: "\u26A0\uFE0F Obsidian \u70ED\u952E\u51B2\u7A81\uFF01\n\n\u6B64\u6309\u952E\u5C06\u8986\u76D6\uFF1A\n\u201C{command}\u201D", + NOTICE_GLOBAL_HOTKEY_CONFLICT: "\u26A0\uFE0F \u5168\u5C40\u70ED\u952E\u51B2\u7A81\uFF01\n\n\u6B64\u6309\u952E\u5C06\u8986\u76D6\uFF1A\n\u201C{command}\u201D", + NOTICE_NO_HEADINGS: "\u94FE\u63A5\u6587\u4EF6\u4E2D\u672A\u53D1\u73B0\u5C0F\u6807\u9898\u3002", + NOTICE_CANNOT_EDIT_MULTILINE: "\u65E0\u6CD5\u76F4\u63A5\u7F16\u8F91\u591A\u884C\u8282\u70B9\u3002\n\u8BF7\u5728 Excalidraw \u4E2D\u53CC\u51FB\u5143\u7D20\u8FDB\u884C\u7F16\u8F91\uFF0C\u7136\u540E\u8FD0\u884C\u201C\u81EA\u52A8\u91CD\u6392\u5BFC\u56FE\u201D\u6765\u66F4\u65B0\u5E03\u5C40\u3002", + NOTICE_CANNOT_MOVE_PINNED: "\u65E0\u6CD5\u79FB\u52A8\u5DF2\u9501\u5B9A\u7684\u8282\u70B9\u3002\u8BF7\u5148\u89E3\u9501\u3002", + NOTICE_CANNOT_MOVE_ROOT: "\u65E0\u6CD5\u79FB\u52A8\u6839\u8282\u70B9\u3002", + NOTICE_CANNOT_PRMOTE_L1: "\u65E0\u6CD5\u63D0\u5347 1 \u7EA7\u8282\u70B9\u3002", + NOTICE_CANNOT_DEMOTE: "\u65E0\u6CD5\u964D\u7EA7\u8282\u70B9\u3002\u6CA1\u6709\u53EF\u4F9D\u9644\u7684\u524D\u7F6E\u540C\u7EA7\u8282\u70B9\u3002", + NOTICE_SELECT_NODE_CONTAINING_LINK: "\u8BF7\u9009\u62E9\u5305\u542B\u94FE\u63A5\u7684\u8282\u70B9\u3002", + NOTICE_CANNOT_DEMOTE_NO_SIBLING_TO_ACCEPT: "\u65E0\u6CD5\u964D\u7EA7\uFF1A\u672A\u627E\u5230\u53EF\u63A5\u6536\u6B64\u8282\u70B9\u7684\u540C\u7EA7\u8282\u70B9\u3002", + NOTICE_CANNOT_DEMOTE_NO_VALID_SIBLING: "\u65E0\u6CD5\u964D\u7EA7\uFF1A\u6CA1\u6709\u53EF\u9644\u52A0\u7684\u6709\u6548\u540C\u7EA7\u8282\u70B9\u3002", + NOTICE_CANNOT_DEMOTE_CROSS_SIDE_NOT_ALLOWED: "\u65E0\u6CD5\u964D\u7EA7\uFF1A\u4E0D\u5141\u8BB8\u8DE8\u4FA7\u964D\u7EA7\u3002", + NOTICE_CANNOT_MOVE_AUTO_LAYOUT_DISABLED: "\u7981\u7528\u81EA\u52A8\u5E03\u5C40\u65F6\u65E0\u6CD5\u79FB\u52A8\u8282\u70B9\u3002\u8BF7\u5148\u542F\u7528\u81EA\u52A8\u5E03\u5C40\u3002", + NOTICE_BRANCH_WIDTH_MANUAL_OVERRIDE: "\u5206\u652F\u7C97\u7EC6\u672A\u66F4\u65B0\uFF0C\u56E0\u4E3A\u90E8\u5206\u5206\u652F\u7C97\u7EC6\u5DF2\u88AB\u624B\u52A8\u4FEE\u6539\u3002", + NOTICE_CANNOT_CHANGE_MASTER_ROOT: "\u4E3B\u6839\u8282\u70B9\u4E0D\u80FD\u88AB\u8F6C\u6362\u3002", + NOTICE_SUBMAP_ROOT_ADDED: "\u5DF2\u542F\u7528\u5B50\u56FE\u6839\u8282\u70B9\u3002", + NOTICE_SUBMAP_ROOT_REMOVED: "\u5DF2\u79FB\u9664\u5B50\u56FE\u6839\u8282\u70B9\u3002\u5176\u5B50\u8282\u70B9\u5C06\u6309\u4EB2\u4EE3\u6839\u8282\u70B9\u5E03\u5C40\u91CD\u6392\u3002", + CONFIRM_REMOVE_SUBMAP_ROOT: "\u6062\u590D\u4E3A\u666E\u901A\u8282\u70B9\u5417\uFF1F\n\n\u5B83\u5C06\u5931\u53BB\u672C\u5730\u5E03\u5C40\u5143\u6570\u636E\uFF0C\u5176\u5B50\u8282\u70B9\u5C06\u6309\u4EB2\u4EE3\u6839\u8282\u70B9\u5E03\u5C40\u91CD\u6392\u3002", + // Action labels (display only) + ACTION_LABEL_ADD: "\u6DFB\u52A0\u5B50\u8282\u70B9", + ACTION_LABEL_ADD_SIBLING_AFTER: "\u6DFB\u52A0\u540E\u7F6E\u540C\u7EA7\u8282\u70B9", + ACTION_LABEL_ADD_SIBLING_BEFORE: "\u6DFB\u52A0\u524D\u7F6E\u540C\u7EA7\u8282\u70B9", + ACTION_LABEL_ADD_FOLLOW: "\u6DFB\u52A0 + \u8DDF\u968F", + ACTION_LABEL_ADD_FOLLOW_FOCUS: "\u6DFB\u52A0 + \u8DDF\u968F + \u805A\u7126", + ACTION_LABEL_ADD_FOLLOW_ZOOM: "\u6DFB\u52A0 + \u8DDF\u968F + \u7F29\u653E", + ACTION_LABEL_SORT_ORDER: "\u66F4\u6539\u987A\u5E8F/\u63D0\u5347\u8282\u70B9", + ACTION_LABEL_EDIT: "\u7F16\u8F91\u8282\u70B9", + ACTION_LABEL_PIN: "\u9501\u5B9A/\u89E3\u9501", + ACTION_LABEL_BOX: "\u6DFB\u52A0/\u79FB\u9664\u8FB9\u6846", + ACTION_LABEL_TOGGLE_GROUP: "\u7F16\u7EC4/\u89E3\u9664\u7F16\u7EC4\u5355\u5206\u652F", + ACTION_LABEL_COPY: "\u590D\u5236", + ACTION_LABEL_CUT: "\u526A\u5207", + ACTION_LABEL_PASTE: "\u7C98\u8D34", + ACTION_LABEL_IMPORT_OUTLINE: "\u5BFC\u5165\u5927\u7EB2", + ACTION_LABEL_ZOOM: "\u5FAA\u73AF\u7F29\u653E", + ACTION_LABEL_FOCUS: "\u805A\u7126\uFF08\u5E76\u5C45\u4E2D\uFF09\u8282\u70B9", + ACTION_LABEL_NAVIGATE: "\u5BFC\u822A", + ACTION_LABEL_NAVIGATE_ZOOM: "\u5BFC\u822A & \u7F29\u653E", + ACTION_LABEL_NAVIGATE_FOCUS: "\u5BFC\u822A & \u805A\u7126", + ACTION_LABEL_FOLD: "\u6298\u53E0/\u5C55\u5F00\u5206\u652F", + ACTION_LABEL_FOLD_L1: "\u6298\u53E0/\u5C55\u5F00 L1 \u5B50\u8282\u70B9", + ACTION_LABEL_FOLD_ALL: "\u9012\u5F52\u6298\u53E0/\u5C55\u5F00\u5206\u652F", + ACTION_LABEL_DOCK_UNDOCK: "\u505C\u9760/\u53D6\u6D88\u505C\u9760", + ACTION_LABEL_HIDE: "\u505C\u9760 & \u9690\u85CF", + ACTION_LABEL_REARRANGE: "\u91CD\u6392\u5BFC\u56FE", + ACTION_LABEL_TOGGLE_SUBMAP_ROOT: "\u5F00\u59CB/\u7ED3\u675F\u5B50\u56FE\u6839\u8282\u70B9", + ACTION_LABEL_TOGGLE_CHECKBOX: "\u5207\u6362\u590D\u9009\u6846\u72B6\u6001", + ACTION_LABEL_CALENDAR: "\u4EFB\u52A1\u65E5\u5386\u4E0E\u4F18\u5148\u7EA7", + ACTION_LABEL_TOGGLE_EMBED: "\u5207\u6362\u5D4C\u5165/\u94FE\u63A5", + // Tooltips (shared) + PIN_TOOLTIP_PINNED: "\u6B64\u5143\u7D20\u5DF2\u9501\u5B9A\u3002\u70B9\u51FB\u89E3\u9501\u6240\u9009\u5143\u7D20\u7684\u4F4D\u7F6E\u3002", + PIN_TOOLTIP_UNPINNED: "\u6B64\u5143\u7D20\u672A\u9501\u5B9A\u3002\u70B9\u51FB\u9501\u5B9A\u6240\u9009\u5143\u7D20\u7684\u4F4D\u7F6E\u3002", + TOGGLE_GROUP_TOOLTIP_GROUP: "\u7F16\u7EC4\u6B64\u5206\u652F\u3002\u4EC5\u5728\u201C\u5206\u652F\u7F16\u7EC4\u201D\u7981\u7528\u65F6\u53EF\u7528\u3002", + TOGGLE_GROUP_TOOLTIP_UNGROUP: "\u89E3\u9664\u7F16\u7EC4\u6B64\u5206\u652F\u3002\u4EC5\u5728\u201C\u5206\u652F\u7F16\u7EC4\u201D\u7981\u7528\u65F6\u53EF\u7528\u3002", + TOOLTIP_EDIT_NODE: "\u7F16\u8F91\u6240\u9009\u8282\u70B9\u7684\u6587\u672C", + TOOLTIP_PIN_INIT: "\u9501\u5B9A/\u89E3\u9501\u8282\u70B9\u4F4D\u7F6E\u3002\u9501\u5B9A\u7684\u8282\u70B9\u4E0D\u4F1A\u88AB\u81EA\u52A8\u91CD\u6392\u3002", + TOOLTIP_REFRESH: "\u81EA\u52A8\u91CD\u6392\u5BFC\u56FE", + TOOLTIP_DOCK: "\u505C\u9760\u5230\u4FA7\u8FB9\u9762\u677F", + TOOLTIP_UNDOCK: "\u8F6C\u4E3A\u6D6E\u52A8\u7A97\u53E3", + TOOLTIP_ZOOM_CYCLE: "\u5FAA\u73AF\u5207\u6362\u5143\u7D20\u7F29\u653E\u7EA7\u522B", + TOOLTIP_TOGGLE_GROUP_BTN: "\u5207\u6362\u5206\u652F\u7684\u7F16\u7EC4\u72B6\u6001\u3002\u4EC5\u5728\u201C\u5206\u652F\u7F16\u7EC4\u201D\u7981\u7528\u65F6\u53EF\u7528\u3002", + TOOLTIP_TOGGLE_BOX: "\u5207\u6362\u8282\u70B9\u8FB9\u6846", + TOOLTIP_TOGGLE_BOUNDARY: "\u5207\u6362\u5B50\u6811\u8FB9\u754C", + TOOLTIP_TOGGLE_FLOATING_EXTRAS: "\u5207\u6362\u989D\u5916\u63A7\u4EF6", + TOOLTIP_CONFIGURE_PALETTE: "\u4E3A\u5206\u652F\u914D\u7F6E\u81EA\u5B9A\u4E49\u8C03\u8272\u677F", + TOOLTIP_CONFIGURE_LAYOUT: "\u914D\u7F6E\u5E03\u5C40\u8BBE\u7F6E", + TOOLTIP_MOVE_UP: "\u4E0A\u79FB", + TOOLTIP_MOVE_DOWN: "\u4E0B\u79FB", + TOOLTIP_EDIT_COLOR: "\u7F16\u8F91", + TOOLTIP_DELETE_COLOR: "\u5220\u9664", + TOOLTIP_OPEN_PALETTE_PICKER: "\u6253\u5F00\u989C\u8272\u9009\u62E9\u5668", + TOOLTIP_FOLD_BRANCH: "\u6298\u53E0/\u5C55\u5F00\u6240\u9009\u5206\u652F", + TOOLTIP_FOLD_L1_BRANCH: "\u6298\u53E0/\u5C55\u5F00 L1 \u5B50\u8282\u70B9", + TOOLTIP_FOLD_ALL: "\u9012\u5F52\u6298\u53E0/\u5C55\u5F00\u5206\u652F", + TOOLTIP_IMPORT_OUTLINE: "\u4ECE\u94FE\u63A5\u6587\u4EF6\u4E2D\u5BFC\u5165\u5C0F\u6807\u9898\u4F5C\u4E3A\u5B50\u8282\u70B9\u6570\u636E", + TOOLTIP_RESET_TO_DEFAULT: "\u6062\u590D\u9ED8\u8BA4", + TOOLTIP_SUBMAP_ROOT_ADD: "\u4ECE\u6240\u9009\u8282\u70B9\u5F00\u59CB\u5B50\u56FE", + TOOLTIP_SUBMAP_ROOT_REMOVE: "\u5C06\u5B50\u56FE\u6839\u8282\u70B9\u6062\u590D\u4E3A\u666E\u901A\u8282\u70B9", + TOOLTIP_TOGGLE_CHECKBOX: "\u5207\u6362\u4EFB\u52A1\u590D\u9009\u6846\u72B6\u6001", + TOOLTIP_CALENDAR: "\u914D\u7F6E\u4EFB\u52A1\u65E5\u671F\u4E0E\u4F18\u5148\u7EA7", + TOOLTIP_TOGGLE_EMBED: "\u5728\u5D4C\u5165\u548C\u94FE\u63A5\u4E4B\u95F4\u5207\u6362\u8282\u70B9", + // Buttons and labels + DOCK_TITLE: "MindMap Builder", + HELP_SUMMARY: "\u5E2E\u52A9", + INPUT_PLACEHOLDER: "\u8F93\u5165\u6982\u5FF5\u2026 \u8F93\u5165 [[ \u63D2\u5165\u94FE\u63A5", + ONTOLOGY_PLACEHOLDER: "\u672C\u4F53\uFF08\u7BAD\u5934\u6807\u7B7E\uFF09", + BUTTON_COPY: "\u590D\u5236", + BUTTON_CUT: "\u526A\u5207", + BUTTON_PASTE: "\u7C98\u8D34", + TITLE_ADD_SIBLING: `\u4F7F\u7528 {modifier}+Enter \u6DFB\u52A0\u540C\u7EA7\u8282\u70B9`, + TITLE_ADD_FOLLOW: "\u6DFB\u52A0\u5E76\u8DDF\u968F", + TITLE_COPY: "\u590D\u5236\u5206\u652F\u4E3A\u6587\u672C", + TITLE_CUT: "\u526A\u5207\u5206\u652F\u4E3A\u6587\u672C", + TITLE_PASTE: "\u4ECE\u526A\u8D34\u677F\u7C98\u8D34\u5217\u8868", + LABEL_ZOOM_LEVEL: "\u7F29\u653E\u7EA7\u522B", + LABEL_GROWTH_STRATEGY: "\u751F\u957F\u7B56\u7565", + LABEL_FILL_SWEEP: "\u586B\u5145\u626B\u8FC7\u89D2\u5EA6", + DESC_FILL_SWEEP: "\u7ACB\u5373\u5728\u6574\u4E2A\u201C\u6700\u5927\u626B\u8FC7\u89D2\u5EA6\u201D\u8303\u56F4\u5185\u5206\u5E03\u8282\u70B9\uFF0C\u800C\u4E0D\u662F\u968F\u7740\u8282\u70B9\u6570\u91CF\u589E\u52A0\u9010\u6E10\u6269\u5927\u5F27\u5EA6\u3002", + LABEL_ARROW_TYPE: "\u66F2\u7EBF\u8FDE\u63A5", + LABEL_AUTO_LAYOUT: "\u81EA\u52A8\u5E03\u5C40", + LABEL_GROUP_BRANCHES: "\u5206\u652F\u7F16\u7EC4", + LABEL_BOX_CHILD_NODES: "\u4E3A\u5B50\u8282\u70B9\u6DFB\u52A0\u8FB9\u6846", + LABEL_ROUNDED_CORNERS: "\u5706\u89D2", + LABEL_USE_SCENE_STROKE: "\u4F7F\u7528\u573A\u666F\u7EBF\u6761\u6837\u5F0F", + DESC_USE_SCENE_STROKE: "\u4F7F\u7528\u573A\u666F\u4E2D\u6700\u65B0\u7684\u7EBF\u6761\u6837\u5F0F\uFF08\u5B9E\u7EBF\u3001\u865A\u7EBF\u3001\u70B9\u7EBF\uFF09\uFF0C\u5426\u5219\u5206\u652F\u5C06\u59CB\u7EC8\u4F7F\u7528\u5B9E\u7EBF\u3002", + LABEL_BRANCH_SCALE: "\u5206\u652F\u7C97\u7EC6\u6BD4\u4F8B", + LABEL_BASE_WIDTH: "\u57FA\u7840\u7C97\u7EC6", + LABEL_MULTICOLOR_BRANCHES: "\u591A\u8272\u5206\u652F", + LABEL_MAX_WRAP_WIDTH: "\u6700\u5927\u6298\u884C\u5BBD\u5EA6", + LABEL_CENTER_TEXT: "\u6587\u672C\u5C45\u4E2D", + DESC_CENTER_TEXT: "\u5173\u95ED\uFF1A\u6839\u636E\u4F4D\u7F6E\u5DE6/\u53F3\u5BF9\u9F50\uFF1B\u5F00\u542F\uFF1A\u6587\u672C\u5F3A\u5236\u5C45\u4E2D\u3002", + LABEL_FONT_SIZES: "\u5B57\u4F53\u5927\u5C0F", + HOTKEY_SECTION_TITLE: "\u70ED\u952E\u914D\u7F6E", + HOTKEY_HINT: "\u8FD9\u4E9B\u70ED\u952E\u53EF\u80FD\u8986\u76D6 Obsidian \u9ED8\u8BA4\u8BBE\u7F6E\u3002\u70ED\u952E\u4F5C\u7528\u57DF\u9ED8\u8BA4\u4E3A\u5C40\u90E8\uFF08\u2328\uFE0F\uFF09\uFF0C\u4F7F\u7528 \u{1F310}/\u{1F3A8}/\u2328\uFE0F \u5207\u6362\u4F5C\u7528\u57DF\uFF1A\u{1F310} Excalidraw \u6807\u7B7E\u9875\u53EF\u89C1\u5373\u751F\u6548\uFF0C\u{1F3A8} Excalidraw \u805A\u7126\u65F6\u751F\u6548\uFF0C\u2328\uFE0F \u8F93\u5165\u6846\u805A\u7126\u65F6\u751F\u6548\u3002", + RECORD_HOTKEY_PROMPT: "\u6309\u4E0B\u70ED\u952E\u2026", + ARIA_SCOPE_INPUT: "\u5C40\u90E8\uFF08Local\uFF09\uFF1A\u4EC5\u5728\u8F93\u5165\u6846\u805A\u7126\u65F6\u751F\u6548", + ARIA_SCOPE_EXCALIDRAW: "Excalidraw\uFF1A\u8F93\u5165\u6846\u6216 Excalidraw \u805A\u7126\u65F6\u751F\u6548", + ARIA_SCOPE_GLOBAL: "\u5168\u5C40\uFF08Global\uFF09\uFF1A\u5728 Obsidian \u4EFB\u4F55\u4F4D\u7F6E\uFF0CExcalidraw \u53EF\u89C1\u5373\u751F\u6548", + ARIA_RESTORE_DEFAULT: "\u6062\u590D\u9ED8\u8BA4", + ARIA_CUSTOMIZE_HOTKEY: "\u81EA\u5B9A\u4E49\u6B64\u70ED\u952E", + ARIA_OVERRIDE_COMMAND: "\u5C06\u8986\u76D6 Obsidian \u547D\u4EE4\uFF1A\n{command}", + // Palette manager + MODAL_PALETTE_TITLE: "\u5BFC\u56FE\u5206\u652F\u8C03\u8272\u677F", + LABEL_ENABLE_CUSTOM_PALETTE: "\u542F\u7528\u81EA\u5B9A\u4E49\u8C03\u8272\u677F", + DESC_ENABLE_CUSTOM_PALETTE: "\u4F7F\u7528\u4EE5\u4E0B\u989C\u8272\u4EE3\u66FF\u81EA\u52A8\u751F\u6210\u7684\u989C\u8272\u3002", + LABEL_RANDOMIZE_ORDER: "\u968F\u673A\u987A\u5E8F", + DESC_RANDOMIZE_ORDER: "\u968F\u673A\u9009\u62E9\u989C\u8272\u800C\u975E\u6309\u987A\u5E8F\u9009\u62E9\u3002", + HEADING_ADD_NEW_COLOR: "\u6DFB\u52A0\u65B0\u989C\u8272", + HEADING_EDIT_COLOR: "\u7F16\u8F91\u989C\u8272", + LABEL_SELECT_COLOR: "\u9009\u62E9\u989C\u8272", + BUTTON_CANCEL_EDIT: "\u53D6\u6D88\u7F16\u8F91", + BUTTON_ADD_COLOR: "\u6DFB\u52A0\u989C\u8272", + BUTTON_UPDATE_COLOR: "\u66F4\u65B0\u989C\u8272", + // Layout configuration + MODAL_LAYOUT_TITLE: "\u5E03\u5C40\u914D\u7F6E", + // Section Headers + SECTION_GENERAL: "\u5E38\u89C4\u95F4\u8DDD", + SECTION_RADIAL: "\u5F84\u5411\u5E03\u5C40\uFF08\u987A\u65F6\u9488\uFF09", + SECTION_DIRECTIONAL: "\u5B9A\u5411\u5E03\u5C40\uFF08\u5DE6/\u53F3\uFF09", + SECTION_VERTICAL: "\u5782\u76F4\u5BFC\u56FE\uFF08\u4E0A/\u4E0B\uFF09", + SECTION_VISUALS: "\u89C6\u89C9\u5143\u7D20", + SECTION_MANUAL: "\u624B\u52A8\u6A21\u5F0F\u884C\u4E3A", + LAYOUT_RESET: "\u91CD\u7F6E\u6240\u6709\u4E3A\u9ED8\u8BA4\u503C", + LAYOUT_SAVE: "\u4FDD\u5B58\u5E76\u5173\u95ED", + // Radial Strings + RADIAL_ASPECT_RATIO: "\u692D\u5706\u957F\u5BBD\u6BD4", + DESC_RADIAL_ASPECT_RATIO: "\u63A7\u5236\u5F62\u72B6\u3002< 1.0 \u4E3A\u7626\u957F\uFF080.7 \u4E3A\u7EB5\u5411\uFF09\uFF0C1.0 \u4E3A\u6B63\u5706\uFF0C> 1.0 \u4E3A\u5BBD\u6241\uFF08\u6A2A\u5411\uFF09\u3002", + RADIAL_POLE_GAP_BONUS: "\u6781\u70B9\u95F4\u8DDD\u8865\u507F", + DESC_RADIAL_POLE_GAP_BONUS: "\u589E\u52A0\u692D\u5706\u5357\u5317\u4E24\u6781\u533A\u57DF\u5185\u8282\u70B9\u7684\u95F4\u8DDD\u3002\u503C\u8D8A\u5927\uFF0C\u8282\u70B9\u6CBF\u5F27\u7EBF\u63A8\u5F97\u8D8A\u8FDC\u3002", + RADIAL_START_ANGLE: "\u8D77\u59CB\u89D2\u5EA6", + DESC_RADIAL_START_ANGLE: "\u7B2C\u4E00\u4E2A\u8282\u70B9\u51FA\u73B0\u7684\u4F4D\u7F6E\uFF08\u5EA6\u6570\uFF09\u3002270 \u4E3A\u5317\uFF0C0 \u4E3A\u4E1C\uFF0C90 \u4E3A\u5357\u3002", + RADIAL_MAX_SWEEP: "\u6700\u5927\u626B\u8FC7\u89D2\u5EA6", + DESC_RADIAL_MAX_SWEEP: "\u5206\u652F\u53EF\u586B\u5145\u7684\u5F27\u8303\u56F4\u3002360 \u4E3A\u5168\u5706\u3002\u8F83\u5C0F\u7684\u503C\u4F1A\u4F7F\u5706\u4E0D\u5B8C\u6574\u3002", + // Others + GAP_X: "\u6C34\u5E73\u95F4\u8DDD\uFF08Gap X\uFF09", + DESC_LAYOUT_GAP_X: "\u4EB2\u4EE3\u8282\u70B9\u4E0E\u5B50\u8282\u70B9\u4E4B\u95F4\u7684\u6C34\u5E73\u8DDD\u79BB\u3002", + GAP_Y: "\u5782\u76F4\u95F4\u8DDD\uFF08Gap Y\uFF09", + DESC_LAYOUT_GAP_Y: "\u540C\u7EA7\u8282\u70B9\u4E4B\u95F4\u7684\u5782\u76F4\u8DDD\u79BB\u3002\u5F84\u5411\u5E03\u5C40\u4E2D\u7684\u57FA\u7840\u95F4\u8DDD\u3002", + GAP_MULTIPLIER: "\u95F4\u8DDD\u500D\u6570", + DESC_LAYOUT_GAP_MULTIPLIER: "\u53F6\u8282\u70B9\uFF08\u65E0\u5B50\u8282\u70B9\u7684\u8282\u70B9\uFF09\u76F8\u5BF9\u4E8E\u5B57\u4F53\u5927\u5C0F\u7684\u5782\u76F4\u95F4\u8DDD\u3002\u4F4E\uFF1A\u7C7B\u4F3C\u5217\u8868\u5806\u53E0\uFF1B\u9AD8\uFF1A\u6807\u51C6\u6811\u72B6\u95F4\u8DDD\u3002", + DIRECTIONAL_ARC_SPAN_RADIANS: "\u5B9A\u5411\u5F20\u5F00\u5F27\u5EA6\uFF08Arc-span Radians\uFF09", + DESC_LAYOUT_ARC_SPAN: "\u5B50\u8282\u70B9\u6392\u5217\u7684\u66F2\u7387\u3002\u4F4E\uFF080.5\uFF09\uFF1A\u8F83\u5E73\uFF0C\u7C7B\u4F3C\u5217\u8868\u3002\u9AD8\uFF082.0\uFF09\uFF1A\u5F2F\u66F2\u6709\u673A\uFF0C\u4F46\u6709\u91CD\u53E0\u98CE\u9669\u3002", + ROOT_RADIUS_FACTOR: "\u6839\u8282\u70B9\u534A\u5F84\u7CFB\u6570", + DESC_LAYOUT_ROOT_RADIUS: "\u76F8\u5BF9\u4E8E\u6839\u8282\u70B9\u8FB9\u6846\u7684\u500D\u6570\uFF0C\u51B3\u5B9A\u6700\u521D\u7684\u534A\u5F84\u3002", + MIN_RADIUS: "\u6700\u5C0F\u534A\u5F84", + DESC_LAYOUT_MIN_RADIUS: "\u4ECE\u6839\u8282\u70B9\u4E2D\u5FC3\u5230\u7B2C\u4E00\u7EA7\u8282\u70B9\u7684\u6700\u5C0F\u7EDD\u5BF9\u8DDD\u79BB\u3002", + RADIUS_PADDING_PER_NODE: "\u5355\u8282\u70B9\u5F84\u5411\u7A7A\u767D\u8FB9\u8DDD", + DESC_LAYOUT_RADIUS_PADDING: "\u6BCF\u4E2A\u5B50\u8282\u70B9\u989D\u5916\u589E\u52A0\u7684\u534A\u5F84\uFF0C\u4EE5\u9002\u5E94\u5BC6\u96C6\u578B\u5BFC\u56FE\u3002", + GAP_MULTIPLIER_RADIAL: "\u5F84\u5411\u5E03\u5C40\u95F4\u8DDD\u500D\u6570", + DESC_LAYOUT_GAP_RADIAL: "\u5F84\u5411\u5E03\u5C40\u6A21\u5F0F\u4E0B\u7684\u89D2\u5EA6\u95F4\u8DDD\u500D\u6570\u3002", + GAP_MULTIPLIER_DIRECTIONAL: "\u5782\u76F4\u65B9\u5411\u95F4\u8DDD\u500D\u6570", + DESC_LAYOUT_GAP_DIRECTIONAL: "\u5B9A\u5411\u5E03\u5C40\u9876\u5C42\u5206\u652F\u4E4B\u95F4\u7684\u95F4\u8DDD\u500D\u6570\u3002", + INDICATOR_OFFSET: "\u6298\u53E0\u6307\u793A\u7B26\u504F\u79FB", + DESC_LAYOUT_INDICATOR_OFFSET: "\u6298\u53E0\u6307\u793A\u7B26\uFF08\u4E09\u8FDE\u70B9\uFF09\u8DDD\u79BB\u8282\u70B9\u7684\u8DDD\u79BB\u3002", + INDICATOR_OPACITY: "\u6298\u53E0\u6307\u793A\u7B26\u4E0D\u900F\u660E\u5EA6", + DESC_LAYOUT_INDICATOR_OPACITY: "\u6298\u53E0\u6307\u793A\u7B26\u7684\u4E0D\u900F\u660E\u5EA6\uFF080-100\uFF09\u3002", + CONTAINER_PADDING: "\u5BB9\u5668\u5185\u8FB9\u8DDD", + DESC_LAYOUT_CONTAINER_PADDING: "\u4F7F\u7528\u8FB9\u6846\u6837\u5F0F\u65F6\u7684\u5185\u8FB9\u8DDD\u3002", + MAX_SEGMENT_LENGTH: "\u8FB9\u754C\u7EBF\u7CBE\u5EA6", + DESC_LAYOUT_BOUNDARY_LINE_PRECISION: "\u8FB9\u754C\u5E73\u6ED1\u7CBE\u5EA6\u3002\u503C\u8D8A\u5C0F\u8D8A\u7CBE\u7EC6\uFF0830 = \u7CBE\u7EC6\uFF09\uFF0C\u503C\u8D8A\u5927\u8D8A\u7C97\u7565\uFF08200 = \u7C97\u7565\uFF09\u3002", + VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "\u5B50\u6811\u5BBD\u5EA6\u53C2\u4E0E\u5EA6\uFF08\u5355\u4FA7\uFF09", + DESC_VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "\u5782\u76F4\u5BFC\u56FE\u4E2D\uFF0C\u5355\u4FA7\u751F\u957F\u7684\u5B50\u56FE\u5360\u7528\uFF08\u5DE6/\u53F3\uFF09\u6C34\u5E73\u7A7A\u95F4\u7684\u5F3A\u5EA6\u3002\u5F71\u54CD\u7A0B\u5EA6\u9AD8\u3002", + VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "\u5B50\u6811\u5BBD\u5EA6\u53C2\u4E0E\u5EA6\uFF08\u53CC\u4FA7\uFF09", + DESC_VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "\u5782\u76F4\u5BFC\u56FE\u4E2D\uFF0C\u53CC\u4FA7\u751F\u957F\u7684\u5B50\u56FE\u5360\u7528\uFF08\u5DE6\u53F3\uFF09\u6C34\u5E73\u7A7A\u95F4\u7684\u5F3A\u5EA6\u3002\u5F71\u54CD\u7A0B\u5EA6\u9AD8\u3002", + VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "\u5B50\u6811\u5E73\u6ED1\u538B\u7F29\u89E6\u53D1\u500D\u6570", + DESC_VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "\u8D85\u8FC7 Gap Y \u4E58\u4EE5\u8BE5\u500D\u6570\u540E\u5F00\u59CB\u5E73\u6ED1\u538B\u7F29\uFF0C\u907F\u514D\u65B0\u589E\u5B50\u8282\u70B9\u95F4\u8DDD\u7A81\u53D8\u3002\u901A\u5E38\u5728\u5927\u5BFC\u56FE\u4E2D\u66F4\u660E\u663E\u3002", + VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "\u5B50\u6811\u5E73\u6ED1\u538B\u7F29\u4E0B\u9650", + DESC_VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "\u5782\u76F4\u5B50\u6811\u5BBD\u5EA6\u5E73\u6ED1\u538B\u7F29\u5230\u7684\u6700\u5C0F\u503C\u3002\u503C\u8D8A\u5927\u8D8A\u4FDD\u7559\u539F\u5BBD\u5EA6\u3002\u901A\u5E38\u5728\u5927\u5BFC\u56FE\u4E2D\u66F4\u660E\u663E\u3002", + HORIZONTAL_L1_SOFTCAP_THRESHOLD: "L1 \u6C34\u5E73\u65B9\u5411\u8F6F\u4E0A\u9650", + DESC_HORIZONTAL_L1_SOFTCAP_THRESHOLD: "\u8D85\u8FC7\u8BE5 px \u503C\u540E\uFF0C\u4E0A/\u4E0B L1 \u5B50\u6811\u5BBD\u5EA6\u5F00\u59CB\u538B\u7F29\u3002\u5BF9\u5927\u5BFC\u56FE\u5F71\u54CD\u7A0B\u5EA6\u4E2D\u5230\u9AD8\u3002", + HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "L1 \u6C34\u5E73\u65B9\u5411\u538B\u7F29\u4E0B\u9650", + DESC_HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "\u4E0A/\u4E0B L1 \u5BBD\u5EA6\u538B\u7F29\u5230\u7684\u6700\u5C0F\u503C\u3002\u503C\u8D8A\u5927\u8D8A\u4FDD\u7559\u539F\u5BBD\u5EA6\u3002\u8F6F\u4E0A\u9650\u88AB\u8FBE\u5230\uFF08\u3001\u5F00\u59CB\u538B\u7F29\uFF09\u540E\u5F71\u54CD\u4E2D\u7B49\u3002", + VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "\u7D27\u51D1\u4EB2\u5B50\u95F4\u8DDD\u6BD4\u4F8B", + DESC_VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "\u7D27\u51D1\u5782\u76F4\u5B50\u6811\u4E2D\uFF0C\u4EB2\u5B50\u95F4\u8DDD\u4F7F\u7528 Gap X \u4E58\u4EE5\u8BE5\u6BD4\u4F8B\u3002\u6781\u5927\u5F71\u54CD\u89C6\u89C9\u6548\u679C\u3002", + DIRECTIONAL_CROSS_AXIS_RATIO: "\u6B63\u4EA4\u8F74\u4E4B\u6BD4", + DESC_DIRECTIONAL_CROSS_AXIS_RATIO: "\u4E0E\u5782\u76F4\u4E8E\u751F\u957F\u65B9\u5411\u7684\u8F74\uFF08Cross-axis\uFF09\u7684\u534A\u5F84\u4E4B\u6BD4\uFF080.2 = \u6241\uFF0C1.0 = \u5706\uFF09\u3002\u6781\u5927\u5F71\u54CD L1 \u5C55\u5F00\u5F62\u6001\u3002", + MANUAL_GAP_MULTIPLIER: "\u624B\u52A8\u5E03\u5C40\u95F4\u8DDD\u500D\u6570", + DESC_LAYOUT_MANUAL_GAP: "\u7981\u7528\u81EA\u52A8\u5E03\u5C40\u65F6\u6DFB\u52A0\u8282\u70B9\u7684\u95F4\u8DDD\u500D\u6570\u3002", + MANUAL_JITTER_RANGE: "\u624B\u52A8\u5E03\u5C40\u6296\u52A8\u8303\u56F4", + DESC_LAYOUT_MANUAL_JITTER: "\u7981\u7528\u81EA\u52A8\u5E03\u5C40\u65F6\u6DFB\u52A0\u8282\u70B9\u7684\u968F\u673A\u4F4D\u7F6E\u504F\u79FB\u3002", + CALENDAR_DATE_INDEX: "\u7B2C {index} \u4E2A\u65E5\u671F\uFF0C\u5171 {total} \u4E2A", + CALENDAR_DATE_LABEL: "\u65E5\u671F", + CALENDAR_DATE_TYPE: "\u65E5\u671F\u7C7B\u578B", + CALENDAR_PRIORITY: "\u4F18\u5148\u7EA7", + CALENDAR_RECURRENCE: "\u91CD\u590D", + CALENDAR_RECURRENCE_PLACEHOLDER: "every day", + CALENDAR_RECURRENCE_DESC: `\u4F8B\u5982\uFF0C'every day'\uFF0C'every 2 weeks'
Tasks \u63D2\u4EF6\u91CD\u590D\u4EFB\u52A1\u6587\u6863`, + CALENDAR_INJECT_LINK: "\u63D2\u5165\u8282\u70B9\u94FE\u63A5", + CALENDAR_INJECT_LINK_DESC: "\u5728\u4EFB\u52A1\u672B\u5C3E\u6DFB\u52A0\u6307\u5411\u8BE5\u8282\u70B9\u7684\u94FE\u63A5\u3002", + CALENDAR_ALIAS_PLACEHOLDER: "\u522B\u540D", + CALENDAR_BTN_CANCEL: "\u53D6\u6D88", + CALENDAR_BTN_TASK_ONLY: "\u4EC5\u4EFB\u52A1", + CALENDAR_BTN_ADD_DATE_TASK: "\u6DFB\u52A0\u65E5\u671F\u548C\u4EFB\u52A1", + CALENDAR_PRIORITY_HIGHEST: "\u6700\u9AD8", + CALENDAR_PRIORITY_HIGH: "\u9AD8", + CALENDAR_PRIORITY_MEDIUM: "\u4E2D", + CALENDAR_PRIORITY_NORMAL: "\u666E\u901A", + CALENDAR_PRIORITY_LOW: "\u4F4E", + CALENDAR_PRIORITY_LOWEST: "\u6700\u4F4E", + CALENDAR_DATETYPE_DUE: "\u622A\u6B62", + CALENDAR_DATETYPE_START: "\u5F00\u59CB", + CALENDAR_DATETYPE_SCHEDULED: "\u8BA1\u5212", + CALENDAR_DATETYPE_CREATED: "\u521B\u5EFA", + CALENDAR_DATETYPE_DONE: "\u5B8C\u6210", + CALENDAR_DATETYPE_CANCELLED: "\u53D6\u6D88", + // Presets + PRESET_LABEL: "\u9884\u8BBE", + PRESET_UNSAVED: "\u81EA\u5B9A\u4E49 / \u672A\u5173\u8054", + PRESET_BTN_SAVE: "\u4FDD\u5B58\u9884\u8BBE", + PRESET_BTN_DELETE: "\u5220\u9664\u9884\u8BBE", + PRESET_BTN_NEW: "\u65B0\u5EFA\u9884\u8BBE", + PRESET_BTN_APPLY: "\u5E94\u7528\u9884\u8BBE\u5230\u5BFC\u56FE", + PRESET_WARNING_MODIFIED: "\u5BFC\u56FE\u8BBE\u7F6E\u4E0E\u9884\u8BBE\u4E0D\u7B26\u3002", + PROMPT_NEW_PRESET_NAME: "\u65B0\u9884\u8BBE\u540D\u79F0\uFF1A", + NOTICE_PRESET_DELETED: "\u9884\u8BBE\u5DF2\u5220\u9664\u3002", + NOTICE_PRESET_SAVED: "\u9884\u8BBE\u5DF2\u4FDD\u5B58\u3002", + NOTICE_PRESET_APPLIED: "\u9884\u8BBE\u5DF2\u5E94\u7528\u3002", + // Misc + INPUT_TITLE_PASTE_ROOT: "MindMap Builder \u7C98\u8D34", + INSTRUCTIONS: "> [!Tip]\n>\u{1F680} \u60F3\u8981\u8FDB\u9636\uFF1F\u6B22\u8FCE\u53C2\u52A0\u5B98\u65B9 [MindMap Builder \u8BFE\u7A0B](https://www.visual-thinking-workshop.com/mindmap)\uFF01\n\n- **ENTER**\uFF1A\u6DFB\u52A0\u5B50\u8282\u70B9\u5E76\u4FDD\u7559\u5728\u5F53\u524D\u4EB2\u4EE3\u8282\u70B9\u4E0A\uFF0C\u65B9\u4FBF\u5FEB\u901F\u8F93\u5165\u3002\u82E5\u8F93\u5165\u6846\u4E3A\u7A7A\u65F6\u6309\u56DE\u8F66\uFF0C\u7126\u70B9\u5C06\u79FB\u52A8\u5230\u6700\u65B0\u6DFB\u52A0\u7684\u5B50\u8282\u70B9\u3002\u8FDE\u7EED\u6309\u56DE\u8F66\u5C06\u5728\u8BE5\u8282\u70B9\u7684\u540C\u7EA7\u8282\u70B9\u95F4\u5FAA\u73AF\u5207\u6362\u3002\n- **\u70ED\u952E**\uFF1A\u89C1\u4FA7\u8FB9\u9762\u677F\u5E95\u90E8\u7684\u914D\u7F6E\u9009\u9879\u3002\n- **\u505C\u9760/\u53D6\u6D88\u505C\u9760**\uFF1A\u4F7F\u7528\u6309\u94AE\u6216\u914D\u7F6E\u597D\u7684\u70ED\u952E\u6765\u5207\u6362\u8F93\u5165\u6846\u4F4D\u7F6E\u3002\n- **\u6298\u53E0**\uFF1A\u4EC5\u5728\u8F93\u5165\u6846\u505C\u9760\u65F6\u663E\u793A\u6309\u94AE\uFF1B\u53D6\u6D88\u505C\u9760\u65F6\u8BF7\u4F7F\u7528\u70ED\u952E\u3002\n- **ESC**\uFF1A\u5C06\u6D6E\u52A8\u8F93\u5165\u6846\u505C\u9760\uFF0C\u4F46\u4E0D\u6FC0\u6D3B\u4FA7\u8FB9\u9762\u677F\u3002\n- **\u7740\u8272**\uFF1A\u9876\u5C42\u5206\u652F\u62E5\u6709\u72EC\u7ACB\u989C\u8272\uFF08\u591A\u8272\u6A21\u5F0F\uFF09\uFF0C\u540E\u4EE3\u8282\u70B9\u7EE7\u627F\u4EB2\u4EE3\u989C\u8272\u3002\n- **\u7F16\u7EC4**\uFF1A\n - \u542F\u7528\u201C\u5206\u652F\u7F16\u7EC4\u201D\u5C06\u9012\u5F52\u5730\u7F16\u7EC4\u5B50\u6811\uFF0C\u4ECE\u53F6\u8282\u70B9\u5230\u9876\u5C42\u5206\u652F\u3002\n- **\u590D\u5236/\u7C98\u8D34**\uFF1A\u5BFC\u51FA/\u5BFC\u5165\u542B\u7F29\u8FDB\u7684 Markdown \u5217\u8868\u3002\n\n\u{1F60D} \u5982\u679C\u4F60\u89C9\u5F97\u8FD9\u4E2A\u811A\u672C\u6709\u7528\uFF0C\u6B22\u8FCE [\u8BF7\u6211\u559D\u676F\u5496\u5561 \u2615](https://ko-fi.com/zsolt)\u3002" + }; + + // src/scripts/mindmap-builder/lang/zh-tw.ts + var zhTw = { + // Notices + NOTICE_SELECT_NODE_TO_COPY: "\u8ACB\u9078\u64C7\u8981\u8907\u88FD\u7684\u7BC0\u9EDE\u3002", + NOTICE_MAP_CUT: "\u5C0E\u5716\u5DF2\u526A\u4E0B\u5230\u526A\u8CBC\u7C3F\u3002", + NOTICE_BRANCH_CUT: "\u5206\u652F\u5DF2\u526A\u4E0B\u5230\u526A\u8CBC\u7C3F\u3002", + NOTICE_MAP_COPIED: "\u5C0E\u5716\u5DF2\u8907\u88FD\u70BA Markdown \u683C\u5F0F\u3002", + NOTICE_BRANCH_COPIED: "\u5206\u652F\u5DF2\u8907\u88FD\u70BA\u5217\u8868\u683C\u5F0F\u3002", + NOTICE_CLIPBOARD_EMPTY: "\u526A\u8CBC\u7C3F\u70BA\u7A7A\u3002", + NOTICE_PASTE_ABORTED: "\u8CBC\u4E0A\u4E2D\u6B62\u3002\u526A\u8CBC\u7C3F\u5167\u5BB9\u975E Markdown \u5217\u8868\u6216\u6A19\u984C\u3002", + NOTICE_NO_LIST: "\u526A\u8CBC\u7C3F\u4E2D\u672A\u767C\u73FE\u6709\u6548\u7684 Markdown \u5217\u8868\u3002", + NOTICE_PASTE_START: "\u6B63\u5728\u8CBC\u4E0A\uFF0C\u8ACB\u7A0D\u5019\uFF0C\u53EF\u80FD\u9700\u8981\u4E00\u4E9B\u6642\u9593\u2026", + NOTICE_PASTE_COMPLETE: "\u8CBC\u4E0A\u5B8C\u6210\u3002", + NOTICE_ACTION_REQUIRES_ARROWS: "\u6B64\u64CD\u4F5C\u9700\u8981\u65B9\u5411\u9375\u3002\u50C5\u53EF\u4FEE\u6539\u4FEE\u98FE\u9375\u3002", + NOTICE_CONFLICT_WITH_ACTION: "\u8207\u201C{action}\u201D\u64CD\u4F5C\u885D\u7A81", + NOTICE_OBSIDIAN_HOTKEY_CONFLICT: "\u26A0\uFE0F Obsidian \u71B1\u9375\u885D\u7A81\uFF01\n\n\u6B64\u6309\u9375\u5C07\u8986\u84CB\uFF1A\n\u201C{command}\u201D", + NOTICE_GLOBAL_HOTKEY_CONFLICT: "\u26A0\uFE0F \u5168\u57DF\u6027\u71B1\u9375\u885D\u7A81\uFF01\n\n\u6B64\u6309\u9375\u5C07\u8986\u84CB\uFF1A\n\u201C{command}\u201D", + NOTICE_NO_HEADINGS: "\u9023\u7D50\u6A94\u6848\u4E2D\u672A\u767C\u73FE\u5C0F\u6A19\u984C\u3002", + NOTICE_CANNOT_EDIT_MULTILINE: "\u7121\u6CD5\u76F4\u63A5\u7DE8\u8F2F\u591A\u884C\u7BC0\u9EDE\u3002\n\u8ACB\u5728 Excalidraw \u4E2D\u96D9\u64CA\u5143\u7D20\u9032\u884C\u7DE8\u8F2F\uFF0C\u7136\u5F8C\u57F7\u884C\u201C\u81EA\u52D5\u91CD\u6392\u5C0E\u5716\u201D\u4F86\u66F4\u65B0\u4F48\u5C40\u3002", + NOTICE_CANNOT_MOVE_PINNED: "\u7121\u6CD5\u79FB\u52D5\u5DF2\u9396\u5B9A\u7684\u7BC0\u9EDE\u3002\u8ACB\u5148\u89E3\u9396\u3002", + NOTICE_CANNOT_MOVE_ROOT: "\u7121\u6CD5\u79FB\u52D5\u6839\u7BC0\u9EDE\u3002", + NOTICE_CANNOT_PRMOTE_L1: "\u7121\u6CD5\u63D0\u5347 1 \u7D1A\u7BC0\u9EDE\u3002", + NOTICE_CANNOT_DEMOTE: "\u7121\u6CD5\u964D\u7D1A\u7BC0\u9EDE\u3002\u6C92\u6709\u53EF\u4F9D\u9644\u7684\u524D\u7F6E\u540C\u7D1A\u7BC0\u9EDE\u3002", + NOTICE_SELECT_NODE_CONTAINING_LINK: "\u8ACB\u9078\u64C7\u5305\u542B\u9023\u7D50\u7684\u7BC0\u9EDE\u3002", + NOTICE_CANNOT_DEMOTE_NO_SIBLING_TO_ACCEPT: "\u7121\u6CD5\u964D\u7D1A\uFF1A\u672A\u627E\u5230\u53EF\u63A5\u6536\u6B64\u7BC0\u9EDE\u7684\u540C\u7D1A\u7BC0\u9EDE\u3002", + NOTICE_CANNOT_DEMOTE_NO_VALID_SIBLING: "\u7121\u6CD5\u964D\u7D1A\uFF1A\u6C92\u6709\u53EF\u9644\u52A0\u7684\u6709\u6548\u540C\u7D1A\u7BC0\u9EDE\u3002", + NOTICE_CANNOT_DEMOTE_CROSS_SIDE_NOT_ALLOWED: "\u7121\u6CD5\u964D\u7D1A\uFF1A\u4E0D\u5141\u8A31\u8DE8\u5074\u964D\u7D1A\u3002", + NOTICE_CANNOT_MOVE_AUTO_LAYOUT_DISABLED: "\u505C\u7528\u81EA\u52D5\u4F48\u5C40\u6642\u7121\u6CD5\u79FB\u52D5\u7BC0\u9EDE\u3002\u8ACB\u5148\u555F\u7528\u81EA\u52D5\u4F48\u5C40\u3002", + NOTICE_BRANCH_WIDTH_MANUAL_OVERRIDE: "\u5206\u652F\u7C97\u7D30\u672A\u66F4\u65B0\uFF0C\u56E0\u70BA\u90E8\u5206\u5206\u652F\u7C97\u7D30\u5DF2\u88AB\u624B\u52D5\u4FEE\u6539\u3002", + NOTICE_CANNOT_CHANGE_MASTER_ROOT: "\u4E3B\u6839\u7BC0\u9EDE\u4E0D\u80FD\u88AB\u8F49\u63DB\u3002", + NOTICE_SUBMAP_ROOT_ADDED: "\u5DF2\u555F\u7528\u5B50\u5716\u6839\u7BC0\u9EDE\u3002", + NOTICE_SUBMAP_ROOT_REMOVED: "\u5DF2\u79FB\u9664\u5B50\u5716\u6839\u7BC0\u9EDE\u3002\u5176\u5B50\u7BC0\u9EDE\u5C07\u6309\u89AA\u4EE3\u6839\u7BC0\u9EDE\u4F48\u5C40\u91CD\u6392\u3002", + CONFIRM_REMOVE_SUBMAP_ROOT: "\u6062\u5FA9\u70BA\u666E\u901A\u7BC0\u9EDE\u55CE\uFF1F\n\n\u5B83\u5C07\u5931\u53BB\u672C\u5730\u4F48\u5C40\u5143\u8CC7\u6599\uFF0C\u5176\u5B50\u7BC0\u9EDE\u5C07\u6309\u89AA\u4EE3\u6839\u7BC0\u9EDE\u4F48\u5C40\u91CD\u6392\u3002", + // Action labels (display only) + ACTION_LABEL_ADD: "\u65B0\u589E\u5B50\u7BC0\u9EDE", + ACTION_LABEL_ADD_SIBLING_AFTER: "\u65B0\u589E\u5F8C\u7F6E\u540C\u7D1A\u7BC0\u9EDE", + ACTION_LABEL_ADD_SIBLING_BEFORE: "\u65B0\u589E\u524D\u7F6E\u540C\u7D1A\u7BC0\u9EDE", + ACTION_LABEL_ADD_FOLLOW: "\u65B0\u589E + \u8DDF\u96A8", + ACTION_LABEL_ADD_FOLLOW_FOCUS: "\u65B0\u589E + \u8DDF\u96A8 + \u805A\u7126", + ACTION_LABEL_ADD_FOLLOW_ZOOM: "\u65B0\u589E + \u8DDF\u96A8 + \u7E2E\u653E", + ACTION_LABEL_SORT_ORDER: "\u66F4\u6539\u9806\u5E8F/\u63D0\u5347\u7BC0\u9EDE", + ACTION_LABEL_EDIT: "\u7DE8\u8F2F\u7BC0\u9EDE", + ACTION_LABEL_PIN: "\u9396\u5B9A/\u89E3\u9396", + ACTION_LABEL_BOX: "\u65B0\u589E/\u79FB\u9664\u908A\u6846", + ACTION_LABEL_TOGGLE_GROUP: "\u7DE8\u7D44/\u89E3\u9664\u7DE8\u7D44\u55AE\u5206\u652F", + ACTION_LABEL_COPY: "\u8907\u88FD", + ACTION_LABEL_CUT: "\u526A\u4E0B", + ACTION_LABEL_PASTE: "\u8CBC\u4E0A", + ACTION_LABEL_IMPORT_OUTLINE: "\u532F\u5165\u5927\u7DB1", + ACTION_LABEL_ZOOM: "\u8FF4\u5708\u7E2E\u653E", + ACTION_LABEL_FOCUS: "\u805A\u7126\uFF08\u4E26\u5C45\u4E2D\uFF09\u7BC0\u9EDE", + ACTION_LABEL_NAVIGATE: "\u5C0E\u822A", + ACTION_LABEL_NAVIGATE_ZOOM: "\u5C0E\u822A & \u7E2E\u653E", + ACTION_LABEL_NAVIGATE_FOCUS: "\u5C0E\u822A & \u805A\u7126", + ACTION_LABEL_FOLD: "\u647A\u758A/\u5C55\u958B\u5206\u652F", + ACTION_LABEL_FOLD_L1: "\u647A\u758A/\u5C55\u958B L1 \u5B50\u7BC0\u9EDE", + ACTION_LABEL_FOLD_ALL: "\u905E\u8FF4\u647A\u758A/\u5C55\u958B\u5206\u652F", + ACTION_LABEL_DOCK_UNDOCK: "\u505C\u9760/\u53D6\u6D88\u505C\u9760", + ACTION_LABEL_HIDE: "\u505C\u9760 & \u96B1\u85CF", + ACTION_LABEL_REARRANGE: "\u91CD\u6392\u5C0E\u5716", + ACTION_LABEL_TOGGLE_SUBMAP_ROOT: "\u958B\u59CB/\u7D50\u675F\u5B50\u5716\u6839\u7BC0\u9EDE", + ACTION_LABEL_TOGGLE_CHECKBOX: "\u5207\u63DB\u8907\u9078\u6846\u72C0\u614B", + ACTION_LABEL_CALENDAR: "\u4EFB\u52D9\u65E5\u66C6\u8207\u512A\u5148\u7D1A", + ACTION_LABEL_TOGGLE_EMBED: "\u5207\u63DB\u5D4C\u5165/\u9023\u7D50", + // Tooltips (shared) + PIN_TOOLTIP_PINNED: "\u6B64\u5143\u7D20\u5DF2\u9396\u5B9A\u3002\u9EDE\u9078\u89E3\u9396\u6240\u9078\u5143\u7D20\u7684\u4F4D\u7F6E\u3002", + PIN_TOOLTIP_UNPINNED: "\u6B64\u5143\u7D20\u672A\u9396\u5B9A\u3002\u9EDE\u9078\u9396\u5B9A\u6240\u9078\u5143\u7D20\u7684\u4F4D\u7F6E\u3002", + TOGGLE_GROUP_TOOLTIP_GROUP: "\u7DE8\u7D44\u6B64\u5206\u652F\u3002\u50C5\u5728\u201C\u5206\u652F\u7DE8\u7D44\u201D\u505C\u7528\u6642\u53EF\u7528\u3002", + TOGGLE_GROUP_TOOLTIP_UNGROUP: "\u89E3\u9664\u7DE8\u7D44\u6B64\u5206\u652F\u3002\u50C5\u5728\u201C\u5206\u652F\u7DE8\u7D44\u201D\u505C\u7528\u6642\u53EF\u7528\u3002", + TOOLTIP_EDIT_NODE: "\u7DE8\u8F2F\u6240\u9078\u7BC0\u9EDE\u7684\u6587\u5B57", + TOOLTIP_PIN_INIT: "\u9396\u5B9A/\u89E3\u9396\u7BC0\u9EDE\u4F4D\u7F6E\u3002\u9396\u5B9A\u7684\u7BC0\u9EDE\u4E0D\u6703\u88AB\u81EA\u52D5\u91CD\u6392\u3002", + TOOLTIP_REFRESH: "\u81EA\u52D5\u91CD\u6392\u5C0E\u5716", + TOOLTIP_DOCK: "\u505C\u9760\u5230\u5074\u908A\u9762\u677F", + TOOLTIP_UNDOCK: "\u8F49\u70BA\u6D6E\u52D5\u8996\u7A97", + TOOLTIP_ZOOM_CYCLE: "\u8FF4\u5708\u5207\u63DB\u5143\u7D20\u7E2E\u653E\u7D1A\u5225", + TOOLTIP_TOGGLE_GROUP_BTN: "\u5207\u63DB\u5206\u652F\u7684\u7DE8\u7D44\u72C0\u614B\u3002\u50C5\u5728\u201C\u5206\u652F\u7DE8\u7D44\u201D\u505C\u7528\u6642\u53EF\u7528\u3002", + TOOLTIP_TOGGLE_BOX: "\u5207\u63DB\u7BC0\u9EDE\u908A\u6846", + TOOLTIP_TOGGLE_BOUNDARY: "\u5207\u63DB\u5B50\u6A39\u908A\u754C", + TOOLTIP_TOGGLE_FLOATING_EXTRAS: "\u5207\u63DB\u984D\u5916\u63A7\u5236\u5143\u4EF6", + TOOLTIP_CONFIGURE_PALETTE: "\u70BA\u5206\u652F\u914D\u7F6E\u81EA\u5B9A\u7FA9\u8ABF\u8272\u76E4", + TOOLTIP_CONFIGURE_LAYOUT: "\u914D\u7F6E\u4F48\u5C40\u8A2D\u5B9A", + TOOLTIP_MOVE_UP: "\u4E0A\u79FB", + TOOLTIP_MOVE_DOWN: "\u4E0B\u79FB", + TOOLTIP_EDIT_COLOR: "\u7DE8\u8F2F", + TOOLTIP_DELETE_COLOR: "\u522A\u9664", + TOOLTIP_OPEN_PALETTE_PICKER: "\u958B\u555F\u984F\u8272\u9078\u64C7\u5668", + TOOLTIP_FOLD_BRANCH: "\u647A\u758A/\u5C55\u958B\u6240\u9078\u5206\u652F", + TOOLTIP_FOLD_L1_BRANCH: "\u647A\u758A/\u5C55\u958B L1 \u5B50\u7BC0\u9EDE", + TOOLTIP_FOLD_ALL: "\u905E\u8FF4\u647A\u758A/\u5C55\u958B\u5206\u652F", + TOOLTIP_IMPORT_OUTLINE: "\u5F9E\u9023\u7D50\u6A94\u6848\u4E2D\u532F\u5165\u5C0F\u6A19\u984C\u4F5C\u70BA\u5B50\u7BC0\u9EDE\u8CC7\u6599", + TOOLTIP_RESET_TO_DEFAULT: "\u6062\u5FA9\u9810\u8A2D", + TOOLTIP_SUBMAP_ROOT_ADD: "\u5F9E\u6240\u9078\u7BC0\u9EDE\u958B\u59CB\u5B50\u5716", + TOOLTIP_SUBMAP_ROOT_REMOVE: "\u5C07\u5B50\u5716\u6839\u7BC0\u9EDE\u6062\u5FA9\u70BA\u666E\u901A\u7BC0\u9EDE", + TOOLTIP_TOGGLE_CHECKBOX: "\u5207\u63DB\u4EFB\u52D9\u8907\u9078\u6846\u72C0\u614B", + TOOLTIP_CALENDAR: "\u914D\u7F6E\u4EFB\u52D9\u65E5\u671F\u8207\u512A\u5148\u7D1A", + TOOLTIP_TOGGLE_EMBED: "\u5728\u5D4C\u5165\u548C\u9023\u7D50\u4E4B\u9593\u5207\u63DB\u7BC0\u9EDE", + // Buttons and labels + DOCK_TITLE: "MindMap Builder", + HELP_SUMMARY: "\u5E6B\u52A9", + INPUT_PLACEHOLDER: "\u8F38\u5165\u6982\u5FF5\u2026 \u8F38\u5165 [[ \u63D2\u5165\u9023\u7D50", + ONTOLOGY_PLACEHOLDER: "\u672C\u9AD4\uFF08\u7BAD\u982D\u6A19\u7C64\uFF09", + BUTTON_COPY: "\u8907\u88FD", + BUTTON_CUT: "\u526A\u4E0B", + BUTTON_PASTE: "\u8CBC\u4E0A", + TITLE_ADD_SIBLING: `\u4F7F\u7528 {modifier}+Enter \u65B0\u589E\u540C\u7D1A\u7BC0\u9EDE`, + TITLE_ADD_FOLLOW: "\u65B0\u589E\u4E26\u8DDF\u96A8", + TITLE_COPY: "\u8907\u88FD\u5206\u652F\u70BA\u6587\u5B57", + TITLE_CUT: "\u526A\u4E0B\u5206\u652F\u70BA\u6587\u5B57", + TITLE_PASTE: "\u5F9E\u526A\u8CBC\u7C3F\u8CBC\u4E0A\u5217\u8868", + LABEL_ZOOM_LEVEL: "\u7E2E\u653E\u7D1A\u5225", + LABEL_GROWTH_STRATEGY: "\u751F\u9577\u7B56\u7565", + LABEL_FILL_SWEEP: "\u586B\u5145\u6383\u904E\u89D2\u5EA6", + DESC_FILL_SWEEP: "\u7ACB\u5373\u5728\u6574\u500B\u201C\u6700\u5927\u6383\u904E\u89D2\u5EA6\u201D\u7BC4\u570D\u5167\u5206\u4F48\u7BC0\u9EDE\uFF0C\u800C\u4E0D\u662F\u96A8\u8457\u7BC0\u9EDE\u6578\u91CF\u589E\u52A0\u9010\u6F38\u64F4\u5927\u5F27\u5EA6\u3002", + LABEL_ARROW_TYPE: "\u66F2\u7DDA\u9023\u7DDA", + LABEL_AUTO_LAYOUT: "\u81EA\u52D5\u4F48\u5C40", + LABEL_GROUP_BRANCHES: "\u5206\u652F\u7DE8\u7D44", + LABEL_BOX_CHILD_NODES: "\u70BA\u5B50\u7BC0\u9EDE\u65B0\u589E\u908A\u6846", + LABEL_ROUNDED_CORNERS: "\u5713\u89D2", + LABEL_USE_SCENE_STROKE: "\u4F7F\u7528\u5834\u666F\u7DDA\u689D\u6A23\u5F0F", + DESC_USE_SCENE_STROKE: "\u4F7F\u7528\u5834\u666F\u4E2D\u6700\u65B0\u7684\u7DDA\u689D\u6A23\u5F0F\uFF08\u5BE6\u7DDA\u3001\u865B\u7DDA\u3001\u9EDE\u7DDA\uFF09\uFF0C\u5426\u5247\u5206\u652F\u5C07\u59CB\u7D42\u4F7F\u7528\u5BE6\u7DDA\u3002", + LABEL_BRANCH_SCALE: "\u5206\u652F\u7C97\u7D30\u6BD4\u4F8B", + LABEL_BASE_WIDTH: "\u57FA\u790E\u7C97\u7D30", + LABEL_MULTICOLOR_BRANCHES: "\u591A\u8272\u5206\u652F", + LABEL_MAX_WRAP_WIDTH: "\u6700\u5927\u6298\u884C\u5BEC\u5EA6", + LABEL_CENTER_TEXT: "\u6587\u5B57\u5C45\u4E2D", + DESC_CENTER_TEXT: "\u95DC\u9589\uFF1A\u6839\u64DA\u4F4D\u7F6E\u5DE6/\u53F3\u5C0D\u9F4A\uFF1B\u958B\u555F\uFF1A\u6587\u5B57\u5F37\u5236\u5C45\u4E2D\u3002", + LABEL_FONT_SIZES: "\u5B57\u578B\u5927\u5C0F", + HOTKEY_SECTION_TITLE: "\u71B1\u9375\u914D\u7F6E", + HOTKEY_HINT: "\u9019\u4E9B\u71B1\u9375\u53EF\u80FD\u8986\u84CB Obsidian \u9810\u8A2D\u8A2D\u5B9A\u3002\u71B1\u9375\u4F5C\u7528\u57DF\u9810\u8A2D\u70BA\u5340\u57DF\u6027\uFF08\u2328\uFE0F\uFF09\uFF0C\u4F7F\u7528 \u{1F310}/\u{1F3A8}/\u2328\uFE0F \u5207\u63DB\u4F5C\u7528\u57DF\uFF1A\u{1F310} Excalidraw \u6A19\u7C64\u9801\u53EF\u898B\u5373\u751F\u6548\uFF0C\u{1F3A8} Excalidraw \u805A\u7126\u6642\u751F\u6548\uFF0C\u2328\uFE0F \u8F38\u5165\u6846\u805A\u7126\u6642\u751F\u6548\u3002", + RECORD_HOTKEY_PROMPT: "\u6309\u4E0B\u71B1\u9375\u2026", + ARIA_SCOPE_INPUT: "\u5340\u57DF\u6027\uFF08Local\uFF09\uFF1A\u50C5\u5728\u8F38\u5165\u6846\u805A\u7126\u6642\u751F\u6548", + ARIA_SCOPE_EXCALIDRAW: "Excalidraw\uFF1A\u8F38\u5165\u6846\u6216 Excalidraw \u805A\u7126\u6642\u751F\u6548", + ARIA_SCOPE_GLOBAL: "\u5168\u57DF\u6027\uFF08Global\uFF09\uFF1A\u5728 Obsidian \u4EFB\u4F55\u4F4D\u7F6E\uFF0CExcalidraw \u53EF\u898B\u5373\u751F\u6548", + ARIA_RESTORE_DEFAULT: "\u6062\u5FA9\u9810\u8A2D", + ARIA_CUSTOMIZE_HOTKEY: "\u81EA\u5B9A\u7FA9\u6B64\u71B1\u9375", + ARIA_OVERRIDE_COMMAND: "\u5C07\u8986\u84CB Obsidian \u547D\u4EE4\uFF1A\n{command}", + // Palette manager + MODAL_PALETTE_TITLE: "\u5C0E\u5716\u5206\u652F\u8ABF\u8272\u76E4", + LABEL_ENABLE_CUSTOM_PALETTE: "\u555F\u7528\u81EA\u5B9A\u7FA9\u8ABF\u8272\u76E4", + DESC_ENABLE_CUSTOM_PALETTE: "\u4F7F\u7528\u4EE5\u4E0B\u984F\u8272\u4EE3\u66FF\u81EA\u52D5\u751F\u6210\u7684\u984F\u8272\u3002", + LABEL_RANDOMIZE_ORDER: "\u96A8\u6A5F\u9806\u5E8F", + DESC_RANDOMIZE_ORDER: "\u96A8\u6A5F\u9078\u64C7\u984F\u8272\u800C\u975E\u6309\u9806\u5E8F\u9078\u64C7\u3002", + HEADING_ADD_NEW_COLOR: "\u65B0\u589E\u65B0\u984F\u8272", + HEADING_EDIT_COLOR: "\u7DE8\u8F2F\u984F\u8272", + LABEL_SELECT_COLOR: "\u9078\u64C7\u984F\u8272", + BUTTON_CANCEL_EDIT: "\u53D6\u6D88\u7DE8\u8F2F", + BUTTON_ADD_COLOR: "\u65B0\u589E\u984F\u8272", + BUTTON_UPDATE_COLOR: "\u66F4\u65B0\u984F\u8272", + // Layout configuration + MODAL_LAYOUT_TITLE: "\u4F48\u5C40\u914D\u7F6E", + // Section Headers + SECTION_GENERAL: "\u5E38\u898F\u9593\u8DDD", + SECTION_RADIAL: "\u5F91\u5411\u4F48\u5C40\uFF08\u9806\u6642\u91DD\uFF09", + SECTION_DIRECTIONAL: "\u5B9A\u5411\u4F48\u5C40\uFF08\u5DE6/\u53F3\uFF09", + SECTION_VERTICAL: "\u5782\u76F4\u5C0E\u5716\uFF08\u4E0A/\u4E0B\uFF09", + SECTION_VISUALS: "\u8996\u89BA\u5143\u7D20", + SECTION_MANUAL: "\u624B\u52D5\u6A21\u5F0F\u884C\u70BA", + LAYOUT_RESET: "\u91CD\u7F6E\u6240\u6709\u70BA\u9810\u8A2D\u503C", + LAYOUT_SAVE: "\u5132\u5B58\u4E26\u95DC\u9589", + // Radial Strings + RADIAL_ASPECT_RATIO: "\u6A62\u5713\u9577\u5BEC\u6BD4", + DESC_RADIAL_ASPECT_RATIO: "\u63A7\u5236\u5F62\u72C0\u3002< 1.0 \u70BA\u7626\u9577\uFF080.7 \u70BA\u7E31\u5411\uFF09\uFF0C1.0 \u70BA\u6B63\u5713\uFF0C> 1.0 \u70BA\u5BEC\u6241\uFF08\u6A6B\u5411\uFF09\u3002", + RADIAL_POLE_GAP_BONUS: "\u6975\u9EDE\u9593\u8DDD\u88DC\u511F", + DESC_RADIAL_POLE_GAP_BONUS: "\u589E\u52A0\u6A62\u5713\u5357\u5317\u5169\u6975\u5340\u57DF\u5167\u7BC0\u9EDE\u7684\u9593\u8DDD\u3002\u503C\u8D8A\u5927\uFF0C\u7BC0\u9EDE\u6CBF\u5F27\u7DDA\u63A8\u5F97\u8D8A\u9060\u3002", + RADIAL_START_ANGLE: "\u8D77\u59CB\u89D2\u5EA6", + DESC_RADIAL_START_ANGLE: "\u7B2C\u4E00\u500B\u7BC0\u9EDE\u51FA\u73FE\u7684\u4F4D\u7F6E\uFF08\u5EA6\u6578\uFF09\u3002270 \u70BA\u5317\uFF0C0 \u70BA\u6771\uFF0C90 \u70BA\u5357\u3002", + RADIAL_MAX_SWEEP: "\u6700\u5927\u6383\u904E\u89D2\u5EA6", + DESC_RADIAL_MAX_SWEEP: "\u5206\u652F\u53EF\u586B\u5145\u7684\u5F27\u7BC4\u570D\u3002360 \u70BA\u5168\u5713\u3002\u8F03\u5C0F\u7684\u503C\u6703\u4F7F\u5713\u4E0D\u5B8C\u6574\u3002", + // Others + GAP_X: "\u6C34\u5E73\u9593\u8DDD\uFF08Gap X\uFF09", + DESC_LAYOUT_GAP_X: "\u89AA\u4EE3\u7BC0\u9EDE\u8207\u5B50\u7BC0\u9EDE\u4E4B\u9593\u7684\u6C34\u5E73\u8DDD\u96E2\u3002", + GAP_Y: "\u5782\u76F4\u9593\u8DDD\uFF08Gap Y\uFF09", + DESC_LAYOUT_GAP_Y: "\u540C\u7D1A\u7BC0\u9EDE\u4E4B\u9593\u7684\u5782\u76F4\u8DDD\u96E2\u3002\u5F91\u5411\u4F48\u5C40\u4E2D\u7684\u57FA\u790E\u9593\u8DDD\u3002", + GAP_MULTIPLIER: "\u9593\u8DDD\u500D\u6578", + DESC_LAYOUT_GAP_MULTIPLIER: "\u8449\u7BC0\u9EDE\uFF08\u7121\u5B50\u7BC0\u9EDE\u7684\u7BC0\u9EDE\uFF09\u76F8\u5C0D\u65BC\u5B57\u578B\u5927\u5C0F\u7684\u5782\u76F4\u9593\u8DDD\u3002\u4F4E\uFF1A\u985E\u4F3C\u5217\u8868\u5806\u758A\uFF1B\u9AD8\uFF1A\u6A19\u6E96\u6A39\u72C0\u9593\u8DDD\u3002", + DIRECTIONAL_ARC_SPAN_RADIANS: "\u5B9A\u5411\u5F35\u958B\u5F27\u5EA6\uFF08Arc-span Radians\uFF09", + DESC_LAYOUT_ARC_SPAN: "\u5B50\u7BC0\u9EDE\u6392\u5217\u7684\u66F2\u7387\u3002\u4F4E\uFF080.5\uFF09\uFF1A\u8F03\u5E73\uFF0C\u985E\u4F3C\u5217\u8868\u3002\u9AD8\uFF082.0\uFF09\uFF1A\u5F4E\u66F2\u6709\u6A5F\uFF0C\u4F46\u6709\u91CD\u758A\u98A8\u96AA\u3002", + ROOT_RADIUS_FACTOR: "\u6839\u7BC0\u9EDE\u534A\u5F91\u4FC2\u6578", + DESC_LAYOUT_ROOT_RADIUS: "\u76F8\u5C0D\u65BC\u6839\u7BC0\u9EDE\u908A\u6846\u7684\u500D\u6578\uFF0C\u6C7A\u5B9A\u6700\u521D\u7684\u534A\u5F91\u3002", + MIN_RADIUS: "\u6700\u5C0F\u534A\u5F91", + DESC_LAYOUT_MIN_RADIUS: "\u5F9E\u6839\u7BC0\u9EDE\u4E2D\u5FC3\u5230\u7B2C\u4E00\u7D1A\u7BC0\u9EDE\u7684\u6700\u5C0F\u7D55\u5C0D\u8DDD\u96E2\u3002", + RADIUS_PADDING_PER_NODE: "\u55AE\u7BC0\u9EDE\u5F91\u5411\u7A7A\u767D\u908A\u8DDD", + DESC_LAYOUT_RADIUS_PADDING: "\u6BCF\u500B\u5B50\u7BC0\u9EDE\u984D\u5916\u589E\u52A0\u7684\u534A\u5F91\uFF0C\u4EE5\u9069\u61C9\u5BC6\u96C6\u578B\u5C0E\u5716\u3002", + GAP_MULTIPLIER_RADIAL: "\u5F91\u5411\u4F48\u5C40\u9593\u8DDD\u500D\u6578", + DESC_LAYOUT_GAP_RADIAL: "\u5F91\u5411\u4F48\u5C40\u6A21\u5F0F\u4E0B\u7684\u89D2\u5EA6\u9593\u8DDD\u500D\u6578\u3002", + GAP_MULTIPLIER_DIRECTIONAL: "\u5782\u76F4\u65B9\u5411\u9593\u8DDD\u500D\u6578", + DESC_LAYOUT_GAP_DIRECTIONAL: "\u5B9A\u5411\u4F48\u5C40\u9802\u5C64\u5206\u652F\u4E4B\u9593\u7684\u9593\u8DDD\u500D\u6578\u3002", + INDICATOR_OFFSET: "\u647A\u758A\u6307\u793A\u7B26\u504F\u79FB", + DESC_LAYOUT_INDICATOR_OFFSET: "\u647A\u758A\u6307\u793A\u7B26\uFF08\u4E09\u9023\u9EDE\uFF09\u8DDD\u96E2\u7BC0\u9EDE\u7684\u8DDD\u96E2\u3002", + INDICATOR_OPACITY: "\u647A\u758A\u6307\u793A\u7B26\u4E0D\u900F\u660E\u5EA6", + DESC_LAYOUT_INDICATOR_OPACITY: "\u647A\u758A\u6307\u793A\u7B26\u7684\u4E0D\u900F\u660E\u5EA6\uFF080-100\uFF09\u3002", + CONTAINER_PADDING: "\u5BB9\u5668\u5167\u908A\u8DDD", + DESC_LAYOUT_CONTAINER_PADDING: "\u4F7F\u7528\u908A\u6846\u6A23\u5F0F\u6642\u7684\u5167\u908A\u8DDD\u3002", + MAX_SEGMENT_LENGTH: "\u908A\u754C\u7DDA\u7CBE\u5EA6", + DESC_LAYOUT_BOUNDARY_LINE_PRECISION: "\u908A\u754C\u5E73\u6ED1\u7CBE\u5EA6\u3002\u503C\u8D8A\u5C0F\u8D8A\u7CBE\u7D30\uFF0830 = \u7CBE\u7D30\uFF09\uFF0C\u503C\u8D8A\u5927\u8D8A\u7C97\u7565\uFF08200 = \u7C97\u7565\uFF09\u3002", + VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "\u5B50\u6A39\u5BEC\u5EA6\u53C3\u8207\u5EA6\uFF08\u55AE\u5074\uFF09", + DESC_VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: "\u5782\u76F4\u5C0E\u5716\u4E2D\uFF0C\u55AE\u5074\u751F\u9577\u7684\u5B50\u5716\u4F54\u7528\uFF08\u5DE6/\u53F3\uFF09\u6C34\u5E73\u7A7A\u9593\u7684\u5F37\u5EA6\u3002\u5F71\u97FF\u7A0B\u5EA6\u9AD8\u3002", + VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "\u5B50\u6A39\u5BEC\u5EA6\u53C3\u8207\u5EA6\uFF08\u96D9\u5074\uFF09", + DESC_VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: "\u5782\u76F4\u5C0E\u5716\u4E2D\uFF0C\u96D9\u5074\u751F\u9577\u7684\u5B50\u5716\u4F54\u7528\uFF08\u5DE6\u53F3\uFF09\u6C34\u5E73\u7A7A\u9593\u7684\u5F37\u5EA6\u3002\u5F71\u97FF\u7A0B\u5EA6\u9AD8\u3002", + VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "\u5B50\u6A39\u5E73\u6ED1\u58D3\u7E2E\u89F8\u767C\u500D\u6578", + DESC_VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: "\u8D85\u904E Gap Y \u4E58\u4EE5\u8A72\u500D\u6578\u5F8C\u958B\u59CB\u5E73\u6ED1\u58D3\u7E2E\uFF0C\u907F\u514D\u65B0\u589E\u5B50\u7BC0\u9EDE\u9593\u8DDD\u7A81\u8B8A\u3002\u901A\u5E38\u5728\u5927\u5C0E\u5716\u4E2D\u66F4\u660E\u986F\u3002", + VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "\u5B50\u6A39\u5E73\u6ED1\u58D3\u7E2E\u4E0B\u9650", + DESC_VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: "\u5782\u76F4\u5B50\u6A39\u5BEC\u5EA6\u5E73\u6ED1\u58D3\u7E2E\u5230\u7684\u6700\u5C0F\u503C\u3002\u503C\u8D8A\u5927\u8D8A\u4FDD\u7559\u539F\u5BEC\u5EA6\u3002\u901A\u5E38\u5728\u5927\u5C0E\u5716\u4E2D\u66F4\u660E\u986F\u3002", + HORIZONTAL_L1_SOFTCAP_THRESHOLD: "L1 \u6C34\u5E73\u65B9\u5411\u8EDF\u4E0A\u9650", + DESC_HORIZONTAL_L1_SOFTCAP_THRESHOLD: "\u8D85\u904E\u8A72 px \u503C\u5F8C\uFF0C\u4E0A/\u4E0B L1 \u5B50\u6A39\u5BEC\u5EA6\u958B\u59CB\u58D3\u7E2E\u3002\u5C0D\u5927\u5C0E\u5716\u5F71\u97FF\u7A0B\u5EA6\u4E2D\u5230\u9AD8\u3002", + HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "L1 \u6C34\u5E73\u65B9\u5411\u58D3\u7E2E\u4E0B\u9650", + DESC_HORIZONTAL_L1_COMPRESSION_MIN_SCALE: "\u4E0A/\u4E0B L1 \u5BEC\u5EA6\u58D3\u7E2E\u5230\u7684\u6700\u5C0F\u503C\u3002\u503C\u8D8A\u5927\u8D8A\u4FDD\u7559\u539F\u5BEC\u5EA6\u3002\u8EDF\u4E0A\u9650\u88AB\u9054\u5230\uFF08\u3001\u958B\u59CB\u58D3\u7E2E\uFF09\u5F8C\u5F71\u97FF\u4E2D\u7B49\u3002", + VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "\u7DCA\u6E4A\u89AA\u5B50\u9593\u8DDD\u6BD4\u4F8B", + DESC_VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: "\u7DCA\u6E4A\u5782\u76F4\u5B50\u6A39\u4E2D\uFF0C\u89AA\u5B50\u9593\u8DDD\u4F7F\u7528 Gap X \u4E58\u4EE5\u8A72\u6BD4\u4F8B\u3002\u6975\u5927\u5F71\u97FF\u8996\u89BA\u6548\u679C\u3002", + DIRECTIONAL_CROSS_AXIS_RATIO: "\u6B63\u4EA4\u8EF8\u4E4B\u6BD4", + DESC_DIRECTIONAL_CROSS_AXIS_RATIO: "\u8207\u5782\u76F4\u65BC\u751F\u9577\u65B9\u5411\u7684\u8EF8\uFF08Cross-axis\uFF09\u7684\u534A\u5F91\u4E4B\u6BD4\uFF080.2 = \u6241\uFF0C1.0 = \u5713\uFF09\u3002\u6975\u5927\u5F71\u97FF L1 \u5C55\u958B\u5F62\u614B\u3002", + MANUAL_GAP_MULTIPLIER: "\u624B\u52D5\u4F48\u5C40\u9593\u8DDD\u500D\u6578", + DESC_LAYOUT_MANUAL_GAP: "\u505C\u7528\u81EA\u52D5\u4F48\u5C40\u6642\u65B0\u589E\u7BC0\u9EDE\u7684\u9593\u8DDD\u500D\u6578\u3002", + MANUAL_JITTER_RANGE: "\u624B\u52D5\u4F48\u5C40\u6296\u52D5\u7BC4\u570D", + DESC_LAYOUT_MANUAL_JITTER: "\u505C\u7528\u81EA\u52D5\u4F48\u5C40\u6642\u65B0\u589E\u7BC0\u9EDE\u7684\u96A8\u6A5F\u4F4D\u7F6E\u504F\u79FB\u3002", + CALENDAR_DATE_INDEX: "\u7B2C {index} \u500B\u65E5\u671F\uFF0C\u5171 {total} \u500B", + CALENDAR_DATE_LABEL: "\u65E5\u671F", + CALENDAR_DATE_TYPE: "\u65E5\u671F\u985E\u578B", + CALENDAR_PRIORITY: "\u512A\u5148\u7D1A", + CALENDAR_RECURRENCE: "\u91CD\u8907", + CALENDAR_RECURRENCE_PLACEHOLDER: "every day", + CALENDAR_RECURRENCE_DESC: `\u4F8B\u5982\uFF0C'every day'\uFF0C'every 2 weeks'
Tasks \u5916\u639B\u91CD\u8907\u4EFB\u52D9\u6587\u4EF6`, + CALENDAR_INJECT_LINK: "\u63D2\u5165\u7BC0\u9EDE\u9023\u7D50", + CALENDAR_INJECT_LINK_DESC: "\u5728\u4EFB\u52D9\u672B\u5C3E\u65B0\u589E\u6307\u5411\u8A72\u7BC0\u9EDE\u7684\u9023\u7D50\u3002", + CALENDAR_ALIAS_PLACEHOLDER: "\u5225\u540D", + CALENDAR_BTN_CANCEL: "\u53D6\u6D88", + CALENDAR_BTN_TASK_ONLY: "\u50C5\u4EFB\u52D9", + CALENDAR_BTN_ADD_DATE_TASK: "\u65B0\u589E\u65E5\u671F\u548C\u4EFB\u52D9", + CALENDAR_PRIORITY_HIGHEST: "\u6700\u9AD8", + CALENDAR_PRIORITY_HIGH: "\u9AD8", + CALENDAR_PRIORITY_MEDIUM: "\u4E2D", + CALENDAR_PRIORITY_NORMAL: "\u666E\u901A", + CALENDAR_PRIORITY_LOW: "\u4F4E", + CALENDAR_PRIORITY_LOWEST: "\u6700\u4F4E", + CALENDAR_DATETYPE_DUE: "\u622A\u6B62", + CALENDAR_DATETYPE_START: "\u958B\u59CB", + CALENDAR_DATETYPE_SCHEDULED: "\u8A08\u756B", + CALENDAR_DATETYPE_CREATED: "\u5EFA\u7ACB", + CALENDAR_DATETYPE_DONE: "\u5B8C\u6210", + CALENDAR_DATETYPE_CANCELLED: "\u53D6\u6D88", + // Presets + PRESET_LABEL: "\u9810\u8A2D", + PRESET_UNSAVED: "\u81EA\u5B9A\u7FA9 / \u672A\u95DC\u806F", + PRESET_BTN_SAVE: "\u5132\u5B58\u9810\u8A2D", + PRESET_BTN_DELETE: "\u522A\u9664\u9810\u8A2D", + PRESET_BTN_NEW: "\u65B0\u5EFA\u9810\u8A2D", + PRESET_BTN_APPLY: "\u61C9\u7528\u9810\u8A2D\u5230\u5C0E\u5716", + PRESET_WARNING_MODIFIED: "\u5C0E\u5716\u8A2D\u5B9A\u8207\u9810\u8A2D\u4E0D\u7B26\u3002", + PROMPT_NEW_PRESET_NAME: "\u65B0\u9810\u8A2D\u540D\u7A31\uFF1A", + NOTICE_PRESET_DELETED: "\u9810\u8A2D\u5DF2\u522A\u9664\u3002", + NOTICE_PRESET_SAVED: "\u9810\u8A2D\u5DF2\u5132\u5B58\u3002", + NOTICE_PRESET_APPLIED: "\u9810\u8A2D\u5DF2\u61C9\u7528\u3002", + // Misc + INPUT_TITLE_PASTE_ROOT: "MindMap Builder \u8CBC\u4E0A", + INSTRUCTIONS: "> [!Tip]\n>\u{1F680} \u60F3\u8981\u9032\u968E\uFF1F\u6B61\u8FCE\u53C3\u52A0\u5B98\u65B9 [MindMap Builder \u8AB2\u7A0B](https://www.visual-thinking-workshop.com/mindmap)\uFF01\n\n- **ENTER**\uFF1A\u65B0\u589E\u5B50\u7BC0\u9EDE\u4E26\u4FDD\u7559\u5728\u7576\u524D\u89AA\u4EE3\u7BC0\u9EDE\u4E0A\uFF0C\u65B9\u4FBF\u5FEB\u901F\u8F38\u5165\u3002\u82E5\u8F38\u5165\u6846\u70BA\u7A7A\u6642\u6309\u56DE\u8ECA\uFF0C\u7126\u9EDE\u5C07\u79FB\u52D5\u5230\u6700\u65B0\u65B0\u589E\u7684\u5B50\u7BC0\u9EDE\u3002\u9023\u7E8C\u6309\u56DE\u8ECA\u5C07\u5728\u8A72\u7BC0\u9EDE\u7684\u540C\u7D1A\u7BC0\u9EDE\u9593\u8FF4\u5708\u5207\u63DB\u3002\n- **\u71B1\u9375**\uFF1A\u898B\u5074\u908A\u9762\u677F\u5E95\u90E8\u7684\u914D\u7F6E\u9078\u9805\u3002\n- **\u505C\u9760/\u53D6\u6D88\u505C\u9760**\uFF1A\u4F7F\u7528\u6309\u9215\u6216\u914D\u7F6E\u597D\u7684\u71B1\u9375\u4F86\u5207\u63DB\u8F38\u5165\u6846\u4F4D\u7F6E\u3002\n- **\u647A\u758A**\uFF1A\u50C5\u5728\u8F38\u5165\u6846\u505C\u9760\u6642\u986F\u793A\u6309\u9215\uFF1B\u53D6\u6D88\u505C\u9760\u6642\u8ACB\u4F7F\u7528\u71B1\u9375\u3002\n- **ESC**\uFF1A\u5C07\u6D6E\u52D5\u8F38\u5165\u6846\u505C\u9760\uFF0C\u4F46\u4E0D\u555F\u7528\u5074\u908A\u9762\u677F\u3002\n- **\u8457\u8272**\uFF1A\u9802\u5C64\u5206\u652F\u64C1\u6709\u7368\u7ACB\u984F\u8272\uFF08\u591A\u8272\u6A21\u5F0F\uFF09\uFF0C\u5F8C\u4EE3\u7BC0\u9EDE\u7E7C\u627F\u89AA\u4EE3\u984F\u8272\u3002\n- **\u7DE8\u7D44**\uFF1A\n - \u555F\u7528\u201C\u5206\u652F\u7DE8\u7D44\u201D\u5C07\u905E\u8FF4\u5730\u7DE8\u7D44\u5B50\u6A39\uFF0C\u5F9E\u8449\u7BC0\u9EDE\u5230\u9802\u5C64\u5206\u652F\u3002\n- **\u8907\u88FD/\u8CBC\u4E0A**\uFF1A\u532F\u51FA/\u532F\u5165\u542B\u7E2E\u6392\u7684 Markdown \u5217\u8868\u3002\n\n\u{1F60D} \u5982\u679C\u4F60\u89BA\u5F97\u9019\u500B\u6307\u4EE4\u78BC\u6709\u7528\uFF0C\u6B61\u8FCE [\u8ACB\u6211\u559D\u676F\u5496\u5561 \u2615](https://ko-fi.com/zsolt)\u3002" + }; + + // src/scripts/mindmap-builder/lang/index.ts + function createMindmapTranslator(locale, isAppleDevice = false) { + const translate = createTranslator(locale, { + en, + de, + es, + fr, + ru, + zh: zhCn, + "zh-cn": zhCn, + "zh-tw": zhTw + }); + return (key, params = {}) => translate(key, { modifier: isAppleDevice ? "OPT" : "ALT", ...params }); + } + + // src/scripts/mindmap-builder/settings.js + function createSettings(runtimeContext) { + const getZoom = (level) => { + const target = runtimeContext.ZOOM_LEVELS[level ?? runtimeContext.zoomLevel] || runtimeContext.ZOOM_LEVELS.Medium; + return runtimeContext.ea.DEVICE.isMobile ? target.mobile : target.desktop; + }; + const fontScale = (type) => { + switch (type) { + case "Use scene fontsize": + return Array(5).fill(runtimeContext.getAppState().currentItemFontSize); + case "Fibonacci Scale": + return [68, 42, 26, 16, 10]; + default: + return [36, 28, 20, 16, 12]; + } + }; + const getFontScale = (type) => fontScale(type) ?? fontScale("Normal Scale"); + const getVal = (key, def) => runtimeContext.ea.getScriptSettingValue(key, typeof def === "object" ? def : { value: def }).value; + const saveSettings = async () => { + if (runtimeContext.dirty) await runtimeContext.ea.saveScriptSettings(); + runtimeContext.dirty = false; + }; + const setVal = (key, value, hidden = false) => { + const def = runtimeContext.ea.getScriptSettingValue(key, { value, hidden }); + const isChanging = def.value !== value || def.hidden !== hidden; + def.value = value; + if (hidden) def.hidden = true; + runtimeContext.ea.setScriptSettingValue(key, def); + if (isChanging) { + runtimeContext.dirty = true; + } + }; + const extractConfigFromGlobals = () => ({ + growthMode: runtimeContext.currentModalGrowthMode, + arrowType: runtimeContext.arrowType, + fontsizeScale: runtimeContext.fontsizeScale, + multicolor: runtimeContext.multicolor, + boxChildren: runtimeContext.boxChildren, + roundedCorners: runtimeContext.roundedCorners, + maxWrapWidth: runtimeContext.maxWidth, + isSolidArrow: runtimeContext.isSolidArrow, + centerText: runtimeContext.centerText, + fillSweep: runtimeContext.fillSweep, + branchScale: runtimeContext.branchScale, + baseStrokeWidth: runtimeContext.baseStrokeWidth, + customPalette: JSON.parse( + JSON.stringify(runtimeContext.customPalette || { enabled: false, random: false, colors: [] }) + ), + layoutSettings: JSON.parse(JSON.stringify(runtimeContext.layoutSettings || {})) + }); + const normalizeMapConfig = (c) => { + if (!c) { + return {}; + } + return { + growthMode: c.growthMode ?? "Right-Left", + arrowType: c.arrowType ?? "curved", + fontsizeScale: c.fontsizeScale ?? "Normal Scale", + multicolor: c.multicolor ?? true, + boxChildren: c.boxChildren ?? false, + roundedCorners: c.roundedCorners ?? false, + maxWrapWidth: c.maxWrapWidth ?? 450, + isSolidArrow: c.isSolidArrow ?? true, + centerText: c.centerText ?? true, + fillSweep: c.fillSweep ?? false, + branchScale: c.branchScale ?? "Hierarchical", + baseStrokeWidth: c.baseStrokeWidth ?? 6, + customPalette: c.customPalette ?? { enabled: false, random: false, colors: [] }, + layoutSettings: { ...runtimeContext.LAYOUT_DEFAULTS, ...c.layoutSettings || {} } + }; + }; + const diffMapConfig = (c1, c2) => { + if (!c1 || !c2) { + return true; + } + const n1 = normalizeMapConfig(c1); + const n2 = normalizeMapConfig(c2); + const keys = [ + "growthMode", + "arrowType", + "fontsizeScale", + "multicolor", + "boxChildren", + "roundedCorners", + "maxWrapWidth", + "isSolidArrow", + "centerText", + "fillSweep", + "branchScale", + "baseStrokeWidth" + ]; + for (let k of keys) { + if (n1[k] !== n2[k]) { + return true; + } + } + if (JSON.stringify(n1.customPalette) !== JSON.stringify(n2.customPalette)) { + return true; + } + for (let k of Object.keys(runtimeContext.LAYOUT_DEFAULTS)) { + const v1 = n1.layoutSettings[k]; + const v2 = n2.layoutSettings[k]; + if (typeof v1 === "number" && typeof v2 === "number") { + if (Math.abs(v1 - v2) > 1e-4) { + return true; + } + } else if (v1 !== v2) { + return true; + } + } + return false; + }; + const applyPresetToGlobals = (presetName) => { + const p = runtimeContext.mapPresets[presetName]; + if (!p) { + return; + } + const n = normalizeMapConfig(p); + runtimeContext.currentModalGrowthMode = n.growthMode; + runtimeContext.arrowType = n.arrowType; + runtimeContext.fontsizeScale = n.fontsizeScale; + runtimeContext.multicolor = n.multicolor; + runtimeContext.boxChildren = n.boxChildren; + runtimeContext.roundedCorners = n.roundedCorners; + runtimeContext.maxWidth = n.maxWrapWidth; + runtimeContext.isSolidArrow = n.isSolidArrow; + runtimeContext.centerText = n.centerText; + runtimeContext.fillSweep = n.fillSweep; + runtimeContext.branchScale = n.branchScale; + runtimeContext.baseStrokeWidth = n.baseStrokeWidth; + runtimeContext.customPalette = JSON.parse( + JSON.stringify(n.customPalette || { enabled: false, random: false, colors: [] }) + ); + runtimeContext.layoutSettings = JSON.parse(JSON.stringify(n.layoutSettings || {})); + setVal(runtimeContext.K_GROWTH, runtimeContext.currentModalGrowthMode); + setVal(runtimeContext.K_ARROW_TYPE, runtimeContext.arrowType); + setVal(runtimeContext.K_FONTSIZE, runtimeContext.fontsizeScale); + setVal(runtimeContext.K_MULTICOLOR, runtimeContext.multicolor); + setVal(runtimeContext.K_BOX, runtimeContext.boxChildren); + setVal(runtimeContext.K_ROUND, runtimeContext.roundedCorners); + setVal(runtimeContext.K_WIDTH, runtimeContext.maxWidth); + setVal(runtimeContext.K_ARROWSTROKE, runtimeContext.isSolidArrow); + setVal(runtimeContext.K_CENTERTEXT, runtimeContext.centerText); + setVal(runtimeContext.K_FILL_SWEEP, runtimeContext.fillSweep); + setVal(runtimeContext.K_BRANCH_SCALE, runtimeContext.branchScale); + setVal(runtimeContext.K_BASE_WIDTH, runtimeContext.baseStrokeWidth); + setVal(runtimeContext.K_PALETTE, runtimeContext.customPalette, true); + setVal(runtimeContext.K_LAYOUT, runtimeContext.layoutSettings, true); + }; + const applyPresetToMap = async (presetName, sel) => { + applyPresetToGlobals(presetName); + await updateRootNodeCustomData( + { + presetName, + growthMode: runtimeContext.currentModalGrowthMode, + arrowType: runtimeContext.arrowType, + fontsizeScale: runtimeContext.fontsizeScale, + multicolor: runtimeContext.multicolor, + boxChildren: runtimeContext.boxChildren, + roundedCorners: runtimeContext.roundedCorners, + maxWrapWidth: runtimeContext.maxWidth, + isSolidArrow: runtimeContext.isSolidArrow, + centerText: runtimeContext.centerText, + fillSweep: runtimeContext.fillSweep, + branchScale: runtimeContext.branchScale, + baseStrokeWidth: runtimeContext.baseStrokeWidth, + layoutSettings: JSON.parse(JSON.stringify(runtimeContext.layoutSettings)) + }, + sel + ); + await runtimeContext.refreshMapLayout(sel); + runtimeContext.updateUI(); + }; + const refreshPresetDropdown = () => { + if (!runtimeContext.presetDropdown) { + return; + } + runtimeContext.presetDropdown.selectEl.innerHTML = ""; + Object.keys(runtimeContext.mapPresets).forEach( + (k) => runtimeContext.presetDropdown.addOption(k, k) + ); + runtimeContext.presetDropdown.setValue(runtimeContext.activePresetName); + }; + const calculateStrokeWidth = (depth, baseWidth, scaleMode) => { + const base = Number.isFinite(baseWidth) ? baseWidth : 6; + const clampedDepth = Math.max(0, Math.min(depth ?? 0, 4)); + if (scaleMode === "Uniform") return base; + const min = Math.max(0.1, base * 0.1); + const slope = (min - base) / 4; + const val = slope * clampedDepth + base; + return Math.round(val * 100) / 100; + }; + const getStrokeWidthForDepth = (depth) => { + return calculateStrokeWidth(depth, runtimeContext.baseStrokeWidth, runtimeContext.branchScale); + }; + const inferDirectionalGrowthMode = (node, parent, sourceRoot = null, sourceMode = null) => { + if (!node || !parent) return "Right-facing"; + const mode = sourceMode || sourceRoot?.customData?.growthMode || runtimeContext.currentModalGrowthMode; + const nodeCenter = { + x: node.x + node.width / 2, + y: node.y + node.height / 2 + }; + const ref = sourceRoot ? { + x: sourceRoot.x + sourceRoot.width / 2, + y: sourceRoot.y + sourceRoot.height / 2 + } : { + x: parent.x + parent.width / 2, + y: parent.y + parent.height / 2 + }; + if (mode === "Up-facing") return "Up-facing"; + if (mode === "Down-facing") return "Down-facing"; + if (mode === "Right-facing") return "Right-facing"; + if (mode === "Left-facing") return "Left-facing"; + if (mode === "Up-Down") { + return nodeCenter.y < ref.y ? "Up-facing" : "Down-facing"; + } + if (mode === "Right-Left" || mode === "Radial") { + return nodeCenter.x >= ref.x ? "Right-facing" : "Left-facing"; + } + const dx = nodeCenter.x - ref.x; + const dy = nodeCenter.y - ref.y; + if (Math.abs(dx) >= Math.abs(dy)) { + return dx >= 0 ? "Right-facing" : "Left-facing"; + } + return dy >= 0 ? "Down-facing" : "Up-facing"; + }; + const getRootConfigForNode = (rootNode) => { + const cd = rootNode?.customData ?? {}; + const defaultLayout = runtimeContext.layoutSettings || {}; + return { + growthMode: cd?.growthMode || runtimeContext.currentModalGrowthMode, + autoLayoutDisabled: cd?.autoLayoutDisabled === true, + arrowType: cd?.arrowType ?? runtimeContext.arrowType, + fontsizeScale: cd?.fontsizeScale ?? runtimeContext.fontsizeScale, + multicolor: typeof cd?.multicolor === "boolean" ? cd.multicolor : runtimeContext.multicolor, + boxChildren: typeof cd?.boxChildren === "boolean" ? cd.boxChildren : runtimeContext.boxChildren, + roundedCorners: typeof cd?.roundedCorners === "boolean" ? cd.roundedCorners : runtimeContext.roundedCorners, + maxWrapWidth: typeof cd?.maxWrapWidth === "number" ? cd.maxWrapWidth : runtimeContext.maxWidth, + isSolidArrow: typeof cd?.isSolidArrow === "boolean" ? cd.isSolidArrow : runtimeContext.isSolidArrow, + centerText: typeof cd?.centerText === "boolean" ? cd.centerText : runtimeContext.centerText, + fillSweep: typeof cd?.fillSweep === "boolean" ? cd.fillSweep : runtimeContext.fillSweep, + branchScale: cd?.branchScale ?? runtimeContext.branchScale, + baseStrokeWidth: typeof cd?.baseStrokeWidth === "number" ? cd.baseStrokeWidth : runtimeContext.baseStrokeWidth, + layoutSettings: JSON.parse(JSON.stringify(cd?.layoutSettings ?? defaultLayout)) + }; + }; + const withRootLayoutContext = (rootNode, fn) => { + const previous = { + growthMode: runtimeContext.currentModalGrowthMode, + arrowType: runtimeContext.arrowType, + centerText: runtimeContext.centerText, + fillSweep: runtimeContext.fillSweep, + layoutSettings: runtimeContext.layoutSettings + }; + const cfg = getRootConfigForNode(rootNode); + runtimeContext.currentModalGrowthMode = cfg.growthMode; + runtimeContext.arrowType = cfg.arrowType; + runtimeContext.centerText = cfg.centerText; + runtimeContext.fillSweep = cfg.fillSweep; + runtimeContext.layoutSettings = JSON.parse(JSON.stringify(cfg.layoutSettings)); + try { + return fn(cfg); + } finally { + runtimeContext.currentModalGrowthMode = previous.growthMode; + runtimeContext.arrowType = previous.arrowType; + runtimeContext.centerText = previous.centerText; + runtimeContext.fillSweep = previous.fillSweep; + runtimeContext.layoutSettings = previous.layoutSettings; + } + }; + const updateRootNodeCustomData = async (data, sel) => { + if (!sel) sel = runtimeContext.getMindmapNodeFromSelection(); + if (sel) { + const allElements = runtimeContext.ea.getViewElements(); + const settingsRoot = runtimeContext.getSettingsRootNode(sel, allElements); + if (!settingsRoot) return null; + runtimeContext.ea.copyViewElementsToEAforEditing( + allElements.filter((e) => e.id === settingsRoot.id) + ); + runtimeContext.ea.addAppendUpdateCustomData(settingsRoot.id, { + ...data + }); + await runtimeContext.addElementsToView({ + captureUpdate: "NEVER" + }); + runtimeContext.updateUI(); + const info = runtimeContext.getHierarchy(settingsRoot, runtimeContext.ea.getViewElements()); + return { + ...info, + rootId: settingsRoot.id, + settingsRootId: settingsRoot.id + }; + } + return null; + }; + const updateBranchStrokes = async (rootId, oldBaseWidth, oldScaleMode, newBaseWidth, newScaleMode) => { + if (!runtimeContext.isViewSet()) return; + const allElements = runtimeContext.ea.getViewElements(); + const root = allElements.find((el) => el.id === rootId); + if (!root) return; + const elementsToUpdate = []; + let manualOverrideFound = false; + const traverse = (nodeId, depth) => { + const children = runtimeContext.getChildrenNodes(nodeId, allElements); + children.forEach((child) => { + const arrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === nodeId && a.endBinding?.elementId === child.id + ); + if (arrow) { + const childDepth = depth + 1; + const expectedOldWidth = calculateStrokeWidth(childDepth, oldBaseWidth, oldScaleMode); + if (Math.abs(arrow.strokeWidth - expectedOldWidth) < 0.05) { + const newWidth = calculateStrokeWidth(childDepth, newBaseWidth, newScaleMode); + if (Math.abs(arrow.strokeWidth - newWidth) > 1e-3) { + elementsToUpdate.push({ + id: arrow.id, + strokeWidth: newWidth + }); + } + } else { + const expectedNewWidth = calculateStrokeWidth(childDepth, newBaseWidth, newScaleMode); + if (Math.abs(arrow.strokeWidth - expectedNewWidth) >= 0.05) { + manualOverrideFound = true; + } + } + } + traverse(child.id, depth + 1); + }); + }; + traverse(rootId, 0); + if (elementsToUpdate.length > 0) { + runtimeContext.ea.copyViewElementsToEAforEditing( + elementsToUpdate.map((i) => allElements.find((e) => e.id === i.id)) + ); + elementsToUpdate.forEach((item) => { + const el = runtimeContext.ea.getElement(item.id); + if (el) el.strokeWidth = item.strokeWidth; + }); + await runtimeContext.addElementsToView({ + captureUpdate: "IMMEDIATELY" + }); + } + if (manualOverrideFound) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_BRANCH_WIDTH_MANUAL_OVERRIDE")); + } + }; + return { + getZoom, + fontScale, + getFontScale, + getVal, + saveSettings, + setVal, + extractConfigFromGlobals, + normalizeMapConfig, + diffMapConfig, + applyPresetToGlobals, + applyPresetToMap, + refreshPresetDropdown, + calculateStrokeWidth, + getStrokeWidthForDepth, + inferDirectionalGrowthMode, + getRootConfigForNode, + withRootLayoutContext, + updateRootNodeCustomData, + updateBranchStrokes + }; + } + + // src/scripts/mindmap-builder/textParsing.js + function createTextParsing(runtimeContext) { + const trimText = (text) => { + if (!text) return text; + return text.match(/^(?:[ \t]*[-\*][ \t])?(?:[ \t]*)(.*?)[ \t]*$/)[1]; + }; + const parseText = async (text) => { + const trimmed = trimText(text); + if (trimmed && (trimmed.startsWith("![[") || trimmed.match(/^[-*][ \t]+!\[\[/)) && trimmed.endsWith("]]")) { + return text; + } + return await runtimeContext.ea.parseText(text); + }; + const parseImageInput = (input) => { + const trimmed = trimText(input); + const externalMatch = trimmed.match(/^!\[(.*?)\]\(((?:https?|file):\/\/[^)]+)\)$/i); + if (externalMatch) { + const altText = externalMatch[1]; + const url = externalMatch[2]; + let width2 = null; + if (altText) { + const parts2 = altText.split("|"); + const last = parts2[parts2.length - 1]; + if (/^\d+$/.test(last)) { + width2 = parseInt(last); + } + } + try { + const urlObj = new URL(url); + const pathname = urlObj.pathname.toLowerCase(); + const isImageUrl = runtimeContext.IMAGE_TYPES.some((ext) => pathname.endsWith("." + ext)); + if (isImageUrl) { + return { + path: url, + width: width2, + imageFile: null, + isImagePath: true, + // This triggers image addition in addNode + file: null, + isExternalImage: true + // Flag to help direct link assignments later + }; + } + } catch (e) { + } + return null; + } + if (!trimmed.startsWith("![[") || !trimmed.endsWith("]]")) return null; + const content = trimmed.slice(3, -2); + const parts = content.split("|"); + const path = parts[0]; + let width = null; + if (parts.length > 1) { + const last = parts[parts.length - 1]; + if (/^\d+$/.test(last)) { + width = parseInt(last); + } + } + let imageFile = null, file = null; + let isImagePath = false; + const PDF_RECT_LINK_REGEX = /^[^#]*#page=\d*/; + if (path.match(PDF_RECT_LINK_REGEX)) { + isImagePath = true; + } else { + const pathParts = path.split("#"); + imageFile = file = app.metadataCache.getFirstLinkpathDest( + pathParts[0], + runtimeContext.ea.targetView.file.path + ); + if (imageFile) { + const isEx = imageFile.extension === "md" && runtimeContext.ea.isExcalidrawFile(imageFile); + if (!runtimeContext.IMAGE_TYPES.includes(imageFile.extension.toLowerCase()) && !isEx) { + if (file.extension === "md" && width !== null) { + isImagePath = true; + } + imageFile = null; + } + if (isEx && pathParts.length === 2) { + isImagePath = true; + imageFile = null; + } + } + } + return { + path, + width, + imageFile, + isImagePath, + file + }; + }; + const parseEmbeddableInput = (input, imageInfo) => { + const trimmed = input.trim(); + const match = trimmed.match(/^!\[(.*?)\]\(((?:https?|file):\/\/[^)]+)\)$/i); + if (match) { + if (imageInfo && imageInfo.isExternalImage) return null; + return match[2]; + } + const dataURL = trimmed.match(/^!\[\[(data:text\/html;base64.*)]]$/i); + if (dataURL) { + return dataURL[1]; + } + if (imageInfo && imageInfo.isImagePath && imageInfo.width !== null) { + return null; + } + const pathSplit = imageInfo?.path?.split("#"); + if (imageInfo && imageInfo.file && imageInfo.file.extension === "md" && // Not an Excalidraw File or maybe an Excalidraw file with a back-of-the-card note reference + (!runtimeContext.ea.isExcalidrawFile(imageInfo.file) || pathSplit?.[1] && !pathSplit[1].startsWith("^"))) { + imageInfo.isImagePath = false; + return `[[${imageInfo.path}]]`; + } + return null; + }; + const getAdjustedMaxWidth = async (text, max) => { + const fontString = `${runtimeContext.ea.style.fontSize.toString()}px ${ExcalidrawLib.getFontFamilyString({ fontFamily: runtimeContext.ea.style.fontFamily })}`; + const parsedText = await parseText(text) ?? text; + const wrappedText = ExcalidrawLib.wrapText(parsedText, fontString, max); + const metrics = runtimeContext.ea.measureText(wrappedText); + const optimalWidth = Math.ceil(metrics.width); + return { + width: Math.min(max, optimalWidth), + height: metrics.height, + wrappedText + }; + }; + const getNodeMarkdownFile = (nodeText) => { + if (!nodeText || !runtimeContext.ea.targetView || !runtimeContext.ea.targetView.file) + return null; + const parts = nodeText.trim().match(/^\[\[([^#\|\]]+)[^\]]*]]$/); + if (!!parts?.[1]) { + const file = app.metadataCache.getFirstLinkpathDest( + parts[1], + runtimeContext.ea.targetView.file.path + ); + return file && file.extension === "md" ? file : null; + } + return null; + }; + const getTextFromNode = (all, node, getRaw = false, shortPath = false) => { + if (node.type === "embeddable") { + return node.link.startsWith("[[") ? `!${node.link}` : `![](${node.link})`; + } + if (node.type === "image") { + const embeddedFile = runtimeContext.ea.targetView?.excalidrawData?.getFile(node.fileId); + if (!embeddedFile) return ""; + const file = runtimeContext.ea.getViewFileForImageElement(node); + if (!file && node.link && node.link.match(/^(https?|file):\/\//i)) { + return `![image|${Math.round(node.width)}](${node.link})`; + } + if (shortPath) { + const originalPath = embeddedFile.linkParts?.original; + return `![[${originalPath}|${Math.round(node.width)}]]`; + } + if (file) { + if (file.extension === "pdf" && node.link?.startsWith("[[")) { + return `!${node.link.match(/^(.*?)\]\]/)[1]}|${Math.round(node.width)}]]`; + } + return `![[${file.path}${embeddedFile.filenameparts?.linkpartReference || ""}|${Math.round(node.width)}]]`; + } + return ""; + } + if (node.type === "text") { + return getRaw ? node.rawText : node.originalText; + } + const textId = node.boundElements?.find((be) => be.type === "text")?.id; + if (!textId) return ""; + const textEl = all.find((el) => el.id === textId); + return textEl ? getRaw ? textEl.rawText : textEl.originalText : ""; + }; + return { + trimText, + parseText, + parseImageInput, + parseEmbeddableInput, + getAdjustedMaxWidth, + getNodeMarkdownFile, + getTextFromNode + }; + } + + // src/scripts/mindmap-builder/graph.js + function createGraph(runtimeContext) { + const buildParentMap = (allElements, elementById) => { + const parentMap = /* @__PURE__ */ new Map(); + const byId = elementById || buildElementMap(allElements); + allElements.forEach((el) => { + if (el.type === "arrow" && el.customData?.isBranch && el.startBinding?.elementId && el.endBinding?.elementId) { + const parent = byId.get(el.startBinding.elementId); + const childId = el.endBinding.elementId; + if (parent && childId) { + const actualParent = parent.containerId ? byId.get(parent.containerId) : parent; + if (actualParent) parentMap.set(childId, actualParent); + } + } + }); + return parentMap; + }; + const getParentNode = (id, allElements, parentMap = null) => { + if (parentMap && parentMap.has(id)) { + return parentMap.get(id); + } + const arrow = allElements.find( + (el) => el.type === "arrow" && el.customData?.isBranch && el.endBinding?.elementId === id + ); + if (!arrow) return null; + const parent = allElements.find((el) => el.id === arrow.startBinding?.elementId); + return parent?.containerId ? allElements.find((el) => el.id === parent.containerId) : parent; + }; + const buildElementMap = (allElements) => { + const map = /* @__PURE__ */ new Map(); + allElements.forEach((el) => map.set(el.id, el)); + return map; + }; + const buildChildrenMap = (allElements, elementById) => { + const childrenByParent = /* @__PURE__ */ new Map(); + const byId = elementById || buildElementMap(allElements); + allElements.forEach((el) => { + if (el.type === "arrow" && el.customData?.isBranch && el.startBinding?.elementId) { + const parentId = el.startBinding.elementId; + const child = byId.get(el.endBinding?.elementId); + if (!child) return; + if (!childrenByParent.has(parentId)) childrenByParent.set(parentId, []); + childrenByParent.get(parentId).push(child); + } + }); + return childrenByParent; + }; + const getChildrenNodes = (id, allElements) => { + const arrows = allElements.filter( + (el) => el.type === "arrow" && el.customData?.isBranch && el.startBinding?.elementId === id + ); + return arrows.map((a) => allElements.find((el) => el.id === a.endBinding?.elementId)).filter(Boolean); + }; + const buildGroupToNodes = (branchIds, allElements) => { + const branchIdSet = new Set(branchIds); + const groupToNodes = /* @__PURE__ */ new Map(); + allElements.forEach((el) => { + if (branchIdSet.has(el.id) && el.type !== "arrow" && el.groupIds) { + el.groupIds.forEach((gid) => { + if (!groupToNodes.has(gid)) groupToNodes.set(gid, /* @__PURE__ */ new Set()); + groupToNodes.get(gid).add(el); + }); + } + }); + return groupToNodes; + }; + const getMasterRoots = () => { + const all = runtimeContext.ea.getViewElements(); + const allMap = new Map(all.map((el) => [el.id, el])); + const maybeRoots = all.filter((el) => el.customData?.growthMode); + const roots = maybeRoots.filter((r) => { + const notRoot = r.boundElements.some((be) => { + if (be.type !== "arrow") return false; + const arrow = allMap.get(be.id); + if (!arrow) return false; + if (!arrow.customData?.isBranch) return false; + if (arrow.endBinding?.elementId === r.id) return true; + return false; + }); + return !notRoot; + }); + return roots.map((r) => r.id); + }; + const getHierarchy = (el, allElements, elementById = null, parentMap = null) => { + if (elementById) { + el = runtimeContext.getBoundaryHost([el]) ?? el; + } else { + el = runtimeContext.getBoundaryHost([el]) ?? el; + } + let depth = 0, curr = el, l1Id = el.id, rootId = el.id; + const visited = /* @__PURE__ */ new Set([el.id]); + while (true) { + let p = getParentNode(curr.id, allElements, parentMap); + if (!p || visited.has(p.id)) { + rootId = curr.id; + break; + } + visited.add(p.id); + l1Id = curr.id; + curr = p; + depth++; + } + return { + depth, + l1AncestorId: l1Id, + rootId + }; + }; + const getSettingsRootNode = (el, allElements, elementById = null, parentMap = null) => { + if (!el) return null; + let curr = runtimeContext.getBoundaryHost([el]) ?? el; + let last = curr; + const visited = /* @__PURE__ */ new Set(); + while (curr && !visited.has(curr.id)) { + visited.add(curr.id); + last = curr; + if (curr.customData?.isAdditionalRoot === true) { + return curr; + } + const p = getParentNode(curr.id, allElements, parentMap); + if (!p) { + return curr; + } + curr = p; + } + return last; + }; + const getDepthFromAncestor = (nodeId, ancestorId, allElements, parentMap = null) => { + const byId = buildElementMap(allElements); + let curr = byId.get(nodeId); + if (!curr) return 0; + let depth = 0; + const visited = /* @__PURE__ */ new Set(); + while (curr && !visited.has(curr.id)) { + if (curr.id === ancestorId) return depth; + visited.add(curr.id); + curr = getParentNode(curr.id, allElements, parentMap); + depth++; + } + const fallbackNode = byId.get(nodeId); + return fallbackNode ? getHierarchy(fallbackNode, allElements, byId, parentMap).depth : 0; + }; + const getBranchElementIds = (nodeId, allElements) => { + const childMap = /* @__PURE__ */ new Map(); + const allArrows = []; + for (let i = 0; i < allElements.length; i++) { + const el = allElements[i]; + if (el.type === "arrow") { + allArrows.push(el); + if (el.customData?.isBranch && el.startBinding?.elementId && el.endBinding?.elementId) { + const start = el.startBinding.elementId; + const end = el.endBinding.elementId; + if (!childMap.has(start)) { + childMap.set(start, []); + } + childMap.get(start).push(end); + } + } + } + const branchNodes = /* @__PURE__ */ new Set([nodeId]); + const queue = [nodeId]; + while (queue.length > 0) { + const currentId = queue.shift(); + const currentNode = allElements.find((el) => el.id === currentId); + if (currentNode?.customData?.boundaryId) { + branchNodes.add(currentNode.customData.boundaryId); + } + const children = childMap.get(currentId); + if (children) { + for (let i = 0; i < children.length; i++) { + const childId = children[i]; + if (!branchNodes.has(childId)) { + branchNodes.add(childId); + queue.push(childId); + } + } + } + } + const branchElementIds = Array.from(branchNodes); + for (let i = 0; i < allArrows.length; i++) { + const el = allArrows[i]; + const startId = el.startBinding?.elementId; + const endId = el.endBinding?.elementId; + if (startId && endId && branchNodes.has(startId) && branchNodes.has(endId)) { + branchElementIds.push(el.id); + } + } + return branchElementIds; + }; + const getMindmapProjectElements = (rootId, allViewElements) => { + const branchIds = getBranchElementIds(rootId, allViewElements); + const decorationAndCrossLinkIds = runtimeContext.getDecorationAndCrossLinkIdsForBranches( + branchIds, + allViewElements, + rootId + ); + const projectElementIds = /* @__PURE__ */ new Set([...branchIds, ...decorationAndCrossLinkIds]); + const projectElements = []; + const addedIds = /* @__PURE__ */ new Set(); + const addWithDependencies = (id) => { + if (addedIds.has(id)) return; + const el = allViewElements.find((e) => e.id === id); + if (!el) return; + projectElements.push(el); + addedIds.add(id); + if (el.boundElements) { + el.boundElements.forEach((be) => addWithDependencies(be.id)); + } + if (el.containerId) { + addWithDependencies(el.containerId); + } + if (el.customData?.foldIndicatorId) { + addWithDependencies(el.customData.foldIndicatorId); + } + if (el.customData?.boundaryId) { + addWithDependencies(el.customData.boundaryId); + } + }; + projectElementIds.forEach((id) => addWithDependencies(id)); + return projectElements; + }; + return { + buildParentMap, + getParentNode, + buildElementMap, + buildChildrenMap, + getChildrenNodes, + buildGroupToNodes, + getMasterRoots, + getHierarchy, + getSettingsRootNode, + getDepthFromAncestor, + getBranchElementIds, + getMindmapProjectElements + }; + } + + // src/scripts/mindmap-builder/selection.js + function createSelection(runtimeContext) { + const selectNodeInView = (node) => { + if (!node) { + runtimeContext.mostRecentlySelectedNodeID = null; + return; + } + const nodeId = typeof node === "string" ? node : node.id; + runtimeContext.ea.selectElementsInView([nodeId]); + runtimeContext.mostRecentlySelectedNodeID = nodeId; + }; + const getBoundaryHost = (selectedElements) => { + if (selectedElements.length === 1 && selectedElements[0].type === "line" && selectedElements[0].customData?.hasOwnProperty("isBoundary")) { + const sel = selectedElements[0]; + const allElements = runtimeContext.ea.getViewElements(); + const owner = allElements.find((el) => el.customData?.boundaryId === sel.id); + return owner; + } + }; + const getMindmapNodeFromSelection = () => { + if (!runtimeContext.isViewSet()) return; + const selectedElements = runtimeContext.ea.getViewSelectedElements().filter( + (el) => el.customData && (el.customData.hasOwnProperty("mindmapOrder") || el.customData.hasOwnProperty("isBranch") || el.customData.hasOwnProperty("growthMode") || el.customData.hasOwnProperty("isBoundary")) + ); + if (selectedElements.length === 0) return; + const owner = getBoundaryHost(selectedElements); + if (owner) { + runtimeContext.mostRecentlySelectedNodeID = owner.id; + return owner; + } + if (selectedElements.length === 1 && (selectedElements[0].customData.hasOwnProperty("mindmapOrder") || selectedElements[0].customData.hasOwnProperty("growthMode"))) { + if (selectedElements[0].type === "text" && selectedElements[0].boundElements.length === 0 && !!selectedElements[0].containerId) { + const node = runtimeContext.ea.getViewElements().find((el) => el.id === selectedElements[0].containerId); + runtimeContext.mostRecentlySelectedNodeID = node?.id; + return node; + } + runtimeContext.mostRecentlySelectedNodeID = selectedElements?.[0]?.id; + return selectedElements[0]; + } + if (selectedElements.length === 1 && selectedElements[0].type === "arrow") { + const sel = selectedElements[0]; + const targetId = sel.startBinding?.elementId || sel.endBinding?.elementId; + if (targetId) { + const target = runtimeContext.ea.getViewElements().find((el) => el.id === targetId); + runtimeContext.mostRecentlySelectedNodeID = target?.id; + return target; + } + return; + } + if (selectedElements.length === 2) { + const textEl = selectedElements.find((el) => el.type === "text"); + if (textEl && textEl.boundElements.length > 0 && textEl.customData.hasOwnProperty("mindmapOrder")) { + runtimeContext.mostRecentlySelectedNodeID = textEl.id; + return textEl; + } else if (textEl) { + const containerId = textEl.containerId; + if (containerId) { + const container = selectedElements.find((el) => el.id === containerId); + if (container && container.boundElements.length > 0 && container.customData.hasOwnProperty("mindmapOrder")) { + runtimeContext.mostRecentlySelectedNodeID = container.id; + return container; + } + } + } + } + if (selectedElements.length > 1) { + const selectedIds = new Set(selectedElements.map((el) => el.id)); + const arrows = selectedElements.filter((el) => el.type === "arrow"); + const sourceIds = /* @__PURE__ */ new Set(); + const sinkIds = /* @__PURE__ */ new Set(); + arrows.forEach((arrow) => { + const startId = arrow.startBinding?.elementId; + const endId = arrow.endBinding?.elementId; + if (startId && selectedIds.has(startId)) sourceIds.add(startId); + if (endId && selectedIds.has(endId)) sinkIds.add(endId); + }); + const rootId = Array.from(sourceIds).find((id) => !sinkIds.has(id)); + if (rootId) { + runtimeContext.mostRecentlySelectedNodeID = rootId; + return selectedElements.find((el) => el.id === rootId); + } + } + }; + const ensureNodeSelected = () => { + const elementToSelect = getMindmapNodeFromSelection(); + if (elementToSelect) { + selectNodeInView(elementToSelect); + } + }; + const getMostRecentlyAddedNode = () => { + if (!runtimeContext.mostRecentlyAddedNodeID) return null; + return runtimeContext.ea.getViewElements().find((el) => el.id === runtimeContext.mostRecentlyAddedNodeID); + }; + return { + selectNodeInView, + getBoundaryHost, + getMindmapNodeFromSelection, + ensureNodeSelected, + getMostRecentlyAddedNode + }; + } + + // src/scripts/mindmap-builder/colors.js + function createColors(runtimeContext) { + const randInt = (range) => Math.round(Math.random() * range); + const getDynamicColor = (existingColors) => { + if (runtimeContext.multicolor && runtimeContext.customPalette.enabled && runtimeContext.customPalette.colors.length > 0) { + if (runtimeContext.customPalette.random) { + return runtimeContext.customPalette.colors[Math.floor(Math.random() * runtimeContext.customPalette.colors.length)]; + } + return runtimeContext.customPalette.colors[existingColors.length % runtimeContext.customPalette.colors.length]; + } + const st = runtimeContext.getAppState(); + const bg = st.viewBackgroundColor === "transparent" ? "#ffffff" : st.viewBackgroundColor; + const bgCM = runtimeContext.ea.getCM(bg); + const isDarkBg = bgCM.isDark(); + const getDist = (c1, c2) => { + let dh = Math.abs(c1.hue - c2.hue); + if (dh > 180) dh = 360 - dh; + const hScore = dh / 1.8; + return hScore * 2 + Math.abs(c1.saturation - c2.saturation) + Math.abs(c1.lightness - c2.lightness); + }; + let palette = st.colorPalette?.elementStroke || []; + if (Array.isArray(palette)) palette = palette.flat(Infinity); + const candidates = []; + new Set(palette).forEach((hex) => { + if (hex && hex !== "transparent") + candidates.push({ + hex, + isPalette: true + }); + }); + for (let h = 0; h < 360; h += runtimeContext.HUE_STEP_BASE + randInt(runtimeContext.HUE_STEP_JITTER)) { + const c = runtimeContext.ea.getCM({ + h, + s: runtimeContext.SAT_BASE + randInt(runtimeContext.SAT_JITTER), + l: isDarkBg ? runtimeContext.LIGHT_BASE_DARK + randInt(runtimeContext.LIGHT_JITTER_DARK) : runtimeContext.LIGHT_BASE_LIGHT + randInt(runtimeContext.LIGHT_JITTER_LIGHT), + a: 1 + }); + candidates.push({ + hex: c.stringHEX(), + isPalette: false + }); + } + const scored = candidates.map((c) => { + let cm = runtimeContext.ea.getCM(c.hex); + if (!cm) return null; + let contrast = cm.contrast({ + bgColor: bg + }); + if (contrast < 3) { + const originalL = cm.lightness; + const targetL = isDarkBg ? Math.min(originalL + 40, 90) : Math.max(originalL - 40, 20); + cm = cm.lightnessTo(targetL); + contrast = cm.contrast({ + bgColor: bg + }); + c.hex = cm.stringHEX({ + alpha: false + }); + } + let minDiff = 1e3; + let closestColor = null; + if (existingColors.length > 0) { + existingColors.forEach((exHex) => { + const exCM = runtimeContext.ea.getCM(exHex); + if (exCM) { + const d = getDist(cm, exCM); + if (d < minDiff) { + minDiff = d; + closestColor = exHex; + } + } + }); + } + return { + ...c, + contrast, + minDiff + }; + }).filter((c) => c && c.contrast >= runtimeContext.COLOR_CONTRAST_MIN); + scored.sort((a, b) => { + const threshold = runtimeContext.COLOR_DISTINCT_THRESHOLD; + const aIsDistinct = a.minDiff > threshold; + const bIsDistinct = b.minDiff > threshold; + if (aIsDistinct && !bIsDistinct) return -1; + if (!aIsDistinct && bIsDistinct) return 1; + if (a.isPalette !== b.isPalette) return a.isPalette ? -1 : 1; + return b.minDiff - a.minDiff; + }); + return scored[0]?.hex || "#000000"; + }; + return { randInt, getDynamicColor }; + } + + // src/scripts/mindmap-builder/folding.js + function createFolding(runtimeContext) { + const manageFoldIndicator = (node, show, allElements) => { + if (show) { + const children = runtimeContext.getChildrenNodes(node.id, allElements); + if (children.length === 0) show = false; + } + const existingId = node.customData?.foldIndicatorId; + let side = 1; + const parent = runtimeContext.getParentNode(node.id, allElements); + if (parent) { + const parentCenter = parent.x + parent.width / 2; + const nodeCenter = node.x + node.width / 2; + side = nodeCenter < parentCenter ? -1 : 1; + } + if (show) { + let ind; + if (existingId) { + ind = allElements.find((el) => el.id === existingId); + if (ind) { + ind.isDeleted = false; + ind.strokeColor = node.strokeColor; + ind.opacity = runtimeContext.layoutSettings.INDICATOR_OPACITY; + } + } + if (!ind) { + const fontSize = runtimeContext.ea.getBoundTextElement(node).eaElement?.fontSize || 20; + const id = runtimeContext.ea.addText(0, 0, "..."); + ind = runtimeContext.ea.getElement(id); + ind.fontSize = fontSize; + ind.strokeColor = node.strokeColor; + ind.opacity = runtimeContext.layoutSettings.INDICATOR_OPACITY; + ind.textVerticalAlign = "middle"; + if (node.groupIds && node.groupIds.length > 0) { + ind.groupIds = [node.groupIds[0]]; + } else { + runtimeContext.ea.addToGroup([node.id, id]); + } + runtimeContext.ea.addAppendUpdateCustomData(node.id, { + foldIndicatorId: id + }); + } + if (side === 1) { + ind.x = node.x + node.width + runtimeContext.layoutSettings.INDICATOR_OFFSET; + ind.textAlign = "left"; + } else { + ind.x = node.x - runtimeContext.layoutSettings.INDICATOR_OFFSET - ind.width; + ind.textAlign = "right"; + } + ind.y = node.y + node.height - ind.fontSize; + } else { + if (existingId) { + const ind = allElements.find((el) => el.id === existingId); + if (ind) ind.isDeleted = true; + runtimeContext.ea.addAppendUpdateCustomData(node.id, { + foldIndicatorId: void 0 + }); + } + } + }; + const setElementVisibility = (el, hide) => { + if (hide) { + if (!el.customData?.foldState) { + const safeOpacity = el.opacity === 0 ? 100 : el.opacity; + runtimeContext.ea.addAppendUpdateCustomData(el.id, { + foldState: { + opacity: safeOpacity, + locked: el.locked + } + }); + } + el.opacity = 0; + el.locked = true; + } else { + if (el.customData?.foldState) { + el.opacity = el.customData.foldState.opacity; + el.locked = el.customData.foldState.locked; + runtimeContext.ea.addAppendUpdateCustomData(el.id, { + foldState: void 0 + }); + } else { + if (el.opacity === 0) el.opacity = 100; + el.locked = false; + } + } + const boundTextElement = runtimeContext.ea.getBoundTextElement(el); + if (boundTextElement.eaElement && boundTextElement.eaElement !== el) { + setElementVisibility(boundTextElement?.eaElement, hide); + } + }; + const updateBranchVisibility = (nodeId, parentHidden, allElements, isRootOfFold, rootId) => { + const node = allElements.find((el) => el.id === nodeId); + if (!node) return; + const isFolded = node.customData?.isFolded === true; + const shouldHideThis = parentHidden && !isRootOfFold; + setElementVisibility(node, shouldHideThis); + const localNodeIds = /* @__PURE__ */ new Set([node.id]); + if (node.groupIds && node.groupIds.length > 0) { + const groupElements = runtimeContext.ea.getElementsInTheSameGroupWithElement( + node, + allElements + ); + const childrenIds = runtimeContext.getChildrenNodes(nodeId, allElements).map((c) => c.id); + groupElements.forEach((el) => { + if (el.id === node.id) return; + if (el.customData?.isBranch) return; + if (el.customData?.isBoundary) return; + if (el.id === node.customData?.foldIndicatorId) return; + if (childrenIds.includes(el.id)) return; + if (runtimeContext.isStructuralElement(el, allElements, rootId)) return; + setElementVisibility(el, shouldHideThis); + localNodeIds.add(el.id); + }); + } + const crossLinks = allElements.filter( + (el) => el.type === "arrow" && !el.customData?.isBranch && (el.startBinding && localNodeIds.has(el.startBinding.elementId) || el.endBinding && localNodeIds.has(el.endBinding.elementId)) + ); + crossLinks.forEach((arrow) => { + if (shouldHideThis) { + setElementVisibility(arrow, true); + } else { + const isStartLocal = arrow.startBinding && localNodeIds.has(arrow.startBinding.elementId); + const otherId = isStartLocal ? arrow.endBinding?.elementId : arrow.startBinding?.elementId; + const otherNode = allElements.find((e) => e.id === otherId); + if (otherNode && !otherNode.isDeleted && otherNode.opacity > 0) { + setElementVisibility(arrow, false); + } + } + }); + if (node.customData?.boundaryId) { + const boundEl = allElements.find((el) => el.id === node.customData.boundaryId); + if (boundEl) { + if (shouldHideThis || isFolded) { + boundEl.opacity = 0; + boundEl.locked = true; + } else { + boundEl.opacity = 30; + boundEl.locked = false; + } + } + } + const showIndicator = !shouldHideThis && isFolded; + manageFoldIndicator(node, showIndicator, allElements); + const childrenHidden = shouldHideThis || isFolded; + const children = runtimeContext.getChildrenNodes(nodeId, allElements); + children.forEach((child) => { + const arrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === nodeId && a.endBinding?.elementId === child.id + ); + if (arrow) { + setElementVisibility(arrow, childrenHidden); + } + updateBranchVisibility(child.id, childrenHidden, allElements, false, rootId); + }); + }; + const toggleFold = async (mode = "L0") => { + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + const allViewElements = runtimeContext.ea.getViewElements(); + const info = runtimeContext.getHierarchy(sel, allViewElements); + const projectElements = runtimeContext.getMindmapProjectElements(info.rootId, allViewElements); + runtimeContext.ea.copyViewElementsToEAforEditing(projectElements); + const wbElements = runtimeContext.ea.getElements(); + const targetNode = wbElements.find((el) => el.id === sel.id); + if (!targetNode) return; + const children = runtimeContext.getChildrenNodes(targetNode.id, wbElements); + if (children.length === 0) return; + if (mode === "L1") { + const hasGrandChildren = children.some( + (child) => runtimeContext.getChildrenNodes(child.id, wbElements).length > 0 + ); + if (!hasGrandChildren) return; + } + let isFoldAction = false; + if (mode === "L0") { + const isCurrentlyFolded = targetNode.customData?.isFolded === true; + isFoldAction = !isCurrentlyFolded; + runtimeContext.ea.addAppendUpdateCustomData(targetNode.id, { + isFolded: isFoldAction + }); + } else if (mode === "L1") { + runtimeContext.ea.addAppendUpdateCustomData(targetNode.id, { + isFolded: false + }); + const anyChildFolded = children.some((child) => child.customData?.isFolded === true); + isFoldAction = !anyChildFolded; + children.forEach((child) => { + runtimeContext.ea.addAppendUpdateCustomData(child.id, { + isFolded: isFoldAction + }); + }); + } else if (mode === "ALL") { + runtimeContext.ea.addAppendUpdateCustomData(targetNode.id, { + isFolded: false + }); + const nonLeafDescendants = []; + const stack = [...children]; + while (stack.length) { + const node = stack.pop(); + const nodeChildren = runtimeContext.getChildrenNodes(node.id, wbElements); + if (nodeChildren.length > 0) { + nonLeafDescendants.push(node); + nodeChildren.forEach((child) => stack.push(child)); + } + } + const anyDescendantFolded = nonLeafDescendants.some( + (node) => node.customData?.isFolded === true + ); + isFoldAction = !anyDescendantFolded; + nonLeafDescendants.forEach((node) => { + runtimeContext.ea.addAppendUpdateCustomData(node.id, { + isFolded: isFoldAction + }); + }); + } + updateBranchVisibility(targetNode.id, false, wbElements, true, info.rootId); + await runtimeContext.addElementsToView({ + captureUpdate: runtimeContext.autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" + }); + if (!runtimeContext.autoLayoutDisabled) { + await runtimeContext.triggerGlobalLayout(info.rootId); + } + runtimeContext.ea.viewUpdateScene({ + appState: { + selectedGroupIds: {} + } + }); + runtimeContext.focusSelected(); + }; + return { manageFoldIndicator, setElementVisibility, updateBranchVisibility, toggleFold }; + } + + // src/scripts/mindmap-builder/decorations.js + function createDecorations(runtimeContext) { + const moveCrossLinks = (allElements, originalPositions) => { + const crossLinkArrows = allElements.filter( + (el) => el.type === "arrow" && !el.customData?.isBranch && el.startBinding?.elementId && el.endBinding?.elementId + ); + const touched = /* @__PURE__ */ new Set(); + crossLinkArrows.forEach((arrow) => { + const startId = arrow.startBinding.elementId; + const endId = arrow.endBinding.elementId; + const startNodeOld = originalPositions.get(startId); + const endNodeOld = originalPositions.get(endId); + const startNodeNew = runtimeContext.ea.getElement(startId); + const endNodeNew = runtimeContext.ea.getElement(endId); + if (startNodeOld && endNodeOld && startNodeNew && endNodeNew) { + touched.add(arrow.id); + const dsX = startNodeNew.x - startNodeOld.x; + const dsY = startNodeNew.y - startNodeOld.y; + const deX = endNodeNew.x - endNodeOld.x; + const deY = endNodeNew.y - endNodeOld.y; + if (dsX === 0 && dsY === 0 && deX === 0 && deY === 0) return; + const eaArrow = runtimeContext.ea.getElement(arrow.id); + if (!eaArrow) return; + eaArrow.x += dsX; + eaArrow.y += dsY; + const diffX = deX - dsX; + const diffY = deY - dsY; + const len = eaArrow.points.length; + if (len > 0) { + eaArrow.points = eaArrow.points.map((p, i) => { + const t = i / (len - 1); + return [p[0] + diffX * t, p[1] + diffY * t]; + }); + } + } + }); + return touched; + }; + const moveDecorations = (allElements, originalPositions, groupToNodes, rootId, elementById, parentMap) => { + const structuralIds = /* @__PURE__ */ new Set(); + if (rootId) { + allElements.forEach((el) => { + if (runtimeContext.isStructuralElement(el, allElements, rootId, elementById, parentMap)) { + structuralIds.add(el.id); + } + }); + } + const decorationsToUpdate = []; + allElements.forEach((el) => { + const isStructural = structuralIds.has(el.id); + const isCrossLink = el.type === "arrow" && !el.customData?.isBranch && el.startBinding?.elementId && el.endBinding?.elementId; + const isDecoration = !isStructural && !isCrossLink && el.groupIds && el.groupIds.length > 0; + if (isDecoration) { + const hostNodes = /* @__PURE__ */ new Set(); + el.groupIds.forEach((gid) => { + const nodesInGroup = groupToNodes.get(gid); + if (nodesInGroup) { + nodesInGroup.forEach((node) => hostNodes.add(node)); + } + }); + if (hostNodes.size > 0) { + const nodesArray = Array.from(hostNodes); + let minXOld = Infinity, minYOld = Infinity, maxXOld = -Infinity, maxYOld = -Infinity; + let minXNew = Infinity, minYNew = Infinity, maxXNew = -Infinity, maxYNew = -Infinity; + let validHost = false; + nodesArray.forEach((n) => { + const oldPos = originalPositions.get(n.id); + const newEl = runtimeContext.ea.getElement(n.id); + if (oldPos && newEl) { + validHost = true; + minXOld = Math.min(minXOld, oldPos.x); + minYOld = Math.min(minYOld, oldPos.y); + maxXOld = Math.max(maxXOld, oldPos.x + n.width); + maxYOld = Math.max(maxYOld, oldPos.y + n.height); + minXNew = Math.min(minXNew, newEl.x); + minYNew = Math.min(minYNew, newEl.y); + maxXNew = Math.max(maxXNew, newEl.x + newEl.width); + maxYNew = Math.max(maxYNew, newEl.y + newEl.height); + } + }); + if (validHost) { + const oldCx = minXOld + (maxXOld - minXOld) / 2; + const oldCy = minYOld + (maxYOld - minYOld) / 2; + const newCx = minXNew + (maxXNew - minXNew) / 2; + const newCy = minYNew + (maxYNew - minYNew) / 2; + decorationsToUpdate.push({ + elementId: el.id, + dx: newCx - oldCx, + dy: newCy - oldCy + }); + } + } + } + }); + decorationsToUpdate.forEach((item) => { + if (Math.abs(item.dx) > 0.01 || Math.abs(item.dy) > 0.01) { + const decoration = runtimeContext.ea.getElement(item.elementId); + if (decoration) { + decoration.x += item.dx; + decoration.y += item.dy; + } + } + }); + return new Set(decorationsToUpdate.map((d) => d.elementId)); + }; + const scaleDecorations = (oldNode, newNode, allElements, rootId) => { + if (!oldNode.groupIds || oldNode.groupIds.length === 0) return; + const groupElements = runtimeContext.ea.getElementsInTheSameGroupWithElement( + oldNode, + allElements + ); + const decorations = groupElements.filter( + (el) => el.id !== oldNode.id && !runtimeContext.isStructuralElement(el, allElements, rootId) + ); + if (decorations.length === 0) return; + const oldCx = oldNode.x + oldNode.width / 2; + const oldCy = oldNode.y + oldNode.height / 2; + const newCx = newNode.x + newNode.width / 2; + const newCy = newNode.y + newNode.height / 2; + const ratioX = oldNode.width > 1 ? newNode.width / oldNode.width : 1; + const ratioY = oldNode.height > 1 ? newNode.height / oldNode.height : 1; + runtimeContext.ea.copyViewElementsToEAforEditing(decorations); + decorations.forEach((dec) => { + const el = runtimeContext.ea.getElement(dec.id); + if (!el) return; + const decCx = dec.x + dec.width / 2; + const decCy = dec.y + dec.height / 2; + const relX = (decCx - oldCx) / (oldNode.width / 2); + const relY = (decCy - oldCy) / (oldNode.height / 2); + const isInside = Math.abs(relX) <= 1.05 && Math.abs(relY) <= 1.05; + if (isInside) { + const dx = decCx - oldCx; + const dy = decCy - oldCy; + const newDx = dx * ratioX; + const newDy = dy * ratioY; + el.x = newCx + newDx - el.width / 2; + el.y = newCy + newDy - el.height / 2; + } else { + if (Math.abs(relX) > Math.abs(relY)) { + const sign = Math.sign(relX); + const oldEdgeX = oldCx + sign * oldNode.width / 2; + const gapX = decCx - oldEdgeX; + const newEdgeX = newCx + sign * newNode.width / 2; + const newDecCx = newEdgeX + gapX; + el.x = newDecCx - el.width / 2; + el.y = newCy + (decCy - oldCy) * ratioY - el.height / 2; + } else { + const sign = Math.sign(relY); + const oldEdgeY = oldCy + sign * oldNode.height / 2; + const gapY = decCy - oldEdgeY; + const newEdgeY = newCy + sign * newNode.height / 2; + const newDecCy = newEdgeY + gapY; + el.y = newDecCy - el.height / 2; + el.x = newCx + (decCx - oldCx) * ratioX - el.width / 2; + } + } + }); + }; + return { moveCrossLinks, moveDecorations, scaleDecorations }; + } + + // src/scripts/mindmap-builder/navigation.js + function createNavigation(runtimeContext) { + const nextZoomLevel = (current) => { + const idx = runtimeContext.ZOOM_TYPES.indexOf(current); + return idx === -1 ? runtimeContext.ZOOM_TYPES[0] : runtimeContext.ZOOM_TYPES[(idx + 1) % runtimeContext.ZOOM_TYPES.length]; + }; + const zoomToFit = (mode) => { + if (!runtimeContext.isViewSet()) return; + let sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel && runtimeContext.mostRecentlySelectedNodeID) { + const fallback = runtimeContext.ea.getViewElements().find((el) => el.id === runtimeContext.mostRecentlySelectedNodeID); + if (fallback) { + sel = fallback; + runtimeContext.selectNodeInView(sel); + runtimeContext.focusInputEl(); + } else { + runtimeContext.mostRecentlySelectedNodeID = null; + } + } + if (sel) { + let nextLevel = runtimeContext.zoomLevel; + if (typeof mode === "string") { + nextLevel = mode; + } else if (!!mode && runtimeContext.storedZoom.elementID === sel.id) { + nextLevel = nextZoomLevel(runtimeContext.storedZoom.level ?? runtimeContext.zoomLevel); + } + runtimeContext.storedZoom = { + elementID: sel.id, + level: nextLevel + }; + const targetZoom = runtimeContext.getZoom(nextLevel); + if (!runtimeContext.ea.verifyMinimumPluginVersion("2.26.0")) { + runtimeContext.api().scrollToContent([sel], { + fitToViewport: true, + viewportZoomFactor: targetZoom, + animate: true + }); + } else { + const appState = runtimeContext.api().getAppState(); + const targetW = appState.width / targetZoom; + const targetH = appState.height / targetZoom; + const cx = sel.x + sel.width / 2; + const cy = sel.y + sel.height / 2; + runtimeContext.api().setViewport({ + target: { + x: cx - targetW / 2, + y: cy - targetH / 2, + width: targetW, + height: targetH + }, + fit: "contain", + animation: true + }); + } + } + }; + const focusSelected = () => { + if (!runtimeContext.isViewSet()) return; + let sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) { + if (!runtimeContext.mostRecentlySelectedNodeID) { + const roots = runtimeContext.getMasterRoots(); + if (roots.length > 0) { + runtimeContext.mostRecentlySelectedNodeID = roots[0]; + } + if (!runtimeContext.mostRecentlySelectedNodeID) return; + } + const fallback = runtimeContext.ea.getViewElements().find((el) => el.id === runtimeContext.mostRecentlySelectedNodeID); + if (fallback) { + sel = fallback; + runtimeContext.selectNodeInView(sel); + runtimeContext.focusInputEl(); + } else { + runtimeContext.mostRecentlySelectedNodeID = null; + } + } + if (!sel) return; + if (!runtimeContext.ea.verifyMinimumPluginVersion("2.26.0")) { + runtimeContext.api().scrollToContent(sel, { + fitToContent: false, + animate: true + }); + } else { + runtimeContext.api().setViewport({ + target: [sel], + fit: "none", + animation: true + }); + } + }; + const navigateMap = async ({ key, zoom = false, focus = false } = {}) => { + if (!key) return; + if (!runtimeContext.isViewSet()) return; + let allElements = runtimeContext.ea.getViewElements(); + const current = runtimeContext.getMindmapNodeFromSelection(); + if (!current) return; + const info = runtimeContext.getHierarchy(current, allElements); + const parent = runtimeContext.getParentNode(current.id, allElements); + const currentSettingsRoot = runtimeContext.getSettingsRootNode(current, allElements); + const root = current.customData?.isAdditionalRoot === true && parent ? runtimeContext.getSettingsRootNode(parent, allElements) || currentSettingsRoot || allElements.find((e) => e.id === info.rootId) : currentSettingsRoot || allElements.find((e) => e.id === info.rootId); + if (!root) return; + const rootCenter = { + x: root.x + root.width / 2, + y: root.y + root.height / 2 + }; + const mapMode = root.customData?.growthMode || runtimeContext.currentModalGrowthMode; + const isVerticalLayout = ["Up-facing", "Down-facing", "Up-Down"].includes(mapMode); + if (current.id === root.id) { + if (current.customData?.isFolded) { + await runtimeContext.toggleFold("L0"); + allElements = runtimeContext.ea.getViewElements(); + } + const children = runtimeContext.getChildrenNodes(root.id, allElements); + if (children.length) { + runtimeContext.sortChildrenStable(children); + let targetChild = null; + if (isVerticalLayout) { + if (key === "ArrowLeft") targetChild = children[0]; + else if (key === "ArrowRight") targetChild = children[children.length - 1]; + else { + const childrenWithPos = children.map((c) => ({ + node: c, + dx: Math.abs(c.x + c.width / 2 - rootCenter.x), + // distance from vertical centerline + dy: c.y + c.height / 2 - rootCenter.y + })); + if (key === "ArrowDown") { + const downNodes = childrenWithPos.filter((c) => c.dy > 0).sort((a, b) => a.dx - b.dx); + targetChild = downNodes.length > 0 ? downNodes[0].node : children[0]; + } else if (key === "ArrowUp") { + const upNodes = childrenWithPos.filter((c) => c.dy < 0).sort((a, b) => a.dx - b.dx); + targetChild = upNodes.length > 0 ? upNodes[0].node : children[children.length - 1]; + } + } + } else { + if (key === "ArrowUp") targetChild = children[0]; + else if (key === "ArrowDown") targetChild = children[children.length - 1]; + else { + const childrenWithPos = children.map((c) => ({ + node: c, + dx: c.x + c.width / 2 - rootCenter.x, + dy: Math.abs(c.y + c.height / 2 - rootCenter.y) + // distance from horizontal centerline + })); + if (key === "ArrowRight") { + const rightNodes = childrenWithPos.filter((c) => c.dx > 0).sort((a, b) => a.dy - b.dy); + targetChild = rightNodes.length > 0 ? rightNodes[0].node : children[0]; + } else if (key === "ArrowLeft") { + const leftNodes = childrenWithPos.filter((c) => c.dx < 0).sort((a, b) => a.dy - b.dy); + targetChild = leftNodes.length > 0 ? leftNodes[0].node : children[children.length - 1]; + } + } + } + if (targetChild) { + runtimeContext.selectNodeInView(targetChild); + if (zoom) zoomToFit(); + if (focus) focusSelected(); + } + } + return; + } + const isHierarchyNav = isVerticalLayout ? key === "ArrowUp" || key === "ArrowDown" : key === "ArrowLeft" || key === "ArrowRight"; + const isSiblingNav = isVerticalLayout ? key === "ArrowLeft" || key === "ArrowRight" : key === "ArrowUp" || key === "ArrowDown"; + if (isHierarchyNav) { + const curCenter = { + x: current.x + current.width / 2, + y: current.y + current.height / 2 + }; + const isInPositive = isVerticalLayout ? curCenter.y > rootCenter.y : curCenter.x > rootCenter.x; + let goIn = false; + if (isVerticalLayout) { + goIn = key === "ArrowUp" && isInPositive || key === "ArrowDown" && !isInPositive; + } else { + goIn = key === "ArrowLeft" && isInPositive || key === "ArrowRight" && !isInPositive; + } + if (goIn) { + runtimeContext.selectNodeInView(runtimeContext.getParentNode(current.id, allElements)); + } else { + if (current.customData?.isFolded) { + await runtimeContext.toggleFold("L0"); + allElements = runtimeContext.ea.getViewElements(); + } + const ch = runtimeContext.getChildrenNodes(current.id, allElements).sort( + (a, b) => (a.customData?.mindmapOrder ?? 100) - (b.customData?.mindmapOrder ?? 100) + ); + if (ch.length) runtimeContext.selectNodeInView(ch[0]); + } + } else if (isSiblingNav) { + const parent2 = runtimeContext.getParentNode(current.id, allElements); + if (!parent2) return; + const siblings = runtimeContext.getChildrenNodes(parent2.id, allElements); + const parentCenter = { + x: parent2.x + parent2.width / 2, + y: parent2.y + parent2.height / 2 + }; + siblings.sort((a, b) => { + const aCX = a.x + a.width / 2; + const aCY = a.y + a.height / 2; + const bCX = b.x + b.width / 2; + const bCY = b.y + b.height / 2; + let aPoint = { + x: aCX, + y: aCY + }; + let bPoint = { + x: bCX, + y: bCY + }; + if (mapMode === "Radial") { + aPoint.x = aCX >= parentCenter.x ? a.x : a.x + a.width; + aPoint.y = aCY >= parentCenter.y ? a.y : a.y + a.height; + bPoint.x = bCX >= parentCenter.x ? b.x : b.x + b.width; + bPoint.y = bCY >= parentCenter.y ? b.y : b.y + b.height; + } else if (isVerticalLayout) { + aPoint.y = parentCenter.y + (aCY >= parentCenter.y ? 1e5 : -1e5); + bPoint.y = parentCenter.y + (bCY >= parentCenter.y ? 1e5 : -1e5); + } else { + aPoint.x = parentCenter.x + (aCX >= parentCenter.x ? 1e5 : -1e5); + bPoint.x = parentCenter.x + (bCX >= parentCenter.x ? 1e5 : -1e5); + } + return runtimeContext.getAngleFromCenter(parentCenter, aPoint) - runtimeContext.getAngleFromCenter(parentCenter, bPoint); + }); + const idx = siblings.findIndex((s) => s.id === current.id); + const startIndex = idx === -1 ? 0 : idx; + const currentIsNegativeBranch = isVerticalLayout ? current.y + current.height / 2 < parent2.y + parent2.height / 2 : current.x + current.width / 2 < parent2.x + parent2.width / 2; + let navigateForward; + if (isVerticalLayout) { + navigateForward = currentIsNegativeBranch ? key === "ArrowRight" : key === "ArrowLeft"; + } else { + navigateForward = currentIsNegativeBranch ? key === "ArrowUp" : key === "ArrowDown"; + } + let nIdx = navigateForward ? (startIndex + 1) % siblings.length : (startIndex - 1 + siblings.length) % siblings.length; + runtimeContext.selectNodeInView(siblings[nIdx]); + } + if (zoom) zoomToFit(); + if (focus) focusSelected(); + }; + return { nextZoomLevel, zoomToFit, focusSelected, navigateMap }; + } + + // src/scripts/mindmap-builder/layoutMetrics.js + function createLayoutMetrics(runtimeContext) { + const getMindmapOrder = (node) => { + const o = node?.customData?.mindmapOrder; + return typeof o === "number" && Number.isFinite(o) ? o : 0; + }; + const getNodeBox = (node, allElements) => { + if (node.groupIds && node.groupIds.length > 0) { + const groupElements = runtimeContext.ea.getElementsInTheSameGroupWithElement( + node, + allElements + ); + if (groupElements.length > 1) { + const box = ExcalidrawLib.getCommonBoundingBox(groupElements); + return { + ...box, + elements: groupElements, + isGroup: true + }; + } + } + return { + minX: node.x, + minY: node.y, + width: node.width, + height: node.height, + elements: [node], + isGroup: false + }; + }; + const sortChildrenStable = (children, allElements) => { + children.sort((a, b) => { + const ao = getMindmapOrder(a), bo = getMindmapOrder(b); + if (ao !== bo) return ao - bo; + const ya = allElements ? getNodeBox(a, allElements).minY : a.y; + const yb = allElements ? getNodeBox(b, allElements).minY : b.y; + const dy = ya - yb; + if (dy !== 0) return dy; + return String(a.id).localeCompare(String(b.id)); + }); + }; + const getSubtreeHeight = (nodeId, allElements, childrenByParent, heightCache, elementById) => { + if (heightCache?.has(nodeId)) return heightCache.get(nodeId); + const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); + if (!node) return 0; + if (node.customData?.isFolded) { + const foldedHeight = node.height; + if (heightCache) heightCache.set(nodeId, foldedHeight); + return foldedHeight; + } + if (node.customData?.isAdditionalRoot && node.customData?.autoLayoutDisabled) { + const branchIds = runtimeContext.getBranchElementIds(nodeId, allElements); + const branchElements = allElements.filter( + (el) => branchIds.includes(el.id) && el.opacity > 0 && !el.isDeleted + ); + const bbox = runtimeContext.ea.getBoundingBox(branchElements); + const height = bbox.height; + if (heightCache) heightCache.set(nodeId, height); + return height; + } + const children = childrenByParent?.get(nodeId) ?? runtimeContext.getChildrenNodes(nodeId, allElements); + const unpinnedChildren = children.filter((child) => !child.customData?.isPinned); + let totalHeight = 0; + if (unpinnedChildren.length === 0) { + totalHeight = node.height; + } else { + let childrenHeight = 0; + unpinnedChildren.forEach((child, index) => { + childrenHeight += getSubtreeHeight( + child.id, + allElements, + childrenByParent, + heightCache, + elementById + ); + if (index < unpinnedChildren.length - 1) { + const childNode = elementById?.get(child.id) ?? allElements.find((el) => el.id === child.id); + const grandChildren = childrenByParent?.get(child.id) ?? runtimeContext.getChildrenNodes(child.id, allElements); + const hasUnpinnedGrandChildren = grandChildren.some((gc) => !gc.customData?.isPinned); + const fontSize = childNode.fontSize ?? 20; + const gap = !hasUnpinnedGrandChildren ? Math.round(fontSize * runtimeContext.layoutSettings.GAP_MULTIPLIER) : runtimeContext.layoutSettings.GAP_Y; + childrenHeight += gap; + } + }); + totalHeight = Math.max(node.height, childrenHeight); + } + if (node.customData?.boundaryId) { + totalHeight += 30; + } + if (heightCache) heightCache.set(nodeId, totalHeight); + return totalHeight; + }; + const getSubtreeWidth = (nodeId, allElements, childrenByParent, widthCache, elementById) => { + if (widthCache?.has(nodeId)) return widthCache.get(nodeId); + const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); + if (!node) return 0; + if (node.customData?.isFolded) { + const foldedWidth = node.width; + if (widthCache) widthCache.set(nodeId, foldedWidth); + return foldedWidth; + } + const children = childrenByParent?.get(nodeId) ?? runtimeContext.getChildrenNodes(nodeId, allElements); + const unpinnedChildren = children.filter((child) => !child.customData?.isPinned); + let totalWidth = 0; + if (unpinnedChildren.length === 0) { + totalWidth = node.width; + } else { + let childrenWidth = 0; + unpinnedChildren.forEach((child, index) => { + childrenWidth += getSubtreeWidth( + child.id, + allElements, + childrenByParent, + widthCache, + elementById + ); + if (index < unpinnedChildren.length - 1) { + const childNode = elementById?.get(child.id) ?? allElements.find((el) => el.id === child.id); + const grandChildren = childrenByParent?.get(child.id) ?? runtimeContext.getChildrenNodes(child.id, allElements); + const hasUnpinnedGrandChildren = grandChildren.some((gc) => !gc.customData?.isPinned); + const fontSize = childNode.fontSize ?? 20; + const gap = !hasUnpinnedGrandChildren ? Math.round(fontSize * runtimeContext.layoutSettings.GAP_MULTIPLIER) : runtimeContext.layoutSettings.GAP_Y; + childrenWidth += gap; + } + }); + totalWidth = Math.max(node.width, childrenWidth); + } + if (node.customData?.boundaryId) { + totalWidth += 30; + } + if (widthCache) widthCache.set(nodeId, totalWidth); + return totalWidth; + }; + const getVerticalPlacementWidth = (nodeId, allElements, childrenByParent, widthCache, elementById, placementWidthCache = null) => { + if (placementWidthCache?.has(nodeId)) return placementWidthCache.get(nodeId); + const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); + if (!node) return 0; + const baseWidth = getSubtreeWidth( + nodeId, + allElements, + childrenByParent, + widthCache, + elementById + ); + if (node.customData?.isAdditionalRoot !== true || node.customData?.autoLayoutDisabled === true) { + if (placementWidthCache) placementWidthCache.set(nodeId, baseWidth); + return baseWidth; + } + const mode = node.customData?.growthMode; + if (!["Right-facing", "Left-facing", "Right-Left"].includes(mode)) { + if (placementWidthCache) placementWidthCache.set(nodeId, baseWidth); + return baseWidth; + } + const children = childrenByParent?.get(nodeId) ?? runtimeContext.getChildrenNodes(nodeId, allElements); + const unpinnedChildren = children.filter((child) => !child.customData?.isPinned); + if (unpinnedChildren.length === 0) { + if (placementWidthCache) placementWidthCache.set(nodeId, baseWidth); + return baseWidth; + } + const childWidths = unpinnedChildren.map( + (child) => getVerticalPlacementWidth( + child.id, + allElements, + childrenByParent, + widthCache, + elementById, + placementWidthCache + ) + ); + const primaryGap = runtimeContext.layoutSettings.GAP_X; + const compactMinWidth = node.width + runtimeContext.layoutSettings.GAP_Y * 2; + let projectedWidth; + if (mode === "Right-facing" || mode === "Left-facing") { + const maxChildWidth = childWidths.reduce((max, width) => Math.max(max, width), 0); + const directionalRawWidth = Math.max(node.width, node.width + primaryGap + maxChildWidth); + const singleSideBlend = runtimeContext.layoutSettings.VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE ?? runtimeContext.LAYOUT_METADATA.VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE.def; + projectedWidth = Math.max( + compactMinWidth, + node.width + (directionalRawWidth - node.width) * singleSideBlend + ); + } else { + const nodeCenterX = node.x + node.width / 2; + let leftMax = 0; + let rightMax = 0; + unpinnedChildren.forEach((child, index) => { + const childCenterX = child.x + child.width / 2; + if (childCenterX < nodeCenterX) { + leftMax = Math.max(leftMax, childWidths[index]); + } else { + rightMax = Math.max(rightMax, childWidths[index]); + } + }); + const directionalRawWidth = node.width + (leftMax > 0 ? primaryGap + leftMax : 0) + (rightMax > 0 ? primaryGap + rightMax : 0); + const dualSideBlend = runtimeContext.layoutSettings.VERTICAL_SUBTREE_WIDTH_BLEND_DUAL ?? runtimeContext.LAYOUT_METADATA.VERTICAL_SUBTREE_WIDTH_BLEND_DUAL.def; + projectedWidth = Math.max( + compactMinWidth, + node.width + (Math.max(node.width, directionalRawWidth) - node.width) * dualSideBlend + ); + } + if (node.customData?.boundaryId) { + projectedWidth += 30; + } + const effectiveWidth = Math.min(baseWidth, projectedWidth); + const widthExtra = Math.max(0, effectiveWidth - node.width); + const smoothThresholdMultiplier = runtimeContext.layoutSettings.VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER ?? runtimeContext.LAYOUT_METADATA.VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER.def; + const softThreshold = Math.max( + runtimeContext.layoutSettings.GAP_X, + runtimeContext.layoutSettings.GAP_Y * smoothThresholdMultiplier + ); + let smoothedWidth = effectiveWidth; + if (widthExtra > softThreshold) { + const smoothMinScale = runtimeContext.layoutSettings.VERTICAL_SUBTREE_SMOOTH_MIN_SCALE ?? runtimeContext.LAYOUT_METADATA.VERTICAL_SUBTREE_SMOOTH_MIN_SCALE.def; + const compressionScale = Math.max(smoothMinScale, runtimeContext.layoutSettings.GAP_X * 2); + const remaining = widthExtra - softThreshold; + const compressedRemaining = compressionScale * Math.log1p(remaining / compressionScale); + smoothedWidth = node.width + softThreshold + compressedRemaining; + } + if (placementWidthCache) placementWidthCache.set(nodeId, smoothedWidth); + return smoothedWidth; + }; + return { + getMindmapOrder, + getNodeBox, + sortChildrenStable, + getSubtreeHeight, + getSubtreeWidth, + getVerticalPlacementWidth + }; + } + + // src/scripts/mindmap-builder/grouping.js + function createGrouping(runtimeContext) { + const isStructuralElement = (el, allElements, rootId = null, elementById = null, parentMap = null) => { + const isStructuralType = el.customData?.isBranch || el.customData?.growthMode || el.customData?.isBoundary || typeof el.customData?.mindmapOrder !== "undefined"; + if (rootId && isStructuralType) { + let targetEl = el; + if (el.type === "arrow" && el.customData?.isBranch) { + const targetId = el.endBinding?.elementId || el.startBinding?.elementId; + if (targetId) { + targetEl = elementById?.get(targetId) || allElements.find((e) => e.id === targetId); + } + } + if (!targetEl) return false; + const info = runtimeContext.getHierarchy(targetEl, allElements, elementById, parentMap); + if (info?.rootId === rootId) return true; + if (info?.rootId) return false; + } + if (!rootId && isStructuralType) return true; + const connectedArrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && (a.startBinding?.elementId === el.id || a.endBinding?.elementId === el.id) + ); + return !!connectedArrow; + }; + const getViewGroupElements = (groupID) => { + return runtimeContext.ea.getViewElements().filter((el) => el.groupIds.includes(groupID)); + }; + const getCommonGroupForElements = (elements) => { + const groupIds = elements.map((el) => el.groupIds).reduce((prev, cur) => cur.filter((v) => prev.includes(v))); + return groupIds; + }; + const isMindmapGroup = (groupId, allElements) => { + const groupEls = allElements.filter((el) => el.groupIds?.includes(groupId)); + const structuralCount = groupEls.filter((el) => isStructuralElement(el, allElements)).length; + return structuralCount >= 2; + }; + const collectCrosslinkIds = (allElements) => new Set( + allElements.filter( + (el) => el.type === "arrow" && !el.customData?.isBranch && el.startBinding?.elementId && el.endBinding?.elementId + ).map((el) => el.id) + ); + const collectDecorationIds = (allElements, rootId) => new Set( + allElements.filter( + (el) => el.groupIds && el.groupIds.length > 0 && !isStructuralElement(el, allElements, rootId) + ).map((el) => el.id) + ); + const getStructuralGroup = (element, allElements, rootId) => { + if (!element.groupIds || element.groupIds.length === 0) return null; + return element.groupIds.find((gid) => isMindmapGroup(gid, allElements)); + }; + const applyRecursiveGrouping = (nodeId, allElements) => { + const children = runtimeContext.getChildrenNodes(nodeId, allElements); + const nodeIdsInSubtree = [nodeId]; + const node = allElements.find((el) => el.id === nodeId); + if (node?.customData?.boundaryId) { + nodeIdsInSubtree.push(node.customData.boundaryId); + } + children.forEach((child) => { + const subtreeIds = applyRecursiveGrouping(child.id, allElements); + nodeIdsInSubtree.push(...subtreeIds); + const arrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === nodeId && a.endBinding?.elementId === child.id + ); + if (arrow) { + nodeIdsInSubtree.push(arrow.id); + } + }); + if (nodeIdsInSubtree.length > 1) { + runtimeContext.ea.addToGroup(nodeIdsInSubtree); + } + return nodeIdsInSubtree; + }; + const getStructuralGroupForNode = (branchIds, workbenchEls, rootId) => { + const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches( + branchIds, + workbenchEls, + rootId + ); + const elements = workbenchEls.filter( + (el) => branchIds.includes(el.id) || decorationAndCrossLinkIds.includes(el.id) + ); + const commonGroupId = getCommonGroupForElements(elements)[0]; + const structuralGroupId = commonGroupId && isMindmapGroup(commonGroupId, workbenchEls) ? commonGroupId : null; + return { + structuralGroupId, + groupedElementIds: structuralGroupId ? elements.map((e) => e.id) : [] + }; + }; + const getStructuralGroupsForNode = (branchIds, workbenchEls, rootId) => { + const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches( + branchIds, + workbenchEls, + rootId + ); + const elements = workbenchEls.filter( + (el) => branchIds.includes(el.id) || decorationAndCrossLinkIds.includes(el.id) + ); + const commonGroupIds = getCommonGroupForElements(elements); + const structuralGroupIds = commonGroupIds.filter( + (commonGroupId) => isMindmapGroup(commonGroupId, workbenchEls) + ); + return { + structuralGroupIds, + groupedElementIds: elements.map((e) => e.id) + }; + }; + const removeGroupFromElements = (groupId, workbenchEls) => { + workbenchEls.forEach((el) => { + if (el.groupIds) { + el.groupIds = el.groupIds.filter((g) => g !== groupId); + } + }); + }; + const getDecorationAndCrossLinkIdsForBranches = (branchIds, allElements, rootId) => { + const idsInBranch = new Set(branchIds); + const decorationsAndCrossLInks = /* @__PURE__ */ new Set(); + const elementMap = /* @__PURE__ */ new Map(); + const groupMap = /* @__PURE__ */ new Map(); + for (const el of allElements) { + elementMap.set(el.id, el); + if (el.groupIds && el.groupIds.length > 0) { + for (const gid of el.groupIds) { + if (!groupMap.has(gid)) { + groupMap.set(gid, []); + } + groupMap.get(gid).push(el); + } + } + } + const processedGroups = /* @__PURE__ */ new Set(); + for (const id of branchIds) { + const el = elementMap.get(id); + if (el && el.groupIds && el.groupIds.length > 0) { + for (const gid of el.groupIds) { + if (processedGroups.has(gid)) continue; + processedGroups.add(gid); + const groupMembers = groupMap.get(gid) || []; + let hasOutsider = false; + const structuralMembers = []; + for (const member of groupMembers) { + if (idsInBranch.has(member.id) || isStructuralElement(member, allElements, rootId)) { + structuralMembers.push(member); + if (!idsInBranch.has(member.id)) { + hasOutsider = true; + break; + } + } + } + if (!hasOutsider) { + const structuralMemberIds = new Set(structuralMembers.map((e) => e.id)); + for (const member of groupMembers) { + if (!structuralMemberIds.has(member.id)) { + decorationsAndCrossLInks.add(member.id); + } + } + } + } + } + } + for (const el of allElements) { + if (idsInBranch.has(el.id) || decorationsAndCrossLInks.has(el.id)) continue; + if (el.type === "arrow" && !el.customData?.isBranch) { + if (el.startBinding?.elementId && el.endBinding?.elementId) { + if (idsInBranch.has(el.startBinding.elementId) && idsInBranch.has(el.endBinding.elementId)) { + decorationsAndCrossLInks.add(el.id); + if (el.boundElements && el.boundElements.length > 0) { + for (const bound of el.boundElements) { + if (bound.type === "text") decorationsAndCrossLInks.add(bound.id); + } + } + } + } + } + } + return Array.from(decorationsAndCrossLInks); + }; + const toggleBranchGroup = async () => { + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + const info = runtimeContext.getHierarchy(sel, runtimeContext.ea.getViewElements()); + if (!info || !info.rootId) return; + const allElements = runtimeContext.ea.getViewElements(); + const branchIds = runtimeContext.getBranchElementIds(sel.id, allElements); + const decorationAndCrossLinkIds = getDecorationAndCrossLinkIdsForBranches( + branchIds, + allElements, + info.rootId + ); + if (branchIds.length <= 1) return; + runtimeContext.ea.copyViewElementsToEAforEditing( + allElements.filter( + (el) => branchIds.includes(el.id) || decorationAndCrossLinkIds.includes(el.id) + ) + ); + const workbenchEls = runtimeContext.ea.getElements(); + let newGroupId; + let { structuralGroupIds, groupedElementIds } = getStructuralGroupsForNode( + branchIds, + workbenchEls, + info.rootId + ); + if (structuralGroupIds.length > 0) { + structuralGroupIds.forEach((structuralGroupId) => { + if (getViewGroupElements(structuralGroupId).length === groupedElementIds.length) { + removeGroupFromElements(structuralGroupId, workbenchEls); + } + }); + } else { + newGroupId = runtimeContext.ea.addToGroup([...branchIds, ...decorationAndCrossLinkIds]); + } + await runtimeContext.addElementsToView({ + captureUpdate: "IMMEDIATELY" + }); + if (newGroupId) { + let selectedGroupIds = {}; + selectedGroupIds[newGroupId] = true; + runtimeContext.ea.viewUpdateScene({ + appState: { + selectedGroupIds, + selectedElementIds: {} + } + }); + } else { + runtimeContext.ea.viewUpdateScene({ + appState: { + selectedGroupIds: {}, + selectedElementIds: { + [sel.id]: true + } + } + }); + } + runtimeContext.updateUI(); + }; + return { + isStructuralElement, + getViewGroupElements, + getCommonGroupForElements, + isMindmapGroup, + collectCrosslinkIds, + collectDecorationIds, + getStructuralGroup, + applyRecursiveGrouping, + getStructuralGroupForNode, + getStructuralGroupsForNode, + removeGroupFromElements, + getDecorationAndCrossLinkIdsForBranches, + toggleBranchGroup + }; + } + + // src/scripts/mindmap-builder/boundaries.js + function createBoundaries(runtimeContext) { + const getAngleFromCenter = (center, point) => { + let dx = point.x - center.x, dy = point.y - center.y; + let angle = Math.atan2(dx, -dy) * (180 / Math.PI); + return angle < 0 ? angle + 360 : angle; + }; + const getConvexHull = (points) => { + points.sort((a, b) => a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]); + const n = points.length; + if (n <= 2) return points; + const cross = (a, b, o) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); + const lower = []; + for (let i = 0; i < n; i++) { + while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], points[i]) <= 0) { + lower.pop(); + } + lower.push(points[i]); + } + const upper = []; + for (let i = n - 1; i >= 0; i--) { + while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], points[i]) <= 0) { + upper.pop(); + } + upper.push(points[i]); + } + upper.pop(); + lower.pop(); + return lower.concat(upper); + }; + const updateNodeBoundary = (node, allElements, rootId) => { + const boundaryId = node.customData?.boundaryId; + if (!boundaryId) { + return; + } + if (node.opacity === 0) return; + const ids = runtimeContext.getBranchElementIds(node.id, allElements); + const branchElements = allElements.filter( + (el) => ids.includes(el.id) && el.id !== boundaryId && el.opacity > 0 && !el.isDeleted + ); + if (branchElements.length === 0) return; + const root = allElements.find((el) => el.id === rootId); + const growthMode = root?.customData?.growthMode || runtimeContext.currentModalGrowthMode; + const isVerticalBoundaryMode = growthMode === "Up-facing" || growthMode === "Down-facing" || growthMode === "Up-Down"; + const padding = 15; + let allPoints = []; + branchElements.forEach((el) => { + if (isVerticalBoundaryMode && el.type === "arrow" && Array.isArray(el.points) && el.points.length > 0) { + el.points.forEach(([px, py]) => { + const x = el.x + px; + const y = el.y + py; + allPoints.push([x - padding, y - padding]); + allPoints.push([x + padding, y - padding]); + allPoints.push([x + padding, y + padding]); + allPoints.push([x - padding, y + padding]); + }); + return; + } + const x1 = el.x - padding; + const y1 = el.y - padding; + const x2 = el.x + el.width + padding; + const y2 = el.y + el.height + padding; + allPoints.push([x1, y1]); + allPoints.push([x2, y1]); + allPoints.push([x2, y2]); + allPoints.push([x1, y2]); + }); + const hullPoints = getConvexHull(allPoints); + if (hullPoints.length < 3) return; + const subdividedPoints = []; + const MAX_SEGMENT_LENGTH = runtimeContext.layoutSettings.MAX_SEGMENT_LENGTH ?? runtimeContext.LAYOUT_METADATA.MAX_SEGMENT_LENGTH.def; + for (let i = 0; i < hullPoints.length; i++) { + const p1 = hullPoints[i]; + const p2 = hullPoints[(i + 1) % hullPoints.length]; + subdividedPoints.push(p1); + const dist = Math.hypot(p2[0] - p1[0], p2[1] - p1[1]); + if (dist > MAX_SEGMENT_LENGTH) { + const steps = Math.ceil(dist / MAX_SEGMENT_LENGTH); + for (let j = 1; j < steps; j++) { + subdividedPoints.push([ + p1[0] + (p2[0] - p1[0]) * (j / steps), + p1[1] + (p2[1] - p1[1]) * (j / steps) + ]); + } + } + } + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + hullPoints.forEach((p) => { + if (p[0] < minX) minX = p[0]; + if (p[1] < minY) minY = p[1]; + if (p[0] > maxX) maxX = p[0]; + if (p[1] > maxY) maxY = p[1]; + }); + const w = maxX - minX; + const h = maxY - minY; + let boundaryEl = runtimeContext.ea.getElement(boundaryId); + if (!boundaryEl) return; + boundaryEl.x = minX; + boundaryEl.y = minY; + boundaryEl.width = w; + boundaryEl.height = h; + const normalizedPoints = subdividedPoints.map((p) => [p[0] - minX, p[1] - minY]); + normalizedPoints.push([normalizedPoints[0][0], normalizedPoints[0][1]]); + boundaryEl.points = normalizedPoints; + boundaryEl.roundness = runtimeContext.arrowType === "curved" ? { + type: 2 + } : null; + boundaryEl.polygon = true; + boundaryEl.locked = false; + if (node.groupIds.length > 0 && runtimeContext.isMindmapGroup(node.groupIds[0], allElements)) { + if (!boundaryEl.groupIds || boundaryEl.groupIds.length === 0 || boundaryEl.groupIds[0] !== node.groupIds[0]) { + boundaryEl.groupIds = [node.groupIds[0]]; + } + } else { + boundaryEl.groupIds = []; + } + }; + const toggleBoundary = async () => { + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (sel) { + const info = runtimeContext.getHierarchy(sel, runtimeContext.ea.getViewElements()); + runtimeContext.ea.copyViewElementsToEAforEditing([sel]); + const eaSel = runtimeContext.ea.getElement(sel.id); + let newBoundaryId = null; + if (eaSel.customData?.boundaryId) { + const b = runtimeContext.ea.getViewElements().find((el) => el.id === eaSel.customData.boundaryId); + if (b) { + runtimeContext.ea.copyViewElementsToEAforEditing([b]); + runtimeContext.ea.getElement(b.id).isDeleted = true; + } + runtimeContext.ea.addAppendUpdateCustomData(sel.id, { + boundaryId: void 0 + }); + } else { + const id = runtimeContext.ea.generateElementId(); + newBoundaryId = id; + const st = runtimeContext.getAppState(); + const boundaryEl = { + id, + type: "line", + x: sel.x, + y: sel.y, + width: 1, + height: 1, + angle: 0, + roughness: st.currentItemRoughness, + strokeColor: sel.strokeColor, + backgroundColor: sel.strokeColor, + fillStyle: "solid", + strokeWidth: 2, + strokeStyle: "solid", + opacity: 30, + points: [ + [0, 0], + [1, 1], + [0, 0] + ], + polygon: true, + locked: false, + groupIds: sel.groupIds || [], + customData: { + isBoundary: true + }, + roundness: runtimeContext.arrowType === "curved" ? { + type: 2 + } : null + }; + if (sel.groupIds.length > 0 && runtimeContext.isMindmapGroup(sel.groupIds[0], runtimeContext.ea.getViewElements())) { + boundaryEl.groupIds = [sel.groupIds[0]]; + } else { + boundaryEl.groupIds = []; + } + runtimeContext.ea.elementsDict[id] = boundaryEl; + runtimeContext.ea.addAppendUpdateCustomData(sel.id, { + boundaryId: id + }); + } + await runtimeContext.addElementsToView({ + newElementsOnTop: false, + captureUpdate: "EVENTUALLY" + }); + if (newBoundaryId) { + const els = runtimeContext.ea.getViewElements(); + let parentBoundaryIndex = -1; + let curr = sel; + while (curr) { + const parent = runtimeContext.getParentNode(curr.id, els); + if (!parent) break; + if (parent.customData?.boundaryId) { + const pIndex = els.findIndex((el) => el.id === parent.customData.boundaryId); + if (pIndex !== -1) { + parentBoundaryIndex = pIndex; + break; + } + } + curr = parent; + } + const targetIndex = parentBoundaryIndex !== -1 ? parentBoundaryIndex + 1 : 0; + runtimeContext.ea.moveViewElementToZIndex(newBoundaryId, targetIndex); + } + await runtimeContext.triggerGlobalLayout(info.rootId); + } + runtimeContext.updateUI(); + }; + return { getAngleFromCenter, getConvexHull, updateNodeBoundary, toggleBoundary }; + } + + // src/scripts/mindmap-builder/arrows.js + function createArrows(runtimeContext) { + const addUpdateArrowLabel = (arrow, text) => { + if (!arrow) { + return; + } + const maybeTextElement = runtimeContext.ea.getBoundTextElement(arrow, true); + let textElement = maybeTextElement.eaElement; + if (!textElement && maybeTextElement.sceneElement) { + runtimeContext.ea.copyViewElementsToEAforEditing([maybeTextElement.sceneElement]); + textElement = runtimeContext.ea.getElement(maybeTextElement.sceneElement.id); + } + if (textElement) { + if (!text) { + textElement.isDeleted = true; + } else { + textElement.rawText = text; + textElement.text = text; + textElement.originalText = text; + } + return; + } + if (!text) { + return; + } + const x = arrow.x + arrow.width / 2; + const y = arrow.y + arrow.height / 2; + const textId = runtimeContext.ea.addText(x, y, text); + const textEl = runtimeContext.ea.getElement(textId); + textEl.strokeColor = arrow.strokeColor; + textEl.containerId = arrow.id; + textEl.textAlign = "center"; + textEl.textVerticalAlign = "middle"; + textEl.fontSize = Math.floor(textEl.fontSize / 2); + arrow.boundElements = [ + { + type: "text", + id: textId + } + ]; + }; + const configureArrow = (context) => { + const { + arrowId, + isChildRight, + isChildBelow, + startId, + endId, + coordinates, + isRadial, + layoutDirection + } = context; + const { sX, sY, eX, eY } = coordinates; + const eaArrow = runtimeContext.ea.getElement(arrowId); + const isVertical = layoutDirection === "vertical"; + if (isVertical) { + const startRatio = isRadial ? 0.50001 : isChildBelow ? 0.9999 : 1e-4; + const endRatio = isChildBelow ? 1e-4 : 0.9999; + const centerRatio = 0.5001; + eaArrow.startBinding = { + ...eaArrow.startBinding, + elementId: startId, + mode: "orbit", + fixedPoint: [centerRatio, startRatio] + }; + eaArrow.endBinding = { + ...eaArrow.endBinding, + elementId: endId, + mode: "orbit", + fixedPoint: [centerRatio, endRatio] + }; + eaArrow.x = sX; + eaArrow.y = sY; + const dx = eX - sX; + const dy = eY - sY; + if (runtimeContext.arrowType === "straight") { + eaArrow.roundness = null; + eaArrow.points = [ + [0, 0], + [dx, dy] + ]; + } else { + eaArrow.roundness = { + type: 2 + }; + if (isRadial) { + eaArrow.points = [ + [0, 0], + [dx * 0.75, dy * 2 / 3], + [dx, dy] + ]; + } else { + eaArrow.points = [ + [0, 0], + [dx * 0.25, dy / 3], + [dx * 0.75, dy * 2 / 3], + [dx, dy] + ]; + } + } + } else { + const startRatio = isRadial ? 0.50001 : isChildRight ? 0.9999 : 1e-4; + const endRatio = isChildRight ? 1e-4 : 0.9999; + const centerYRatio = 0.5001; + eaArrow.startBinding = { + ...eaArrow.startBinding, + elementId: startId, + mode: "orbit", + fixedPoint: [startRatio, centerYRatio] + }; + eaArrow.endBinding = { + ...eaArrow.endBinding, + elementId: endId, + mode: "orbit", + fixedPoint: [endRatio, centerYRatio] + }; + eaArrow.x = sX; + eaArrow.y = sY; + const dx = eX - sX; + const dy = eY - sY; + if (runtimeContext.arrowType === "straight") { + eaArrow.roundness = null; + eaArrow.points = [ + [0, 0], + [dx, dy] + ]; + } else { + eaArrow.roundness = { + type: 2 + }; + if (isRadial) { + eaArrow.points = [ + [0, 0], + [dx * 2 / 3, dy * 0.75], + [dx, dy] + ]; + } else { + eaArrow.points = [ + [0, 0], + [dx / 3, dy * 0.25], + [dx * 2 / 3, dy * 0.75], + [dx, dy] + ]; + } + } + } + }; + const updateL1Arrow = (node, context, layoutDirection = "horizontal") => { + const { rootId, rootCenter, mode } = context; + const arrow = runtimeContext.ea.getElements().find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === rootId && a.endBinding?.elementId === node.id + ); + if (arrow) { + const childNode = runtimeContext.ea.getElement(node.id); + const rootNode = runtimeContext.ea.getElement(rootId); + if (!childNode || !rootNode) return; + const isRadial = mode === "Radial"; + if (layoutDirection === "vertical") { + const childCenterY = childNode.y + childNode.height / 2; + const isChildBelow = childCenterY > rootCenter.y; + const sX = rootCenter.x; + const sY = isRadial ? rootCenter.y : isChildBelow ? rootNode.y + rootNode.height : rootNode.y; + const eX = childNode.x + childNode.width / 2; + const eY = isChildBelow ? childNode.y : childNode.y + childNode.height; + configureArrow({ + arrowId: arrow.id, + isChildBelow, + startId: rootId, + endId: node.id, + coordinates: { + sX, + sY, + eX, + eY + }, + isRadial, + layoutDirection + }); + } else { + const childCenterX = childNode.x + childNode.width / 2; + const isChildRight = childCenterX > rootCenter.x; + const sX = isRadial ? rootCenter.x : isChildRight ? rootNode.x + rootNode.width : rootNode.x; + const sY = rootCenter.y; + const eX = isChildRight ? childNode.x : childNode.x + childNode.width; + const eY = childNode.y + childNode.height / 2; + configureArrow({ + arrowId: arrow.id, + isChildRight, + startId: rootId, + endId: node.id, + coordinates: { + sX, + sY, + eX, + eY + }, + isRadial, + layoutDirection + }); + } + } + }; + const reconnectArrow = (currentBindingElement, newBindingElement, arrow, side = "start") => { + const elementsToCheck = [currentBindingElement, newBindingElement, arrow]; + const elementsToCopy = elementsToCheck.filter((el) => !runtimeContext.ea.getElement(el.id)); + if (elementsToCopy.length > 0) { + runtimeContext.ea.copyViewElementsToEAforEditing(elementsToCopy); + } + const oldNode = runtimeContext.ea.getElement(currentBindingElement.id); + const newNode = runtimeContext.ea.getElement(newBindingElement.id); + const targetArrow = runtimeContext.ea.getElement(arrow.id); + const bindingKey = side === "start" ? "startBinding" : "endBinding"; + targetArrow[bindingKey] = { + ...targetArrow[bindingKey] || {}, + elementId: newNode.id + }; + if (oldNode.boundElements) { + oldNode.boundElements = oldNode.boundElements.filter((be) => be.id !== targetArrow.id); + } + if (!newNode.boundElements) newNode.boundElements = []; + if (!newNode.boundElements.some((be) => be.id === targetArrow.id)) { + newNode.boundElements.push({ + type: "arrow", + id: targetArrow.id + }); + } + }; + return { addUpdateArrowLabel, configureArrow, updateL1Arrow, reconnectArrow }; + } + + // src/scripts/mindmap-builder/horizontalLayout.js + function createHorizontalLayout(runtimeContext) { + const layoutChildrenAsAdditionalRoot = (nodeId, allElements, hasGlobalFolds, childrenByParent, heightCache, widthCache, elementById, mustHonorMindmapOrder = false, parentMap = null) => { + const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); + if (!node || node.customData?.isAdditionalRoot !== true) return false; + const l1Nodes = runtimeContext.getChildrenNodes(nodeId, allElements); + if (l1Nodes.length === 0) return false; + runtimeContext.withRootLayoutContext(node, (cfg) => { + const localHeightCache = heightCache ?? /* @__PURE__ */ new Map(); + const localWidthCache = widthCache ?? /* @__PURE__ */ new Map(); + const eaNode = runtimeContext.ea.getElement(nodeId); + if (!eaNode) return; + const rootBox = runtimeContext.getNodeBox(eaNode, allElements); + const rootCenter = { + x: rootBox.minX + rootBox.width / 2, + y: rootBox.minY + rootBox.height / 2 + }; + const mode = cfg.growthMode; + const layoutContext = { + allElements, + rootId: nodeId, + rootBox, + rootCenter, + hasGlobalFolds, + mode, + childrenByParent, + heightCache: localHeightCache, + widthCache: localWidthCache, + elementById, + parentMap + }; + if (!mustHonorMindmapOrder) { + runtimeContext.sortL1NodesBasedOnVisualSequence(l1Nodes, mode, rootCenter); + } + if (mode === "Radial") { + runtimeContext.layoutL1Nodes( + l1Nodes, + { + sortMethod: "radial", + centerAngle: null, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_RADIAL, + fillSweep: cfg.fillSweep + }, + layoutContext, + mustHonorMindmapOrder + ); + return; + } + if (["Right-facing", "Left-facing", "Right-Left"].includes(mode)) { + const leftNodes = []; + const rightNodes = []; + if (mode === "Right-Left") { + l1Nodes.forEach((child) => { + const childCX = child.x + child.width / 2; + if (childCX > rootCenter.x) rightNodes.push(child); + else leftNodes.push(child); + }); + if ((leftNodes.length === 0 || rightNodes.length === 0) && l1Nodes.length > 1) { + leftNodes.length = 0; + rightNodes.length = 0; + const splitIdx = Math.ceil(l1Nodes.length / 2); + l1Nodes.forEach((child, i) => { + if (i < splitIdx) rightNodes.push(child); + else leftNodes.push(child); + }); + } + } else if (mode === "Left-facing") { + l1Nodes.forEach((child) => leftNodes.push(child)); + } else { + l1Nodes.forEach((child) => rightNodes.push(child)); + } + if (rightNodes.length > 0) { + runtimeContext.layoutL1Nodes( + rightNodes, + { + sortMethod: "vertical", + centerAngle: 90, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_DIRECTIONAL + }, + layoutContext, + mustHonorMindmapOrder + ); + } + if (leftNodes.length > 0) { + runtimeContext.layoutL1Nodes( + leftNodes, + { + sortMethod: "vertical", + centerAngle: 270, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_DIRECTIONAL + }, + layoutContext, + mustHonorMindmapOrder + ); + } + return; + } + const upNodes = []; + const downNodes = []; + if (mode === "Up-Down") { + l1Nodes.forEach((child) => { + const childCY = child.y + child.height / 2; + if (childCY > rootCenter.y) downNodes.push(child); + else upNodes.push(child); + }); + if ((upNodes.length === 0 || downNodes.length === 0) && l1Nodes.length > 1) { + upNodes.length = 0; + downNodes.length = 0; + const splitIdx = Math.ceil(l1Nodes.length / 2); + l1Nodes.forEach((child, i) => { + if (i < splitIdx) downNodes.push(child); + else upNodes.push(child); + }); + } + } else if (mode === "Up-facing") { + l1Nodes.forEach((child) => upNodes.push(child)); + } else { + l1Nodes.forEach((child) => downNodes.push(child)); + } + layoutContext.widthCache = /* @__PURE__ */ new Map(); + if (downNodes.length > 0) { + runtimeContext.layoutL1Nodes( + downNodes, + { + sortMethod: "horizontal", + centerAngle: 90, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_DIRECTIONAL + }, + layoutContext, + mustHonorMindmapOrder + ); + } + if (upNodes.length > 0) { + runtimeContext.layoutL1Nodes( + upNodes, + { + sortMethod: "horizontal", + centerAngle: 270, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_DIRECTIONAL + }, + layoutContext, + mustHonorMindmapOrder + ); + } + }); + return true; + }; + const layoutSubtree = (nodeId, targetX, targetCenterY, side, allElements, hasGlobalFolds, childrenByParent, heightCache, elementById, mustHonorMindmapOrder = false, rootId, parentMap = null) => { + const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); + const eaNode = runtimeContext.ea.getElement(nodeId); + const isPinned = node.customData?.isPinned === true; + let dx = 0, dy = 0; + if (!isPinned) { + const newX = side === 1 ? targetX : targetX - node.width; + const newY = targetCenterY - node.height / 2; + dx = newX - eaNode.x; + dy = newY - eaNode.y; + eaNode.x = newX; + eaNode.y = newY; + } + if (node.customData?.isFolded) return; + const currentX = eaNode.x; + const currentYCenter = eaNode.y + node.height / 2; + let effectiveSide = side; + const parent = runtimeContext.getParentNode(nodeId, allElements, parentMap); + if (parent) { + const parentCenterX = parent.x + parent.width / 2; + const nodeCenterX = currentX + node.width / 2; + effectiveSide = nodeCenterX >= parentCenterX ? 1 : -1; + } + if (node.customData?.foldIndicatorId) { + const ind = runtimeContext.ea.getElement(node.customData.foldIndicatorId); + if (ind) { + if (effectiveSide === 1) { + ind.x = eaNode.x + eaNode.width + runtimeContext.layoutSettings.INDICATOR_OFFSET; + ind.textAlign = "left"; + } else { + ind.x = eaNode.x - runtimeContext.layoutSettings.INDICATOR_OFFSET - ind.width; + ind.textAlign = "right"; + } + ind.y = eaNode.y + eaNode.height / 2 - ind.height / 2; + } + } + const textElement = runtimeContext.ea.getBoundTextElement(eaNode).eaElement; + if (textElement && !runtimeContext.centerText && textElement.textAlign !== "center") { + textElement.textAlign = effectiveSide === 1 ? "left" : "right"; + } + const children = childrenByParent?.get(nodeId) ?? runtimeContext.getChildrenNodes(nodeId, allElements); + if (node.customData?.isAdditionalRoot === true) { + if (node.customData?.autoLayoutDisabled) { + if (dx !== 0 || dy !== 0) { + const branchIds = runtimeContext.getBranchElementIds(nodeId, allElements); + const descendants = branchIds.filter((id) => id !== nodeId); + descendants.forEach((descId) => { + const descNode = elementById?.get(descId) ?? allElements.find((e) => e.id === descId); + if (descNode?.customData?.isPinned) return; + if (descNode && descNode.type === "arrow" && !descNode.customData?.isBranch) return; + if (!runtimeContext.ea.getElement(descId)) { + if (descNode) runtimeContext.ea.copyViewElementsToEAforEditing([descNode]); + } + const descEl = runtimeContext.ea.getElement(descId); + if (descEl) { + descEl.x += dx; + descEl.y += dy; + } + }); + } + } else { + layoutChildrenAsAdditionalRoot( + nodeId, + allElements, + hasGlobalFolds, + childrenByParent, + heightCache, + null, + elementById, + mustHonorMindmapOrder, + parentMap + ); + } + if (node.customData?.boundaryId) { + runtimeContext.updateNodeBoundary(node, runtimeContext.ea.getElements(), rootId); + } + return; + } + const unpinnedChildren = children.filter((child) => !child.customData?.isPinned); + const pinnedChildren = children.filter((child) => child.customData?.isPinned); + if (unpinnedChildren.length > 0) { + unpinnedChildren.sort((a, b) => { + if (mustHonorMindmapOrder) { + return runtimeContext.getMindmapOrder(a) - runtimeContext.getMindmapOrder(b); + } + const dy2 = a.y - b.y; + if (dy2 !== 0) return dy2; + return String(a.id).localeCompare(String(b.id)); + }); + if (!mustHonorMindmapOrder) { + unpinnedChildren.forEach((child, i) => { + if (runtimeContext.getMindmapOrder(child) !== i) { + runtimeContext.ea.addAppendUpdateCustomData(child.id, { + mindmapOrder: i + }); + } + }); + } + const subtreeHeight = runtimeContext.getSubtreeHeight( + nodeId, + allElements, + childrenByParent, + heightCache, + elementById + ); + let currentY = currentYCenter - subtreeHeight / 2; + const dynamicGapX = runtimeContext.layoutSettings.GAP_X; + unpinnedChildren.forEach((child) => { + const childH = runtimeContext.getSubtreeHeight( + child.id, + allElements, + childrenByParent, + heightCache, + elementById + ); + layoutSubtree( + child.id, + effectiveSide === 1 ? currentX + node.width + dynamicGapX : currentX - dynamicGapX, + currentY + childH / 2, + effectiveSide, + allElements, + hasGlobalFolds, + childrenByParent, + heightCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ); + const childNode = elementById?.get(child.id) ?? allElements.find((el) => el.id === child.id); + const grandChildren = childrenByParent?.get(child.id) ?? runtimeContext.getChildrenNodes(child.id, allElements); + const hasUnpinnedGrandChildren = grandChildren.some((gc) => !gc.customData?.isPinned); + const fontSize = childNode.fontSize ?? 20; + const gap = !hasUnpinnedGrandChildren ? Math.round(fontSize * runtimeContext.layoutSettings.GAP_MULTIPLIER) : runtimeContext.layoutSettings.GAP_Y; + currentY += childH + gap; + }); + } + pinnedChildren.forEach( + (child) => layoutSubtree( + child.id, + child.x, + child.y + child.height / 2, + effectiveSide, + allElements, + hasGlobalFolds, + childrenByParent, + heightCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ) + ); + children.forEach((child) => { + const arrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === nodeId && a.endBinding?.elementId === child.id + ); + if (arrow) { + const eaChild = runtimeContext.ea.getElement(child.id); + const childCenterX = eaChild.x + eaChild.width / 2; + const parentCenterX = currentX + node.width / 2; + const isChildRight = childCenterX > parentCenterX; + const sX = isChildRight ? currentX + node.width : currentX; + const sY = currentYCenter; + const eX = isChildRight ? eaChild.x : eaChild.x + eaChild.width; + const eY = eaChild.y + eaChild.height / 2; + runtimeContext.configureArrow({ + arrowId: arrow.id, + isChildRight, + startId: node.id, + endId: child.id, + coordinates: { + sX, + sY, + eX, + eY + } + }); + } + }); + if (node.customData?.boundaryId) { + runtimeContext.updateNodeBoundary(node, runtimeContext.ea.getElements(), rootId); + } + }; + return { layoutChildrenAsAdditionalRoot, layoutSubtree }; + } + + // src/scripts/mindmap-builder/verticalLayout.js + function createVerticalLayout(runtimeContext) { + const layoutSubtreeVertical = (nodeId, targetCenterX, targetY, side, allElements, hasGlobalFolds, childrenByParent, widthCache, elementById, mustHonorMindmapOrder = false, rootId, parentMap = null) => { + const node = elementById?.get(nodeId) ?? allElements.find((el) => el.id === nodeId); + const eaNode = runtimeContext.ea.getElement(nodeId); + const isPinned = node.customData?.isPinned === true; + let dx = 0, dy = 0; + if (!isPinned) { + const newX = targetCenterX - node.width / 2; + const newY = side === 1 ? targetY : targetY - node.height; + dx = newX - eaNode.x; + dy = newY - eaNode.y; + eaNode.x = newX; + eaNode.y = newY; + } + if (node.customData?.isFolded) return; + const currentXCenter = eaNode.x + node.width / 2; + const currentY = eaNode.y; + let effectiveSide = side; + const parent = runtimeContext.getParentNode(nodeId, allElements, parentMap); + if (parent) { + const parentCenterY = parent.y + parent.height / 2; + const nodeCenterY = currentY + node.height / 2; + effectiveSide = nodeCenterY >= parentCenterY ? 1 : -1; + } + if (node.customData?.foldIndicatorId) { + const ind = runtimeContext.ea.getElement(node.customData.foldIndicatorId); + if (ind) { + ind.x = eaNode.x + eaNode.width / 2 - ind.width / 2; + if (effectiveSide === 1) { + ind.y = eaNode.y + eaNode.height + runtimeContext.layoutSettings.INDICATOR_OFFSET; + ind.textAlign = "center"; + } else { + ind.y = eaNode.y - runtimeContext.layoutSettings.INDICATOR_OFFSET - ind.height; + ind.textAlign = "center"; + } + } + } + const textElement = runtimeContext.ea.getBoundTextElement(eaNode).eaElement; + if (textElement && !runtimeContext.centerText && textElement.textAlign !== "center") { + textElement.textAlign = "center"; + } + const children = childrenByParent?.get(nodeId) ?? runtimeContext.getChildrenNodes(nodeId, allElements); + if (node.customData?.isAdditionalRoot === true) { + if (node.customData?.autoLayoutDisabled) { + if (dx !== 0 || dy !== 0) { + const branchIds = runtimeContext.getBranchElementIds(nodeId, allElements); + const descendants = branchIds.filter((id) => id !== nodeId); + descendants.forEach((descId) => { + const descNode = elementById?.get(descId) ?? allElements.find((e) => e.id === descId); + if (descNode?.customData?.isPinned) return; + if (descNode && descNode.type === "arrow" && !descNode.customData?.isBranch) return; + if (!runtimeContext.ea.getElement(descId)) { + if (descNode) runtimeContext.ea.copyViewElementsToEAforEditing([descNode]); + } + const descEl = runtimeContext.ea.getElement(descId); + if (descEl) { + descEl.x += dx; + descEl.y += dy; + } + }); + } + } else { + runtimeContext.layoutChildrenAsAdditionalRoot( + nodeId, + allElements, + hasGlobalFolds, + childrenByParent, + null, + widthCache, + elementById, + mustHonorMindmapOrder, + parentMap + ); + } + if (node.customData?.boundaryId) { + runtimeContext.updateNodeBoundary(node, runtimeContext.ea.getElements(), rootId); + } + return; + } + const unpinnedChildren = children.filter((child) => !child.customData?.isPinned); + const pinnedChildren = children.filter((child) => child.customData?.isPinned); + if (unpinnedChildren.length > 0) { + unpinnedChildren.sort((a, b) => { + if (mustHonorMindmapOrder) { + return runtimeContext.getMindmapOrder(a) - runtimeContext.getMindmapOrder(b); + } + const dx2 = a.x - b.x; + if (dx2 !== 0) return dx2; + return String(a.id).localeCompare(String(b.id)); + }); + if (!mustHonorMindmapOrder) { + unpinnedChildren.forEach((child, i) => { + if (runtimeContext.getMindmapOrder(child) !== i) { + runtimeContext.ea.addAppendUpdateCustomData(child.id, { + mindmapOrder: i + }); + } + }); + } + const placementWidthCache = /* @__PURE__ */ new Map(); + const childWidths = unpinnedChildren.map( + (child) => runtimeContext.getVerticalPlacementWidth( + child.id, + allElements, + childrenByParent, + widthCache, + elementById, + placementWidthCache + ) + ); + const childrenRowWidth = childWidths.reduce((sum, width, index) => { + const childNode = elementById?.get(unpinnedChildren[index].id) ?? allElements.find((el) => el.id === unpinnedChildren[index].id); + const grandChildren = childrenByParent?.get(unpinnedChildren[index].id) ?? runtimeContext.getChildrenNodes(unpinnedChildren[index].id, allElements); + const hasUnpinnedGrandChildren = grandChildren.some((gc) => !gc.customData?.isPinned); + const fontSize = childNode?.fontSize ?? 20; + const gap = index < unpinnedChildren.length - 1 ? !hasUnpinnedGrandChildren ? Math.round(fontSize * runtimeContext.layoutSettings.GAP_MULTIPLIER) : runtimeContext.layoutSettings.GAP_Y : 0; + return sum + width + gap; + }, 0); + let currentX = currentXCenter - childrenRowWidth / 2; + const allChildrenCompact = unpinnedChildren.every((child) => { + const grandChildren = childrenByParent?.get(child.id) ?? runtimeContext.getChildrenNodes(child.id, allElements); + return !grandChildren.some((gc) => !gc.customData?.isPinned); + }); + const compactGap = Math.max( + runtimeContext.layoutSettings.GAP_Y, + Math.round( + runtimeContext.layoutSettings.GAP_X * (runtimeContext.layoutSettings.VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO ?? runtimeContext.LAYOUT_METADATA.VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO.def) + ) + ); + const dynamicGapPrimary = unpinnedChildren.length <= 2 && allChildrenCompact ? compactGap : runtimeContext.layoutSettings.GAP_X; + unpinnedChildren.forEach((child, index) => { + const childW = childWidths[index]; + layoutSubtreeVertical( + child.id, + currentX + childW / 2, + effectiveSide === 1 ? currentY + node.height + dynamicGapPrimary : currentY - dynamicGapPrimary, + effectiveSide, + allElements, + hasGlobalFolds, + childrenByParent, + widthCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ); + const childNode = elementById?.get(child.id) ?? allElements.find((el) => el.id === child.id); + const grandChildren = childrenByParent?.get(child.id) ?? runtimeContext.getChildrenNodes(child.id, allElements); + const hasUnpinnedGrandChildren = grandChildren.some((gc) => !gc.customData?.isPinned); + const fontSize = childNode.fontSize ?? 20; + const gap = !hasUnpinnedGrandChildren ? Math.round(fontSize * runtimeContext.layoutSettings.GAP_MULTIPLIER) : runtimeContext.layoutSettings.GAP_Y; + currentX += childW + gap; + }); + } + pinnedChildren.forEach( + (child) => layoutSubtreeVertical( + child.id, + child.x + child.width / 2, + child.y + (effectiveSide === 1 ? 0 : child.height), + effectiveSide, + allElements, + hasGlobalFolds, + childrenByParent, + widthCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ) + ); + children.forEach((child) => { + const arrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === nodeId && a.endBinding?.elementId === child.id + ); + if (arrow) { + const eaChild = runtimeContext.ea.getElement(child.id); + const childCenterY = eaChild.y + eaChild.height / 2; + const parentCenterY = currentY + node.height / 2; + const isChildBelow = childCenterY > parentCenterY; + const sX = currentXCenter; + const sY = isChildBelow ? currentY + node.height : currentY; + const eX = eaChild.x + eaChild.width / 2; + const eY = isChildBelow ? eaChild.y : eaChild.y + eaChild.height; + runtimeContext.configureArrow({ + arrowId: arrow.id, + isChildBelow, + startId: node.id, + endId: child.id, + coordinates: { + sX, + sY, + eX, + eY + }, + layoutDirection: "vertical" + }); + } + }); + if (node.customData?.boundaryId) { + runtimeContext.updateNodeBoundary(node, runtimeContext.ea.getElements(), rootId); + } + }; + return { layoutSubtreeVertical }; + } + + // src/scripts/mindmap-builder/firstLevelLayout.js + function createFirstLevelLayout(runtimeContext) { + const radialL1Distribution = (nodes, context, l1Metrics, totalSubtreeHeight, options, mustHonorMindmapOrder = false) => { + const { + allElements, + rootBox, + rootCenter, + hasGlobalFolds, + childrenByParent, + heightCache, + elementById, + rootId, + parentMap + } = context; + const count = nodes.length; + const START_ANGLE = runtimeContext.layoutSettings.RADIAL_START_ANGLE; + const MAX_SWEEP_DEG = options.fillSweep ? runtimeContext.layoutSettings.RADIAL_MAX_SWEEP : Math.min( + runtimeContext.layoutSettings.RADIAL_MAX_SWEEP / 8 * count, + runtimeContext.layoutSettings.RADIAL_MAX_SWEEP + ); + const ASPECT_RATIO = runtimeContext.layoutSettings.RADIAL_ASPECT_RATIO; + const POLE_GAP_BONUS = runtimeContext.layoutSettings.RADIAL_POLE_GAP_BONUS; + const BASE_GAP = runtimeContext.layoutSettings.GAP_Y * 2; + const minRadiusY = Math.max( + Math.round( + Math.max(rootBox.height, rootBox.width) * runtimeContext.layoutSettings.ROOT_RADIUS_FACTOR * 1.5 + ), + runtimeContext.layoutSettings.MIN_RADIUS + ); + const minRadiusX = minRadiusY * ASPECT_RATIO; + let simAngle = START_ANGLE; + let totalRequiredSpan = 0; + const nodeSimData = nodes.map((node, i) => { + const rad = simAngle * (Math.PI / 180); + const localR = minRadiusX * minRadiusY / Math.sqrt( + Math.pow(minRadiusY * Math.cos(rad), 2) + Math.pow(minRadiusX * Math.sin(rad), 2) + ); + const sinComp = Math.abs(Math.sin(rad)); + const cosComp = Math.abs(Math.cos(rad)); + const effSize = node.width * sinComp + l1Metrics[i] * cosComp; + const nodeSpan = effSize / localR * (180 / Math.PI); + const isLast = i === count - 1; + const dynamicGapPx = isLast ? 0 : BASE_GAP * (1 + sinComp * POLE_GAP_BONUS); + const gapSpan = dynamicGapPx / localR * (180 / Math.PI); + const totalSpan = nodeSpan + gapSpan; + simAngle += totalSpan; + totalRequiredSpan += totalSpan; + return { + node, + nodeSpan, + gapSpan + }; + }); + let finalRadiusY = minRadiusY; + let angleExpansionFactor = 1; + if (totalRequiredSpan > MAX_SWEEP_DEG) { + const radiusScale = totalRequiredSpan / MAX_SWEEP_DEG; + finalRadiusY = minRadiusY * radiusScale; + angleExpansionFactor = 1 / radiusScale; + } else { + angleExpansionFactor = MAX_SWEEP_DEG / totalRequiredSpan; + } + const finalRadiusX = finalRadiusY * ASPECT_RATIO; + let currentAngle = START_ANGLE; + nodes.forEach((node, i) => { + const isPinned = node.customData?.isPinned === true; + const hasBoundary = !!node.customData?.boundaryId; + const data = nodeSimData[i]; + const realNodeSpan = data.nodeSpan * angleExpansionFactor; + const realGapSpan = data.gapSpan * angleExpansionFactor; + const placementAngle = currentAngle + realNodeSpan / 2; + const normAngle = (placementAngle % 360 + 360) % 360; + const dynamicSide = normAngle > 90 && normAngle < 270 ? -1 : 1; + const rad = placementAngle * (Math.PI / 180); + const finalLocalR = finalRadiusX * finalRadiusY / Math.sqrt( + Math.pow(finalRadiusY * Math.cos(rad), 2) + Math.pow(finalRadiusX * Math.sin(rad), 2) + ); + const placeR = hasBoundary ? finalLocalR * 1 : finalLocalR; + const tCX = rootCenter.x + placeR * Math.cos(rad); + const tCY = rootCenter.y + placeR * Math.sin(rad); + if (isPinned) { + runtimeContext.layoutSubtree( + node.id, + node.x, + node.y + node.height / 2, + dynamicSide, + allElements, + hasGlobalFolds, + childrenByParent, + heightCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ); + } else { + runtimeContext.layoutSubtree( + node.id, + tCX, + tCY, + dynamicSide, + allElements, + hasGlobalFolds, + childrenByParent, + heightCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ); + } + currentAngle += realNodeSpan + realGapSpan; + if (node.customData?.mindmapNew) { + runtimeContext.ea.addAppendUpdateCustomData(node.id, { + mindmapNew: void 0 + }); + } + runtimeContext.updateL1Arrow(node, context); + if (runtimeContext.groupBranches) runtimeContext.applyRecursiveGrouping(node.id, allElements); + }); + }; + const verticalL1Distribution = (nodes, context, l1Metrics, totalSubtreeHeight, isLeftSide, centerAngle, gapMultiplier, mustHonorMindmapOrder = false) => { + const { + allElements, + rootBox, + rootCenter, + hasGlobalFolds, + childrenByParent, + heightCache, + elementById, + rootId, + parentMap + } = context; + const count = nodes.length; + const totalContentHeight = totalSubtreeHeight + (count - 1) * runtimeContext.layoutSettings.GAP_Y; + const radiusFromHeight = totalContentHeight / runtimeContext.layoutSettings.DIRECTIONAL_ARC_SPAN_RADIANS; + const radiusY = Math.max( + Math.round(rootBox.height * runtimeContext.layoutSettings.ROOT_RADIUS_FACTOR), + runtimeContext.layoutSettings.MIN_RADIUS, + radiusFromHeight + ) + count * runtimeContext.layoutSettings.RADIUS_PADDING_PER_NODE; + const crossAxisRatio = runtimeContext.layoutSettings.DIRECTIONAL_CROSS_AXIS_RATIO ?? runtimeContext.LAYOUT_METADATA.DIRECTIONAL_CROSS_AXIS_RATIO.def; + const radiusX = Math.max( + Math.round(rootBox.width * runtimeContext.layoutSettings.ROOT_RADIUS_FACTOR), + runtimeContext.layoutSettings.MIN_RADIUS, + radiusY * crossAxisRatio + ) + count * runtimeContext.layoutSettings.RADIUS_PADDING_PER_NODE; + const totalThetaDeg = totalContentHeight / radiusY * (180 / Math.PI); + let currentAngle = isLeftSide ? centerAngle + totalThetaDeg / 2 : centerAngle - totalThetaDeg / 2; + nodes.forEach((node, i) => { + const nodeHeight = l1Metrics[i]; + const isPinned = node.customData?.isPinned === true; + const side = isLeftSide ? -1 : 1; + const getAngularInfo = (targetNode, height) => { + const angleRad = Math.atan2( + targetNode.y + targetNode.height / 2 - rootCenter.y, + targetNode.x + targetNode.width / 2 - rootCenter.x + ); + const angleDeg = angleRad * (180 / Math.PI) + 90; + const normAngle = angleDeg < 0 ? angleDeg + 360 : angleDeg; + const spanDeg = height / radiusY * (180 / Math.PI); + return { + center: normAngle, + span: spanDeg, + start: normAngle - spanDeg / 2, + end: normAngle + spanDeg / 2 + }; + }; + const effectiveGap = runtimeContext.layoutSettings.GAP_Y * gapMultiplier; + const gapSpanDeg = effectiveGap / radiusY * (180 / Math.PI); + const nodeSpanDeg = nodeHeight / radiusY * (180 / Math.PI); + if (isPinned) { + runtimeContext.layoutSubtree( + node.id, + node.x, + node.y + node.height / 2, + side, + allElements, + hasGlobalFolds, + childrenByParent, + heightCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ); + const info = getAngularInfo(node, nodeHeight); + if (isLeftSide) { + if (currentAngle > info.start - gapSpanDeg) currentAngle = info.start - gapSpanDeg; + } else { + if (currentAngle < info.end + gapSpanDeg) currentAngle = info.end + gapSpanDeg; + } + } else { + const nextPinned = nodes.slice(i + 1).find((n) => n.customData?.isPinned); + if (nextPinned) { + const nextInfo = getAngularInfo( + nextPinned, + runtimeContext.getSubtreeHeight( + nextPinned.id, + allElements, + childrenByParent, + heightCache, + elementById + ) + ); + if (isLeftSide) { + if (currentAngle - nodeSpanDeg < nextInfo.end + gapSpanDeg) + currentAngle = nextInfo.start - gapSpanDeg; + } else { + if (currentAngle + nodeSpanDeg > nextInfo.start - gapSpanDeg) + currentAngle = nextInfo.end + gapSpanDeg; + } + } + let angleDeg = isLeftSide ? currentAngle - nodeSpanDeg / 2 : currentAngle + nodeSpanDeg / 2; + currentAngle = isLeftSide ? currentAngle - (nodeSpanDeg + gapSpanDeg) : currentAngle + (nodeSpanDeg + gapSpanDeg); + const angleRad = (angleDeg - 90) * (Math.PI / 180); + const tCX = rootCenter.x + radiusX * Math.cos(angleRad); + const tCY = rootCenter.y + radiusY * Math.sin(angleRad); + runtimeContext.layoutSubtree( + node.id, + tCX, + tCY, + side, + allElements, + hasGlobalFolds, + childrenByParent, + heightCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ); + } + if (node.customData?.mindmapNew) { + runtimeContext.ea.addAppendUpdateCustomData(node.id, { + mindmapNew: void 0 + }); + } + runtimeContext.updateL1Arrow(node, context); + if (runtimeContext.groupBranches) runtimeContext.applyRecursiveGrouping(node.id, allElements); + }); + }; + const horizontalL1Distribution = (nodes, context, l1Metrics, totalSubtreeWidth, isTopSide, centerAngle, gapMultiplier, mustHonorMindmapOrder = false) => { + const { + allElements, + rootBox, + rootCenter, + hasGlobalFolds, + childrenByParent, + widthCache, + elementById, + rootId, + parentMap + } = context; + const count = nodes.length; + const compressDirectionalWidth = (node, rawWidth) => { + const nodeWidth = Math.max(node?.width ?? 0, 1); + if (rawWidth <= nodeWidth) return rawWidth; + const extra = rawWidth - nodeWidth; + const softCapThreshold = runtimeContext.layoutSettings.HORIZONTAL_L1_SOFTCAP_THRESHOLD ?? runtimeContext.LAYOUT_METADATA.HORIZONTAL_L1_SOFTCAP_THRESHOLD.def; + if (extra <= softCapThreshold) return rawWidth; + const remaining = extra - softCapThreshold; + const compressionMinScale = runtimeContext.layoutSettings.HORIZONTAL_L1_COMPRESSION_MIN_SCALE ?? runtimeContext.LAYOUT_METADATA.HORIZONTAL_L1_COMPRESSION_MIN_SCALE.def; + const compressionScale = Math.max( + compressionMinScale, + (runtimeContext.layoutSettings.GAP_X ?? runtimeContext.LAYOUT_METADATA.GAP_X.def) * 2 + ); + const compressedRemaining = compressionScale * Math.log1p(remaining / compressionScale); + return nodeWidth + softCapThreshold + compressedRemaining; + }; + const effectiveWidths = nodes.map((node, i) => compressDirectionalWidth(node, l1Metrics[i])); + const effectiveWidthById = new Map(nodes.map((node, i) => [node.id, effectiveWidths[i]])); + const totalEffectiveWidth = effectiveWidths.reduce((sum, width) => sum + width, 0); + const effectiveGap = runtimeContext.layoutSettings.GAP_Y * gapMultiplier; + const totalContentWidth = totalEffectiveWidth + (count - 1) * effectiveGap; + const baseArcSpan = runtimeContext.layoutSettings.DIRECTIONAL_ARC_SPAN_RADIANS; + const baselineRadius = Math.max( + Math.round(rootBox.width * runtimeContext.layoutSettings.ROOT_RADIUS_FACTOR), + runtimeContext.layoutSettings.MIN_RADIUS + ) + count * runtimeContext.layoutSettings.RADIUS_PADDING_PER_NODE; + const pressure = totalContentWidth / Math.max(1, baselineRadius * baseArcSpan); + const adaptiveArcSpan = Math.min( + Math.PI, + Math.max(baseArcSpan, baseArcSpan * Math.sqrt(Math.max(1, pressure))) + ); + const radiusFromWidth = totalContentWidth / adaptiveArcSpan; + const radiusX = Math.max( + Math.round(rootBox.width * runtimeContext.layoutSettings.ROOT_RADIUS_FACTOR), + runtimeContext.layoutSettings.MIN_RADIUS, + radiusFromWidth + ) + count * runtimeContext.layoutSettings.RADIUS_PADDING_PER_NODE; + const crossAxisRatio = runtimeContext.layoutSettings.DIRECTIONAL_CROSS_AXIS_RATIO ?? runtimeContext.LAYOUT_METADATA.DIRECTIONAL_CROSS_AXIS_RATIO.def; + const radiusY = Math.max( + Math.round(rootBox.height * runtimeContext.layoutSettings.ROOT_RADIUS_FACTOR), + runtimeContext.layoutSettings.MIN_RADIUS, + radiusX * crossAxisRatio + ) + count * runtimeContext.layoutSettings.RADIUS_PADDING_PER_NODE; + const totalThetaDeg = totalContentWidth / radiusX * (180 / Math.PI); + let currentAngle = isTopSide ? centerAngle - totalThetaDeg / 2 : centerAngle + totalThetaDeg / 2; + nodes.forEach((node, i) => { + const nodeWidth = effectiveWidths[i]; + const isPinned = node.customData?.isPinned === true; + const side = isTopSide ? -1 : 1; + const getAngularInfo = (targetNode, width) => { + const angleRad = Math.atan2( + targetNode.y + targetNode.height / 2 - rootCenter.y, + targetNode.x + targetNode.width / 2 - rootCenter.x + ); + const angleDeg = angleRad * (180 / Math.PI); + const normAngle = angleDeg < 0 ? angleDeg + 360 : angleDeg; + const spanDeg = width / radiusX * (180 / Math.PI); + return { + center: normAngle, + span: spanDeg, + start: normAngle - spanDeg / 2, + end: normAngle + spanDeg / 2 + }; + }; + const gapSpanDeg = effectiveGap / radiusX * (180 / Math.PI); + const nodeSpanDeg = nodeWidth / radiusX * (180 / Math.PI); + if (isPinned) { + runtimeContext.layoutSubtreeVertical( + node.id, + node.x + node.width / 2, + node.y, + side, + allElements, + hasGlobalFolds, + childrenByParent, + widthCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ); + const info = getAngularInfo(node, nodeWidth); + if (isTopSide) { + if (currentAngle < info.start - gapSpanDeg) currentAngle = info.start - gapSpanDeg; + } else { + if (currentAngle > info.end + gapSpanDeg) currentAngle = info.end + gapSpanDeg; + } + } else { + const nextPinned = nodes.slice(i + 1).find((n) => n.customData?.isPinned); + if (nextPinned) { + const nextPinnedWidth = effectiveWidthById.get(nextPinned.id) ?? compressDirectionalWidth( + nextPinned, + runtimeContext.getSubtreeWidth( + nextPinned.id, + allElements, + childrenByParent, + widthCache, + elementById + ) + ); + const nextInfo = getAngularInfo(nextPinned, nextPinnedWidth); + if (isTopSide) { + if (currentAngle + nodeSpanDeg > nextInfo.start - gapSpanDeg) + currentAngle = nextInfo.start - gapSpanDeg - nodeSpanDeg; + } else { + if (currentAngle - nodeSpanDeg < nextInfo.end + gapSpanDeg) + currentAngle = nextInfo.end + gapSpanDeg + nodeSpanDeg; + } + } + let angleDeg = isTopSide ? currentAngle + nodeSpanDeg / 2 : currentAngle - nodeSpanDeg / 2; + currentAngle = isTopSide ? currentAngle + (nodeSpanDeg + gapSpanDeg) : currentAngle - (nodeSpanDeg + gapSpanDeg); + const angleRad = angleDeg * (Math.PI / 180); + const tCX = rootCenter.x + radiusX * Math.cos(angleRad); + const tCY = rootCenter.y + radiusY * Math.sin(angleRad); + runtimeContext.layoutSubtreeVertical( + node.id, + tCX, + tCY, + side, + allElements, + hasGlobalFolds, + childrenByParent, + widthCache, + elementById, + mustHonorMindmapOrder, + rootId, + parentMap + ); + } + if (node.customData?.mindmapNew) { + runtimeContext.ea.addAppendUpdateCustomData(node.id, { + mindmapNew: void 0 + }); + } + runtimeContext.updateL1Arrow(node, context, "vertical"); + if (runtimeContext.groupBranches) runtimeContext.applyRecursiveGrouping(node.id, allElements); + }); + }; + const layoutL1Nodes = (nodes, options, context, mustHonorMindmapOrder = false) => { + if (nodes.length === 0) return false; + const { allElements, childrenByParent, heightCache, widthCache, elementById } = context; + const { sortMethod, centerAngle, gapMultiplier } = options; + nodes.sort((a, b) => runtimeContext.getMindmapOrder(a) - runtimeContext.getMindmapOrder(b)); + if (sortMethod === "radial") { + const l1Metrics = nodes.map( + (node) => runtimeContext.getSubtreeHeight( + node.id, + allElements, + childrenByParent, + heightCache, + elementById + ) + ); + const totalSubtreeHeight = l1Metrics.reduce((sum, h) => sum + h, 0); + radialL1Distribution( + nodes, + context, + l1Metrics, + totalSubtreeHeight, + options, + mustHonorMindmapOrder + ); + } else if (sortMethod === "horizontal") { + const l1Metrics = nodes.map( + (node) => runtimeContext.getSubtreeWidth( + node.id, + allElements, + childrenByParent, + widthCache, + elementById + ) + ); + const totalSubtreeWidth = l1Metrics.reduce((sum, w) => sum + w, 0); + const isTopSide = Math.abs((centerAngle ?? 0) - 270) < 1; + horizontalL1Distribution( + nodes, + context, + l1Metrics, + totalSubtreeWidth, + isTopSide, + centerAngle, + gapMultiplier, + mustHonorMindmapOrder + ); + } else { + const l1Metrics = nodes.map( + (node) => runtimeContext.getSubtreeHeight( + node.id, + allElements, + childrenByParent, + heightCache, + elementById + ) + ); + const totalSubtreeHeight = l1Metrics.reduce((sum, h) => sum + h, 0); + const isLeftSide = sortMethod === "vertical" && Math.abs((centerAngle ?? 0) - 270) < 1; + verticalL1Distribution( + nodes, + context, + l1Metrics, + totalSubtreeHeight, + isLeftSide, + centerAngle, + gapMultiplier, + mustHonorMindmapOrder + ); + } + return true; + }; + const sortL1NodesBasedOnVisualSequence = (l1Nodes, mode, rootCenter) => { + if (l1Nodes.length === 0) return false; + let orderChanged = false; + const isVerticalMode = ["Up-facing", "Down-facing", "Up-Down"].includes(mode); + const sortByReadingOrder = (a, b) => { + const aCX = a.x + a.width / 2; + const bCX = b.x + b.width / 2; + const aCY = a.y + a.height / 2; + const bCY = b.y + b.height / 2; + if (isVerticalMode) { + const aIsBottom = aCY > rootCenter.y; + const bIsBottom = bCY > rootCenter.y; + if (aIsBottom !== bIsBottom) return aIsBottom ? -1 : 1; + return aCX - bCX; + } else { + const aIsR = aCX > rootCenter.x; + const bIsR = bCX > rootCenter.x; + if (aIsR !== bIsR) return aIsR ? -1 : 1; + return a.y - b.y; + } + }; + const sortByAngle = (a, b) => { + return runtimeContext.getAngleFromCenter(rootCenter, { + x: a.x + a.width / 2, + y: a.y + a.height / 2 + }) - runtimeContext.getAngleFromCenter(rootCenter, { + x: b.x + b.width / 2, + y: b.y + b.height / 2 + }); + }; + const sortFn = mode === "Radial" ? sortByAngle : sortByReadingOrder; + const existingNodes = l1Nodes.filter((n) => !n.customData?.mindmapNew); + const newNodes = l1Nodes.filter((n) => n.customData?.mindmapNew); + existingNodes.sort(sortFn); + existingNodes.forEach((node, i) => { + if (node.customData?.mindmapOrder !== i) { + runtimeContext.ea.addAppendUpdateCustomData(node.id, { + mindmapOrder: i + }); + orderChanged = true; + } + }); + newNodes.forEach((node, i) => { + const newOrder = existingNodes.length + i; + runtimeContext.ea.addAppendUpdateCustomData(node.id, { + mindmapOrder: newOrder + }); + orderChanged = true; + }); + return orderChanged; + }; + return { + radialL1Distribution, + verticalL1Distribution, + horizontalL1Distribution, + layoutL1Nodes, + sortL1NodesBasedOnVisualSequence + }; + } + + // src/scripts/mindmap-builder/layout.js + function createLayout(runtimeContext) { + const triggerGlobalLayout = async (rootId, forceUngroup = false, mustHonorMindmapOrder = false) => { + if (!runtimeContext.isViewSet()) return; + const selectedElement = runtimeContext.getMindmapNodeFromSelection(); + if (!selectedElement) return; + const run = async (allElements2, mindmapIds2, root2, doVisualSort, sharedSets2, mustHonorMindmapOrder2 = false) => { + return runtimeContext.withRootLayoutContext(root2, () => { + const oldMode = root2.customData?.growthMode; + const newMode = root2.customData?.growthMode || runtimeContext.currentModalGrowthMode; + let orderChanged = false; + let modeChanged = false; + let visualChange = false; + const originalPositions = /* @__PURE__ */ new Map(); + allElements2.forEach((el) => { + originalPositions.set(el.id, { + x: el.x, + y: el.y + }); + }); + const elementById = runtimeContext.buildElementMap(allElements2); + const parentMap = runtimeContext.buildParentMap(allElements2, elementById); + const childrenByParent = runtimeContext.buildChildrenMap(allElements2, elementById); + const heightCache = /* @__PURE__ */ new Map(); + const widthCache = /* @__PURE__ */ new Map(); + const branchIds = new Set(mindmapIds2); + const groupToNodes = runtimeContext.buildGroupToNodes(branchIds, allElements2); + const hasGlobalFolds = allElements2.some((el) => el.customData?.isFolded === true); + const l1Nodes = runtimeContext.getChildrenNodes(rootId, allElements2); + if (l1Nodes.length === 0) + return { + structuralChange: false, + visualChange: false + }; + if (runtimeContext.groupBranches || forceUngroup) { + mindmapIds2.forEach((id) => { + const el = runtimeContext.ea.getElement(id); + if (el && el.groupIds) { + el.groupIds = el.groupIds.filter( + (gid) => !runtimeContext.isMindmapGroup(gid, allElements2) + ); + } + }); + } + const rootBox = runtimeContext.getNodeBox(root2, allElements2); + const rootCenter = { + x: rootBox.minX + rootBox.width / 2, + y: rootBox.minY + rootBox.height / 2 + }; + const layoutContext = { + allElements: allElements2, + rootId, + rootBox, + rootCenter, + hasGlobalFolds, + mode: newMode, + childrenByParent, + heightCache, + widthCache, + elementById, + parentMap + }; + const isModeSwitch = mustHonorMindmapOrder2 || oldMode && oldMode !== newMode; + if (!isModeSwitch && doVisualSort && !mustHonorMindmapOrder2) { + orderChanged = runtimeContext.sortL1NodesBasedOnVisualSequence( + l1Nodes, + newMode, + rootCenter + ); + } else if (!mustHonorMindmapOrder2) { + if (oldMode !== newMode) { + runtimeContext.ea.addAppendUpdateCustomData(rootId, { + growthMode: newMode + }); + modeChanged = true; + } + } + if (newMode === "Radial") { + runtimeContext.layoutL1Nodes( + l1Nodes, + { + sortMethod: "radial", + centerAngle: null, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_RADIAL, + fillSweep: root2.customData?.fillSweep ?? runtimeContext.fillSweep + }, + layoutContext, + mustHonorMindmapOrder2 + ); + } else if (["Right-facing", "Left-facing", "Right-Left"].includes(newMode)) { + const leftNodes = []; + const rightNodes = []; + if (newMode === "Right-Left") { + if (isModeSwitch && !mustHonorMindmapOrder2) { + const splitIdx = Math.ceil(l1Nodes.length / 2); + l1Nodes.forEach((node, i) => { + if (i < splitIdx) rightNodes.push(node); + else leftNodes.push(node); + }); + } else { + l1Nodes.forEach((node) => { + const nodeCX = node.x + node.width / 2; + if (nodeCX > rootCenter.x) rightNodes.push(node); + else leftNodes.push(node); + }); + } + } else if (newMode === "Left-facing") { + l1Nodes.forEach((node) => leftNodes.push(node)); + } else { + l1Nodes.forEach((node) => rightNodes.push(node)); + } + if (rightNodes.length > 0) { + runtimeContext.layoutL1Nodes( + rightNodes, + { + sortMethod: "vertical", + centerAngle: 90, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_DIRECTIONAL + }, + layoutContext, + mustHonorMindmapOrder2 + ); + } + if (leftNodes.length > 0) { + runtimeContext.layoutL1Nodes( + leftNodes, + { + sortMethod: "vertical", + centerAngle: 270, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_DIRECTIONAL + }, + layoutContext, + mustHonorMindmapOrder2 + ); + } + } else if (["Up-facing", "Down-facing", "Up-Down"].includes(newMode)) { + const upNodes = []; + const downNodes = []; + if (newMode === "Up-Down") { + if (isModeSwitch && !mustHonorMindmapOrder2) { + const splitIdx = Math.ceil(l1Nodes.length / 2); + l1Nodes.forEach((node, i) => { + if (i < splitIdx) downNodes.push(node); + else upNodes.push(node); + }); + } else { + l1Nodes.forEach((node) => { + const nodeCY = node.y + node.height / 2; + if (nodeCY > rootCenter.y) downNodes.push(node); + else upNodes.push(node); + }); + } + } else if (newMode === "Up-facing") { + l1Nodes.forEach((node) => upNodes.push(node)); + } else { + l1Nodes.forEach((node) => downNodes.push(node)); + } + layoutContext.widthCache = /* @__PURE__ */ new Map(); + if (downNodes.length > 0) { + runtimeContext.layoutL1Nodes( + downNodes, + { + sortMethod: "horizontal", + centerAngle: 90, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_DIRECTIONAL + }, + layoutContext, + mustHonorMindmapOrder2 + ); + } + if (upNodes.length > 0) { + runtimeContext.layoutL1Nodes( + upNodes, + { + sortMethod: "horizontal", + centerAngle: 270, + gapMultiplier: runtimeContext.layoutSettings.GAP_MULTIPLIER_DIRECTIONAL + }, + layoutContext, + mustHonorMindmapOrder2 + ); + } + } + const { mindmapIdsSet: mindmapIdsSet2, crosslinkIdSet: crosslinkIdSet2, decorationIdSet: decorationIdSet2 } = sharedSets2; + runtimeContext.moveCrossLinks(runtimeContext.ea.getElements(), originalPositions); + runtimeContext.moveDecorations( + runtimeContext.ea.getElements(), + originalPositions, + groupToNodes, + rootId, + elementById, + parentMap + ); + runtimeContext.ea.getElements().filter( + (el) => !mindmapIdsSet2.has(el.id) && !crosslinkIdSet2.has(el.id) && !decorationIdSet2.has(el.id) + ).forEach((el) => { + delete runtimeContext.ea.elementsDict[el.id]; + }); + for (const el of runtimeContext.ea.getElements()) { + const oldPos = originalPositions.get(el.id); + if (oldPos) { + if (Math.abs(el.x - oldPos.x) > 0.01 || Math.abs(el.y - oldPos.y) > 0.01) { + visualChange = true; + break; + } + } + } + return { + structuralChange: orderChanged || modeChanged, + visualChange + }; + }); + }; + const viewElements = runtimeContext.ea.getViewElements(); + const projectElements = runtimeContext.getMindmapProjectElements(rootId, viewElements); + runtimeContext.ea.copyViewElementsToEAforEditing(projectElements); + let allElements = runtimeContext.ea.getElements(); + let root = allElements.find((el) => el.id === rootId); + if (!root) return; + if (root.customData?.autoLayoutDisabled) return; + const mindmapIds = runtimeContext.getBranchElementIds(rootId, allElements); + const { structuralGroupId, groupedElementIds } = runtimeContext.getStructuralGroupForNode( + mindmapIds, + allElements, + rootId + ); + if (structuralGroupId) { + runtimeContext.removeGroupFromElements(structuralGroupId, allElements); + } + const expandedMindmapIds = [...mindmapIds]; + mindmapIds.forEach((id) => { + const el = allElements.find((e) => e.id === id); + if (el && el.boundElements) { + el.boundElements.forEach((be) => expandedMindmapIds.push(be.id)); + } + }); + const mindmapIdsSet = new Set(expandedMindmapIds); + const crosslinkIdSet = runtimeContext.collectCrosslinkIds(allElements); + const decorationIdSet = runtimeContext.collectDecorationIds(allElements, rootId); + const sharedSets = { + mindmapIdsSet, + crosslinkIdSet, + decorationIdSet + }; + const boundaryNodeSnapshot = /* @__PURE__ */ new Map(); + allElements.forEach((el) => { + if (typeof el.customData?.mindmapOrder !== "undefined" && el.customData?.boundaryId) { + boundaryNodeSnapshot.set(el.id, { + x: el.x, + y: el.y, + width: el.width, + height: el.height + }); + } + }); + const result1 = await run( + allElements, + mindmapIds, + root, + true, + sharedSets, + mustHonorMindmapOrder + ); + let boundaryMoved = false; + if (boundaryNodeSnapshot.size > 0) { + for (const [id, oldSnapshot] of boundaryNodeSnapshot) { + const newEl = runtimeContext.ea.getElement(id); + if (newEl) { + if (Math.abs(newEl.x - oldSnapshot.x) > 0.01 || Math.abs(newEl.y - oldSnapshot.y) > 0.01 || Math.abs(newEl.width - oldSnapshot.width) > 0.01 || Math.abs(newEl.height - oldSnapshot.height) > 0.01) { + boundaryMoved = true; + break; + } + } + } + } + if (result1.structuralChange || forceUngroup || boundaryMoved) { + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY" + }); + const viewElementsRun2 = runtimeContext.ea.getViewElements(); + const projectElementsRun2 = runtimeContext.getMindmapProjectElements( + rootId, + viewElementsRun2 + ); + runtimeContext.ea.copyViewElementsToEAforEditing(projectElementsRun2); + allElements = runtimeContext.ea.getElements(); + root = allElements.find((el) => el.id === rootId); + await run(allElements, mindmapIds, root, false, sharedSets, mustHonorMindmapOrder); + if (structuralGroupId && !forceUngroup) { + groupedElementIds.forEach((id) => { + const el = runtimeContext.ea.getElement(id); + if (el && (!el.groupIds || !el.groupIds.includes(structuralGroupId))) { + el.groupIds = [...el.groupIds || [], structuralGroupId]; + } + }); + } + await runtimeContext.addElementsToView({ + captureUpdate: "IMMEDIATELY" + }); + } else { + if (result1.visualChange) { + if (structuralGroupId && !forceUngroup) { + groupedElementIds.forEach((id) => { + const el = runtimeContext.ea.getElement(id); + if (el && (!el.groupIds || !el.groupIds.includes(structuralGroupId))) { + el.groupIds = [...el.groupIds || [], structuralGroupId]; + } + }); + } + await runtimeContext.addElementsToView({ + captureUpdate: "IMMEDIATELY" + }); + } else { + runtimeContext.ea.clear(); + } + } + runtimeContext.selectNodeInView(selectedElement); + }; + const refreshMapLayout = async (sel) => { + if (!runtimeContext.isViewSet()) return; + if (!sel) sel = runtimeContext.getMindmapNodeFromSelection(); + if (sel) { + const allElements = runtimeContext.ea.getViewElements(); + const settingsRoot = runtimeContext.getSettingsRootNode(sel, allElements); + if (!settingsRoot) return; + if (settingsRoot.customData?.autoLayoutDisabled === true) return; + await triggerGlobalLayout(settingsRoot.id); + } + }; + return { triggerGlobalLayout, refreshMapLayout }; + } + + // src/scripts/mindmap-builder/nodes.js + function createNodes(runtimeContext) { + const addEmbeddableNode = ({ px = 0, py = 0, url, depth }) => { + isWikiLink = url.startsWith("[["); + const width = isWikiLink ? depth === 0 ? runtimeContext.EMBEDED_OBJECT_WIDTH_ROOT : runtimeContext.EMBEDED_OBJECT_WIDTH_CHILD : runtimeContext.EMBEDED_OBJECT_WIDTH_CHILD; + const height = isWikiLink ? width / 2 : 0; + const embeddableId = runtimeContext.ea.addEmbeddable(px, py, width, height, url); + if (isWikiLink) { + runtimeContext.ea.getElement(embeddableId).scale = depth === 0 ? [0.5, 0.5] : [0.3, 0.3]; + } + return embeddableId; + }; + const addImage = async ({ + pathOrFile, + width, + leftFacing = false, + x = 0, + y = 0, + depth = 0 + } = {}) => { + const newNodeId = await runtimeContext.ea.addImage(x, y, pathOrFile); + const el = runtimeContext.ea.getElement(newNodeId); + const targetWidth = width || (depth === 0 ? runtimeContext.EMBEDED_OBJECT_WIDTH_ROOT : runtimeContext.EMBEDED_OBJECT_WIDTH_CHILD); + const ratio = el.width / el.height; + el.width = targetWidth; + el.height = targetWidth / ratio; + if (leftFacing) el.x = x - el.width; + return newNodeId; + }; + const initializeRootCustomData = (nodeId) => { + runtimeContext.ea.addAppendUpdateCustomData(nodeId, { + presetName: runtimeContext.activePresetName, + growthMode: runtimeContext.currentModalGrowthMode, + autoLayoutDisabled: false, + arrowType: runtimeContext.arrowType, + fontsizeScale: runtimeContext.fontsizeScale, + multicolor: runtimeContext.multicolor, + boxChildren: runtimeContext.boxChildren, + roundedCorners: runtimeContext.roundedCorners, + maxWrapWidth: runtimeContext.maxWidth, + isSolidArrow: runtimeContext.isSolidArrow, + centerText: runtimeContext.centerText, + fillSweep: runtimeContext.fillSweep, + branchScale: runtimeContext.branchScale, + baseStrokeWidth: runtimeContext.baseStrokeWidth, + layoutSettings: JSON.parse(JSON.stringify(runtimeContext.layoutSettings)) + }); + }; + const addNode = async (text, follow = false, skipFinalLayout = false, batchModeAllElements = null, batchModeParent = null, pos = null, ontology = null) => { + if (!runtimeContext.isViewSet()) return; + if (!text || text.trim() === "") return; + const preGenTextId = runtimeContext.ea.generateElementId(); + if (text.includes("__NODE_LINK_PLACEHOLDER__")) { + const file = app.workspace.getActiveFile(); + const fileName = file ? file.basename : ""; + const linkStr = `[[${fileName}#^group=${preGenTextId}|${runtimeContext.nodeLinkAlias}]]`; + text = text.replace("__NODE_LINK_PLACEHOLDER__", linkStr); + } + const st = runtimeContext.getAppState(); + const isBatchMode = batchModeAllElements !== null; + let allElements = batchModeAllElements || runtimeContext.ea.getViewElements(); + let parent = batchModeParent; + let usingCustomParent = false; + if (!isBatchMode) { + parent = runtimeContext.getMindmapNodeFromSelection(); + if (!parent) { + parent = runtimeContext.ea.getViewSelectedElement(); + usingCustomParent = !!parent; + } + if (parent?.containerId) { + parent = allElements.find((el) => el.id === parent.containerId); + } + if (parent && parent.customData?.isFolded) { + await runtimeContext.toggleFold("L0"); + allElements = runtimeContext.ea.getViewElements(); + parent = allElements.find((el) => el.id === parent.id); + } + } + let newNodeId; + let arrowId; + const imageInfo = runtimeContext.parseImageInput(text); + const embeddableUrl = runtimeContext.parseEmbeddableInput(text, imageInfo); + const defaultNodeColor = runtimeContext.ea.getCM(st.viewBackgroundColor).invert().stringHEX({ + alpha: false + }); + let depth = 0, nodeColor = defaultNodeColor, rootId, nextSiblingOrder = 0; + let settingsRoot = null; + let rootCfgForAdd = null; + if (parent) { + const siblings = runtimeContext.getChildrenNodes(parent.id, allElements); + nextSiblingOrder = Math.max(0, ...siblings.map(runtimeContext.getMindmapOrder)) + 1; + settingsRoot = runtimeContext.getSettingsRootNode(parent, allElements) || allElements.find((e) => e.id === runtimeContext.getHierarchy(parent, allElements).rootId); + rootId = settingsRoot?.id; + rootCfgForAdd = runtimeContext.getRootConfigForNode(settingsRoot); + const parentDepthFromSettingsRoot = runtimeContext.getDepthFromAncestor( + parent.id, + rootId, + allElements + ); + depth = parentDepthFromSettingsRoot + 1; + const rootEl = settingsRoot; + if (depth === 1) { + if (rootCfgForAdd.multicolor) { + const existingColors = runtimeContext.getChildrenNodes(parent.id, allElements).map((n) => n.strokeColor); + nodeColor = runtimeContext.getDynamicColor(existingColors); + } else { + nodeColor = rootEl.strokeColor; + } + } else { + if (parent.type === "image" || parent.type === "embeddable") { + const incomingArrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === parent.id + ); + nodeColor = incomingArrow ? incomingArrow.strokeColor : parent.strokeColor && parent.strokeColor.toLowerCase() !== "transparent" ? parent.strokeColor : defaultNodeColor; + } else { + nodeColor = parent.strokeColor; + } + } + const effectiveMulticolor = rootCfgForAdd?.multicolor ?? runtimeContext.multicolor; + const effectiveIsSolidArrow = rootCfgForAdd?.isSolidArrow ?? runtimeContext.isSolidArrow; + if (!effectiveMulticolor && !effectiveIsSolidArrow) { + const parentStrokeColor = (parent.strokeColor || "transparent").toLowerCase(); + const isTransparent = parentStrokeColor === "transparent"; + let isSameAsBg = false; + if (!isTransparent) { + const parentColorCM = runtimeContext.ea.getCM(parent.strokeColor); + const bgColorCM = runtimeContext.ea.getCM(st.viewBackgroundColor); + if (parentColorCM && bgColorCM && parentColorCM.stringHEX() === bgColorCM.stringHEX()) { + isSameAsBg = true; + } + } + if (isTransparent || isSameAsBg) { + nodeColor = runtimeContext.ea.getCM(st.viewBackgroundColor).invert().stringHEX({ alpha: false }); + } + } + } + const fontScale = runtimeContext.getFontScale( + rootCfgForAdd?.fontsizeScale ?? runtimeContext.fontsizeScale + ); + if (!isBatchMode) runtimeContext.ea.clear(); + runtimeContext.ea.style.fontFamily = st.currentItemFontFamily; + runtimeContext.ea.style.fontSize = fontScale[Math.min(depth, fontScale.length - 1)]; + runtimeContext.ea.style.roundness = rootCfgForAdd?.roundedCorners ?? runtimeContext.roundedCorners ? { + type: 3 + } : null; + const effectiveMaxWrap = rootCfgForAdd?.maxWrapWidth ?? runtimeContext.maxWidth; + let curMaxW = depth === 0 ? Math.max(400, effectiveMaxWrap) : effectiveMaxWrap; + let renderedText = text; + let metrics = { + w: 0, + h: 0 + }; + let shouldWrap = false; + let curMaxH = 0; + if (!imageInfo?.isImagePath && !imageInfo?.imageFile && !embeddableUrl) { + renderedText = await runtimeContext.parseText(text) ?? text; + metrics = runtimeContext.ea.measureText(renderedText); + shouldWrap = metrics.width > curMaxW; + curMaxH = metrics.height; + if (shouldWrap) { + const res = await runtimeContext.getAdjustedMaxWidth(text, curMaxW); + curMaxW = res.width; + curMaxH = res.height; + } + } + if (!parent) { + runtimeContext.ea.style.strokeColor = runtimeContext.multicolor ? defaultNodeColor : st.currentItemStrokeColor; + if (imageInfo?.isImagePath) { + newNodeId = await addImage({ + pathOrFile: imageInfo.path, + width: imageInfo.width, + depth + }); + if (imageInfo.isExternalImage && newNodeId) { + const el = runtimeContext.ea.getElement(newNodeId); + if (el && !el.link) el.link = imageInfo.path; + } + } else if (imageInfo?.imageFile) { + newNodeId = await addImage({ + pathOrFile: imageInfo.imageFile, + width: imageInfo.width, + depth + }); + } else if (embeddableUrl) { + newNodeId = addEmbeddableNode({ + url: embeddableUrl, + depth: 0 + }); + } else { + runtimeContext.ea.style.fillStyle = "solid"; + runtimeContext.ea.style.backgroundColor = st.viewBackgroundColor; + runtimeContext.ea.style.strokeWidth = runtimeContext.getStrokeWidthForDepth(0); + runtimeContext.ea.style.roughness = runtimeContext.getAppState().currentItemRoughness; + newNodeId = runtimeContext.ea.addText( + 0, + 0, + text, + { + box: "rectangle", + textAlign: "center", + textVerticalAlign: "middle", + // Use a distinct color representation so the frame can be recolored separately from text + boxStrokeColor: runtimeContext.ea.getCM(runtimeContext.ea.style.strokeColor).stringRGB(), + width: shouldWrap ? curMaxW : void 0, + height: shouldWrap ? curMaxH : void 0, + autoResize: !shouldWrap + }, + preGenTextId + ); + runtimeContext.ea.style.backgroundColor = "transparent"; + } + initializeRootCustomData(newNodeId); + rootId = newNodeId; + } else { + runtimeContext.ea.style.strokeColor = nodeColor; + const rootEl = allElements.find((e) => e.id === rootId); + const rootBox = runtimeContext.getNodeBox(rootEl, allElements); + const mode = rootCfgForAdd?.growthMode || rootEl.customData?.growthMode || runtimeContext.currentModalGrowthMode; + const rootCenter = { + x: rootBox.minX + rootBox.width / 2, + y: rootBox.minY + rootBox.height / 2 + }; + const parentBox = runtimeContext.getNodeBox(parent, allElements); + const isVerticalMode = ["Up-facing", "Down-facing", "Up-Down"].includes(mode); + let targetSide = 1; + if (depth === 1) { + if (mode === "Left-facing" || mode === "Up-facing") targetSide = -1; + else if (mode === "Right-facing" || mode === "Down-facing") targetSide = 1; + else if (mode === "Right-Left" || mode === "Up-Down") { + const siblings = runtimeContext.getChildrenNodes(parent.id, allElements); + const idx = siblings.length; + if (idx < 2) targetSide = 1; + else if (idx < 4) targetSide = -1; + else targetSide = idx % 2 === 0 ? 1 : -1; + } else { + if (isVerticalMode) { + const parentCenterY = parentBox.minY + parentBox.height / 2; + targetSide = parentCenterY > rootCenter.y ? 1 : -1; + } else { + const parentCenterX = parentBox.minX + parentBox.width / 2; + targetSide = parentCenterX > rootCenter.x ? 1 : -1; + } + } + } else { + if (isVerticalMode) { + const parentCenterY = parentBox.minY + parentBox.height / 2; + targetSide = parentCenterY > rootCenter.y ? 1 : -1; + } else { + const parentCenterX = parentBox.minX + parentBox.width / 2; + targetSide = parentCenterX > rootCenter.x ? 1 : -1; + } + } + let side = targetSide; + let px = parentBox.minX, py = parentBox.minY; + if (isVerticalMode) { + const offset = side === 1 ? rootBox.height * 2 : -rootBox.height; + px = parentBox.minX + parentBox.width / 2 - (shouldWrap ? curMaxW : metrics.width) / 2; + py = parentBox.minY + offset; + if (!runtimeContext.autoLayoutDisabled && pos) { + px = pos.x; + py = pos.y; + side = py + metrics.height / 2 > rootCenter.y ? 1 : -1; + } else if (!runtimeContext.autoLayoutDisabled) { + const siblings = runtimeContext.getChildrenNodes(parent.id, allElements); + if (siblings.length > 0) { + const sortedSiblings = siblings.sort((a, b) => a.x - b.x); + const lastSibling = sortedSiblings[sortedSiblings.length - 1]; + const lastSiblingBox = runtimeContext.getNodeBox(lastSibling, allElements); + px = lastSiblingBox.minX + lastSiblingBox.width + runtimeContext.layoutSettings.GAP_Y; + py = parentBox.minY + (side === 1 ? parentBox.height + runtimeContext.layoutSettings.GAP_X : -runtimeContext.layoutSettings.GAP_X - metrics.height); + } + } else if (runtimeContext.autoLayoutDisabled) { + const manualGapY = Math.round( + parentBox.height * runtimeContext.layoutSettings.MANUAL_GAP_MULTIPLIER + ); + const jitterX = (Math.random() - 0.5) * runtimeContext.layoutSettings.MANUAL_JITTER_RANGE; + const jitterY = (Math.random() - 0.5) * runtimeContext.layoutSettings.MANUAL_JITTER_RANGE; + px = parentBox.minX + parentBox.width / 2 - metrics.width / 2 + jitterX; + py = side === 1 ? parentBox.minY + parentBox.height + manualGapY + jitterY : parentBox.minY - manualGapY - metrics.height + jitterY; + } + } else { + const offset = mode === "Radial" || side === 1 ? rootBox.width * 2 : -rootBox.width; + px = parentBox.minX + offset; + py = parentBox.minY; + if (!runtimeContext.autoLayoutDisabled && pos) { + px = pos.x; + py = pos.y; + side = px + (shouldWrap ? curMaxW : metrics.width) / 2 > rootCenter.x ? 1 : -1; + } else if (!runtimeContext.autoLayoutDisabled) { + const siblings = runtimeContext.getChildrenNodes(parent.id, allElements); + if (siblings.length > 0) { + const sortedSiblings = siblings.sort((a, b) => a.y - b.y); + const lastSibling = sortedSiblings[sortedSiblings.length - 1]; + const lastSiblingBox = runtimeContext.getNodeBox(lastSibling, allElements); + py = lastSiblingBox.minY + lastSiblingBox.height + runtimeContext.layoutSettings.GAP_Y; + } + } else if (runtimeContext.autoLayoutDisabled) { + const manualGapX = Math.round( + parentBox.width * runtimeContext.layoutSettings.MANUAL_GAP_MULTIPLIER + ); + const jitterX = (Math.random() - 0.5) * runtimeContext.layoutSettings.MANUAL_JITTER_RANGE; + const jitterY = (Math.random() - 0.5) * runtimeContext.layoutSettings.MANUAL_JITTER_RANGE; + const nodeW = shouldWrap ? curMaxW : metrics.width; + px = side === 1 ? parentBox.minX + parentBox.width + manualGapX + jitterX : parentBox.minX - manualGapX - nodeW + jitterX; + py = parentBox.minY + parentBox.height / 2 - metrics.height / 2 + jitterY; + } + } + const effectiveCenterText = rootCfgForAdd?.centerText ?? runtimeContext.centerText; + const effectiveBoxChildren = rootCfgForAdd?.boxChildren ?? runtimeContext.boxChildren; + const effectiveArrowType = rootCfgForAdd?.arrowType ?? runtimeContext.arrowType; + const effectiveIsSolidArrow = rootCfgForAdd?.isSolidArrow ?? runtimeContext.isSolidArrow; + const effectiveBranchScale = rootCfgForAdd?.branchScale ?? runtimeContext.branchScale; + const effectiveBaseStrokeWidth = rootCfgForAdd?.baseStrokeWidth ?? runtimeContext.baseStrokeWidth; + const textAlign = effectiveCenterText ? "center" : isVerticalMode ? "center" : side === 1 ? "left" : "right"; + if (imageInfo?.isImagePath) { + newNodeId = await addImage({ + pathOrFile: imageInfo.path, + width: imageInfo.width, + leftFacing: side === -1 && !runtimeContext.autoLayoutDisabled, + x: px, + y: py, + depth + }); + if (imageInfo.isExternalImage && newNodeId) { + const el = runtimeContext.ea.getElement(newNodeId); + if (el && !el.link) el.link = imageInfo.path; + } + } else if (imageInfo?.imageFile) { + newNodeId = await addImage({ + pathOrFile: imageInfo.imageFile, + width: imageInfo.width, + leftFacing: side === -1 && !runtimeContext.autoLayoutDisabled, + x: px, + y: py, + depth + }); + } else if (embeddableUrl) { + newNodeId = addEmbeddableNode({ + px, + py, + url: embeddableUrl, + depth + }); + const el = runtimeContext.ea.getElement(newNodeId); + if (side === -1 && !runtimeContext.autoLayoutDisabled) el.x = px - el.width; + } else { + runtimeContext.ea.style.strokeWidth = runtimeContext.calculateStrokeWidth( + depth, + effectiveBaseStrokeWidth, + effectiveBranchScale + ); + runtimeContext.ea.style.roughness = runtimeContext.getAppState().currentItemRoughness; + newNodeId = runtimeContext.ea.addText( + px, + py, + text, + { + box: effectiveBoxChildren ? "rectangle" : false, + textAlign, + textVerticalAlign: "middle", + width: shouldWrap ? curMaxW : void 0, + height: shouldWrap ? curMaxH : void 0, + autoResize: !shouldWrap + }, + preGenTextId + ); + } + if (depth === 1) { + runtimeContext.ea.addAppendUpdateCustomData(newNodeId, { + mindmapNew: !!pos ? false : true, + // if position is provided a sibling is being added to a defined spot in the layout + mindmapOrder: nextSiblingOrder + }); + } else { + runtimeContext.ea.addAppendUpdateCustomData(newNodeId, { + mindmapOrder: nextSiblingOrder + }); + } + if (!runtimeContext.ea.getElement(parent.id)) { + runtimeContext.ea.copyViewElementsToEAforEditing([parent]); + parent = runtimeContext.ea.getElement(parent.id); + } + if (depth > 1 && usingCustomParent && !parent.customData?.mindmapOrder) { + runtimeContext.ea.addAppendUpdateCustomData(parent.id, { + mindmapOrder: nextSiblingOrder + }); + } + if ((depth === 0 || usingCustomParent) && !parent.customData?.growthMode && !parent.customData?.mindmapOrder) { + initializeRootCustomData(parent.id); + } + if ((parent.type === "image" || parent.type === "embeddable") && typeof parent.customData?.mindmapOrder === "undefined") { + runtimeContext.ea.addAppendUpdateCustomData(parent.id, { + mindmapOrder: 0 + }); + } + runtimeContext.ea.style.strokeWidth = runtimeContext.calculateStrokeWidth( + depth, + effectiveBaseStrokeWidth, + effectiveBranchScale + ); + runtimeContext.ea.style.roughness = runtimeContext.getAppState().currentItemRoughness; + runtimeContext.ea.style.strokeStyle = effectiveIsSolidArrow ? "solid" : runtimeContext.getAppState().currentItemStrokeStyle; + const startPoint = [ + parentBox.minX + parentBox.width / 2, + parentBox.minY + parentBox.height / 2 + ]; + arrowId = runtimeContext.ea.addArrow([startPoint, startPoint], { + startObjectId: parent.id, + endObjectId: newNodeId, + startArrowHead: null, + endArrowHead: null + }); + const eaArrow = runtimeContext.ea.getElement(arrowId); + if (effectiveArrowType === "curved") { + eaArrow.roundness = { + type: 2 + }; + } else { + eaArrow.roundness = null; + } + runtimeContext.ea.addAppendUpdateCustomData(arrowId, { + isBranch: true + }); + if (ontology) { + runtimeContext.addUpdateArrowLabel(eaArrow, ontology); + } + if (!runtimeContext.groupBranches && parent.groupIds?.length > 0) { + const mindmapIds = runtimeContext.getBranchElementIds( + parent.id, + runtimeContext.ea.getViewElements() + ); + const { structuralGroupId } = runtimeContext.getStructuralGroupForNode( + mindmapIds, + allElements, + rootId + ); + if (structuralGroupId) { + const newNode = runtimeContext.ea.getElement(newNodeId); + const newArrow = runtimeContext.ea.getElement(arrowId); + if (newNode) newNode.groupIds = [structuralGroupId]; + if (newArrow) newArrow.groupIds = [structuralGroupId]; + } + } + } + if (isBatchMode) { + return runtimeContext.ea.getElement(newNodeId); + } + const hasImage = !!imageInfo?.imageFile || imageInfo?.isImagePath; + await runtimeContext.addElementsToView({ + repositionToCursor: !parent, + save: hasImage, + captureUpdate: "EVENTUALLY" + }); + if (rootId && (runtimeContext.autoLayoutDisabled || skipFinalLayout) && parent) { + const allEls = runtimeContext.ea.getViewElements(); + const node = allEls.find((el) => el.id === newNodeId); + const arrow = allEls.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === newNodeId + ); + runtimeContext.ea.copyViewElementsToEAforEditing( + runtimeContext.groupBranches ? allEls : arrow ? [arrow] : [] + ); + if (arrow) { + const parentCenterX = parent.x + parent.width / 2; + const childCenterX = node.x + node.width / 2; + const isChildRight = childCenterX > parentCenterX; + const sX = isChildRight ? parent.x + parent.width : parent.x; + const sY = parent.y + parent.height / 2; + const eX = isChildRight ? node.x : node.x + node.width; + const eY = node.y + node.height / 2; + runtimeContext.configureArrow({ + arrowId: arrow.id, + isChildRight, + startId: parent.id, + endId: node.id, + coordinates: { + sX, + sY, + eX, + eY + } + }); + } + if (runtimeContext.groupBranches) { + runtimeContext.ea.getElements().forEach((el) => { + if (el.groupIds) { + el.groupIds = el.groupIds.filter((gid) => !runtimeContext.isMindmapGroup(gid, allEls)); + } + }); + const l1Nodes = runtimeContext.getChildrenNodes(rootId, allEls); + l1Nodes.forEach((l1) => runtimeContext.applyRecursiveGrouping(l1.id, allEls)); + } else { + const { l1AncestorId } = runtimeContext.getHierarchy(parent, allEls); + const bIds = runtimeContext.getBranchElementIds(l1AncestorId, allEls); + const existingGroupedEl = allEls.find( + (el) => bIds.includes(el.id) && el.id !== newNodeId && el.id !== arrowId && runtimeContext.getStructuralGroup(el, allEls, rootId) + ); + const commonGroupId = existingGroupedEl ? runtimeContext.getStructuralGroup(existingGroupedEl, allEls, rootId) : null; + if (commonGroupId) { + const newIds = [newNodeId, arrowId].filter(Boolean); + runtimeContext.ea.copyViewElementsToEAforEditing( + allEls.filter((el) => newIds.includes(el.id)) + ); + newIds.forEach((id) => { + const el = runtimeContext.ea.getElement(id); + if (el) el.groupIds = [commonGroupId]; + }); + } + } + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY" + }); + } + const finalNode = runtimeContext.ea.getViewElements().find((el) => el.id === newNodeId); + if (follow || !parent) { + runtimeContext.selectNodeInView(finalNode); + } else if (parent) { + runtimeContext.selectNodeInView(parent); + } + if (!parent) { + runtimeContext.zoomToFit(); + } + runtimeContext.mostRecentlyAddedNodeID = finalNode.id; + runtimeContext.focusInputEl(); + await runtimeContext.triggerGlobalLayout(rootId); + return finalNode; + }; + return { addEmbeddableNode, addImage, initializeRootCustomData, addNode }; + } + + // src/scripts/mindmap-builder/markdownExport.js + function createMarkdownExport(runtimeContext) { + const copyMapAsText = async (cut = false, toClipboard = true) => { + if (!runtimeContext.isViewSet()) return; + runtimeContext.ensureNodeSelected(); + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_SELECT_NODE_TO_COPY")); + return; + } + const all = runtimeContext.ea.getViewElements(); + const info = runtimeContext.getHierarchy(sel, all); + const isRootSelected = info.rootId === sel.id; + const parentNode = runtimeContext.getParentNode(sel.id, all); + const root = all.find((el) => el.id === info.rootId); + const defaultMode = root?.customData?.growthMode || runtimeContext.currentModalGrowthMode; + const elementsToDelete = []; + const useTab = app.vault.getConfig("useTab"); + const tabSize = app.vault.getConfig("tabSize"); + const indentVal = useTab ? " " : " ".repeat(tabSize); + const branchIds = new Set(runtimeContext.getBranchElementIds(sel.id, all)); + const nodeBlockRefs = /* @__PURE__ */ new Map(); + const nodeOutgoingLinks = /* @__PURE__ */ new Map(); + const crossLinkArrows = all.filter( + (el) => el.type === "arrow" && !el.customData?.isBranch && branchIds.has(el.startBinding?.elementId) && branchIds.has(el.endBinding?.elementId) + ); + const hasCrosslinks = crossLinkArrows.length > 0; + const lineSeparator = hasCrosslinks ? "\n\n" : "\n"; + if (hasCrosslinks) { + crossLinkArrows.forEach((arrow) => { + const startId = arrow.startBinding.elementId; + const endId = arrow.endBinding.elementId; + if (!nodeBlockRefs.has(endId)) { + nodeBlockRefs.set(endId, "^" + runtimeContext.ea.generateElementId().substring(0, 8)); + } + if (!nodeOutgoingLinks.has(startId)) { + nodeOutgoingLinks.set(startId, []); + } + const boundTextId = arrow.boundElements?.find((be) => be.type === "text")?.id; + const labelTextElement = boundTextId ? all.find((el) => el.id === boundTextId) : null; + const refString = nodeBlockRefs.get(endId); + let linkText; + if (labelTextElement && labelTextElement.rawText) { + const label = labelTextElement.rawText.replace(/\n/g, " "); + linkText = `(${label}:: [[#${refString}|*]])`; + } else { + linkText = `[[#${refString}|*]]`; + } + nodeOutgoingLinks.get(startId).push(linkText); + if (cut) elementsToDelete.push(arrow); + }); + } + const submapsQueue = []; + const buildList = (nodeId, depth = 0, isSubmapChild = false, isPrintRoot = false) => { + const node = all.find((e) => e.id === nodeId); + if (!node) return ""; + if (cut) { + elementsToDelete.push(node); + node.boundElements?.forEach((be) => { + const boundEl = all.find((e) => e.id === be.id); + if (boundEl) elementsToDelete.push(boundEl); + }); + if (node.customData?.foldIndicatorId) { + const ind = all.find((e) => e.id === node.customData.foldIndicatorId); + if (ind) elementsToDelete.push(ind); + } + if (node.customData?.boundaryId) { + const boundary = all.find((e) => e.id === node.customData.boundaryId); + if (boundary) elementsToDelete.push(boundary); + } + } + let str = ""; + let text = runtimeContext.getTextFromNode(all, node, true); + let ontologyStr = ""; + if (!isRootSelected || depth > 0 || isSubmapChild) { + const incomingArrow = all.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === nodeId + ); + if (incomingArrow) { + const boundTextEl = runtimeContext.ea.getBoundTextElement( + incomingArrow, + true + ).sceneElement; + if (boundTextEl && boundTextEl.rawText) { + ontologyStr = boundTextEl.rawText.replace(/\n/g, " ") + ":: "; + if (cut) elementsToDelete.push(boundTextEl); + } + } + } + let refSuffixes = ""; + if (nodeOutgoingLinks.has(nodeId)) + refSuffixes += ` ${nodeOutgoingLinks.get(nodeId).join(" ")}`; + if (node.customData?.boundaryId) refSuffixes += " #boundary"; + if (nodeBlockRefs.has(nodeId)) refSuffixes += ` ${nodeBlockRefs.get(nodeId)}`; + let isTask = false; + let taskPrefix = ""; + const taskMatch = text.match(/^- \[[ xX]\] /); + if (taskMatch) { + isTask = true; + taskPrefix = taskMatch[0]; + text = text.substring(taskPrefix.length); + } + if (!isPrintRoot && node.customData?.isAdditionalRoot) { + let submapTitle = text; + if (submapTitle.startsWith("![[") && submapTitle.endsWith("]]")) { + submapTitle = submapTitle.slice(3, -2).split("|")[0]; + } else if (submapTitle.startsWith("![") && submapTitle.endsWith(")")) { + submapTitle = "Submap " + nodeId.substring(0, 4); + } + const linkText = `![[#${submapTitle}]]`; + const repeatCount = Math.max(0, depth - (isRootSelected ? 1 : 0)); + let currentIndent = isSubmapChild ? indentVal.repeat(depth) : indentVal.repeat(repeatCount); + if (isTask) { + str += `${currentIndent}${taskPrefix}${ontologyStr}${linkText}${refSuffixes}${lineSeparator}`; + } else { + str += `${currentIndent}- ${ontologyStr}${linkText}${refSuffixes}${lineSeparator}`; + } + submapsQueue.push({ + id: nodeId, + title: submapTitle + }); + return str; + } + if (depth === 0 && isRootSelected && !isSubmapChild) { + str += `# ${taskPrefix}${ontologyStr}${text}${refSuffixes}${lineSeparator}`; + } else { + const repeatCount = Math.max(0, depth - (isRootSelected ? 1 : 0)); + let currentIndent = isSubmapChild ? indentVal.repeat(depth) : indentVal.repeat(repeatCount); + if (isTask) { + str += `${currentIndent}${taskPrefix}${ontologyStr}${text}${refSuffixes}${lineSeparator}`; + } else { + str += `${currentIndent}- ${ontologyStr}${text}${refSuffixes}${lineSeparator}`; + } + } + let children = runtimeContext.getChildrenNodes(nodeId, all); + const parentCenter = { + x: node.x + node.width / 2, + y: node.y + node.height / 2 + }; + const mode = node.customData?.isAdditionalRoot ? node.customData.growthMode : defaultMode; + if (mode === "Radial") { + children.sort((a, b) => { + const centerA = { + x: a.x + a.width / 2, + y: a.y + a.height / 2 + }; + const centerB = { + x: b.x + b.width / 2, + y: b.y + b.height / 2 + }; + return runtimeContext.getAngleFromCenter(parentCenter, centerA) - runtimeContext.getAngleFromCenter(parentCenter, centerB); + }); + } else if (mode === "Right-Left" && nodeId === info.rootId) { + const right = []; + const left = []; + children.forEach((child) => { + const childCx = child.x + child.width / 2; + if (childCx > parentCenter.x) right.push(child); + else left.push(child); + }); + right.sort((a, b) => a.y - b.y); + left.sort((a, b) => a.y - b.y); + children = [...right, ...left]; + } else { + children.sort((a, b) => a.y - b.y); + } + children.forEach((c) => { + if (cut) { + const arrow = all.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === nodeId && a.endBinding?.elementId === c.id + ); + if (arrow) elementsToDelete.push(arrow); + } + str += buildList(c.id, depth + 1, isSubmapChild, false); + }); + return str; + }; + let md = buildList(sel.id, 0, false, true); + const processedSubmaps = /* @__PURE__ */ new Set(); + if (submapsQueue.length > 0) { + md += ` +--- +`; + } + while (submapsQueue.length > 0) { + const submapObj = submapsQueue.shift(); + if (processedSubmaps.has(submapObj.id)) continue; + processedSubmaps.add(submapObj.id); + md += ` +## ${submapObj.title} +`; + const submapNode = all.find((e) => e.id === submapObj.id); + let children = runtimeContext.getChildrenNodes(submapObj.id, all); + const parentCenter = { + x: submapNode.x + submapNode.width / 2, + y: submapNode.y + submapNode.height / 2 + }; + const mode = submapNode.customData?.growthMode || defaultMode; + if (mode === "Radial") { + children.sort((a, b) => { + const centerA = { + x: a.x + a.width / 2, + y: a.y + a.height / 2 + }; + const centerB = { + x: b.x + b.width / 2, + y: b.y + b.height / 2 + }; + return runtimeContext.getAngleFromCenter(parentCenter, centerA) - runtimeContext.getAngleFromCenter(parentCenter, centerB); + }); + } else if (mode === "Right-Left") { + const right = []; + const left = []; + children.forEach((child) => { + const childCx = child.x + child.width / 2; + if (childCx > parentCenter.x) right.push(child); + else left.push(child); + }); + right.sort((a, b) => a.y - b.y); + left.sort((a, b) => a.y - b.y); + children = [...right, ...left]; + } else { + children.sort((a, b) => a.y - b.y); + } + children.forEach((c) => { + if (cut) { + const arrow = all.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === submapObj.id && a.endBinding?.elementId === c.id + ); + if (arrow) elementsToDelete.push(arrow); + } + md += buildList(c.id, 0, true, false); + }); + } + if (toClipboard) await navigator.clipboard.writeText(md); + if (cut) { + const incomingArrow = all.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === sel.id + ); + if (incomingArrow) elementsToDelete.push(incomingArrow); + runtimeContext.ea.deleteViewElements(elementsToDelete); + if (parentNode) { + const remainingChildren = runtimeContext.getChildrenNodes( + parentNode.id, + runtimeContext.ea.getViewElements() + ); + if (remainingChildren.length === 0) { + runtimeContext.ea.copyViewElementsToEAforEditing([parentNode]); + runtimeContext.ea.addAppendUpdateCustomData(parentNode.id, { + isFolded: false, + foldIndicatorId: void 0 + }); + if (parentNode.customData?.foldIndicatorId) { + const indicator = runtimeContext.ea.getViewElements().find((el) => el.id === parentNode.customData.foldIndicatorId); + if (indicator) runtimeContext.ea.deleteViewElements([indicator]); + } + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY" + }); + } + runtimeContext.selectNodeInView(parentNode); + } + runtimeContext.triggerGlobalLayout(info.rootId); + new runtimeContext.Notice( + isRootSelected ? runtimeContext.t("NOTICE_MAP_CUT") : runtimeContext.t("NOTICE_BRANCH_CUT") + ); + } else { + new runtimeContext.Notice( + isRootSelected ? runtimeContext.t("NOTICE_MAP_COPIED") : runtimeContext.t("NOTICE_BRANCH_COPIED") + ); + } + return md; + }; + return { copyMapAsText }; + } + + // src/scripts/mindmap-builder/branchClipboard.ts + var nodeTypes = /* @__PURE__ */ new Set(["text", "rectangle", "ellipse", "diamond", "image", "embeddable"]); + function isTaggedNode(element) { + if (element.containerId || !nodeTypes.has(element.type)) return false; + const data = element.customData; + return !!data && (data.mindmapOrder !== void 0 || !!data.growthMode || data.isAdditionalRoot === true); + } + function hasParentCycle(nodes, incoming) { + const checked = /* @__PURE__ */ new Set(); + for (const id of nodes) { + const path = /* @__PURE__ */ new Set(); + let current = id; + while (current && !checked.has(current)) { + if (path.has(current)) return true; + path.add(current); + current = incoming.get(current); + } + path.forEach((n) => checked.add(n)); + } + return false; + } + function branchEndpoints(arrow, normalize) { + const start = normalize(arrow.startBinding?.elementId); + const end = normalize(arrow.endBinding?.elementId); + return start && end ? { start, end } : null; + } + function excludeConnector(element, excluded) { + excluded.add(element.id); + for (const bound of element.boundElements ?? []) { + if (bound.type === "text") excluded.add(bound.id); + } + } + function supportsBranchEndpoints(start, end) { + return nodeTypes.has(start.type) && nodeTypes.has(end.type); + } + function parseBranchClipboard(text) { + try { + const data = JSON.parse(text); + if (data?.type !== "excalidraw/clipboard" || !Array.isArray(data.elements)) return null; + if (!data.elements.every((e) => e && typeof e.id === "string" && typeof e.type === "string")) + return null; + return data; + } catch { + return null; + } + } + function analyzeBranchClipboard(payload) { + const elements = payload.elements.filter((e) => !e.isDeleted); + const byId = new Map(elements.map((e) => [e.id, e])); + if (byId.size !== elements.length) return { kind: "invalid" }; + const normalize = (id) => { + const e = id ? byId.get(id) : void 0; + return e?.containerId ? byId.get(e.containerId) : e; + }; + const nodes = /* @__PURE__ */ new Map(); + elements.forEach((e) => { + if (isTaggedNode(e)) nodes.set(e.id, e); + }); + const incoming = /* @__PURE__ */ new Map(); + const excluded = /* @__PURE__ */ new Set(); + const branches = elements.filter((e) => e.type === "arrow" && e.customData?.isBranch); + for (const e of branches) { + const endpoints = branchEndpoints(e, normalize); + if (!endpoints) { + excludeConnector(e, excluded); + continue; + } + const { start, end } = endpoints; + if (!supportsBranchEndpoints(start, end) || incoming.has(end.id)) return { kind: "invalid" }; + nodes.set(start.id, start); + nodes.set(end.id, end); + incoming.set(end.id, start.id); + } + if (!nodes.size) return { kind: "none" }; + if (hasParentCycle(nodes.keys(), incoming)) return { kind: "invalid" }; + const rootIds = [...nodes.keys()].filter((id) => !incoming.has(id)); + return { kind: "branch", elements: elements.filter((e) => !excluded.has(e.id)), rootIds }; + } + function markBranchClipboard(payload, elements, marker) { + const copy = JSON.parse(JSON.stringify({ ...payload, elements })); + const kept = new Set(elements.map((e) => e.id)); + copy.elements.forEach((e) => { + e.customData = { ...e.customData, [marker]: e.id }; + if (e.boundElements) e.boundElements = e.boundElements.filter((b) => kept.has(b.id)); + }); + return copy; + } + function remapBranchMetadata(element, source, idMap, marker) { + const customData = { ...element.customData }; + delete customData[marker]; + for (const key of ["boundaryId", "foldIndicatorId"]) { + if (typeof source.customData?.[key] === "string") { + const id = idMap.get(source.customData[key]); + if (id) customData[key] = id; + else delete customData[key]; + } + } + return customData; + } + + // src/scripts/mindmap-builder/pasteMetadata.js + function createPasteMetadataCleanup() { + const registrations = /* @__PURE__ */ new Map(); + const dispose = () => { + registrations.forEach(({ unsubscribe, operations, repair: repair2 }) => { + operations.forEach((op) => { + op.transportActive = false; + }); + repair2(); + unsubscribe(); + }); + registrations.clear(); + }; + const track = (api, marker, operation) => { + registrations.forEach((registration2, oldApi) => { + if (oldApi.isDestroyed) { + registration2.unsubscribe(); + registrations.delete(oldApi); + } + }); + let registration = registrations.get(api); + if (!registration) { + registration = { operations: /* @__PURE__ */ new Map(), unsubscribe: () => { + } }; + registrations.set(api, registration); + registration.repair = () => { + if (api.isDestroyed) return; + const elements = api.getSceneElementsIncludingDeleted(); + if (!elements.some( + (e) => e.customData && Object.keys(e.customData).some( + (key) => key.startsWith("__mindmapPaste_") && registration.operations.get(key)?.transportActive !== true + ) + )) + return; + let changed = false; + const repaired = elements.map((e) => { + if (!e.customData) return e; + let customData; + for (const key of Object.keys(e.customData)) { + if (!key.startsWith("__mindmapPaste_")) continue; + let operation2 = registration.operations.get(key); + if (!operation2) { + operation2 = { transportActive: false, idMap: /* @__PURE__ */ new Map() }; + registration.operations.set(key, operation2); + } + if (operation2.transportActive) continue; + customData ??= { ...e.customData }; + delete customData[key]; + if (!operation2.idMap.size) + operation2.idMap = new Map( + api.getSceneElementsIncludingDeleted().filter((e2) => e2.customData?.[key]).map((e2) => [e2.customData[key], e2.id]) + ); + const mapping = operation2.idMap; + for (const ref of ["boundaryId", "foldIndicatorId"]) { + const oldId = customData[ref]; + if (typeof oldId === "string") { + if (mapping.has(oldId)) customData[ref] = mapping.get(oldId); + else if (![...mapping.values()].includes(oldId)) delete customData[ref]; + } + } + } + if (!customData) return e; + changed = true; + return ExcalidrawLib.newElementWith(e, { customData }); + }); + if (changed && !api.isDestroyed) + api.updateScene({ elements: repaired, captureUpdate: "NEVER" }); + }; + registration.unsubscribe = api.onChange(registration.repair); + } + if (marker) registration.operations.set(marker, operation); + }; + const repair = (api) => registrations.get(api)?.repair(); + const watch = (api) => { + if (!api || api.isDestroyed) return; + track(api, null, null); + repair(api); + }; + return { track, dispose, repair, watch }; + } + + // src/scripts/mindmap-builder/branchPaste.js + function createBranchPaste(ctx) { + let pending = null; + const metadata = createPasteMetadataCleanup(); + const cancelBranchPaste = () => pending?.cancel(); + const disposeBranchPaste = () => { + cancelBranchPaste(); + metadata.dispose(); + }; + ctx.ea.registerCleanup?.(disposeBranchPaste); + const watchPasteMetadata = () => metadata.watch(ctx.api()); + watchPasteMetadata(); + const isBranchPasteBusy = () => pending !== null; + const pasteBranch = async (payload, parent) => { + const analysis = analyzeBranchClipboard(payload); + if (analysis.kind === "none") return false; + if (pending) return true; + if (analysis.kind === "invalid") { + new ctx.Notice(ctx.t("NOTICE_BRANCH_PASTE_INVALID")); + return true; + } + const view = ctx.ea.targetView; + const api = ctx.api(); + const filePath = view.file?.path; + const win = view.ownerWindow; + const marker = `__mindmapPaste_${ctx.ea.generateElementId()}`; + const transport = markBranchClipboard(payload, analysis.elements, marker); + const sources = new Map(analysis.elements.map((e) => [e.id, e])); + const op = { cancelled: false, cancel: () => { + }, transportActive: true, idMap: /* @__PURE__ */ new Map() }; + pending = op; + const alive = () => !op.cancelled && ctx.isViewSet() && ctx.ea.sidepanelTab && ctx.ea.targetView === view && view.file?.path === filePath && ctx.api() === api && !api.isDestroyed; + let pasted = []; + const gestureDocuments = new Set( + [view.ownerDocument, ctx.sidepanelWindow?.document].filter(Boolean) + ); + gestureDocuments.forEach( + (doc) => doc.addEventListener?.("pointerdown", cancelBranchPaste, true) + ); + try { + metadata.track(api, marker, op); + if (!alive() || api.getAppState().viewModeEnabled || api.getAppState().editingTextElement) + throw new Error("paste unavailable"); + if (parent) { + const all2 = ctx.ea.getViewElements(); + const seen = /* @__PURE__ */ new Set(); + let cursor = parent; + while (cursor) { + if (seen.has(cursor.id)) throw new Error("cyclic destination"); + seen.add(cursor.id); + const incoming = all2.filter( + (e) => e.type === "arrow" && e.customData?.isBranch && e.endBinding?.elementId === cursor.id + ); + if (incoming.length > 1) throw new Error("multiple destination parents"); + cursor = incoming.length ? all2.find((e) => e.id === incoming[0].startBinding?.elementId) : null; + } + } + const container = view.contentEl.querySelector(".excalidraw"); + const canvas = container?.querySelector("canvas.excalidraw__canvas.interactive") ?? container?.querySelector("canvas"); + if (!container || !canvas) throw new Error("canvas unavailable"); + const rect = canvas.getBoundingClientRect(); + let point = null; + for (const [rx, ry] of [ + [0.5, 0.5], + [0.75, 0.5], + [0.25, 0.5], + [0.5, 0.75] + ]) { + const x = rect.left + rect.width * rx, y = rect.top + rect.height * ry; + if (view.ownerDocument.elementFromPoint(x, y) === canvas) { + point = { x, y }; + break; + } + } + if (!point) throw new Error("canvas obscured"); + ctx.linkSuggester?.close(); + container.focus({ preventScroll: true }); + container.dispatchEvent( + new win.PointerEvent("pointermove", { + bubbles: true, + clientX: point.x, + clientY: point.y, + pointerType: "mouse" + }) + ); + const data = new win.DataTransfer(); + data.setData("text/plain", JSON.stringify(transport)); + const event = new win.ClipboardEvent("paste", { + clipboardData: data, + bubbles: true, + cancelable: true + }); + pasted = await new Promise((resolve, reject) => { + let unsubscribe = () => { + }; + let timer; + let settled = false; + const finish = (elements, error) => { + if (settled) return; + settled = true; + unsubscribe(); + win.clearTimeout(timer); + if (error) reject(error); + else resolve(elements); + }; + op.cancel = () => { + op.cancelled = true; + finish([], new Error("paste cancelled")); + }; + unsubscribe = api.onChange((elements) => { + if (!alive()) { + op.cancel(); + return; + } + const inserted = elements.filter((e) => !e.isDeleted && e.customData?.[marker]); + if (inserted.length === transport.elements.length) finish(inserted); + }); + timer = win.setTimeout(() => finish([], new Error("native paste timeout")), 5e3); + try { + container.dispatchEvent(event); + } catch (error) { + finish([], error); + } + }); + op.cancel = () => { + op.cancelled = true; + }; + if (!alive()) throw new Error("drawing changed"); + const idMap = op.idMap = new Map(pasted.map((e) => [e.customData[marker], e.id])); + if (idMap.size !== transport.elements.length) throw new Error("ambiguous pasted IDs"); + const all = ctx.ea.getViewElements(); + const destination = parent ? all.find((e) => e.id === parent.id && !e.isDeleted) : null; + if (parent && !destination) throw new Error("destination removed"); + ctx.ea.clear(); + ctx.ea.copyViewElementsToEAforEditing(pasted); + for (const e of pasted) { + const source = sources.get(e.customData[marker]); + ctx.ea.getElement(e.id).customData = remapBranchMetadata(e, source, idMap, marker); + } + const roots = analysis.rootIds.map((id) => ctx.ea.getElement(idMap.get(id))); + if (destination) { + ctx.ea.copyViewElementsToEAforEditing([destination]); + const editedParent = ctx.ea.getElement(destination.id); + const settingsRoot = ctx.getSettingsRootNode(destination, all); + const cfg = ctx.getRootConfigForNode(settingsRoot); + const depth = ctx.getDepthFromAncestor(destination.id, settingsRoot.id, all) + 1; + const siblings = ctx.getChildrenNodes(destination.id, all); + let order = Math.max(0, ...siblings.map(ctx.getMindmapOrder)) + 1; + if (editedParent.customData?.isFolded) { + ctx.ea.addAppendUpdateCustomData(destination.id, { isFolded: false }); + } + for (const root of roots) { + if (root.customData?.growthMode) root.customData.isAdditionalRoot = true; + root.customData = { ...root.customData, mindmapOrder: order++ }; + ctx.ea.style.strokeColor = root.strokeColor && root.strokeColor !== "transparent" ? root.strokeColor : destination.strokeColor; + ctx.ea.style.strokeWidth = ctx.calculateStrokeWidth( + depth, + cfg.baseStrokeWidth, + cfg.branchScale + ); + ctx.ea.style.strokeStyle = cfg.isSolidArrow ? "solid" : ctx.getAppState().currentItemStrokeStyle; + ctx.ea.style.roughness = destination.roughness; + const arrowId = ctx.ea.addArrow( + [ + [destination.x + destination.width / 2, destination.y + destination.height / 2], + [root.x + root.width / 2, root.y + root.height / 2] + ], + { + startObjectId: destination.id, + endObjectId: root.id, + startArrowHead: null, + endArrowHead: null + } + ); + const arrow = ctx.ea.getElement(arrowId); + arrow.customData = { ...arrow.customData, isBranch: true }; + for (const node of [editedParent, root]) { + node.boundElements = [ + ...(node.boundElements || []).filter((b) => b.id !== arrowId), + { id: arrowId, type: "arrow" } + ]; + } + const vertical = ["Up-facing", "Down-facing", "Up-Down"].includes(cfg.growthMode); + const radial = cfg.growthMode === "Radial" && destination.id === settingsRoot.id; + const right = root.x + root.width / 2 >= destination.x + destination.width / 2; + const below = root.y + root.height / 2 >= destination.y + destination.height / 2; + ctx.withRootLayoutContext( + settingsRoot, + () => ctx.configureArrow({ + arrowId, + startId: destination.id, + endId: root.id, + isChildRight: root.x + root.width / 2 >= destination.x + destination.width / 2, + isChildBelow: root.y + root.height / 2 >= destination.y + destination.height / 2, + layoutDirection: vertical ? "vertical" : "horizontal", + isRadial: radial, + coordinates: { + sX: vertical || radial ? destination.x + destination.width / 2 : destination.x + (right ? destination.width : 0), + sY: vertical ? destination.y + (below ? destination.height : 0) : destination.y + destination.height / 2, + eX: vertical ? root.x + root.width / 2 : root.x + (right ? 0 : root.width), + eY: vertical ? root.y + (below ? 0 : root.height) : root.y + root.height / 2 + } + }) + ); + } + } else { + for (const root of roots) { + if (!root.customData?.growthMode) ctx.initializeRootCustomData(root.id); + } + } + ctx.currentTransactionAccumulator = 0; + ctx.lastCommittedTransaction = null; + ctx.redoAvailable = null; + await ctx.addElementsToView({ captureUpdate: "IMMEDIATELY" }); + if (!alive()) return true; + if (destination) { + ctx.selectNodeInView(destination); + const elements = ctx.ea.getViewElements(); + if (destination.customData?.isFolded) { + const pastedIds = new Set(pasted.map((e) => e.id)); + ctx.ea.copyViewElementsToEAforEditing( + ctx.getMindmapProjectElements(ctx.getHierarchy(destination, elements).rootId, elements).filter((e) => !pastedIds.has(e.id)) + ); + ctx.updateBranchVisibility( + destination.id, + false, + ctx.ea.getElements(), + true, + ctx.getHierarchy(destination, elements).rootId + ); + await ctx.addElementsToView({ captureUpdate: "EVENTUALLY" }); + } + if (alive() && !ctx.getRootConfigForNode(ctx.getSettingsRootNode(destination, elements)).autoLayoutDisabled) + await ctx.triggerGlobalLayout( + ctx.getHierarchy(destination, elements).rootId, + false, + true + ); + } else { + ctx.selectNodeInView(roots[0]); + } + new ctx.Notice(ctx.t("NOTICE_PASTE_COMPLETE")); + ctx.currentTransactionAccumulator = 0; + ctx.lastCommittedTransaction = { + steps: 0, + branchPasteIds: roots.map((root) => root.id), + version: ExcalidrawLib.getSceneVersion(api.getSceneElements()) + }; + ctx.redoAvailable = null; + } catch (error) { + if (!op.cancelled && ctx.ea.targetView === view) { + console.error("Mindmap Builder branch paste:", error); + new ctx.Notice(ctx.t("NOTICE_BRANCH_PASTE_FAILED")); + } + } finally { + gestureDocuments.forEach( + (doc) => doc.removeEventListener?.("pointerdown", cancelBranchPaste, true) + ); + op.transportActive = false; + op.cancel = () => { + }; + metadata.repair(api); + if (pending === op) pending = null; + if (!op.cancelled && ctx.ea.targetView === view && ctx.api() === api && ctx.ea.sidepanelTab && !api.isDestroyed) { + ctx.ea.clear(); + ctx.focusInputEl(); + } + } + return true; + }; + return { + pasteBranch, + cancelBranchPaste, + disposeBranchPaste, + isBranchPasteBusy, + watchPasteMetadata + }; + } + + // src/scripts/mindmap-builder/markdownImport.js + function createMarkdownImport(runtimeContext) { + const { + pasteBranch, + cancelBranchPaste, + disposeBranchPaste, + isBranchPasteBusy, + watchPasteMetadata + } = createBranchPaste(runtimeContext); + const importOutline = async () => { + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_SELECT_NODE_CONTAINING_LINK")); + return; + } + const allElements = runtimeContext.ea.getViewElements(); + const nodeText = runtimeContext.getTextFromNode(allElements, sel, true, false); + const markdownFile = runtimeContext.getNodeMarkdownFile(nodeText); + if (!markdownFile) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_NO_LINKED_FILE")); + return; + } + const cache = await app.metadataCache.blockCache.getForFile( + { + isCancelled: () => false + }, + markdownFile + ); + if (!cache || !cache.blocks) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_NO_HEADINGS")); + return; + } + const shortFilePath = app.metadataCache.fileToLinktext( + markdownFile, + runtimeContext.ea.targetView.file.path, + true + ); + const outlines = []; + for (const block of cache.blocks) { + if (block.node.type === "heading") { + const depth = block.node.depth; + const rawHeadingText = block.display.replace(/^#+\s+/, ""); + if (rawHeadingText === "Excalidraw Data") break; + const alias = rawHeadingText.replace(/\|/g, " "); + const anchor = rawHeadingText.replace(/[|#\\:]/g, " "); + const indent = " ".repeat(Math.max(0, depth - 1)); + outlines.push(`${indent}- [[${shortFilePath}#${anchor}|${alias}]]`); + } + } + if (outlines.length === 0) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_NO_HEADINGS")); + return; + } + await importTextToMap(outlines.join("\n")); + }; + const importTextToMap = async (rawText) => { + if (!runtimeContext.isViewSet()) return; + if (!rawText) return; + let sel = runtimeContext.getMindmapNodeFromSelection(); + let currentParent; + const lines = rawText.split(/\r\n|\n|\r/).filter((l) => { + const trimmed = l.trim(); + return trimmed !== "" && !/^-{3,}$/.test(trimmed); + }); + if (lines.length === 0) return; + const boundaryRegex = /\s#boundary\b/; + const blockRefRegex = /\s\^([a-zA-Z0-9]{8})$/; + const crossLinkRegex = /(?:\(([^):]+)::\s*)?\[\[#\^([a-zA-Z0-9]{8})\|\*\]\](?:\))?/g; + const ontologyRegex = /^(.+?)::\s*(.*)$/; + const submapRefRegex = /^!\[\[#([^\]]+)\]\]$/; + if (lines.length === 1) { + let text = lines[0]; + const listMatch = text.match(/^(\s*)(?:-|\*|\d+\.)\s+(.*)$/); + if (listMatch) { + text = listMatch[2].trim(); + if (/^\[[ xX]\] /.test(text)) { + text = "- " + text; + } + } else { + text = text.trim(); + } + text = text.replace(boundaryRegex, ""); + text = text.replace(blockRefRegex, ""); + const ontologyMatch = text.match(ontologyRegex); + let ontology = null; + if (ontologyMatch) { + ontology = ontologyMatch[1].trim(); + text = ontologyMatch[2].trim(); + } + let isSubmapRef = false; + const submapRefMatch = text.match(submapRefRegex); + if (submapRefMatch) { + isSubmapRef = true; + text = submapRefMatch[1].trim(); + } + if (text) { + currentParent = await runtimeContext.addNode( + text.trim(), + true, + false, + null, + null, + null, + ontology + ); + if (isSubmapRef) { + runtimeContext.ea.addAppendUpdateCustomData(currentParent.id, { + isAdditionalRoot: true + }); + } + if (sel) { + runtimeContext.selectNodeInView(sel); + } + return; + } + } + let parsed = []; + let rootTextFromHeader = null; + const isHeader = (l) => l.match(/^#+\s/); + const isListItem = (l) => l.match(/^(\s*)(?:-|\*|\d+\.)\s+(.*)$/); + if (!isHeader(lines[0]) && !isListItem(lines[0])) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_PASTE_ABORTED")); + return; + } + const delta = isHeader(lines[0]) ? 1 : 0; + const notice = new runtimeContext.Notice(runtimeContext.t("NOTICE_PASTE_START"), 0); + await sleep(10); + const blockRefToNodeId = /* @__PURE__ */ new Map(); + const nodeToOutgoingRefs = /* @__PURE__ */ new Map(); + lines.forEach((line, index) => { + let text = ""; + let indent = 0; + let isSubmapDef = false; + if (isHeader(line)) { + if (index === 0) { + indent = 0; + text = line.replace(/^#+\s/, "").trim(); + } else { + isSubmapDef = true; + text = line.replace(/^#+\s/, "").trim(); + indent = -1; + } + } else { + const match = isListItem(line); + if (match) { + indent = delta + match[1].length; + let extractedText = match[2].trim(); + if (/^\[[ xX]\] /.test(extractedText)) { + extractedText = "- " + extractedText; + } + text = extractedText; + } else if (parsed.length > 0) { + parsed[parsed.length - 1].text += "\n" + line.trim(); + return; + } + } + if (text || isSubmapDef) { + const hasBoundary = boundaryRegex.test(text); + text = text.replace(boundaryRegex, ""); + const refMatch = text.match(blockRefRegex); + let blockRef = null; + if (refMatch) { + blockRef = refMatch[1]; + text = text.replace(blockRefRegex, ""); + } + const outgoingRefs = []; + crossLinkRegex.lastIndex = 0; + text = text.replace(crossLinkRegex, (_match, label, ref) => { + outgoingRefs.push({ + ref, + label: label ? label.trim() : null + }); + return ""; + }); + const ontologyMatch = text.match(ontologyRegex); + let ontology = null; + if (ontologyMatch) { + ontology = ontologyMatch[1].trim(); + text = ontologyMatch[2].trim(); + } + let isSubmapRef = false; + text = text.trim(); + const submapRefMatch = text.match(submapRefRegex); + if (submapRefMatch) { + isSubmapRef = true; + text = submapRefMatch[1].trim(); + } + parsed.push({ + indent, + text, + hasBoundary, + blockRef, + outgoingRefs, + ontology, + isSubmapDef, + isSubmapRef + }); + } + }); + if (parsed.length === 0 && !rootTextFromHeader) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_NO_LIST")); + return; + } + runtimeContext.ea.clear(); + const rootSelected = !!sel; + const createdBoundaries = []; + const createImportBoundary = (nodeId) => { + const node = runtimeContext.ea.getElement(nodeId); + if (!node) return; + const id = runtimeContext.ea.generateElementId(); + const st = runtimeContext.getAppState(); + const boundaryEl = { + id, + type: "line", + x: node.x, + y: node.y, + width: 1, + height: 1, + angle: 0, + roughness: st.currentItemRoughness, + strokeColor: node.strokeColor, + backgroundColor: node.strokeColor, + fillStyle: "solid", + strokeWidth: 2, + strokeStyle: "solid", + opacity: 30, + points: [ + [0, 0], + [1, 1], + [0, 0] + ], + polygon: true, + locked: false, + groupIds: node.groupIds || [], + customData: { + isBoundary: true + }, + roundness: runtimeContext.arrowType === "curved" ? { + type: 2 + } : null + }; + runtimeContext.ea.elementsDict[id] = boundaryEl; + runtimeContext.ea.addAppendUpdateCustomData(nodeId, { + boundaryId: id + }); + createdBoundaries.push({ + nodeId, + boundaryId: id + }); + }; + const submapNodesByName = /* @__PURE__ */ new Map(); + if (!sel) { + const nonSubmapItems = parsed.filter((p) => !p.isSubmapDef); + const minIndent = Math.min(...nonSubmapItems.map((p) => p.indent)); + const topLevelItems = nonSubmapItems.filter((p) => p.indent === minIndent); + const processRootMeta = (item, id) => { + if (item.blockRef) blockRefToNodeId.set(item.blockRef, id); + if (item.outgoingRefs.length > 0) nodeToOutgoingRefs.set(id, item.outgoingRefs); + if (item.hasBoundary) createImportBoundary(id); + if (item.isSubmapRef) { + runtimeContext.ea.addAppendUpdateCustomData(id, { + isAdditionalRoot: true + }); + submapNodesByName.set(item.text, runtimeContext.ea.getElement(id)); + } + }; + if (topLevelItems.length === 1) { + const rootItem = topLevelItems[0]; + const rootIndex = parsed.indexOf(rootItem); + sel = currentParent = await runtimeContext.addNode( + rootItem.text, + true, + true, + [], + null, + null, + rootItem.ontology + ); + processRootMeta(rootItem, currentParent.id); + if (rootIndex !== -1) { + parsed.splice(rootIndex, 1); + } + } else { + sel = currentParent = await runtimeContext.addNode( + runtimeContext.t("INPUT_TITLE_PASTE_ROOT"), + true, + true, + [], + null + ); + } + } else { + currentParent = sel; + runtimeContext.ea.copyViewElementsToEAforEditing([sel]); + currentParent = runtimeContext.ea.getElement(sel.id); + } + const stack = [ + { + indent: -1, + node: currentParent + } + ]; + if (rootSelected) { + const allViewElements = runtimeContext.ea.getViewElements(); + const info = runtimeContext.getHierarchy(sel, allViewElements); + const projectElements = runtimeContext.getMindmapProjectElements( + info.rootId, + allViewElements + ); + runtimeContext.ea.copyViewElementsToEAforEditing( + projectElements.filter((el) => !runtimeContext.ea.getElement(el.id)) + ); + } + for (const item of parsed) { + if (item.isSubmapDef) { + const targetNode = submapNodesByName.get(item.text); + if (targetNode) { + stack.length = 0; + stack.push({ + indent: -1, + node: targetNode + }); + } else { + const currentAllElements2 = runtimeContext.ea.getElements(); + const newNode2 = await runtimeContext.addNode( + item.text, + false, + true, + currentAllElements2, + currentParent, + null, + null + ); + runtimeContext.ea.addAppendUpdateCustomData(newNode2.id, { + isAdditionalRoot: true + }); + submapNodesByName.set(item.text, newNode2); + stack.length = 0; + stack.push({ + indent: -1, + node: newNode2 + }); + } + continue; + } + while (stack.length > 1 && item.indent <= stack[stack.length - 1].indent) { + stack.pop(); + } + const parentNode = stack[stack.length - 1].node; + const currentAllElements = runtimeContext.ea.getElements(); + const newNode = await runtimeContext.addNode( + item.text, + false, + true, + currentAllElements, + parentNode, + null, + item.ontology + ); + if (item.blockRef) blockRefToNodeId.set(item.blockRef, newNode.id); + if (item.outgoingRefs.length > 0) nodeToOutgoingRefs.set(newNode.id, item.outgoingRefs); + if (item.hasBoundary) createImportBoundary(newNode.id); + if (item.isSubmapRef) { + runtimeContext.ea.addAppendUpdateCustomData(newNode.id, { + isAdditionalRoot: true + }); + submapNodesByName.set(item.text, newNode); + } + stack.push({ + indent: item.indent, + node: newNode + }); + } + nodeToOutgoingRefs.forEach((targetRefs, sourceId) => { + targetRefs.forEach((targetObj) => { + const { ref, label } = targetObj; + const targetId = blockRefToNodeId.get(ref); + if (targetId) { + const arrowId = runtimeContext.ea.connectObjects(sourceId, null, targetId, null, { + startArrowHead: null, + endArrowHead: "triangle" + }); + const arrowEl = runtimeContext.ea.getElement(arrowId); + if (arrowEl) { + arrowEl.strokeStyle = "dashed"; + runtimeContext.addUpdateArrowLabel(arrowEl, label); + } + } + }); + }); + const rootIdForImport = sel ? runtimeContext.getHierarchy(sel, runtimeContext.ea.getElements()).rootId : currentParent.id; + const rootElForImport = sel ? runtimeContext.ea.getElement(rootIdForImport) : currentParent; + if (rootElForImport) { + const mode = rootElForImport.customData?.growthMode || runtimeContext.currentModalGrowthMode; + if (mode === "Right-Left" && currentParent.id === rootIdForImport) { + const eaElements = runtimeContext.ea.getElements(); + const importedL1Nodes = eaElements.filter( + (el) => el.customData?.mindmapNew && eaElements.some( + (arrow) => arrow.type === "arrow" && arrow.customData?.isBranch && arrow.startBinding?.elementId === currentParent.id && arrow.endBinding?.elementId === el.id + ) + ); + importedL1Nodes.sort( + (a, b) => (a.customData?.mindmapOrder || 0) - (b.customData?.mindmapOrder || 0) + ); + if (importedL1Nodes.length > 0) { + const splitIndex = Math.ceil(importedL1Nodes.length / 2); + importedL1Nodes.forEach((node, i) => { + runtimeContext.ea.addAppendUpdateCustomData(node.id, { + mindmapNew: void 0 + }); + if (i < splitIndex) { + node.x = rootElForImport.x + rootElForImport.width + 100; + } else { + node.x = rootElForImport.x - node.width - 100; + } + }); + } + } + } + await runtimeContext.addElementsToView({ + repositionToCursor: !rootSelected, + captureUpdate: "EVENTUALLY" + }); + if (createdBoundaries.length > 0) { + const allEls = runtimeContext.ea.getViewElements(); + const boundariesWithDepth = createdBoundaries.map((b) => { + const node = allEls.find((e) => e.id === b.nodeId); + const depth = node ? runtimeContext.getHierarchy(node, allEls).depth : 0; + return { + ...b, + depth + }; + }); + boundariesWithDepth.sort((a, b) => a.depth - b.depth); + for (const b of boundariesWithDepth) { + const currentEls = runtimeContext.ea.getViewElements(); + let parentBoundaryIndex = -1; + let curr = currentEls.find((e) => e.id === b.nodeId); + while (curr) { + const parent = runtimeContext.getParentNode(curr.id, currentEls); + if (!parent) break; + if (parent.customData?.boundaryId) { + const pIndex = currentEls.findIndex((el) => el.id === parent.customData.boundaryId); + if (pIndex !== -1) { + parentBoundaryIndex = pIndex; + break; + } + } + curr = parent; + } + const targetIndex = parentBoundaryIndex !== -1 ? parentBoundaryIndex + 1 : 0; + runtimeContext.ea.moveViewElementToZIndex(b.boundaryId, targetIndex); + } + } + const allInView = runtimeContext.ea.getViewElements(); + const targetToSelect = sel ? allInView.find((e) => e.id === sel.id) : allInView.find((e) => e.id === currentParent?.id); + if (targetToSelect) { + runtimeContext.selectNodeInView(targetToSelect); + } + const rootId = sel ? runtimeContext.getHierarchy(sel, allInView).rootId : currentParent.id; + await runtimeContext.triggerGlobalLayout(rootId); + notice.setMessage(runtimeContext.t("NOTICE_PASTE_COMPLETE")); + notice.setAutoHide(4e3); + }; + const pasteListToMap = async (contentToPaste = null) => { + const rawText = contentToPaste || await navigator.clipboard.readText(); + if (!rawText) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_CLIPBOARD_EMPTY")); + return; + } + await importTextToMap(rawText); + }; + const pasteElementToMap = async () => { + if (!runtimeContext.isViewSet()) return; + if (isBranchPasteBusy()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + let rawText = ""; + try { + rawText = await navigator.clipboard.readText(); + } catch (e) { + } + const clipboardPayload = parseBranchClipboard(rawText); + if (clipboardPayload && await pasteBranch(clipboardPayload, sel)) return; + if (!sel) { + await pasteListToMap(rawText); + return; + } + const excalidrawClipboardPayload = !!clipboardPayload; + if (excalidrawClipboardPayload) { + const clipboardData = clipboardPayload; + if (clipboardData && clipboardData.elements) { + const els = clipboardData.elements.filter((e) => !e.isDeleted); + const isSingleElement = els.length === 1 && ["embeddable", "text"].includes(els[0].type); + const textEl = els.find((e) => e.type === "text"); + const containerEl = els.find((e) => ["rectangle", "ellipse", "diamond"].includes(e.type)); + const isContainerText = els.length === 2 && textEl && containerEl && textEl.containerId === containerEl.id; + const isSingleImageJSON = els.length === 1 && els[0].type === "image"; + if (isSingleImageJSON) { + const fileId = els[0].fileId; + const imagePathResolved = runtimeContext.ea.getPathForImageFileId(fileId); + if (imagePathResolved) { + if (app.vault.getFileByPath(imagePathResolved)) { + await pasteListToMap(`![[${imagePathResolved}]]`); + } else { + await pasteListToMap(`![pasted image](${imagePathResolved})`); + } + return; + } + } else if (isSingleElement || isContainerText) { + let textToPaste = ""; + let shapeToPaste = null; + if (isContainerText) { + textToPaste = textEl.rawText; + shapeToPaste = containerEl.type; + } else if (els[0].type === "text") { + textToPaste = els[0].rawText; + } else if (els[0].type === "embeddable") { + const link = els[0].link; + if (link.match(/^https?:\/\//i)) { + textToPaste = `![](${link})`; + } else { + textToPaste = link.startsWith("[[") ? `!${link}` : `![[${link}]]`; + } + if (textToPaste) { + pasteListToMap(textToPaste); + return; + } + } + if (textToPaste) { + const newNode = await runtimeContext.addNode( + textToPaste, + false, + false, + null, + null, + null, + null + ); + if (newNode && textEl && textEl.link) { + const freshNode = runtimeContext.ea.getViewElements().find((el) => el.id === newNode.id); + if (freshNode) { + runtimeContext.ea.copyViewElementsToEAforEditing([freshNode]); + runtimeContext.ea.getElement(freshNode.id).link = textEl.link; + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY" + }); + } + } + if (shapeToPaste) { + const isContainer = ["rectangle", "ellipse", "diamond"].includes(newNode.type); + if (isContainer) { + if (newNode.type !== shapeToPaste) { + runtimeContext.selectNodeInView(newNode); + await runtimeContext.toggleBox(); + await runtimeContext.toggleBox(shapeToPaste); + } + } else { + runtimeContext.selectNodeInView(newNode); + await runtimeContext.toggleBox(shapeToPaste); + } + } + return; + } + } + } + } + let hasImageBlob = false; + let blob = null; + let mimeType = null; + try { + const items = await navigator.clipboard.read(); + for (const item of items) { + const imageType = item.types.find((t) => t.startsWith("image/")); + if (imageType) { + hasImageBlob = true; + mimeType = imageType; + blob = await item.getType(imageType); + break; + } + } + } catch (e) { + } + if (hasImageBlob) { + const beforeIds = new Set(runtimeContext.ea.getViewElements().map((e) => e.id)); + const dt = new DataTransfer(); + if (hasImageBlob && blob) { + const file = new File([blob], `Pasted image.${mimeType.split("/")[1] || "png"}`, { + type: mimeType + }); + dt.items.add(file); + } + const pasteEvent = new ClipboardEvent("paste", { + clipboardData: dt, + bubbles: true, + cancelable: true + }); + const targetEl = runtimeContext.ea.targetView.contentEl.querySelector(".excalidraw") || runtimeContext.ea.targetView.contentEl; + const originallySelectedElement = runtimeContext.ea.getViewSelectedElement(); + targetEl.dispatchEvent(pasteEvent); + let newImageEl = null; + for (let i = 0; i < 40; i++) { + await sleep(50); + const currentElements = runtimeContext.ea.getViewElements(); + const added = currentElements.filter((e) => !beforeIds.has(e.id) && e.type === "image"); + if (added.length > 0) { + const tmpNewImageEl = added[added.length - 1]; + if (!tmpNewImageEl.fileId) continue; + const path = runtimeContext.ea.getPathForImageFileId(tmpNewImageEl.fileId); + if (!path) continue; + newImageEl = tmpNewImageEl; + break; + } + } + if (newImageEl) { + await sleep(200); + const imageID = newImageEl.id; + const imagePathResolved = runtimeContext.ea.getPathForImageFileId(newImageEl.fileId); + runtimeContext.ea.clear(); + runtimeContext.ea.copyViewElementsToEAforEditing([newImageEl]); + runtimeContext.ea.getElement(imageID).isDeleted = true; + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY", + shouldRestoreElements: false + }); + if (originallySelectedElement) { + runtimeContext.ea.selectElementsInView([originallySelectedElement.id]); + } + if (imagePathResolved) { + await pasteListToMap(`![pasted image](${imagePathResolved})`); + } + } + return; + } + if (!excalidrawClipboardPayload) { + await pasteListToMap(); + } else { + new runtimeContext.Notice(runtimeContext.t("NOTICE_PASTE_ABORTED")); + } + }; + return { + importOutline, + importTextToMap, + pasteListToMap, + pasteElementToMap, + cancelBranchPaste, + disposeBranchPaste, + isBranchPasteBusy, + watchPasteMetadata + }; + } + + // src/scripts/mindmap-builder/nodeOrder.js + function createNodeOrder(runtimeContext) { + const updateSubtreeFontSize = (nodeId, newDepth, oldDepth, allElements, newFontScaleType, oldFontScaleType) => { + const newFontScale = runtimeContext.getFontScale(newFontScaleType); + const oldFontScale = runtimeContext.getFontScale(oldFontScaleType); + const node = allElements.find((el) => el.id === nodeId); + if (!node) return; + if (!runtimeContext.ea.getElement(nodeId)) { + runtimeContext.ea.copyViewElementsToEAforEditing([node]); + } + const oldStandardSize = oldFontScale[Math.min(oldDepth, oldFontScale.length - 1)]; + const newStandardSize = newFontScale[Math.min(newDepth, newFontScale.length - 1)]; + if (node.fontSize === oldStandardSize) { + const eaNode = runtimeContext.ea.getElement(nodeId); + eaNode.fontSize = newStandardSize; + if (eaNode.type === "text" || eaNode.boundElements && eaNode.boundElements.some((b) => b.type === "text")) { + runtimeContext.ea.refreshTextElementSize(eaNode.id); + } + } + const incomingArrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === nodeId + ); + if (incomingArrow) { + const maybeTextElement = runtimeContext.ea.getBoundTextElement(incomingArrow, true); + let eaOntologyEl = maybeTextElement.eaElement; + if (!eaOntologyEl && maybeTextElement.sceneElement) { + runtimeContext.ea.copyViewElementsToEAforEditing([maybeTextElement.sceneElement]); + eaOntologyEl = runtimeContext.ea.getElement(maybeTextElement.sceneElement.id); + } + if (eaOntologyEl && eaOntologyEl.fontSize === Math.floor(oldStandardSize / 2)) { + eaOntologyEl.fontSize = Math.floor(newStandardSize / 2); + runtimeContext.ea.refreshTextElementSize(eaOntologyEl.id); + } + } + if (node.customData?.isAdditionalRoot === true) { + return; + } + const children = runtimeContext.getChildrenNodes(nodeId, allElements); + children.forEach((child) => { + updateSubtreeFontSize( + child.id, + newDepth + 1, + oldDepth + 1, + allElements, + newFontScaleType, + oldFontScaleType + ); + }); + }; + const updateSubtreeStrokeWidth = (nodeId, newDepth, oldDepth, allElements, newBaseWidth, newBranchScale, oldBaseWidth, oldBranchScale) => { + const node = allElements.find((el) => el.id === nodeId); + if (!node) return; + if (!runtimeContext.ea.getElement(nodeId)) { + runtimeContext.ea.copyViewElementsToEAforEditing([node]); + } + const oldStandardWidth = runtimeContext.calculateStrokeWidth( + oldDepth, + oldBaseWidth, + oldBranchScale + ); + const newStandardWidth = runtimeContext.calculateStrokeWidth( + newDepth, + newBaseWidth, + newBranchScale + ); + const tolerance = 0.05; + const incomingArrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === nodeId + ); + if (incomingArrow) { + if (!runtimeContext.ea.getElement(incomingArrow.id)) + runtimeContext.ea.copyViewElementsToEAforEditing([incomingArrow]); + const eaArrow = runtimeContext.ea.getElement(incomingArrow.id); + if (Math.abs(eaArrow.strokeWidth - oldStandardWidth) < tolerance) { + eaArrow.strokeWidth = newStandardWidth; + } + } + if (node.type !== "text" && Math.abs(node.strokeWidth - oldStandardWidth) < tolerance) { + const eaNode = runtimeContext.ea.getElement(nodeId); + eaNode.strokeWidth = newStandardWidth; + } + if (node.customData?.isAdditionalRoot === true) { + return; + } + const children = runtimeContext.getChildrenNodes(nodeId, allElements); + children.forEach((child) => { + updateSubtreeStrokeWidth( + child.id, + newDepth + 1, + oldDepth + 1, + allElements, + newBaseWidth, + newBranchScale, + oldBaseWidth, + oldBranchScale + ); + }); + }; + const updateSubtreeColor = (nodeId, oldColor, newColor, allElements) => { + const node = allElements.find((el) => el.id === nodeId); + if (!node) return; + if (node.strokeColor !== oldColor) return; + if (!runtimeContext.ea.getElement(nodeId)) + runtimeContext.ea.copyViewElementsToEAforEditing([node]); + const eaNode = runtimeContext.ea.getElement(nodeId); + eaNode.strokeColor = newColor; + if (node.customData?.boundaryId) { + const boundaryEl = allElements.find((e) => e.id === node.customData.boundaryId); + if (boundaryEl) { + if (!runtimeContext.ea.getElement(boundaryEl.id)) + runtimeContext.ea.copyViewElementsToEAforEditing([boundaryEl]); + const eaBoundary = runtimeContext.ea.getElement(boundaryEl.id); + eaBoundary.strokeColor = newColor; + eaBoundary.backgroundColor = newColor; + } + } + const incomingArrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === nodeId + ); + if (incomingArrow && incomingArrow.strokeColor === oldColor) { + if (!runtimeContext.ea.getElement(incomingArrow.id)) + runtimeContext.ea.copyViewElementsToEAforEditing([incomingArrow]); + const eaArrow = runtimeContext.ea.getElement(incomingArrow.id); + eaArrow.strokeColor = newColor; + const maybeTextElement = runtimeContext.ea.getBoundTextElement(incomingArrow, true); + let eaOntologyEl = maybeTextElement.eaElement; + if (!eaOntologyEl && maybeTextElement.sceneElement) { + runtimeContext.ea.copyViewElementsToEAforEditing([maybeTextElement.sceneElement]); + eaOntologyEl = runtimeContext.ea.getElement(maybeTextElement.sceneElement.id); + } + if (eaOntologyEl) { + eaOntologyEl.strokeColor = newColor; + } + } + const children = runtimeContext.getChildrenNodes(nodeId, allElements); + children.forEach((child) => { + updateSubtreeColor(child.id, oldColor, newColor, allElements); + }); + }; + const toggleSubmapRoot = async () => { + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + const allElements = runtimeContext.ea.getViewElements(); + const parent = runtimeContext.getParentNode(sel.id, allElements); + if (!parent) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_CANNOT_CHANGE_MASTER_ROOT")); + return; + } + const isAdditionalRoot = sel.customData?.isAdditionalRoot === true; + runtimeContext.ea.copyViewElementsToEAforEditing([sel]); + if (isAdditionalRoot) { + const ok = await runtimeContext.utils.suggester( + ["Yes", "No"], + [true, false], + runtimeContext.t("CONFIRM_REMOVE_SUBMAP_ROOT") + ); + if (!ok) { + return; + } + const clearData = {}; + runtimeContext.MAP_ROOT_CUSTOMDATA_KEYS.forEach((key) => { + clearData[key] = void 0; + }); + clearData.presetName = void 0; + runtimeContext.ea.addAppendUpdateCustomData(sel.id, clearData); + } else { + const sourceRoot = runtimeContext.getSettingsRootNode(parent, allElements) || parent; + const sourceCfg = runtimeContext.getRootConfigForNode(sourceRoot); + const inferredMode = runtimeContext.inferDirectionalGrowthMode( + sel, + parent, + sourceRoot, + sourceCfg.growthMode + ); + runtimeContext.ea.addAppendUpdateCustomData(sel.id, { + isAdditionalRoot: true, + presetName: sourceRoot.customData?.presetName || runtimeContext.activePresetName, + growthMode: inferredMode, + autoLayoutDisabled: sourceCfg.autoLayoutDisabled, + arrowType: sourceCfg.arrowType, + fontsizeScale: sourceCfg.fontsizeScale, + multicolor: sourceCfg.multicolor, + boxChildren: sourceCfg.boxChildren, + roundedCorners: sourceCfg.roundedCorners, + maxWrapWidth: sourceCfg.maxWrapWidth, + isSolidArrow: sourceCfg.isSolidArrow, + centerText: sourceCfg.centerText, + fillSweep: sourceCfg.fillSweep, + branchScale: sourceCfg.branchScale, + baseStrokeWidth: sourceCfg.baseStrokeWidth, + layoutSettings: JSON.parse(JSON.stringify(sourceCfg.layoutSettings)) + }); + } + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY" + }); + const info = runtimeContext.getHierarchy(sel, runtimeContext.ea.getViewElements()); + await runtimeContext.triggerGlobalLayout(info.rootId); + new runtimeContext.Notice( + runtimeContext.t( + isAdditionalRoot ? "NOTICE_SUBMAP_ROOT_REMOVED" : "NOTICE_SUBMAP_ROOT_ADDED" + ) + ); + runtimeContext.updateUI(); + }; + const changeNodeOrder = async (key) => { + if (!runtimeContext.isViewSet()) return; + const allElements = runtimeContext.ea.getViewElements(); + const current = runtimeContext.getMindmapNodeFromSelection(); + if (!current) return; + const parent = runtimeContext.getParentNode(current.id, allElements); + if (!parent) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_CANNOT_MOVE_ROOT")); + return; + } + const info = runtimeContext.getHierarchy(current, allElements); + const currentSettingsRoot = runtimeContext.getSettingsRootNode(current, allElements); + const root = current.customData?.isAdditionalRoot === true ? runtimeContext.getSettingsRootNode(parent, allElements) || currentSettingsRoot || allElements.find((e) => e.id === info.rootId) : currentSettingsRoot || allElements.find((e) => e.id === info.rootId); + if (!root) return; + if (current.id === root.id) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_CANNOT_MOVE_ROOT")); + return; + } + if (root.customData?.autoLayoutDisabled) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_CANNOT_MOVE_AUTO_LAYOUT_DISABLED")); + return; + } + if (current.customData?.isPinned) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_CANNOT_MOVE_PINNED")); + return; + } + const rootCenter = root.x + root.width / 2; + const curCenter = current.x + current.width / 2; + const rootCenterY = root.y + root.height / 2; + const curCenterY = current.y + current.height / 2; + const mapMode = root.customData?.growthMode || runtimeContext.currentModalGrowthMode; + const isVerticalMode = ["Up-facing", "Down-facing", "Up-Down"].includes(mapMode); + const isRadial = mapMode === "Radial"; + const isInPositive = isVerticalMode ? curCenterY > rootCenterY : curCenter > rootCenter; + const oldSettingsRoot = runtimeContext.getSettingsRootNode(parent, allElements) || allElements.find((e) => e.id === info.rootId); + const oldDepth = runtimeContext.getDepthFromAncestor( + current.id, + oldSettingsRoot.id, + allElements + ); + const oldRootCfg = runtimeContext.getRootConfigForNode(oldSettingsRoot); + if (parent.id === root.id && (!isVerticalMode && mapMode === "Right-Left" || isVerticalMode && mapMode === "Up-Down")) { + const movePos = isVerticalMode ? !isInPositive && key === "ArrowDown" : !isInPositive && key === "ArrowRight"; + const moveNeg = isVerticalMode ? isInPositive && key === "ArrowUp" : isInPositive && key === "ArrowLeft"; + if (movePos || moveNeg) { + const delta = isVerticalMode ? 2 * (rootCenterY - curCenterY) : 2 * (rootCenter - curCenter); + const branchIds = runtimeContext.getBranchElementIds(current.id, allElements); + const decorationAndCrossLinkIds = runtimeContext.getDecorationAndCrossLinkIdsForBranches( + branchIds, + allElements, + info.rootId + ); + const elementsToMove = /* @__PURE__ */ new Set(); + branchIds.forEach((id) => { + const el = allElements.find((x) => x.id === id); + if (el) elementsToMove.add(el); + }); + decorationAndCrossLinkIds.forEach((id) => { + const el = allElements.find((x) => x.id === id); + if (el) elementsToMove.add(el); + }); + const arr = Array.from(elementsToMove); + runtimeContext.ea.copyViewElementsToEAforEditing(arr); + arr.forEach((el) => { + const eaEl = runtimeContext.ea.getElement(el.id); + if (isVerticalMode) eaEl.y += delta; + else eaEl.x += delta; + }); + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY" + }); + runtimeContext.triggerGlobalLayout(root.id, false, false); + return; + } + } + const isPromote = isVerticalMode ? isInPositive && key === "ArrowUp" || !isInPositive && key === "ArrowDown" : isInPositive && key === "ArrowLeft" || !isInPositive && key === "ArrowRight"; + const isDemote = isVerticalMode ? isInPositive && key === "ArrowDown" || !isInPositive && key === "ArrowUp" : isInPositive && key === "ArrowRight" || !isInPositive && key === "ArrowLeft"; + if (isPromote) { + if (parent.id === root.id && root.customData?.isAdditionalRoot !== true) return; + const grandParent = runtimeContext.getParentNode(parent.id, allElements); + if (!grandParent) return; + const arrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === parent.id && a.endBinding?.elementId === current.id + ); + if (arrow) { + const newSettingsRoot = runtimeContext.getSettingsRootNode(grandParent, allElements) || allElements.find((e) => e.id === info.rootId); + const newRootCfg = runtimeContext.getRootConfigForNode(newSettingsRoot); + const newDepth = runtimeContext.getDepthFromAncestor(grandParent.id, newSettingsRoot.id, allElements) + 1; + runtimeContext.reconnectArrow(parent, grandParent, arrow, "start"); + const parentOrder = runtimeContext.getMindmapOrder(parent); + const promoteTargetRoot = parent.customData?.isAdditionalRoot === true ? newSettingsRoot : root; + runtimeContext.ea.copyViewElementsToEAforEditing([current]); + runtimeContext.ea.addAppendUpdateCustomData(current.id, { + mindmapOrder: isRadial && !isInPositive ? parentOrder - 0.5 : parentOrder + 0.5 + }); + updateSubtreeFontSize( + current.id, + newDepth, + oldDepth, + allElements, + newRootCfg.fontsizeScale, + oldRootCfg.fontsizeScale + ); + updateSubtreeStrokeWidth( + current.id, + newDepth, + oldDepth, + allElements, + newRootCfg.baseStrokeWidth, + newRootCfg.branchScale, + oldRootCfg.baseStrokeWidth, + oldRootCfg.branchScale + ); + const isTargetL1 = grandParent.id === promoteTargetRoot.id; + let targetColor; + if (isTargetL1) { + if (newRootCfg.multicolor) { + targetColor = current.customData?.previousL1Color; + if (!targetColor) { + const existingL1Colors = runtimeContext.getChildrenNodes(promoteTargetRoot.id, allElements).map((n) => n.strokeColor); + targetColor = runtimeContext.getDynamicColor(existingL1Colors); + } + } else { + targetColor = promoteTargetRoot.strokeColor; + } + } else { + targetColor = grandParent.strokeColor; + } + updateSubtreeColor(current.id, current.strokeColor, targetColor, allElements); + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY" + }); + runtimeContext.triggerGlobalLayout(promoteTargetRoot.id, false, true); + return; + } + } + if (isDemote) { + const siblings = runtimeContext.getChildrenNodes(parent.id, allElements); + siblings.sort( + (a, b) => runtimeContext.getMindmapOrder(a) - runtimeContext.getMindmapOrder(b) + ); + if (siblings.length < 2) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_CANNOT_DEMOTE_NO_SIBLING_TO_ACCEPT")); + return; + } + const currentIndex = siblings.findIndex((s) => s.id === current.id); + const mirrorBehavior = isRadial && !isInPositive; + let targetIndex = mirrorBehavior ? currentIndex + 1 : currentIndex - 1; + if (targetIndex < 0 || targetIndex >= siblings.length) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_CANNOT_DEMOTE_NO_VALID_SIBLING")); + return; + } + const newParent = siblings[targetIndex]; + if (parent.id === root.id) { + const targetIsPos = isVerticalMode ? newParent.y + newParent.height / 2 > rootCenterY : newParent.x + newParent.width / 2 > rootCenter; + if (targetIsPos !== isInPositive) { + new runtimeContext.Notice( + runtimeContext.t("NOTICE_CANNOT_DEMOTE_CROSS_SIDE_NOT_ALLOWED") + ); + return; + } + } + const arrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.startBinding?.elementId === parent.id && a.endBinding?.elementId === current.id + ); + if (arrow) { + const newSettingsRoot = runtimeContext.getSettingsRootNode(newParent, allElements) || allElements.find((e) => e.id === info.rootId); + const newRootCfg = runtimeContext.getRootConfigForNode(newSettingsRoot); + const newDepth = runtimeContext.getDepthFromAncestor(newParent.id, newSettingsRoot.id, allElements) + 1; + runtimeContext.reconnectArrow(parent, newParent, arrow, "start"); + const newParentChildren = runtimeContext.getChildrenNodes(newParent.id, allElements); + const nextOrder = newParentChildren.length > 0 ? Math.max(...newParentChildren.map(runtimeContext.getMindmapOrder)) + 1 : 0; + runtimeContext.ea.copyViewElementsToEAforEditing([current]); + if (parent.id === oldSettingsRoot.id) { + runtimeContext.ea.addAppendUpdateCustomData(current.id, { + mindmapOrder: nextOrder, + previousL1Color: current.strokeColor + }); + } else { + runtimeContext.ea.addAppendUpdateCustomData(current.id, { + mindmapOrder: nextOrder + }); + } + updateSubtreeFontSize( + current.id, + newDepth, + oldDepth, + allElements, + newRootCfg.fontsizeScale, + oldRootCfg.fontsizeScale + ); + updateSubtreeStrokeWidth( + current.id, + newDepth, + oldDepth, + allElements, + newRootCfg.baseStrokeWidth, + newRootCfg.branchScale, + oldRootCfg.baseStrokeWidth, + oldRootCfg.branchScale + ); + const isTargetL1 = newParent.id === newSettingsRoot.id; + let targetColor; + if (isTargetL1) { + if (newRootCfg.multicolor) { + const existingL1Colors = runtimeContext.getChildrenNodes(newSettingsRoot.id, allElements).map((n) => n.strokeColor); + targetColor = runtimeContext.getDynamicColor(existingL1Colors); + } else { + targetColor = newSettingsRoot.strokeColor; + } + } else { + targetColor = newParent.strokeColor; + } + updateSubtreeColor(current.id, current.strokeColor, targetColor, allElements); + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY" + }); + runtimeContext.triggerGlobalLayout(root.id, false, true); + } + return; + } + const isReorderPos = isVerticalMode ? key === "ArrowRight" : key === "ArrowDown"; + const isReorderNeg = isVerticalMode ? key === "ArrowLeft" : key === "ArrowUp"; + if (isReorderPos || isReorderNeg) { + const siblings = runtimeContext.getChildrenNodes(parent.id, allElements); + if (siblings.length < 2) return; + siblings.sort( + (a, b) => runtimeContext.getMindmapOrder(a) - runtimeContext.getMindmapOrder(b) + ); + const currentIndex = siblings.findIndex((s) => s.id === current.id); + if (currentIndex === -1) return; + let swapIndex = -1; + if (isVerticalMode) { + if (key === "ArrowRight") swapIndex = currentIndex + 1; + if (key === "ArrowLeft") swapIndex = currentIndex - 1; + } else { + if (isRadial && !isInPositive) { + if (key === "ArrowUp") swapIndex = currentIndex + 1; + if (key === "ArrowDown") swapIndex = currentIndex - 1; + } else { + if (key === "ArrowDown") swapIndex = currentIndex + 1; + if (key === "ArrowUp") swapIndex = currentIndex - 1; + } + } + if (isRadial && parent.id === root.id) { + swapIndex = (swapIndex + siblings.length) % siblings.length; + } + if (swapIndex >= 0 && swapIndex < siblings.length) { + const swapNode = siblings[swapIndex]; + if (parent.id === root.id && !isRadial) { + const swapIsPos = isVerticalMode ? swapNode.y + swapNode.height / 2 > rootCenterY : swapNode.x + swapNode.width / 2 > rootCenter; + if (swapIsPos !== isInPositive) { + return; + } + } + runtimeContext.ea.copyViewElementsToEAforEditing(siblings); + siblings.forEach((sib, idx) => { + let newOrder = idx; + if (idx === currentIndex) newOrder = swapIndex; + if (idx === swapIndex) newOrder = currentIndex; + runtimeContext.ea.addAppendUpdateCustomData(sib.id, { + mindmapOrder: newOrder + }); + }); + await runtimeContext.addElementsToView({ + captureUpdate: "EVENTUALLY" + }); + runtimeContext.triggerGlobalLayout(root.id, false, true); + } + } + }; + return { + updateSubtreeFontSize, + updateSubtreeStrokeWidth, + updateSubtreeColor, + toggleSubmapRoot, + changeNodeOrder + }; + } + + // src/scripts/mindmap-builder/nodeStyles.js + function createNodeStyles(runtimeContext) { + const togglePin = async () => { + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (sel) { + const boundTextElement = runtimeContext.ea.getBoundTextElement(sel, true)?.sceneElement; + const newPinnedState = !(sel.customData?.isPinned === true); + runtimeContext.ea.copyViewElementsToEAforEditing( + boundTextElement ? [sel, boundTextElement] : [sel] + ); + runtimeContext.ea.addAppendUpdateCustomData(sel.id, { + isPinned: newPinnedState + }); + if (boundTextElement && !newPinnedState && boundTextElement.customData?.hasOwnProperty("isPinned")) { + runtimeContext.ea.addAppendUpdateCustomData(boundTextElement.id, { + isPinned: void 0 + }); + } + await runtimeContext.addElementsToView({ + captureUpdate: runtimeContext.autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" + }); + if (!runtimeContext.autoLayoutDisabled) await runtimeContext.refreshMapLayout(); + runtimeContext.selectNodeInView(sel); + runtimeContext.updateUI(); + } + }; + const toggleCheckboxStatus = async () => { + if (!runtimeContext.isViewSet()) return; + let targetText = ""; + let isInputEl = false; + let textElId = null; + let sel = null; + if (runtimeContext.inputEl && runtimeContext.inputEl.value.trim() !== "") { + targetText = runtimeContext.inputEl.value; + isInputEl = true; + } else { + sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + const all = runtimeContext.ea.getViewElements(); + const info = runtimeContext.getHierarchy(sel, all); + if (info.rootId === sel.id) return; + textElId = sel.type === "text" ? sel.id : null; + if (!textElId && sel.boundElements) { + const boundText = sel.boundElements.find((be) => be.type === "text"); + if (boundText) textElId = boundText.id; + } + if (!textElId) return; + const textEl = all.find((el) => el.id === textElId); + if (!textEl) return; + targetText = textEl.rawText; + } + const taskRegex = /^- \[([ xX])\] (.*)/s; + const match = targetText.match(taskRegex); + let newText = ""; + if (match) { + const status = match[1]; + const content = match[2]; + if (status === " ") { + newText = `- [x] ${content}`; + } else { + newText = `${content}`; + } + } else { + newText = `- [ ] ${targetText}`; + } + if (isInputEl) { + runtimeContext.inputEl.value = newText; + runtimeContext.updateUI(); + } else { + const all = runtimeContext.ea.getViewElements(); + const textEl = all.find((el) => el.id === textElId); + runtimeContext.ea.copyViewElementsToEAforEditing([textEl]); + const eaEl = runtimeContext.ea.getElement(textEl.id); + eaEl.rawText = newText; + eaEl.text = newText; + eaEl.originalText = newText; + runtimeContext.ea.refreshTextElementSize(eaEl.id); + await runtimeContext.addElementsToView({ + captureUpdate: runtimeContext.autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" + }); + if (eaEl.containerId) { + const updatedContainer = runtimeContext.ea.getViewElements().find((el) => el.id === eaEl.containerId); + if (updatedContainer) runtimeContext.api().updateContainerSize([updatedContainer]); + } + if (!runtimeContext.autoLayoutDisabled) { + const info = runtimeContext.getHierarchy(sel, runtimeContext.ea.getViewElements()); + await runtimeContext.triggerGlobalLayout(info.rootId); + } + } + }; + const toggleEmbedStatus = async () => { + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + const all = runtimeContext.ea.getViewElements(); + const visualNode = sel.containerId ? all.find((el) => el.id === sel.containerId) : sel; + const nodeText = runtimeContext.getTextFromNode(all, visualNode, true, true).trim(); + const linkRegex = /^(!?)\[\[([^\]]+?#([^\]|]+))(?:\|[^\]]*)?\]\]$/; + const match = nodeText.match(linkRegex); + if (!match) return; + const isEmbed = match[1] === "!"; + const linkCore = match[2]; + const sectionRef = match[3]; + let newText = ""; + if (isEmbed) { + const alias = sectionRef.replace(/^#+\s*/, "").trim(); + newText = `[[${linkCore}|${alias}]]`; + } else { + newText = `![[${linkCore}]]`; + } + runtimeContext.editingNodeId = sel.id; + runtimeContext.inputEl.value = newText; + const incomingArrow = all.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === sel.id + ); + runtimeContext.ontologyEl.value = incomingArrow ? runtimeContext.ea.getBoundTextElement(incomingArrow, true)?.sceneElement?.rawText || "" : ""; + await runtimeContext.commitEdit(); + }; + const toggleBox = async (shape = "rectangle") => { + if (!runtimeContext.isViewSet()) return; + let sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + sel = runtimeContext.ea.getBoundTextElement(sel, true).sceneElement; + if (!sel) return; + let oldBindId, newBindId, finalElId; + const hasContainer = !!sel.containerId; + const ids = hasContainer ? [sel.id, sel.containerId] : [sel.id]; + const allElements = runtimeContext.ea.getViewElements(); + const arrowsToUpdate = allElements.filter( + (el) => el.type === "arrow" && (ids.includes(el.startBinding?.elementId) || ids.includes(el.endBinding?.elementId)) + ); + if (hasContainer) { + const containerId = oldBindId = sel.containerId; + finalElId = newBindId = sel.id; + const container = allElements.find((el) => el.id === containerId); + runtimeContext.ea.copyViewElementsToEAforEditing(arrowsToUpdate.concat(sel, container)); + const textEl = runtimeContext.ea.getElement(sel.id); + const dataToCopy = { + ...container.customData || {} + }; + runtimeContext.ea.addAppendUpdateCustomData(textEl.id, dataToCopy); + textEl.containerId = null; + textEl.boundElements = []; + runtimeContext.ea.getElement(containerId).isDeleted = true; + } else { + runtimeContext.ea.copyViewElementsToEAforEditing(arrowsToUpdate.concat(sel)); + const depth = runtimeContext.getHierarchy(sel, allElements)?.depth || 0; + oldBindId = sel.id; + let rectId; + if (shape === "ellipse") { + rectId = runtimeContext.ea.addEllipse( + sel.x - runtimeContext.padding, + sel.y - runtimeContext.padding, + sel.width + runtimeContext.padding * 2, + sel.height + runtimeContext.padding * 2 + ); + } else if (shape === "diamond") { + rectId = runtimeContext.ea.addDiamond( + sel.x - runtimeContext.padding, + sel.y - runtimeContext.padding, + sel.width + runtimeContext.padding * 2, + sel.height + runtimeContext.padding * 2 + ); + } else { + rectId = runtimeContext.ea.addRect( + sel.x - runtimeContext.padding, + sel.y - runtimeContext.padding, + sel.width + runtimeContext.padding * 2, + sel.height + runtimeContext.padding * 2 + ); + } + finalElId = newBindId = rectId; + const rect = runtimeContext.ea.getElement(rectId); + const dataToCopy = { + ...sel.customData || {} + }; + runtimeContext.ea.addAppendUpdateCustomData(rectId, dataToCopy); + rect.strokeColor = runtimeContext.ea.getCM(sel.strokeColor).stringRGB(); + rect.strokeWidth = runtimeContext.getStrokeWidthForDepth(depth); + rect.roughness = runtimeContext.getAppState().currentItemRoughness; + rect.roundness = runtimeContext.roundedCorners ? { + type: 3 + } : null; + rect.backgroundColor = "transparent"; + const textEl = runtimeContext.ea.getElement(sel.id); + textEl.containerId = rectId; + textEl.boundElements = null; + rect.boundElements = [ + { + type: "text", + id: sel.id + } + ]; + rect.groupIds = sel.groupIds ? [...sel.groupIds] : []; + } + runtimeContext.ea.getElements().filter((el) => el.type === "arrow").forEach((a) => { + if (a.startBinding?.elementId === oldBindId) { + a.startBinding.elementId = newBindId; + runtimeContext.ea.getElement(newBindId).boundElements.push({ + type: "arrow", + id: a.id + }); + } + if (a.endBinding?.elementId === oldBindId) { + a.endBinding.elementId = newBindId; + runtimeContext.ea.getElement(newBindId).boundElements.push({ + type: "arrow", + id: a.id + }); + } + }); + runtimeContext.ea.getElement(oldBindId).boundElements = []; + delete runtimeContext.ea.getElement(oldBindId).customData; + await runtimeContext.addElementsToView({ + captureUpdate: runtimeContext.autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" + }); + if (!hasContainer) { + const textElement = runtimeContext.ea.getViewElements().find((el) => el.id === sel.id); + const idx = runtimeContext.ea.getViewElements().indexOf(textElement); + runtimeContext.ea.moveViewElementToZIndex(textElement.containerId, idx); + } + if (!hasContainer) { + runtimeContext.api().updateContainerSize([ + runtimeContext.ea.getViewElements().find((el) => el.id === newBindId) + ]); + } + runtimeContext.selectNodeInView(finalElId); + if (!runtimeContext.autoLayoutDisabled) await runtimeContext.refreshMapLayout(); + runtimeContext.updateUI(); + }; + return { togglePin, toggleCheckboxStatus, toggleEmbedStatus, toggleBox }; + } + + // src/scripts/mindmap-builder/keyboard.js + function createKeyboard(runtimeContext) { + let disposed = false; + let popRootScope = () => { + }; + const ownedKeydownCleanups = /* @__PURE__ */ new Set(); + const removeObsidianHotkeyOverrides = () => popRootScope(); + const disposeKeyboard = () => { + disposed = true; + removeObsidianHotkeyOverrides(); + ownedKeydownCleanups.forEach((cleanup) => cleanup()); + }; + const getObsidianConflict = (h) => { + if (!h) return null; + const normalize = (s) => s.toLowerCase().replace("key", "").replace("digit", ""); + const sortMods = (m) => [...m].sort().join(","); + const keysToCheck = h.isNavigation ? ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"] : [h.code ? h.code : h.key]; + const targetMods = sortMods(h.modifiers); + const commands = app.commands.listCommands(); + for (const cmd of commands) { + const hotkeys = app.hotkeyManager.getHotkeys(cmd.id) || app.hotkeyManager.getDefaultHotkeys(cmd.id); + if (!hotkeys) continue; + for (const hk of hotkeys) { + const hkKey = normalize(hk.key); + const hkMods = sortMods(hk.modifiers); + for (const targetKeyRaw of keysToCheck) { + if (normalize(targetKeyRaw) === hkKey && targetMods === hkMods) { + return cmd.name; + } + } + } + } + return null; + }; + function updateUserHotkeys() { + let dirty = false; + const defaultByAction = new Map(runtimeContext.DEFAULT_HOTKEYS.map((d) => [d.action, d])); + const structuralKeys = ["isInputOnly", "requiresNode", "isNavigation", "hidden"]; + const userByAction = /* @__PURE__ */ new Map(); + for (const u of runtimeContext.userHotkeys) { + if (u && typeof u.action === "string" && defaultByAction.has(u.action)) { + userByAction.set(u.action, u); + } else if (u && u.action) { + dirty = true; + } + } + const next = []; + for (const d of runtimeContext.DEFAULT_HOTKEYS) { + const u = userByAction.get(d.action); + if (!u) { + next.push(structuredClone ? structuredClone(d) : JSON.parse(JSON.stringify(d))); + dirty = true; + continue; + } + const cleaned = { + action: d.action + }; + for (const key of Object.keys(d)) { + if (key === "action") continue; + if (structuralKeys.includes(key)) { + cleaned[key] = d[key]; + continue; + } + if (Object.prototype.hasOwnProperty.call(u, key)) { + cleaned[key] = u[key]; + } else { + cleaned[key] = d[key]; + dirty = true; + } + } + for (const key of Object.keys(u)) { + if (key === "action") continue; + if (structuralKeys.includes(key)) { + dirty = true; + } else if (!Object.prototype.hasOwnProperty.call(d, key)) { + dirty = true; + break; + } + } + next.push(cleaned); + } + runtimeContext.userHotkeys = next; + return dirty; + } + const getHotkeyDefByAction = (action) => runtimeContext.userHotkeys.find((h) => h.action === action); + const getHotkeyDisplayString = (h) => { + const parts = []; + if (h.modifiers.includes("Ctrl")) parts.push("Ctrl"); + if (h.modifiers.includes("Meta")) parts.push("Cmd"); + if (h.modifiers.includes("Mod")) parts.push(runtimeContext.isMac ? "Cmd" : "Ctrl"); + if (h.modifiers.includes("Alt")) parts.push(runtimeContext.isMac ? "Opt" : "Alt"); + if (h.modifiers.includes("Shift")) parts.push("Shift"); + if (h.code) parts.push(h.code.replace("Key", "").replace("Digit", "")); + else if (h.key === "ArrowKeys") parts.push("Arrow"); + else if (h.key === " ") parts.push("Space"); + else parts.push(h.key); + return parts.join(" + "); + }; + const getActionHotkeyString = (action) => `(${getHotkeyDisplayString(getHotkeyDefByAction(action))})`; + const generateRuntimeHotkeys = () => { + const runtimeKeys = []; + runtimeContext.userHotkeys.forEach((h) => { + if (h.isNavigation) { + ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].forEach((key) => { + runtimeKeys.push({ + action: h.action, + key, + modifiers: h.modifiers, + scope: h.scope, + requiresNode: h.requiresNode, + isInputOnly: h.isInputOnly + }); + }); + } else { + runtimeKeys.push(h); + } + }); + return runtimeKeys; + }; + const getHotkeyContext = (event) => { + if (disposed || !runtimeContext.ea.sidepanelTab || !runtimeContext.isViewSet()) { + return runtimeContext.SCOPE.none; + } + const currentWindow = runtimeContext.isUndocked && runtimeContext.floatingInputModal ? runtimeContext.ea.targetView?.ownerWindow : runtimeContext.sidepanelWindow; + const activeElement = event?.target ?? currentWindow?.document?.activeElement; + if (runtimeContext.inputEl && activeElement === runtimeContext.inputEl || runtimeContext.ontologyEl && activeElement === runtimeContext.ontologyEl) { + return runtimeContext.SCOPE.input; + } + const leaf = app.workspace.activeLeaf; + if (!leaf) return runtimeContext.SCOPE.none; + if (runtimeContext.ea.targetView.leaf === leaf || runtimeContext.ea.getSidepanelLeaf() === leaf && runtimeContext.ea.sidepanelTab.isVisible()) { + return runtimeContext.SCOPE.excalidraw; + } + if (runtimeContext.ea.targetView.leaf.isVisible()) { + return runtimeContext.SCOPE.global; + } + return runtimeContext.SCOPE.none; + }; + const registerKeydownHandler = (host, handler) => { + if (disposed || !runtimeContext.ea.sidepanelTab) return; + runtimeContext.removeKeydownHandlers(); + if (!window.MindmapBuilder) return; + if (!window.MindmapBuilder.keydownHandlers) { + window.MindmapBuilder.keydownHandlers = []; + } + host.addEventListener("keydown", handler, true); + const cleanup = () => { + host.removeEventListener("keydown", handler, true); + ownedKeydownCleanups.delete(cleanup); + }; + ownedKeydownCleanups.add(cleanup); + window.MindmapBuilder.keydownHandlers.push(cleanup); + }; + const registerObsidianHotkeyOverrides = () => { + removeObsidianHotkeyOverrides(); + if (disposed || !runtimeContext.ea.sidepanelTab) return; + const keymapScope = app.keymap.getRootScope(); + if (getHotkeyContext() === runtimeContext.SCOPE.none) return; + const handler = keymapScope.register( + null, + null, + (event) => canOverrideObsidianHotkey(event) ? true : void 0 + ); + const registry = window.MindmapBuilder; + const release = () => { + keymapScope.unregister(handler); + if (registry?.popObsidianHotkeyScope === release) { + delete registry.popObsidianHotkeyScope; + } + if (popRootScope === release) popRootScope = () => { + }; + }; + popRootScope = release; + try { + const index = keymapScope.keys.indexOf(handler); + if (index !== -1) keymapScope.keys.splice(index, 1); + keymapScope.keys.unshift(handler); + if (registry) registry.popObsidianHotkeyScope = release; + } catch (error) { + release(); + throw error; + } + }; + const updateKeyHandlerLocation = () => { + if (runtimeContext.isUndocked) { + if (runtimeContext.ea.targetView && runtimeContext.ea.targetView.ownerWindow) { + registerKeydownHandler(runtimeContext.ea.targetView.ownerWindow, handleKeydown); + } + } else { + if (runtimeContext.sidepanelWindow) { + registerKeydownHandler(runtimeContext.sidepanelWindow, handleKeydown); + } + } + }; + const getActionFromEvent = (e) => { + const isMod = e.ctrlKey || e.metaKey; + const match = runtimeContext.RUNTIME_HOTKEYS.find((h) => { + const keyMatch = h.code ? e.code === h.code : e.key === h.key; + if (!keyMatch) return false; + const hasMod = h.modifiers.includes("Mod") || h.modifiers.includes("Ctrl") || h.modifiers.includes("Meta"); + const hasShift = h.modifiers.includes("Shift"); + const hasAlt = h.modifiers.includes("Alt"); + return isMod === hasMod && e.shiftKey === hasShift && e.altKey === hasAlt; + }); + return match ? { + action: match.action, + scope: match.scope ?? runtimeContext.SCOPE.none, + requiresNode: match.requiresNode, + isInputOnly: match.isInputOnly + } : {}; + }; + const canOverrideObsidianHotkey = (event) => { + if (disposed || event.isComposing || event.keyCode === 229 || runtimeContext.isRecordingHotkey) + return false; + if (!runtimeContext.ea.targetView?.leaf.isVisible()) return false; + const state = runtimeContext.getAppState(); + if (!state || state.editingTextElement || state.selectedLinearElement?.isEditing || state.showHyperlinkPopup === "editor") + return false; + if (runtimeContext.linkSuggester?.isBlockingKeys()) return false; + const { action, scope, requiresNode, isInputOnly } = getActionFromEvent(event); + const context = getHotkeyContext(event); + if (!action || context < scope || isInputOnly && context !== runtimeContext.SCOPE.input) + return false; + if (requiresNode && !runtimeContext.getMindmapNodeFromSelection()) return false; + if (action === runtimeContext.ACTION_UNDO && runtimeContext.lastCommittedTransaction === null) + return false; + if ((action === runtimeContext.ACTION_REDO_Z || action === runtimeContext.ACTION_REDO_Y) && runtimeContext.redoAvailable === null) + return false; + return true; + }; + const handleKeydown = (e) => { + if (disposed || !runtimeContext.ea.sidepanelTab) return; + if (e.isComposing || e.keyCode === 229) return; + if (runtimeContext.isRecordingHotkey) return; + if (!runtimeContext.ea.targetView || !runtimeContext.ea.targetView.leaf.isVisible()) return; + const currentWindow = runtimeContext.isUndocked && runtimeContext.floatingInputModal ? runtimeContext.ea.targetView?.ownerWindow : runtimeContext.sidepanelWindow; + if (!currentWindow) return; + const st = runtimeContext.getAppState(); + if (!st || !!st.editingTextElement || !!st.selectedLinearElement?.isEditing || st.showHyperlinkPopup === "editor") + return; + if (runtimeContext.linkSuggester?.isBlockingKeys()) { + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + } + return; + } + if (e.key === "Escape" && !runtimeContext.isUndocked && runtimeContext.inputEl.ownerDocument.activeElement !== runtimeContext.inputEl) { + return; + } + let { action, scope, requiresNode, isInputOnly } = getActionFromEvent(e); + if (!action && !["Tab", "Enter"].includes(e.key)) return; + let context = getHotkeyContext(e); + if (!action && runtimeContext.isUndocked && runtimeContext.floatingInputModal && e.key === "Tab") { + const modalEl = runtimeContext.floatingInputModal.modalEl; + if (!modalEl) return; + const activeEl = modalEl.ownerDocument.activeElement; + if (!modalEl.contains(activeEl)) return; + const selector = ["input:not([disabled])", "div:not([style*='not-allowed'])"].join(","); + const focusables = Array.from(modalEl.querySelectorAll(selector)).filter((el) => { + if (el.tabIndex === -1 || el.hidden) return false; + return el.offsetParent !== null || el.getClientRects().length > 0; + }); + if (focusables.length > 0) { + e.preventDefault(); + e.stopPropagation(); + const active = modalEl.ownerDocument.activeElement; + let idx = focusables.indexOf(active); + if (idx === -1) idx = 0; + idx = e.shiftKey ? idx === 0 ? focusables.length - 1 : idx - 1 : idx === focusables.length - 1 ? 0 : idx + 1; + focusables[idx].focus(); + } + return; + } + if (e.key === "Enter" && context === runtimeContext.SCOPE.excalidraw && (runtimeContext.isUndocked && runtimeContext.floatingInputModal || !runtimeContext.isUndocked)) { + const modalEl = runtimeContext.isUndocked ? runtimeContext.floatingInputModal.modalEl : runtimeContext.ea.sidepanelTab.containerEl; + const activeEl = modalEl?.ownerDocument.activeElement; + action = activeEl?.getAttribute("action"); + if (!action) return; + context = runtimeContext.SCOPE.input; + } + if (!action || context < scope || isInputOnly && context !== runtimeContext.SCOPE.input) + return; + if (requiresNode && !runtimeContext.getMindmapNodeFromSelection()) { + return; + } + if (action === runtimeContext.ACTION_UNDO && runtimeContext.lastCommittedTransaction === null) { + return; + } + if ((action === runtimeContext.ACTION_REDO_Z || action === runtimeContext.ACTION_REDO_Y) && runtimeContext.redoAvailable === null) { + return; + } + e.preventDefault(); + e.stopPropagation(); + runtimeContext.performAction(action, e); + }; + const addSibling = async (event, insertAfter = true) => { + if (!runtimeContext.inputEl.value) return; + const dir = insertAfter ? 1 : -1; + const allElementsForSibling = runtimeContext.ea.getViewElements(); + const selectedForSibling = runtimeContext.getMindmapNodeFromSelection(); + if (!selectedForSibling) { + await runtimeContext.addNode( + runtimeContext.inputEl.value, + true, + false, + null, + null, + null, + runtimeContext.ontologyEl.value + ); + } else { + const info = runtimeContext.getHierarchy(selectedForSibling, allElementsForSibling); + const root = allElementsForSibling.find((el) => el.id === info.rootId); + const parentOfSelected = runtimeContext.getParentNode( + selectedForSibling.id, + allElementsForSibling + ); + const rootMode = root.customData?.growthMode || runtimeContext.currentModalGrowthMode; + const isVertical = ["Up-facing", "Down-facing", "Up-Down"].includes(rootMode); + const targetParent = parentOfSelected ?? selectedForSibling; + let pos = { + x: selectedForSibling.x + (isVertical && insertAfter ? selectedForSibling.width : 0) + (isVertical ? dir : 0), + y: selectedForSibling.y + (!isVertical && insertAfter ? selectedForSibling.height : 0) + (!isVertical ? dir : 0) + }; + if (parentOfSelected && parentOfSelected.id === root.id && root.customData?.growthMode === "Radial") { + const rb = runtimeContext.getNodeBox(root, allElementsForSibling); + const rc = { + x: rb.minX + rb.width / 2, + y: rb.minY + rb.height / 2 + }; + const sc = { + x: selectedForSibling.x + selectedForSibling.width / 2, + y: selectedForSibling.y + selectedForSibling.height / 2 + }; + const angle = Math.atan2(sc.y - rc.y, sc.x - rc.x) + dir * 0.2; + const dist = Math.hypot(sc.x - rc.x, sc.y - rc.y); + pos = { + x: rc.x + Math.cos(angle) * dist - selectedForSibling.width / 2, + y: rc.y + Math.sin(angle) * dist - selectedForSibling.height / 2 + }; + } + runtimeContext.selectNodeInView(targetParent); + await runtimeContext.addNode( + runtimeContext.inputEl.value, + false, + false, + null, + null, + pos, + runtimeContext.ontologyEl.value + ); + } + runtimeContext.inputEl.value = ""; + runtimeContext.ontologyEl.value = ""; + runtimeContext.updateUI(); + await runtimeContext.performAction(runtimeContext.ACTION_ADD, event); + }; + runtimeContext.ea.registerCleanup?.(disposeKeyboard); + return { + removeObsidianHotkeyOverrides, + disposeKeyboard, + getObsidianConflict, + updateUserHotkeys, + getHotkeyDefByAction, + getHotkeyDisplayString, + getActionHotkeyString, + generateRuntimeHotkeys, + getHotkeyContext, + registerKeydownHandler, + registerObsidianHotkeyOverrides, + updateKeyHandlerLocation, + getActionFromEvent, + handleKeydown, + addSibling + }; + } + + // src/scripts/mindmap-builder/inputUi.js + function createInputUi(runtimeContext) { + const revealInputEl = () => { + const undockPreference = runtimeContext.getVal(runtimeContext.K_UNDOCKED, false); + if (undockPreference && !runtimeContext.isUndocked) { + runtimeContext.toggleDock({ + saveSetting: false + }); + return true; + } else if (!undockPreference && !runtimeContext.isUndocked && runtimeContext.ea.sidepanelTab && !runtimeContext.ea.sidepanelTab.isVisible()) { + runtimeContext.ea.sidepanelTab.reveal(); + } + return false; + }; + const focusInputEl = () => { + revealInputEl(); + setTimeout(() => { + if (runtimeContext.isRecordingHotkey) return; + const target = runtimeContext.isOntologyFocused ? runtimeContext.ontologyEl.style.display === "none" ? runtimeContext.inputEl : runtimeContext.ontologyEl : runtimeContext.inputEl; + if (!target || target.disabled) { + return; + } + target.focus(); + if (!window.MindmapBuilder?.popObsidianHotkeyScope) + runtimeContext.registerObsidianHotkeyOverrides(); + }, 200); + }; + const setButtonDisabled = (btn, disabled) => { + if (!btn) return; + btn.disabled = disabled; + const btnEl = btn.extraSettingsEl ?? btn.buttonEl ?? btn.toggleEl; + if (!btnEl) return; + btnEl.tabIndex = disabled ? -1 : 0; + btnEl.style.opacity = disabled ? "0.5" : ""; + btnEl.style.cursor = disabled ? "not-allowed" : ""; + if (disabled && btn.buttonEl) { + btn.buttonEl.style.pointerEvents = "auto"; + btn.buttonEl.style.cursor = "not-allowed"; + } + }; + const disableUI = () => { + if (runtimeContext.pinBtn) runtimeContext.pinBtn.setIcon("pin-off"); + setButtonDisabled(runtimeContext.pinBtn, true); + setButtonDisabled(runtimeContext.refreshBtn, true); + setButtonDisabled(runtimeContext.copyBtn, true); + setButtonDisabled(runtimeContext.cutBtn, true); + setButtonDisabled(runtimeContext.importOutlineBtn, true); + setButtonDisabled(runtimeContext.boxBtn, true); + setButtonDisabled(runtimeContext.foldBtnL0, true); + setButtonDisabled(runtimeContext.foldBtnL1, true); + setButtonDisabled(runtimeContext.foldBtnAll, true); + setButtonDisabled(runtimeContext.editBtn, true); + setButtonDisabled(runtimeContext.toggleGroupBtn, true); + setButtonDisabled(runtimeContext.zoomBtn, true); + setButtonDisabled(runtimeContext.focusBtn, true); + setButtonDisabled(runtimeContext.boundaryBtn, true); + setButtonDisabled(runtimeContext.submapRootBtn, true); + setButtonDisabled(runtimeContext.toggleCheckboxBtn, true); + setButtonDisabled(runtimeContext.calendarBtn, true); + setButtonDisabled(runtimeContext.toggleEmbedBtn, true); + setButtonDisabled(runtimeContext.floatingGroupBtn, true); + setButtonDisabled(runtimeContext.floatingBoxBtn, true); + setButtonDisabled(runtimeContext.floatingZoomBtn, true); + setButtonDisabled(runtimeContext.autoLayoutToggle, true); + runtimeContext.editingNodeId = null; + if (runtimeContext.editBtn) runtimeContext.editBtn.extraSettingsEl.style.color = ""; + }; + const updateUI = (sel) => { + if (!runtimeContext.isViewSet()) { + if (runtimeContext.inputEl) { + runtimeContext.inputEl.disabled = true; + } + if (runtimeContext.ontologyEl) { + runtimeContext.ontologyEl.style.display = "none"; + } + disableUI(); + return; + } + if (runtimeContext.inputEl) { + runtimeContext.inputEl.disabled = false; + } + const all = runtimeContext.ea.getViewElements(); + sel = sel ?? runtimeContext.getMindmapNodeFromSelection(); + if (runtimeContext.ontologyEl) { + runtimeContext.ontologyEl.style.display = sel ? "" : "none"; + } + let cd = {}; + const isMapSelected = !!sel; + if (isMapSelected) { + runtimeContext.disableTabEvents = true; + const info = runtimeContext.getHierarchy(sel, all); + const isMasterRootSelected = info.rootId === sel.id; + const root = runtimeContext.getSettingsRootNode(sel, all) || all.find((e) => e.id === info.rootId); + const isPinned = sel.customData?.isPinned === true; + const isAdditionalRoot = sel.customData?.isAdditionalRoot === true; + const isMasterRoot = !runtimeContext.getParentNode(sel.id, all); + const isEditing = runtimeContext.editingNodeId && runtimeContext.editingNodeId === sel.id; + const branchIds = runtimeContext.getBranchElementIds(sel.id, all); + const children = runtimeContext.getChildrenNodes(sel.id, all); + const hasChildren = children.length > 0; + const hasGrandChildren = hasChildren && children.some((child) => runtimeContext.getChildrenNodes(child.id, all).length > 0); + const nodeText = runtimeContext.getTextFromNode(all, sel, true, false); + const isLinkedFile = !!runtimeContext.getNodeMarkdownFile(nodeText); + cd = root?.customData ?? {}; + if (runtimeContext.toggleCheckboxBtn) { + const isTextNode = sel.type === "text" || sel.boundElements && sel.boundElements.some((be) => be.type === "text"); + const canEditTask = isTextNode && !isMasterRootSelected || runtimeContext.inputEl && runtimeContext.inputEl.value.trim() !== ""; + setButtonDisabled(runtimeContext.toggleCheckboxBtn, !canEditTask); + } + if (runtimeContext.calendarBtn) { + const isTextNode = sel.type === "text" || sel.boundElements && sel.boundElements.some((be) => be.type === "text"); + const canEditTask = isTextNode && !isMasterRootSelected || runtimeContext.inputEl && runtimeContext.inputEl.value.trim() !== ""; + setButtonDisabled(runtimeContext.calendarBtn, !canEditTask); + } + if (runtimeContext.toggleEmbedBtn) { + const visualNode = sel.containerId ? all.find((el) => el.id === sel.containerId) : sel; + const nodeTextForEmbed = runtimeContext.getTextFromNode(all, visualNode, true, true).trim(); + const linkRegex = /^!?\[\[([^\]]+?#[^\]|]+)(?:\|[^\]]*)?\]\]$/; + setButtonDisabled(runtimeContext.toggleEmbedBtn, !linkRegex.test(nodeTextForEmbed)); + } + if (runtimeContext.pinBtn) { + runtimeContext.pinBtn.setIcon(isPinned ? "pin" : "pin-off"); + runtimeContext.pinBtn.setTooltip( + `${isPinned ? runtimeContext.t("PIN_TOOLTIP_PINNED") : runtimeContext.t("PIN_TOOLTIP_UNPINNED")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_PIN)}` + ); + setButtonDisabled(runtimeContext.pinBtn, false); + } + if (runtimeContext.submapRootBtn) { + runtimeContext.submapRootBtn.setIcon( + isAdditionalRoot ? "map-pin-minus-inside" : "map-pin-plus-inside" + ); + runtimeContext.submapRootBtn.setTooltip( + `${isAdditionalRoot ? runtimeContext.t("TOOLTIP_SUBMAP_ROOT_REMOVE") : runtimeContext.t("TOOLTIP_SUBMAP_ROOT_ADD")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_TOGGLE_SUBMAP_ROOT)}` + ); + setButtonDisabled(runtimeContext.submapRootBtn, isMasterRoot); + } + if (runtimeContext.editBtn) { + setButtonDisabled(runtimeContext.editBtn, false); + if (isEditing) { + runtimeContext.editBtn.extraSettingsEl.style.color = "var(--interactive-accent)"; + } else { + runtimeContext.editingNodeId = null; + runtimeContext.editBtn.extraSettingsEl.style.color = ""; + } + } + const updateGroupBtn = (btn) => { + if (!btn) { + return; + } + const isGrouped = branchIds.length > 1 && !!runtimeContext.getCommonGroupForElements( + all.filter((el) => branchIds.includes(el.id)) + )[0]; + btn.setIcon(isGrouped ? "ungroup" : "group"); + btn.setTooltip( + `${isGrouped ? runtimeContext.t("TOGGLE_GROUP_TOOLTIP_UNGROUP") : runtimeContext.t("TOGGLE_GROUP_TOOLTIP_GROUP")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_TOGGLE_GROUP)}` + ); + setButtonDisabled(btn, runtimeContext.groupBranches || branchIds.length <= 1); + }; + updateGroupBtn(runtimeContext.toggleGroupBtn); + updateGroupBtn(runtimeContext.floatingGroupBtn); + setButtonDisabled(runtimeContext.boxBtn, false); + setButtonDisabled(runtimeContext.floatingBoxBtn, false); + setButtonDisabled(runtimeContext.foldBtnL0, !hasChildren); + setButtonDisabled(runtimeContext.foldBtnL1, !hasGrandChildren); + setButtonDisabled(runtimeContext.foldBtnAll, !hasGrandChildren); + setButtonDisabled(runtimeContext.zoomBtn, false); + setButtonDisabled(runtimeContext.focusBtn, false); + setButtonDisabled(runtimeContext.floatingZoomBtn, false); + if (runtimeContext.boundaryBtn) { + runtimeContext.boundaryBtn.setIcon(sel.customData?.boundaryId ? "cloud-off" : "cloud"); + } + setButtonDisabled(runtimeContext.boundaryBtn, isMasterRootSelected); + setButtonDisabled(runtimeContext.cutBtn, isMasterRootSelected); + setButtonDisabled(runtimeContext.copyBtn, false); + setButtonDisabled(runtimeContext.importOutlineBtn, !isLinkedFile); + if (runtimeContext.refreshBtn) { + setButtonDisabled(runtimeContext.refreshBtn, cd.autoLayoutDisabled === true); + runtimeContext.refreshBtn.setTooltip( + `${runtimeContext.t("TOOLTIP_REFRESH")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_REARRANGE)}` + ); + } + } else { + disableUI(); + if (runtimeContext.mostRecentlySelectedNodeID) { + setButtonDisabled(runtimeContext.zoomBtn, false); + setButtonDisabled(runtimeContext.focusBtn, false); + setButtonDisabled(runtimeContext.floatingZoomBtn, false); + } + if (runtimeContext.inputEl && runtimeContext.inputEl.value.trim() !== "") { + if (runtimeContext.toggleCheckboxBtn) { + setButtonDisabled(runtimeContext.toggleCheckboxBtn, false); + } + if (runtimeContext.calendarBtn) { + setButtonDisabled(runtimeContext.calendarBtn, false); + } + } + setButtonDisabled(runtimeContext.autoLayoutToggle, false); + } + const mapPresetName = cd?.presetName; + if (isMapSelected) { + runtimeContext.activePresetName = mapPresetName || "Default"; + runtimeContext.setVal(runtimeContext.K_ACTIVE_PRESET, runtimeContext.activePresetName); + } else { + runtimeContext.activePresetName = runtimeContext.getVal( + runtimeContext.K_ACTIVE_PRESET, + "Default" + ); + } + if (runtimeContext.presetDropdown) { + runtimeContext.presetDropdown.setValue(runtimeContext.activePresetName); + } + let showWarning = false; + if (isMapSelected) { + const presetConfig = runtimeContext.mapPresets[runtimeContext.activePresetName]; + const currentMapConfig = { + growthMode: cd?.growthMode ?? runtimeContext.currentModalGrowthMode, + arrowType: cd?.arrowType ?? runtimeContext.arrowType, + fontsizeScale: cd?.fontsizeScale ?? runtimeContext.fontsizeScale, + multicolor: typeof cd?.multicolor === "boolean" ? cd.multicolor : runtimeContext.multicolor, + boxChildren: typeof cd?.boxChildren === "boolean" ? cd.boxChildren : runtimeContext.boxChildren, + roundedCorners: typeof cd?.roundedCorners === "boolean" ? cd.roundedCorners : runtimeContext.roundedCorners, + maxWrapWidth: typeof cd?.maxWrapWidth === "number" ? cd.maxWrapWidth : runtimeContext.maxWidth, + isSolidArrow: typeof cd?.isSolidArrow === "boolean" ? cd.isSolidArrow : runtimeContext.isSolidArrow, + centerText: typeof cd?.centerText === "boolean" ? cd.centerText : runtimeContext.centerText, + fillSweep: typeof cd?.fillSweep === "boolean" ? cd.fillSweep : runtimeContext.fillSweep, + branchScale: cd?.branchScale ?? runtimeContext.branchScale, + baseStrokeWidth: typeof cd?.baseStrokeWidth === "number" ? cd.baseStrokeWidth : runtimeContext.baseStrokeWidth, + customPalette: cd?.customPalette ?? runtimeContext.customPalette, + layoutSettings: cd?.layoutSettings ?? runtimeContext.layoutSettings + }; + showWarning = runtimeContext.diffMapConfig(presetConfig, currentMapConfig); + } + if (runtimeContext.presetWarningEl) { + runtimeContext.presetWarningEl.style.display = showWarning ? "block" : "none"; + } + if (runtimeContext.presetApplyBtn) { + setButtonDisabled(runtimeContext.presetApplyBtn, !isMapSelected); + } + if (runtimeContext.presetTrashBtn) { + setButtonDisabled( + runtimeContext.presetTrashBtn, + runtimeContext.activePresetName === "Default" + ); + } + if (runtimeContext.presetSaveBtn) { + setButtonDisabled(runtimeContext.presetSaveBtn, false); + } + if (isMapSelected) { + runtimeContext.currentModalGrowthMode = typeof cd.growthMode === "string" && runtimeContext.GROWTH_TYPES.includes(cd.growthMode) ? cd.growthMode : runtimeContext.getVal(runtimeContext.K_GROWTH, "Right-Left"); + runtimeContext.setVal(runtimeContext.K_GROWTH, runtimeContext.currentModalGrowthMode); + runtimeContext.autoLayoutDisabled = cd.autoLayoutDisabled === true; + runtimeContext.arrowType = typeof cd.arrowType === "string" && runtimeContext.ARROW_TYPES.includes(cd.arrowType) ? cd.arrowType : runtimeContext.getVal(runtimeContext.K_ARROW_TYPE, "curved"); + runtimeContext.setVal(runtimeContext.K_ARROW_TYPE, runtimeContext.arrowType); + runtimeContext.fontsizeScale = cd.fontsizeScale ?? runtimeContext.getVal(runtimeContext.K_FONTSIZE, "Normal Scale"); + runtimeContext.setVal(runtimeContext.K_FONTSIZE, runtimeContext.fontsizeScale); + runtimeContext.multicolor = typeof cd.multicolor === "boolean" ? cd.multicolor : runtimeContext.getVal(runtimeContext.K_MULTICOLOR, true); + runtimeContext.setVal(runtimeContext.K_MULTICOLOR, runtimeContext.multicolor); + runtimeContext.boxChildren = typeof cd.boxChildren === "boolean" ? cd.boxChildren : runtimeContext.getVal(runtimeContext.K_BOX, false); + runtimeContext.setVal(runtimeContext.K_BOX, runtimeContext.boxChildren); + runtimeContext.roundedCorners = typeof cd.roundedCorners === "boolean" ? cd.roundedCorners : runtimeContext.getVal(runtimeContext.K_ROUND, false); + runtimeContext.setVal(runtimeContext.K_ROUND, runtimeContext.roundedCorners); + runtimeContext.maxWidth = typeof cd.maxWrapWidth === "number" ? cd.maxWrapWidth : parseInt(runtimeContext.getVal(runtimeContext.K_WIDTH, 450)) || 450; + runtimeContext.setVal(runtimeContext.K_WIDTH, runtimeContext.maxWidth); + runtimeContext.isSolidArrow = typeof cd.isSolidArrow === "boolean" ? cd.isSolidArrow : runtimeContext.getVal(runtimeContext.K_ARROWSTROKE, true); + runtimeContext.setVal(runtimeContext.K_ARROWSTROKE, runtimeContext.isSolidArrow); + runtimeContext.centerText = typeof cd.centerText === "boolean" ? cd.centerText : runtimeContext.getVal(runtimeContext.K_CENTERTEXT, true); + runtimeContext.setVal(runtimeContext.K_CENTERTEXT, runtimeContext.centerText); + runtimeContext.fillSweep = typeof cd.fillSweep === "boolean" ? cd.fillSweep : runtimeContext.getVal(runtimeContext.K_FILL_SWEEP, false); + runtimeContext.setVal(runtimeContext.K_FILL_SWEEP, runtimeContext.fillSweep); + runtimeContext.branchScale = cd.branchScale && runtimeContext.BRANCH_SCALE_TYPES.includes(cd.branchScale) ? cd.branchScale : runtimeContext.getVal(runtimeContext.K_BRANCH_SCALE, "Hierarchical"); + runtimeContext.setVal(runtimeContext.K_BRANCH_SCALE, runtimeContext.branchScale); + runtimeContext.baseStrokeWidth = typeof cd.baseStrokeWidth === "number" ? cd.baseStrokeWidth : parseFloat(runtimeContext.getVal(runtimeContext.K_BASE_WIDTH, 6)) || 6; + runtimeContext.setVal(runtimeContext.K_BASE_WIDTH, runtimeContext.baseStrokeWidth); + if (cd.customPalette) { + runtimeContext.customPalette = JSON.parse(JSON.stringify(cd.customPalette)); + } else { + runtimeContext.customPalette = runtimeContext.getVal(runtimeContext.K_PALETTE, { + enabled: false, + random: false, + colors: [] + }) || { enabled: false, random: false, colors: [] }; + } + runtimeContext.setVal(runtimeContext.K_PALETTE, runtimeContext.customPalette, true); + if (cd.layoutSettings && typeof cd.layoutSettings === "object") { + runtimeContext.layoutSettings = { ...runtimeContext.layoutSettings, ...cd.layoutSettings }; + } else { + const globalDefaults = runtimeContext.getVal(runtimeContext.K_LAYOUT, {}); + Object.keys(runtimeContext.LAYOUT_METADATA).forEach((k) => { + runtimeContext.layoutSettings[k] = globalDefaults[k] !== void 0 ? globalDefaults[k] : runtimeContext.LAYOUT_METADATA[k].def; + }); + } + runtimeContext.setVal(runtimeContext.K_LAYOUT, runtimeContext.layoutSettings, true); + } + if (runtimeContext.strategyDropdown) { + runtimeContext.strategyDropdown.setValue(runtimeContext.currentModalGrowthMode); + } + if (runtimeContext.autoLayoutToggle) { + runtimeContext.autoLayoutToggle.setValue(!runtimeContext.autoLayoutDisabled); + } + if (runtimeContext.arrowTypeToggle) { + runtimeContext.arrowTypeToggle.setValue(runtimeContext.arrowType === "curved"); + } + if (runtimeContext.fontSizeDropdown) { + runtimeContext.fontSizeDropdown.setValue(runtimeContext.fontsizeScale); + } + if (runtimeContext.colorToggle) { + runtimeContext.colorToggle.setValue(runtimeContext.multicolor); + } + if (runtimeContext.boxToggle) { + runtimeContext.boxToggle.setValue(runtimeContext.boxChildren); + } + if (runtimeContext.roundToggle) { + runtimeContext.roundToggle.setValue(runtimeContext.roundedCorners); + } + if (runtimeContext.widthSlider) { + runtimeContext.widthSlider.setValue(runtimeContext.maxWidth); + if (runtimeContext.widthSlider.valLabelEl) { + runtimeContext.widthSlider.valLabelEl.setText(`${runtimeContext.maxWidth}px`); + } + } + if (runtimeContext.strokeToggle) { + runtimeContext.strokeToggle.setValue(!runtimeContext.isSolidArrow); + } + if (runtimeContext.centerToggle) { + runtimeContext.centerToggle.setValue(runtimeContext.centerText); + } + if (runtimeContext.fillSweepToggle) { + runtimeContext.fillSweepToggle.setValue(runtimeContext.fillSweep); + } + if (runtimeContext.branchScaleDropdown) { + runtimeContext.branchScaleDropdown.setValue(runtimeContext.branchScale); + } + if (runtimeContext.baseWidthSlider) { + runtimeContext.baseWidthSlider.setValue(runtimeContext.baseStrokeWidth); + if (runtimeContext.baseWidthSlider.valLabelEl) { + runtimeContext.baseWidthSlider.valLabelEl.setText(`${runtimeContext.baseStrokeWidth}`); + } + } + if (runtimeContext.fillSweepToggleSetting && runtimeContext.fillSweepToggleSetting.settingEl) { + runtimeContext.fillSweepToggleSetting.settingEl.style.display = runtimeContext.currentModalGrowthMode === "Radial" ? "" : "none"; + } + runtimeContext.disableTabEvents = false; + }; + return { revealInputEl, focusInputEl, setButtonDisabled, disableUI, updateUI }; + } + + // src/scripts/mindmap-builder/nodeEditing.js + function createNodeEditing(runtimeContext) { + const startEditing = () => { + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + const all = runtimeContext.ea.getViewElements(); + const text = runtimeContext.getTextFromNode(all, sel, true, true); + if (text.match(/\n/)) { + new runtimeContext.Notice( + `${runtimeContext.t("NOTICE_CANNOT_EDIT_MULTILINE")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_REARRANGE)}`, + 7e3 + ); + return; + } + const didToggle = runtimeContext.revealInputEl(); + setTimeout( + () => { + runtimeContext.inputEl.value = text; + const incomingArrow = all.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === sel.id + ); + runtimeContext.ontologyEl.value = runtimeContext.ea.getBoundTextElement(incomingArrow, true)?.sceneElement?.rawText || ""; + runtimeContext.editingNodeId = sel.id; + runtimeContext.updateUI(); + runtimeContext.inputEl.focus(); + }, + didToggle ? 200 : 0 + ); + }; + const commitEdit = async () => { + if (!runtimeContext.editingNodeId) return; + const all = runtimeContext.ea.getViewElements(); + let targetNode = all.find((el) => el.id === runtimeContext.editingNodeId); + if (!targetNode) return; + const visualNode = targetNode.containerId ? all.find((el) => el.id === targetNode.containerId) : targetNode; + let textElId = targetNode.id; + if (targetNode.boundElements) { + const boundText = targetNode.boundElements.find((be) => be.type === "text"); + if (boundText) textElId = boundText.id; + } + const textEl = all.find((el) => el.id === textElId && el.type === "text"); + const textInput = runtimeContext.inputEl.value; + const ontologyInput = runtimeContext.ontologyEl.value; + const currentText = runtimeContext.getTextFromNode(all, visualNode, true, true); + const incomingArrow = all.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === targetNode.id + // Target node might be container + ); + const currentOntology = incomingArrow ? runtimeContext.ea.getBoundTextElement(incomingArrow, true)?.sceneElement?.rawText || "" : ""; + const textChanged = textInput !== currentText; + const ontologyChanged = ontologyInput !== currentOntology; + if (!textChanged && !ontologyChanged) { + runtimeContext.editingNodeId = null; + runtimeContext.inputEl.value = ""; + runtimeContext.ontologyEl.value = ""; + runtimeContext.updateUI(); + return; + } + const imageInfo = runtimeContext.parseImageInput(textInput); + const embeddableUrl = runtimeContext.parseEmbeddableInput(textInput, imageInfo); + let newType = "text"; + if (imageInfo?.isImagePath || imageInfo?.imageFile) newType = "image"; + else if (embeddableUrl) newType = "embeddable"; + const isTypeChange = textEl && newType !== "text" || !textEl && newType !== targetNode.type; + const isNonTextUpdate = !textEl && newType === targetNode.type && textChanged; + let containerToUpdate = null; + if (isTypeChange || isNonTextUpdate) { + const cx = visualNode.x + visualNode.width / 2; + const cy = visualNode.y + visualNode.height / 2; + const info = runtimeContext.getHierarchy(visualNode, all); + const depth = info.depth; + let newNodeId; + const st = runtimeContext.getAppState(); + runtimeContext.ea.style.strokeColor = targetNode.strokeColor ?? st.currentItemStrokeColor; + if (newType === "image") { + if (imageInfo?.isImagePath) { + newNodeId = await runtimeContext.addImage({ + pathOrFile: imageInfo.path, + width: imageInfo.width, + depth + }); + if (imageInfo.isExternalImage && newNodeId) { + const el2 = runtimeContext.ea.getElement(newNodeId); + if (el2 && !el2.link) el2.link = imageInfo.path; + } + } else { + newNodeId = await runtimeContext.addImage({ + pathOrFile: imageInfo.imageFile, + width: imageInfo.width, + depth + }); + } + const el = runtimeContext.ea.getElement(newNodeId); + el.x = cx - el.width / 2; + el.y = cy - el.height / 2; + } else if (newType === "embeddable") { + newNodeId = runtimeContext.addEmbeddableNode({ + url: embeddableUrl, + depth + }); + const el = runtimeContext.ea.getElement(newNodeId); + el.x = cx - el.width / 2; + el.y = cy - el.height / 2; + } else { + if (runtimeContext.ea.style.strokeColor === "transparent") + runtimeContext.ea.style.strokeColor = "black"; + runtimeContext.ea.style.fontFamily = st.currentItemFontFamily; + const fontScale = runtimeContext.getFontScale(runtimeContext.fontsizeScale); + runtimeContext.ea.style.fontSize = fontScale[Math.min(depth, fontScale.length - 1)]; + runtimeContext.ea.style.backgroundColor = "transparent"; + runtimeContext.ea.style.strokeWidth = runtimeContext.getStrokeWidthForDepth(depth); + if (incomingArrow) { + runtimeContext.ea.style.strokeColor = incomingArrow.strokeColor; + } + runtimeContext.ea.style.roughness = runtimeContext.getAppState().currentItemRoughness; + const renderedText = await runtimeContext.parseText(textInput); + const metrics = runtimeContext.ea.measureText(renderedText); + const shouldWrap = metrics.width > runtimeContext.maxWidth; + let finalWidth = Math.ceil(metrics.width); + let finalHeight = metrics.height; + let finalWrappedText = renderedText; + if (shouldWrap) { + const res = await runtimeContext.getAdjustedMaxWidth(textInput, runtimeContext.maxWidth); + finalWidth = res.width; + finalHeight = res.height; + finalWrappedText = res.wrappedText; + } + newNodeId = runtimeContext.ea.addText(cx, cy, renderedText, { + textAlign: "center", + textVerticalAlign: "middle", + box: runtimeContext.boxChildren ? "rectangle" : false, + width: shouldWrap ? finalWidth : void 0, + height: shouldWrap ? finalHeight : void 0, + autoResize: runtimeContext.boxChildren ? false : !shouldWrap + }); + const newElement = runtimeContext.ea.getElement(newNodeId); + containerToUpdate = runtimeContext.boxChildren ? newElement : null; + newTextElement = runtimeContext.boxChildren ? runtimeContext.ea.getElement(containerToUpdate.boundElements[0].id) : newElement; + newTextElement.rawText = textInput; + newTextElement.originalText = renderedText; + newTextElement.text = finalWrappedText; + if (!shouldWrap) { + newTextElement.width = finalWidth; + newTextElement.height = finalHeight; + } + } + const newNode = runtimeContext.ea.getElement(newNodeId); + runtimeContext.scaleDecorations(visualNode, newNode, all, info.rootId); + const keysToCopy = [ + "mindmapOrder", + "isPinned", + "growthMode", + "autoLayoutDisabled", + "isFolded", + "foldIndicatorId", + "foldState", + "boundaryId", + "fontsizeScale", + "multicolor", + "boxChildren", + "roundedCorners", + "maxWrapWidth", + "isSolidArrow", + "centerText", + "arrowType", + "fillSweep", + "branchScale", + "baseStrokeWidth", + "layoutSettings" + ]; + const dataToCopy = {}; + keysToCopy.forEach((k) => { + if (visualNode.customData && visualNode.customData.hasOwnProperty(k)) { + dataToCopy[k] = visualNode.customData[k]; + } + }); + runtimeContext.ea.addAppendUpdateCustomData(newNodeId, dataToCopy); + if (visualNode.groupIds && visualNode.groupIds.length > 0) { + newNode.groupIds = [...visualNode.groupIds]; + } + const idsToReplace = [visualNode.id]; + if (textEl) idsToReplace.push(textEl.id); + const connectedArrows = all.filter( + (el) => el.type === "arrow" && (idsToReplace.includes(el.startBinding?.elementId) || idsToReplace.includes(el.endBinding?.elementId)) + ); + if (connectedArrows.length > 0) { + runtimeContext.ea.copyViewElementsToEAforEditing(connectedArrows); + const newBoundElements = []; + connectedArrows.forEach((arrow) => { + const eaArrow = runtimeContext.ea.getElement(arrow.id); + let isConnected = false; + const ratioX = visualNode.width > 1 ? newNode.width / visualNode.width : 1; + const ratioY = visualNode.height > 1 ? newNode.height / visualNode.height : 1; + if (idsToReplace.includes(eaArrow.startBinding?.elementId)) { + eaArrow.startBinding = { + ...eaArrow.startBinding, + elementId: newNodeId + }; + isConnected = true; + if (eaArrow.points.length > 0) { + const absX = arrow.x + arrow.points[0][0]; + const absY = arrow.y + arrow.points[0][1]; + const dx = absX - cx; + const dy = absY - cy; + const newAbsX = cx + dx * ratioX; + const newAbsY = cy + dy * ratioY; + eaArrow.points[0] = [ + eaArrow.points[0][0] + (newAbsX - absX), + eaArrow.points[0][1] + (newAbsY - absY) + ]; + } + } + if (idsToReplace.includes(eaArrow.endBinding?.elementId)) { + eaArrow.endBinding = { + ...eaArrow.endBinding, + elementId: newNodeId + }; + isConnected = true; + runtimeContext.addUpdateArrowLabel(eaArrow, ontologyInput); + if (eaArrow.points.length > 0) { + const lastIdx = eaArrow.points.length - 1; + const absX = arrow.x + arrow.points[lastIdx][0]; + const absY = arrow.y + arrow.points[lastIdx][1]; + const dx = absX - cx; + const dy = absY - cy; + const newAbsX = cx + dx * ratioX; + const newAbsY = cy + dy * ratioY; + eaArrow.points[lastIdx] = [ + eaArrow.points[lastIdx][0] + (newAbsX - absX), + eaArrow.points[lastIdx][1] + (newAbsY - absY) + ]; + } + } + if (isConnected) { + newBoundElements.push({ + type: "arrow", + id: arrow.id + }); + } + }); + if (newBoundElements.length > 0) { + newNode.boundElements = [...newNode.boundElements || [], ...newBoundElements]; + } + } + runtimeContext.ea.copyViewElementsToEAforEditing([visualNode]); + runtimeContext.ea.getElement(visualNode.id).isDeleted = true; + if (textEl && textEl.id !== visualNode.id) { + runtimeContext.ea.copyViewElementsToEAforEditing([textEl]); + runtimeContext.ea.getElement(textEl.id).isDeleted = true; + } + await runtimeContext.addElementsToView({ + captureUpdate: runtimeContext.autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" + }); + if (!runtimeContext.autoLayoutDisabled) { + const newViewElements = runtimeContext.ea.getViewElements(); + const newViewNode = newViewElements.find((el) => el.id === newNodeId); + if (newViewNode) { + runtimeContext.selectNodeInView(newViewNode); + const newInfo = runtimeContext.getHierarchy(newViewNode, newViewElements); + await runtimeContext.triggerGlobalLayout(newInfo.rootId, false, true); + } + } + } else { + if (ontologyChanged && incomingArrow) { + runtimeContext.ea.copyViewElementsToEAforEditing([incomingArrow]); + runtimeContext.addUpdateArrowLabel( + runtimeContext.ea.getElement(incomingArrow.id), + ontologyInput + ); + } + if (textChanged && textEl) { + runtimeContext.ea.copyViewElementsToEAforEditing([textEl]); + const eaEl = runtimeContext.ea.getElement(textEl.id); + const renderedText = await runtimeContext.parseText(textInput); + eaEl.rawText = textInput; + eaEl.originalText = renderedText; + runtimeContext.ea.style.fontFamily = eaEl.fontFamily; + runtimeContext.ea.style.fontSize = eaEl.fontSize; + const metrics = runtimeContext.ea.measureText(renderedText); + const shouldWrap = metrics.width > runtimeContext.maxWidth; + if (!shouldWrap) { + eaEl.autoResize = true; + eaEl.width = Math.ceil(metrics.width); + eaEl.height = metrics.height; + eaEl.text = renderedText; + } else { + eaEl.autoResize = false; + const res = await runtimeContext.getAdjustedMaxWidth(textInput, runtimeContext.maxWidth); + eaEl.width = res.width; + eaEl.height = res.height; + eaEl.text = res.wrappedText; + } + runtimeContext.ea.refreshTextElementSize(eaEl.id); + } + const hierarchyNode = targetNode.containerId ? all.find((el) => el.id === targetNode.containerId) : textEl; + await runtimeContext.addElementsToView({ + captureUpdate: !hierarchyNode || runtimeContext.autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" + }); + if (textChanged && textEl && textEl.containerId) { + const container = runtimeContext.ea.getViewElements().find((el) => el.id === textEl.containerId); + if (container) { + runtimeContext.api().updateContainerSize([container]); + } + } + if (containerToUpdate) { + runtimeContext.api().updateContainerSize([containerToUpdate]); + } + if (textChanged && hierarchyNode && !runtimeContext.autoLayoutDisabled) { + const info = runtimeContext.getHierarchy( + hierarchyNode, + runtimeContext.ea.getViewElements() + ); + await runtimeContext.triggerGlobalLayout(info.rootId); + } + } + runtimeContext.editingNodeId = null; + runtimeContext.inputEl.value = ""; + runtimeContext.ontologyEl.value = ""; + }; + return { startEditing, commitEdit }; + } + + // src/scripts/mindmap-builder/helpUi.js + function createHelpUi(runtimeContext) { + const getInstructions = () => ` +
+ +${runtimeContext.t("INSTRUCTIONS")} + +
Buy Me a Coffee at ko-fi.com
+ + +`; + const renderHelp = (container) => { + runtimeContext.helpContainer = container.createDiv(); + runtimeContext.detailsEl = runtimeContext.helpContainer.createEl("details"); + const summary = runtimeContext.detailsEl.createEl("summary", { + attr: { + style: "cursor: pointer;" + } + }); + summary.createSpan({ + text: runtimeContext.t("HELP_SUMMARY"), + attr: { + style: "font-weight: bold;" + } + }); + summary.createSpan({ + text: runtimeContext.VERSION, + attr: { + style: "float: right; color: var(--text-muted); font-size: 0.8em;" + } + }); + runtimeContext.ea.obsidian.MarkdownRenderer.render( + app, + getInstructions(), + runtimeContext.detailsEl.createDiv(), + "", + runtimeContext.ea.plugin + ); + }; + return { getInstructions, renderHelp }; + } + + // src/scripts/mindmap-builder/PaletteManagerModal.js + function createPaletteManagerModal(runtimeContext) { + class PaletteManagerModal extends runtimeContext.ea.FloatingModal { + constructor(app2, settings, onUpdate) { + super(app2); + this.settings = JSON.parse(JSON.stringify(settings)); + this.onUpdate = onUpdate; + this.editIndex = -1; + this.tempColor = "#000000"; + } + onOpen() { + this.display(); + } + display() { + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { + text: runtimeContext.t("MODAL_PALETTE_TITLE") + }); + new runtimeContext.ea.obsidian.Setting(contentEl).setName(runtimeContext.t("LABEL_ENABLE_CUSTOM_PALETTE")).setDesc(runtimeContext.t("DESC_ENABLE_CUSTOM_PALETTE")).addToggle( + (t) => t.setValue(this.settings.enabled).onChange((v) => { + this.settings.enabled = v; + this.save(); + this.display(); + }) + ); + if (this.settings.enabled) { + new runtimeContext.ea.obsidian.Setting(contentEl).setName(runtimeContext.t("LABEL_RANDOMIZE_ORDER")).setDesc(runtimeContext.t("DESC_RANDOMIZE_ORDER")).addToggle( + (t) => t.setValue(this.settings.random).onChange((v) => { + this.settings.random = v; + this.save(); + }) + ); + contentEl.createEl("hr"); + const listContainer = contentEl.createDiv(); + this.settings.colors.forEach((color, index) => { + const row = new runtimeContext.ea.obsidian.Setting(listContainer); + const nameEl = row.nameEl; + nameEl.style.display = "flex"; + nameEl.style.alignItems = "center"; + nameEl.style.gap = "10px"; + const preview = nameEl.createDiv(); + preview.style.width = "20px"; + preview.style.height = "20px"; + preview.style.backgroundColor = color; + preview.style.border = "1px solid var(--background-modifier-border)"; + preview.style.borderRadius = "4px"; + nameEl.createSpan({ + text: color + }); + row.addExtraButton( + (btn) => btn.setIcon("arrow-big-up").setTooltip(runtimeContext.t("TOOLTIP_MOVE_UP")).setDisabled(index === 0).onClick(() => { + if (index === 0) return; + [this.settings.colors[index - 1], this.settings.colors[index]] = [ + this.settings.colors[index], + this.settings.colors[index - 1] + ]; + this.save(); + this.display(); + }) + ).addExtraButton( + (btn) => btn.setIcon("arrow-big-down").setTooltip(runtimeContext.t("TOOLTIP_MOVE_DOWN")).setDisabled(index === this.settings.colors.length - 1).onClick(() => { + if (index === this.settings.colors.length - 1) return; + [this.settings.colors[index + 1], this.settings.colors[index]] = [ + this.settings.colors[index], + this.settings.colors[index + 1] + ]; + this.save(); + this.display(); + }) + ).addExtraButton( + (btn) => btn.setIcon("pencil").setTooltip(runtimeContext.t("TOOLTIP_EDIT_COLOR")).onClick(() => { + this.editIndex = index; + this.tempColor = color; + this.display(); + }) + ).addExtraButton( + (btn) => btn.setIcon("trash-2").setTooltip(runtimeContext.t("TOOLTIP_DELETE_COLOR")).onClick(() => { + this.settings.colors.splice(index, 1); + if (this.editIndex === index) this.editIndex = -1; + this.save(); + this.display(); + }) + ); + }); + contentEl.createEl("hr"); + contentEl.createEl("h4", { + text: this.editIndex === -1 ? runtimeContext.t("HEADING_ADD_NEW_COLOR") : runtimeContext.t("HEADING_EDIT_COLOR") + }); + const getHex = (val) => { + const cm = runtimeContext.ea.getCM(val); + return cm ? cm.stringHEX({ + alpha: false + }) : "#000000"; + }; + const updateEditorState = (val, textComp, pickerComp) => { + this.tempColor = val; + if (textComp) textComp.inputEl.value = val; + if (pickerComp) pickerComp.setValue(getHex(val)); + }; + let textComponent, pickerComponent; + new runtimeContext.ea.obsidian.Setting(contentEl).setName(runtimeContext.t("LABEL_SELECT_COLOR")).addText((text) => { + textComponent = text; + text.setValue(this.tempColor).onChange((value) => { + this.tempColor = value; + pickerComponent.setValue(getHex(value)); + }); + }).addColorPicker((picker) => { + pickerComponent = picker; + picker.setValue(getHex(this.tempColor)).onChange((value) => { + this.tempColor = value; + textComponent.setValue(value); + }); + }).addButton( + (btn) => btn.setIcon("swatch-book").setTooltip(runtimeContext.t("TOOLTIP_OPEN_PALETTE_PICKER")).onClick(async () => { + const selected = await runtimeContext.ea.showColorPicker( + btn.buttonEl, + "elementStroke" + ); + if (selected) { + updateEditorState(selected, textComponent, pickerComponent); + } + }) + ); + const actionContainer = contentEl.createDiv(); + actionContainer.style.display = "flex"; + actionContainer.style.justifyContent = "flex-end"; + actionContainer.style.gap = "10px"; + actionContainer.style.marginTop = "10px"; + if (this.editIndex !== -1) { + const cancelBtn = actionContainer.createEl("button", { + text: runtimeContext.t("BUTTON_CANCEL_EDIT") + }); + cancelBtn.onclick = () => { + this.editIndex = -1; + this.tempColor = "#000000"; + this.display(); + }; + } + const saveBtn = actionContainer.createEl("button", { + text: this.editIndex === -1 ? runtimeContext.t("BUTTON_ADD_COLOR") : runtimeContext.t("BUTTON_UPDATE_COLOR"), + cls: "mod-cta" + }); + saveBtn.onclick = () => { + if (this.editIndex === -1) { + this.settings.colors.push(this.tempColor); + } else { + this.settings.colors[this.editIndex] = this.tempColor; + this.editIndex = -1; + } + this.save(); + this.display(); + }; + } + } + save() { + this.onUpdate(this.settings); + } + } + return { PaletteManagerModal }; + } + + // src/scripts/mindmap-builder/LayoutConfigModal.js + function createLayoutConfigModal(runtimeContext) { + class LayoutConfigModal extends runtimeContext.ea.FloatingModal { + constructor(app2, currentSettings, onUpdate) { + super(app2); + this.settings = this.normalizeSettings(currentSettings); + this.onUpdate = onUpdate; + this.updateTimer = null; + this.focusRefreshHandler = (evt) => this.handleFocusRefresh(evt); + this.focusDoc = null; + } + normalizeSettings(settingsLike) { + const normalized = {}; + Object.keys(runtimeContext.LAYOUT_METADATA).forEach((key) => { + const meta = runtimeContext.LAYOUT_METADATA[key]; + const candidate = settingsLike?.[key]; + normalized[key] = typeof candidate === "number" && Number.isFinite(candidate) ? candidate : meta.def; + }); + return normalized; + } + onOpen() { + this.display({ + preserveSectionState: false + }); + this.focusDoc = this.contentEl?.ownerDocument ?? document; + this.focusDoc.addEventListener("focusin", this.focusRefreshHandler, true); + } + onClose() { + if (this.focusDoc) { + this.focusDoc.removeEventListener("focusin", this.focusRefreshHandler, true); + this.focusDoc = null; + } + if (this.updateTimer) clearTimeout(this.updateTimer); + this.settings = this.normalizeSettings(this.settings); + this.onUpdate(this.settings); + } + handleFocusRefresh(evt) { + if (!runtimeContext.isViewSet()) { + this.close(); + return; + } + if (!this.contentEl || !(this.contentEl.contains(evt.target) || this.modalEl.contains(evt.target))) + return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + const allElements = runtimeContext.ea.getViewElements(); + const settingsRoot = runtimeContext.getSettingsRootNode(sel, allElements) ?? sel; + const rootCfg = runtimeContext.getRootConfigForNode(settingsRoot); + const nextSettings = this.normalizeSettings(rootCfg?.layoutSettings); + if (!nextSettings) return; + const currentSig = JSON.stringify(this.settings); + const nextSig = JSON.stringify(nextSettings); + if (currentSig === nextSig) return; + this.settings = nextSettings; + this.display({ + preserveSectionState: true + }); + } + triggerUpdate() { + if (this.updateTimer) clearTimeout(this.updateTimer); + this.updateTimer = setTimeout(() => { + this.settings = this.normalizeSettings(this.settings); + this.onUpdate(this.settings); + this.updateTimer = null; + }, 500); + } + display({ preserveSectionState = true } = {}) { + const { contentEl } = this; + let lastScrollPosition = 0; + const previousSectionState = {}; + const existingContainer = contentEl.querySelector(".layout-settings-container"); + if (existingContainer) { + lastScrollPosition = existingContainer.scrollTop; + if (preserveSectionState) { + existingContainer.querySelectorAll("details[data-layout-section]").forEach((detailsEl) => { + const sectionKey = detailsEl.getAttribute("data-layout-section"); + if (sectionKey) previousSectionState[sectionKey] = detailsEl.open; + }); + } + } + contentEl.empty(); + contentEl.createEl("h2", { + text: runtimeContext.t("MODAL_LAYOUT_TITLE") + }); + const container = contentEl.createDiv(); + container.addClass("layout-settings-container"); + container.style.maxHeight = "70vh"; + container.style.overflowY = "auto"; + container.style.paddingRight = "10px"; + const groupedKeys = {}; + Object.keys(runtimeContext.LAYOUT_METADATA).forEach((key) => { + const section = runtimeContext.LAYOUT_METADATA[key].section; + if (!groupedKeys[section]) groupedKeys[section] = []; + groupedKeys[section].push(key); + }); + const renderSection = (sectionKey, title) => { + if (!groupedKeys[sectionKey]) return; + const details = container.createEl("details", { + attr: { + "data-layout-section": sectionKey + } + }); + details.open = preserveSectionState ? previousSectionState[sectionKey] ?? false : false; + details.style.marginBottom = "10px"; + details.style.border = "1px solid var(--background-modifier-border)"; + details.style.borderRadius = "5px"; + const summary = details.createEl("summary"); + summary.style.padding = "10px"; + summary.style.fontWeight = "bold"; + summary.style.cursor = "pointer"; + summary.style.backgroundColor = "var(--background-secondary)"; + summary.innerText = title; + const content = details.createDiv(); + content.style.padding = "10px"; + groupedKeys[sectionKey].forEach((key) => { + const meta = runtimeContext.LAYOUT_METADATA[key]; + const setting = new runtimeContext.ea.obsidian.Setting(content).setName(meta.name).setDesc(meta.desc); + let valLabel; + let resetButtonComp; + const updateResetButton = (val) => { + if (!resetButtonComp) return; + const isModified = Math.abs(val - meta.def) > 1e-4; + const el = resetButtonComp.extraSettingsEl; + el.style.opacity = isModified ? "1" : "0"; + el.style.pointerEvents = isModified ? "auto" : "none"; + el.style.cursor = isModified ? "pointer" : "default"; + if (isModified) el.setAttribute("tabindex", "0"); + else el.setAttribute("tabindex", "-1"); + }; + setting.addSlider( + (slider) => slider.setLimits(meta.min, meta.max, meta.step).setValue(this.settings[key] ?? meta.def).onChange((value) => { + this.settings[key] = value; + valLabel.setText(String(value.toFixed(meta.step < 1 ? 1 : 0))); + updateResetButton(value); + this.triggerUpdate(); + }) + ); + setting.settingEl.createDiv("", (el) => { + valLabel = el; + el.style.minWidth = "3em"; + el.style.textAlign = "right"; + el.innerText = String(this.settings[key].toFixed(meta.step < 1 ? 1 : 0)); + }); + setting.addExtraButton((btn) => { + resetButtonComp = btn; + btn.setIcon("rotate-ccw").setTooltip(runtimeContext.t("TOOLTIP_RESET_TO_DEFAULT")).onClick(() => { + this.settings[key] = meta.def; + this.triggerUpdate(); + this.display(); + }); + updateResetButton(this.settings[key]); + }); + }); + }; + renderSection("SECTION_GENERAL", runtimeContext.t("SECTION_GENERAL")); + renderSection("SECTION_RADIAL", runtimeContext.t("SECTION_RADIAL")); + renderSection("SECTION_DIRECTIONAL", runtimeContext.t("SECTION_DIRECTIONAL")); + renderSection("SECTION_VERTICAL", runtimeContext.t("SECTION_VERTICAL")); + renderSection("SECTION_VISUALS", runtimeContext.t("SECTION_VISUALS")); + renderSection("SECTION_MANUAL", runtimeContext.t("SECTION_MANUAL")); + const footer = contentEl.createDiv(); + footer.style.marginTop = "20px"; + footer.style.display = "flex"; + footer.style.justifyContent = "space-between"; + new runtimeContext.ea.obsidian.Setting(footer).addButton( + (btn) => btn.setButtonText(runtimeContext.t("LAYOUT_RESET")).setWarning().onClick(() => { + Object.keys(runtimeContext.LAYOUT_METADATA).forEach((k) => { + this.settings[k] = runtimeContext.LAYOUT_METADATA[k].def; + }); + this.triggerUpdate(); + this.display(); + }) + ).addButton( + (btn) => btn.setButtonText(runtimeContext.t("LAYOUT_SAVE")).setCta().onClick(() => { + if (this.updateTimer) clearTimeout(this.updateTimer); + this.onUpdate(this.settings); + this.close(); + }) + ); + container.scrollTop = lastScrollPosition; + } + } + return { LayoutConfigModal }; + } + + // src/scripts/mindmap-builder/inputControls.js + function createInputControls(runtimeContext) { + const renderInput = (container, isFloating = false) => { + runtimeContext.linkSuggester?.close(); + runtimeContext.linkSuggester = null; + runtimeContext.ignoreFocusChanges = true; + setTimeout(() => { + runtimeContext.ignoreFocusChanges = false; + if (runtimeContext.lastFocusedInput) runtimeContext.lastFocusedInput.focus(); + }, 200); + container.empty(); + runtimeContext.pinBtn = runtimeContext.submapRootBtn = runtimeContext.refreshBtn = runtimeContext.dockBtn = runtimeContext.inputEl = runtimeContext.ontologyEl = null; + runtimeContext.foldBtnL0 = runtimeContext.foldBtnL1 = runtimeContext.foldBtnAll = null; + runtimeContext.boundaryBtn = runtimeContext.panelExpandBtn = null; + runtimeContext.floatingGroupBtn = runtimeContext.floatingBoxBtn = runtimeContext.floatingZoomBtn = null; + runtimeContext.importOutlineBtn = runtimeContext.toggleCheckboxBtn = null; + runtimeContext.calendarBtn = null; + runtimeContext.inputRow = new runtimeContext.ea.obsidian.Setting(container); + let secondaryButtonContainer = null; + if (!isFloating) { + runtimeContext.inputRow.settingEl.style.display = "block"; + runtimeContext.inputRow.controlEl.style.display = "block"; + runtimeContext.inputRow.controlEl.style.width = "100%"; + runtimeContext.inputRow.controlEl.style.marginTop = "8px"; + } else { + container.style.width = "85vw"; + container.style.maxWidth = "calc((var(--icon-size) + 2 * var(--size-2-3)) * 18)"; + runtimeContext.inputRow.settingEl.style.border = "none"; + runtimeContext.inputRow.settingEl.style.padding = "0"; + runtimeContext.inputRow.infoEl.style.display = "none"; + secondaryButtonContainer = container.createDiv(); + secondaryButtonContainer.style.display = runtimeContext.isFloatingPanelExpanded ? "flex" : "none"; + secondaryButtonContainer.style.justifyContent = "flex-end"; + secondaryButtonContainer.style.flexWrap = "wrap"; + secondaryButtonContainer.style.gap = "0px"; + secondaryButtonContainer.style.marginTop = "6px"; + } + runtimeContext.inputRow.controlEl.empty(); + const wrapper = runtimeContext.inputRow.controlEl.createDiv("mindmap-input-wrapper"); + runtimeContext.ontologyEl = wrapper.createEl("input", { + type: "text", + cls: "mindmap-input-ontology", + placeholder: runtimeContext.t("ONTOLOGY_PLACEHOLDER") + }); + runtimeContext.inputEl = wrapper.createEl("input", { + type: "text", + cls: "mindmap-input-main", + placeholder: runtimeContext.t("INPUT_PLACEHOLDER") + }); + runtimeContext.inputEl.addEventListener("input", () => runtimeContext.updateUI()); + runtimeContext.ontologyEl.addEventListener("input", () => runtimeContext.updateUI()); + const updateFocusState = (focusedElement) => { + if (runtimeContext.ignoreFocusChanges) return; + runtimeContext.isOntologyFocused = focusedElement === runtimeContext.ontologyEl; + runtimeContext.lastFocusedInput = focusedElement; + if (runtimeContext.isOntologyFocused) { + runtimeContext.ontologyEl.addClass("is-focused"); + runtimeContext.inputEl.addClass("is-shrunk"); + } else { + runtimeContext.ontologyEl.removeClass("is-focused"); + runtimeContext.inputEl.removeClass("is-shrunk"); + } + }; + const onFocus = (el) => { + if (runtimeContext.ignoreFocusChanges) return; + updateFocusState(el); + runtimeContext.registerObsidianHotkeyOverrides(); + runtimeContext.ensureNodeSelected(); + runtimeContext.updateUI(); + }; + if (runtimeContext.isOntologyFocused) { + runtimeContext.ontologyEl.addClass("is-focused"); + runtimeContext.inputEl.addClass("is-shrunk"); + runtimeContext.lastFocusedInput = runtimeContext.ontologyEl; + } else { + runtimeContext.ontologyEl.removeClass("is-focused"); + runtimeContext.inputEl.removeClass("is-shrunk"); + runtimeContext.lastFocusedInput = runtimeContext.inputEl; + } + runtimeContext.ontologyEl.addEventListener("focus", () => onFocus(runtimeContext.ontologyEl)); + runtimeContext.inputEl.addEventListener("focus", () => onFocus(runtimeContext.inputEl)); + const onBlur = () => { + if (runtimeContext.ignoreFocusChanges) return; + runtimeContext.removeObsidianHotkeyOverrides(); + runtimeContext.saveSettings(); + }; + runtimeContext.ontologyEl.addEventListener("blur", onBlur); + runtimeContext.inputEl.addEventListener("blur", onBlur); + runtimeContext.linkSuggester = runtimeContext.ea.attachInlineLinkSuggester( + runtimeContext.inputEl, + runtimeContext.inputRow.settingEl + ); + if (runtimeContext.linkSuggester) { + runtimeContext.linkSuggester.modifyInput = (input) => input.replace(/\./g, " "); + } + const ariaHelp = [ + `${runtimeContext.getActionLabel(runtimeContext.ACTION_ADD)} (Enter)`, + `${runtimeContext.getActionLabel(runtimeContext.ACTION_ADD_FOLLOW)} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_ADD_FOLLOW)}`, + `${runtimeContext.getActionLabel(runtimeContext.ACTION_ADD_FOLLOW_FOCUS)} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_ADD_FOLLOW_FOCUS)}`, + `${runtimeContext.getActionLabel(runtimeContext.ACTION_ADD_FOLLOW_ZOOM)} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_ADD_FOLLOW_ZOOM)}` + ].join("\n"); + runtimeContext.inputEl.ariaLabel = ariaHelp; + let dockedButtonContainer; + if (!isFloating) { + dockedButtonContainer = runtimeContext.inputRow.controlEl.createDiv(); + dockedButtonContainer.style.display = "flex"; + dockedButtonContainer.style.justifyContent = "flex-end"; + dockedButtonContainer.style.flexWrap = "wrap"; + dockedButtonContainer.style.gap = "2px"; + dockedButtonContainer.style.marginTop = "6px"; + } + const addButton = (cb, moveToSecondary = false) => { + runtimeContext.inputRow.addExtraButton((btn) => { + cb(btn); + if (btn.buttonEl) btn.buttonEl.tabIndex = 0; + if (btn.extraSettingsEl) btn.extraSettingsEl.tabIndex = 0; + const el = btn.extraSettingsEl; + if (!el) return; + if (!isFloating && dockedButtonContainer) { + dockedButtonContainer.appendChild(el); + } else if (isFloating && moveToSecondary && secondaryButtonContainer) { + secondaryButtonContainer.appendChild(el); + } + }); + }; + addButton((btn) => { + runtimeContext.editBtn = btn; + btn.setIcon("pencil"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_EDIT_NODE")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_EDIT)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_EDIT); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_EDIT)); + }, false); + addButton((btn) => { + runtimeContext.pinBtn = btn; + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_PIN_INIT")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_PIN)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_PIN); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_PIN)); + }, false); + addButton((btn) => { + runtimeContext.toggleCheckboxBtn = btn; + btn.setIcon("square-check-big"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_TOGGLE_CHECKBOX")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_TOGGLE_CHECKBOX)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_TOGGLE_CHECKBOX); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_TOGGLE_CHECKBOX)); + }, true); + addButton((btn) => { + runtimeContext.calendarBtn = btn; + btn.setIcon("calendar"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_CALENDAR")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_CALENDAR)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_CALENDAR); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_CALENDAR)); + }, true); + addButton((btn) => { + runtimeContext.toggleEmbedBtn = btn; + btn.setIcon("file-sliders"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_TOGGLE_EMBED")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_TOGGLE_EMBED)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_TOGGLE_EMBED); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_TOGGLE_EMBED)); + }, true); + runtimeContext.toggleFloatingExtras = null; + if (isFloating) { + runtimeContext.toggleFloatingExtras = () => { + runtimeContext.isFloatingPanelExpanded = !runtimeContext.isFloatingPanelExpanded; + runtimeContext.panelExpandBtn.setIcon( + runtimeContext.isFloatingPanelExpanded ? "panel-bottom-open" : "panel-top-open" + ); + if (secondaryButtonContainer) { + secondaryButtonContainer.style.display = runtimeContext.isFloatingPanelExpanded ? "flex" : "none"; + if (runtimeContext.floatingInputModal && runtimeContext.floatingInputModal.modalEl) { + runtimeContext.floatingInputModal.modalEl.style.maxHeight = runtimeContext.isFloatingPanelExpanded ? "unset" : runtimeContext.FLOAT_MODAL_MAX_HEIGHT; + } + } + }; + addButton((btn) => { + runtimeContext.panelExpandBtn = btn; + btn.setIcon( + runtimeContext.isFloatingPanelExpanded ? "panel-bottom-open" : "panel-top-open" + ); + btn.setTooltip(runtimeContext.t("TOOLTIP_TOGGLE_FLOATING_EXTRAS")); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_TOGGLE_FLOATING_EXTRAS); + btn.onClick( + () => runtimeContext.performAction(runtimeContext.ACTION_TOGGLE_FLOATING_EXTRAS) + ); + }, false); + addButton((btn) => { + runtimeContext.floatingGroupBtn = btn; + btn.setIcon("group"); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_TOGGLE_GROUP); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_TOGGLE_GROUP)); + }, true); + addButton((btn) => { + runtimeContext.floatingBoxBtn = btn; + btn.setIcon("rectangle-horizontal"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_TOGGLE_BOX")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_BOX)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_BOX); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_BOX)); + }, true); + addButton((btn) => { + runtimeContext.floatingZoomBtn = btn; + btn.setIcon("scan-search"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_ZOOM_CYCLE")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_ZOOM)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_ZOOM); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_ZOOM)); + }, true); + } + addButton((btn) => { + runtimeContext.focusBtn = btn; + btn.setIcon("scan-eye"); + btn.setTooltip( + `${runtimeContext.t("ACTION_LABEL_FOCUS")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_FOCUS)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_FOCUS); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_FOCUS)); + }, true); + addButton((btn) => { + runtimeContext.boundaryBtn = btn; + btn.setIcon("cloud"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_TOGGLE_BOUNDARY")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_TOGGLE_BOUNDARY)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_TOGGLE_BOUNDARY); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_TOGGLE_BOUNDARY)); + }, true); + addButton((btn) => { + runtimeContext.submapRootBtn = btn; + btn.setIcon("map-pin-plus-inside"); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_TOGGLE_SUBMAP_ROOT); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_TOGGLE_SUBMAP_ROOT)); + }, true); + addButton((btn) => { + runtimeContext.foldBtnL0 = btn; + btn.setIcon("wifi-low"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_FOLD_BRANCH")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_FOLD)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_FOLD); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_FOLD)); + }, true); + addButton((btn) => { + runtimeContext.foldBtnL1 = btn; + btn.setIcon("wifi-high"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_FOLD_L1_BRANCH")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_FOLD_L1)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_FOLD_L1); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_FOLD_L1)); + }, true); + addButton((btn) => { + runtimeContext.foldBtnAll = btn; + btn.setIcon("wifi"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_FOLD_ALL")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_FOLD_ALL)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_FOLD_ALL); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_FOLD_ALL)); + }, true); + addButton((btn) => { + runtimeContext.refreshBtn = btn; + btn.setIcon("refresh-ccw"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_REFRESH")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_REARRANGE)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_REARRANGE); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_REARRANGE)); + }, true); + addButton((btn) => { + runtimeContext.copyBtn = btn; + btn.setIcon("copy"); + btn.setTooltip( + `${runtimeContext.t("ACTION_LABEL_COPY")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_COPY)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_COPY); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_COPY)); + }, true); + addButton((btn) => { + runtimeContext.cutBtn = btn; + btn.setIcon("scissors"); + btn.setTooltip( + `${runtimeContext.t("ACTION_LABEL_CUT")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_CUT)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_CUT); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_CUT)); + }, true); + addButton((btn) => { + btn.setIcon("clipboard"); + btn.setTooltip( + `${runtimeContext.t("ACTION_LABEL_PASTE")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_PASTE)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_PASTE); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_PASTE)); + }, true); + addButton((btn) => { + runtimeContext.importOutlineBtn = btn; + btn.setIcon("list-tree"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_IMPORT_OUTLINE")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_IMPORT_OUTLINE)}` + ); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_IMPORT_OUTLINE); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_IMPORT_OUTLINE)); + }, true); + addButton((btn) => { + runtimeContext.dockBtn = btn; + btn.setIcon(isFloating ? "dock" : "external-link"); + btn.extraSettingsEl.setAttr("action", runtimeContext.ACTION_DOCK_UNDOCK); + btn.setTooltip( + `${isFloating ? runtimeContext.t("TOOLTIP_DOCK") : runtimeContext.t("TOOLTIP_UNDOCK")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_DOCK_UNDOCK)}` + ); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_DOCK_UNDOCK)); + }, true); + runtimeContext.updateUI(); + }; + return { renderInput }; + } + + // src/scripts/mindmap-builder/HotkeyRecorder.ts + var HotkeyRecorder = class { + constructor(keymap, createScope) { + this.keymap = keymap; + this.createScope = createScope; + } + keymap; + createScope; + finish = null; + /** Starts one recording, releasing the previous session before pushing a new scope. */ + start(onKey, onFinish) { + this.cancel(); + const scope = this.createScope(); + let finished = false; + const finish = () => { + if (finished) return; + finished = true; + if (this.finish === finish) this.finish = null; + try { + this.keymap.popScope(scope); + } finally { + onFinish(); + } + }; + this.finish = finish; + try { + scope.register(null, null, (event) => { + if (finished) return void 0; + if (["Control", "Shift", "Alt", "Meta"].includes(event.key)) return false; + try { + onKey(event); + } finally { + finish(); + } + return false; + }); + this.keymap.pushScope(scope); + } catch (error) { + finish(); + throw error; + } + } + /** Idempotently releases the recording scope from its original window's stack. */ + cancel() { + this.finish?.(); + } + }; + + // src/scripts/mindmap-builder/sidepanelControls.js + function createSidepanelControls(runtimeContext) { + const hotkeyRecorder = new HotkeyRecorder( + app.keymap, + () => new runtimeContext.ea.obsidian.Scope() + ); + runtimeContext.ea.registerCleanup?.(() => hotkeyRecorder.cancel()); + const renderBody = (contentEl) => { + runtimeContext.bodyContainer = contentEl.createDiv(); + runtimeContext.bodyContainer.style.width = "100%"; + runtimeContext.bodyContainer.createEl("hr"); + const presetSetting = new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("PRESET_LABEL")).addDropdown((d) => { + runtimeContext.presetDropdown = d; + runtimeContext.refreshPresetDropdown(); + d.onChange(async (v) => { + runtimeContext.activePresetName = v; + runtimeContext.setVal(runtimeContext.K_ACTIVE_PRESET, v); + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (sel) { + await runtimeContext.applyPresetToMap(v, sel); + new runtimeContext.Notice(runtimeContext.t("NOTICE_PRESET_APPLIED")); + } else { + runtimeContext.applyPresetToGlobals(v); + runtimeContext.updateUI(); + } + }); + }); + presetSetting.addExtraButton((btn) => { + runtimeContext.presetSaveBtn = btn; + btn.setIcon("save").setTooltip(runtimeContext.t("PRESET_BTN_SAVE")).onClick(async () => { + if (!runtimeContext.activePresetName) return; + runtimeContext.mapPresets[runtimeContext.activePresetName] = runtimeContext.extractConfigFromGlobals(); + runtimeContext.setVal(runtimeContext.K_PRESETS, runtimeContext.mapPresets, true); + new runtimeContext.Notice(runtimeContext.t("NOTICE_PRESET_SAVED")); + runtimeContext.updateUI(); + }); + }); + presetSetting.addExtraButton((btn) => { + runtimeContext.presetTrashBtn = btn; + btn.setIcon("trash-2").setTooltip(runtimeContext.t("PRESET_BTN_DELETE")).onClick(async () => { + if (!runtimeContext.activePresetName || runtimeContext.activePresetName === "Default") + return; + delete runtimeContext.mapPresets[runtimeContext.activePresetName]; + runtimeContext.activePresetName = "Default"; + runtimeContext.setVal(runtimeContext.K_PRESETS, runtimeContext.mapPresets, true); + runtimeContext.setVal(runtimeContext.K_ACTIVE_PRESET, runtimeContext.activePresetName); + new runtimeContext.Notice(runtimeContext.t("NOTICE_PRESET_DELETED")); + runtimeContext.refreshPresetDropdown(); + runtimeContext.updateUI(); + }); + }); + presetSetting.addExtraButton((btn) => { + runtimeContext.presetPlusBtn = btn; + btn.setIcon("plus").setTooltip(runtimeContext.t("PRESET_BTN_NEW")).onClick(async () => { + const name = await runtimeContext.utils.inputPrompt( + runtimeContext.t("PROMPT_NEW_PRESET_NAME") + ); + if (name && name.trim()) { + const trimmed = name.trim(); + runtimeContext.mapPresets[trimmed] = runtimeContext.extractConfigFromGlobals(); + runtimeContext.activePresetName = trimmed; + runtimeContext.setVal(runtimeContext.K_PRESETS, runtimeContext.mapPresets, true); + runtimeContext.setVal(runtimeContext.K_ACTIVE_PRESET, runtimeContext.activePresetName); + runtimeContext.refreshPresetDropdown(); + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (sel) { + await runtimeContext.updateRootNodeCustomData( + { presetName: runtimeContext.activePresetName }, + sel + ); + } + new runtimeContext.Notice(runtimeContext.t("NOTICE_PRESET_SAVED")); + runtimeContext.updateUI(); + } + }); + }); + presetSetting.addExtraButton((btn) => { + runtimeContext.presetApplyBtn = btn; + btn.setIcon("refresh-cw").setTooltip(runtimeContext.t("PRESET_BTN_APPLY")).onClick(async () => { + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (sel && runtimeContext.activePresetName) { + await runtimeContext.applyPresetToMap(runtimeContext.activePresetName, sel); + new runtimeContext.Notice(runtimeContext.t("NOTICE_PRESET_APPLIED")); + } + }); + }); + runtimeContext.presetWarningEl = runtimeContext.bodyContainer.createEl("div", { + text: runtimeContext.t("PRESET_WARNING_MODIFIED"), + cls: "mod-warning", + attr: { + style: "font-size: 0.85em; margin-top: -10px; margin-bottom: 10px; display: none; text-align: right;" + } + }); + runtimeContext.bodyContainer.createEl("hr"); + const zoomSetting = new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer); + zoomSetting.setName(runtimeContext.t("LABEL_ZOOM_LEVEL")).addDropdown((d) => { + runtimeContext.ZOOM_TYPES.forEach((key) => d.addOption(key, key)); + d.setValue(runtimeContext.zoomLevel); + d.onChange((v) => { + runtimeContext.zoomLevel = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_ZOOM, v); + runtimeContext.zoomToFit(); + }); + }); + zoomSetting.addExtraButton((btn) => { + runtimeContext.zoomBtn = btn; + btn.setIcon("scan-search").setTooltip( + `${runtimeContext.t("TOOLTIP_ZOOM_CYCLE")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_ZOOM)}` + ).onClick(() => runtimeContext.performAction(runtimeContext.ACTION_ZOOM)); + }); + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_GROWTH_STRATEGY")).addDropdown((d) => { + runtimeContext.strategyDropdown = d; + runtimeContext.GROWTH_TYPES.forEach((key) => d.addOption(key, key)); + d.setValue(runtimeContext.currentModalGrowthMode); + d.onChange(async (v) => { + runtimeContext.currentModalGrowthMode = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_GROWTH, v); + if (runtimeContext.fillSweepToggleSetting) { + runtimeContext.fillSweepToggleSetting.settingEl.style.display = v === "Radial" ? "" : "none"; + } + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + await runtimeContext.updateRootNodeCustomData( + { + growthMode: v + }, + sel + ); + await runtimeContext.refreshMapLayout(sel); + }); + }); + runtimeContext.fillSweepToggleSetting = new runtimeContext.ea.obsidian.Setting( + runtimeContext.bodyContainer + ).setName(runtimeContext.t("LABEL_FILL_SWEEP")).setDesc(runtimeContext.t("DESC_FILL_SWEEP")).addToggle((t) => { + runtimeContext.fillSweepToggle = t; + t.setValue(runtimeContext.fillSweep).onChange(async (v) => { + runtimeContext.fillSweep = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_FILL_SWEEP, v); + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + await runtimeContext.updateRootNodeCustomData( + { + fillSweep: v + }, + sel + ); + await runtimeContext.refreshMapLayout(sel); + }); + }); + if (runtimeContext.currentModalGrowthMode !== "Radial") { + runtimeContext.fillSweepToggleSetting.settingEl.style.display = "none"; + } + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_AUTO_LAYOUT")).addToggle((t) => { + runtimeContext.autoLayoutToggle = t; + t.setValue(!runtimeContext.autoLayoutDisabled).onChange(async (v) => { + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + runtimeContext.autoLayoutDisabled = !v; + if (runtimeContext.disableTabEvents) return; + await runtimeContext.updateRootNodeCustomData( + { + autoLayoutDisabled: runtimeContext.autoLayoutDisabled + }, + sel + ); + await runtimeContext.refreshMapLayout(sel); + }); + }).addExtraButton( + (btn) => btn.setIcon("pencil-ruler").setTooltip(runtimeContext.t("TOOLTIP_CONFIGURE_LAYOUT")).onClick(() => { + const modal = new runtimeContext.LayoutConfigModal( + app, + runtimeContext.layoutSettings, + async (newSettings) => { + runtimeContext.layoutSettings = newSettings; + runtimeContext.setVal(runtimeContext.K_LAYOUT, runtimeContext.layoutSettings, true); + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + await runtimeContext.updateRootNodeCustomData( + { + layoutSettings: newSettings + }, + sel + ); + const allElements = runtimeContext.ea.getViewElements(); + const hierarchy = runtimeContext.getHierarchy(sel, allElements); + const masterRoot = allElements.find((el) => el.id === hierarchy.rootId) ?? sel; + await runtimeContext.refreshMapLayout(masterRoot); + } + ); + modal.open(); + }) + ); + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_GROUP_BRANCHES")).addToggle( + (t) => t.setValue(runtimeContext.groupBranches).onChange(async (v) => { + if (!runtimeContext.isViewSet()) return; + runtimeContext.groupBranches = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_GROUP, v); + await runtimeContext.refreshMapLayout(); + runtimeContext.updateUI(); + }) + ).addExtraButton((btn) => { + runtimeContext.toggleGroupBtn = btn; + btn.setIcon("group"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_TOGGLE_GROUP_BTN")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_TOGGLE_GROUP)}` + ); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_TOGGLE_GROUP)); + }); + runtimeContext.bodyContainer.createEl("hr"); + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_BOX_CHILD_NODES")).addToggle((t) => { + runtimeContext.boxToggle = t; + t.setValue(runtimeContext.boxChildren).onChange(async (v) => { + runtimeContext.boxChildren = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_BOX, v); + await runtimeContext.updateRootNodeCustomData({ + boxChildren: v + }); + }); + }).addExtraButton((btn) => { + runtimeContext.boxBtn = btn; + btn.setIcon("rectangle-horizontal"); + btn.setTooltip( + `${runtimeContext.t("TOOLTIP_TOGGLE_BOX")} ${runtimeContext.getActionHotkeyString(runtimeContext.ACTION_BOX)}` + ); + btn.onClick(() => runtimeContext.performAction(runtimeContext.ACTION_BOX)); + }); + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_ROUNDED_CORNERS")).addToggle((t) => { + runtimeContext.roundToggle = t; + t.setValue(runtimeContext.roundedCorners).onChange(async (v) => { + runtimeContext.roundedCorners = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_ROUND, v); + await runtimeContext.updateRootNodeCustomData({ + roundedCorners: v + }); + }); + }); + runtimeContext.bodyContainer.createEl("hr"); + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_ARROW_TYPE")).addToggle((t) => { + runtimeContext.arrowTypeToggle = t; + t.setValue(runtimeContext.arrowType === "curved").onChange(async (v) => { + runtimeContext.arrowType = v ? "curved" : "straight"; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_ARROW_TYPE, runtimeContext.arrowType); + if (!runtimeContext.isViewSet()) return; + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + await runtimeContext.updateRootNodeCustomData( + { + arrowType: runtimeContext.arrowType + }, + sel + ); + await runtimeContext.refreshMapLayout(sel); + }); + }); + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_USE_SCENE_STROKE")).setDesc(runtimeContext.t("DESC_USE_SCENE_STROKE")).addToggle((t) => { + runtimeContext.strokeToggle = t; + t.setValue(!runtimeContext.isSolidArrow).onChange(async (v) => { + runtimeContext.isSolidArrow = !v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_ARROWSTROKE, !v); + await runtimeContext.updateRootNodeCustomData({ + isSolidArrow: !v + }); + }); + }); + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_BRANCH_SCALE")).addDropdown((d) => { + runtimeContext.branchScaleDropdown = d; + runtimeContext.BRANCH_SCALE_TYPES.forEach((key) => d.addOption(key, key)); + d.setValue(runtimeContext.branchScale); + d.onChange(async (v) => { + const oldScale = runtimeContext.branchScale; + runtimeContext.branchScale = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_BRANCH_SCALE, v); + const info = await runtimeContext.updateRootNodeCustomData({ + branchScale: v + }); + if (info) { + await runtimeContext.updateBranchStrokes( + info.rootId, + runtimeContext.baseStrokeWidth, + oldScale, + runtimeContext.baseStrokeWidth, + runtimeContext.branchScale + ); + } + }); + }); + let baseWidthDisplay; + let baseWidthUpdateTimer = null; + let baseWidthSnapshot = null; + const baseWidthSetting = new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_BASE_WIDTH")).addSlider((s) => { + runtimeContext.baseWidthSlider = s; + s.setLimits(0.2, 16, 0.1).setValue(runtimeContext.baseStrokeWidth).onChange((v) => { + if (baseWidthUpdateTimer) clearTimeout(baseWidthUpdateTimer); + if (!runtimeContext.disableTabEvents && baseWidthSnapshot === null) + baseWidthSnapshot = runtimeContext.baseStrokeWidth; + runtimeContext.baseStrokeWidth = v; + baseWidthDisplay.setText(`${v}`); + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_BASE_WIDTH, v); + baseWidthUpdateTimer = setTimeout(async () => { + const info = await runtimeContext.updateRootNodeCustomData({ + baseStrokeWidth: v + }); + if (info) { + await runtimeContext.updateBranchStrokes( + info.rootId, + baseWidthSnapshot, + runtimeContext.branchScale, + runtimeContext.baseStrokeWidth, + runtimeContext.branchScale + ); + } + baseWidthSnapshot = null; + baseWidthUpdateTimer = null; + }, 500); + }); + }); + baseWidthDisplay = baseWidthSetting.descEl.createSpan({ + text: `${runtimeContext.baseStrokeWidth}`, + attr: { + style: "margin-left:10px; font-weight:bold;" + } + }); + if (runtimeContext.baseWidthSlider) + runtimeContext.baseWidthSlider.valLabelEl = baseWidthDisplay; + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_MULTICOLOR_BRANCHES")).addToggle((t) => { + runtimeContext.colorToggle = t; + t.setValue(runtimeContext.multicolor).onChange(async (v) => { + runtimeContext.multicolor = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_MULTICOLOR, v); + await runtimeContext.updateRootNodeCustomData({ + multicolor: v + }); + }); + }).addExtraButton( + (btn) => btn.setIcon("palette").setTooltip(runtimeContext.t("TOOLTIP_CONFIGURE_PALETTE")).onClick(() => { + const modal = new runtimeContext.PaletteManagerModal( + app, + runtimeContext.customPalette, + (newSettings) => { + runtimeContext.customPalette = newSettings; + runtimeContext.setVal(runtimeContext.K_PALETTE, runtimeContext.customPalette, true); + } + ); + modal.open(); + }) + ); + runtimeContext.bodyContainer.createEl("hr"); + let sliderValDisplay; + const sliderSetting = new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_MAX_WRAP_WIDTH")).addSlider((s) => { + runtimeContext.widthSlider = s; + s.setLimits( + runtimeContext.WRAP_WIDTH_MIN, + runtimeContext.WRAP_WIDTH_MAX, + runtimeContext.WRAP_WIDTH_STEP + ).setValue(runtimeContext.maxWidth).onChange(async (v) => { + runtimeContext.maxWidth = v; + sliderValDisplay.setText(`${v}px`); + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_WIDTH, v); + await runtimeContext.updateRootNodeCustomData({ + maxWrapWidth: v + }); + }); + }); + sliderValDisplay = sliderSetting.descEl.createSpan({ + text: `${runtimeContext.maxWidth}px`, + attr: { + style: "margin-left:10px; font-weight:bold;" + } + }); + if (runtimeContext.widthSlider) runtimeContext.widthSlider.valLabelEl = sliderValDisplay; + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_CENTER_TEXT")).setDesc(runtimeContext.t("DESC_CENTER_TEXT")).addToggle((t) => { + runtimeContext.centerToggle = t; + t.setValue(runtimeContext.centerText).onChange(async (v) => { + runtimeContext.centerText = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_CENTERTEXT, v); + await runtimeContext.updateRootNodeCustomData({ + centerText: v + }); + }); + }); + new runtimeContext.ea.obsidian.Setting(runtimeContext.bodyContainer).setName(runtimeContext.t("LABEL_FONT_SIZES")).addDropdown((d) => { + runtimeContext.fontSizeDropdown = d; + runtimeContext.FONT_SCALE_TYPES.forEach((key) => d.addOption(key, key)); + d.setValue(runtimeContext.fontsizeScale); + d.onChange(async (v) => { + runtimeContext.fontsizeScale = v; + if (runtimeContext.disableTabEvents) return; + runtimeContext.setVal(runtimeContext.K_FONTSIZE, v); + await runtimeContext.updateRootNodeCustomData({ + fontsizeScale: v + }); + }); + }); + runtimeContext.bodyContainer.createEl("hr"); + const hkDetails = runtimeContext.bodyContainer.createEl("details", { + attr: { + style: "margin-right: 5px; margin-left: 5px;" + } + }); + hkDetails.createEl("summary", { + text: runtimeContext.t("HOTKEY_SECTION_TITLE"), + attr: { + style: "cursor: pointer; font-weight: bold;" + } + }); + const hkContainer = hkDetails.createDiv(); + const hint = hkContainer.createEl("p", { + text: runtimeContext.t("HOTKEY_HINT"), + attr: { + style: "color: var(--text-muted); font-size: 0.85em; margin-bottom: 10px;" + } + }); + const refreshHotkeys = () => { + runtimeContext.RUNTIME_HOTKEYS = runtimeContext.generateRuntimeHotkeys(); + runtimeContext.registerObsidianHotkeyOverrides(); + runtimeContext.updateKeyHandlerLocation(); + }; + const saveHotkeys = () => { + const hotkeysToSave = runtimeContext.userHotkeys.map((h) => { + const { isInputOnly, requiresNode, isNavigation, hidden, ...configurableProps } = h; + return configurableProps; + }); + runtimeContext.setVal(runtimeContext.K_HOTKEYS, hotkeysToSave, true); + refreshHotkeys(); + }; + const isModified = (current) => { + const def = runtimeContext.DEFAULT_HOTKEYS.find((d) => d.action === current.action); + if (!def) return false; + const k1 = current.code || current.key; + const k2 = def.code || def.key; + if (k1 !== k2) return true; + if (current.modifiers.length !== def.modifiers.length) return true; + return !current.modifiers.every((m) => def.modifiers.includes(m)); + }; + const recordHotkey = (btn, hIndex, onUpdate) => { + hotkeyRecorder.cancel(); + const originalText = btn.innerHTML; + const label = btn.parentElement.querySelector(".setting-hotkey"); + btn.innerHTML = runtimeContext.t("RECORD_HOTKEY_PROMPT"); + btn.addClass("is-recording"); + runtimeContext.isRecordingHotkey = true; + const cancel = () => hotkeyRecorder.cancel(); + const cleanup = () => { + btn.innerHTML = originalText; + btn.removeClass("is-recording"); + if (runtimeContext.cancelHotkeyRecording === cancel) { + runtimeContext.isRecordingHotkey = false; + runtimeContext.cancelHotkeyRecording = null; + } + }; + runtimeContext.cancelHotkeyRecording = cancel; + const handler = (e) => { + if (e.key === "Escape") { + return false; + } + if (["Control", "Shift", "Alt", "Meta"].includes(e.key)) return false; + const mods = []; + if (e.ctrlKey) mods.push("Ctrl"); + if (e.metaKey) mods.push("Meta"); + if (e.altKey) mods.push("Alt"); + if (e.shiftKey) mods.push("Shift"); + let key = e.key; + let code = e.code; + if (key === " ") key = "Space"; + const targetConfig = runtimeContext.userHotkeys[hIndex]; + const isNav = targetConfig.isNavigation; + if (isNav && !["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(key)) { + new runtimeContext.Notice(runtimeContext.t("NOTICE_ACTION_REQUIRES_ARROWS")); + return false; + } + const conflict = runtimeContext.userHotkeys.find((h, i) => { + if (i === hIndex) return false; + const sameMods = h.modifiers.length === mods.length && h.modifiers.every((m) => mods.includes(m)); + if (!sameMods) return false; + if (h.isNavigation && isNav) return true; + if (h.isNavigation && key.startsWith("Arrow")) return true; + const hKey = h.code ? h.code.replace("Key", "").replace("Digit", "") : h.key; + const eKey = code ? code.replace("Key", "").replace("Digit", "") : key; + return hKey.toLowerCase() === eKey.toLowerCase(); + }); + if (conflict) { + label.style.color = "var(--text-error)"; + new runtimeContext.Notice( + runtimeContext.t("NOTICE_CONFLICT_WITH_ACTION", { + action: runtimeContext.getActionLabel(conflict.action) + }), + runtimeContext.NOTICE_DURATION_CONFLICT + ); + setTimeout(() => label.style.color = "", 4e3); + } else { + if (isNav) { + targetConfig.modifiers = mods.map((m) => m === "Ctrl" || m === "Meta" ? "Mod" : m); + } else { + targetConfig.modifiers = mods.map((m) => m === "Ctrl" || m === "Meta" ? "Mod" : m); + if (code && (code.startsWith("Key") || code.startsWith("Digit"))) { + targetConfig.code = code; + delete targetConfig.key; + } else { + targetConfig.key = key; + delete targetConfig.code; + } + } + saveHotkeys(); + if (targetConfig.scope === runtimeContext.SCOPE.global) { + const obsConflict = runtimeContext.getObsidianConflict(targetConfig); + if (obsConflict) { + new runtimeContext.Notice( + runtimeContext.t("NOTICE_OBSIDIAN_HOTKEY_CONFLICT", { + command: obsConflict + }), + runtimeContext.NOTICE_DURATION_GLOBAL_CONFLICT + ); + } + } + if (onUpdate) onUpdate(); + } + return false; + }; + hotkeyRecorder.start(handler, cleanup); + }; + runtimeContext.userHotkeys.forEach((h, index) => { + if (h.hidden) return; + const setting = new runtimeContext.ea.obsidian.Setting(hkContainer).setName( + runtimeContext.getActionLabel(h.action) + ); + setting.settingEl.style.paddingRight = "0"; + setting.settingEl.style.paddingLeft = "0"; + const controlDiv = setting.controlEl; + controlDiv.addClass("setting-item-control"); + let scopeBtn = null; + let updateScopeUI = null; + const hotkeyDisplay = controlDiv.createDiv("setting-command-hotkeys"); + const span = hotkeyDisplay.createSpan("setting-hotkey"); + const restoreBtn = controlDiv.createSpan("clickable-icon setting-restore-hotkey-button"); + const updateRowUI = () => { + span.textContent = runtimeContext.getHotkeyDisplayString(runtimeContext.userHotkeys[index]); + restoreBtn.style.display = isModified(runtimeContext.userHotkeys[index]) ? "" : "none"; + if (updateScopeUI) updateScopeUI(); + const existingAlert = hotkeyDisplay.querySelector(".hotkey-conflict-icon"); + if (existingAlert) existingAlert.remove(); + span.removeClass("has-conflict"); + span.style.color = ""; + if (runtimeContext.userHotkeys[index].scope === runtimeContext.SCOPE.global) { + const conflict = runtimeContext.getObsidianConflict(runtimeContext.userHotkeys[index]); + if (conflict) { + span.addClass("has-conflict"); + const alert = hotkeyDisplay.createSpan("hotkey-conflict-icon"); + alert.innerHTML = runtimeContext.ea.obsidian.getIcon("octagon-alert").outerHTML; + alert.style.color = "var(--text-error)"; + alert.style.marginRight = "calc(-1 * var(--size-2-2))"; + alert.style.display = "inline-flex"; + alert.style.cursor = "pointer"; + alert.ariaLabel = runtimeContext.t("ARIA_OVERRIDE_COMMAND", { + command: conflict + }); + alert.onclick = (e) => { + e.preventDefault(); + e.stopPropagation(); + new runtimeContext.Notice( + runtimeContext.t("NOTICE_GLOBAL_HOTKEY_CONFLICT", { + command: conflict + }), + runtimeContext.NOTICE_DURATION_GLOBAL_CONFLICT + ); + }; + } + } + }; + if (!h.isInputOnly) { + scopeBtn = controlDiv.createSpan("clickable-icon setting-global-hotkey-button"); + scopeBtn.style.marginRight = "calc(-1 * var(--size-2-2))"; + updateScopeUI = () => { + const scope = runtimeContext.userHotkeys[index].scope; + switch (scope) { + case runtimeContext.SCOPE.input: + scopeBtn.innerHTML = runtimeContext.ea.obsidian.getIcon("keyboard").outerHTML; + scopeBtn.ariaLabel = runtimeContext.t("ARIA_SCOPE_INPUT"); + scopeBtn.style.color = "var(--text-muted)"; + break; + case runtimeContext.SCOPE.excalidraw: + scopeBtn.innerHTML = runtimeContext.ea.obsidian.getIcon("excalidraw-icon").outerHTML; + scopeBtn.ariaLabel = runtimeContext.t("ARIA_SCOPE_EXCALIDRAW"); + scopeBtn.style.color = "var(--interactive-accent)"; + break; + case runtimeContext.SCOPE.global: + scopeBtn.innerHTML = runtimeContext.ea.obsidian.getIcon("globe").outerHTML; + scopeBtn.ariaLabel = runtimeContext.t("ARIA_SCOPE_GLOBAL"); + scopeBtn.style.color = "var(--text-error)"; + break; + } + }; + scopeBtn.onclick = () => { + const current = runtimeContext.userHotkeys[index].scope; + let next = runtimeContext.SCOPE.input; + if (current === runtimeContext.SCOPE.input) next = runtimeContext.SCOPE.excalidraw; + else if (current === runtimeContext.SCOPE.excalidraw) next = runtimeContext.SCOPE.global; + else if (current === runtimeContext.SCOPE.global) next = runtimeContext.SCOPE.input; + runtimeContext.userHotkeys[index].scope = next; + saveHotkeys(); + if (next === runtimeContext.SCOPE.global) { + const conflict = runtimeContext.getObsidianConflict(runtimeContext.userHotkeys[index]); + if (conflict) { + new runtimeContext.Notice( + runtimeContext.t("NOTICE_GLOBAL_HOTKEY_CONFLICT", { + command: conflict + }), + runtimeContext.NOTICE_DURATION_GLOBAL_CONFLICT + ); + } + } + updateRowUI(); + }; + updateScopeUI(); + } + restoreBtn.innerHTML = runtimeContext.ea.obsidian.getIcon("rotate-ccw").outerHTML; + restoreBtn.ariaLabel = runtimeContext.t("ARIA_RESTORE_DEFAULT"); + restoreBtn.onclick = () => { + const def = runtimeContext.DEFAULT_HOTKEYS.find( + (d) => d.action === runtimeContext.userHotkeys[index].action + ); + if (def) { + runtimeContext.userHotkeys[index] = JSON.parse(JSON.stringify(def)); + saveHotkeys(); + updateRowUI(); + } + }; + updateRowUI(); + const addBtn = controlDiv.createSpan("clickable-icon setting-add-hotkey-button"); + addBtn.innerHTML = runtimeContext.ea.obsidian.getIcon("plus-circle").outerHTML; + if (h.key === "Escape") { + addBtn.style.opacity = 0; + return; + } + addBtn.ariaLabel = runtimeContext.t("ARIA_CUSTOMIZE_HOTKEY"); + addBtn.onclick = () => recordHotkey(addBtn, index, updateRowUI); + }); + runtimeContext.bodyContainer.createDiv({ + attr: { + style: "height: 40px;" + } + }); + }; + return { renderBody }; + } + + // src/scripts/mindmap-builder/styles.js + function createStyles(runtimeContext) { + const registerStyles = () => { + const existing = document.getElementById(runtimeContext.MINDMAP_FOCUS_STYLE_ID); + if (existing) existing.remove(); + const styleEl = document.createElement("style"); + styleEl.id = runtimeContext.MINDMAP_FOCUS_STYLE_ID; + styleEl.textContent = [ + ".modal.excalidraw-mindmap-ui {", + " overflow: hidden;", + " scrollbar-width: none;", + "}", + ".excalidraw-mindmap-ui .modal-header-button {display: none;}", + // Focus styles + ".excalidraw-mindmap-ui button:focus,", + ".excalidraw-mindmap-ui .clickable-icon:focus,", + ".excalidraw-mindmap-ui [tabindex]:focus,", + ".excalidraw-mindmap-ui button:focus-visible,", + ".excalidraw-mindmap-ui .clickable-icon:focus-visible,", + ".excalidraw-mindmap-ui [tabindex]:focus-visible {", + " outline: 2px solid var(--interactive-accent) !important;", + " outline-offset: 2px;", + "}", + ...runtimeContext.ea.DEVICE.isDesktop ? [".excalidraw-mindmap-ui hr {margin: 5px;}"] : [".excalidraw-mindmap-ui hr {margin: 15px 5px;}"], + ".excalidraw-mindmap-ui .clickable-icon:focus svg,", + ".excalidraw-mindmap-ui .clickable-icon:focus-visible svg {", + " color: inherit;", + "}", + // New Flex Input Styles + ".mindmap-input-wrapper { display: flex; gap: 8px; width: 100%; transition: all 0.3s ease; }", + ".mindmap-input-ontology { flex: 1; transition: flex-grow 0.3s ease; min-width: 0; }", + ".mindmap-input-main { flex: 17; transition: flex-grow 0.3s ease; min-width: 0; }", + ".mindmap-input-ontology.is-focused { flex: 17; }", + ".mindmap-input-main.is-shrunk { flex: 1; }", + // Drag Handle Styles + ".excalidraw-mindmap-ui .mindmap-drag-handle {", + " position: absolute;", + " right: 0;", + " top: 0;", + " bottom: 0;", + " width: 20px;", + " cursor: grab;", + " display: flex;", + " align-items: center;", + " justify-content: center;", + " opacity: 0.4;", + " color: var(--text-muted);", + " transition: opacity 0.2s ease, color 0.2s ease;", + " background: var(--background-secondary);", + " border-left: 1px solid var(--background-modifier-border);", + " border-top-right-radius: 6px;", + " border-bottom-right-radius: 6px;", + "}", + ".excalidraw-mindmap-ui:focus-within .mindmap-drag-handle,", + ".excalidraw-mindmap-ui .mindmap-drag-handle:hover,", + ".excalidraw-mindmap-ui .mindmap-drag-handle:active {", + " opacity: 1;", + " color: var(--text-normal);", + "}", + ".excalidraw-mindmap-ui.is-dragging .mindmap-drag-handle {", + " cursor: grabbing;", + "}" + ].join("\n"); + document.head.appendChild(styleEl); + }; + const removeStyles = () => { + const styleEl = document.getElementById(runtimeContext.MINDMAP_FOCUS_STYLE_ID); + if (styleEl) styleEl.remove(); + }; + return { registerStyles, removeStyles }; + } + + // src/scripts/mindmap-builder/floatingInput.js + function createFloatingInput(runtimeContext) { + const toggleDock = async ({ silent = false, forceDock = false, saveSetting = false } = {}) => { + runtimeContext.editingNodeId = null; + if (!runtimeContext.ea.targetView && !(forceDock && runtimeContext.isUndocked)) return; + if (!silent) { + const isSidepanelVisible = runtimeContext.ea.getSidepanelLeaf().isVisible(); + if (runtimeContext.isUndocked && !isSidepanelVisible) { + const leaf = runtimeContext.ea.getSidepanelLeaf(); + if (leaf) app.workspace.revealLeaf(leaf); + } else if (isSidepanelVisible && !runtimeContext.isUndocked) { + runtimeContext.ea.toggleSidepanelView(); + } + if (runtimeContext.isUndocked) { + app.workspace.setActiveLeaf(runtimeContext.ea.getSidepanelLeaf(), { + focus: true + }); + } else { + app.workspace.setActiveLeaf(runtimeContext.ea.targetView.leaf, { + focus: true + }); + } + } + runtimeContext.isUndocked = !runtimeContext.isUndocked; + if (saveSetting) { + runtimeContext.setVal(runtimeContext.K_UNDOCKED, runtimeContext.isUndocked); + } + runtimeContext.updateKeyHandlerLocation(); + if (runtimeContext.isUndocked) { + runtimeContext.floatingInputModal = new runtimeContext.ea.FloatingModal( + runtimeContext.ea.plugin.app + ); + const { contentEl, titleEl, modalEl, headerEl, bgEl } = runtimeContext.floatingInputModal; + modalEl.classList.add("excalidraw-mindmap-ui"); + if (bgEl) { + bgEl.style.display = "none"; + } + runtimeContext.floatingInputModal.onOpen = () => { + if (runtimeContext.ea.targetView && modalEl.ownerDocument !== runtimeContext.ea.targetView.ownerDocument) { + runtimeContext.ea.targetView.ownerDocument.body.appendChild(modalEl); + } + const { x, y } = runtimeContext.ea.targetView.contentEl.getBoundingClientRect(); + contentEl.empty(); + const closeEl = modalEl.querySelector(".modal-close-button"); + if (closeEl) closeEl.style.display = "none"; + titleEl.style.display = "none"; + headerEl.style.display = "none"; + modalEl.style.opacity = `${runtimeContext.FLOAT_MODAL_OPACITY}`; + modalEl.style.padding = "6px"; + modalEl.style.paddingRight = "26px"; + modalEl.style.minHeight = "0px"; + modalEl.style.width = "fit-content"; + modalEl.style.height = "auto"; + modalEl.style.maxHeight = runtimeContext.FLOAT_MODAL_MAX_HEIGHT; + if (runtimeContext.isExcaliBrainView()) { + modalEl.style.display = "none"; + } + const container = runtimeContext.floatingInputModal.contentEl.createDiv(); + runtimeContext.renderInput(container, true); + const dragHandle = modalEl.createDiv("mindmap-drag-handle"); + dragHandle.innerHTML = runtimeContext.ea.obsidian.getIcon("grip-vertical").outerHTML; + let isDragging = false; + let startX, startY, initialLeft, initialTop; + dragHandle.addEventListener("pointerdown", (e) => { + isDragging = true; + startX = e.clientX; + startY = e.clientY; + const rect = modalEl.getBoundingClientRect(); + initialLeft = rect.left; + initialTop = rect.top; + dragHandle.setPointerCapture(e.pointerId); + modalEl.classList.add("is-dragging"); + e.preventDefault(); + }); + dragHandle.addEventListener("pointermove", (e) => { + if (!isDragging) return; + const dx = e.clientX - startX; + const dy = e.clientY - startY; + modalEl.style.left = `${initialLeft + dx}px`; + modalEl.style.top = `${initialTop + dy}px`; + }); + dragHandle.addEventListener("pointerup", (e) => { + isDragging = false; + dragHandle.releasePointerCapture(e.pointerId); + modalEl.classList.remove("is-dragging"); + }); + dragHandle.addEventListener("dblclick", (e) => { + const { x: x2, y: y2 } = runtimeContext.ea.targetView.contentEl.getBoundingClientRect(); + const desktopShift = !!runtimeContext.ea.targetView.contentEl.querySelector( + ".App-bottom-bar .App-toolbar" + ) ? 0 : runtimeContext.ea.targetView.contentEl.clientWidth < 1200 ? 36 : 0; + modalEl.style.top = `${y2 + runtimeContext.FLOAT_MODAL_OFFSET + desktopShift}px`; + modalEl.style.left = `${x2 + runtimeContext.FLOAT_MODAL_OFFSET}px`; + }); + setTimeout( + () => { + const { x: x2, y: y2 } = runtimeContext.ea.targetView.contentEl.getBoundingClientRect(); + const desktopShift = !!runtimeContext.ea.targetView.contentEl.querySelector( + ".App-bottom-bar .App-toolbar" + ) ? 0 : runtimeContext.ea.targetView.contentEl.clientWidth < 1200 ? 36 : 0; + modalEl.style.top = `${y2 + runtimeContext.FLOAT_MODAL_OFFSET + desktopShift}px`; + modalEl.style.left = `${x2 + runtimeContext.FLOAT_MODAL_OFFSET}px`; + }, + runtimeContext.ea.DEVICE.isMobile ? 400 : 150 + ); + }; + runtimeContext.floatingInputModal.onClose = () => { + runtimeContext.removeObsidianHotkeyOverrides(); + runtimeContext.floatingInputModal = null; + if (runtimeContext.isUndocked) { + runtimeContext.isUndocked = false; + runtimeContext.setVal(runtimeContext.K_UNDOCKED, false); + runtimeContext.updateKeyHandlerLocation(); + if (runtimeContext.ea.sidepanelTab && runtimeContext.inputContainer) + runtimeContext.renderInput(runtimeContext.inputContainer, false); + } + }; + runtimeContext.linkSuggester?.close(); + runtimeContext.inputContainer.empty(); + runtimeContext.floatingInputModal.open(); + } else { + if (runtimeContext.floatingInputModal) { + runtimeContext.linkSuggester?.close(); + if (runtimeContext.floatingInputModal.modalEl && runtimeContext.floatingInputModal.modalEl.parentElement) { + runtimeContext.floatingInputModal.modalEl.remove(); + } + runtimeContext.floatingInputModal.close(); + runtimeContext.floatingInputModal = null; + } + runtimeContext.renderInput(runtimeContext.inputContainer, false); + if (forceDock) return; + if (!silent) { + runtimeContext.focusInputEl(); + } + } + }; + return { toggleDock }; + } + + // src/scripts/mindmap-builder/tasks.js + function createTasks(runtimeContext) { + const getTasksUiOptions = () => { + const tasksPlugin = app.plugins.getPlugin("obsidian-tasks-plugin"); + const mode = tasksPlugin?.configuration?.taskFormat || "emoji"; + let dateFields = []; + if (mode === "dataview") { + dateFields = [ + "\u{1F4C5} [due:: ]", + "\u{1F6EB} [start:: ]", + "\u23F3 [scheduled:: ]", + "\u2795 [created:: ]", + "\u2705 [done:: ]", + "\u274C [cancelled:: ]" + ]; + } else { + dateFields = ["\u{1F4C5} Due", "\u{1F6EB} Start", "\u23F3 Scheduled", "\u2795 Created", "\u2705 Done", "\u274C Cancelled"]; + } + const priorities = ["\u{1F53A} Highest", "\u23EB High", "\u{1F53C} Medium", " Normal", "\u{1F53D} Low", "\u23EC Lowest"]; + return { + mode, + dateFields, + priorities + }; + }; + const parseTasksData = (text, mode) => { + const priorityMap = { + "\u{1F53A}": "highest", + "\u23EB": "high", + "\u{1F53C}": "medium", + "\u{1F53D}": "low", + "\u23EC": "lowest" + }; + let priority = "normal"; + for (const [emoji, val] of Object.entries(priorityMap)) { + if (text.includes(emoji)) { + priority = val; + break; + } + } + let recurrence = ""; + let dates = []; + if (mode === "dataview") { + const recMatch = text.match(/\[recurrence:: ([^\]]+)\]/i); + if (recMatch) recurrence = recMatch[1]; + const dateFields = ["due", "start", "scheduled", "created", "done", "cancelled"]; + for (const field of dateFields) { + const regex = new RegExp(`\\[${field}:: (\\d{4}-\\d{2}-\\d{2})\\]`, "gi"); + let match; + while ((match = regex.exec(text)) !== null) { + dates.push({ + type: field, + date: match[1] + }); + } + } + } else { + const recMatch = text.match(/🔁\s*([a-zA-Z0-9 ,]+)/i); + if (recMatch) recurrence = recMatch[1].trim(); + const emojiFields = { + "\u{1F4C5}": "due", + "\u{1F6EB}": "start", + "\u23F3": "scheduled", + "\u2795": "created", + "\u2705": "done", + "\u274C": "cancelled" + }; + for (const [emoji, field] of Object.entries(emojiFields)) { + const regex = new RegExp(`${emoji}\\s*(\\d{4}-\\d{2}-\\d{2})`, "g"); + let match; + while ((match = regex.exec(text)) !== null) { + dates.push({ + type: field, + date: match[1] + }); + } + } + } + return { + priority, + recurrence, + dates + }; + }; + const cleanTasksString = (text) => { + let cleaned = text; + cleaned = cleaned.replace( + /\[(due|start|scheduled|created|done|cancelled|recurrence)::\s*[^\]]+\]/gi, + "" + ); + cleaned = cleaned.replace(/[📅🛫⏳➕✅❌]\s*\d{4}-\d{2}-\d{2}/g, ""); + cleaned = cleaned.replace(/🔁\s*[a-zA-Z0-9 ,]+/g, ""); + cleaned = cleaned.replace(/[🔺⏫🔼🔽⏬]/g, ""); + cleaned = cleaned.replace(/ +/g, " ").trim(); + return cleaned; + }; + const openCalendarModal = async () => { + let targetText = ""; + let isInputEl = false; + let textElId = null; + let sel = null; + if (runtimeContext.inputEl && runtimeContext.inputEl.value.trim() !== "") { + targetText = runtimeContext.inputEl.value; + isInputEl = true; + } else { + sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return; + const all = runtimeContext.ea.getViewElements(); + const info = runtimeContext.getHierarchy(sel, all); + if (info.rootId === sel.id) return; + textElId = sel.type === "text" ? sel.id : null; + if (!textElId && sel.boundElements) { + const boundText = sel.boundElements.find((be) => be.type === "text"); + if (boundText) textElId = boundText.id; + } + if (!textElId) return; + const textEl = all.find((el) => el.id === textElId); + if (!textEl) return; + targetText = textEl.rawText; + } + const uiOpts = getTasksUiOptions(); + const parsed = parseTasksData(targetText, uiOpts.mode); + let dates = parsed.dates.length > 0 ? parsed.dates : [ + { + type: "due", + date: window.moment().format("YYYY-MM-DD") + } + ]; + let activeDateIndex = 0; + let priority = parsed.priority; + let recurrence = parsed.recurrence; + const modal = new runtimeContext.ea.obsidian.Modal(app); + modal.titleEl.setText(runtimeContext.t("ACTION_LABEL_CALENDAR")); + let dateInputComp, typeDropdownComp; + const renderContent = () => { + const { contentEl } = modal; + contentEl.empty(); + const navRow = contentEl.createDiv({ + attr: { + style: "display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;" + } + }); + const leftNav = navRow.createDiv({ + attr: { + style: "display: flex; align-items: center; gap: 10px;" + } + }); + const prevBtn = leftNav.createEl("button"); + prevBtn.innerHTML = runtimeContext.ea.obsidian.getIcon("chevron-left").outerHTML; + prevBtn.disabled = activeDateIndex === 0; + prevBtn.onclick = () => { + activeDateIndex--; + renderContent(); + }; + leftNav.createSpan({ + text: runtimeContext.t("CALENDAR_DATE_INDEX", { + index: activeDateIndex + 1, + total: dates.length + }) + }); + const nextBtn = leftNav.createEl("button"); + nextBtn.innerHTML = runtimeContext.ea.obsidian.getIcon("chevron-right").outerHTML; + nextBtn.onclick = () => { + if (activeDateIndex === dates.length - 1) { + dates.push({ + type: "due", + date: window.moment().format("YYYY-MM-DD") + }); + } + activeDateIndex++; + renderContent(); + }; + const delBtn = navRow.createEl("button"); + delBtn.innerHTML = runtimeContext.ea.obsidian.getIcon("trash-2").outerHTML; + delBtn.disabled = dates.length === 1 && !dates[0].date; + delBtn.onclick = () => { + dates.splice(activeDateIndex, 1); + if (dates.length === 0) { + dates.push({ + type: "due", + date: window.moment().format("YYYY-MM-DD") + }); + } + if (activeDateIndex >= dates.length) activeDateIndex = dates.length - 1; + renderContent(); + }; + const activeDateObj = dates[activeDateIndex]; + new runtimeContext.ea.obsidian.Setting(contentEl).setName(runtimeContext.t("CALENDAR_DATE_LABEL")).addText((text) => { + dateInputComp = text; + text.inputEl.type = "date"; + text.setValue(activeDateObj.date); + text.onChange((val) => { + activeDateObj.date = val; + }); + text.inputEl.addEventListener("keydown", (e) => { + if (e.key === "Enter") { + e.preventDefault(); + if (typeDropdownComp && typeDropdownComp.selectEl) { + typeDropdownComp.selectEl.focus(); + } + } + }); + text.inputEl.addEventListener("change", (e) => { + if (document.activeElement === text.inputEl && typeDropdownComp && typeDropdownComp.selectEl) { + typeDropdownComp.selectEl.focus(); + } + }); + }); + new runtimeContext.ea.obsidian.Setting(contentEl).setName(runtimeContext.t("CALENDAR_DATE_TYPE")).addDropdown((dropdown) => { + typeDropdownComp = dropdown; + if (uiOpts.mode === "dataview") { + dropdown.addOption("due", "\u{1F4C5} [due:: ]"); + dropdown.addOption("start", "\u{1F6EB} [start:: ]"); + dropdown.addOption("scheduled", "\u23F3 [scheduled:: ]"); + dropdown.addOption("created", "\u2795 [created:: ]"); + dropdown.addOption("done", "\u2705 [done:: ]"); + dropdown.addOption("cancelled", "\u274C [cancelled:: ]"); + } else { + dropdown.addOption("due", `\u{1F4C5} ${runtimeContext.t("CALENDAR_DATETYPE_DUE")}`); + dropdown.addOption("start", `\u{1F6EB} ${runtimeContext.t("CALENDAR_DATETYPE_START")}`); + dropdown.addOption( + "scheduled", + `\u23F3 ${runtimeContext.t("CALENDAR_DATETYPE_SCHEDULED")}` + ); + dropdown.addOption("created", `\u2795 ${runtimeContext.t("CALENDAR_DATETYPE_CREATED")}`); + dropdown.addOption("done", `\u2705 ${runtimeContext.t("CALENDAR_DATETYPE_DONE")}`); + dropdown.addOption( + "cancelled", + `\u274C ${runtimeContext.t("CALENDAR_DATETYPE_CANCELLED")}` + ); + } + dropdown.setValue(activeDateObj.type); + dropdown.onChange((val) => { + activeDateObj.type = val; + }); + }); + new runtimeContext.ea.obsidian.Setting(contentEl).setName(runtimeContext.t("CALENDAR_PRIORITY")).addDropdown((dropdown) => { + dropdown.addOption("highest", `\u{1F53A} ${runtimeContext.t("CALENDAR_PRIORITY_HIGHEST")}`); + dropdown.addOption("high", `\u23EB ${runtimeContext.t("CALENDAR_PRIORITY_HIGH")}`); + dropdown.addOption("medium", `\u{1F53C} ${runtimeContext.t("CALENDAR_PRIORITY_MEDIUM")}`); + dropdown.addOption("normal", ` ${runtimeContext.t("CALENDAR_PRIORITY_NORMAL")}`); + dropdown.addOption("low", `\u{1F53D} ${runtimeContext.t("CALENDAR_PRIORITY_LOW")}`); + dropdown.addOption("lowest", `\u23EC ${runtimeContext.t("CALENDAR_PRIORITY_LOWEST")}`); + dropdown.setValue(priority); + dropdown.onChange((val) => { + priority = val; + }); + }); + const recSetting = new runtimeContext.ea.obsidian.Setting(contentEl).setName(runtimeContext.t("CALENDAR_RECURRENCE")).addText((text) => { + text.setPlaceholder(runtimeContext.t("CALENDAR_RECURRENCE_PLACEHOLDER")).setValue(recurrence).onChange((val) => { + recurrence = val; + }); + }); + recSetting.descEl.innerHTML = runtimeContext.t("CALENDAR_RECURRENCE_DESC"); + const linkSettingsRow = new runtimeContext.ea.obsidian.Setting(contentEl).setName(runtimeContext.t("CALENDAR_INJECT_LINK")).setDesc(runtimeContext.t("CALENDAR_INJECT_LINK_DESC")); + let aliasTextComp; + linkSettingsRow.addToggle((toggle) => { + toggle.setValue(runtimeContext.injectNodeLink).onChange((val) => { + runtimeContext.injectNodeLink = val; + runtimeContext.setVal(runtimeContext.K_INJECT_LINK, val); + aliasTextComp.inputEl.style.display = val ? "" : "none"; + }); + }); + linkSettingsRow.addText((text) => { + aliasTextComp = text; + text.setPlaceholder(runtimeContext.t("CALENDAR_ALIAS_PLACEHOLDER")).setValue(runtimeContext.nodeLinkAlias).onChange((val) => { + runtimeContext.nodeLinkAlias = val || "link"; + runtimeContext.setVal(runtimeContext.K_LINK_ALIAS, runtimeContext.nodeLinkAlias); + }); + text.inputEl.style.display = runtimeContext.injectNodeLink ? "" : "none"; + text.inputEl.style.width = "100px"; + text.inputEl.style.marginLeft = "10px"; + }); + const btnContainer = contentEl.createDiv({ + attr: { + style: "display: flex; gap: 10px; justify-content: flex-end; margin-top: 15px;" + } + }); + const cancelBtn = btnContainer.createEl("button", { + text: runtimeContext.t("CALENDAR_BTN_CANCEL") + }); + cancelBtn.onclick = () => modal.close(); + const taskOnlyBtn = btnContainer.createEl("button", { + text: runtimeContext.t("CALENDAR_BTN_TASK_ONLY") + }); + taskOnlyBtn.onclick = () => handleSave(false); + const saveBtn = btnContainer.createEl("button", { + text: runtimeContext.t("CALENDAR_BTN_ADD_DATE_TASK"), + cls: "mod-cta" + }); + saveBtn.onclick = () => handleSave(true); + setTimeout(() => { + if (dateInputComp && dateInputComp.inputEl) { + dateInputComp.inputEl.focus(); + if (typeof dateInputComp.inputEl.showPicker === "function") { + try { + dateInputComp.inputEl.showPicker(); + } catch (e) { + } + } + } + }, 50); + }; + const handleSave = async (includeDate = true) => { + modal.close(); + let tasksString = ""; + if (includeDate) { + const validDates = dates.filter((d) => d.date); + if (uiOpts.mode === "dataview") { + let priorityStr = ""; + const priorityMap = { + highest: "\u{1F53A}", + high: "\u23EB", + medium: "\u{1F53C}", + normal: "", + low: "\u{1F53D}", + lowest: "\u23EC" + }; + if (priority !== "normal") priorityStr = priorityMap[priority]; + let dateStrs = validDates.map((d) => `[${d.type}:: ${d.date}]`); + let recStr = recurrence ? `[recurrence:: ${recurrence}]` : ""; + const parts = [priorityStr, ...dateStrs, recStr].filter(Boolean); + if (parts.length > 0) tasksString = " " + parts.join(" "); + } else { + let priorityStr = ""; + const priorityMap = { + highest: " \u{1F53A}", + high: " \u23EB", + medium: " \u{1F53C}", + normal: "", + low: " \u{1F53D}", + lowest: " \u23EC" + }; + priorityStr = priorityMap[priority] || ""; + const emojiMap = { + due: "\u{1F4C5}", + start: "\u{1F6EB}", + scheduled: "\u23F3", + created: "\u2795", + done: "\u2705", + cancelled: "\u274C" + }; + let dateStrs = validDates.map((d) => ` ${emojiMap[d.type]} ${d.date}`); + let recStr = recurrence ? ` \u{1F501} ${recurrence}` : ""; + tasksString = `${priorityStr}${dateStrs.join("")}${recStr}`; + } + } + const taskRegex = /^- \[([ xX])\] (.*)/s; + const match = targetText.match(taskRegex); + let cleanText = cleanTasksString(match ? match[2] : targetText); + const linkRegex = /\s*\(\[\[[^\]]+#\^group=[a-zA-Z0-9_-]+\|[^\]]+\]\]\)$/; + if (linkRegex.test(cleanText)) { + cleanText = cleanText.replace(linkRegex, ""); + } + let finalPrefix = match ? `- [${match[1]}] ` : "- [ ] "; + let newText = `${finalPrefix}${cleanText}`; + if (runtimeContext.injectNodeLink) { + if (isInputEl) { + newText += ` __NODE_LINK_PLACEHOLDER__`; + } else { + const file = app.workspace.getActiveFile(); + const fileName = file ? file.basename : ""; + newText += ` ([[${fileName}#^group=${textElId}|${runtimeContext.nodeLinkAlias}]])`; + } + } + newText += tasksString; + if (isInputEl) { + runtimeContext.inputEl.value = newText; + runtimeContext.updateUI(); + } else { + const all = runtimeContext.ea.getViewElements(); + const textEl = all.find((el) => el.id === textElId); + runtimeContext.ea.copyViewElementsToEAforEditing([textEl]); + const eaEl = runtimeContext.ea.getElement(textEl.id); + eaEl.rawText = newText; + eaEl.text = newText; + eaEl.originalText = newText; + runtimeContext.ea.refreshTextElementSize(eaEl.id); + await runtimeContext.addElementsToView({ + captureUpdate: runtimeContext.autoLayoutDisabled ? "IMMEDIATELY" : "EVENTUALLY" + }); + if (eaEl.containerId) { + const updatedContainer = runtimeContext.ea.getViewElements().find((el) => el.id === eaEl.containerId); + if (updatedContainer) runtimeContext.api().updateContainerSize([updatedContainer]); + } + if (!runtimeContext.autoLayoutDisabled) { + const info = runtimeContext.getHierarchy(sel, runtimeContext.ea.getViewElements()); + await runtimeContext.triggerGlobalLayout(info.rootId); + } + runtimeContext.updateUI(); + } + }; + modal.onOpen = () => { + renderContent(); + modal.modalEl.addEventListener("keydown", (e) => { + if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + e.stopPropagation(); + handleSave(true); + } + if (e.key === "Escape") { + e.preventDefault(); + e.stopPropagation(); + modal.close(); + } + }); + }; + modal.open(); + }; + return { getTasksUiOptions, parseTasksData, cleanTasksString, openCalendarModal }; + } + + // src/scripts/mindmap-builder/branchHistory.ts + async function undoPastedBranch(api, rootIds, waitForCommit) { + const roots = new Set(rootIds); + let steps = 0; + while (!api.isDestroyed && api.getSceneElements().some((e) => roots.has(e.id)) && steps < 64) { + api.history.undo(); + steps++; + await waitForCommit(); + } + return steps; + } + + // src/scripts/mindmap-builder/actions.js + function createActions(runtimeContext) { + let historyBusy = false; + const performAction = async (action, event) => { + if (!action || !runtimeContext.ea.targetView || historyBusy) return; + if (runtimeContext.isBranchPasteBusy?.()) return; + switch (action) { + case runtimeContext.ACTION_CALENDAR: + await runtimeContext.openCalendarModal(); + break; + case runtimeContext.ACTION_TOGGLE_FLOATING_EXTRAS: + runtimeContext.toggleFloatingExtras?.(); + break; + case runtimeContext.ACTION_REARRANGE: + await runtimeContext.refreshMapLayout(); + break; + case runtimeContext.ACTION_TOGGLE_GROUP: + await runtimeContext.toggleBranchGroup(); + break; + case runtimeContext.ACTION_HIDE: + if (runtimeContext.editingNodeId) { + runtimeContext.editingNodeId = null; + runtimeContext.updateUI(); + } else if (runtimeContext.isUndocked) { + runtimeContext.toggleDock({ + silent: true, + forceDock: true, + saveSetting: false + }); + } + break; + case runtimeContext.ACTION_PIN: + await runtimeContext.togglePin(); + break; + case runtimeContext.ACTION_TOGGLE_CHECKBOX: + await runtimeContext.toggleCheckboxStatus(); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_TOGGLE_EMBED: + await runtimeContext.toggleEmbedStatus(); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_TOGGLE_SUBMAP_ROOT: + await runtimeContext.toggleSubmapRoot(); + break; + case runtimeContext.ACTION_BOX: + await runtimeContext.toggleBox(); + break; + case runtimeContext.ACTION_TOGGLE_BOUNDARY: + await runtimeContext.toggleBoundary(); + break; + case runtimeContext.ACTION_FOLD: + await runtimeContext.toggleFold("L0"); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_FOLD_L1: + await runtimeContext.toggleFold("L1"); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_FOLD_ALL: + await runtimeContext.toggleFold("ALL"); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_COPY: + runtimeContext.copyMapAsText(false); + break; + case runtimeContext.ACTION_CUT: + runtimeContext.copyMapAsText(true); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_PASTE: + await runtimeContext.pasteElementToMap(); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_IMPORT_OUTLINE: + await runtimeContext.importOutline(); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_ZOOM: + runtimeContext.zoomToFit(true); + break; + case runtimeContext.ACTION_FOCUS: + runtimeContext.focusSelected(); + break; + case runtimeContext.ACTION_SORT_ORDER: + runtimeContext.changeNodeOrder(event?.key); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_NAVIGATE: + await runtimeContext.navigateMap({ + key: event?.key, + zoom: false, + focus: false + }); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_NAVIGATE_ZOOM: + await runtimeContext.navigateMap({ + key: event?.key, + zoom: true, + focus: false + }); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_NAVIGATE_FOCUS: + await runtimeContext.navigateMap({ + key: event?.key, + zoom: false, + focus: true + }); + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_DOCK_UNDOCK: + runtimeContext.toggleDock({ + saveSetting: true + }); + break; + case runtimeContext.ACTION_EDIT: + runtimeContext.startEditing(); + break; + case runtimeContext.ACTION_ADD_SIBLING_AFTER: + runtimeContext.addSibling(event, true); + break; + case runtimeContext.ACTION_ADD_SIBLING_BEFORE: + runtimeContext.addSibling(event, false); + break; + case runtimeContext.ACTION_ADD_FOLLOW: + case runtimeContext.ACTION_ADD_FOLLOW_FOCUS: + case runtimeContext.ACTION_ADD_FOLLOW_ZOOM: + if (!runtimeContext.inputEl.value) return; + await runtimeContext.addNode( + runtimeContext.inputEl.value, + true, + false, + null, + null, + null, + runtimeContext.ontologyEl.value + ); + runtimeContext.inputEl.value = ""; + runtimeContext.ontologyEl.value = ""; + runtimeContext.updateUI(); + if (action === runtimeContext.ACTION_ADD_FOLLOW_FOCUS) runtimeContext.focusSelected(); + if (action === runtimeContext.ACTION_ADD_FOLLOW_ZOOM) runtimeContext.zoomToFit(); + break; + case runtimeContext.ACTION_ADD: + const currentSel = runtimeContext.getMindmapNodeFromSelection() ?? runtimeContext.ea.getViewSelectedElement(); + if (runtimeContext.editingNodeId && currentSel && (currentSel.id === runtimeContext.editingNodeId || currentSel.containerId === runtimeContext.editingNodeId)) { + await runtimeContext.commitEdit(); + } else { + if (runtimeContext.editingNodeId) { + runtimeContext.editingNodeId = null; + } + if (runtimeContext.inputEl.value) { + await runtimeContext.addNode( + runtimeContext.inputEl.value, + false, + false, + null, + null, + null, + runtimeContext.ontologyEl.value + ); + runtimeContext.inputEl.value = ""; + runtimeContext.ontologyEl.value = ""; + } else { + const sel = runtimeContext.getMindmapNodeFromSelection(); + const allElements = runtimeContext.ea.getViewElements(); + let handledRecent = false; + if (runtimeContext.mostRecentlyAddedNodeID) { + const mostRecentNode = runtimeContext.getMostRecentlyAddedNode(); + if (mostRecentNode && sel) { + const selParent = runtimeContext.getParentNode(sel.id, allElements); + const recentParent = runtimeContext.getParentNode(mostRecentNode.id, allElements); + const isSameOrSibling = sel.id === mostRecentNode.id || selParent && recentParent && selParent.id === recentParent.id; + if (!isSameOrSibling) { + runtimeContext.selectNodeInView(mostRecentNode); + handledRecent = true; + } + } else { + runtimeContext.mostRecentlyAddedNodeID = null; + } + } + if (!handledRecent && sel) { + const parent = runtimeContext.getParentNode(sel.id, allElements); + const siblings = parent ? runtimeContext.getChildrenNodes(parent.id, allElements) : []; + if (siblings.length > 1) { + siblings.sort( + (a, b) => runtimeContext.getMindmapOrder(a) - runtimeContext.getMindmapOrder(b) + ); + const idx = siblings.findIndex((s) => s.id === sel.id); + const nextIdx = (idx + 1) % siblings.length; + runtimeContext.selectNodeInView(siblings[nextIdx]); + } else { + const children = runtimeContext.getChildrenNodes(sel.id, allElements); + if (children.length > 0) { + children.sort( + (a, b) => runtimeContext.getMindmapOrder(a) - runtimeContext.getMindmapOrder(b) + ); + runtimeContext.selectNodeInView(children[0]); + } else if (parent) { + runtimeContext.selectNodeInView(parent); + } + } + } + } + } + runtimeContext.updateUI(); + break; + case runtimeContext.ACTION_UNDO: + if (runtimeContext.ea.targetView) { + const currentVer = ExcalidrawLib.getSceneVersion(runtimeContext.api().getSceneElements()); + const transaction = runtimeContext.lastCommittedTransaction; + if (transaction?.branchPasteIds && currentVer === transaction.version) { + const api = runtimeContext.api(); + let steps; + historyBusy = true; + try { + steps = await undoPastedBranch(api, transaction.branchPasteIds, () => sleep(0)); + } finally { + historyBusy = false; + } + if (api.isDestroyed || runtimeContext.api() !== api) { + runtimeContext.redoAvailable = null; + runtimeContext.lastCommittedTransaction = null; + break; + } + runtimeContext.redoAvailable = { + steps: Math.max(0, steps - 1), + branchPasteIds: transaction.branchPasteIds, + version: ExcalidrawLib.getSceneVersion(api.getSceneElements()) + }; + runtimeContext.lastCommittedTransaction = null; + break; + } + if (runtimeContext.lastCommittedTransaction && currentVer === runtimeContext.lastCommittedTransaction.version && runtimeContext.lastCommittedTransaction.steps > 0) { + for (let i = 0; i <= runtimeContext.lastCommittedTransaction.steps; i++) { + runtimeContext.api().history.undo(); + } + const afterUndoVer = ExcalidrawLib.getSceneVersion( + runtimeContext.api().getSceneElements() + ); + runtimeContext.redoAvailable = { + steps: runtimeContext.lastCommittedTransaction.steps, + version: afterUndoVer + }; + runtimeContext.lastCommittedTransaction = null; + } else { + runtimeContext.api().history.undo(); + runtimeContext.lastCommittedTransaction = null; + runtimeContext.redoAvailable = null; + } + } + break; + case runtimeContext.ACTION_REDO_Z: + case runtimeContext.ACTION_REDO_Y: + if (runtimeContext.ea.targetView) { + const currentVer = ExcalidrawLib.getSceneVersion(runtimeContext.api().getSceneElements()); + if (runtimeContext.redoAvailable && currentVer === runtimeContext.redoAvailable.version && runtimeContext.redoAvailable.steps > 0) { + const api = runtimeContext.api(); + historyBusy = !!runtimeContext.redoAvailable.branchPasteIds; + try { + for (let i = 0; i <= runtimeContext.redoAvailable.steps; i++) { + if (api.isDestroyed || runtimeContext.api() !== api) break; + api.history.redo(); + if (runtimeContext.redoAvailable.branchPasteIds) await sleep(0); + } + } finally { + historyBusy = false; + } + if (api.isDestroyed || runtimeContext.api() !== api) { + runtimeContext.redoAvailable = null; + runtimeContext.lastCommittedTransaction = null; + break; + } + const afterRedoVer = ExcalidrawLib.getSceneVersion( + runtimeContext.api().getSceneElements() + ); + runtimeContext.lastCommittedTransaction = { + steps: runtimeContext.redoAvailable.steps, + version: afterRedoVer, + ...runtimeContext.redoAvailable.branchPasteIds ? { branchPasteIds: runtimeContext.redoAvailable.branchPasteIds } : {} + }; + runtimeContext.redoAvailable = null; + } else { + runtimeContext.api().history.redo(); + runtimeContext.lastCommittedTransaction = null; + runtimeContext.redoAvailable = null; + } + } + break; + } + }; + return { performAction }; + } + + // src/scripts/mindmap-builder/lifecycle.js + function createLifecycle(runtimeContext) { + const removeKeydownHandlers = () => { + if (!window.MindmapBuilder) return; + window.MindmapBuilder.keydownHandlers.forEach((f) => { + try { + f(); + } catch (e) { + console.error("Mindmap Builder: Error removing keydown handler:", e); + } + }); + window.MindmapBuilder.keydownHandlers = []; + }; + const removeEventListeners = () => { + removeKeydownHandlers(); + try { + window.MindmapBuilder?.popObsidianHotkeyScope?.(); + } catch (e) { + console.error("Mindmap Builder: Error popping hotkey scope:", e); + } + try { + window.MindmapBuilder?.removePointerDownHandler?.(); + } catch (e) { + console.error("Mindmap Builder: Error removing pointerdown handler:", e); + } + try { + window.MindmapBuilder?.removeActiveLeafListener?.(); + } catch (e) { + console.error("Mindmap Builder: Error removing active-leaf-change listener:", e); + } + }; + const handleCanvasPointerDown = (e) => { + if (!runtimeContext.isViewSet()) return; + if (runtimeContext.floatingInputModal && runtimeContext.floatingInputModal.modalEl.contains(e.target)) + return; + if (runtimeContext.uiUpdateTimer) { + clearTimeout(runtimeContext.uiUpdateTimer); + } + runtimeContext.uiUpdateTimer = setTimeout(() => { + if (!runtimeContext.isViewSet()) return; + const selection = runtimeContext.getMindmapNodeFromSelection(); + runtimeContext.updateUI(selection); + runtimeContext.uiUpdateTimer = null; + }, 50); + }; + return { removeKeydownHandlers, removeEventListeners, handleCanvasPointerDown }; + } + + // src/scripts/mindmap-builder/transactions.js + function createTransactions(runtimeContext) { + const addElementsToView = async ({ + repositionToCursor = false, + save = false, + newElementsOnTop = true, + shouldRestoreElements = true, + captureUpdate = "IMMEDIATELY" + } = {}) => { + if (!runtimeContext.isViewSet()) return; + if (["EVENTUALLY", "IMMEDIATELY"].includes(captureUpdate)) { + runtimeContext.currentTransactionAccumulator++; + } + await runtimeContext.ea.addElementsToView( + repositionToCursor, + save, + newElementsOnTop, + shouldRestoreElements, + captureUpdate + ); + const fileIds = new Set( + runtimeContext.ea.getElements().filter((el) => el.fileId && !el.isDeleted).map((el) => el.fileId) + ); + runtimeContext.ea.clear(); + if (captureUpdate === "IMMEDIATELY") { + const currentSceneVersion = ExcalidrawLib.getSceneVersion( + runtimeContext.api().getSceneElements() + ); + runtimeContext.lastCommittedTransaction = { + steps: runtimeContext.currentTransactionAccumulator, + version: currentSceneVersion + }; + runtimeContext.currentTransactionAccumulator = 0; + runtimeContext.redoAvailable = null; + } + if (fileIds.size === 0) return; + const checker = () => { + const loadedFiles = runtimeContext.api().getFiles(); + const loadedKeys = Object.keys(loadedFiles).filter((f) => loadedFiles[f].dataURL); + for (const fileId of fileIds) { + if (!loadedKeys.find((f) => f.id === fileId)) return false; + } + return true; + }; + let watchdog = 0; + while (!checker() && watchdog++ < 20) { + await sleep(15); + } + }; + return { addElementsToView }; + } + + // src/scripts/mindmap-builder/configuration.js + function createConfiguration(runtimeContext) { + const VALUE_SETS = Object.freeze({ + SCOPE: Object.freeze({ + input: 3, + excalidraw: 2, + global: 1, + none: 0 + }), + FONT_SCALE: Object.freeze(["Use scene fontsize", "Fibonacci Scale", "Normal Scale"]), + GROWTH: Object.freeze([ + "Radial", + "Right-facing", + "Left-facing", + "Right-Left", + "Up-facing", + "Down-facing", + "Up-Down" + ]), + ZOOM: Object.freeze(["Low", "Medium", "High"]), + ARROW: Object.freeze(["curved", "straight"]), + BRANCH_SCALE: Object.freeze(["Hierarchical", "Uniform"]) + }); + const FONT_SCALE_TYPES = VALUE_SETS.FONT_SCALE; + const GROWTH_TYPES = VALUE_SETS.GROWTH; + const ZOOM_TYPES = VALUE_SETS.ZOOM; + const SCOPE = VALUE_SETS.SCOPE; + const ARROW_TYPES = VALUE_SETS.ARROW; + const BRANCH_SCALE_TYPES = VALUE_SETS.BRANCH_SCALE; + const ZOOM_LEVELS = Object.freeze({ + Low: { desktop: 0.1, mobile: 0.2 }, + Medium: { desktop: 0.25, mobile: 0.35 }, + High: { desktop: 0.5, mobile: 0.6 } + }); + const K_WIDTH = "Max Text Width"; + const K_FONTSIZE = "Font Sizes"; + const K_BOX = "Box Children"; + const K_ROUND = "Rounded Corners"; + const K_BRANCH_SCALE = "Branch Scale Style"; + const K_BASE_WIDTH = "Base Stroke Width"; + const K_GROWTH = "Growth Mode"; + const K_MULTICOLOR = "Multicolor Mode"; + const K_UNDOCKED = "Is Undocked"; + const K_GROUP = "Group Branches"; + const K_ARROWSTROKE = "Arrow Stroke Style"; + const K_CENTERTEXT = "Center text in nodes?"; + const K_ZOOM = "Preferred Zoom Level"; + const K_HOTKEYS = "Hotkeys"; + const K_PALETTE = "Custom Palette"; + const K_LAYOUT = "Layout Config"; + const K_ARROW_TYPE = "Arrow Type"; + const K_FILL_SWEEP = "Fill Sweep"; + const K_INJECT_LINK = "Inject Node Link"; + const K_LINK_ALIAS = "Node Link Alias"; + const K_PRESETS = "Map Presets"; + const K_ACTIVE_PRESET = "Active Preset"; + const LAYOUT_METADATA = { + // --- General --- + GAP_X: { + section: "SECTION_GENERAL", + def: 120, + min: 10, + max: 400, + step: 10, + desc: runtimeContext.t("DESC_LAYOUT_GAP_X"), + name: runtimeContext.t("GAP_X") + }, + GAP_Y: { + section: "SECTION_GENERAL", + def: 25, + min: 5, + max: 150, + step: 5, + desc: runtimeContext.t("DESC_LAYOUT_GAP_Y"), + name: runtimeContext.t("GAP_Y") + }, + GAP_MULTIPLIER: { + section: "SECTION_GENERAL", + def: 0.6, + min: 0.1, + max: 3, + step: 0.1, + desc: runtimeContext.t("DESC_LAYOUT_GAP_MULTIPLIER"), + name: runtimeContext.t("GAP_MULTIPLIER") + }, + // --- Radial (New & Updated) --- + ROOT_RADIUS_FACTOR: { + section: "SECTION_GENERAL", + def: 0.8, + min: 0.5, + max: 2, + step: 0.1, + desc: runtimeContext.t("DESC_LAYOUT_ROOT_RADIUS"), + name: runtimeContext.t("ROOT_RADIUS_FACTOR") + }, + MIN_RADIUS: { + section: "SECTION_GENERAL", + def: 350, + min: 30, + max: 800, + step: 10, + desc: runtimeContext.t("DESC_LAYOUT_MIN_RADIUS"), + name: runtimeContext.t("MIN_RADIUS") + }, + RADIAL_ASPECT_RATIO: { + section: "SECTION_RADIAL", + def: 0.7, + min: 0.5, + max: 2, + step: 0.1, + desc: runtimeContext.t("DESC_RADIAL_ASPECT_RATIO"), + name: runtimeContext.t("RADIAL_ASPECT_RATIO") + }, + RADIAL_POLE_GAP_BONUS: { + section: "SECTION_RADIAL", + def: 2, + min: 0, + max: 5, + step: 0.1, + desc: runtimeContext.t("DESC_RADIAL_POLE_GAP_BONUS"), + name: runtimeContext.t("RADIAL_POLE_GAP_BONUS") + }, + RADIAL_START_ANGLE: { + section: "SECTION_RADIAL", + def: 280, + min: 0, + max: 360, + step: 10, + desc: runtimeContext.t("DESC_RADIAL_START_ANGLE"), + name: runtimeContext.t("RADIAL_START_ANGLE") + }, + RADIAL_MAX_SWEEP: { + section: "SECTION_RADIAL", + def: 340, + min: 90, + max: 360, + step: 10, + desc: runtimeContext.t("DESC_RADIAL_MAX_SWEEP"), + name: runtimeContext.t("RADIAL_MAX_SWEEP") + }, + // --- Directional --- + DIRECTIONAL_ARC_SPAN_RADIANS: { + section: "SECTION_DIRECTIONAL", + def: 1, + min: 0.1, + max: 3.14, + step: 0.1, + desc: runtimeContext.t("DESC_LAYOUT_ARC_SPAN"), + name: runtimeContext.t("DIRECTIONAL_ARC_SPAN_RADIANS") + }, + GAP_MULTIPLIER_DIRECTIONAL: { + section: "SECTION_DIRECTIONAL", + def: 1.5, + min: 1, + max: 3, + step: 0.1, + desc: runtimeContext.t("DESC_LAYOUT_GAP_DIRECTIONAL"), + name: runtimeContext.t("GAP_MULTIPLIER_DIRECTIONAL") + }, + RADIUS_PADDING_PER_NODE: { + section: "SECTION_DIRECTIONAL", + def: 7, + min: 0, + max: 20, + step: 1, + desc: runtimeContext.t("DESC_LAYOUT_RADIUS_PADDING"), + name: runtimeContext.t("RADIUS_PADDING_PER_NODE") + }, + // --- Vertical Maps (Up/Down) --- + VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE: { + section: "SECTION_VERTICAL", + def: 0.35, + min: 0.05, + max: 1.2, + step: 0.05, + desc: runtimeContext.t("DESC_VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE"), + name: runtimeContext.t("VERTICAL_SUBTREE_WIDTH_BLEND_SINGLE") + }, + VERTICAL_SUBTREE_WIDTH_BLEND_DUAL: { + section: "SECTION_VERTICAL", + def: 0.6, + min: 0.1, + max: 1.4, + step: 0.05, + desc: runtimeContext.t("DESC_VERTICAL_SUBTREE_WIDTH_BLEND_DUAL"), + name: runtimeContext.t("VERTICAL_SUBTREE_WIDTH_BLEND_DUAL") + }, + VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER: { + section: "SECTION_VERTICAL", + def: 6, + min: 0.5, + max: 20, + step: 0.5, + desc: runtimeContext.t("DESC_VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER"), + name: runtimeContext.t("VERTICAL_SUBTREE_SMOOTH_THRESHOLD_MULTIPLIER") + }, + VERTICAL_SUBTREE_SMOOTH_MIN_SCALE: { + section: "SECTION_VERTICAL", + def: 240, + min: 10, + max: 1600, + step: 10, + desc: runtimeContext.t("DESC_VERTICAL_SUBTREE_SMOOTH_MIN_SCALE"), + name: runtimeContext.t("VERTICAL_SUBTREE_SMOOTH_MIN_SCALE") + }, + HORIZONTAL_L1_SOFTCAP_THRESHOLD: { + section: "SECTION_VERTICAL", + def: 560, + min: 20, + max: 3e3, + step: 20, + desc: runtimeContext.t("DESC_HORIZONTAL_L1_SOFTCAP_THRESHOLD"), + name: runtimeContext.t("HORIZONTAL_L1_SOFTCAP_THRESHOLD") + }, + HORIZONTAL_L1_COMPRESSION_MIN_SCALE: { + section: "SECTION_VERTICAL", + def: 240, + min: 10, + max: 1600, + step: 10, + desc: runtimeContext.t("DESC_HORIZONTAL_L1_COMPRESSION_MIN_SCALE"), + name: runtimeContext.t("HORIZONTAL_L1_COMPRESSION_MIN_SCALE") + }, + VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO: { + section: "SECTION_VERTICAL", + def: 0.55, + min: 0.05, + max: 1.3, + step: 0.05, + desc: runtimeContext.t("DESC_VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO"), + name: runtimeContext.t("VERTICAL_COMPACT_PARENT_CHILD_GAP_RATIO") + }, + DIRECTIONAL_CROSS_AXIS_RATIO: { + section: "SECTION_VERTICAL", + def: 0.2, + min: 0.05, + max: 1.2, + step: 0.05, + desc: runtimeContext.t("DESC_DIRECTIONAL_CROSS_AXIS_RATIO"), + name: runtimeContext.t("DIRECTIONAL_CROSS_AXIS_RATIO") + }, + // --- Visuals --- + INDICATOR_OFFSET: { + section: "SECTION_VISUALS", + def: 10, + min: 5, + max: 50, + step: 5, + desc: runtimeContext.t("DESC_LAYOUT_INDICATOR_OFFSET"), + name: runtimeContext.t("INDICATOR_OFFSET") + }, + INDICATOR_OPACITY: { + section: "SECTION_VISUALS", + def: 40, + min: 10, + max: 100, + step: 10, + desc: runtimeContext.t("DESC_LAYOUT_INDICATOR_OPACITY"), + name: runtimeContext.t("INDICATOR_OPACITY") + }, + CONTAINER_PADDING: { + section: "SECTION_VISUALS", + def: 10, + min: 0, + max: 50, + step: 2, + desc: runtimeContext.t("DESC_LAYOUT_CONTAINER_PADDING"), + name: runtimeContext.t("CONTAINER_PADDING") + }, + MAX_SEGMENT_LENGTH: { + section: "SECTION_VISUALS", + def: 80, + min: 30, + max: 200, + step: 10, + desc: runtimeContext.t("DESC_LAYOUT_BOUNDARY_LINE_PRECISION"), + name: runtimeContext.t("MAX_SEGMENT_LENGTH") + }, + // --- Manual Mode --- + MANUAL_GAP_MULTIPLIER: { + section: "SECTION_MANUAL", + def: 1.3, + min: 1, + max: 2, + step: 0.1, + desc: runtimeContext.t("DESC_LAYOUT_MANUAL_GAP"), + name: runtimeContext.t("MANUAL_GAP_MULTIPLIER") + }, + MANUAL_JITTER_RANGE: { + section: "SECTION_MANUAL", + def: 300, + min: 0, + max: 400, + step: 10, + desc: runtimeContext.t("DESC_LAYOUT_MANUAL_JITTER"), + name: runtimeContext.t("MANUAL_JITTER_RANGE") + } + }; + const COLOR_CONTRAST_MIN = 2.5; + const COLOR_DISTINCT_THRESHOLD = 40; + const HUE_STEP_BASE = 15; + const HUE_STEP_JITTER = 4; + const SAT_BASE = 75; + const SAT_JITTER = 10; + const LIGHT_BASE_DARK = 65; + const LIGHT_JITTER_DARK = 10; + const LIGHT_BASE_LIGHT = 36; + const LIGHT_JITTER_LIGHT = 8; + const WRAP_WIDTH_MIN = 100; + const WRAP_WIDTH_MAX = 600; + const WRAP_WIDTH_STEP = 10; + const FLOAT_MODAL_OPACITY = 0.8; + const FLOAT_MODAL_OFFSET = 5; + const FLOAT_MODAL_MAX_HEIGHT = "calc(2 * var(--size-4-4) + 12px + var(--input-height))"; + const NOTICE_DURATION_CONFLICT = 6e3; + const NOTICE_DURATION_GLOBAL_CONFLICT = 1e4; + const LAYOUT_DEFAULTS = {}; + const IMAGE_TYPES = [ + "jpeg", + "jpg", + "png", + "gif", + "svg", + "webp", + "bmp", + "ico", + "jtif", + "tif", + "jfif", + "avif" + ]; + const EMBEDED_OBJECT_WIDTH_ROOT = 400; + const EMBEDED_OBJECT_WIDTH_CHILD = 180; + const ACTION_ADD = "Add"; + const ACTION_ADD_SIBLING_AFTER = "Add Next Sibling"; + const ACTION_ADD_SIBLING_BEFORE = "Add Prev Sibling"; + const ACTION_ADD_FOLLOW = "Add + follow"; + const ACTION_ADD_FOLLOW_FOCUS = "Add + follow + focus"; + const ACTION_ADD_FOLLOW_ZOOM = "Add + follow + zoom"; + const ACTION_SORT_ORDER = "Change Order/Promote Node"; + const ACTION_EDIT = "Edit node"; + const ACTION_TOGGLE_CHECKBOX = "Toggle Checkbox"; + const ACTION_CALENDAR = "Calendar"; + const ACTION_PIN = "Pin/Unpin"; + const ACTION_BOX = "Box/Unbox"; + const ACTION_TOGGLE_GROUP = "Group/Ungroup Single Branch"; + const ACTION_COPY = "Copy"; + const ACTION_CUT = "Cut"; + const ACTION_PASTE = "Paste"; + const ACTION_IMPORT_OUTLINE = "Import Outline from Linked File"; + const ACTION_ZOOM = "Cycle Zoom"; + const ACTION_FOCUS = "Focus (center) node"; + const ACTION_NAVIGATE = "Navigate"; + const ACTION_NAVIGATE_ZOOM = "Navigate & zoom"; + const ACTION_NAVIGATE_FOCUS = "Navigate & focus"; + const ACTION_FOLD = "Fold/Unfold Branch"; + const ACTION_FOLD_L1 = "Fold/Unfold to Level 1"; + const ACTION_FOLD_ALL = "Fold/Unfold Branch Recursively"; + const ACTION_TOGGLE_BOUNDARY = "Toggle Boundary"; + const ACTION_TOGGLE_SUBMAP_ROOT = "Toggle Submap Root"; + const ACTION_TOGGLE_EMBED = "Toggle Embed/Link"; + const ACTION_DOCK_UNDOCK = "Dock/Undock"; + const ACTION_HIDE = "Dock & hide"; + const ACTION_REARRANGE = "Rearrange Map"; + const ACTION_TOGGLE_FLOATING_EXTRAS = "Toggle Floating Extra Buttons"; + const ACTION_UNDO = "Undo"; + const ACTION_REDO_Z = "Redo (Ctrl-Shift-Z)"; + const ACTION_REDO_Y = "Redo (Ctrl-Y)"; + const ACTION_LABEL_KEYS = { + [ACTION_ADD]: "ACTION_LABEL_ADD", + [ACTION_ADD_SIBLING_AFTER]: "ACTION_LABEL_ADD_SIBLING_AFTER", + [ACTION_ADD_SIBLING_BEFORE]: "ACTION_LABEL_ADD_SIBLING_BEFORE", + [ACTION_ADD_FOLLOW]: "ACTION_LABEL_ADD_FOLLOW", + [ACTION_ADD_FOLLOW_FOCUS]: "ACTION_LABEL_ADD_FOLLOW_FOCUS", + [ACTION_ADD_FOLLOW_ZOOM]: "ACTION_LABEL_ADD_FOLLOW_ZOOM", + [ACTION_SORT_ORDER]: "ACTION_LABEL_SORT_ORDER", + [ACTION_EDIT]: "ACTION_LABEL_EDIT", + [ACTION_TOGGLE_CHECKBOX]: "ACTION_LABEL_TOGGLE_CHECKBOX", + [ACTION_CALENDAR]: "ACTION_LABEL_CALENDAR", + [ACTION_PIN]: "ACTION_LABEL_PIN", + [ACTION_BOX]: "ACTION_LABEL_BOX", + [ACTION_TOGGLE_GROUP]: "ACTION_LABEL_TOGGLE_GROUP", + [ACTION_COPY]: "ACTION_LABEL_COPY", + [ACTION_CUT]: "ACTION_LABEL_CUT", + [ACTION_PASTE]: "ACTION_LABEL_PASTE", + [ACTION_IMPORT_OUTLINE]: "ACTION_LABEL_IMPORT_OUTLINE", + [ACTION_ZOOM]: "ACTION_LABEL_ZOOM", + [ACTION_FOCUS]: "ACTION_LABEL_FOCUS", + [ACTION_NAVIGATE]: "ACTION_LABEL_NAVIGATE", + [ACTION_NAVIGATE_ZOOM]: "ACTION_LABEL_NAVIGATE_ZOOM", + [ACTION_NAVIGATE_FOCUS]: "ACTION_LABEL_NAVIGATE_FOCUS", + [ACTION_FOLD]: "ACTION_LABEL_FOLD", + [ACTION_FOLD_L1]: "ACTION_LABEL_FOLD_L1", + [ACTION_FOLD_ALL]: "ACTION_LABEL_FOLD_ALL", + [ACTION_TOGGLE_BOUNDARY]: "TOOLTIP_TOGGLE_BOUNDARY", + [ACTION_TOGGLE_SUBMAP_ROOT]: "ACTION_LABEL_TOGGLE_SUBMAP_ROOT", + [ACTION_TOGGLE_EMBED]: "ACTION_LABEL_TOGGLE_EMBED", + [ACTION_DOCK_UNDOCK]: "ACTION_LABEL_DOCK_UNDOCK", + [ACTION_HIDE]: "ACTION_LABEL_HIDE", + [ACTION_REARRANGE]: "ACTION_LABEL_REARRANGE", + [ACTION_TOGGLE_FLOATING_EXTRAS]: "TOOLTIP_TOGGLE_FLOATING_EXTRAS", + [ACTION_UNDO]: "Undo", + [ACTION_REDO_Z]: "Redo", + [ACTION_REDO_Y]: "Redo" + }; + const DEFAULT_HOTKEYS = [ + // Creation - Enter based + { + action: ACTION_ADD, + key: "Enter", + modifiers: [], + scope: SCOPE.input, + isInputOnly: true, + requiresNode: false + }, + { + action: ACTION_ADD_SIBLING_AFTER, + key: "Enter", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: true, + requiresNode: false + }, + { + action: ACTION_ADD_SIBLING_BEFORE, + key: "Enter", + modifiers: ["Alt", "Shift"], + scope: SCOPE.input, + isInputOnly: true, + requiresNode: false + }, + { + action: ACTION_ADD_FOLLOW, + key: "Enter", + modifiers: ["Mod", "Alt"], + scope: SCOPE.input, + isInputOnly: true, + requiresNode: false + }, + { + action: ACTION_ADD_FOLLOW_FOCUS, + key: "Enter", + modifiers: ["Mod"], + scope: SCOPE.input, + isInputOnly: true, + requiresNode: false + }, + { + action: ACTION_ADD_FOLLOW_ZOOM, + key: "Enter", + modifiers: ["Mod", "Shift"], + scope: SCOPE.input, + isInputOnly: true, + requiresNode: false + }, + //Window + { + action: ACTION_DOCK_UNDOCK, + key: "Enter", + modifiers: ["Shift"], + scope: SCOPE.input, + isInputOnly: true, + requiresNode: false + }, + { + action: ACTION_HIDE, + key: "Escape", + modifiers: [], + scope: SCOPE.excalidraw, + isInputOnly: true, + requiresNode: false + }, + // Edit + { + action: ACTION_EDIT, + code: "KeyE", + modifiers: ["Mod"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + // Structure Modifiers + { + action: ACTION_TOGGLE_CHECKBOX, + code: "KeyL", + modifiers: ["Mod"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_CALENDAR, + code: "KeyD", + modifiers: ["Alt", "Mod"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: false + }, + { + action: ACTION_PIN, + code: "KeyP", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_BOX, + code: "KeyB", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_TOGGLE_BOUNDARY, + code: "KeyB", + modifiers: ["Alt", "Shift"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_TOGGLE_SUBMAP_ROOT, + code: "KeyJ", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_TOGGLE_GROUP, + code: "KeyG", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_TOGGLE_EMBED, + code: "KeyE", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + // Clipboard (Alt to distinguish from text editing) + { + action: ACTION_COPY, + code: "KeyC", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_CUT, + code: "KeyX", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_PASTE, + code: "KeyV", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: false + }, + { + action: ACTION_IMPORT_OUTLINE, + code: "KeyI", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + // View Actions + { + action: ACTION_REARRANGE, + code: "KeyR", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_ZOOM, + code: "KeyZ", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_FOCUS, + code: "KeyF", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: false + }, + //Navigation + { + action: ACTION_NAVIGATE, + key: "ArrowKeys", + modifiers: ["Alt"], + isNavigation: true, + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_NAVIGATE_ZOOM, + key: "ArrowKeys", + modifiers: ["Alt", "Shift"], + isNavigation: true, + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_NAVIGATE_FOCUS, + key: "ArrowKeys", + modifiers: ["Alt", "Mod"], + isNavigation: true, + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_SORT_ORDER, + code: "ArrowKeys", + modifiers: ["Mod"], + isNavigation: true, + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_FOLD, + code: "Digit1", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_FOLD_L1, + code: "Digit2", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + { + action: ACTION_FOLD_ALL, + code: "Digit3", + modifiers: ["Alt"], + scope: SCOPE.input, + isInputOnly: false, + requiresNode: true + }, + // Undo / Redo + { + action: ACTION_UNDO, + key: "z", + modifiers: ["Mod"], + scope: SCOPE.excalidraw, + isInputOnly: false, + hidden: true, + requiresNode: false + }, + { + action: ACTION_REDO_Z, + key: "z", + modifiers: ["Mod", "Shift"], + scope: SCOPE.excalidraw, + isInputOnly: false, + hidden: true, + requiresNode: false + }, + { + action: ACTION_REDO_Y, + key: "y", + modifiers: ["Mod"], + scope: SCOPE.excalidraw, + isInputOnly: false, + hidden: true, + requiresNode: false + } + ]; + const MAP_ROOT_CUSTOMDATA_KEYS = [ + "isAdditionalRoot", + "growthMode", + "autoLayoutDisabled", + "arrowType", + "fontsizeScale", + "multicolor", + "boxChildren", + "roundedCorners", + "maxWrapWidth", + "isSolidArrow", + "centerText", + "fillSweep", + "branchScale", + "baseStrokeWidth", + "layoutSettings" + ]; + const MINDMAP_FOCUS_STYLE_ID = "excalidraw-mindmap-focus-style"; + return { + VALUE_SETS, + FONT_SCALE_TYPES, + GROWTH_TYPES, + ZOOM_TYPES, + SCOPE, + ARROW_TYPES, + BRANCH_SCALE_TYPES, + ZOOM_LEVELS, + K_WIDTH, + K_FONTSIZE, + K_BOX, + K_ROUND, + K_BRANCH_SCALE, + K_BASE_WIDTH, + K_GROWTH, + K_MULTICOLOR, + K_UNDOCKED, + K_GROUP, + K_ARROWSTROKE, + K_CENTERTEXT, + K_ZOOM, + K_HOTKEYS, + K_PALETTE, + K_LAYOUT, + K_ARROW_TYPE, + K_FILL_SWEEP, + K_INJECT_LINK, + K_LINK_ALIAS, + K_PRESETS, + K_ACTIVE_PRESET, + LAYOUT_METADATA, + COLOR_CONTRAST_MIN, + COLOR_DISTINCT_THRESHOLD, + HUE_STEP_BASE, + HUE_STEP_JITTER, + SAT_BASE, + SAT_JITTER, + LIGHT_BASE_DARK, + LIGHT_JITTER_DARK, + LIGHT_BASE_LIGHT, + LIGHT_JITTER_LIGHT, + WRAP_WIDTH_MIN, + WRAP_WIDTH_MAX, + WRAP_WIDTH_STEP, + FLOAT_MODAL_OPACITY, + FLOAT_MODAL_OFFSET, + FLOAT_MODAL_MAX_HEIGHT, + NOTICE_DURATION_CONFLICT, + NOTICE_DURATION_GLOBAL_CONFLICT, + LAYOUT_DEFAULTS, + IMAGE_TYPES, + EMBEDED_OBJECT_WIDTH_ROOT, + EMBEDED_OBJECT_WIDTH_CHILD, + ACTION_ADD, + ACTION_ADD_SIBLING_AFTER, + ACTION_ADD_SIBLING_BEFORE, + ACTION_ADD_FOLLOW, + ACTION_ADD_FOLLOW_FOCUS, + ACTION_ADD_FOLLOW_ZOOM, + ACTION_SORT_ORDER, + ACTION_EDIT, + ACTION_TOGGLE_CHECKBOX, + ACTION_CALENDAR, + ACTION_PIN, + ACTION_BOX, + ACTION_TOGGLE_GROUP, + ACTION_COPY, + ACTION_CUT, + ACTION_PASTE, + ACTION_IMPORT_OUTLINE, + ACTION_ZOOM, + ACTION_FOCUS, + ACTION_NAVIGATE, + ACTION_NAVIGATE_ZOOM, + ACTION_NAVIGATE_FOCUS, + ACTION_FOLD, + ACTION_FOLD_L1, + ACTION_FOLD_ALL, + ACTION_TOGGLE_BOUNDARY, + ACTION_TOGGLE_SUBMAP_ROOT, + ACTION_TOGGLE_EMBED, + ACTION_DOCK_UNDOCK, + ACTION_HIDE, + ACTION_REARRANGE, + ACTION_TOGGLE_FLOATING_EXTRAS, + ACTION_UNDO, + ACTION_REDO_Z, + ACTION_REDO_Y, + ACTION_LABEL_KEYS, + DEFAULT_HOTKEYS, + MAP_ROOT_CUSTOMDATA_KEYS, + MINDMAP_FOCUS_STYLE_ID + }; + } + + // src/scripts/mindmap-builder/publicApi.js + function installMindmapPublicApi(runtimeContext) { + (() => { + const MMError = { + NOT_READY: "NOT_READY", + NO_VIEW: "NO_VIEW", + INVALID_VIEW: "INVALID_VIEW", + INVALID_NODE: "INVALID_NODE", + NO_SELECTION: "NO_SELECTION", + NO_ROOT: "NO_ROOT", + AUTO_LAYOUT_DISABLED: "AUTO_LAYOUT_DISABLED", + INVALID_ACTION: "INVALID_ACTION", + INVALID_ARGUMENT: "INVALID_ARGUMENT", + OPERATION_FAILED: "OPERATION_FAILED" + }; + const mmOk = (data) => ({ + ok: true, + data + }); + const mmErr = (code, message, details) => ({ + ok: false, + error: details === void 0 ? { + code, + message + } : { + code, + message, + details + } + }); + const requireView = () => { + if (!runtimeContext.isViewSet()) return mmErr(MMError.NO_VIEW, "No active ExcalidrawView"); + return null; + }; + const findNodeById = (nodeId) => { + const all = runtimeContext.ea.getViewElements(); + return all.find((el) => el.id === nodeId); + }; + const resolveNode = (nodeId) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + if (nodeId) { + const node = findNodeById(nodeId); + if (!node) return mmErr(MMError.INVALID_NODE, `Node not found: ${nodeId}`); + return mmOk(node); + } + const sel = runtimeContext.getMindmapNodeFromSelection(); + if (!sel) return mmErr(MMError.NO_SELECTION, "No mindmap node selected"); + return mmOk(sel); + }; + const getNodeOntology = (node, allElements) => { + const incomingArrow = allElements.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === node.id + ); + return incomingArrow ? runtimeContext.ea.getBoundTextElement(incomingArrow, true)?.sceneElement?.rawText || "" : ""; + }; + const extractMapConfig = (rootNode) => ({ + growthMode: rootNode.customData?.growthMode || runtimeContext.currentModalGrowthMode, + autoLayoutDisabled: rootNode.customData?.autoLayoutDisabled === true, + arrowType: rootNode.customData?.arrowType ?? runtimeContext.arrowType, + fontsizeScale: rootNode.customData?.fontsizeScale ?? runtimeContext.fontsizeScale, + multicolor: typeof rootNode.customData?.multicolor === "boolean" ? rootNode.customData.multicolor : runtimeContext.multicolor, + boxChildren: typeof rootNode.customData?.boxChildren === "boolean" ? rootNode.customData.boxChildren : runtimeContext.boxChildren, + roundedCorners: typeof rootNode.customData?.roundedCorners === "boolean" ? rootNode.customData.roundedCorners : runtimeContext.roundedCorners, + maxWrapWidth: typeof rootNode.customData?.maxWrapWidth === "number" ? rootNode.customData.maxWrapWidth : runtimeContext.maxWidth, + isSolidArrow: typeof rootNode.customData?.isSolidArrow === "boolean" ? rootNode.customData.isSolidArrow : runtimeContext.isSolidArrow, + centerText: typeof rootNode.customData?.centerText === "boolean" ? rootNode.customData.centerText : runtimeContext.centerText, + fillSweep: typeof rootNode.customData?.fillSweep === "boolean" ? rootNode.customData.fillSweep : runtimeContext.fillSweep, + branchScale: rootNode.customData?.branchScale ?? runtimeContext.branchScale, + baseStrokeWidth: typeof rootNode.customData?.baseStrokeWidth === "number" ? rootNode.customData.baseStrokeWidth : runtimeContext.baseStrokeWidth, + layoutSettings: JSON.parse( + JSON.stringify(rootNode.customData?.layoutSettings ?? runtimeContext.layoutSettings) + ) + }); + const API_ACTIONS = { + ADD: runtimeContext.ACTION_ADD, + ADD_SIBLING_AFTER: runtimeContext.ACTION_ADD_SIBLING_AFTER, + ADD_SIBLING_BEFORE: runtimeContext.ACTION_ADD_SIBLING_BEFORE, + ADD_FOLLOW: runtimeContext.ACTION_ADD_FOLLOW, + ADD_FOLLOW_FOCUS: runtimeContext.ACTION_ADD_FOLLOW_FOCUS, + ADD_FOLLOW_ZOOM: runtimeContext.ACTION_ADD_FOLLOW_ZOOM, + EDIT: runtimeContext.ACTION_EDIT, + TOGGLE_CHECKBOX: runtimeContext.ACTION_TOGGLE_CHECKBOX, + PIN: runtimeContext.ACTION_PIN, + BOX: runtimeContext.ACTION_BOX, + TOGGLE_EMBED: runtimeContext.ACTION_TOGGLE_EMBED, + TOGGLE_BOUNDARY: runtimeContext.ACTION_TOGGLE_BOUNDARY, + TOGGLE_SUBMAP_ROOT: runtimeContext.ACTION_TOGGLE_SUBMAP_ROOT, + TOGGLE_GROUP: runtimeContext.ACTION_TOGGLE_GROUP, + FOLD: runtimeContext.ACTION_FOLD, + FOLD_L1: runtimeContext.ACTION_FOLD_L1, + FOLD_ALL: runtimeContext.ACTION_FOLD_ALL, + COPY: runtimeContext.ACTION_COPY, + CUT: runtimeContext.ACTION_CUT, + PASTE: runtimeContext.ACTION_PASTE, + ZOOM: runtimeContext.ACTION_ZOOM, + FOCUS: runtimeContext.ACTION_FOCUS, + NAVIGATE: runtimeContext.ACTION_NAVIGATE, + NAVIGATE_ZOOM: runtimeContext.ACTION_NAVIGATE_ZOOM, + NAVIGATE_FOCUS: runtimeContext.ACTION_NAVIGATE_FOCUS, + SORT_ORDER: runtimeContext.ACTION_SORT_ORDER, + REARRANGE: runtimeContext.ACTION_REARRANGE, + DOCK_UNDOCK: runtimeContext.ACTION_DOCK_UNDOCK, + HIDE: runtimeContext.ACTION_HIDE, + UNDO: runtimeContext.ACTION_UNDO, + REDO_Z: runtimeContext.ACTION_REDO_Z, + REDO_Y: runtimeContext.ACTION_REDO_Y + }; + const API_ERROR_DOC = { + [MMError.NOT_READY]: "MindMapBuilder runtime is not initialized", + [MMError.NO_VIEW]: "No active ExcalidrawView is set", + [MMError.INVALID_VIEW]: "The provided view is missing or not an ExcalidrawView", + [MMError.INVALID_NODE]: "The provided node id does not exist in the active view", + [MMError.NO_SELECTION]: "No mindmap node is currently selected", + [MMError.NO_ROOT]: "Unable to resolve a root/settings root for the selected node", + [MMError.AUTO_LAYOUT_DISABLED]: "The map has auto-layout disabled", + [MMError.INVALID_ACTION]: "The provided action is unknown", + [MMError.INVALID_ARGUMENT]: "One or more arguments are invalid", + [MMError.OPERATION_FAILED]: "The underlying operation failed at runtime" + }; + const API_METHOD_SPEC = { + ready: { + summary: "Returns whether the API runtime is initialized", + params: [], + returns: "boolean" + }, + listMethods: { + summary: "Returns the list of public method names", + params: [], + returns: "MMResult<{methods:string[]}>" + }, + getErrorCodes: { + summary: "Returns known error codes and their meaning", + params: [], + returns: "MMResult<{errors:Record}>" + }, + spec: { + summary: "Returns machine-readable API metadata for agents", + params: [], + returns: "MMResult<{version:string,actions:string[],errors:Record,methods:object}>" + }, + help: { + summary: "Returns method docs for one method or the full API", + params: [ + { + name: "method", + type: "string", + required: false + }, + { + name: "format", + type: "string", + required: false, + enum: ["object", "text"] + } + ], + returns: "MMResult" + }, + validate: { + summary: "Validates arguments against the API method contract", + params: [ + { + name: "method", + type: "string", + required: true + }, + { + name: "args", + type: "any", + required: false + } + ], + returns: "MMResult<{valid:boolean,errors:string[],normalizedArgs:object}>" + }, + getCapabilities: { + summary: "Returns available actions and methods", + params: [], + returns: "{actions:string[],methods:string[]}" + }, + setView: { + summary: "Sets the active ExcalidrawView context", + params: [ + { + name: "view", + type: "object", + required: true + } + ], + returns: "MMResult<{view:ExcalidrawView|null,filePath:string|null}>" + }, + getView: { + summary: "Gets the current ExcalidrawView and filepath", + params: [], + returns: "MMResult<{view:ExcalidrawView|null,filePath:string|null}>" + }, + getSelection: { + summary: "Returns selected node id and selected element ids", + params: [], + returns: "MMResult<{nodeId:string|null,elementIds:string[]}>" + }, + selectNode: { + summary: "Selects a node by id or current selected node when omitted", + params: [ + { + name: "nodeId", + type: "string", + required: false + } + ], + returns: "MMResult<{nodeId:string}>" + }, + setInputFieldDockStatus: { + summary: "Forces docked/undocked input mode and applies matching sidepanel visibility", + params: [ + { + name: "isDocked", + type: "boolean", + required: true + } + ], + returns: "Promise>" + }, + getMindMapRoots: { + summary: "Returns top-level mindmap root node ids", + params: [], + returns: "MMResult<{rootIds:string[]}>" + }, + getMapInfo: { + summary: "Returns hierarchy info for a node or current selection", + params: [ + { + name: "nodeId", + type: "string", + required: false + } + ], + returns: "MMResult<{nodeId:string,rootId:string,settingsRootId:string,depth:number}>" + }, + getNodeText: { + summary: "Returns node text and ontology", + params: [ + { + name: "nodeId", + type: "string", + required: false + } + ], + returns: "MMResult<{nodeId:string,text:string,ontology:string}>" + }, + performAction: { + summary: "Runs one built-in mindmap action", + params: [ + { + name: "action", + type: "string", + required: true, + enum: Object.values(API_ACTIONS) + }, + { + name: "event", + type: "object", + required: false + } + ], + returns: "Promise>" + }, + refreshMapLayout: { + summary: "Refreshes map layout from the selected node or provided node id", + params: [ + { + name: "nodeId", + type: "string", + required: false + } + ], + returns: "Promise>" + }, + addNode: { + summary: "Adds a node under selected node or a provided parent", + params: [ + { + name: "text", + type: "string", + required: true + }, + { + name: "parentId", + type: "string", + required: false + }, + { + name: "ontology", + type: "string", + required: false + }, + { + name: "follow", + type: "boolean", + required: false + }, + { + name: "position", + type: "string", + required: false + } + ], + returns: "Promise>" + }, + importMarkdown: { + summary: "Imports markdown bullet hierarchy into map", + params: [ + { + name: "markdown", + type: "string", + required: true + }, + { + name: "parentId", + type: "string", + required: false + } + ], + returns: "Promise>" + }, + exportMarkdown: { + summary: "Exports selected branch to markdown through clipboard", + params: [ + { + name: "nodeId", + type: "string", + required: false + }, + { + name: "cut", + type: "boolean", + required: false + } + ], + returns: "Promise>" + }, + toggleSubmapRoot: { + summary: "Toggles or forces additional-root state on node", + params: [ + { + name: "nodeId", + type: "string", + required: false + }, + { + name: "enabled", + type: "boolean", + required: false + } + ], + returns: "Promise>" + }, + getMapConfig: { + summary: "Returns effective map config for node/root", + params: [ + { + name: "nodeId", + type: "string", + required: false + } + ], + returns: "MMResult<{rootId:string,settingsRootId:string,config:object}>" + }, + setMapConfig: { + summary: "Patches map config and optionally relayouts", + params: [ + { + name: "patch", + type: "object", + required: true + }, + { + name: "nodeId", + type: "string", + required: false + }, + { + name: "relayout", + type: "boolean", + required: false + } + ], + returns: "Promise>" + }, + getBranchElementIds: { + summary: "Returns branch element ids with optional decorations/crosslinks", + params: [ + { + name: "nodeId", + type: "string", + required: true + }, + { + name: "includeDecorations", + type: "boolean", + required: false + }, + { + name: "includeCrosslinks", + type: "boolean", + required: false + } + ], + returns: "MMResult<{ids:string[]}>" + }, + getProjectElementIds: { + summary: "Returns all project element ids for a root", + params: [ + { + name: "rootId", + type: "string", + required: true + } + ], + returns: "MMResult<{ids:string[]}>" + }, + getElementIdsByRole: { + summary: "Returns role-based element id groups for a root", + params: [ + { + name: "rootId", + type: "string", + required: true + } + ], + returns: "MMResult<{nodes:string[],branchArrows:string[],crossLinks:string[],boundaries:string[],decorations:string[],boundTexts:string[]}>" + }, + getGlobalConfig: { + summary: "Returns the global map and layout configurations, including custom color palette", + params: [], + returns: "MMResult<{config:object}>" + }, + setGlobalConfig: { + summary: "Updates the global map and layout configurations and persists them", + params: [ + { + name: "patch", + type: "object", + required: true + } + ], + returns: "Promise>" + }, + getConfigSchema: { + summary: "Returns the schema, allowed values, and definitions for map configurations", + params: [], + returns: "MMResult<{schema:object}>" + } + }; + const cloneJSON = (value) => JSON.parse(JSON.stringify(value)); + const normalizeValidationArgs = (method, args) => { + const spec = API_METHOD_SPEC[method]; + if (!spec) return null; + if (args === void 0 || args === null) return {}; + if (Array.isArray(args)) { + const out = {}; + spec.params.forEach((p, idx) => { + if (idx < args.length) out[p.name] = args[idx]; + }); + return out; + } + if (typeof args === "object") + return { + ...args + }; + if (spec.params.length === 1) + return { + [spec.params[0].name]: args + }; + return null; + }; + const isTypeMatch = (value, type) => { + if (type === "any") return true; + if (type === "array") return Array.isArray(value); + if (type === "object") + return value !== null && typeof value === "object" && !Array.isArray(value); + return typeof value === type; + }; + const validateMethodArgs = (method, args) => { + const spec = API_METHOD_SPEC[method]; + if (!spec) { + return { + valid: false, + errors: [`Unknown method: ${method}`], + normalizedArgs: {} + }; + } + const normalizedArgs = normalizeValidationArgs(method, args); + if (normalizedArgs === null) { + return { + valid: false, + errors: [ + "Arguments must be an object, an array of positional values, or a single value for single-parameter methods" + ], + normalizedArgs: {} + }; + } + const errors = []; + spec.params.forEach((p) => { + const v = normalizedArgs[p.name]; + if (p.required && (v === void 0 || v === null || p.type === "string" && v === "")) { + errors.push(`Missing required parameter: ${p.name}`); + return; + } + if (v !== void 0 && v !== null && !isTypeMatch(v, p.type)) { + errors.push( + `Invalid type for ${p.name}: expected ${p.type}, got ${Array.isArray(v) ? "array" : typeof v}` + ); + } + if (p.enum && v !== void 0 && v !== null && !p.enum.includes(v)) { + errors.push(`Invalid value for ${p.name}: ${v}`); + } + }); + return { + valid: errors.length === 0, + errors, + normalizedArgs + }; + }; + const buildHelpText = (methodName, doc) => { + const params = doc.params.map((p) => { + const req = p.required ? "required" : "optional"; + const enumValues = p.enum ? ` | enum: ${p.enum.join(", ")}` : ""; + return `- ${p.name}: ${p.type} (${req})${enumValues}`; + }); + const paramsText = params.length ? params.join("\n") : "- (none)"; + return [ + `${methodName}`, + `${doc.summary}`, + "Parameters:", + paramsText, + `Returns: ${doc.returns}` + ].join("\n"); + }; + const API = { + version: "1.0.0", + Actions: Object.freeze(API_ACTIONS), + Errors: Object.freeze(MMError), + ready: () => !!runtimeContext.ea, + listMethods: () => mmOk({ + methods: Object.keys(API_METHOD_SPEC) + }), + getErrorCodes: () => mmOk({ + errors: cloneJSON(API_ERROR_DOC) + }), + spec: () => mmOk({ + version: API.version, + actions: Object.values(API_ACTIONS), + errors: cloneJSON(API_ERROR_DOC), + methods: cloneJSON(API_METHOD_SPEC) + }), + help: (method, format = "object") => { + if (method !== void 0 && (typeof method !== "string" || method.trim() === "")) { + return mmErr( + MMError.INVALID_ARGUMENT, + "help expects method to be a non-empty string when provided" + ); + } + if (!["object", "text"].includes(format)) { + return mmErr(MMError.INVALID_ARGUMENT, "help format must be 'object' or 'text'"); + } + if (!method) { + if (format === "text") { + const lines = Object.keys(API_METHOD_SPEC).map( + (name) => `${name}: ${API_METHOD_SPEC[name].summary}` + ); + return mmOk([`MindMapBuilder API v${API.version}`, ...lines].join("\n")); + } + return mmOk({ + version: API.version, + methods: cloneJSON(API_METHOD_SPEC), + actions: Object.values(API_ACTIONS), + errors: cloneJSON(API_ERROR_DOC) + }); + } + const doc = API_METHOD_SPEC[method]; + if (!doc) { + return mmErr(MMError.INVALID_ARGUMENT, `Unknown method: ${method}`); + } + if (format === "text") return mmOk(buildHelpText(method, doc)); + return mmOk({ + method, + ...cloneJSON(doc) + }); + }, + validate: (method, args) => { + if (typeof method !== "string" || method.trim() === "") { + return mmErr(MMError.INVALID_ARGUMENT, "validate requires a method name"); + } + const result = validateMethodArgs(method, args); + return mmOk(result); + }, + getCapabilities: () => ({ + actions: Object.values(API_ACTIONS), + methods: Object.keys(API) + }), + setView: (view) => { + if (!view) return mmErr(MMError.INVALID_VIEW, "setView expects an ExcalidrawView object"); + const isValid = !!runtimeContext.ea?.isExcalidrawView(view); + if (!isValid) + return mmErr(MMError.INVALID_VIEW, "setView expects an ExcalidrawView object"); + try { + runtimeContext.ea.setView(view); + runtimeContext.ea.clear(); + runtimeContext.ensureNodeSelected(); + runtimeContext.updateUI(); + return mmOk({ + view: runtimeContext.ea.targetView, + filePath: runtimeContext.ea.targetView?.file?.path || null + }); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "Failed to set view", e); + } + }, + getView: () => mmOk({ + view: runtimeContext.ea.targetView || null, + filePath: runtimeContext.ea.targetView?.file?.path || null + }), + getSelection: () => { + const viewErr = requireView(); + if (viewErr) return viewErr; + return mmOk({ + nodeId: runtimeContext.getMindmapNodeFromSelection()?.id || null, + elementIds: runtimeContext.ea.getViewSelectedElements().map((e) => e.id) + }); + }, + selectNode: (nodeId) => { + const nodeRes = resolveNode(nodeId); + if (!nodeRes.ok) return nodeRes; + runtimeContext.selectNodeInView(nodeRes.data); + runtimeContext.performAction(runtimeContext.ACTION_FOCUS); + runtimeContext.updateUI(nodeRes.data); + return mmOk({ + nodeId: nodeRes.data.id + }); + }, + setInputFieldDockStatus: async ({ isDocked } = {}) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + if (typeof isDocked !== "boolean") { + return mmErr( + MMError.INVALID_ARGUMENT, + "setInputFieldDockStatus requires a boolean isDocked" + ); + } + try { + const sidepanelLeaf = runtimeContext.ea.getSidepanelLeaf?.(); + const isSidepanelVisible = !!sidepanelLeaf?.isVisible?.(); + if (isDocked) { + if (runtimeContext.isUndocked) { + await runtimeContext.performAction(runtimeContext.ACTION_DOCK_UNDOCK); + } else if (!isSidepanelVisible && sidepanelLeaf) { + app.workspace.revealLeaf(sidepanelLeaf); + } + } else { + if (!runtimeContext.isUndocked) { + await runtimeContext.performAction(runtimeContext.ACTION_DOCK_UNDOCK); + } else if (isSidepanelVisible) { + runtimeContext.ea.toggleSidepanelView(); + } + } + const finalSidepanelLeaf = runtimeContext.ea.getSidepanelLeaf?.(); + const sidepanelVisible = !!finalSidepanelLeaf?.isVisible?.(); + return mmOk({ + isDocked: !runtimeContext.isUndocked, + isUndocked: runtimeContext.isUndocked, + sidepanelVisible + }); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "setInputFieldDockStatus failed", e); + } + }, + getMindMapRoots: () => { + const viewErr = requireView(); + if (viewErr) return viewErr; + return mmOk({ + rootIds: runtimeContext.getMasterRoots() + }); + }, + getMapInfo: (nodeId) => { + const nodeRes = resolveNode(nodeId); + if (!nodeRes.ok) return nodeRes; + const node = nodeRes.data; + const all = runtimeContext.ea.getViewElements(); + const info = runtimeContext.getHierarchy(node, all); + const settingsRoot = runtimeContext.getSettingsRootNode(node, all); + return mmOk({ + nodeId: node.id, + rootId: info.rootId, + settingsRootId: settingsRoot?.id || info.rootId, + depth: info.depth + }); + }, + getNodeText: (nodeId) => { + const nodeRes = resolveNode(nodeId); + if (!nodeRes.ok) return nodeRes; + const node = nodeRes.data; + const all = runtimeContext.ea.getViewElements(); + return mmOk({ + nodeId: node.id, + text: runtimeContext.getTextFromNode(all, node, true, true), + ontology: getNodeOntology(node, all) + }); + }, + performAction: async (action, event = {}) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + if (!action || !Object.values(API_ACTIONS).includes(action)) { + return mmErr(MMError.INVALID_ACTION, `Unknown action: ${action}`); + } + try { + await runtimeContext.performAction(action, event); + return mmOk(void 0); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "performAction failed", e); + } + }, + refreshMapLayout: async (nodeId) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + let sel = null; + if (nodeId) { + const node = findNodeById(nodeId); + if (!node) return mmErr(MMError.INVALID_NODE, `Node not found: ${nodeId}`); + sel = node; + } + try { + await runtimeContext.refreshMapLayout(sel); + const target = sel || runtimeContext.getMindmapNodeFromSelection(); + if (!target) return mmErr(MMError.NO_SELECTION, "No selected node for layout refresh"); + const info = runtimeContext.getHierarchy(target, runtimeContext.ea.getViewElements()); + return mmOk({ + rootId: info.rootId + }); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "refreshMapLayout failed", e); + } + }, + addNode: async ({ text, parentId, ontology, follow = false, position } = {}) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + if (!text || typeof text !== "string") { + return mmErr(MMError.INVALID_ARGUMENT, "addNode requires non-empty text"); + } + if (parentId) { + const parent = findNodeById(parentId); + if (!parent) return mmErr(MMError.INVALID_NODE, `Parent node not found: ${parentId}`); + runtimeContext.selectNodeInView(parent); + } + try { + const node = await runtimeContext.addNode( + text, + follow, + false, + null, + null, + position || null, + ontology ?? null + ); + if (!node) return mmErr(MMError.OPERATION_FAILED, "Failed to create node"); + const all = runtimeContext.ea.getViewElements(); + const info = runtimeContext.getHierarchy(node, all); + const arrow = all.find( + (a) => a.type === "arrow" && a.customData?.isBranch && a.endBinding?.elementId === node.id + ); + return mmOk({ + nodeId: node.id, + arrowId: arrow?.id, + rootId: info.rootId + }); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "addNode failed", e); + } + }, + importMarkdown: async ({ markdown, parentId } = {}) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + if (typeof markdown !== "string" || markdown.trim() === "") { + return mmErr( + MMError.INVALID_ARGUMENT, + "importMarkdown requires a non-empty markdown string" + ); + } + if (parentId) { + const parent = findNodeById(parentId); + if (!parent) return mmErr(MMError.INVALID_NODE, `Parent node not found: ${parentId}`); + runtimeContext.selectNodeInView(parent); + } + const beforeIds = new Set(runtimeContext.ea.getViewElements().map((e) => e.id)); + try { + await runtimeContext.importTextToMap(markdown); + const after = runtimeContext.ea.getViewElements(); + const addedNodeIds = after.filter((e) => !beforeIds.has(e.id) && e.type !== "arrow" && !e.customData?.isBoundary).map((e) => e.id); + let rootId = null; + if (parentId) { + const parent = after.find((e) => e.id === parentId); + rootId = parent ? runtimeContext.getHierarchy(parent, after).rootId : null; + } else if (addedNodeIds.length > 0) { + const n = after.find((e) => e.id === addedNodeIds[0]); + rootId = n ? runtimeContext.getHierarchy(n, after).rootId : null; + } + return mmOk({ + addedNodeIds, + rootId + }); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "importMarkdown failed", e); + } + }, + exportMarkdown: async ({ nodeId, cut = false } = {}) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + if (nodeId) { + const node = findNodeById(nodeId); + if (!node) return mmErr(MMError.INVALID_NODE, `Node not found: ${nodeId}`); + runtimeContext.selectNodeInView(node); + } + try { + const markdown = await runtimeContext.copyMapAsText(!!cut, false); + return mmOk({ + markdown + }); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "exportMarkdown failed", e); + } + }, + toggleSubmapRoot: async ({ nodeId, enabled } = {}) => { + const nodeRes = resolveNode(nodeId); + if (!nodeRes.ok) return nodeRes; + const node = nodeRes.data; + const current = node.customData?.isAdditionalRoot === true; + if (typeof enabled === "boolean" && enabled === current) { + return mmOk({ + nodeId: node.id, + enabled: current + }); + } + runtimeContext.selectNodeInView(node); + try { + await runtimeContext.toggleSubmapRoot(); + const updated = findNodeById(node.id); + return mmOk({ + nodeId: node.id, + enabled: updated?.customData?.isAdditionalRoot === true + }); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "toggleSubmapRoot failed", e); + } + }, + getMapConfig: (nodeId) => { + const nodeRes = resolveNode(nodeId); + if (!nodeRes.ok) return nodeRes; + const node = nodeRes.data; + const all = runtimeContext.ea.getViewElements(); + const info = runtimeContext.getHierarchy(node, all); + const settingsRoot = runtimeContext.getSettingsRootNode(node, all); + if (!settingsRoot) return mmErr(MMError.NO_ROOT, "Could not resolve settings root"); + return mmOk({ + rootId: info.rootId, + settingsRootId: settingsRoot.id, + config: extractMapConfig(settingsRoot) + }); + }, + setMapConfig: async ({ patch, nodeId, relayout = true } = {}) => { + const nodeRes = resolveNode(nodeId); + if (!nodeRes.ok) return nodeRes; + const node = nodeRes.data; + if (!patch || typeof patch !== "object") { + return mmErr(MMError.INVALID_ARGUMENT, "setMapConfig requires a patch object"); + } + try { + runtimeContext.selectNodeInView(node); + const info = await runtimeContext.updateRootNodeCustomData( + { + ...patch + }, + node + ); + if (!info) return mmErr(MMError.OPERATION_FAILED, "Failed to update map config"); + if (relayout) await runtimeContext.refreshMapLayout(node); + return mmOk({ + rootId: info.rootId, + settingsRootId: info.settingsRootId + }); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "setMapConfig failed", e); + } + }, + getBranchElementIds: ({ + nodeId, + includeDecorations = true, + includeCrosslinks = true + } = {}) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + if (!nodeId) return mmErr(MMError.INVALID_ARGUMENT, "getBranchElementIds requires nodeId"); + const node = findNodeById(nodeId); + if (!node) return mmErr(MMError.INVALID_NODE, `Node not found: ${nodeId}`); + const all = runtimeContext.ea.getViewElements(); + let ids = runtimeContext.getBranchElementIds(nodeId, all); + if (includeDecorations || includeCrosslinks) { + const info = runtimeContext.getHierarchy(node, all); + const extras = runtimeContext.getDecorationAndCrossLinkIdsForBranches( + ids, + all, + info.rootId + ); + if (!includeDecorations || !includeCrosslinks) { + const extraEls = extras.map((id) => all.find((e) => e.id === id)).filter(Boolean); + const filteredExtra = extraEls.filter((e) => { + if (e.type === "arrow") return includeCrosslinks; + return includeDecorations; + }); + ids = ids.concat(filteredExtra.map((e) => e.id)); + } else { + ids = ids.concat(extras); + } + } + return mmOk({ + ids: Array.from(new Set(ids)) + }); + }, + getProjectElementIds: (rootId) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + if (!rootId) return mmErr(MMError.INVALID_ARGUMENT, "getProjectElementIds requires rootId"); + const all = runtimeContext.ea.getViewElements(); + const root = all.find((e) => e.id === rootId); + if (!root) return mmErr(MMError.INVALID_NODE, `Root not found: ${rootId}`); + const project = runtimeContext.getMindmapProjectElements(rootId, all); + return mmOk({ + ids: project.map((e) => e.id) + }); + }, + getElementIdsByRole: (rootId) => { + const viewErr = requireView(); + if (viewErr) return viewErr; + if (!rootId) return mmErr(MMError.INVALID_ARGUMENT, "getElementIdsByRole requires rootId"); + const all = runtimeContext.ea.getViewElements(); + const root = all.find((e) => e.id === rootId); + if (!root) return mmErr(MMError.INVALID_NODE, `Root not found: ${rootId}`); + const branchIds = runtimeContext.getBranchElementIds(rootId, all); + const decorationAndCrossLinkIds = runtimeContext.getDecorationAndCrossLinkIdsForBranches( + branchIds, + all, + rootId + ); + const project = runtimeContext.getMindmapProjectElements(rootId, all); + const nodes = branchIds.map((id) => all.find((e) => e.id === id)).filter((e) => e && e.type !== "arrow" && !e.customData?.isBoundary).map((e) => e.id); + const boundaries = project.filter((e) => e.customData?.isBoundary).map((e) => e.id); + const branchArrows = project.filter((e) => e.type === "arrow" && e.customData?.isBranch).map((e) => e.id); + const crossLinks = project.filter((e) => e.type === "arrow" && !e.customData?.isBranch).map((e) => e.id); + const boundTexts = project.filter((e) => e.type === "text").filter((t) => { + if (t.containerId) return true; + return project.some((el) => el.boundElements?.some((be) => be.id === t.id)); + }).map((e) => e.id); + const decorationSet = new Set(decorationAndCrossLinkIds); + const roleSet = /* @__PURE__ */ new Set([ + ...nodes, + ...boundaries, + ...branchArrows, + ...crossLinks, + ...boundTexts + ]); + const decorations = project.filter( + (e) => decorationSet.has(e.id) || !roleSet.has(e.id) && !branchIds.includes(e.id) + ).filter((e) => !crossLinks.includes(e.id) && !boundaries.includes(e.id)).map((e) => e.id); + return mmOk({ + nodes: Array.from(new Set(nodes)), + branchArrows: Array.from(new Set(branchArrows)), + crossLinks: Array.from(new Set(crossLinks)), + boundaries: Array.from(new Set(boundaries)), + decorations: Array.from(new Set(decorations)), + boundTexts: Array.from(new Set(boundTexts)) + }); + }, + getGlobalConfig: () => { + return mmOk({ + config: { + growthMode: runtimeContext.currentModalGrowthMode, + autoLayoutDisabled: runtimeContext.autoLayoutDisabled, + arrowType: runtimeContext.arrowType, + fontsizeScale: runtimeContext.fontsizeScale, + multicolor: runtimeContext.multicolor, + boxChildren: runtimeContext.boxChildren, + roundedCorners: runtimeContext.roundedCorners, + maxWrapWidth: runtimeContext.maxWidth, + isSolidArrow: runtimeContext.isSolidArrow, + centerText: runtimeContext.centerText, + fillSweep: runtimeContext.fillSweep, + branchScale: runtimeContext.branchScale, + baseStrokeWidth: runtimeContext.baseStrokeWidth, + customPalette: cloneJSON(runtimeContext.customPalette), + layoutSettings: cloneJSON(runtimeContext.layoutSettings) + } + }); + }, + setGlobalConfig: async ({ patch } = {}) => { + if (!patch || typeof patch !== "object") { + return mmErr(MMError.INVALID_ARGUMENT, "setGlobalConfig requires a patch object"); + } + try { + let requiresSave = false; + if (patch.growthMode && runtimeContext.GROWTH_TYPES.includes(patch.growthMode)) { + runtimeContext.currentModalGrowthMode = patch.growthMode; + runtimeContext.setVal(runtimeContext.K_GROWTH, patch.growthMode); + requiresSave = true; + } + if (typeof patch.autoLayoutDisabled === "boolean") { + runtimeContext.autoLayoutDisabled = patch.autoLayoutDisabled; + } + if (patch.arrowType && runtimeContext.ARROW_TYPES.includes(patch.arrowType)) { + runtimeContext.arrowType = patch.arrowType; + runtimeContext.setVal(runtimeContext.K_ARROW_TYPE, patch.arrowType); + requiresSave = true; + } + if (patch.fontsizeScale && runtimeContext.FONT_SCALE_TYPES.includes(patch.fontsizeScale)) { + runtimeContext.fontsizeScale = patch.fontsizeScale; + runtimeContext.setVal(runtimeContext.K_FONTSIZE, patch.fontsizeScale); + requiresSave = true; + } + if (patch.branchScale && runtimeContext.BRANCH_SCALE_TYPES.includes(patch.branchScale)) { + runtimeContext.branchScale = patch.branchScale; + runtimeContext.setVal(runtimeContext.K_BRANCH_SCALE, patch.branchScale); + requiresSave = true; + } + if (typeof patch.multicolor === "boolean") { + runtimeContext.multicolor = patch.multicolor; + runtimeContext.setVal(runtimeContext.K_MULTICOLOR, patch.multicolor); + requiresSave = true; + } + if (typeof patch.boxChildren === "boolean") { + runtimeContext.boxChildren = patch.boxChildren; + runtimeContext.setVal(runtimeContext.K_BOX, patch.boxChildren); + requiresSave = true; + } + if (typeof patch.roundedCorners === "boolean") { + runtimeContext.roundedCorners = patch.roundedCorners; + runtimeContext.setVal(runtimeContext.K_ROUND, patch.roundedCorners); + requiresSave = true; + } + if (typeof patch.maxWrapWidth === "number") { + runtimeContext.maxWidth = patch.maxWrapWidth; + runtimeContext.setVal(runtimeContext.K_WIDTH, patch.maxWrapWidth); + requiresSave = true; + } + if (typeof patch.isSolidArrow === "boolean") { + runtimeContext.isSolidArrow = patch.isSolidArrow; + runtimeContext.setVal(runtimeContext.K_ARROWSTROKE, patch.isSolidArrow); + requiresSave = true; + } + if (typeof patch.centerText === "boolean") { + runtimeContext.centerText = patch.centerText; + runtimeContext.setVal(runtimeContext.K_CENTERTEXT, patch.centerText); + requiresSave = true; + } + if (typeof patch.fillSweep === "boolean") { + runtimeContext.fillSweep = patch.fillSweep; + runtimeContext.setVal(runtimeContext.K_FILL_SWEEP, patch.fillSweep); + requiresSave = true; + } + if (typeof patch.baseStrokeWidth === "number") { + runtimeContext.baseStrokeWidth = patch.baseStrokeWidth; + runtimeContext.setVal(runtimeContext.K_BASE_WIDTH, patch.baseStrokeWidth); + requiresSave = true; + } + if (patch.customPalette && typeof patch.customPalette === "object") { + runtimeContext.customPalette = { + ...runtimeContext.customPalette, + ...patch.customPalette + }; + runtimeContext.setVal(runtimeContext.K_PALETTE, runtimeContext.customPalette, true); + requiresSave = true; + } + if (patch.layoutSettings && typeof patch.layoutSettings === "object") { + runtimeContext.layoutSettings = { + ...runtimeContext.layoutSettings, + ...patch.layoutSettings + }; + runtimeContext.setVal(runtimeContext.K_LAYOUT, runtimeContext.layoutSettings, true); + requiresSave = true; + } + if (requiresSave) { + await runtimeContext.saveSettings(); + runtimeContext.updateUI(); + } + return mmOk({ success: true }); + } catch (e) { + return mmErr(MMError.OPERATION_FAILED, "setGlobalConfig failed", e); + } + }, + getConfigSchema: () => { + const schema = { + growthMode: { type: "string", valueset: runtimeContext.GROWTH_TYPES }, + autoLayoutDisabled: { type: "boolean" }, + arrowType: { type: "string", valueset: runtimeContext.ARROW_TYPES }, + fontsizeScale: { type: "string", valueset: runtimeContext.FONT_SCALE_TYPES }, + branchScale: { type: "string", valueset: runtimeContext.BRANCH_SCALE_TYPES }, + multicolor: { type: "boolean" }, + boxChildren: { type: "boolean" }, + roundedCorners: { type: "boolean" }, + maxWrapWidth: { type: "number" }, + isSolidArrow: { type: "boolean" }, + centerText: { type: "boolean" }, + fillSweep: { type: "boolean" }, + baseStrokeWidth: { type: "number" }, + customPalette: { + type: "object", + properties: { + enabled: { type: "boolean" }, + random: { type: "boolean" }, + colors: { type: "array", items: "string (hex color)" } + } + }, + layoutSettings: {} + }; + Object.keys(runtimeContext.LAYOUT_METADATA).forEach((key) => { + const meta = runtimeContext.LAYOUT_METADATA[key]; + schema.layoutSettings[key] = { + type: "number", + default: meta.def, + min: meta.min, + max: meta.max, + step: meta.step, + description: meta.desc + }; + }); + return mmOk({ schema }); + } + }; + window.MindMapBuilderAPI = API; + console.log( + "window.MindMapBuilderAPI initialized. For documentation visit: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/ea-script-docs/MindMapBuilderAPI.md", + API + ); + })(); + } + + // src/scripts/mindmap-builder/sidepanelLifecycle.js + async function openMindmapSidepanel(runtimeContext) { + return runtimeContext.ea.createSidepanelTab(runtimeContext.t("DOCK_TITLE"), true, true).then((tab) => { + if (!tab) return; + runtimeContext.registerStyles(); + tab.onWindowMigrated = (newWin) => { + runtimeContext.cancelBranchPaste?.(); + runtimeContext.cancelHotkeyRecording?.(); + runtimeContext.linkSuggester?.close(); + runtimeContext.sidepanelWindow = newWin; + if (!runtimeContext.isUndocked && runtimeContext.sidepanelWindow) { + runtimeContext.registerKeydownHandler( + runtimeContext.sidepanelWindow, + runtimeContext.handleKeydown + ); + } + }; + tab.onExcalidrawViewClosed = () => { + if (runtimeContext.isUndocked) { + runtimeContext.toggleDock({ + silent: true, + forceDock: true, + saveSetting: false + }); + } + }; + tab.onOpen = () => { + const contentEl = tab.contentEl; + contentEl.classList.add("excalidraw-mindmap-ui"); + if (!contentEl.hasChildNodes()) { + runtimeContext.renderHelp(contentEl); + runtimeContext.inputContainer = contentEl.createDiv(); + runtimeContext.renderBody(contentEl); + runtimeContext.sidepanelWindow = contentEl.ownerDocument.defaultView; + if (runtimeContext.isUndocked) { + runtimeContext.toggleDock({ + silent: true, + forceDock: true, + saveSetting: false + }); + } else { + runtimeContext.renderInput(runtimeContext.inputContainer, false); + } + } + runtimeContext.ensureNodeSelected(); + runtimeContext.updateUI(); + runtimeContext.focusInputEl(); + if (runtimeContext.ea.activateMindmap) { + runtimeContext.ea.activateMindmap = false; + const undockPreference = runtimeContext.getVal(runtimeContext.K_UNDOCKED, false); + if (undockPreference && !runtimeContext.isUndocked) { + setTimeout( + () => runtimeContext.toggleDock({ + saveSetting: false + }) + ); + } else if (!undockPreference && runtimeContext.isUndocked) { + setTimeout( + () => runtimeContext.toggleDock({ + saveSetting: false + }) + ); + tab.reveal(); + } else if (!undockPreference) { + tab.reveal(); + } + } else { + setupEventListeners(runtimeContext.ea.targetView); + if (!window.MindmapBuilder?.popObsidianHotkeyScope) + runtimeContext.registerObsidianHotkeyOverrides(); + } + }; + const setupEventListeners = (view) => { + if (!view || !view.ownerWindow) return; + window.MindmapBuilder?.removePointerDownHandler?.(); + const win = view.ownerWindow; + win.addEventListener("pointerdown", runtimeContext.handleCanvasPointerDown); + window.MindmapBuilder.removePointerDownHandler = () => { + if (win) win.removeEventListener("pointerdown", runtimeContext.handleCanvasPointerDown); + delete window.MindmapBuilder.removePointerDownHandler; + }; + runtimeContext.updateKeyHandlerLocation(); + if (!window.MindmapBuilder?.removeActiveLeafListener) { + const leafChangeRef = app.workspace.on("active-leaf-change", onActiveLeafChange); + window.MindmapBuilder.removeActiveLeafListener = () => { + app.workspace.offref(leafChangeRef); + delete window.MindmapBuilder.removeActiveLeafListener; + }; + } + }; + const onFocus = (view) => { + if (!view) return; + if (runtimeContext.ea.targetView !== view) { + runtimeContext.mostRecentlySelectedNodeID = null; + if (runtimeContext.ea.targetView) + runtimeContext.removeEventListeners(runtimeContext.ea.targetView); + runtimeContext.ea.setView(view); + runtimeContext.ea.clear(); + } + setupEventListeners(view); + runtimeContext.watchPasteMetadata?.(); + runtimeContext.ensureNodeSelected(); + runtimeContext.updateUI(); + }; + tab.onFocus = (view) => onFocus(view); + const onActiveLeafChange = (leaf) => { + if (runtimeContext.cancelHotkeyRecording) runtimeContext.cancelHotkeyRecording(); + if (runtimeContext.ea.targetView !== leaf.view && runtimeContext.ea.isExcalidrawView(leaf.view)) { + runtimeContext.mostRecentlySelectedNodeID = null; + if (runtimeContext.ea.targetView) + runtimeContext.removeEventListeners(runtimeContext.ea.targetView); + runtimeContext.ea.setView(leaf.view); + runtimeContext.ea.clear(); + setupEventListeners(leaf.view); + } + runtimeContext.registerObsidianHotkeyOverrides(); + if (!runtimeContext.isUndocked || !runtimeContext.floatingInputModal || !leaf) { + return; + } + if (runtimeContext.ea.isExcalidrawView(leaf.view)) { + runtimeContext.ensureNodeSelected(); + runtimeContext.updateUI(); + const { modalEl } = runtimeContext.floatingInputModal; + if (runtimeContext.isExcaliBrainView()) { + modalEl.style.display = "none"; + } else { + if (modalEl.style.display === "none") { + modalEl.style.display = ""; + } + } + if (runtimeContext.ea.targetView && modalEl.ownerDocument !== runtimeContext.ea.targetView.ownerDocument) { + runtimeContext.ea.targetView.ownerDocument.body.appendChild(modalEl); + runtimeContext.linkSuggester?.close(); + runtimeContext.linkSuggester = runtimeContext.ea.attachInlineLinkSuggester( + runtimeContext.inputEl, + runtimeContext.inputRow?.settingEl + ); + } + const { x, y } = runtimeContext.ea.targetView.contentEl.getBoundingClientRect(); + modalEl.style.top = `${y + 5}px`; + modalEl.style.left = `${x + 5}px`; + } else { + if (leaf.view?.getViewType() === "excalidraw-sidepanel") return; + const { modalEl } = runtimeContext.floatingInputModal; + if (modalEl.style.display !== "none") { + modalEl.style.display = "none"; + } + } + }; + tab.onClose = async () => { + runtimeContext.disposeBranchPaste?.(); + runtimeContext.cancelHotkeyRecording?.(); + runtimeContext.linkSuggester?.close(); + runtimeContext.disposeKeyboard(); + runtimeContext.removeEventListeners(); + delete window.MindmapBuilder; + delete window.MindMapBuilderAPI; + runtimeContext.removeStyles(); + if (runtimeContext.floatingInputModal) { + if (runtimeContext.floatingInputModal.modalEl && runtimeContext.floatingInputModal.modalEl.parentElement) { + runtimeContext.floatingInputModal.modalEl.remove(); + } + runtimeContext.floatingInputModal.close(); + runtimeContext.floatingInputModal = null; + } + await runtimeContext.saveSettings(); + }; + if (runtimeContext.ea.targetView) { + setupEventListeners(runtimeContext.ea.targetView); + } + tab.open(); + }); + } + + // src/scripts/mindmap-builder/runtime.js + async function initializeMindmapBuilder(ea2, utils2, VERSION2, t) { + const { Notice } = ea2.obsidian; + const runtimeContext = { + get ACTION_ADD() { + return ACTION_ADD; + }, + get ACTION_ADD_FOLLOW() { + return ACTION_ADD_FOLLOW; + }, + get ACTION_ADD_FOLLOW_FOCUS() { + return ACTION_ADD_FOLLOW_FOCUS; + }, + get ACTION_ADD_FOLLOW_ZOOM() { + return ACTION_ADD_FOLLOW_ZOOM; + }, + get ACTION_ADD_SIBLING_AFTER() { + return ACTION_ADD_SIBLING_AFTER; + }, + get ACTION_ADD_SIBLING_BEFORE() { + return ACTION_ADD_SIBLING_BEFORE; + }, + get ACTION_BOX() { + return ACTION_BOX; + }, + get ACTION_CALENDAR() { + return ACTION_CALENDAR; + }, + get ACTION_COPY() { + return ACTION_COPY; + }, + get ACTION_CUT() { + return ACTION_CUT; + }, + get ACTION_DOCK_UNDOCK() { + return ACTION_DOCK_UNDOCK; + }, + get ACTION_EDIT() { + return ACTION_EDIT; + }, + get ACTION_FOCUS() { + return ACTION_FOCUS; + }, + get ACTION_FOLD() { + return ACTION_FOLD; + }, + get ACTION_FOLD_ALL() { + return ACTION_FOLD_ALL; + }, + get ACTION_FOLD_L1() { + return ACTION_FOLD_L1; + }, + get ACTION_HIDE() { + return ACTION_HIDE; + }, + get ACTION_IMPORT_OUTLINE() { + return ACTION_IMPORT_OUTLINE; + }, + get ACTION_NAVIGATE() { + return ACTION_NAVIGATE; + }, + get ACTION_NAVIGATE_FOCUS() { + return ACTION_NAVIGATE_FOCUS; + }, + get ACTION_NAVIGATE_ZOOM() { + return ACTION_NAVIGATE_ZOOM; + }, + get ACTION_PASTE() { + return ACTION_PASTE; + }, + get ACTION_PIN() { + return ACTION_PIN; + }, + get ACTION_REARRANGE() { + return ACTION_REARRANGE; + }, + get ACTION_REDO_Y() { + return ACTION_REDO_Y; + }, + get ACTION_REDO_Z() { + return ACTION_REDO_Z; + }, + get ACTION_SORT_ORDER() { + return ACTION_SORT_ORDER; + }, + get ACTION_TOGGLE_BOUNDARY() { + return ACTION_TOGGLE_BOUNDARY; + }, + get ACTION_TOGGLE_CHECKBOX() { + return ACTION_TOGGLE_CHECKBOX; + }, + get ACTION_TOGGLE_EMBED() { + return ACTION_TOGGLE_EMBED; + }, + get ACTION_TOGGLE_FLOATING_EXTRAS() { + return ACTION_TOGGLE_FLOATING_EXTRAS; + }, + get ACTION_TOGGLE_GROUP() { + return ACTION_TOGGLE_GROUP; + }, + get ACTION_TOGGLE_SUBMAP_ROOT() { + return ACTION_TOGGLE_SUBMAP_ROOT; + }, + get ACTION_UNDO() { + return ACTION_UNDO; + }, + get ACTION_ZOOM() { + return ACTION_ZOOM; + }, + get activePresetName() { + return activePresetName; + }, + set activePresetName(value) { + activePresetName = value; + }, + get addElementsToView() { + return addElementsToView; + }, + get addEmbeddableNode() { + return addEmbeddableNode; + }, + get addImage() { + return addImage; + }, + get addNode() { + return addNode; + }, + get addSibling() { + return addSibling; + }, + get addUpdateArrowLabel() { + return addUpdateArrowLabel; + }, + get api() { + return api; + }, + get applyPresetToGlobals() { + return applyPresetToGlobals; + }, + get applyPresetToMap() { + return applyPresetToMap; + }, + get applyRecursiveGrouping() { + return applyRecursiveGrouping; + }, + get ARROW_TYPES() { + return ARROW_TYPES; + }, + get arrowType() { + return arrowType; + }, + set arrowType(value) { + arrowType = value; + }, + get arrowTypeToggle() { + return arrowTypeToggle; + }, + set arrowTypeToggle(value) { + arrowTypeToggle = value; + }, + get autoLayoutDisabled() { + return autoLayoutDisabled; + }, + set autoLayoutDisabled(value) { + autoLayoutDisabled = value; + }, + get autoLayoutToggle() { + return autoLayoutToggle; + }, + set autoLayoutToggle(value) { + autoLayoutToggle = value; + }, + get baseStrokeWidth() { + return baseStrokeWidth; + }, + set baseStrokeWidth(value) { + baseStrokeWidth = value; + }, + get baseWidthSlider() { + return baseWidthSlider; + }, + set baseWidthSlider(value) { + baseWidthSlider = value; + }, + get bodyContainer() { + return bodyContainer; + }, + set bodyContainer(value) { + bodyContainer = value; + }, + get boundaryBtn() { + return boundaryBtn; + }, + set boundaryBtn(value) { + boundaryBtn = value; + }, + get boxBtn() { + return boxBtn; + }, + set boxBtn(value) { + boxBtn = value; + }, + get boxChildren() { + return boxChildren; + }, + set boxChildren(value) { + boxChildren = value; + }, + get boxToggle() { + return boxToggle; + }, + set boxToggle(value) { + boxToggle = value; + }, + get BRANCH_SCALE_TYPES() { + return BRANCH_SCALE_TYPES; + }, + get branchScale() { + return branchScale; + }, + set branchScale(value) { + branchScale = value; + }, + get branchScaleDropdown() { + return branchScaleDropdown; + }, + set branchScaleDropdown(value) { + branchScaleDropdown = value; + }, + get buildChildrenMap() { + return buildChildrenMap; + }, + get buildElementMap() { + return buildElementMap; + }, + get buildGroupToNodes() { + return buildGroupToNodes; + }, + get buildParentMap() { + return buildParentMap; + }, + get calculateStrokeWidth() { + return calculateStrokeWidth; + }, + get calendarBtn() { + return calendarBtn; + }, + set calendarBtn(value) { + calendarBtn = value; + }, + get cancelHotkeyRecording() { + return cancelHotkeyRecording; + }, + set cancelHotkeyRecording(value) { + cancelHotkeyRecording = value; + }, + get centerText() { + return centerText; + }, + set centerText(value) { + centerText = value; + }, + get centerToggle() { + return centerToggle; + }, + set centerToggle(value) { + centerToggle = value; + }, + get changeNodeOrder() { + return changeNodeOrder; + }, + get collectCrosslinkIds() { + return collectCrosslinkIds; + }, + get collectDecorationIds() { + return collectDecorationIds; + }, + get COLOR_CONTRAST_MIN() { + return COLOR_CONTRAST_MIN; + }, + get COLOR_DISTINCT_THRESHOLD() { + return COLOR_DISTINCT_THRESHOLD; + }, + get colorToggle() { + return colorToggle; + }, + set colorToggle(value) { + colorToggle = value; + }, + get commitEdit() { + return commitEdit; + }, + get configureArrow() { + return configureArrow; + }, + get copyBtn() { + return copyBtn; + }, + set copyBtn(value) { + copyBtn = value; + }, + get copyMapAsText() { + return copyMapAsText; + }, + get currentModalGrowthMode() { + return currentModalGrowthMode; + }, + set currentModalGrowthMode(value) { + currentModalGrowthMode = value; + }, + get currentTransactionAccumulator() { + return currentTransactionAccumulator; + }, + set currentTransactionAccumulator(value) { + currentTransactionAccumulator = value; + }, + get customPalette() { + return customPalette; + }, + set customPalette(value) { + customPalette = value; + }, + get cutBtn() { + return cutBtn; + }, + set cutBtn(value) { + cutBtn = value; + }, + get DEFAULT_HOTKEYS() { + return DEFAULT_HOTKEYS; + }, + get detailsEl() { + return detailsEl; + }, + set detailsEl(value) { + detailsEl = value; + }, + get diffMapConfig() { + return diffMapConfig; + }, + get dirty() { + return dirty; + }, + set dirty(value) { + dirty = value; + }, + get disableTabEvents() { + return disableTabEvents; + }, + set disableTabEvents(value) { + disableTabEvents = value; + }, + get dockBtn() { + return dockBtn; + }, + set dockBtn(value) { + dockBtn = value; + }, + get ea() { + return ea2; + }, + get editBtn() { + return editBtn; + }, + set editBtn(value) { + editBtn = value; + }, + get editingNodeId() { + return editingNodeId; + }, + set editingNodeId(value) { + editingNodeId = value; + }, + get EMBEDED_OBJECT_WIDTH_CHILD() { + return EMBEDED_OBJECT_WIDTH_CHILD; + }, + get EMBEDED_OBJECT_WIDTH_ROOT() { + return EMBEDED_OBJECT_WIDTH_ROOT; + }, + get ensureNodeSelected() { + return ensureNodeSelected; + }, + get extractConfigFromGlobals() { + return extractConfigFromGlobals; + }, + get fillSweep() { + return fillSweep; + }, + set fillSweep(value) { + fillSweep = value; + }, + get fillSweepToggle() { + return fillSweepToggle; + }, + set fillSweepToggle(value) { + fillSweepToggle = value; + }, + get fillSweepToggleSetting() { + return fillSweepToggleSetting; + }, + set fillSweepToggleSetting(value) { + fillSweepToggleSetting = value; + }, + get FLOAT_MODAL_MAX_HEIGHT() { + return FLOAT_MODAL_MAX_HEIGHT; + }, + get FLOAT_MODAL_OFFSET() { + return FLOAT_MODAL_OFFSET; + }, + get FLOAT_MODAL_OPACITY() { + return FLOAT_MODAL_OPACITY; + }, + get floatingBoxBtn() { + return floatingBoxBtn; + }, + set floatingBoxBtn(value) { + floatingBoxBtn = value; + }, + get floatingGroupBtn() { + return floatingGroupBtn; + }, + set floatingGroupBtn(value) { + floatingGroupBtn = value; + }, + get floatingInputModal() { + return floatingInputModal; + }, + set floatingInputModal(value) { + floatingInputModal = value; + }, + get floatingZoomBtn() { + return floatingZoomBtn; + }, + set floatingZoomBtn(value) { + floatingZoomBtn = value; + }, + get focusBtn() { + return focusBtn; + }, + set focusBtn(value) { + focusBtn = value; + }, + get focusInputEl() { + return focusInputEl; + }, + get focusSelected() { + return focusSelected; + }, + get foldBtnAll() { + return foldBtnAll; + }, + set foldBtnAll(value) { + foldBtnAll = value; + }, + get foldBtnL0() { + return foldBtnL0; + }, + set foldBtnL0(value) { + foldBtnL0 = value; + }, + get foldBtnL1() { + return foldBtnL1; + }, + set foldBtnL1(value) { + foldBtnL1 = value; + }, + get FONT_SCALE_TYPES() { + return FONT_SCALE_TYPES; + }, + get fontSizeDropdown() { + return fontSizeDropdown; + }, + set fontSizeDropdown(value) { + fontSizeDropdown = value; + }, + get fontsizeScale() { + return fontsizeScale; + }, + set fontsizeScale(value) { + fontsizeScale = value; + }, + get generateRuntimeHotkeys() { + return generateRuntimeHotkeys; + }, + get getActionHotkeyString() { + return getActionHotkeyString; + }, + get getActionLabel() { + return getActionLabel; + }, + get getAdjustedMaxWidth() { + return getAdjustedMaxWidth; + }, + get getAngleFromCenter() { + return getAngleFromCenter; + }, + get getAppState() { + return getAppState; + }, + get getBoundaryHost() { + return getBoundaryHost; + }, + get getBranchElementIds() { + return getBranchElementIds; + }, + get getChildrenNodes() { + return getChildrenNodes; + }, + get getCommonGroupForElements() { + return getCommonGroupForElements; + }, + get getDecorationAndCrossLinkIdsForBranches() { + return getDecorationAndCrossLinkIdsForBranches; + }, + get getDepthFromAncestor() { + return getDepthFromAncestor; + }, + get getDynamicColor() { + return getDynamicColor; + }, + get getFontScale() { + return getFontScale; + }, + get getHierarchy() { + return getHierarchy; + }, + get getHotkeyDisplayString() { + return getHotkeyDisplayString; + }, + get getMasterRoots() { + return getMasterRoots; + }, + get getMindmapNodeFromSelection() { + return getMindmapNodeFromSelection; + }, + get getMindmapOrder() { + return getMindmapOrder; + }, + get getMindmapProjectElements() { + return getMindmapProjectElements; + }, + get getMostRecentlyAddedNode() { + return getMostRecentlyAddedNode; + }, + get getNodeBox() { + return getNodeBox; + }, + get getNodeMarkdownFile() { + return getNodeMarkdownFile; + }, + get getObsidianConflict() { + return getObsidianConflict; + }, + get getParentNode() { + return getParentNode; + }, + get getRootConfigForNode() { + return getRootConfigForNode; + }, + get getSettingsRootNode() { + return getSettingsRootNode; + }, + get initializeRootCustomData() { + return initializeRootCustomData; + }, + get updateBranchVisibility() { + return updateBranchVisibility; + }, + get getStrokeWidthForDepth() { + return getStrokeWidthForDepth; + }, + get getStructuralGroup() { + return getStructuralGroup; + }, + get getStructuralGroupForNode() { + return getStructuralGroupForNode; + }, + get getSubtreeHeight() { + return getSubtreeHeight; + }, + get getSubtreeWidth() { + return getSubtreeWidth; + }, + get getTextFromNode() { + return getTextFromNode; + }, + get getVal() { + return getVal; + }, + get getVerticalPlacementWidth() { + return getVerticalPlacementWidth; + }, + get getZoom() { + return getZoom; + }, + get groupBranches() { + return groupBranches; + }, + set groupBranches(value) { + groupBranches = value; + }, + get GROWTH_TYPES() { + return GROWTH_TYPES; + }, + get handleCanvasPointerDown() { + return handleCanvasPointerDown; + }, + get handleKeydown() { + return handleKeydown; + }, + get helpContainer() { + return helpContainer; + }, + set helpContainer(value) { + helpContainer = value; + }, + get HUE_STEP_BASE() { + return HUE_STEP_BASE; + }, + get HUE_STEP_JITTER() { + return HUE_STEP_JITTER; + }, + get ignoreFocusChanges() { + return ignoreFocusChanges; + }, + set ignoreFocusChanges(value) { + ignoreFocusChanges = value; + }, + get IMAGE_TYPES() { + return IMAGE_TYPES; + }, + get importOutline() { + return importOutline; + }, + get importOutlineBtn() { + return importOutlineBtn; + }, + set importOutlineBtn(value) { + importOutlineBtn = value; + }, + get importTextToMap() { + return importTextToMap; + }, + get inferDirectionalGrowthMode() { + return inferDirectionalGrowthMode; + }, + get injectNodeLink() { + return injectNodeLink; + }, + set injectNodeLink(value) { + injectNodeLink = value; + }, + get inputContainer() { + return inputContainer; + }, + set inputContainer(value) { + inputContainer = value; + }, + get ontologyEl() { + return ontologyEl; + }, + set ontologyEl(value) { + ontologyEl = value; + }, + get inputEl() { + return inputEl; + }, + set inputEl(value) { + inputEl = value; + }, + get inputRow() { + return inputRow; + }, + set inputRow(value) { + inputRow = value; + }, + get isExcaliBrainView() { + return isExcaliBrainView; + }, + get isFloatingPanelExpanded() { + return isFloatingPanelExpanded; + }, + set isFloatingPanelExpanded(value) { + isFloatingPanelExpanded = value; + }, + get isMac() { + return isMac; + }, + get isMindmapGroup() { + return isMindmapGroup; + }, + get isOntologyFocused() { + return isOntologyFocused; + }, + set isOntologyFocused(value) { + isOntologyFocused = value; + }, + get isRecordingHotkey() { + return isRecordingHotkey; + }, + set isRecordingHotkey(value) { + isRecordingHotkey = value; + }, + get isSolidArrow() { + return isSolidArrow; + }, + set isSolidArrow(value) { + isSolidArrow = value; + }, + get isStructuralElement() { + return isStructuralElement; + }, + get isUndocked() { + return isUndocked; + }, + set isUndocked(value) { + isUndocked = value; + }, + get isViewSet() { + return isViewSet; + }, + get K_ACTIVE_PRESET() { + return K_ACTIVE_PRESET; + }, + get K_ARROW_TYPE() { + return K_ARROW_TYPE; + }, + get K_ARROWSTROKE() { + return K_ARROWSTROKE; + }, + get K_BASE_WIDTH() { + return K_BASE_WIDTH; + }, + get K_BOX() { + return K_BOX; + }, + get K_BRANCH_SCALE() { + return K_BRANCH_SCALE; + }, + get K_CENTERTEXT() { + return K_CENTERTEXT; + }, + get K_FILL_SWEEP() { + return K_FILL_SWEEP; + }, + get K_FONTSIZE() { + return K_FONTSIZE; + }, + get K_GROUP() { + return K_GROUP; + }, + get K_GROWTH() { + return K_GROWTH; + }, + get K_HOTKEYS() { + return K_HOTKEYS; + }, + get K_INJECT_LINK() { + return K_INJECT_LINK; + }, + get K_LAYOUT() { + return K_LAYOUT; + }, + get K_LINK_ALIAS() { + return K_LINK_ALIAS; + }, + get K_MULTICOLOR() { + return K_MULTICOLOR; + }, + get K_PALETTE() { + return K_PALETTE; + }, + get K_PRESETS() { + return K_PRESETS; + }, + get K_ROUND() { + return K_ROUND; + }, + get K_UNDOCKED() { + return K_UNDOCKED; + }, + get K_WIDTH() { + return K_WIDTH; + }, + get K_ZOOM() { + return K_ZOOM; + }, + get lastCommittedTransaction() { + return lastCommittedTransaction; + }, + set lastCommittedTransaction(value) { + lastCommittedTransaction = value; + }, + get lastFocusedInput() { + return lastFocusedInput; + }, + set lastFocusedInput(value) { + lastFocusedInput = value; + }, + get LAYOUT_DEFAULTS() { + return LAYOUT_DEFAULTS; + }, + get LAYOUT_METADATA() { + return LAYOUT_METADATA; + }, + get layoutChildrenAsAdditionalRoot() { + return layoutChildrenAsAdditionalRoot; + }, + get LayoutConfigModal() { + return LayoutConfigModal; + }, + get layoutL1Nodes() { + return layoutL1Nodes; + }, + get layoutSettings() { + return layoutSettings; + }, + set layoutSettings(value) { + layoutSettings = value; + }, + get layoutSubtree() { + return layoutSubtree; + }, + get layoutSubtreeVertical() { + return layoutSubtreeVertical; + }, + get LIGHT_BASE_DARK() { + return LIGHT_BASE_DARK; + }, + get LIGHT_BASE_LIGHT() { + return LIGHT_BASE_LIGHT; + }, + get LIGHT_JITTER_DARK() { + return LIGHT_JITTER_DARK; + }, + get LIGHT_JITTER_LIGHT() { + return LIGHT_JITTER_LIGHT; + }, + get linkSuggester() { + return linkSuggester; + }, + set linkSuggester(value) { + linkSuggester = value; + }, + get MAP_ROOT_CUSTOMDATA_KEYS() { + return MAP_ROOT_CUSTOMDATA_KEYS; + }, + get mapPresets() { + return mapPresets; + }, + set mapPresets(value) { + mapPresets = value; + }, + get maxWidth() { + return maxWidth; + }, + set maxWidth(value) { + maxWidth = value; + }, + get MINDMAP_FOCUS_STYLE_ID() { + return MINDMAP_FOCUS_STYLE_ID; + }, + get mostRecentlyAddedNodeID() { + return mostRecentlyAddedNodeID; + }, + set mostRecentlyAddedNodeID(value) { + mostRecentlyAddedNodeID = value; + }, + get mostRecentlySelectedNodeID() { + return mostRecentlySelectedNodeID; + }, + set mostRecentlySelectedNodeID(value) { + mostRecentlySelectedNodeID = value; + }, + get moveCrossLinks() { + return moveCrossLinks; + }, + get moveDecorations() { + return moveDecorations; + }, + get multicolor() { + return multicolor; + }, + set multicolor(value) { + multicolor = value; + }, + get navigateMap() { + return navigateMap; + }, + get nodeLinkAlias() { + return nodeLinkAlias; + }, + set nodeLinkAlias(value) { + nodeLinkAlias = value; + }, + get Notice() { + return Notice; + }, + get NOTICE_DURATION_CONFLICT() { + return NOTICE_DURATION_CONFLICT; + }, + get NOTICE_DURATION_GLOBAL_CONFLICT() { + return NOTICE_DURATION_GLOBAL_CONFLICT; + }, + get openCalendarModal() { + return openCalendarModal; + }, + get padding() { + return padding; + }, + get PaletteManagerModal() { + return PaletteManagerModal; + }, + get panelExpandBtn() { + return panelExpandBtn; + }, + set panelExpandBtn(value) { + panelExpandBtn = value; + }, + get parseEmbeddableInput() { + return parseEmbeddableInput; + }, + get parseImageInput() { + return parseImageInput; + }, + get parseText() { + return parseText; + }, + get pasteElementToMap() { + return pasteElementToMap; + }, + get cancelBranchPaste() { + return cancelBranchPaste; + }, + get disposeBranchPaste() { + return disposeBranchPaste; + }, + get watchPasteMetadata() { + return watchPasteMetadata; + }, + get isBranchPasteBusy() { + return isBranchPasteBusy; + }, + get performAction() { + return performAction; + }, + get pinBtn() { + return pinBtn; + }, + set pinBtn(value) { + pinBtn = value; + }, + get presetApplyBtn() { + return presetApplyBtn; + }, + set presetApplyBtn(value) { + presetApplyBtn = value; + }, + get presetDropdown() { + return presetDropdown; + }, + set presetDropdown(value) { + presetDropdown = value; + }, + get presetPlusBtn() { + return presetPlusBtn; + }, + set presetPlusBtn(value) { + presetPlusBtn = value; + }, + get presetSaveBtn() { + return presetSaveBtn; + }, + set presetSaveBtn(value) { + presetSaveBtn = value; + }, + get presetTrashBtn() { + return presetTrashBtn; + }, + set presetTrashBtn(value) { + presetTrashBtn = value; + }, + get presetWarningEl() { + return presetWarningEl; + }, + set presetWarningEl(value) { + presetWarningEl = value; + }, + get reconnectArrow() { + return reconnectArrow; + }, + get redoAvailable() { + return redoAvailable; + }, + set redoAvailable(value) { + redoAvailable = value; + }, + get refreshBtn() { + return refreshBtn; + }, + set refreshBtn(value) { + refreshBtn = value; + }, + get refreshMapLayout() { + return refreshMapLayout; + }, + get refreshPresetDropdown() { + return refreshPresetDropdown; + }, + get registerKeydownHandler() { + return registerKeydownHandler; + }, + get registerObsidianHotkeyOverrides() { + return registerObsidianHotkeyOverrides; + }, + get removeObsidianHotkeyOverrides() { + return removeObsidianHotkeyOverrides; + }, + get disposeKeyboard() { + return disposeKeyboard; + }, + get registerStyles() { + return registerStyles; + }, + get removeEventListeners() { + return removeEventListeners; + }, + get removeGroupFromElements() { + return removeGroupFromElements; + }, + get removeKeydownHandlers() { + return removeKeydownHandlers; + }, + get removeStyles() { + return removeStyles; + }, + get renderBody() { + return renderBody; + }, + get renderHelp() { + return renderHelp; + }, + get renderInput() { + return renderInput; + }, + get revealInputEl() { + return revealInputEl; + }, + get roundedCorners() { + return roundedCorners; + }, + set roundedCorners(value) { + roundedCorners = value; + }, + get roundToggle() { + return roundToggle; + }, + set roundToggle(value) { + roundToggle = value; + }, + get RUNTIME_HOTKEYS() { + return RUNTIME_HOTKEYS; + }, + set RUNTIME_HOTKEYS(value) { + RUNTIME_HOTKEYS = value; + }, + get SAT_BASE() { + return SAT_BASE; + }, + get SAT_JITTER() { + return SAT_JITTER; + }, + get saveSettings() { + return saveSettings; + }, + get scaleDecorations() { + return scaleDecorations; + }, + get SCOPE() { + return SCOPE; + }, + get selectNodeInView() { + return selectNodeInView; + }, + get setVal() { + return setVal; + }, + get sidepanelWindow() { + return sidepanelWindow; + }, + set sidepanelWindow(value) { + sidepanelWindow = value; + }, + get sortChildrenStable() { + return sortChildrenStable; + }, + get sortL1NodesBasedOnVisualSequence() { + return sortL1NodesBasedOnVisualSequence; + }, + get startEditing() { + return startEditing; + }, + get storedZoom() { + return storedZoom; + }, + set storedZoom(value) { + storedZoom = value; + }, + get strategyDropdown() { + return strategyDropdown; + }, + set strategyDropdown(value) { + strategyDropdown = value; + }, + get strokeToggle() { + return strokeToggle; + }, + set strokeToggle(value) { + strokeToggle = value; + }, + get submapRootBtn() { + return submapRootBtn; + }, + set submapRootBtn(value) { + submapRootBtn = value; + }, + get t() { + return t; + }, + get toggleBoundary() { + return toggleBoundary; + }, + get toggleBox() { + return toggleBox; + }, + get toggleBranchGroup() { + return toggleBranchGroup; + }, + get toggleCheckboxBtn() { + return toggleCheckboxBtn; + }, + set toggleCheckboxBtn(value) { + toggleCheckboxBtn = value; + }, + get toggleCheckboxStatus() { + return toggleCheckboxStatus; + }, + get toggleDock() { + return toggleDock; + }, + get toggleEmbedBtn() { + return toggleEmbedBtn; + }, + set toggleEmbedBtn(value) { + toggleEmbedBtn = value; + }, + get toggleEmbedStatus() { + return toggleEmbedStatus; + }, + get toggleFloatingExtras() { + return toggleFloatingExtras; + }, + set toggleFloatingExtras(value) { + toggleFloatingExtras = value; + }, + get toggleFold() { + return toggleFold; + }, + get toggleGroupBtn() { + return toggleGroupBtn; + }, + set toggleGroupBtn(value) { + toggleGroupBtn = value; + }, + get togglePin() { + return togglePin; + }, + get toggleSubmapRoot() { + return toggleSubmapRoot; + }, + get triggerGlobalLayout() { + return triggerGlobalLayout; + }, + get uiUpdateTimer() { + return uiUpdateTimer; + }, + set uiUpdateTimer(value) { + uiUpdateTimer = value; + }, + get updateBranchStrokes() { + return updateBranchStrokes; + }, + get updateKeyHandlerLocation() { + return updateKeyHandlerLocation; + }, + get updateL1Arrow() { + return updateL1Arrow; + }, + get updateNodeBoundary() { + return updateNodeBoundary; + }, + get updateRootNodeCustomData() { + return updateRootNodeCustomData; + }, + get updateUI() { + return updateUI; + }, + get userHotkeys() { + return userHotkeys; + }, + set userHotkeys(value) { + userHotkeys = value; + }, + get utils() { + return utils2; + }, + get VERSION() { + return VERSION2; + }, + get widthSlider() { + return widthSlider; + }, + set widthSlider(value) { + widthSlider = value; + }, + get withRootLayoutContext() { + return withRootLayoutContext; + }, + get WRAP_WIDTH_MAX() { + return WRAP_WIDTH_MAX; + }, + get WRAP_WIDTH_MIN() { + return WRAP_WIDTH_MIN; + }, + get WRAP_WIDTH_STEP() { + return WRAP_WIDTH_STEP; + }, + get ZOOM_LEVELS() { + return ZOOM_LEVELS; + }, + get ZOOM_TYPES() { + return ZOOM_TYPES; + }, + get zoomBtn() { + return zoomBtn; + }, + set zoomBtn(value) { + zoomBtn = value; + }, + get zoomLevel() { + return zoomLevel; + }, + set zoomLevel(value) { + zoomLevel = value; + }, + get zoomToFit() { + return zoomToFit; + } + }; + const { removeKeydownHandlers, removeEventListeners, handleCanvasPointerDown } = createLifecycle(runtimeContext); + if (!window.MindmapBuilder) { + window.MindmapBuilder = { + keydownHandlers: [] + }; + } else { + removeEventListeners(); + } + const api = () => ea2?.getExcalidrawAPI(); + const getAppState = () => api()?.getAppState(); + const isViewSet = () => ea2.targetView && ea2.targetView._loaded; + const { + VALUE_SETS, + FONT_SCALE_TYPES, + GROWTH_TYPES, + ZOOM_TYPES, + SCOPE, + ARROW_TYPES, + BRANCH_SCALE_TYPES, + ZOOM_LEVELS, + K_WIDTH, + K_FONTSIZE, + K_BOX, + K_ROUND, + K_BRANCH_SCALE, + K_BASE_WIDTH, + K_GROWTH, + K_MULTICOLOR, + K_UNDOCKED, + K_GROUP, + K_ARROWSTROKE, + K_CENTERTEXT, + K_ZOOM, + K_HOTKEYS, + K_PALETTE, + K_LAYOUT, + K_ARROW_TYPE, + K_FILL_SWEEP, + K_INJECT_LINK, + K_LINK_ALIAS, + K_PRESETS, + K_ACTIVE_PRESET, + LAYOUT_METADATA, + COLOR_CONTRAST_MIN, + COLOR_DISTINCT_THRESHOLD, + HUE_STEP_BASE, + HUE_STEP_JITTER, + SAT_BASE, + SAT_JITTER, + LIGHT_BASE_DARK, + LIGHT_JITTER_DARK, + LIGHT_BASE_LIGHT, + LIGHT_JITTER_LIGHT, + WRAP_WIDTH_MIN, + WRAP_WIDTH_MAX, + WRAP_WIDTH_STEP, + FLOAT_MODAL_OPACITY, + FLOAT_MODAL_OFFSET, + FLOAT_MODAL_MAX_HEIGHT, + NOTICE_DURATION_CONFLICT, + NOTICE_DURATION_GLOBAL_CONFLICT, + LAYOUT_DEFAULTS, + IMAGE_TYPES, + EMBEDED_OBJECT_WIDTH_ROOT, + EMBEDED_OBJECT_WIDTH_CHILD, + ACTION_ADD, + ACTION_ADD_SIBLING_AFTER, + ACTION_ADD_SIBLING_BEFORE, + ACTION_ADD_FOLLOW, + ACTION_ADD_FOLLOW_FOCUS, + ACTION_ADD_FOLLOW_ZOOM, + ACTION_SORT_ORDER, + ACTION_EDIT, + ACTION_TOGGLE_CHECKBOX, + ACTION_CALENDAR, + ACTION_PIN, + ACTION_BOX, + ACTION_TOGGLE_GROUP, + ACTION_COPY, + ACTION_CUT, + ACTION_PASTE, + ACTION_IMPORT_OUTLINE, + ACTION_ZOOM, + ACTION_FOCUS, + ACTION_NAVIGATE, + ACTION_NAVIGATE_ZOOM, + ACTION_NAVIGATE_FOCUS, + ACTION_FOLD, + ACTION_FOLD_L1, + ACTION_FOLD_ALL, + ACTION_TOGGLE_BOUNDARY, + ACTION_TOGGLE_SUBMAP_ROOT, + ACTION_TOGGLE_EMBED, + ACTION_DOCK_UNDOCK, + ACTION_HIDE, + ACTION_REARRANGE, + ACTION_TOGGLE_FLOATING_EXTRAS, + ACTION_UNDO, + ACTION_REDO_Z, + ACTION_REDO_Y, + ACTION_LABEL_KEYS, + DEFAULT_HOTKEYS, + MAP_ROOT_CUSTOMDATA_KEYS, + MINDMAP_FOCUS_STYLE_ID + } = createConfiguration(runtimeContext); + const { + getZoom, + fontScale, + getFontScale, + getVal, + saveSettings, + setVal, + extractConfigFromGlobals, + normalizeMapConfig, + diffMapConfig, + applyPresetToGlobals, + applyPresetToMap, + refreshPresetDropdown, + calculateStrokeWidth, + getStrokeWidthForDepth, + inferDirectionalGrowthMode, + getRootConfigForNode, + withRootLayoutContext, + updateRootNodeCustomData, + updateBranchStrokes + } = createSettings(runtimeContext); + let dirty = false; + let injectNodeLink = getVal(K_INJECT_LINK, true); + let nodeLinkAlias = getVal(K_LINK_ALIAS, "(\u2026)"); + const isExcaliBrainView = () => { + if (!ea2.targetView || !ea2.targetView.file) return false; + const eb = app.plugins.plugins["excalibrain"]; + return eb && eb.settings?.excalibrainFilepath === ea2.targetView.file.path; + }; + let layoutSettings = getVal(K_LAYOUT, { + value: {}, + hidden: true + }); + let layoutSettingsDirty = false; + Object.keys(LAYOUT_METADATA).forEach((k) => { + const val = layoutSettings[k]; + const def = LAYOUT_METADATA[k].def; + if (val === void 0 || val === null || typeof val !== "number" || !Number.isFinite(val)) { + layoutSettings[k] = def; + layoutSettingsDirty = true; + } + }); + if (layoutSettingsDirty) { + setVal(K_LAYOUT, layoutSettings, true); + } + let arrowType = getVal(K_ARROW_TYPE, { + value: "curved", + valueset: ARROW_TYPES + }); + let maxWidth = parseInt(getVal(K_WIDTH, 450)); + if (isNaN(maxWidth)) maxWidth = 450; + let fontsizeScale = getVal(K_FONTSIZE, { + value: "Normal Scale", + valueset: FONT_SCALE_TYPES + }); + let boxChildren = getVal(K_BOX, false); + let roundedCorners = getVal(K_ROUND, false); + let multicolor = getVal(K_MULTICOLOR, true); + let groupBranches = getVal(K_GROUP, false); + let currentModalGrowthMode = getVal(K_GROWTH, { + value: "Right-Left", + valueset: GROWTH_TYPES + }); + let isUndocked = getVal(K_UNDOCKED, false); + let isSolidArrow = getVal(K_ARROWSTROKE, true); + let centerText = getVal(K_CENTERTEXT, true); + let autoLayoutDisabled = false; + let zoomLevel = getVal(K_ZOOM, { + value: "Medium", + valueset: ZOOM_TYPES + }); + let customPalette = getVal(K_PALETTE, { + value: { + enabled: false, + random: false, + colors: [] + }, + hidden: true + }); + let fillSweep = getVal(K_FILL_SWEEP, false); + let editingNodeId = null; + let mostRecentlySelectedNodeID = null; + let currentTransactionAccumulator = 0; + let lastCommittedTransaction = null; + let redoAvailable = null; + if (!ea2.getScriptSettingValue(K_FONTSIZE, { + value: "Normal Scale", + valueset: FONT_SCALE_TYPES + }).hasOwnProperty("valueset")) { + ea2.setScriptSettingValue(K_FONTSIZE, { + value: fontsizeScale, + valueset: FONT_SCALE_TYPES + }); + dirty = true; + } + if (!ea2.getScriptSettingValue(K_GROWTH, { + value: "Right-Left", + valueset: GROWTH_TYPES + }).hasOwnProperty("valueset")) { + ea2.setScriptSettingValue(K_GROWTH, { + value: currentModalGrowthMode, + valueset: GROWTH_TYPES + }); + dirty = true; + } + const settingsTemp = ea2.getScriptSettings(); + if (settingsTemp && settingsTemp.hasOwnProperty("Is Minimized")) { + delete settingsTemp["Is Minimized"]; + dirty = true; + } + let branchScale = getVal(K_BRANCH_SCALE, { + value: "Hierarchical", + valueset: BRANCH_SCALE_TYPES + }); + let baseStrokeWidth = parseFloat( + getVal(K_BASE_WIDTH, { + value: 6 + }) + ); + if (isNaN(baseStrokeWidth)) baseStrokeWidth = 6; + Object.keys(LAYOUT_METADATA).forEach((k) => LAYOUT_DEFAULTS[k] = LAYOUT_METADATA[k].def); + let mapPresets = getVal(K_PRESETS, { + value: { + Default: extractConfigFromGlobals() + }, + hidden: true + }); + if (!mapPresets || typeof mapPresets !== "object") { + mapPresets = {}; + } + let activePresetName = getVal(K_ACTIVE_PRESET, "Default"); + if (!mapPresets["Default"]) { + mapPresets["Default"] = extractConfigFromGlobals(); + setVal(K_PRESETS, mapPresets, true); + } + const ownerWindow = ea2.targetView?.ownerWindow; + const isMac = ea2.DEVICE.isMacOS || ea2.DEVICE.isIOS; + const { + trimText, + parseText, + parseImageInput, + parseEmbeddableInput, + getAdjustedMaxWidth, + getNodeMarkdownFile, + getTextFromNode + } = createTextParsing(runtimeContext); + const getActionLabel = (action) => t(ACTION_LABEL_KEYS[action] ?? action); + let userHotkeys = getVal(K_HOTKEYS, { + value: JSON.parse(JSON.stringify(DEFAULT_HOTKEYS)), + hidden: true + }); + let isRecordingHotkey = false; + let cancelHotkeyRecording = null; + const { + getObsidianConflict, + updateUserHotkeys, + getHotkeyDefByAction, + getHotkeyDisplayString, + getActionHotkeyString, + generateRuntimeHotkeys, + getHotkeyContext, + registerKeydownHandler, + registerObsidianHotkeyOverrides, + removeObsidianHotkeyOverrides, + disposeKeyboard, + updateKeyHandlerLocation, + getActionFromEvent, + handleKeydown, + addSibling + } = createKeyboard(runtimeContext); + dirty = updateUserHotkeys(); + if (userHotkeys.length !== DEFAULT_HOTKEYS.length) { + const merged = [...userHotkeys]; + DEFAULT_HOTKEYS.forEach((d) => { + if (!merged.find((u) => u.action === d.action)) merged.push(JSON.parse(JSON.stringify(d))); + }); + userHotkeys = merged; + } + let RUNTIME_HOTKEYS = generateRuntimeHotkeys(); + const { getInstructions, renderHelp } = createHelpUi(runtimeContext); + const { addElementsToView } = createTransactions(runtimeContext); + const { + selectNodeInView, + getBoundaryHost, + getMindmapNodeFromSelection, + ensureNodeSelected, + getMostRecentlyAddedNode + } = createSelection(runtimeContext); + const { + buildParentMap, + getParentNode, + buildElementMap, + buildChildrenMap, + getChildrenNodes, + buildGroupToNodes, + getMasterRoots, + getHierarchy, + getSettingsRootNode, + getDepthFromAncestor, + getBranchElementIds, + getMindmapProjectElements + } = createGraph(runtimeContext); + const { getAngleFromCenter, getConvexHull, updateNodeBoundary, toggleBoundary } = createBoundaries(runtimeContext); + const { randInt, getDynamicColor } = createColors(runtimeContext); + const { manageFoldIndicator, setElementVisibility, updateBranchVisibility, toggleFold } = createFolding(runtimeContext); + const { moveCrossLinks, moveDecorations, scaleDecorations } = createDecorations(runtimeContext); + let storedZoom = { + elementID: void 0, + level: void 0 + }; + const { nextZoomLevel, zoomToFit, focusSelected, navigateMap } = createNavigation(runtimeContext); + const { + getMindmapOrder, + getNodeBox, + sortChildrenStable, + getSubtreeHeight, + getSubtreeWidth, + getVerticalPlacementWidth + } = createLayoutMetrics(runtimeContext); + const { + isStructuralElement, + getViewGroupElements, + getCommonGroupForElements, + isMindmapGroup, + collectCrosslinkIds, + collectDecorationIds, + getStructuralGroup, + applyRecursiveGrouping, + getStructuralGroupForNode, + getStructuralGroupsForNode, + removeGroupFromElements, + getDecorationAndCrossLinkIdsForBranches, + toggleBranchGroup + } = createGrouping(runtimeContext); + const { addEmbeddableNode, addImage, initializeRootCustomData, addNode } = createNodes(runtimeContext); + const { addUpdateArrowLabel, configureArrow, updateL1Arrow, reconnectArrow } = createArrows(runtimeContext); + const { layoutChildrenAsAdditionalRoot, layoutSubtree } = createHorizontalLayout(runtimeContext); + const { layoutSubtreeVertical } = createVerticalLayout(runtimeContext); + const { + radialL1Distribution, + verticalL1Distribution, + horizontalL1Distribution, + layoutL1Nodes, + sortL1NodesBasedOnVisualSequence + } = createFirstLevelLayout(runtimeContext); + const { triggerGlobalLayout, refreshMapLayout } = createLayout(runtimeContext); + let mostRecentlyAddedNodeID; + const { + importOutline, + importTextToMap, + pasteListToMap, + pasteElementToMap, + cancelBranchPaste, + disposeBranchPaste, + watchPasteMetadata, + isBranchPasteBusy + } = createMarkdownImport(runtimeContext); + const { copyMapAsText } = createMarkdownExport(runtimeContext); + const { + updateSubtreeFontSize, + updateSubtreeStrokeWidth, + updateSubtreeColor, + toggleSubmapRoot, + changeNodeOrder + } = createNodeOrder(runtimeContext); + const { togglePin, toggleCheckboxStatus, toggleEmbedStatus, toggleBox } = createNodeStyles(runtimeContext); + const padding = layoutSettings.CONTAINER_PADDING; + let detailsEl, inputEl, ontologyEl, inputRow, bodyContainer, strategyDropdown; + let lastFocusedInput = null; + let isOntologyFocused = false; + let ignoreFocusChanges = false; + let autoLayoutToggle, linkSuggester, arrowTypeToggle; + let fontSizeDropdown, boxToggle, roundToggle, strokeToggle; + let branchScaleDropdown, baseWidthSlider; + let colorToggle, widthSlider, centerToggle; + let fillSweepToggleSetting, fillSweepToggle; + let pinBtn, refreshBtn, cutBtn, copyBtn, boxBtn, dockBtn, editBtn; + let toggleGroupBtn, zoomBtn, focusBtn, boundaryBtn, calendarBtn; + let submapRootBtn; + let foldBtnL0, foldBtnL1, foldBtnAll; + let floatingGroupBtn, floatingBoxBtn, floatingZoomBtn; + let panelExpandBtn, importOutlineBtn, toggleCheckboxBtn, toggleEmbedBtn; + let isFloatingPanelExpanded = false; + let toggleFloatingExtras = null; + let inputContainer; + let helpContainer; + let floatingInputModal = null; + let sidepanelWindow; + let disableTabEvents = false; + let presetDropdown, presetWarningEl, presetSaveBtn, presetTrashBtn, presetPlusBtn, presetApplyBtn; + const { revealInputEl, focusInputEl, setButtonDisabled, disableUI, updateUI } = createInputUi(runtimeContext); + const { startEditing, commitEdit } = createNodeEditing(runtimeContext); + const { PaletteManagerModal } = createPaletteManagerModal(runtimeContext); + const { LayoutConfigModal } = createLayoutConfigModal(runtimeContext); + const { renderInput } = createInputControls(runtimeContext); + const { renderBody } = createSidepanelControls(runtimeContext); + const { registerStyles, removeStyles } = createStyles(runtimeContext); + const { toggleDock } = createFloatingInput(runtimeContext); + const { getTasksUiOptions, parseTasksData, cleanTasksString, openCalendarModal } = createTasks(runtimeContext); + const { performAction } = createActions(runtimeContext); + installMindmapPublicApi(runtimeContext); + let uiUpdateTimer = null; + ea2.registerCleanup?.(() => { + cancelHotkeyRecording?.(); + linkSuggester?.close(); + disposeKeyboard(); + removeEventListeners(); + if (uiUpdateTimer) clearTimeout(uiUpdateTimer); + }); + return openMindmapSidepanel(runtimeContext); + } + + // src/scripts/mindmap-builder/run.ts + var minimumPluginVersion = "2.23.4"; + function getTranslator(ea2) { + return createMindmapTranslator( + localStorage.getItem("language") ?? "en", + ea2.DEVICE.isMacOS || ea2.DEVICE.isIOS + ); + } + async function runMindmapBuilder(ea2, utils2, version) { + const t = getTranslator(ea2); + if (!ea2.verifyMinimumPluginVersion?.(minimumPluginVersion)) { + new ea2.obsidian.Notice(t("requiresNewerVersion", { version: minimumPluginVersion })); + return; + } + ea2.skipSidepanelScriptRestore(); + const existingTab = ea2.checkForActiveSidepanelTabForScript(); + const hostEA = existingTab?.getHostEA(); + if (existingTab && hostEA && hostEA !== ea2) { + const mindmapHost = hostEA; + mindmapHost.activateMindmap = true; + hostEA.setView(ea2.targetView); + existingTab.open(false); + return; + } + await initializeMindmapBuilder(ea2, utils2, version, t); + } + function reportMindmapLaunchError(ea2, error) { + console.error("Mindmap Builder could not start", error); + const t = getTranslator(ea2); + new ea2.obsidian.Notice(t("launchFailed")); + } + + // src/scripts/mindmap-builder/main.ts + void runMindmapBuilder(ea, utils, VERSION).catch((error) => { + reportMindmapLaunchError(ea, error); + }); +})(); + +/* end of bundle */ diff --git a/ea-scripts/directory-info.json b/ea-scripts/directory-info.json index c3164032..5cfc41e6 100644 --- a/ea-scripts/directory-info.json +++ b/ea-scripts/directory-info.json @@ -641,7 +641,7 @@ }, { "fname": "Mindmap Builder.md", - "mtime": 1785045917003 + "mtime": 1791905383390 }, { "fname": "Mindmap Builder.svg", diff --git a/ea-scripts/index-new.md b/ea-scripts/index-new.md index bf65ad28..97fbcfb7 100644 --- a/ea-scripts/index-new.md +++ b/ea-scripts/index-new.md @@ -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 ``` -
Author@zsviczian
SourceFile on GitHub
DescriptionRapid 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 MindMap Builder Self-Paced Course!

Link to video on YouTube

Link to video on YouTube
+
Author@zsviczian
SourceModular source on GitHub
DescriptionRapid 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 MindMap Builder Self-Paced Course!

Link to video on YouTube

Link to video on YouTube
## Mindmap connector ```excalidraw-script-install diff --git a/ea-scripts/script-store.json b/ea-scripts/script-store.json index ad041d7f..bb4fa399 100644 --- a/ea-scripts/script-store.json +++ b/ea-scripts/script-store.json @@ -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 MindMap Builder Self-Paced Course!

Link to video on YouTube

Link to video on YouTube
", "categories": [ "Editors Picks", diff --git a/package.json b/package.json index 29728057..4d4a6537 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/rollup.config.mjs b/rollup.config.mjs index 4c1862f1..09b87e37 100644 --- a/rollup.config.mjs +++ b/rollup.config.mjs @@ -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 diff --git a/scripts/deploy-mindmap-builder.mjs b/scripts/deploy-mindmap-builder.mjs index 7d53c668..0a459ee7 100644 --- a/scripts/deploy-mindmap-builder.mjs +++ b/scripts/deploy-mindmap-builder.mjs @@ -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; -}); \ No newline at end of file +deploy().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/scripts/testing/bundle.test.mjs b/scripts/testing/bundle.test.mjs new file mode 100644 index 00000000..357f678a --- /dev/null +++ b/scripts/testing/bundle.test.mjs @@ -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`); +}); diff --git a/scripts/testing/inlineLinkSuggester.test.mjs b/scripts/testing/inlineLinkSuggester.test.mjs new file mode 100644 index 00000000..3fbb42b2 --- /dev/null +++ b/scripts/testing/inlineLinkSuggester.test.mjs @@ -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); +}); diff --git a/src/shared/Dialogs/Messages.ts b/src/shared/Dialogs/Messages.ts index 4ad1d55b..cfda3b22 100644 --- a/src/shared/Dialogs/Messages.ts +++ b/src/shared/Dialogs/Messages.ts @@ -17,6 +17,12 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
Buy Me a Coffee at ko-fi.com
`, +"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")} diff --git a/src/shared/Suggesters/InlineLinkSuggester.ts b/src/shared/Suggesters/InlineLinkSuggester.ts index 8e69b179..2ed7554c 100644 --- a/src/shared/Suggesters/InlineLinkSuggester.ts +++ b/src/shared/Suggesters/InlineLinkSuggester.ts @@ -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; + } }); }