Compare commits

...
Author SHA1 Message Date
zsviczian b35fea7eb7 refactor: extract Excalidraw extension renderer 2026-08-09 14:15:27 +02:00
zsviczian 3ceed630b7 refactor: remove obsolete drawio integration 2026-08-09 13:21:42 +02:00
zsviczian ee223fa239 refactor: extract view link navigation manager 2026-08-09 12:50:38 +02:00
zsviczian f1e089930b refactor: extract view fullscreen manager 2026-08-09 12:17:21 +02:00
zsviczian da9dd0fa0b removed commented out old code and debug lines 2026-08-09 11:54:31 +02:00
zsviczian 04f38a6455 refactor: extract view export manager 2026-08-09 11:24:56 +02:00
zsviczian 6976d0969c Merge pull request #2874 from zsviczian/refactor-excalidarw-batch-2
Refactor: move supporting logic out of main.ts into dedicated managers
2026-08-09 10:58:14 +02:00
zsviczian b196ac3de6 refactor: remove dead plugin lifecycle code 2026-08-09 10:56:34 +02:00
zsviczian 776b32216d refactor: extract startup timer 2026-08-09 10:46:18 +02:00
zsviczian 5843e88e6f refactor: extract font manager 2026-08-09 10:29:01 +02:00
zsviczian e0c4eecef4 refactor: extract footer safe area manager 2026-08-09 10:16:39 +02:00
zsviczian fd9090562e updated nanoid to patched version 2026-08-09 09:55:29 +02:00
zsviczian 1a78992ef1 refactor: extract settings management 2026-08-09 09:55:01 +02:00
zsviczian 703355f036 Merge pull request #2873 from zsviczian/refactor-excalidraw
Refactoring: Remove duplicate functions
2026-08-09 08:20:03 +02:00
zsviczian 150f5ccbea Merge pull request #2872 from verryp/fix/text-elements-null-crash
fix: guard null match when .excalidraw.md has no Text Elements heading
2026-08-08 19:37:34 +02:00
verryantopaulus 4f5d913004 fix: simplify null fallback per review suggestion
Per @zsviczian's suggestion on #2872 — collapse the two-step
normalMatch/fallbackMatch into a single optional-chained expression.
Same behavior, less code.
2026-08-09 00:36:02 +07:00
verryantopaulus 64be1aee1e fix: fall through instead of early-return when Text Elements heading missing
Per @zsviczian's review on #2872: an early return skips parsing
"## Element Links" and "## Embedded Files", which may still be present
even when "## Text Elements" itself is missing or was deleted (e.g. a
file with embeddable elements whose link/file sections survived but
the Text Elements heading did not).

Instead of returning early, treat the missing heading as matching zero
characters and fall through to the existing parsing below — the same
codepath that already runs for a file with an empty "## Text Elements"
section. Element Links, Embedded Files, and any block-ref text are
still parsed normally; only the (non-existent) text-element block-refs
are skipped, which is correct since there's nothing there to parse.
2026-08-09 00:19:44 +07:00
verryantopaulus acf7b8d642 fix: guard null match when .excalidraw.md has no Text Elements heading
A valid .excalidraw.md file (correct frontmatter, "# Excalidraw Data"
header, valid "## Drawing" JSON) with no "## Text Elements" heading
anywhere in the body crashed with:

  Cannot read properties of null (reading '0')

loadData() finds "# Excalidraw Data" via RE_EXCALIDRAWDATA_NOSECTION_OK,
so `position` is not -1 and execution moves past the earlier
`position === -1` guard. It then searches for a "## Text Elements"
heading specifically; when that heading doesn't exist at all, both
`normalMatch` and the fallback `data.match(...)` return null, and the
unguarded `data.match(...)[0]` on the null fallback throws.

The plugin's own writer (generateMDBase) always emits the heading
unconditionally, so files it creates itself never hit this path — it
only surfaces for hand-authored or externally-generated .excalidraw.md
files that reasonably omit an empty section.

Treats "no Text Elements heading found" as "zero text elements" and
returns gracefully, mirroring the existing guard a few lines above for
the same underlying condition, instead of throwing.

Fixes #2871
2026-08-09 00:08:02 +07:00
31 changed files with 2697 additions and 2114 deletions

No files matched your search

+67 -25
View File
@@ -1,6 +1,6 @@
# Incremental refactor assessment and plan
Status: active plan for the 2.27.0 refactor, last updated 2026-08-08
Status: active plan for the 2.27.0 refactor, last updated 2026-08-09
This document is the working plan for reducing the size and coupling of
`src/core/main.ts` and `src/view/ExcalidrawView.ts` without destabilizing the
@@ -20,8 +20,19 @@ validated, and what remains uncertain.
| --- | --- | --- |
| Assessment and baseline design | Complete | Initial architecture, risks, sequencing, and validation matrix documented |
| 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 |
| Extract footer safe-area styling | Implemented; awaiting manual validation | `FooterSafeAreaManager` now owns device-specific stylesheet injection, open-document traversal, and unload cleanup; the plugin method remains as a settings-UI compatibility delegate |
| Extract font management | Implemented; awaiting manual validation | `FontManager` now owns CJK discovery/loading, custom-font registration, document stylesheets, readiness, and cleanup; plugin methods and the externally read `fourthFontLoaded` field remain intact |
| Extract startup instrumentation | Implemented; awaiting manual validation | `StartupTimer` now owns startup event history, delta tracking, and breakdown formatting; lifecycle calls, public methods, and the public `loadTimestamp` field remain intact |
| Remove confirmed dead `main.ts` code | Implemented; awaiting manual validation | Removed the uncalled cache-registration method and the never-assigned duplicate file-explorer observer field/cleanup; the active observer in `ObserverManager` remains unchanged |
| Extract view export pipeline | Implemented; awaiting manual validation | `ViewExportManager` now owns raw scene, SVG, PNG, clipboard, PDF, option-resolution, and alternate-theme embedded-file export behavior; all view methods and `exportDialog` compatibility remain intact |
| Remove inert `ExcalidrawView` fragments | Complete | Removed obsolete commented declarations, experiments, debug calls, and alternative implementations; no active code or workaround documentation changed |
| Extract view fullscreen handling | Implemented; awaiting manual validation | `ViewFullscreenManager` now owns the existing document-scoped fullscreen class and style mutations while `ExcalidrawView` retains its public compatibility methods |
| Extract view link navigation | Implemented; awaiting manual validation | `ViewLinkNavigationManager` now owns element-link resolution, hook dispatch, link prompting, modifier-aware navigation, and special image-link handling while all view methods remain compatibility delegates |
| Retire obsolete Draw.io integration | Implemented; awaiting manual validation | Removed special Diagram-plugin routing and retired the Create DrawIO file script from the maintained library and generated reference catalogs; user-installed vault scripts remain untouched |
| Extract Excalidraw extension rendering | Implemented; awaiting manual validation | `ViewExcalidrawExtensionRenderer` now owns text-to-diagram, diagram-to-code, welcome screen, custom main menu, and embeddable rendering while the view retains its existing render delegates and package-managed React runtime |
| Audit and consolidate duplicate logic | In progress | Consolidated `updateFrontmatterInString()`, `arrayToMap()`, `wrapTextAtCharLength()`, `getLinkParts()`/`LinkParts`, `getBinaryFileFromDataURL()`, `svgToBase64()`, `getFontDataURL()`, `cropCanvas()`, `getImageSize()`, `promiseTry()`, `isVersionNewerThanOther()`, `repositionElementsToCursor()`, the internal `cloneElement()`, and `getBoundTextElementId()`; continue one independently testable helper family at a time |
| All later phases | Planned | Begin only after the preceding checkpoint is validated |
| Remaining view phases | In progress | Manually validate the extension renderer checkpoint before choosing between the higher-risk scene-file loader and a mechanical package-aware React-root extraction |
### Action log
@@ -46,6 +57,19 @@ validated, and what remains uncertain.
| 2026-08-08 | Consolidated `getImageSize()` and `promiseTry()` | Kept the identical embedded-asset implementations as canonical, documented their native image-loading and promise-boundary semantics, and preserved the `utils.ts` import surface through re-exports. The former `getImageSize()` differed only in bracing and comments; both `promiseTry()` copies were textually identical. No caller used distinct behavior | Repository search confirms one implementation of each helper; `npm run build` passed after each code change; targeted ESLint passed |
| 2026-08-08 | Consolidated `isVersionNewerThanOther()` | Extracted the identical implementations to dependency-light `versionUtils.ts` and preserved both `utils.ts` and `sceneDataUtils.ts` import paths. Missing, malformed, prerelease, and numeric comparison behavior remains unchanged | Repository search confirms one implementation; `npm run build` and targeted ESLint passed |
| 2026-08-08 | Consolidated element positioning, cloning, and bound-text helpers | Extracted `estimateBounds()`, `repositionElementsToCursor()`, the internal ID-preserving `cloneElement()`, and `getBoundTextElementId()` to documented `excalidrawElementUtils.ts`, preserving exports from both former owner modules. Repositioning and cloning were identical. The only bound-text difference was a redundant optional chain after an equivalent non-null/length guard, so callers could not observe it. The public `ExcalidrawAutomate.cloneElement()` API, which assigns a new ID, was not changed | Repository search confirms one implementation of each helper; targeted ESLint, `npm run build`, `npm run lib`, and `git diff --check` passed; bundle size remains 5,095,379 bytes because Rollup had already eliminated the duplicate paths; `npm run madge` could not run because `madge` is not installed |
| 2026-08-08 | Extracted plugin settings implementation from `main.ts` | Added documented `PluginSettingsManager` with a narrow host contract to own load/save, default assembly, existing library/Markdown-image/oEmbed/preview migrations, and API-key obfuscation. At this extraction checkpoint, retained `plugin.settings`, all public plugin method signatures, startup autosave behavior, settings readiness, settings-tab timing, external-change library invalidation, persisted format, and unknown-key behavior. After delegate TSDoc, `main.ts` decreased from 1,676 to 1,563 lines | `npm run build` passed after each code change; `npm run lib` and a scoped `git diff --check` passed; the new manager and changed delegate lines have no ESLint diagnostics, while targeted lint still reports four unrelated existing `any` diagnostics in the startup-script block of `main.ts`; the initial extraction build was 5,094,122 bytes, 1,257 bytes below the preceding checkpoint. A concurrent unrelated `nanoid` dependency update changed the final workspace build to 5,094,522 bytes; `npm run madge` could not run because `madge` is not installed; manual settings validation remains pending |
| 2026-08-09 | Reviewed and retained `reEnableAutosave` | An attempted removal was reversed after confirming that this is not migration code: it resets the session-scoped temporary disable/enable autosave commands when the plugin starts. Restored `LoadSettingsOptions`, startup `{ reEnableAutosave: true }`, and the post-load in-memory assignment exactly as extracted. No autosave behavior change remains | Repository search confirms the complete option flow is restored; `npm run build`, `npm run lib`, targeted manager ESLint, and scoped `git diff --check` passed; the existing 34 circular dependency warnings are unchanged; `main.ts` is again 1,563 lines and the bundle is again 5,094,522 bytes; manual settings validation remains pending |
| 2026-08-09 | Moved temporary autosave enablement out of persisted settings | A full runtime and history review confirmed that `settings.autosave` had no settings UI and served only as the global gate for the temporary enable/disable commands. Replaced it with documented plugin-instance state initialized to enabled, updated commands and view scheduling to use that state, removed `autosave` from `ExcalidrawSettings` and `DEFAULT_SETTINGS`, and removed `LoadSettingsOptions`/`reEnableAutosave`. Desktop and mobile interval settings remain unchanged. Existing persisted `autosave` keys are intentionally left inert under the no-sanitizer policy | Repository search confirms there are no remaining supported-setting or runtime references to `settings.autosave`; the settings interface and defaults contain the same 182 keys; `npm run build`, `npm run lib`, and scoped `git diff --check` passed with the existing 34 circular dependency warnings. Broad lint reports only the existing backlog and no diagnostics on changed lines; bundle size decreased by 151 bytes to 5,094,371 bytes; manual session-command validation remains pending |
| 2026-08-09 | Extracted footer safe-area styling from `main.ts` | Added documented `FooterSafeAreaManager` with a narrow host contract to own phone/tablet CSS injection, exact device-aware open-document traversal, setting-driven removal, and unload cleanup. Kept `plugin.updateFooterSafeAreaPadding()` and its layout-ready and settings UI call sites unchanged as delegates. Font document traversal remains in `main.ts` until the separate font extraction | `npm run build`, targeted manager ESLint, and scoped `git diff --check` passed; `main.ts` decreased by 46 lines from 1,558 to 1,512; bundle size increased by 99 bytes to 5,094,470 bytes from manager/delegate overhead; `npm run madge` could not run because `madge` is not installed; phone/tablet manual validation remains pending |
| 2026-08-09 | Extracted font management from `main.ts` | Added documented `FontManager` to own the existing CJK asset cache, vault reads, CJK/custom stylesheet lifecycle, custom font metrics and package registration, readiness state, and device-aware document traversal. Preserved every plugin-facing font method as a delegate, retained `plugin.fourthFontLoaded` for view compatibility, kept the initial readiness value and 100ms timer unchanged, and injected lazy package-map access without changing `PackageManager` construction or ownership | `npm run build`, `npm run lib`, targeted manager ESLint, and scoped `git diff --check` passed; `main.ts` decreased by 130 lines from 1,512 to 1,382; bundle size increased by 379 bytes to 5,094,849 bytes from manager/facade overhead; `npm run madge` could not run because `madge` is not installed; desktop, mobile, CJK, custom-font, and popout manual validation remains pending |
| 2026-08-09 | Extracted startup timing instrumentation from `main.ts` | Added documented `StartupTimer` to own the private event list, previous-event timestamp, total/delta formatting, and debug output. Kept every timing call in its original lifecycle position, retained `logStartupEvent()` and the misspelled `printStarupBreakdown()` as plugin delegates, preserved pre-layout events across the layout-ready baseline reset, and retained `loadTimestamp` as an own public field with unchanged assignment behavior | `npm run build`, `npm run lib`, targeted manager ESLint, and scoped `git diff --check` passed; `main.ts` decreased by 6 lines from 1,382 to 1,376; the latest bundle is 5,095,747 bytes, 898 bytes above the preceding checkpoint due to the manager and compatibility facade; `npm run madge` could not run because `madge` is not installed; startup breakdown inspection remains pending |
| 2026-08-09 | Rejected a catch-all Markdown integration manager and removed proven dead code from `main.ts` | Markdown post-processing, install-codeblock handling, observer setup, and rerender behavior have different lifecycle and ownership constraints, so they will remain explicit rather than being grouped under a weak abstraction. Removed the uncalled private `registerEventListeners()`, its `MetadataCache` import, the never-assigned `main.ts` `fileExplorerObserver`, and its inert unload check. The active file-explorer observer and teardown in `ObserverManager` were not changed | Repository-wide reference searches confirmed both removed members had no callers or assignments and that `PluginFileManager.initialize()` owns the active initial cache walk; `npm run build` passed with the existing circular-dependency warnings; targeted lint reports only the same four pre-existing startup-script `any` diagnostics and none on changed lines; `git diff --check` passed; `main.ts` decreased by 29 lines from 1,376 to 1,347 and the bundle decreased by 381 bytes to 5,095,366 bytes; manual unload/reload validation remains pending |
| 2026-08-09 | Extracted the complete `ExcalidrawView` export pipeline | Added documented `ViewExportManager` to own raw `.excalidraw`, SVG, PNG, clipboard, PDF, export-option resolution, autoexport file writing, and alternate-theme embedded-file loading. Retained every existing public method on `ExcalidrawView` as a documented delegate, kept the public `exportDialog` field and its persistence/teardown lifecycle on the view, and supplied existing runtime dependencies explicitly to avoid a new import cycle. Converted seven type-only imports and pointed `exportUtils` directly at canonical `svgToBase64()` to remove runtime back-edges without changing behavior | `npm run build` passed after every code change; `npm run lib`, manager-targeted ESLint, repository reference searches, and `git diff --check` passed. Broader touched-file lint retains the existing backlog but reports no manager diagnostics. Circular dependency warnings decreased from 34 to 33; `ExcalidrawView.ts` decreased by 365 lines from 9,080 to 8,715; the bundle increased by 2,177 bytes to 5,097,543 bytes and remains below 5 MiB; manual export validation remains pending |
| 2026-08-09 | Removed inert commented-out fragments from `ExcalidrawView` | Deleted the obsolete `excalidrawRef` declaration, disabled dimensions state/effect experiment and matching width/height props, old tooltip and paste alternatives, commented debug logging, and retired `setLocalFont()` calls. Retained comments that explain active semaphore, timer, observer, and sizing workarounds | `npm run build` passed with the same 33 circular-dependency warnings; residue search found none of the targeted fragments; `git diff --check` passed; `ExcalidrawView.ts` decreased by 46 lines from 8,715 to 8,669; bundle size is unchanged at 5,097,543 bytes because comments were not emitted; no runtime testing is required beyond the export-manager checkpoint |
| 2026-08-09 | Extracted fullscreen DOM coordination from `ExcalidrawView` | Added documented `ViewFullscreenManager` with a narrow structural host to own the existing enter, state-check, and exit algorithms. Preserved the public `gotoFullscreen()`, `isFullscreen()`, and `exitFullscreen()` methods as delegates, the owner-document scoping needed by popout windows, tools-panel state updates, leaf-change timeout cancellation, CSS class names, selectors, and mobile layout restoration | `npm run build`, `npm run lib`, manager-targeted ESLint, repository call-site searches, and `git diff --check` passed. The same 33 circular-dependency warnings remain; `ExcalidrawView.ts` decreased by 105 lines from 8,669 to 8,564; the manager contains 166 documented lines; bundle size increased by 828 bytes to 5,098,371 bytes and remains below 5 MiB. Manual main-window, popout, mobile, and teardown validation remains pending, with cross-document DOM restoration the highest-risk area |
| 2026-08-09 | Extracted link navigation from `ExcalidrawView` | Added documented `ViewLinkNavigationManager` to own tooltip removal, link-source resolution, public hook dispatch, modifier handling, link prompting, new-file behavior, embedded and Markdown image links, LaTeX/Mermaid/Draw.io branches, fullscreen exit, and pane navigation. Retained `removeLinkTooltip()`, `handleLinkHookCall()`, the private selection resolver, `processLinkText()`, `linkClick()`, and `handleLinkClick()` on the view as delegates so every existing caller and hook surface remains intact. Supplied cyclic runtime dependencies and four private view operations explicitly; the manager imports the concrete view only as a type. Reused canonical `SelectedElementWithLink` and `SelectedImage` interfaces from `excalidrawViewTypes.ts` and removed their local duplicates | Final `npm run build`, `npm run lib`, manager-targeted ESLint, repository call-site searches, import-graph analysis, and `git diff --check` passed. The build retained the 33-warning circular-dependency baseline; static analysis found zero runtime import paths from the manager back to `ExcalidrawView`. The full-view lint retains its pre-existing type backlog but no new unused import. `ExcalidrawView.ts` decreased by 442 lines from 8,564 to 8,122; the manager contains 649 documented lines; bundle size increased by 2,478 bytes to 5,100,849 bytes and remains below 5 MiB. Manual link-routing validation remains pending, with modifier semantics and special image-link branches the highest-risk areas |
| 2026-08-09 | Retired Draw.io/Diagram plugin customization | Removed detection of `drawio-obsidian`, Draw.io SVG inspection, and routing to the external `diagram-edit` view from link navigation. Deleted the Create DrawIO file Automate script and icon from the maintained script library, its directory metadata and install catalog entries, and its generated script-library and AI-reference copies. Added a 2.27.0 release note. Historical release notes remain unchanged as an accurate record, and existing script files in user vaults are intentionally not deleted | `npm run build`, `npm run lib`, manager-targeted ESLint, JSON parsing, repository residue searches, and `git diff --check` passed. Runtime and maintained catalog searches find no Draw.io plugin IDs, view types, or SVG markers; only the new retirement note, this action history, and historical release notes retain the name. Circular-dependency warnings remain at 33; `ViewLinkNavigationManager.ts` decreased by 25 lines from 649 to 624; the final bundle is 5,100,535 bytes, 314 bytes below the preceding checkpoint and still below 5 MiB. Manual validation should confirm ordinary SVG links now follow normal Obsidian navigation and that the script no longer appears in the downloadable catalog |
| 2026-08-09 | Extracted Excalidraw extension rendering from `ExcalidrawView` | Added documented `ViewExcalidrawExtensionRenderer` to own `ttdDialog()`, `diagramToCode()`, `ttdDialogTrigger()`, `renderWelcomeScreen()`, `renderCustomActionsMenu()`, and `renderEmbeddable()`. Kept the six private view methods and all Excalidraw root call sites as delegates. The renderer uses `view.packages.react` and `view.packages.excalidrawLib`; back-edge-prone runtime modules and private dialog actions are constructor-injected, and the concrete view import is type-only. `renderEmbeddableMenu()`, `renderToolsPanel()`, and `renderTopRightUI()` remain in the view because they own refs, live menu instances, or view lifecycle state | Production builds passed after every code edit, `npm run lib` passed, renderer-targeted ESLint and `git diff --check` passed, and full-view lint showed only the established type backlog after extraction-specific unused imports were removed. The build retained the 33-warning circular-dependency baseline. `ExcalidrawView.ts` decreased by 358 lines from 8,122 to 7,764; the renderer contains 479 documented lines; the bundle increased by 1,746 bytes to 5,102,281 bytes and remains below 5 MiB. Manual testing should prioritize a popout window, then the main-window welcome/menu/embeddable paths, then ExcaliAI text-to-diagram and diagram-to-code; repeat core rendering on mobile, with popout React isolation the highest-risk regression |
## Executive recommendation
@@ -286,13 +310,13 @@ src/core/
PluginSettingsManager.ts Load/save/encryption/default assembly
FontManager.ts Per-document fonts and package registration
ViewportStyleManager.ts Phone/tablet safe-area behavior
MarkdownIntegrationManager.ts Post processors and install code blocks
src/view/
ExcalidrawView.ts Obsidian host, public facade, composition
components/
ExcalidrawRoot.tsx Package-aware render tree, eventually TSX
managers/
ViewExcalidrawExtensionRenderer.ts
ViewExportManager.ts
ViewLinkNavigationManager.ts
ViewSceneFileManager.ts
@@ -468,19 +492,20 @@ popout creation, so it should not be combined with package-manager changes.
Candidates should be extracted one at a time:
1. Move install-codeblock registration and Markdown integration setup behind a
`MarkdownIntegrationManager`, while still registering the Markdown post
processor from `onload()`.
1. Keep Markdown post-processing, install-codeblock registration, observer
setup, and rerender behavior explicit in their current owners. A proposed
`MarkdownIntegrationManager` was rejected because these responsibilities do
not form a cohesive lifecycle unit.
2. Move startup-script execution behind a focused runner owned by the script
subsystem.
3. Move startup timing storage/formatting into a small `StartupTimer` while
retaining `plugin.logStartupEvent()` as a delegate if consumers need it.
3. Completed: startup timing storage/formatting now belongs to `StartupTimer`,
with the plugin methods retained as compatibility delegates.
4. Group initialization and cleanup of managers, but keep a readable ordered
list in `onloadOnLayoutReady()` and `onunload()`.
5. Only after reference searches and runtime validation, remove confirmed dead
members. Current review candidates include the unused private
`registerEventListeners()` and a `fileExplorerObserver` field in `main.ts`
that appears separate from the observer owned by `ObserverManager`.
5. Completed: after repository-wide reference searches, removed the unused
private `registerEventListeners()` and the never-assigned
`fileExplorerObserver` field and unload check from `main.ts`. The active
observer owned by `ObserverManager` remains intact.
Do not hide lifecycle ordering inside a generic service container. The desired
`main.ts` is a readable composition root, not an empty forwarding shell.
@@ -493,15 +518,25 @@ mutual exclusion. For every extraction, retain the current method on
Recommended order:
1. `ViewExportManager`: export preference resolution, file collection, SVG,
PNG, PDF, clipboard, and save-to-file operations.
2. `ViewLinkNavigationManager`: link parsing, hook invocation, navigation, and
link click handling.
3. `ViewSceneFileManager`: active/next/deferred embedded-file loaders and
1. Completed: `ViewExportManager` owns export preference resolution, file
collection, SVG, PNG, PDF, clipboard, and save-to-file operations while the
view retains compatibility delegates and dialog lifecycle.
2. Implemented: `ViewFullscreenManager` owns fullscreen DOM class and style
coordination while the view retains compatibility delegates. Validate the
unchanged selectors in the main window, popouts, mobile layouts, screenshot
capture, link-driven exit, and view teardown before closing this checkpoint.
3. Implemented: `ViewLinkNavigationManager` owns link-source resolution, hook
invocation, prompting, modifier handling, special embedded-image branches,
and pane navigation while the view retains compatibility delegates.
4. Implemented: `ViewExcalidrawExtensionRenderer` owns the plugin-specific
Excalidraw render slots for TTD, diagram-to-code, the welcome screen, custom
actions, and embeddables. The view retains its render delegates and supplies
all elements through its window-scoped React and Excalidraw packages.
5. `ViewSceneFileManager`: active/next/deferred embedded-file loaders and
deferred validation scheduling.
4. `MarkdownImageController`: deletion queue, edit handoff, conversion, and
6. `MarkdownImageController`: deletion queue, edit handoff, conversion, and
local-source operations.
5. `ViewInteractionController`: hover preview and pointer/key interaction only
7. `ViewInteractionController`: hover preview and pointer/key interaction only
after the earlier controllers establish a working host-interface pattern.
Each manager should depend on the smallest host interface practical rather
@@ -729,13 +764,20 @@ Before merging any refactor step, answer all of the following:
2. Complete the duplicate inventory, classify the confirmed utility
candidates, and consolidate one exact, low-risk family after mapping all
callers. Record the decision and validation in the action log.
3. Extract `ViewExportManager` while keeping all current `ExcalidrawView`
export methods as delegates. This establishes the view-controller pattern
away from lifecycle and synchronization.
3. Completed: extracted `ViewExportManager` while keeping all current
`ExcalidrawView` export methods as delegates. This establishes the
view-controller pattern away from lifecycle and synchronization.
The next checkpoint is extracting the package-aware React root using
`createElement()` without TSX or state changes, followed by popout validation.
Convert to TSX only in the subsequent change.
The current checkpoint is manual validation of
`ViewExcalidrawExtensionRenderer`. First test a popout window because a
cross-window React mismatch is the highest-impact risk, then verify the welcome
screen, custom menu actions, web and Obsidian embeddables, text-to-diagram, and
diagram-to-code in the main window. Repeat basic rendering and embeddables on a
mobile device. The next controller candidate remains `ViewSceneFileManager`,
but its loader queue, retry timers, cache validation, and lifecycle teardown
make it a higher-risk extraction. A mechanical package-aware React-root move
is now also viable, but it must keep `createElement()` and current state timing
unchanged; any TSX or state-management conversion belongs in a later step.
After those steps, reassess coupling, bundle size, and manual-test coverage
before committing to the next phase. The plan is deliberately a sequence of
@@ -182,7 +182,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.svg"/></div>|[[#Create DrawIO file]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
@@ -358,12 +357,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
## Create DrawIO file
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="https://www.youtube.com/watch?v=DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Create new markdown file and embed into active drawing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
@@ -7837,46 +7830,6 @@ if(element.type === 'arrow') {
---
## Create DrawIO file.md
<!-- Source: ea-scripts/Create DrawIO file.md -->
/*
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
```js*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const drawIO = app.plugins.plugins["drawio-obsidian"];
if(!drawIO || !drawIO?._loaded) {
new Notice("Can't find the draw.io diagram plugin");
}
filename = await utils.inputPrompt("Diagram name?");
if(!filename) return;
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
const filepath = await ea.getAttachmentFilepath(filename);
if(!filepath) return;
const leaf = app.workspace.getLeaf('tab')
if(!leaf) return;
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="&lt;mxGraphModel&gt;&lt;root&gt;&lt;mxCell id=&quot;0&quot;/&gt;&lt;mxCell id=&quot;1&quot; parent=&quot;0&quot;/&gt;&lt;/root&gt;&lt;/mxGraphModel&gt;"></svg>`);
await ea.addImage(0,0,file);
await ea.addElementsToView(true,true);
leaf.setViewState({
type: "diagram-edit",
state: {
file: filepath
}
});
```
---
## Create new markdown file and embed into active drawing.md
<!-- Source: ea-scripts/Create new markdown file and embed into active drawing.md -->
@@ -4796,7 +4796,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.svg"/></div>|[[#Create DrawIO file]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
@@ -4972,12 +4971,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
## Create DrawIO file
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="YouTube: DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Create new markdown file and embed into active drawing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
@@ -12451,46 +12444,6 @@ if(element.type === 'arrow') {
---
## Create DrawIO file.md
<!-- Source: ea-scripts/Create DrawIO file.md -->
/*
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
```js*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const drawIO = app.plugins.plugins["drawio-obsidian"];
if(!drawIO || !drawIO?._loaded) {
new Notice("Can't find the draw.io diagram plugin");
}
filename = await utils.inputPrompt("Diagram name?");
if(!filename) return;
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
const filepath = await ea.getAttachmentFilepath(filename);
if(!filepath) return;
const leaf = app.workspace.getLeaf('tab')
if(!leaf) return;
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="&lt;mxGraphModel&gt;&lt;root&gt;&lt;mxCell id=&quot;0&quot;/&gt;&lt;mxCell id=&quot;1&quot; parent=&quot;0&quot;/&gt;&lt;/root&gt;&lt;/mxGraphModel&gt;"></svg>`);
await ea.addImage(0,0,file);
await ea.addElementsToView(true,true);
leaf.setViewState({
type: "diagram-edit",
state: {
file: filepath
}
});
```
---
## Create new markdown file and embed into active drawing.md
<!-- Source: ea-scripts/Create new markdown file and embed into active drawing.md -->
@@ -46316,4 +46269,3 @@ ea.onSceneChangeHook = {
}
}
};
@@ -9,11 +9,11 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **addAppendUpdateCustomData**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **addArrow**: [Concatenate lines.md](scripts/Concatenate%20lines.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md)
- **addDiamond**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addElementsToView**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%20selected%20elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Icon Library.md](scripts/Icon%20Library.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md), [Uniform sizLine truncated
- **addElementsToView**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%20selected%20elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Icon Library.md](scripts/Icon%20Library.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md), [Uniform size.md](scripts/Uniform%20size.md)
- **addEllipse**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addEmbeddable**: [Capture Note.md](scripts/Capture%20Note.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addFrame**: [Capture Note.md](scripts/Capture%20Note.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
- **addImage**: [Capture Note.md](scripts/Capture%20Note.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addImage**: [Capture Note.md](scripts/Capture%20Note.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **addLaTex**: [ExcaliMath.md](scripts/ExcaliMath.md)
- **addLine**: [Boolean Operations.md](scripts/Boolean%20Operations.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [To Line.md](scripts/To%20Line.md)
- **addMermaid**: [ExcaliAI.md](scripts/ExcaliAI.md)
@@ -46,10 +46,10 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **formatAIUsageLabel**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **generateAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **generateAIText**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **generateElementId**: [Capture Note.md](scripts/Capture%20Note.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **generateElementId**: [Capture Note.md](scripts/Capture%20Note.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
- **getAISettings**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **getAPI**: [Capture Note.md](scripts/Capture%20Note.md)
- **getAttachmentFilepath**: [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **getAttachmentFilepath**: [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
- **getBoundingBox**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Slideshow.md](scripts/Slideshow.md)
- **getBoundTextElement**: [Capture Note.md](scripts/Capture%20Note.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
- **getCM**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Text Aura.md](scripts/Text%20Aura.md)
@@ -116,7 +116,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
- **toggleSidepanelView**: [Capture Note.md](scripts/Capture%20Note.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
- **transformAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
- **updateViewSVGImageColorMap**: [Shade Master.md](scripts/Shade%20Master.md)
- **verifyMinimumPluginVersion**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **verifyMinimumPluginVersion**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **viewToggleFullScreen**: [Slideshow.md](scripts/Slideshow.md)
- **viewUpdateScene**: [Invert colors.md](scripts/Invert%20colors.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
- **viewZoomToElements**: [Capture Note.md](scripts/Capture%20Note.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
@@ -1,35 +0,0 @@
/*
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
```js*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const drawIO = app.plugins.plugins["drawio-obsidian"];
if(!drawIO || !drawIO?._loaded) {
new Notice("Can't find the draw.io diagram plugin");
}
filename = await utils.inputPrompt("Diagram name?");
if(!filename) return;
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
const filepath = await ea.getAttachmentFilepath(filename);
if(!filepath) return;
const leaf = app.workspace.getLeaf('tab')
if(!leaf) return;
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="&lt;mxGraphModel&gt;&lt;root&gt;&lt;mxCell id=&quot;0&quot;/&gt;&lt;mxCell id=&quot;1&quot; parent=&quot;0&quot;/&gt;&lt;/root&gt;&lt;/mxGraphModel&gt;"></svg>`);
await ea.addImage(0,0,file);
await ea.addElementsToView(true,true);
leaf.setViewState({
type: "diagram-edit",
state: {
file: filepath
}
});
```
-33
View File
@@ -1,33 +0,0 @@
/*
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
```js*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const drawIO = app.plugins.plugins["drawio-obsidian"];
if(!drawIO || !drawIO?._loaded) {
new Notice("Can't find the draw.io diagram plugin");
}
filename = await utils.inputPrompt("Diagram name?");
if(!filename) return;
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
const filepath = await ea.getAttachmentFilepath(filename);
if(!filepath) return;
const leaf = app.workspace.getLeaf('tab')
if(!leaf) return;
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="&lt;mxGraphModel&gt;&lt;root&gt;&lt;mxCell id=&quot;0&quot;/&gt;&lt;mxCell id=&quot;1&quot; parent=&quot;0&quot;/&gt;&lt;/root&gt;&lt;/mxGraphModel&gt;"></svg>`);
await ea.addImage(0,0,file);
await ea.addElementsToView(true,true);
leaf.setViewState({
type: "diagram-edit",
state: {
file: filepath
}
});
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="24 26 68 68" stroke="#000"><path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3.553" d="m58.069 43.384-17.008 29.01"/><path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3.501" d="m58.068 43.384 17.008 29.01"/><path fill="#000" d="M52.773 77.084a3.564 3.564 0 0 1-3.553 3.553H36.999a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553h12.222a3.564 3.564 0 0 1 3.553 3.553v9.379zM67.762 48.074a3.564 3.564 0 0 1-3.553 3.553H51.988a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553H64.21a3.564 3.564 0 0 1 3.553 3.553v9.379zM82.752 77.084a3.564 3.564 0 0 1-3.553 3.553H66.977a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553h12.222a3.564 3.564 0 0 1 3.553 3.553v9.379z"/></svg>

Before

Width:  |  Height:  |  Size: 830 B

-8
View File
@@ -471,14 +471,6 @@
"fname": "Excalidraw Collaboration Frame.svg",
"mtime": 1687881495985
},
{
"fname": "Create DrawIO file.md",
"mtime": 1688243858267
},
{
"fname": "Create DrawIO file.svg",
"mtime": 1688243858267
},
{
"fname": "Ellipse Selected Elements.md",
"mtime": 1690131476331
-7
View File
@@ -164,7 +164,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.svg"/></div>|[[#Create DrawIO file]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
@@ -340,12 +339,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
## Create DrawIO file
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="https://www.youtube.com/watch?v=DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Create new markdown file and embed into active drawing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
+4 -4
View File
@@ -20,7 +20,7 @@
"gl-matrix": "^3.4.3",
"lz-string": "^1.5.0",
"monkey-around": "^2.3.0",
"nanoid": "^5.1.11",
"nanoid": "^5.1.16",
"opentype.js": "^1.3.4",
"pako": "^2.1.0",
"points-on-path": "^0.2.1",
@@ -10239,9 +10239,9 @@
}
},
"node_modules/nanoid": {
"version": "5.1.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.11.tgz",
"integrity": "sha512-v+KEsUv2ps74PaSKv0gHTxTCgMXOIfBEbaqa6w6ISIGC7ZsvHN4N9oJ8d4cmf0n5oTzQz2SLmThbQWhjd/8eKg==",
"version": "5.1.16",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz",
"integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==",
"funding": [
{
"type": "github",
+2 -2
View File
@@ -37,7 +37,7 @@
"gl-matrix": "^3.4.3",
"lz-string": "^1.5.0",
"monkey-around": "^2.3.0",
"nanoid": "^5.1.11",
"nanoid": "^5.1.16",
"opentype.js": "^1.3.4",
"pako": "^2.1.0",
"points-on-path": "^0.2.1",
@@ -96,7 +96,7 @@
"lodash": "^4.18.1",
"lodash-es": "^4.18.1",
"serialize-javascript": "^7.0.5",
"nanoid": "^5.1.11",
"nanoid": "^5.1.16",
"dompurify": "^3.4.12",
"fast-uri": "^3.1.4",
"immutable": "^4.3.9",
+1 -1
View File
@@ -1,6 +1,6 @@
import { customAlphabet } from "nanoid";
import { ExcalidrawLib } from "../types/excalidrawLib";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import { DeviceType } from "src/types/types";
import { errorHandler } from "../utils/ErrorHandler";
import { getLanguage } from "obsidian";
+55 -384
View File
@@ -11,7 +11,6 @@ import {
ViewState,
ViewStateResult,
Notice,
MetadataCache,
TAbstractFile,
FrontMatterCache,
} from "obsidian";
@@ -33,13 +32,10 @@ import {
LOCALE,
setExcalidrawPlugin,
DEVICE,
FONTS_STYLE_ID,
CJK_STYLE_ID,
setRootElementSize,
} from "../constants/constants";
import {
ExcalidrawSettings,
DEFAULT_SETTINGS,
ExcalidrawSettingTab,
} from "./settings";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
@@ -52,11 +48,9 @@ import {
getNewUniqueFilepath,
} from "../utils/fileUtils";
import {
getFontDataURL,
errorlog,
isVersionNewerThanOther,
versionUpdateCheckTimer,
getFontMetrics,
calculateUIModeValue,
} from "../utils/utils";
import {
@@ -75,7 +69,7 @@ import {
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes";
import { DeviceType, Packages } from "../types/types";
import { PaneTarget, PreviewImageType } from "../types/utilTypes";
import { PaneTarget } from "../types/utilTypes";
import {
emulateCTRLClickForLinks,
linkClickModifierType,
@@ -92,7 +86,6 @@ import {
terminateCompressionWorker,
} from "../shared/Workers/compression-worker";
import { WeakArray } from "../shared/WeakArray";
import { getCJKDataURLs } from "../utils/CJKLoader";
import {
ExcalidrawLoading,
switchToExcalidraw,
@@ -111,22 +104,20 @@ import { getHighlightColor } from "src/utils/dynamicStyling";
import { InlineLinkSuggester } from "src/shared/Suggesters/InlineLinkSuggester";
import { KeyBlocker } from "src/types/excalidrawAutomateTypes";
import { UIMode } from "src/shared/Dialogs/UIModeSettingComponent";
import {
decryptPersistedAPIKeys,
encryptPersistedAPIKeys,
} from "src/utils/settingsKeyObfuscation";
import { hideElement, setButtonBgColor } from "src/utils/styleUtils";
import { installButton } from "src/utils/scriptLibraryUtils";
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
import type { MarkdownImageData } from "src/types/markdownImageTypes";
import { StencilLibraryManager } from "./managers/StencilLibraryManager";
import type { StencilLibraryData } from "src/types/stencilLibraryTypes";
import { PluginSettingsManager } from "./managers/PluginSettingsManager";
import { FooterSafeAreaManager } from "./managers/FooterSafeAreaManager";
import { FontManager } from "./managers/FontManager";
import { StartupTimer } from "./managers/StartupTimer";
declare const PLUGIN_VERSION: string;
declare const INITIAL_TIMESTAMP: number;
declare const mainDocument: Document;
declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLStyleElement;
type FileMasterInfo = {
isHyperLink: boolean;
@@ -137,16 +128,6 @@ type FileMasterInfo = {
colorMapJSON?: string;
};
const PHONE_FOOTER_SAFE_AREA_STYLE_ID = "excalidraw-phone-footer-safe-area";
const PHONE_FOOTER_SAFE_AREA_CSS = `
.excalidraw .App-bottom-bar {
padding-bottom: 50px;
}
`;
type PersistedExcalidrawSettings = Partial<ExcalidrawSettings> &
Record<string, unknown>;
/**
* Compatibility labels consumed by upstream Excalidraw via ExcalidrawPlugin.getLabel().
* Keep these keys present in `en.ts`, and keep maintained locales in sync.
@@ -174,12 +155,18 @@ export default class ExcalidrawPlugin extends Plugin {
private monkeyPatchManager: MonkeyPatchManager;
private commandManager: CommandManager;
private eventManager: EventManager;
private settingsManager: PluginSettingsManager;
private footerSafeAreaManager: FooterSafeAreaManager;
private fontManager: FontManager;
private startupTimer: StartupTimer;
public stencilLibraryManager: StencilLibraryManager;
public eaInstances = new WeakArray<ExcalidrawAutomate>();
public fourthFontLoaded: boolean = false;
public excalidrawConfig: ExcalidrawConfig;
public excalidrawFileModes: { [file: string]: string } = {};
public declare settings: ExcalidrawSettings;
/** Session-scoped autosave gate controlled by the temporary commands. */
public autosaveEnabled: boolean = true;
public activeExcalidrawView: ExcalidrawView = null;
public lastActiveExcalidrawFilePath: string = null;
public lastActiveExcalidrawLeafID: string = null;
@@ -190,7 +177,6 @@ export default class ExcalidrawPlugin extends Plugin {
private legacyExcalidrawPopoverObserver:
| MutationObserver
| CustomMutationObserver;
private fileExplorerObserver: MutationObserver | CustomMutationObserver;
public opencount: number = 0;
public ea: ExcalidrawAutomate;
//A master list of fileIds to facilitate copy / paste
@@ -205,11 +191,7 @@ export default class ExcalidrawPlugin extends Plugin {
public forceToOpenInMarkdownFilepath: string = null;
//private slob:string;
public loadTimestamp: number;
private isLocalCJKFontAvailabe: boolean = undefined;
public isReady = false;
private fontsReady = true; //setting this to true allows for a race condition during startup loading fonts and rendering Excalidraw
private startupAnalytics: string[] = [];
private lastLogTimestamp: number;
private settingsReady: boolean = false;
public wasPenModeActivePreviously: boolean = false;
public popScope: (() => void) | null = null;
@@ -219,7 +201,7 @@ export default class ExcalidrawPlugin extends Plugin {
constructor(app: App, manifest: PluginManifest) {
super(app, manifest);
this.loadTimestamp = INITIAL_TIMESTAMP;
this.lastLogTimestamp = this.loadTimestamp;
this.startupTimer = new StartupTimer(this.loadTimestamp, PLUGIN_VERSION);
this.filesMaster = new Map<
FileId,
{
@@ -237,6 +219,11 @@ export default class ExcalidrawPlugin extends Plugin {
//isExcalidraw function is used already is already used by MarkdownPostProcessor in onLoad before onLayoutReady
this.fileManager = new PluginFileManager(this);
this.settingsManager = new PluginSettingsManager(this);
this.footerSafeAreaManager = new FooterSafeAreaManager(this);
this.fontManager = new FontManager(this, () =>
this.packageManager.getPackageMap(),
);
setExcalidrawPlugin(this);
/*if((process.env.NODE_ENV === 'development')) {
@@ -244,20 +231,14 @@ export default class ExcalidrawPlugin extends Plugin {
}*/
}
public logStartupEvent(message: string) {
const timestamp = Date.now();
this.startupAnalytics.push(
`${message}\nTotal: ${timestamp - this.loadTimestamp}ms Delta: ${timestamp - this.lastLogTimestamp}ms\n`,
);
this.lastLogTimestamp = timestamp;
/** Records a startup timing event without changing lifecycle ordering. */
public logStartupEvent(message: string): void {
this.startupTimer.logEvent(message, this.loadTimestamp);
}
public printStarupBreakdown() {
log(
`Excalidraw ${PLUGIN_VERSION} startup breakdown:\n${this.startupAnalytics.join(
"\n",
)}`,
);
/** Prints the startup breakdown; spelling retained for compatibility. */
public printStarupBreakdown(): void {
this.startupTimer.printBreakdown();
}
get locale() {
@@ -342,38 +323,16 @@ export default class ExcalidrawPlugin extends Plugin {
);
}
public getCJKFontSettings() {
const assetsFoler = this.settings.fontAssetsPath;
if (typeof this.isLocalCJKFontAvailabe === "undefined") {
this.isLocalCJKFontAvailabe = this.app.vault
.getFiles()
.some((f) => f.path.startsWith(assetsFoler));
}
if (!this.isLocalCJKFontAvailabe) {
return { c: false, j: false, k: false };
}
return {
c: this.settings.loadChineseFonts,
j: this.settings.loadJapaneseFonts,
k: this.settings.loadKoreanFonts,
};
/** Returns the configured CJK ranges when local font assets are available. */
public getCJKFontSettings(): { c: boolean; j: boolean; k: boolean } {
return this.fontManager.getCJKFontSettings();
}
/** Reads a configured CJK font file from the vault. */
public async loadFontFromFile(
fontName: string,
): Promise<ArrayBuffer | undefined> {
const assetsFoler = this.settings.fontAssetsPath;
if (!this.isLocalCJKFontAvailabe) {
return;
}
const file = this.app.vault.getFileByPath(
normalizePath(`${assetsFoler}/${fontName}`),
);
if (!file || !(file instanceof TFile)) {
return;
}
return await this.app.vault.readBinary(file);
return await this.fontManager.loadFontFromFile(fontName);
}
async onload() {
@@ -399,7 +358,7 @@ export default class ExcalidrawPlugin extends Plugin {
);
try {
void this.loadSettings({ reEnableAutosave: true }).then(() =>
void this.loadSettings().then(() =>
this.onloadCheckForOnceOffSettingsUpdates(),
);
} catch (e) {
@@ -442,7 +401,7 @@ export default class ExcalidrawPlugin extends Plugin {
private async onloadOnLayoutReady() {
this.loadTimestamp = Date.now();
this.lastLogTimestamp = this.loadTimestamp;
this.startupTimer.reset(this.loadTimestamp);
this.logStartupEvent(
"\n----------------------------------\nWorkspace onLayoutReady event fired (these actions are outside the plugin initialization)",
);
@@ -613,7 +572,7 @@ export default class ExcalidrawPlugin extends Plugin {
public async awaitInit() {
let counter = 0;
while ((!this.isReady || !this.fontsReady) && counter++ < 200) {
while ((!this.isReady || !this.fontManager.isReady) && counter++ < 200) {
await sleep(50);
}
}
@@ -639,174 +598,28 @@ export default class ExcalidrawPlugin extends Plugin {
);
}
public async initializeFonts() {
const cjkFontDataURLs = await getCJKDataURLs(this);
if (typeof cjkFontDataURLs === "boolean" && !cjkFontDataURLs) {
new Notice(t("FONTS_LOAD_ERROR") + this.settings.fontAssetsPath, 6000);
}
if (typeof cjkFontDataURLs === "object") {
const fontDeclarations = cjkFontDataURLs.map(
(dataURL) =>
`@font-face { font-family: 'Xiaolai'; src: url("${dataURL}"); font-display: swap; font-weight: 400; }`,
);
for (const ownerDocument of this.getOpenObsidianDocuments()) {
await this.addFonts(fontDeclarations, ownerDocument, CJK_STYLE_ID);
}
new Notice(t("FONTS_LOADED"));
}
const font = await getFontDataURL(
this.app,
this.settings.experimantalFourthFont,
"",
"Local Font",
);
if (font.dataURL === "") {
this.fourthFontLoaded = true;
return;
}
const fourthFontDataURL = font.dataURL;
const f = this.app.metadataCache.getFirstLinkpathDest(
this.settings.experimantalFourthFont,
"",
);
// Call getFontMetrics with the fourthFontDataURL
let fontMetrics = f.extension.startsWith("woff")
? undefined
: await getFontMetrics(fourthFontDataURL, "Local Font");
if (!fontMetrics) {
//console.log("Font Metrics not found, using default");
fontMetrics = {
unitsPerEm: 1000,
ascender: 750,
descender: -250,
lineHeight: 1.2,
fontName: "Local Font",
};
}
this.packageManager.getPackageMap().forEach(({ excalidrawLib }) => {
if (!fontMetrics) {
return;
}
excalidrawLib.registerLocalFont(
{ metrics: fontMetrics },
fourthFontDataURL,
);
});
// Add fonts to open Obsidian documents
for (const ownerDocument of this.getOpenObsidianDocuments()) {
await this.addFonts(
[
`@font-face{font-family:'Local Font';src:url("${fourthFontDataURL}");font-display: swap;font-weight: 400;`,
],
ownerDocument,
);
}
if (!this.fourthFontLoaded) {
window.setTimeout(() => {
this.fourthFontLoaded = true;
}, 100);
}
this.fontsReady = true;
/** Initializes configured CJK and custom fonts across open documents. */
public async initializeFonts(): Promise<void> {
await this.fontManager.initializeFonts();
}
/** Adds or replaces a plugin-owned font stylesheet. */
public async addFonts(
declarations: string[],
ownerDocument: Document = mainDocument,
styleId: string = FONTS_STYLE_ID,
) {
// replace the old local font <style> element with the one we just created
const newStylesheet = deliberateCreateElement(ownerDocument, "style");
newStylesheet.id = styleId;
newStylesheet.textContent = declarations.join("");
const oldStylesheet = ownerDocument.getElementById(styleId);
ownerDocument.head.appendChild(newStylesheet);
if (oldStylesheet) {
ownerDocument.head.removeChild(oldStylesheet);
}
await ownerDocument.fonts.load("20px Local Font");
ownerDocument?: Document,
styleId?: string,
): Promise<void> {
await this.fontManager.addFonts(declarations, ownerDocument, styleId);
}
public removeFonts() {
this.getOpenObsidianDocuments().forEach((ownerDocument) => {
const oldCustomFontStylesheet =
ownerDocument.getElementById(FONTS_STYLE_ID);
if (oldCustomFontStylesheet) {
ownerDocument.head.removeChild(oldCustomFontStylesheet);
}
const oldCJKFontStylesheet = ownerDocument.getElementById(CJK_STYLE_ID);
if (oldCJKFontStylesheet) {
ownerDocument.head.removeChild(oldCJKFontStylesheet);
}
});
/** Removes plugin-owned font stylesheets from all open documents. */
public removeFonts(): void {
this.fontManager.removeFonts();
}
public updateFooterSafeAreaPadding() {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
const shouldEnable =
(DEVICE.isPhone && this.settings?.phoneFooterSafeAreaPadding) ||
(DEVICE.isTablet && this.settings?.tabletFooterSafeAreaPadding);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
PHONE_FOOTER_SAFE_AREA_STYLE_ID,
);
if (!shouldEnable) {
if (existingStylesheet) {
ownerDocument.head.removeChild(existingStylesheet);
}
return;
}
if (isInstanceOfHTMLStyleElement(existingStylesheet)) {
existingStylesheet.textContent = PHONE_FOOTER_SAFE_AREA_CSS;
return;
}
const stylesheet = deliberateCreateElement(ownerDocument, "style");
stylesheet.id = PHONE_FOOTER_SAFE_AREA_STYLE_ID;
stylesheet.textContent = PHONE_FOOTER_SAFE_AREA_CSS;
ownerDocument.head.appendChild(stylesheet);
});
}
private removePhoneFooterSafeAreaPadding() {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
PHONE_FOOTER_SAFE_AREA_STYLE_ID,
);
if (existingStylesheet) {
ownerDocument.head.removeChild(existingStylesheet);
}
});
}
private getOpenObsidianDocuments(): Document[] {
const visitedDocs = new Set<Document>();
this.app.workspace.iterateAllLeaves((leaf) => {
const ownerDocument = DEVICE.isMobile
? mainDocument
: leaf.view.containerEl.ownerDocument;
if (!ownerDocument) {
return;
}
if (visitedDocs.has(ownerDocument)) {
return;
}
visitedDocs.add(ownerDocument);
});
return Array.from(visitedDocs);
/** Updates the optional mobile footer padding across open documents. */
public updateFooterSafeAreaPadding(): void {
this.footerSafeAreaManager.updateFooterSafeAreaPadding();
}
/**
@@ -1093,29 +906,6 @@ export default class ExcalidrawPlugin extends Plugin {
};
}
/**
* Registers event listeners for the plugin
* Must be called after the workspace is read (onLayoutReady)
* Intended to be called from onLayoutReady in onload()
*/
private async registerEventListeners() {
await this.awaitInit();
const metaCache: MetadataCache = this.app.metadataCache;
metaCache.getCachedFiles().forEach((filename: string) => {
const fm = metaCache.getCache(filename)?.frontmatter;
if (
(fm && typeof fm[FRONTMATTER_KEYS.plugin.name] !== "undefined") ||
filename.match(/\.excalidraw$/)
) {
this.fileManager.updateFileCache(
this.app.vault.getFileByPath(filename),
fm,
);
}
});
}
onunload() {
ExcalidrawSidepanelView.onPluginUnload(this);
const excalidrawViews = getExcalidrawViews(this.app);
@@ -1140,7 +930,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.stylesManager = null;
this.removeFonts();
this.removePhoneFooterSafeAreaPadding();
this.footerSafeAreaManager.destroy();
this.eaInstances.forEach((ea) => ea?.destroy());
this.eaInstances.clear();
@@ -1161,10 +951,6 @@ export default class ExcalidrawPlugin extends Plugin {
}
this.observerManager.destroy();
if (this.fileExplorerObserver) {
this.fileExplorerObserver.disconnect();
}
this.excalidrawConfig = null;
this.editorHandler.destroy();
@@ -1191,134 +977,19 @@ export default class ExcalidrawPlugin extends Plugin {
terminateCompressionWorker();
}
public async loadSettings(
opts: { reEnableAutosave?: boolean } = { reEnableAutosave: false },
) {
if (typeof opts.reEnableAutosave === "undefined") {
opts.reEnableAutosave = false;
}
const persistedSettings = ((await this.loadData()) ??
{}) as PersistedExcalidrawSettings;
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
let didSettingsMigration = false;
this.settings = Object.assign({}, DEFAULT_SETTINGS, decryptedSettings);
if (typeof decryptedSettings.libraryStorageMode === "undefined") {
const legacyLibrary: unknown =
typeof decryptedSettings.library === "string" &&
decryptedSettings.library !== "" &&
decryptedSettings.library !== "deprecated"
? JSON_parse(decryptedSettings.library)
: decryptedSettings.library2;
const legacyLibraryRecord =
typeof legacyLibrary === "object" && legacyLibrary !== null
? (legacyLibrary as Record<string, unknown>)
: null;
const hasLegacyItems = Boolean(
(Array.isArray(legacyLibraryRecord?.library) &&
legacyLibraryRecord.library.length) ||
(Array.isArray(legacyLibraryRecord?.libraryItems) &&
legacyLibraryRecord.libraryItems.length),
);
this.settings.libraryStorageMode = hasLegacyItems ? "data-json" : "vault";
this.settings.libraryMigrationStatus = hasLegacyItems
? "pending"
: "not-required";
didSettingsMigration = true;
}
const savedMarkdownImageSettings = decryptedSettings.markdownImageSettings;
if (!savedMarkdownImageSettings) {
this.settings.markdownImageSettings = {
defaults: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
width: this.settings.mdSVGwidth,
fontFamily: this.settings.mdFont,
fontColor: this.settings.mdFontColor ?? "#000000",
border: {
enabled: false,
color: this.settings.mdBorderColor,
},
css: "",
transclusion: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
.border,
},
},
},
};
didSettingsMigration = true;
} else {
this.settings.markdownImageSettings = {
defaults: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
...savedMarkdownImageSettings.defaults,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.border,
...savedMarkdownImageSettings.defaults?.border,
},
transclusion: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
...savedMarkdownImageSettings.defaults?.transclusion,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
.border,
...savedMarkdownImageSettings.defaults?.transclusion?.border,
},
},
},
};
}
const markdownImageDefaults = this.settings.markdownImageSettings
.defaults as unknown as Record<string, unknown>;
if ("theme" in markdownImageDefaults) {
delete markdownImageDefaults.theme;
didSettingsMigration = true;
}
const settingsRecord = this.settings as unknown as Record<string, unknown>;
if (
typeof settingsRecord.iframelyAllowed === "boolean" &&
typeof this.settings.oEmbedAllowed !== "boolean"
) {
this.settings.oEmbedAllowed = settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if ("iframelyAllowed" in settingsRecord) {
delete settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if (!this.settings.previewImageType) {
//migration 1.9.13
if (typeof this.settings.displaySVGInPreview === "undefined") {
this.settings.previewImageType = PreviewImageType.SVGIMG;
} else {
this.settings.previewImageType = this.settings.displaySVGInPreview
? PreviewImageType.SVGIMG
: PreviewImageType.PNG;
}
}
const encryptedPersistedSettings = encryptPersistedAPIKeys(
this.settings as PersistedExcalidrawSettings,
);
const shouldPersistEncryptedSettings =
JSON.stringify(encryptedPersistedSettings) !==
JSON.stringify(persistedSettings);
if (didSettingsMigration || shouldPersistEncryptedSettings) {
await this.saveData(encryptedPersistedSettings);
}
if (opts.reEnableAutosave) {
this.settings.autosave = true;
}
/**
* Loads settings through the plugin-owned settings manager.
*/
public async loadSettings(): Promise<void> {
await this.settingsManager.loadSettings();
}
async saveSettings() {
await this.saveData(
encryptPersistedAPIKeys(
this.settings as PersistedExcalidrawSettings,
),
);
/** Persists the current settings through the plugin-owned settings manager. */
async saveSettings(): Promise<void> {
await this.settingsManager.saveSettings();
}
/** Reloads externally changed settings and invalidates cached libraries. */
async onExternalSettingsChange() {
await this.loadSettings();
this.stencilLibraryManager?.invalidate();
+4 -4
View File
@@ -485,13 +485,13 @@ export class CommandManager {
id: "excalidraw-disable-autosave",
name: t("TEMPORARY_DISABLE_AUTOSAVE"),
checkCallback: (checking) => {
if (!this.settings.autosave) {
if (!this.plugin.autosaveEnabled) {
return false;
} //already disabled
if (checking) {
return true;
}
this.settings.autosave = false;
this.plugin.autosaveEnabled = false;
return true;
},
});
@@ -500,13 +500,13 @@ export class CommandManager {
id: "excalidraw-enable-autosave",
name: t("TEMPORARY_ENABLE_AUTOSAVE"),
checkCallback: (checking) => {
if (this.settings.autosave) {
if (this.plugin.autosaveEnabled) {
return false;
} //already enabled
if (checking) {
return true;
}
this.settings.autosave = true;
this.plugin.autosaveEnabled = true;
return true;
},
});
+201
View File
@@ -0,0 +1,201 @@
import type { Packages } from "src/types/types";
import { Notice, normalizePath, TFile } from "obsidian";
import {
CJK_STYLE_ID,
DEVICE,
FONTS_STYLE_ID,
} from "src/constants/constants";
import { t } from "src/lang/helpers";
import { getCJKDataURLs } from "src/utils/CJKLoader";
import { getFontDataURL, getFontMetrics } from "src/utils/utils";
import type ExcalidrawPlugin from "src/core/main";
declare const mainDocument: Document;
declare const deliberateCreateElement: (
document: Document,
tagName: string,
) => HTMLStyleElement;
type PackageMapProvider = () => Map<Window, Packages>;
/**
* Owns CJK and custom-font discovery, registration, document stylesheets, and
* readiness state while preserving the plugin's existing public font facade.
*/
export class FontManager {
private isLocalCJKFontAvailabe: boolean = undefined;
// Intentionally true to preserve the existing startup race behavior.
private fontsReady = true;
public constructor(
private readonly plugin: ExcalidrawPlugin,
private readonly getPackageMap: PackageMapProvider,
) {}
/** Whether font initialization permits the plugin readiness wait to finish. */
public get isReady(): boolean {
return this.fontsReady;
}
/** Returns the enabled CJK ranges when local CJK font assets are available. */
public getCJKFontSettings(): { c: boolean; j: boolean; k: boolean } {
const assetsFoler = this.plugin.settings.fontAssetsPath;
if (typeof this.isLocalCJKFontAvailabe === "undefined") {
this.isLocalCJKFontAvailabe = this.plugin.app.vault
.getFiles()
.some((file) => file.path.startsWith(assetsFoler));
}
if (!this.isLocalCJKFontAvailabe) {
return { c: false, j: false, k: false };
}
return {
c: this.plugin.settings.loadChineseFonts,
j: this.plugin.settings.loadJapaneseFonts,
k: this.plugin.settings.loadKoreanFonts,
};
}
/** Reads a configured CJK font asset from the vault. */
public async loadFontFromFile(
fontName: string,
): Promise<ArrayBuffer | undefined> {
const assetsFoler = this.plugin.settings.fontAssetsPath;
if (!this.isLocalCJKFontAvailabe) {
return;
}
const file = this.plugin.app.vault.getFileByPath(
normalizePath(`${assetsFoler}/${fontName}`),
);
if (!file || !(file instanceof TFile)) {
return;
}
return await this.plugin.app.vault.readBinary(file);
}
/**
* Loads configured CJK and custom fonts into every open Obsidian document
* and registers custom font metrics with each window-scoped Excalidraw package.
*/
public async initializeFonts(): Promise<void> {
const cjkFontDataURLs = await getCJKDataURLs(this.plugin);
if (typeof cjkFontDataURLs === "boolean" && !cjkFontDataURLs) {
new Notice(
t("FONTS_LOAD_ERROR") + this.plugin.settings.fontAssetsPath,
6000,
);
}
if (typeof cjkFontDataURLs === "object") {
const fontDeclarations = cjkFontDataURLs.map(
(dataURL) =>
`@font-face { font-family: 'Xiaolai'; src: url("${dataURL}"); font-display: swap; font-weight: 400; }`,
);
for (const ownerDocument of this.getOpenObsidianDocuments()) {
await this.addFonts(fontDeclarations, ownerDocument, CJK_STYLE_ID);
}
new Notice(t("FONTS_LOADED"));
}
const font = await getFontDataURL(
this.plugin.app,
this.plugin.settings.experimantalFourthFont,
"",
"Local Font",
);
if (font.dataURL === "") {
this.plugin.fourthFontLoaded = true;
return;
}
const fourthFontDataURL = font.dataURL;
const file = this.plugin.app.metadataCache.getFirstLinkpathDest(
this.plugin.settings.experimantalFourthFont,
"",
);
let fontMetrics = file.extension.startsWith("woff")
? undefined
: await getFontMetrics(fourthFontDataURL, "Local Font");
if (!fontMetrics) {
fontMetrics = {
unitsPerEm: 1000,
ascender: 750,
descender: -250,
lineHeight: 1.2,
fontName: "Local Font",
};
}
this.getPackageMap().forEach(({ excalidrawLib }) => {
if (!fontMetrics) {
return;
}
excalidrawLib.registerLocalFont(
{ metrics: fontMetrics },
fourthFontDataURL,
);
});
for (const ownerDocument of this.getOpenObsidianDocuments()) {
await this.addFonts(
[
`@font-face{font-family:'Local Font';src:url("${fourthFontDataURL}");font-display: swap;font-weight: 400;`,
],
ownerDocument,
);
}
if (!this.plugin.fourthFontLoaded) {
window.setTimeout(() => {
this.plugin.fourthFontLoaded = true;
}, 100);
}
this.fontsReady = true;
}
/** Replaces a plugin-owned font stylesheet and waits for the font to load. */
public async addFonts(
declarations: string[],
ownerDocument: Document = mainDocument,
styleId: string = FONTS_STYLE_ID,
): Promise<void> {
const newStylesheet = deliberateCreateElement(ownerDocument, "style");
newStylesheet.id = styleId;
newStylesheet.textContent = declarations.join("");
const oldStylesheet = ownerDocument.getElementById(styleId);
ownerDocument.head.appendChild(newStylesheet);
if (oldStylesheet) {
ownerDocument.head.removeChild(oldStylesheet);
}
await ownerDocument.fonts.load("20px Local Font");
}
/** Removes custom and CJK font stylesheets from all open documents. */
public removeFonts(): void {
this.getOpenObsidianDocuments().forEach((ownerDocument) => {
const oldCustomFontStylesheet =
ownerDocument.getElementById(FONTS_STYLE_ID);
if (oldCustomFontStylesheet) {
ownerDocument.head.removeChild(oldCustomFontStylesheet);
}
const oldCJKFontStylesheet = ownerDocument.getElementById(CJK_STYLE_ID);
if (oldCJKFontStylesheet) {
ownerDocument.head.removeChild(oldCJKFontStylesheet);
}
});
}
private getOpenObsidianDocuments(): Document[] {
const visitedDocuments = new Set<Document>();
this.plugin.app.workspace.iterateAllLeaves((leaf) => {
const ownerDocument = DEVICE.isMobile
? mainDocument
: leaf.view.containerEl.ownerDocument;
if (!ownerDocument || visitedDocuments.has(ownerDocument)) {
return;
}
visitedDocuments.add(ownerDocument);
});
return Array.from(visitedDocuments);
}
}
@@ -0,0 +1,92 @@
import type { App } from "obsidian";
import { DEVICE } from "src/constants/constants";
import type { ExcalidrawSettings } from "src/core/settings";
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
declare const mainDocument: Document;
declare const deliberateCreateElement: (
document: Document,
tagName: string,
) => HTMLStyleElement;
const FOOTER_SAFE_AREA_STYLE_ID = "excalidraw-phone-footer-safe-area";
const FOOTER_SAFE_AREA_CSS = `
.excalidraw .App-bottom-bar {
padding-bottom: 50px;
}
`;
interface FooterSafeAreaHost {
app: App;
settings: ExcalidrawSettings;
}
/**
* Owns the optional phone and tablet footer-padding stylesheet across Obsidian
* documents, including cleanup when the plugin unloads.
*/
export class FooterSafeAreaManager {
public constructor(private readonly host: FooterSafeAreaHost) {}
/** Applies or removes footer padding according to the current device and settings. */
public updateFooterSafeAreaPadding(): void {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
const shouldEnable =
(DEVICE.isPhone && this.host.settings?.phoneFooterSafeAreaPadding) ||
(DEVICE.isTablet && this.host.settings?.tabletFooterSafeAreaPadding);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
FOOTER_SAFE_AREA_STYLE_ID,
);
if (!shouldEnable) {
if (existingStylesheet) {
ownerDocument.head.removeChild(existingStylesheet);
}
return;
}
if (isInstanceOfHTMLStyleElement(existingStylesheet)) {
existingStylesheet.textContent = FOOTER_SAFE_AREA_CSS;
return;
}
const stylesheet = deliberateCreateElement(ownerDocument, "style");
stylesheet.id = FOOTER_SAFE_AREA_STYLE_ID;
stylesheet.textContent = FOOTER_SAFE_AREA_CSS;
ownerDocument.head.appendChild(stylesheet);
});
}
/** Removes every footer-padding stylesheet owned by the plugin. */
public destroy(): void {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
FOOTER_SAFE_AREA_STYLE_ID,
);
if (existingStylesheet) {
ownerDocument.head.removeChild(existingStylesheet);
}
});
}
private getOpenObsidianDocuments(): Document[] {
const visitedDocuments = new Set<Document>();
this.host.app.workspace.iterateAllLeaves((leaf) => {
const ownerDocument = DEVICE.isMobile
? mainDocument
: leaf.view.containerEl.ownerDocument;
if (!ownerDocument || visitedDocuments.has(ownerDocument)) {
return;
}
visitedDocuments.add(ownerDocument);
});
return Array.from(visitedDocuments);
}
}
+165
View File
@@ -0,0 +1,165 @@
import { JSON_parse } from "src/constants/constants";
import {
DEFAULT_SETTINGS,
type ExcalidrawSettings,
} from "src/core/settings";
import { PreviewImageType } from "src/types/utilTypes";
import {
decryptPersistedAPIKeys,
encryptPersistedAPIKeys,
} from "src/utils/settingsKeyObfuscation";
type PersistedExcalidrawSettings = Partial<ExcalidrawSettings> &
Record<string, unknown>;
interface PluginSettingsHost {
settings: ExcalidrawSettings;
loadData(): Promise<unknown>;
saveData(data: unknown): Promise<void>;
}
/**
* Owns plugin settings persistence, default assembly, and compatibility
* migrations while leaving startup readiness and settings UI registration to
* the plugin lifecycle.
*/
export class PluginSettingsManager {
public constructor(private readonly host: PluginSettingsHost) {}
/**
* Loads persisted settings, applies defaults and migrations, and decrypts
* protected API-key fields.
*
* @remarks Unknown persisted properties are intentionally retained.
*/
public async loadSettings(): Promise<void> {
const persistedSettings = ((await this.host.loadData()) ??
{}) as PersistedExcalidrawSettings;
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
let didSettingsMigration = false;
this.host.settings = Object.assign(
{},
DEFAULT_SETTINGS,
decryptedSettings,
);
if (typeof decryptedSettings.libraryStorageMode === "undefined") {
const legacyLibrary: unknown =
typeof decryptedSettings.library === "string" &&
decryptedSettings.library !== "" &&
decryptedSettings.library !== "deprecated"
? JSON_parse(decryptedSettings.library)
: decryptedSettings.library2;
const legacyLibraryRecord =
typeof legacyLibrary === "object" && legacyLibrary !== null
? (legacyLibrary as Record<string, unknown>)
: null;
const hasLegacyItems = Boolean(
(Array.isArray(legacyLibraryRecord?.library) &&
legacyLibraryRecord.library.length) ||
(Array.isArray(legacyLibraryRecord?.libraryItems) &&
legacyLibraryRecord.libraryItems.length),
);
this.host.settings.libraryStorageMode = hasLegacyItems
? "data-json"
: "vault";
this.host.settings.libraryMigrationStatus = hasLegacyItems
? "pending"
: "not-required";
didSettingsMigration = true;
}
const savedMarkdownImageSettings = decryptedSettings.markdownImageSettings;
if (!savedMarkdownImageSettings) {
this.host.settings.markdownImageSettings = {
defaults: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
width: this.host.settings.mdSVGwidth,
fontFamily: this.host.settings.mdFont,
fontColor: this.host.settings.mdFontColor ?? "#000000",
border: {
enabled: false,
color: this.host.settings.mdBorderColor,
},
css: "",
transclusion: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
.border,
},
},
},
};
didSettingsMigration = true;
} else {
this.host.settings.markdownImageSettings = {
defaults: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
...savedMarkdownImageSettings.defaults,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.border,
...savedMarkdownImageSettings.defaults?.border,
},
transclusion: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
...savedMarkdownImageSettings.defaults?.transclusion,
border: {
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
.border,
...savedMarkdownImageSettings.defaults?.transclusion?.border,
},
},
},
};
}
const markdownImageDefaults = this.host.settings.markdownImageSettings
.defaults as unknown as Record<string, unknown>;
if ("theme" in markdownImageDefaults) {
delete markdownImageDefaults.theme;
didSettingsMigration = true;
}
const settingsRecord = this.host.settings as unknown as Record<
string,
unknown
>;
if (
typeof settingsRecord.iframelyAllowed === "boolean" &&
typeof this.host.settings.oEmbedAllowed !== "boolean"
) {
this.host.settings.oEmbedAllowed = settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if ("iframelyAllowed" in settingsRecord) {
delete settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if (!this.host.settings.previewImageType) {
// Migration introduced in 1.9.13.
if (typeof this.host.settings.displaySVGInPreview === "undefined") {
this.host.settings.previewImageType = PreviewImageType.SVGIMG;
} else {
this.host.settings.previewImageType = this.host.settings
.displaySVGInPreview
? PreviewImageType.SVGIMG
: PreviewImageType.PNG;
}
}
const encryptedPersistedSettings = encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
);
const shouldPersistEncryptedSettings =
JSON.stringify(encryptedPersistedSettings) !==
JSON.stringify(persistedSettings);
if (didSettingsMigration || shouldPersistEncryptedSettings) {
await this.host.saveData(encryptedPersistedSettings);
}
}
/** Encrypts protected fields and persists the current settings object. */
public async saveSettings(): Promise<void> {
await this.host.saveData(
encryptPersistedAPIKeys(
this.host.settings as PersistedExcalidrawSettings,
),
);
}
}
+40
View File
@@ -0,0 +1,40 @@
import { log } from "src/utils/debugHelper";
/** Stores and formats plugin startup timing events without owning startup order. */
export class StartupTimer {
private readonly events: string[] = [];
private lastLogTimestamp: number;
public constructor(
initialTimestamp: number,
private readonly pluginVersion: string,
) {
this.lastLogTimestamp = initialTimestamp;
}
/**
* Starts a new timing baseline while retaining events recorded before the
* reset, matching the existing constructor-to-layout startup breakdown.
*/
public reset(timestamp: number): void {
this.lastLogTimestamp = timestamp;
}
/** Records one startup event with total and previous-event elapsed times. */
public logEvent(message: string, loadTimestamp: number): void {
const timestamp = Date.now();
this.events.push(
`${message}\nTotal: ${timestamp - loadTimestamp}ms Delta: ${timestamp - this.lastLogTimestamp}ms\n`,
);
this.lastLogTimestamp = timestamp;
}
/** Writes the complete startup timing breakdown to the debug log. */
public printBreakdown(): void {
log(
`Excalidraw ${this.pluginVersion} startup breakdown:\n${this.events.join(
"\n",
)}`,
);
}
}
-2
View File
@@ -111,7 +111,6 @@ export interface ExcalidrawSettings {
compress: boolean;
decompressForMDView: boolean;
onceOffCompressFlagReset: boolean; //used to reset compress to true in 2.2.0
autosave: boolean;
autosaveIntervalDesktop: number;
autosaveIntervalMobile: number;
drawingFilenamePrefix: string;
@@ -558,7 +557,6 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
compress: true,
decompressForMDView: false,
onceOffCompressFlagReset: false,
autosave: true,
autosaveIntervalDesktop: 60000,
autosaveIntervalMobile: 30000,
drawingFilenamePrefix: "Drawing ",
+1 -1
View File
@@ -3,7 +3,7 @@ import { Modal, Notice, Setting, TFile } from "obsidian";
import { getEA } from "src/core";
import { DEVICE } from "src/constants/constants";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import ExcalidrawView from "src/view/ExcalidrawView";
import type ExcalidrawView from "src/view/ExcalidrawView";
import ExcalidrawPlugin from "src/core/main";
import {
fragWithHTML,
+1 -1
View File
@@ -19,7 +19,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
`,
"2.27.0": `
## Maintenance
- Retired obsolete pre-profile ExcalidrawAI settings migration and fallback handling. Current provider profiles and model configurations are unchanged.
- Refactoring the plugin. Removed unused functions, improved code structure and readability. Removed the obsolete Draw.io/Diagram plugin integration (since the other plugin no longer works and is not maintained) and retired the Create DrawIO file script from the script library.
`,
"2.26.4": `
+1 -1
View File
@@ -23,7 +23,7 @@ import { createSVG } from "src/utils/excalidrawAutomateUtils";
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import { t } from "../lang/helpers";
import { tex2dataURL } from "./LaTeX";
import ExcalidrawPlugin from "../core/main";
import type ExcalidrawPlugin from "../core/main";
import type { PdfJsDocumentProxy } from "src/types/pdfJsTypes";
import {
blobToBase64,
+1 -1
View File
@@ -20,7 +20,7 @@ import {
getExcalidrawMarkdownHeaderSection,
REGEX_TAGS,
} from "../shared/ExcalidrawData";
import ExcalidrawView from "src/view/ExcalidrawView";
import type ExcalidrawView from "src/view/ExcalidrawView";
import {
ExcalidrawElement,
ExcalidrawFrameElement,
+1 -1
View File
@@ -2,7 +2,7 @@ import { Notice } from "obsidian";
import { DEVICE, EXCALIDRAW_PLUGIN } from "src/constants/constants";
import { t } from "src/lang/helpers";
import { download } from "./fileUtils";
import { svgToBase64 } from "./utils";
import { svgToBase64 } from "./embeddedAssetUtils";
import {
PageDimensions,
PageOrientation,
+1 -1
View File
@@ -20,7 +20,7 @@ import {
} from "src/constants/constants";
import { ExcalidrawSettings } from "src/core/settings";
import { errorlog, getDataURL } from "./coreUtils";
import ExcalidrawPlugin from "src/core/main";
import type ExcalidrawPlugin from "src/core/main";
import {
getAttachmentsFolderAndFilePath,
splitFolderAndFilename,
+1 -1
View File
@@ -19,7 +19,7 @@ import {
SCRIPT_INSTALL_FOLDER,
VIEW_TYPE_EXCALIDRAW,
} from "../constants/constants";
import ExcalidrawPlugin from "../core/main";
import type ExcalidrawPlugin from "../core/main";
import {
ElementsMap,
ExcalidrawElement,
+185 -1501
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,479 @@
import type React from "react";
import type {
ExcalidrawElement,
ExcalidrawEmbeddableElement,
ExcalidrawMagicFrameElement,
NonDeletedExcalidrawElement,
} from "@zsviczian/excalidraw/types/element/src/types";
import type { UIAppState } from "@zsviczian/excalidraw/types/excalidraw/types";
import type { TTTDDialog } from "@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/types";
import {
excalidrawSword,
ICONS,
LogoWrapper,
saveIcon,
SwordColors,
} from "../../constants/actionIcons";
import { URLs } from "../../constants/safeUrls";
import { t } from "../../lang/helpers";
import { ttdPersistenceAdapter } from "../../shared/TTDDialogPersistanceAdater";
import { log } from "../../utils/debugHelper";
import type ExcalidrawView from "../ExcalidrawView";
/** Runtime dependencies and private view actions used by Excalidraw extensions. */
export interface ViewExcalidrawExtensionRendererDependencies {
CustomEmbeddable: typeof import("../components/CustomEmbeddable").CustomEmbeddable;
REGEX_LINK: typeof import("../../shared/ExcalidrawData").REGEX_LINK;
REG_LINKINDEX_HYPERLINK: typeof import("../../shared/ExcalidrawData").REG_LINKINDEX_HYPERLINK;
diagramToHTML: typeof import("../../utils/matic").diagramToHTML;
errorHTML: typeof import("../../utils/AIUtils").errorHTML;
extractCodeBlocks: typeof import("../../utils/AIUtils").extractCodeBlocks;
generateAIText: typeof import("../../utils/AIUtils").generateAIText;
getJsonErrorMessage: typeof import("../../utils/AIUtils").getJsonErrorMessage;
openExternalLink: typeof import("../../utils/excalidrawViewUtils").openExternalLink;
renderWebView: typeof import("../components/CustomEmbeddable").renderWebView;
useDefaultExcalidrawFrame: typeof import("../../utils/customEmbeddableUtils").useDefaultExcalidrawFrame;
openUIModeSettings: () => void;
openScriptInstallPrompt: () => void;
openExportImageDialog: () => void;
}
/**
* Renders the plugin-specific extension points supplied to Excalidraw.
*
* All elements are created with the owning view's package-managed React
* instance so main-window and popout-window runtimes remain isolated. Runtime
* dependencies that import the concrete view elsewhere are supplied by the
* composition root to avoid adding a circular import.
*/
export class ViewExcalidrawExtensionRenderer {
public constructor(
private readonly view: ExcalidrawView,
private readonly dependencies: ViewExcalidrawExtensionRendererDependencies,
) {}
/** Renders Excalidraw's text-to-diagram dialog with the plugin AI provider. */
public ttdDialog() {
const systemPrompt =
"The user will provide you with a text prompt. Your task is to generate a mermaid diagram based on the prompt. Use the graph, sequenceDiagram, flowchart or classDiagram types based on what best fits the request. Return a single message containing only the mermaid diagram in a codeblock. Avoid the use of `()` parenthesis in the mermaid script.";
const instruction =
"Return a single message containing only the mermaid diagram in a codeblock.";
return this.view.packages.react.createElement(
this.view.packages.excalidrawLib.TTDDialog,
{
persistenceAdapter: ttdPersistenceAdapter,
onTextSubmit: async (
props: Parameters<TTTDDialog.onTextSubmit>[0],
): Promise<TTTDDialog.OnTextSubmitRetValue> => {
const {
messages = [],
onChunk,
onStreamCreated,
signal,
} = props ?? {};
try {
onStreamCreated?.();
const { response, json, content, rateLimit, rateLimitRemaining } =
await this.dependencies.generateAIText(
{
systemPrompt,
messages,
instruction,
},
{
plugin: this.view.plugin,
signal,
},
);
if (
!response ||
response.status < 200 ||
response.status >= 300 ||
json?.error
) {
log(json);
return {
error: new Error(
this.dependencies.getJsonErrorMessage(json) ??
`Request failed with status ${response?.status ?? 0}`,
),
rateLimit,
rateLimitRemaining,
};
}
if (!content) {
log(json);
return {
error: new Error(
"Generation failed... see console log for details",
),
rateLimit,
rateLimitRemaining,
};
}
let generatedResponse =
this.dependencies
.extractCodeBlocks(content)
.find(
(block) => (block.type ?? "").toLowerCase() === "mermaid",
)?.data ??
this.dependencies.extractCodeBlocks(content)[0]?.data ??
content.trim();
if (!generatedResponse) {
log(json);
return {
error: new Error(
"Generation failed... see console log for details",
),
rateLimit,
rateLimitRemaining,
};
}
if (generatedResponse.startsWith("mermaid")) {
generatedResponse = generatedResponse
.replace(/^mermaid/, "")
.trim();
}
onChunk?.(generatedResponse);
return {
generatedResponse,
error: null,
rateLimit,
rateLimitRemaining,
};
} catch (error) {
const err = error as { name?: string; message?: string };
if (err?.name === "AbortError") {
return { error: new Error("Request aborted") };
}
log(error);
return { error: new Error(err?.message ?? "Request failed") };
}
},
},
);
}
/** Renders Excalidraw's diagram-to-code extension backed by ExcaliAI. */
public diagramToCode() {
return this.view.packages.react.createElement(
this.view.packages.excalidrawLib.DiagramToCodePlugin,
{
generate: async ({
frame,
children,
}: {
frame: ExcalidrawMagicFrameElement;
children: readonly ExcalidrawElement[];
}) => {
const appState = this.view.excalidrawAPI.getAppState();
const { theme } = appState as unknown as {
theme: "light" | "dark";
};
const nonDeletedChildren = children.filter(
(child): child is NonDeletedExcalidrawElement => !child.isDeleted,
);
try {
const blob =
await this.view.packages.excalidrawLib.exportToBlob({
elements: nonDeletedChildren,
appState: {
...appState,
exportBackground: true,
viewBackgroundColor: appState.viewBackgroundColor,
},
exportingFrame: frame,
files: this.view.excalidrawAPI.getFiles(),
mimeType: "image/jpeg",
});
const dataURL =
await this.view.packages.excalidrawLib.getDataURL(blob);
const textFromFrameChildren =
this.view.packages.excalidrawLib.getTextFromElements(
nonDeletedChildren,
);
const response = await this.dependencies.diagramToHTML({
image: dataURL,
text: textFromFrameChildren,
theme,
});
if (!response.ok) {
const text =
response.error ||
this.dependencies.getJsonErrorMessage(response.json) ||
"Unknown error during generation";
return {
html: this.dependencies.errorHTML(text),
};
}
if (!response.html) {
return {
html: this.dependencies.errorHTML("Nothing generated"),
};
}
return { html: response.html };
} catch (error) {
const err = error as { message?: string };
return {
html: this.dependencies.errorHTML(
err?.message ?? "Request failed",
),
};
}
},
},
);
}
/** Renders the trigger that opens the text-to-diagram dialog. */
public ttdDialogTrigger() {
return this.view.packages.react.createElement(
this.view.packages.excalidrawLib.TTDDialogTrigger,
{},
);
}
/** Renders the optional rank and resource welcome screen. */
public renderWelcomeScreen() {
if (!this.view.plugin.settings.showSplashscreen) {
return null;
}
const React = this.view.packages.react;
const { WelcomeScreen } = this.view.packages.excalidrawLib;
const filecount = this.view.app.vault
.getFiles()
.filter((file) => this.view.plugin.isExcalidrawFile(file)).length;
const rank =
filecount < 200
? "Bronze"
: filecount < 750
? "Silver"
: filecount < 2000
? "Gold"
: "Platinum";
const nextRankDelta =
filecount < 200
? 200 - filecount
: filecount < 750
? 750 - filecount
: filecount < 2000
? 2000 - filecount
: 0;
const { title } = SwordColors[rank];
return React.createElement(
WelcomeScreen,
{},
React.createElement(
WelcomeScreen.Center,
{},
React.createElement(
WelcomeScreen.Center.Logo,
{},
React.createElement(
LogoWrapper as React.FC<{ children?: React.ReactNode }>,
{},
excalidrawSword(rank),
),
),
React.createElement(WelcomeScreen.Center.Heading, {
color: "var(--color-gray-40)",
message:
nextRankDelta > 0
? `${rank}: ${nextRankDelta} ${t("WELCOME_RANK_NEXT")}`
: `${rank}: ${t("WELCOME_RANK_LEGENDARY")}`,
children: title,
}),
React.createElement(
WelcomeScreen.Center.Heading,
null,
t("WELCOME_COMMAND_PALETTE"),
React.createElement("br"),
t("WELCOME_OBSIDIAN_MENU"),
React.createElement("br"),
t("WELCOME_SCRIPT_LIBRARY"),
React.createElement("br"),
t("WELCOME_HELP_MENU"),
),
React.createElement(
WelcomeScreen.Center.Menu,
{},
React.createElement(WelcomeScreen.Center.MenuItemLink, {
icon: ICONS.Learn,
href: URLs.COMMUNITY_SKETCH_YOUR_MIND_COM,
shortcut: null,
"aria-label": t("WELCOME_SYM_ARIA"),
children: t("WELCOME_SYM_LINK"),
}),
React.createElement(WelcomeScreen.Center.MenuItemLink, {
icon: ICONS.YouTube,
href: URLs.WWW_YOUTUBE_COM_VISUALPKM,
shortcut: null,
"aria-label": t("WELCOME_YOUTUBE_ARIA"),
children: t("WELCOME_YOUTUBE_LINK"),
}),
React.createElement(WelcomeScreen.Center.MenuItemLink, {
icon: ICONS.twitter,
href: URLs.TWITTER_COM_ZSVICZIAN,
shortcut: null,
"aria-label": t("WELCOME_TWITTER_ARIA"),
children: t("WELCOME_TWITTER_LINK"),
}),
React.createElement(WelcomeScreen.Center.MenuItemLink, {
icon: ICONS.heart,
href: URLs.KO_FI_COM_ZSOLT,
shortcut: null,
"aria-label": t("WELCOME_DONATE_ARIA"),
children: t("WELCOME_DONATE_LINK"),
}),
),
),
);
}
/** Renders the plugin-specific items in Excalidraw's main actions menu. */
public renderCustomActionsMenu() {
const React = this.view.packages.react;
const { MainMenu } = this.view.packages.excalidrawLib;
return React.createElement(
MainMenu,
{},
React.createElement(MainMenu.DefaultItems.ChangeCanvasBackground),
React.createElement(MainMenu.DefaultItems.Preferences),
React.createElement(MainMenu.DefaultItems.ToggleTheme),
React.createElement(MainMenu.Separator),
React.createElement(MainMenu.Item, {
icon: ICONS.tray,
"aria-label": t("ARIA_LABEL_TRAY_MODE"),
onSelect: () => this.dependencies.openUIModeSettings(),
children: t("TRAY_TRAY_MODE"),
}),
React.createElement(MainMenu.Item, {
icon: saveIcon(false),
"aria-label": t("FORCE_SAVE"),
onSelect: () => {
void this.view.forceSave();
},
children: t("TRAY_SAVE"),
}),
React.createElement(MainMenu.Item, {
icon: ICONS.scriptEngine,
"aria-label": t("TRAY_SCRIPT_LIBRARY_ARIA"),
onSelect: () => this.dependencies.openScriptInstallPrompt(),
children: t("TRAY_SCRIPT_LIBRARY"),
}),
React.createElement(MainMenu.Item, {
icon: ICONS.ExportImage,
"aria-label": t("TRAY_EXPORT_ARIA"),
onSelect: () => this.dependencies.openExportImageDialog(),
children: t("TRAY_EXPORT"),
}),
React.createElement(MainMenu.Item, {
icon: ICONS.switchToMarkdown,
"aria-label": t("TRAY_SWITCH_TO_MD_ARIA"),
onSelect: () => {
void this.view.openAsMarkdown();
},
children: t("TRAY_SWITCH_TO_MD"),
}),
React.createElement(MainMenu.Separator),
React.createElement(MainMenu.Item, {
icon: ICONS.Learn,
"aria-label": t("LINKS_JOIN_SYM_ARIA"),
onSelect: () =>
this.dependencies.openExternalLink(
URLs.COMMUNITY_SKETCH_YOUR_MIND_COM,
this.view.app,
),
children: t("LINKS_JOIN_SYM"),
}),
React.createElement(MainMenu.DefaultItems.Help),
React.createElement(MainMenu.DefaultItems.ClearCanvas),
);
}
/** Renders Obsidian links, web views, and custom content as embeddables. */
public renderEmbeddable(
element: ExcalidrawEmbeddableElement,
appState: UIAppState,
) {
const React = this.view.packages.react;
try {
const useExcalidrawFrame =
this.dependencies.useDefaultExcalidrawFrame(element);
if (
!this.view.file ||
!element ||
!element.link ||
element.link.length === 0 ||
useExcalidrawFrame
) {
return null;
}
if (
element.link.match(this.dependencies.REG_LINKINDEX_HYPERLINK) ||
element.link.startsWith("data:")
) {
if (!useExcalidrawFrame) {
return this.dependencies.renderWebView(
element.link,
this.view,
element.id,
appState,
);
}
return null;
}
const res = this.dependencies.REGEX_LINK.getRes(element.link).next();
if (!res || (!res.value && res.done)) {
return null;
}
const linkText = this.dependencies.REGEX_LINK.getLink(res);
if (linkText.match(this.dependencies.REG_LINKINDEX_HYPERLINK)) {
if (!useExcalidrawFrame) {
return this.dependencies.renderWebView(
linkText,
this.view,
element.id,
appState,
);
}
return null;
}
return React.createElement(this.dependencies.CustomEmbeddable, {
element,
view: this.view,
appState,
linkText,
});
} catch (error) {
console.error(
"unexpected error in renderEmbeddable",
this.renderEmbeddable.bind(this),
error,
);
return null;
}
}
}
+600
View File
@@ -0,0 +1,600 @@
import { Notice } from "obsidian";
import type { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import type { BinaryFileData } from "@zsviczian/excalidraw/types/excalidraw/types";
import { DEVICE } from "../../constants/constants";
import { t } from "../../lang/helpers";
import type { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader";
import type { ExportDialog } from "../../shared/Dialogs/ExportDialog";
import { FileAndFolderSelectorModal } from "../../shared/Dialogs/FileAndFolderSelectorModal";
import type {
AutoexportConfig,
ExcalidrawViewScene,
} from "../../types/excalidrawViewTypes";
import type {
ExportSettings,
PageOrientation,
PageSize,
} from "../../types/exportUtilTypes";
import type { FileData } from "../../types/embeddedFileLoaderTypes";
import {
download,
exportImageToFile,
getIMGFilename,
getNewUniqueFilepath,
splitFolderAndFilename,
} from "../../utils/fileUtils";
import {
exportPNG,
exportPNGToClipboard,
exportSVG,
exportToPDF,
getMarginValue,
getPageDimensions,
} from "../../utils/exportUtils";
import type ExcalidrawView from "../ExcalidrawView";
/** Runtime dependencies supplied by the view's existing import graph. */
export interface ViewExportDependencies {
getOrCreateExportDialog: () => ExportDialog | null;
createEmbeddedFilesLoader: (isDark: boolean) => EmbeddedFilesLoader;
getExportInternalLinks: typeof import("../../utils/utils").getExportInternalLinks;
getExportPadding: typeof import("../../utils/utils").getExportPadding;
getExportTheme: typeof import("../../utils/utils").getExportTheme;
getPNG: typeof import("../../utils/utils").getPNG;
getPNGScale: typeof import("../../utils/utils").getPNGScale;
getSVG: typeof import("../../utils/utils").getSVG;
getWithBackground: typeof import("../../utils/utils").getWithBackground;
isMaskFile: typeof import("../../utils/utils").isMaskFile;
sceneRemoveInternalLinks: typeof import("../../utils/excalidrawViewUtils").sceneRemoveInternalLinks;
}
/**
* Owns export option resolution and raw, SVG, PNG, clipboard, and PDF export
* operations for one {@link ExcalidrawView}.
*
* The view retains its public export methods as compatibility delegates for
* scripts, dialogs, commands, and ExcalidrawAutomate. Export dialog state also
* remains on the view because existing consumers access that field directly.
*/
export class ViewExportManager {
public constructor(
private readonly view: ExcalidrawView,
private readonly dependencies: ViewExportDependencies,
) {}
/** Saves the supplied or current scene beside the Markdown file as JSON. */
public saveExcalidraw(scene?: ExcalidrawViewScene): void {
if (!scene) {
if (!this.view.excalidrawAPI) {
return;
}
scene = this.view.getScene();
}
const filepath = `${this.view.file?.path.substring(
0,
this.view.file.path.lastIndexOf(".md"),
)}.excalidraw`;
void exportImageToFile(
this.view,
filepath,
JSON.stringify(scene, null, "\t"),
".excalidraw",
);
}
/** Downloads or saves the current scene as a raw `.excalidraw` file. */
public async exportExcalidraw(selectedOnly?: boolean): Promise<void> {
if (!this.view.excalidrawAPI || !this.view.file) {
return;
}
if (DEVICE.isMobile) {
const location = await new FileAndFolderSelectorModal(this.view.app, {
title: t("FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE"),
folderLabel: t("FILE_AND_FOLDER_SELECTOR_FOLDER"),
fileNameLabel: t("FILE_AND_FOLDER_SELECTOR_FILENAME"),
submitButtonText: t("FILE_AND_FOLDER_SELECTOR_EXPORT"),
folderPath: splitFolderAndFilename(this.view.file.path).folderpath,
fileName: `${this.view.file.basename}.excalidraw`,
}).start();
if (!location) {
return;
}
const filename = location.fileName.toLowerCase().endsWith(".excalidraw")
? location.fileName
: `${location.fileName}.excalidraw`;
const path = getNewUniqueFilepath(
this.view.app.vault,
filename,
location.folderPath,
);
const file = await exportImageToFile(
this.view,
path,
JSON.stringify(this.view.getScene(), null, "\t"),
".excalidraw",
);
new Notice(`Exported to ${file?.name}`, 6000);
return;
}
download(
"data:text/plain;charset=utf-8",
encodeURIComponent(
JSON.stringify(this.view.getScene(selectedOnly), null, "\t"),
),
`${this.view.file.basename}.excalidraw`,
);
}
/** Resolves the explicit, dialog, or file-based export theme. */
public getViewExportTheme(theme?: string): string {
if (theme) {
return theme;
}
if (!this.view.file) {
return (
this.view.excalidrawAPI.getAppState() as unknown as { theme: string }
).theme;
}
const ed = this.dependencies.getOrCreateExportDialog();
return ed
? ed.theme
: this.dependencies.getExportTheme(
this.view.plugin,
this.view.file,
(
this.view.excalidrawAPI.getAppState() as unknown as {
theme: string;
}
).theme,
);
}
/** Resolves whether the serialized scene is embedded in an image export. */
public getViewExportEmbedScene(embedScene?: boolean): boolean {
if (!this.view.file) {
return false;
}
const ed = this.dependencies.getOrCreateExportDialog();
return typeof embedScene === "undefined"
? ed
? ed.embedScene
: false
: embedScene;
}
/** Resolves the explicit, dialog, or file-based image padding. */
public getViewExportPadding(padding?: number): number {
if (typeof padding !== "undefined") {
return padding;
}
if (!this.view.file) {
return 0;
}
const ed = this.dependencies.getOrCreateExportDialog();
return ed
? ed.padding
: this.dependencies.getExportPadding(this.view.plugin, this.view.file);
}
/** Resolves the explicit, dialog, or file-based PNG scale. */
public getViewExportScale(scale?: number): number {
if (typeof scale !== "undefined") {
return scale;
}
if (!this.view.file) {
return 1;
}
const ed = this.dependencies.getOrCreateExportDialog();
return ed
? ed.scale
: this.dependencies.getPNGScale(this.view.plugin, this.view.file);
}
/** Resolves whether image exports include the canvas background. */
public getViewExportWithBackground(
withBackground?: boolean,
): boolean | undefined {
if (typeof withBackground !== "undefined" || !this.view.file) {
return withBackground;
}
const ed = this.dependencies.getOrCreateExportDialog();
return ed
? !ed.transparent
: this.dependencies.getWithBackground(
this.view.plugin,
this.view.file,
);
}
/** Resolves whether SVG and PDF exports preserve internal links. */
public getViewExportIncludeInternalLinks(
includeInternalLinks?: boolean,
): boolean | undefined {
if (typeof includeInternalLinks !== "undefined" || !this.view.file) {
return includeInternalLinks;
}
const ed = this.dependencies.getOrCreateExportDialog();
return ed
? ed.exportInternalLinks
: this.dependencies.getExportInternalLinks(
this.view.plugin,
this.view.file,
);
}
/** Creates an SVG for the supplied scene using the view's export options. */
public async svg(
scene: ExcalidrawViewScene,
theme?: string,
embedScene?: boolean,
embedFont: boolean = false,
): Promise<SVGSVGElement> {
const exportSettings: ExportSettings = {
withBackground: !!this.getViewExportWithBackground(),
withTheme: true,
isMask: this.dependencies.isMaskFile(
this.view.plugin,
this.view.file,
),
skipInliningFonts: !embedFont,
};
const exportTheme = this.getViewExportTheme(theme);
const overrideFiles = await this.loadFilesForExport(exportTheme);
return await this.dependencies.getSVG(
{
...scene,
...{
appState: {
...scene.appState,
theme: exportTheme,
exportEmbedScene: this.getViewExportEmbedScene(embedScene),
},
},
},
exportSettings,
this.getViewExportPadding(),
this.view.file,
overrideFiles ?? undefined,
);
}
/** Saves SVG autoexports for the supplied or current scene. */
public async saveSVG(data: {
scene?: ExcalidrawViewScene;
embedScene?: boolean;
autoexportConfig?: AutoexportConfig;
}): Promise<void | false> {
if (!data) {
data = {};
}
if (!this.view.file) {
return;
}
let { scene, embedScene, autoexportConfig } = data;
if (!scene) {
if (!this.view.excalidrawAPI) {
return false;
}
scene = this.view.getScene();
}
const exportImage = async (filepath: string, theme?: string) => {
const svg = await this.svg(scene, theme, embedScene, true);
if (!svg) {
return;
}
// Serialize before passing the SVG across Obsidian's file boundary.
// See https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2026.
const svgString = svg.outerHTML;
await exportImageToFile(
this.view,
filepath,
svgString,
theme === "dark"
? ".dark.svg"
: theme === "light"
? ".light.svg"
: ".svg",
);
};
if (
autoexportConfig?.theme
? autoexportConfig.theme === "both"
: this.view.plugin.settings.autoExportLightAndDark
) {
await exportImage(
getIMGFilename(this.view.file.path, "dark.svg"),
"dark",
);
await exportImage(
getIMGFilename(this.view.file.path, "light.svg"),
"light",
);
} else {
await exportImage(
getIMGFilename(this.view.file.path, "svg"),
autoexportConfig?.theme,
);
}
}
/** Downloads an SVG export of the current or selected scene. */
public async exportSVG(
embedScene?: boolean,
selectedOnly?: boolean,
): Promise<void> {
if (!this.view.excalidrawAPI || !this.view.file) {
return;
}
const scene = this.view.getScene(selectedOnly);
if (!scene) {
return;
}
if (!this.getViewExportIncludeInternalLinks()) {
scene.elements = this.dependencies.sceneRemoveInternalLinks(scene);
}
const svg = await this.svg(scene, undefined, embedScene, true);
if (!svg) {
return;
}
exportSVG(svg, this.view.file.basename);
}
/** Returns an SVG export of the current or selected scene. */
public async getSVG(
embedScene?: boolean,
selectedOnly?: boolean,
): Promise<SVGSVGElement> {
if (!this.view.excalidrawAPI || !this.view.file) {
return new SVGSVGElement();
}
const svg = await this.svg(
this.view.getScene(selectedOnly),
undefined,
embedScene,
true,
);
if (!svg) {
return new SVGSVGElement();
}
return svg;
}
/** Downloads a PDF export of the current or selected scene. */
public async exportPDF(
selectedOnly?: boolean,
pageSize: PageSize = "A4",
orientation: PageOrientation = "portrait",
): Promise<void> {
if (!this.view.excalidrawAPI || !this.view.file) {
return;
}
const scene = this.view.getScene(selectedOnly);
if (!scene) {
return;
}
if (!this.getViewExportIncludeInternalLinks()) {
scene.elements = this.dependencies.sceneRemoveInternalLinks(scene);
}
const svg = await this.svg(scene, undefined, false, true);
if (!svg) {
return;
}
const boundingBox = this.view.plugin.ea.getBoundingBox(scene.elements);
const margin = getMarginValue(this.view.exportDialog?.margin ?? "normal");
const [width, height] = [boundingBox.width, boundingBox.height];
await exportToPDF({
SVG: [svg],
scale: {
zoom: this.view.exportDialog?.scale ?? 1,
fitToPage:
pageSize === "MATCH IMAGE" || pageSize === "HD Screen"
? 1
: (this.view.exportDialog?.fitToPage ?? 1),
},
pageProps: {
dimensions: getPageDimensions(pageSize, orientation, { width, height }),
backgroundColor:
this.view.exportDialog?.getPaperColor() ?? "#FFFFFF",
margin,
alignment: this.view.exportDialog?.alignment ?? "center",
},
filename: `${this.view.file.basename}.pdf`,
});
}
/** Creates a PNG blob for the supplied scene using the view's export options. */
public async png(
scene: ExcalidrawViewScene,
theme?: string,
embedScene?: boolean,
): Promise<Blob> {
const exportSettings: ExportSettings = {
withBackground: !!this.getViewExportWithBackground(),
withTheme: true,
isMask: this.dependencies.isMaskFile(
this.view.plugin,
this.view.file,
),
};
const exportTheme = this.getViewExportTheme(theme);
const overrideFiles = await this.loadFilesForExport(exportTheme);
return await this.dependencies.getPNG(
{
...scene,
...{
appState: {
...scene.appState,
theme: exportTheme,
exportEmbedScene: this.getViewExportEmbedScene(embedScene),
},
},
},
exportSettings,
this.getViewExportPadding(),
this.getViewExportScale(),
overrideFiles ?? undefined,
);
}
/** Saves PNG autoexports for the supplied or current scene. */
public async savePNG(data: {
scene?: ExcalidrawViewScene;
embedScene?: boolean;
autoexportConfig?: AutoexportConfig;
}): Promise<void | false> {
if (!data) {
data = {};
}
if (!this.view.file) {
return;
}
let { scene, embedScene, autoexportConfig } = data;
if (!scene) {
if (!this.view.excalidrawAPI) {
return false;
}
scene = this.view.getScene();
}
const exportImage = async (filepath: string, theme?: string) => {
const png = await this.png(scene, theme, embedScene);
if (!png) {
return;
}
await exportImageToFile(
this.view,
filepath,
png,
theme === "dark"
? ".dark.png"
: theme === "light"
? ".light.png"
: ".png",
);
};
if (
autoexportConfig?.theme
? autoexportConfig.theme === "both"
: this.view.plugin.settings.autoExportLightAndDark
) {
await exportImage(
getIMGFilename(this.view.file.path, "dark.png"),
"dark",
);
await exportImage(
getIMGFilename(this.view.file.path, "light.png"),
"light",
);
} else {
await exportImage(
getIMGFilename(this.view.file.path, "png"),
autoexportConfig?.theme,
);
}
}
/** Copies a PNG export of the current or selected scene to the clipboard. */
public async exportPNGToClipboard(
embedScene?: boolean,
selectedOnly?: boolean,
): Promise<void> {
if (!this.view.excalidrawAPI || !this.view.file) {
return;
}
const png = await this.png(
this.view.getScene(selectedOnly),
undefined,
embedScene,
);
if (!png) {
return;
}
// Safari requires ClipboardItem creation to remain associated with the
// originating user gesture. The shared helper preserves the established
// Promise-based ClipboardItem fallback for that browser behavior.
await exportPNGToClipboard(png);
}
/** Downloads a PNG export of the current or selected scene. */
public async exportPNG(
embedScene?: boolean,
selectedOnly?: boolean,
): Promise<void> {
if (!this.view.excalidrawAPI || !this.view.file) {
return;
}
const png = await this.png(
this.view.getScene(selectedOnly),
undefined,
embedScene,
);
if (!png) {
return;
}
exportPNG(png, this.view.file.basename);
}
/** Reloads embedded files when an export theme differs from the view theme. */
private async loadFilesForExport(
exportTheme: string,
): Promise<Record<FileId, BinaryFileData> | null> {
const api = this.view.excalidrawAPI;
if (!api || !this.view.excalidrawData) {
return null;
}
const viewTheme = (api.getAppState() as unknown as { theme: string }).theme;
if (!exportTheme || exportTheme === viewTheme) {
return null;
}
const loader = this.dependencies.createEmbeddedFilesLoader(
exportTheme === "dark",
);
const collected: Record<FileId, BinaryFileData> = {};
let resolved = false;
void (await new Promise<void>((resolve) => {
void loader.loadSceneFiles({
excalidrawData: this.view.excalidrawData,
sceneElements: this.view.getViewElements(),
addFiles: (
files: FileData[],
_isDark: boolean,
final: boolean = true,
) => {
if (files && files.length > 0) {
files.forEach((f) => {
const fileId = f.id as unknown as FileId;
collected[fileId] = { ...f };
});
}
if (final && !resolved) {
resolved = true;
resolve();
}
},
depth: 0,
isThemeChange: true,
});
}));
return Object.keys(collected).length ? collected : null;
}
}
+166
View File
@@ -0,0 +1,166 @@
import { setStyle } from "../../utils/styleUtils";
import { isInstanceOfHTMLElement } from "../../utils/typechecks";
const FULLSCREEN_HIDDEN_CLASS = "excalidraw-hidden";
const FULLSCREEN_VISIBLE_CLASS = "excalidraw-visible";
interface FullscreenToolsPanel {
setFullscreen(isFullscreen: boolean): void;
}
/**
* Minimal view surface required by {@link ViewFullscreenManager}.
*
* `ownerDocument` must remain view-scoped so fullscreen DOM changes target the
* correct Obsidian window when the view is hosted in a popout.
*/
export interface ViewFullscreenHost {
contentEl: HTMLElement;
readonly ownerDocument: Document;
excalidrawWrapperRef: { current: HTMLDivElement | null } | null;
toolsPanelRef: { current: FullscreenToolsPanel | null } | null;
plugin: {
readonly leafChangeTimeout: number | null;
clearLeafChangeTimeout(): void;
};
}
/**
* Applies and restores the DOM classes used by one Excalidraw view's
* fullscreen mode.
*/
export class ViewFullscreenManager {
public constructor(private readonly host: ViewFullscreenHost) {}
/** Enters fullscreen mode within the view's owning Obsidian document. */
public gotoFullscreen(): void {
if (this.host.plugin.leafChangeTimeout) {
// The timeout is created on the main window by EventManager.
window.clearTimeout(this.host.plugin.leafChangeTimeout);
this.host.plugin.clearLeafChangeTimeout();
}
if (!this.host.excalidrawWrapperRef) {
return;
}
if (this.host.toolsPanelRef?.current) {
this.host.toolsPanelRef.current.setFullscreen(true);
}
const hide = (el: HTMLElement) => {
setStyle(el, { marginTop: "0px" });
let tmpEl = el;
while (tmpEl && !tmpEl.hasClass("workspace-split")) {
el.addClass(FULLSCREEN_VISIBLE_CLASS);
el = tmpEl;
tmpEl = el.parentElement;
}
if (el) {
el.addClass(FULLSCREEN_VISIBLE_CLASS);
el.querySelectorAll(
`div.workspace-split:not(.${FULLSCREEN_VISIBLE_CLASS})`,
).forEach((node) => {
if (node !== el) {
node.addClass(FULLSCREEN_VISIBLE_CLASS);
}
});
el.querySelector(
`div.workspace-leaf-content.${FULLSCREEN_VISIBLE_CLASS} > .view-header`,
).addClass(FULLSCREEN_VISIBLE_CLASS);
el.querySelectorAll(
`div.workspace-tab-container.${FULLSCREEN_VISIBLE_CLASS} > div.workspace-leaf:not(.${FULLSCREEN_VISIBLE_CLASS})`,
).forEach((node) => node.addClass(FULLSCREEN_VISIBLE_CLASS));
el.querySelectorAll(
`div.workspace-tabs.${FULLSCREEN_VISIBLE_CLASS} > div.workspace-tab-header-container`,
).forEach((node) => node.addClass(FULLSCREEN_VISIBLE_CLASS));
el.querySelectorAll(
`div.workspace-split.${FULLSCREEN_VISIBLE_CLASS} > div.workspace-tabs:not(.${FULLSCREEN_VISIBLE_CLASS})`,
).forEach((node) => node.addClass(FULLSCREEN_VISIBLE_CLASS));
}
const doc = this.host.ownerDocument;
doc.body
.querySelectorAll(
`div.workspace-split:not(.${FULLSCREEN_VISIBLE_CLASS})`,
)
.forEach((node) => {
if (node !== tmpEl) {
node.addClass(FULLSCREEN_HIDDEN_CLASS);
} else {
node.addClass(FULLSCREEN_VISIBLE_CLASS);
}
});
doc.body
.querySelector(
`div.workspace-leaf-content.${FULLSCREEN_VISIBLE_CLASS} > .view-header`,
)
.addClass(FULLSCREEN_HIDDEN_CLASS);
doc.body
.querySelectorAll(
`div.workspace-tab-container.${FULLSCREEN_VISIBLE_CLASS} > div.workspace-leaf:not(.${FULLSCREEN_VISIBLE_CLASS})`,
)
.forEach((node) => node.addClass(FULLSCREEN_HIDDEN_CLASS));
doc.body
.querySelectorAll(
`div.workspace-tabs.${FULLSCREEN_VISIBLE_CLASS} > div.workspace-tab-header-container`,
)
.forEach((node) => node.addClass(FULLSCREEN_HIDDEN_CLASS));
doc.body
.querySelectorAll(
`div.workspace-split.${FULLSCREEN_VISIBLE_CLASS} > div.workspace-tabs:not(.${FULLSCREEN_VISIBLE_CLASS})`,
)
.forEach((node) => node.addClass(FULLSCREEN_HIDDEN_CLASS));
doc.body
.querySelectorAll("div.workspace-ribbon")
.forEach((node) => node.addClass(FULLSCREEN_HIDDEN_CLASS));
doc.body
.querySelectorAll("div.mobile-navbar")
.forEach((node) => node.addClass(FULLSCREEN_HIDDEN_CLASS));
doc.body
.querySelectorAll("div.status-bar")
.forEach((node) => node.addClass(FULLSCREEN_HIDDEN_CLASS));
doc.body
.querySelectorAll("div.titlebar")
.forEach((node) => node.addClass(FULLSCREEN_HIDDEN_CLASS));
const topPadding = doc.body.querySelector(
".is-mobile .workspace > .mod-root",
);
if (topPadding && isInstanceOfHTMLElement(topPadding)) {
setStyle(topPadding, { paddingTop: "0px" });
}
};
hide(this.host.contentEl);
}
/** Returns whether this view's owning document contains fullscreen classes. */
public isFullscreen(): boolean {
return Boolean(
this.host.ownerDocument.body.querySelector(
`.${FULLSCREEN_HIDDEN_CLASS}`,
),
);
}
/** Restores DOM classes and layout styles applied by fullscreen mode. */
public exitFullscreen(): void {
if (!this.isFullscreen()) {
return;
}
if (this.host.toolsPanelRef?.current) {
this.host.toolsPanelRef.current.setFullscreen(false);
}
const doc = this.host.ownerDocument;
doc
.querySelectorAll(`.${FULLSCREEN_HIDDEN_CLASS}`)
.forEach((el) => el.removeClass(FULLSCREEN_HIDDEN_CLASS));
doc
.querySelectorAll(`.${FULLSCREEN_VISIBLE_CLASS}`)
.forEach((el) => el.removeClass(FULLSCREEN_VISIBLE_CLASS));
const topPadding = doc.body.querySelector(
".is-mobile .workspace > .mod-root",
);
if (topPadding && isInstanceOfHTMLElement(topPadding)) {
setStyle(topPadding, { paddingTop: "" });
}
setStyle(this.host.contentEl, { marginTop: "" });
}
}
@@ -0,0 +1,624 @@
import { Notice } from "obsidian";
import {
ElementsMap,
ExcalidrawElement,
ExcalidrawImageElement,
ExcalidrawTextElement,
} from "@zsviczian/excalidraw/types/element/src/types";
import {
CaptureUpdateAction,
getContainerElement,
} from "../../constants/constants";
import { t } from "../../lang/helpers";
import { TextMode } from "../../shared/TextMode";
import type {
SelectedElementWithLink,
SelectedImage,
} from "../../types/excalidrawViewTypes";
import type { ModifierKeys } from "../../utils/modifierkeyHelper";
import { getMermaidText, shouldRenderMermaid } from "../../utils/mermaidUtils";
import type ExcalidrawView from "../ExcalidrawView";
/** Runtime dependencies and private view operations needed by link navigation. */
export interface ViewLinkNavigationDependencies {
REGEX_LINK: typeof import("../../shared/ExcalidrawData").REGEX_LINK;
REG_LINKINDEX_HYPERLINK: typeof import("../../shared/ExcalidrawData").REG_LINKINDEX_HYPERLINK;
NewFileActions: typeof import("../../shared/Dialogs/Prompt").NewFileActions;
linkPrompt: typeof import("../../shared/Dialogs/Prompt").linkPrompt;
getMarkdownImageSource: typeof import("../../shared/MarkdownImage").getMarkdownImageSource;
isMarkdownImageElement: typeof import("../../shared/MarkdownImage").isMarkdownImageElement;
splitFolderAndFilename: typeof import("../../utils/fileUtils").splitFolderAndFilename;
getTextElementAtPointer: typeof import("../../utils/getElementAtPointer").getTextElementAtPointer;
anyModifierKeysPressed: typeof import("../../utils/modifierkeyHelper").anyModifierKeysPressed;
emulateKeysForLinkClick: typeof import("../../utils/modifierkeyHelper").emulateKeysForLinkClick;
linkClickModifierType: typeof import("../../utils/modifierkeyHelper").linkClickModifierType;
getLeaf: typeof import("../../utils/obsidianUtils").getLeaf;
openLeaf: typeof import("../../utils/obsidianUtils").openLeaf;
getExcalidrawFileForwardLinks: typeof import("../../utils/excalidrawViewUtils").getExcalidrawFileForwardLinks;
openExternalLink: typeof import("../../utils/excalidrawViewUtils").openExternalLink;
parseObsidianLink: typeof import("../../utils/excalidrawViewUtils").parseObsidianLink;
arrayToMap: typeof import("../../utils/utils").arrayToMap;
errorlog: typeof import("../../utils/utils").errorlog;
getContainerElementForText: (
element: ExcalidrawTextElement,
) => ExcalidrawElement | null;
getSelectedTextElement: () => SelectedElementWithLink;
getSelectedImageElement: () => SelectedImage;
getSelectedElementWithLink: () => SelectedElementWithLink;
forceSaveIfRequired: () => Promise<boolean>;
}
/**
* Resolves element links and coordinates navigation for one Excalidraw view.
*
* The owning view retains compatibility delegates for scripts, commands, UI
* components, and Excalidraw callbacks. The concrete view is referenced only
* as a TypeScript type because established link helpers require that surface;
* this module does not create a runtime import cycle.
*/
export class ViewLinkNavigationManager {
public constructor(
private readonly view: ExcalidrawView,
private readonly dependencies: ViewLinkNavigationDependencies,
) {}
/** Hides the Excalidraw link tooltip in the view's owning document. */
public removeLinkTooltip(): void {
const tooltip = this.view.ownerDocument.body.querySelector(
"body>div.excalidraw-tooltip,div.excalidraw-tooltip--visible",
);
if (tooltip) {
tooltip.classList.remove("excalidraw-tooltip--visible");
}
}
/**
* Invokes the public link-click hook and reports whether default navigation
* should stop.
*/
public handleLinkHookCall(
element: ExcalidrawElement,
link: string,
event: MouseEvent | null,
): boolean {
if (this.view.getHookServer().onLinkClickHook) {
try {
if (
!this.view.getHookServer().onLinkClickHook(
element,
link,
event,
this.view,
this.view.getHookServer(),
)
) {
return true;
}
} catch (e: unknown) {
this.dependencies.errorlog({
where: "ExcalidrawView.onLinkOpen",
fn: "getHookServer().onLinkClickHook",
error: e,
});
}
}
return false;
}
/** Resolves the effective link and source element for a view selection. */
public getLinkTextForElement(
selectedText: SelectedElementWithLink,
selectedElementWithLink?: SelectedElementWithLink,
allowLinearElementClick: boolean = false,
): {
linkText: string;
selectedElement: ExcalidrawElement;
isLinearElement: boolean;
} {
if (selectedText?.id || selectedElementWithLink?.id) {
let selectedTextElement: ExcalidrawTextElement = selectedText.id
? (this.view.excalidrawAPI
.getSceneElements()
.find(
(el: ExcalidrawElement) => el.id === selectedText.id,
) as ExcalidrawTextElement)
: null;
let selectedElement = selectedElementWithLink.id
? (this.view.excalidrawAPI
.getSceneElements()
.find(
(el: ExcalidrawElement) => el.id === selectedElementWithLink.id,
) as ExcalidrawElement)
: null;
// If the user clicked the label of an arrow, Excalidraw returns the
// container as selected. Treat the label as text so its link navigates.
if (!selectedTextElement && selectedElement?.type === "text") {
const container = getContainerElement(
selectedElement,
this.dependencies.arrayToMap(
this.view.excalidrawAPI.getSceneElements(),
) as ElementsMap,
);
if (container?.type === "arrow") {
const x = this.dependencies.getTextElementAtPointer(
this.view.currentPosition,
this.view,
);
if (x?.id === selectedElement.id) {
selectedTextElement = selectedElement;
selectedElement = null;
}
}
}
// CTRL click on a linear element with a link navigates instead of opening
// the linear element editor.
if (
!allowLinearElementClick &&
["arrow", "line"].includes(selectedElement?.type)
) {
return {
linkText: selectedElement.link,
selectedElement,
isLinearElement: true,
};
}
if (!selectedTextElement && selectedElement?.type === "text") {
if (!allowLinearElementClick) {
const container = getContainerElement(
selectedElement,
this.dependencies.arrayToMap(
this.view.excalidrawAPI.getSceneElements(),
) as ElementsMap,
);
if (container?.type !== "arrow") {
selectedTextElement = selectedElement;
selectedElement = null;
} else {
const x = this.view.processLinkText(
selectedElement.rawText,
selectedElement,
container,
false,
);
return {
linkText: x.linkText,
selectedElement: container,
isLinearElement: true,
};
}
} else {
selectedTextElement = selectedElement;
selectedElement = null;
}
}
const linkCandidates: string[] = [];
const addCandidate = (value?: string | null) => {
if (value && value.trim().length > 0) {
linkCandidates.push(value);
}
};
if (selectedTextElement) {
const textBody =
this.view.textMode === TextMode.parsed
? this.view.excalidrawData.getRawText(selectedTextElement.id)
: (selectedTextElement.rawText ??
selectedTextElement.text ??
selectedText.text);
addCandidate(textBody);
addCandidate(selectedTextElement.link);
if (!selectedElement && selectedTextElement.containerId) {
const container =
this.dependencies.getContainerElementForText(selectedTextElement);
addCandidate(container?.link);
}
} else {
const rawTextCandidate = selectedText?.id
? this.view.textMode === TextMode.parsed
? this.view.excalidrawData.getRawText(selectedText.id)
: selectedText.text
: selectedText?.text;
addCandidate(rawTextCandidate);
}
addCandidate(selectedElement?.link ?? selectedElementWithLink?.text);
const linkText = Array.from(new Set(linkCandidates)).join(" ");
return {
linkText: linkText || null,
selectedElement: selectedElement ?? selectedTextElement,
isLinearElement: false,
};
}
return { linkText: null, selectedElement: null, isLinearElement: false };
}
/** Resolves raw element text to the link used by the navigation flow. */
public processLinkText(
linkText: string,
selectedTextElement: ExcalidrawTextElement,
selectedElement: ExcalidrawElement,
shouldOpenLink: boolean = true,
): { linkText: string | null; selectedElement: ExcalidrawElement | null } {
if (!linkText) {
return { linkText: null, selectedElement: null };
}
if (linkText.startsWith("#")) {
return {
linkText,
selectedElement: selectedTextElement ?? selectedElement,
};
}
const maybeObsidianLink = this.dependencies.parseObsidianLink(
linkText,
this.view.app,
shouldOpenLink,
);
if (typeof maybeObsidianLink === "string") {
linkText = maybeObsidianLink;
}
const partsArray = this.dependencies.REGEX_LINK.getResList(linkText);
if (!linkText || partsArray.length === 0) {
// The container link takes precedence over the text link.
if (selectedTextElement?.containerId) {
const container =
this.dependencies.getContainerElementForText(selectedTextElement);
if (container) {
linkText = container.link;
if (linkText?.startsWith("#")) {
return {
linkText,
selectedElement: selectedTextElement ?? selectedElement,
};
}
const maybeObsidianLink = this.dependencies.parseObsidianLink(
linkText,
this.view.app,
shouldOpenLink,
);
if (typeof maybeObsidianLink === "string") {
linkText = maybeObsidianLink;
}
}
}
if (!linkText || partsArray.length === 0) {
linkText = selectedTextElement?.link;
}
}
return {
linkText,
selectedElement: selectedTextElement ?? selectedElement,
};
}
/** Resolves the clicked element and performs the configured link action. */
public async linkClick(
ev: MouseEvent | null,
selectedText: SelectedElementWithLink,
selectedImage: SelectedImage,
selectedElementWithLink: SelectedElementWithLink,
keys?: ModifierKeys,
allowLinearElementClick: boolean = false,
): Promise<void> {
if (!selectedText) {
selectedText = { id: null, text: null };
}
if (!selectedImage) {
selectedImage = { id: null, fileId: null };
}
if (!selectedElementWithLink) {
selectedElementWithLink = { id: null, text: null };
}
if (!ev && !keys) {
keys = this.dependencies.emulateKeysForLinkClick("new-tab");
}
if (ev && !keys) {
keys = {
shiftKey: ev.shiftKey,
ctrlKey: ev.ctrlKey,
metaKey: ev.metaKey,
altKey: ev.altKey,
};
}
const linkClickType = this.dependencies.linkClickModifierType(keys);
let file = null;
let subpath: string = null;
let { linkText, selectedElement, isLinearElement } =
this.getLinkTextForElement(
selectedText,
selectedElementWithLink,
allowLinearElementClick,
);
if (selectedElement) {
if (!allowLinearElementClick && linkText && isLinearElement) {
if (this.view.semaphores.warnAboutLinearElementLinkClick) {
new Notice(t("LINEAR_ELEMENT_LINK_CLICK_ERROR"), 20000);
this.view.semaphores.warnAboutLinearElementLinkClick = false;
}
return;
}
if (!linkText) {
return;
}
linkText = linkText.replaceAll("\n", "");
if (this.dependencies.openExternalLink(linkText, this.view.app)) {
return;
}
const maybeObsidianLink = this.dependencies.parseObsidianLink(
linkText,
this.view.app,
);
if (typeof maybeObsidianLink === "boolean" && maybeObsidianLink) {
return;
}
if (typeof maybeObsidianLink === "string") {
linkText = maybeObsidianLink;
}
const result = await this.dependencies.linkPrompt(
linkText,
this.view.app,
this.view,
);
if (!result) {
return;
}
[file, linkText, subpath] = result;
if (this.view.handleLinkHookCall(selectedElement, linkText, ev)) {
return;
}
}
if (selectedImage?.id) {
const imageElement = this.view
.getScene()
.elements.find(
(el: ExcalidrawElement) => el.id === selectedImage.id,
) as ExcalidrawImageElement;
if (
linkClickType === "md-properties" &&
this.view.excalidrawData.hasFile(selectedImage.fileId)
) {
this.view.updateScene({ appState: { contextMenu: null } });
void this.view.openEmbeddedLinkEditor(selectedImage.id);
return;
}
const markdownImageSource = this.dependencies.isMarkdownImageElement(
this.view,
imageElement,
)
? await this.dependencies.getMarkdownImageSource(this.view, imageElement)
: null;
if (markdownImageSource) {
const externalSourceLink =
markdownImageSource.source === "external" &&
markdownImageSource.embeddedFile
? markdownImageSource.embeddedFile.linkParts.original
: null;
const result = await this.dependencies.linkPrompt(
`${externalSourceLink ? `[[${externalSourceLink}]] ` : ""}${markdownImageSource.markdown}`,
this.view.app,
this.view,
);
if (!result) {
return;
}
[file, linkText, subpath] = result;
if (
markdownImageSource.source === "external" &&
markdownImageSource.embeddedFile?.file &&
linkText
) {
file =
linkText === markdownImageSource.embeddedFile.linkParts.path
? markdownImageSource.embeddedFile.file
: this.view.app.metadataCache.getFirstLinkpathDest(
linkText,
markdownImageSource.embeddedFile.file.path,
);
}
}
if (
!markdownImageSource &&
this.view.excalidrawData.hasEquation(selectedImage.fileId)
) {
this.view.updateScene({ appState: { contextMenu: null } });
void this.view.openLaTeXEditor(selectedImage.id);
return;
}
if (
!markdownImageSource &&
(this.view.excalidrawData.hasMermaid(selectedImage.fileId) ||
getMermaidText(imageElement))
) {
if (shouldRenderMermaid) {
const api = this.view.excalidrawAPI;
api.updateScene({
appState: { openDialog: { name: "ttd", tab: "mermaid" } },
captureUpdate: CaptureUpdateAction.NEVER,
});
}
return;
}
if (!markdownImageSource) {
await this.view.save(false);
}
if (
!markdownImageSource &&
this.view.excalidrawData.hasFile(selectedImage.fileId)
) {
const fileId = selectedImage.fileId;
const ef = this.view.excalidrawData.getFile(fileId);
if (
!ef.isHyperLink &&
!ef.isLocalLink &&
ef.file &&
linkClickType === "md-properties"
) {
this.view.updateScene({ appState: { contextMenu: null } });
void this.view.openEmbeddedLinkEditor(selectedImage.id);
return;
}
let secondOrderLinks: string = " ";
const backlinks = this.view.app.metadataCache?.getBacklinksForFile(
ef.file,
)?.data;
const secondOrderLinksSet = new Set<string>();
if (backlinks && this.view.plugin.settings.showSecondOrderLinks) {
const linkPaths = Object.keys(backlinks)
.filter(
(path) =>
path !== this.view.file.path && path !== ef.file.path,
)
.map((path) => {
const filepathParts =
this.dependencies.splitFolderAndFilename(path);
if (secondOrderLinksSet.has(path)) {
return "";
}
secondOrderLinksSet.add(path);
return `[[${path}|${t("LINKLIST_SECOND_ORDER_LINK")}: ${filepathParts.basename}]]`;
});
secondOrderLinks += linkPaths.join(" ");
}
if (
this.view.plugin.settings.showSecondOrderLinks &&
this.view.plugin.isExcalidrawFile(ef.file)
) {
secondOrderLinks += this.dependencies.getExcalidrawFileForwardLinks(
this.view.app,
ef.file,
secondOrderLinksSet,
);
}
const linkString =
(ef.isHyperLink || ef.isLocalLink
? `[](${ef.hyperlink}) `
: `[[${ef.linkParts.original}]] `) +
(imageElement.link
? imageElement.link.match(/$cmd:\/\/.*/) ||
imageElement.link.match(
this.dependencies.REG_LINKINDEX_HYPERLINK,
)
? `[](${imageElement.link})`
: imageElement.link
: "");
const result = await this.dependencies.linkPrompt(
linkString + secondOrderLinks,
this.view.app,
this.view,
);
if (!result) {
return;
}
[file, linkText, subpath] = result;
}
}
if (!linkText) {
if (allowLinearElementClick) {
return;
}
new Notice(t("LINK_BUTTON_CLICK_NO_TEXT"), 20000);
return;
}
const id =
selectedImage.id ?? selectedText.id ?? selectedElementWithLink.id;
const sceneElements = this.view.excalidrawAPI.getSceneElements() as readonly
ExcalidrawElement[];
const el = sceneElements.filter((element) => element.id === id)[0];
if (this.view.handleLinkHookCall(el, linkText, ev)) {
return;
}
try {
if (linkClickType !== "active-pane" && this.view.isFullscreen()) {
this.view.exitFullscreen();
}
if (!file) {
new this.dependencies.NewFileActions({
plugin: this.view.plugin,
path: linkText,
keys,
view: this.view,
sourceElement: el,
}).open();
return;
}
if (
this.view.linksAlwaysOpenInANewPane &&
!this.dependencies.anyModifierKeysPressed(keys)
) {
keys = this.dependencies.emulateKeysForLinkClick("new-pane");
}
// Save before replacing this pane with the link destination.
await this.dependencies.forceSaveIfRequired();
const { promise } = this.dependencies.openLeaf({
plugin: this.view.plugin,
fnGetLeaf: () =>
this.dependencies.getLeaf(
this.view.plugin,
this.view.leaf,
keys,
),
file,
openState: {
active: !this.view.linksAlwaysOpenInANewPane,
...(subpath ? { eState: { subpath } } : {}),
},
});
await promise;
} catch (e: unknown) {
new Notice(e as string, 4000);
}
}
/** Resolves the current selection and starts its configured link action. */
public async handleLinkClick(
ev: MouseEvent | ModifierKeys,
allowLinearElementClick: boolean = false,
): Promise<void> {
this.view.removeLinkTooltip();
const selectedText = this.dependencies.getSelectedTextElement();
const selectedImage = selectedText?.id
? null
: this.dependencies.getSelectedImageElement();
const selectedElementWithLink =
selectedImage?.id || selectedText?.id
? null
: this.dependencies.getSelectedElementWithLink();
void this.view.linkClick(
ev instanceof MouseEvent ? ev : null,
selectedText,
selectedImage,
selectedElementWithLink,
ev instanceof MouseEvent ? null : ev,
allowLinearElementClick,
);
}
}