mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b35fea7eb7 | ||
|
|
3ceed630b7 | ||
|
|
ee223fa239 | ||
|
|
f1e089930b | ||
|
|
da9dd0fa0b | ||
|
|
04f38a6455 | ||
|
|
6976d0969c | ||
|
|
b196ac3de6 | ||
|
|
776b32216d | ||
|
|
5843e88e6f | ||
|
|
e0c4eecef4 | ||
|
|
fd9090562e | ||
|
|
1a78992ef1 | ||
|
|
703355f036 | ||
|
|
371fa7a254 | ||
|
|
00a1bed763 | ||
|
|
ff2c8536ce | ||
|
|
eee975c44d | ||
|
|
150f5ccbea | ||
|
|
4f5d913004 | ||
|
|
64be1aee1e | ||
|
|
acf7b8d642 | ||
|
|
95d89f2fed | ||
|
|
c86db2152e | ||
|
|
7caf768b8f | ||
|
|
b295723780 | ||
|
|
40e747c3bd | ||
|
|
dd06b07a12 | ||
|
|
b4df1d8e5b | ||
|
|
614f0fbab0 | ||
|
|
07ff3b7e96 | ||
|
|
75940d6173 | ||
|
|
8ba60c43e8 | ||
|
|
ae73115e9c | ||
|
|
723c7c5de2 | ||
|
|
680ae101cb | ||
|
|
82578a0a58 | ||
|
|
8c2da6a1c3 | ||
|
|
b09fa3b1ed | ||
|
|
6001ef3f1f | ||
|
|
40e204c2d9 | ||
|
|
e6c07bb615 | ||
|
|
7aa3f044cf | ||
|
|
b901bfbcac |
No files matched your search
+784
@@ -0,0 +1,784 @@
|
||||
# Incremental refactor assessment and plan
|
||||
|
||||
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
|
||||
Obsidian integration. It is intentionally incremental. Each implementation
|
||||
step should be small enough to review, build, and manually validate in
|
||||
isolation.
|
||||
|
||||
## Progress tracking
|
||||
|
||||
Release target: **2.27.0**.
|
||||
|
||||
Update this document in every refactor change. A change is not complete until
|
||||
its phase status and the action log reflect what was implemented, what was
|
||||
validated, and what remains uncertain.
|
||||
|
||||
| Phase | Status | Current outcome |
|
||||
| --- | --- | --- |
|
||||
| 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 |
|
||||
| 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
|
||||
|
||||
| Date | Action | Outcome | Validation |
|
||||
| --- | --- | --- | --- |
|
||||
| 2026-08-08 | Reviewed `AGENTS.md`, `CONTRIBUTING.md`, plugin lifecycle, view lifecycle, package loading, rendering, and Rollup packaging | Established the hybrid Obsidian-host/React-child target and incremental implementation sequence | `npm run build` passed; existing circular dependency warnings recorded |
|
||||
| 2026-08-08 | Refined scope for 2.27.0 | Legacy AI migration will be retired; generic top-level settings normalization, ExcalidrawAutomate compatibility, duplicate-logic review, and TSDoc are now explicit requirements | Settings and utility reference searches completed; documentation-only build passed |
|
||||
| 2026-08-08 | Assessed automatic supported-key settings sanitization | Confirmed that removing `stripLegacyAISettings()` alone would re-persist legacy defaults; a shallow replacement is viable only with a cleaned runtime schema and forward-version protection | TypeScript AST check confirmed 204 interface keys and 204 matching `DEFAULT_SETTINGS` keys; load/save, migration, encryption, and dynamic-settings writes reviewed |
|
||||
| 2026-08-08 | Rejected automatic settings sanitization | Because supported settings change frequently, unknown-key removal creates unacceptable forward-version, downgrade, and mixed-device sync risk. Phase 1 is now limited to removing confirmed legacy AI code and fallback fields | Plan updated; no runtime code changed |
|
||||
| 2026-08-08 | Completed Phase 1 legacy AI retirement | Removed the legacy migration and stripping helpers from `main.ts`, retired obsolete settings/default fields and the GPT one-off reset, and removed all legacy fallback reads from `AIUtils.ts`. Current provider profiles, model maps, multimodal default, and token settings remain intact. Unknown persisted keys are not sanitized and may round-trip inertly | Repository-wide residue search found no legacy AI runtime references; `ExcalidrawSettings` and `DEFAULT_SETTINGS` each contain the same 183 keys; production build passed after every code slice with the existing 34 circular dependency warnings and no new warnings; `dist/main.js` is 5,097,728 bytes (8,657 bytes smaller than baseline) |
|
||||
| 2026-08-08 | Closed the Phase 1 validation checkpoint | Manual testing of the legacy AI retirement found no regressions | User confirmed testing completed with no issues |
|
||||
| 2026-08-08 | Consolidated `updateFrontmatterInString()` | Kept the used implementation in `sceneDataUtils.ts` as canonical, added TSDoc describing its intentionally string-based behavior, and removed the identical unreferenced implementation from `utils.ts` | Repository search confirms one definition and one consumer import; `npm run build` passed with the existing 34 circular dependency warnings; bundle size remains 5,097,728 bytes; targeted ESLint reports the existing backlog but no diagnostics on changed lines; `git diff --check` passed |
|
||||
| 2026-08-08 | Consolidated `arrayToMap()` | Extracted the identical implementations to side-effect-free `collectionUtils.ts` with TSDoc, then re-exported the same binding from `utils.ts` and `sceneDataUtils.ts` so all existing import paths and callers remain intact. Directly importing `sceneDataUtils.ts` from `utils.ts` was rejected because it would introduce a cycle through `fileUtils`, `main`, and `utils` | Repository search confirms one implementation; `npm run build` passed with the same 34 circular dependency warnings; bundle size is 5,097,611 bytes, 117 bytes smaller than the preceding step; the new module passes targeted ESLint; `npm run madge` remains unavailable because `madge` is not installed; `git diff --check` passed |
|
||||
| 2026-08-08 | Consolidated `wrapTextAtCharLength()` | Extracted the identical pure wrapping logic to documented `textUtils.ts` and re-exported it from both existing modules, preserving ExcalidrawData and ExcalidrawAutomate imports and behavior | Repository search confirms one implementation; targeted ESLint and `npm run build` passed; the existing 34 circular dependency warnings are unchanged; bundle size decreased by 623 bytes to 5,096,988 bytes |
|
||||
| 2026-08-08 | Consolidated `getLinkParts()` and `LinkParts` | Moved the duplicated parser and type to documented `linkUtils.ts`, preserving both existing value and type import paths through re-exports | Repository search confirms one function and one type definition; targeted ESLint and `npm run build` passed; the existing 34 circular dependency warnings are unchanged; bundle size decreased by 395 bytes to 5,096,593 bytes |
|
||||
| 2026-08-08 | Consolidated `getBinaryFileFromDataURL()` | Moved the duplicated URL-fetch/base64 decoding helper into `fileUtils.ts`, its existing dependency owner, and preserved both old import paths through re-exports. Replaced the loosely typed first `matchAll()` result with equivalent typed `match()` capture handling | Repository search confirms one implementation; targeted ESLint, `npm run build`, `npm run lib`, and `git diff --check` passed; the existing 34 circular dependency warnings are unchanged; bundle size decreased by 405 bytes to 5,096,188 bytes |
|
||||
| 2026-08-08 | Closed the text, link, and binary helper validation checkpoint | Manual testing found no regressions in wrapping, link parsing, or binary image handling | User confirmed the recommended checks completed successfully |
|
||||
| 2026-08-08 | Consolidated `svgToBase64()` | Kept `embeddedAssetUtils.ts` as the canonical owner, added TSDoc for XML entity and UTF-8 handling, and preserved the `utils.ts` import surface through a re-export. Added explicit regex callback parameter types without changing encoding behavior | Repository search confirms one implementation; `npm run build` passed with the unchanged 34 circular dependency warnings; bundle size decreased by 206 bytes to 5,095,988 bytes; targeted ESLint has no diagnostics on the consolidated helper and retains two unrelated backlog errors in `embeddedAssetUtils.ts`; `git diff --check` passed |
|
||||
| 2026-08-08 | Consolidated `getFontDataURL()` | Kept `embeddedAssetUtils.ts` as the canonical owner, added TSDoc for vault resolution, extension mapping, and empty-result behavior, and preserved the `utils.ts` export used by plugin startup | Repository search confirms one implementation; `npm run build` passed with the unchanged 34 circular dependency warnings; bundle size decreased by 609 bytes to 5,095,379 bytes; targeted ESLint has no diagnostics on the consolidated helper and retains the same two unrelated backlog errors in `embeddedAssetUtils.ts`; `git diff --check` passed |
|
||||
| 2026-08-08 | Closed the font helper validation checkpoint | Manual testing found no regressions in vault font loading | User confirmed `getFontDataURL()` works |
|
||||
| 2026-08-08 | Consolidated `cropCanvas()` | Kept `embeddedAssetUtils.ts` as the canonical owner, added TSDoc for source rectangles, output scaling, and intentionally unchanged browser canvas behavior, and preserved the `utils.ts` export | Repository search confirms one implementation; `npm run build` passed with the unchanged 34 circular dependency warnings; bundle size remains 5,095,379 bytes because Rollup already removed the unused duplicate; targeted ESLint has no diagnostics on the consolidated helper and retains the same two unrelated backlog errors in `embeddedAssetUtils.ts`; `git diff --check` passed |
|
||||
| 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
|
||||
|
||||
Do not convert `ExcalidrawView` wholesale into a React component.
|
||||
|
||||
`ExcalidrawView` must remain an Obsidian `TextFileView` because Obsidian owns
|
||||
its file/view lifecycle, leaf identity, serialization hooks, window migration,
|
||||
and teardown. React is a child runtime mounted inside that host. The viable
|
||||
target is therefore a hybrid:
|
||||
|
||||
1. Keep `ExcalidrawView` as a thin Obsidian adapter and stable compatibility
|
||||
facade.
|
||||
2. Move cohesive, non-rendering behavior into view-scoped controllers under
|
||||
`src/view/managers/`.
|
||||
3. Move the current `excalidrawRootElement()` function component and its render
|
||||
wiring into a package-aware component module.
|
||||
4. Use React state only for state that determines rendered UI.
|
||||
5. Move save/reload/unload coordination toward explicit non-React
|
||||
coordinators. Do not replace these flags with React state.
|
||||
|
||||
Two compatibility requirements apply to every phase:
|
||||
|
||||
- The ExcalidrawAutomate API, hook behavior, defaults, signatures, and its
|
||||
access to `ExcalidrawView` must remain intact for scripts and companion
|
||||
plugins.
|
||||
- Extracted modules, exported functions, public methods, compatibility shims,
|
||||
and non-obvious lifecycle code must receive high-signal TSDoc. TSDoc is the
|
||||
TypeScript equivalent intended by “JavaDoc-like documentation” in this plan.
|
||||
|
||||
For `main.ts`, keep the lifecycle ordering visible in the plugin class while
|
||||
moving implementation details into focused managers. A short explicit startup
|
||||
sequence is safer here than a generic dependency-injection or plugin framework.
|
||||
|
||||
## Current-state assessment
|
||||
|
||||
### Size and dependency surface
|
||||
|
||||
At the time of this assessment:
|
||||
|
||||
| File | Lines | Primary responsibilities currently mixed together |
|
||||
| --- | ---: | --- |
|
||||
| `src/core/main.ts` | 2,102 | Entry point, settings migration and persistence, startup choreography, teardown, fonts, styles, post processors, script startup, compatibility facades |
|
||||
| `src/view/ExcalidrawView.ts` | 9,080 | Obsidian view lifecycle, persistence, sync, scene loading, exports, link handling, input handling, embeddables, menus, React root, Excalidraw callbacks |
|
||||
| `src/core/managers/PackageManager.ts` | 235 | Per-window React, ReactDOM, and Excalidraw runtime creation and cleanup |
|
||||
| `rollup.config.mjs` | 294 | Single-bundle construction, runtime injection, compression, CSS, locales, and build-time compatibility workarounds |
|
||||
|
||||
A repository search finds approximately 62 source modules importing the
|
||||
concrete plugin class and 46 importing `ExcalidrawView`. These counts do not
|
||||
include unknown user scripts or companion plugins. Both classes are therefore
|
||||
compatibility surfaces even where TypeScript marks a member as an internal
|
||||
implementation detail.
|
||||
|
||||
The production `dist/main.js` built during this assessment is 5,106,385 bytes.
|
||||
That is only 136,495 bytes, or 2.60%, below a 5 MiB limit. Bundle size
|
||||
must be checked after every refactor. Source-file splitting will improve source
|
||||
architecture but will not create runtime chunks because Rollup uses
|
||||
`inlineDynamicImports: true` and deliberately emits one CommonJS `main.js`.
|
||||
|
||||
### `main.ts`
|
||||
|
||||
The plugin class is doing three different jobs:
|
||||
|
||||
- It is the required Rollup and Obsidian entry point.
|
||||
- It is the ordered composition root for plugin-wide services.
|
||||
- It is a widely used facade over settings, file, event, observer, command,
|
||||
stencil, package, and view operations.
|
||||
|
||||
The first roughly 580 lines also contain pure or mostly pure settings
|
||||
compatibility logic, especially the legacy AI-setting migration. That
|
||||
compatibility has reached its retirement point and can be removed as the first
|
||||
substantial reduction of the entry module.
|
||||
|
||||
Several existing managers already own meaningful behavior, but `main.ts`
|
||||
retains delegate methods such as `openDrawing()`, `isExcalidrawFile()`,
|
||||
`modifyEventHandler()`, `getPackage()`, and observer operations. Those delegates
|
||||
should remain during early refactors. Removing them would turn a structural
|
||||
change into a repository-wide and potentially external API change.
|
||||
|
||||
The ordering inside `onload()` and `onloadOnLayoutReady()` is behavioral:
|
||||
|
||||
- The Markdown post processor must be registered during `onload()`.
|
||||
- `PluginFileManager` must exist early enough for Markdown processing.
|
||||
- Settings and Excalidraw Automate are needed before layout-ready work.
|
||||
- Per-window packages, observers, monkey patches, styles, scripts, fonts, and
|
||||
image cache have a deliberate sequence.
|
||||
- Loading views are switched only after the required runtime is ready.
|
||||
- Some work is intentionally deferred until after real Excalidraw views exist.
|
||||
|
||||
The refactor must preserve this sequence, including which calls are awaited,
|
||||
which are launched without awaiting, and the current error isolation around
|
||||
individual startup steps.
|
||||
|
||||
### Persisted settings and legacy AI compatibility
|
||||
|
||||
There is currently no generic supported-key normalization, and this refactor
|
||||
will not add one. Obsidian stores the plugin's persisted settings in
|
||||
`data.json`; `loadSettings()` merges all loaded top-level properties into
|
||||
`plugin.settings`, and `saveSettings()` can write those properties back.
|
||||
|
||||
Before Phase 1, `ExcalidrawSettings` and `DEFAULT_SETTINGS` contained the same 204
|
||||
top-level keys. This is useful, but an interface is erased by TypeScript and
|
||||
cannot be inspected at runtime. `DEFAULT_SETTINGS` or a generated/explicit key
|
||||
set must be the runtime representation of the specification.
|
||||
After the targeted legacy AI removal, both contain the same 183 keys. No
|
||||
runtime supported-key filter was introduced.
|
||||
|
||||
The legacy AI compatibility path is spread across more than the migration
|
||||
function:
|
||||
|
||||
- migration and stripping helpers in `main.ts`;
|
||||
- legacy properties in `ExcalidrawSettings` and `DEFAULT_SETTINGS`;
|
||||
- fallback reads in `AIUtils.ts`;
|
||||
- a one-off GPT reset during startup.
|
||||
|
||||
The existing `LEGACY_AI_SETTING_KEYS` list also mixes genuinely obsolete keys
|
||||
with `aiDefaultMultimodalModel`, which is still used by the current settings UI
|
||||
and AI model selection. The list must not simply be deleted wholesale. The
|
||||
first implementation must define the current supported AI schema, preserve
|
||||
current profile/model/default fields, and remove only the retired compatibility
|
||||
surface.
|
||||
|
||||
Removing `stripLegacyAISettings()` is safe only after legacy members are also
|
||||
removed from `DEFAULT_SETTINGS`. Otherwise
|
||||
`Object.assign({}, DEFAULT_SETTINGS, loaded)` reintroduces every legacy default
|
||||
into memory and an unfiltered `saveSettings()` persists them again.
|
||||
|
||||
The chosen 2.27.0 policy is deliberately non-destructive: remove confirmed
|
||||
legacy AI members from the current TypeScript settings contract, defaults,
|
||||
migration, and runtime fallback logic, but do not delete arbitrary persisted
|
||||
keys. A stale legacy key already present in `data.json` may continue to
|
||||
round-trip as an inert unknown property. This is preferable to risking deletion
|
||||
of settings introduced by a newer plugin version or stored by another device.
|
||||
|
||||
### `ExcalidrawView`
|
||||
|
||||
The view class currently combines several distinct state domains:
|
||||
|
||||
| State domain | Examples | Appropriate owner |
|
||||
| --- | --- | --- |
|
||||
| Obsidian lifecycle | loaded, unloading, popout unload, window migration, leaf close | `ExcalidrawView` plus a lifecycle helper |
|
||||
| Persistence and synchronization | dirty path, saving, autosaving, force-saving, prevent reload, just loaded | Plain TypeScript coordinator, not React |
|
||||
| Excalidraw runtime | imperative API, scene, files, Excalidraw `AppState` | Excalidraw itself plus view adapters |
|
||||
| Rendered plugin UI | tools panel visibility, theme, fullscreen indicator, preview mode | React component state or a small UI store |
|
||||
| Transient interaction throttles | hover sleep, wheel timeout, text-edit resize guard, imported-image timer | Focused controller or lifecycle-owned timers |
|
||||
|
||||
The current `ViewSemaphores` object mixes all five domains. Its name obscures
|
||||
the fact that some values are lifecycle state, some are mutex-like guards, some
|
||||
are one-shot event suppression, and some are timer state.
|
||||
|
||||
This does not mean the flags can be removed mechanically. They coordinate
|
||||
events from independent owners: Obsidian file events, React/Excalidraw
|
||||
callbacks, autosave timers, sync, view unload, leaf detach monkey patches,
|
||||
embeddable editors, mobile keyboards, and popout teardown. The current file has
|
||||
46 `window.setTimeout()` calls, 22 `window.clearTimeout()` calls, two
|
||||
`ResizeObserver` constructions, and both native and debugging mutation
|
||||
observer paths. Changes to timing, scheduling, or cleanup are behavioral
|
||||
changes even when the resulting code looks simpler.
|
||||
|
||||
The view's public identity must also remain stable. `ExcalidrawAutomate` uses
|
||||
`instanceof ExcalidrawView`, stores it as `targetView`, and exposes it through
|
||||
hooks. Dialogs, managers, utilities, components, scripts, and companion-plugin
|
||||
behavior access many view members directly.
|
||||
|
||||
### Duplicate and triplicate logic
|
||||
|
||||
An initial exact-name scan confirmed several consolidation candidates:
|
||||
|
||||
- `utils.ts` and `sceneDataUtils.ts` both contain helpers including
|
||||
`wrapTextAtCharLength`, `getBinaryFileFromDataURL`, `getLinkParts`,
|
||||
`arrayToMap`, and `updateFrontmatterInString`.
|
||||
- `utils.ts` and `embeddedAssetUtils.ts` both contain helpers including
|
||||
`getFontDataURL`, `svgToBase64`, export-setting helpers, and `cropCanvas`.
|
||||
- `excalidrawAutomateUtils.ts` and `excalidrawViewHelpers.ts` both contain
|
||||
`cloneElement` and `getBoundTextElementId`.
|
||||
|
||||
Some pairs are textually identical; others have already diverged in types,
|
||||
null handling, safe-frontmatter access, or naming. This is evidence for an
|
||||
audit, not permission for bulk deletion. Overload declarations, intentionally
|
||||
isolated build subprojects, domain-specific variants, and compatibility
|
||||
re-exports must not be misclassified as accidental duplication.
|
||||
|
||||
### React and popout windows
|
||||
|
||||
The current root renderer is already a React function component in substance:
|
||||
`excalidrawRootElement()` calls hooks and is mounted with `createRoot()`. It is
|
||||
embedded as a class method and written with `React.createElement()` rather than
|
||||
living in a component module.
|
||||
|
||||
The unusual runtime binding is essential:
|
||||
|
||||
- Rollup embeds React, ReactDOM, and compressed Excalidraw payloads.
|
||||
- `PackageManager` evaluates a fresh package set in each Obsidian window.
|
||||
- `ExcalidrawView.onload()` resolves packages for `ownerWindow`.
|
||||
- The root, hooks, refs, and elements use `this.packages.react` and
|
||||
`this.packages.reactDOM`.
|
||||
- The package is removed when the last relevant leaf in a window closes.
|
||||
|
||||
An extracted component must preserve that binding. A normal module-level
|
||||
`import React from "react"` followed by global `ReactDOM.createRoot()` is not a
|
||||
safe replacement. JSX is possible, but only after proving that every emitted
|
||||
element and hook call is bound to the view's package-managed React instance.
|
||||
|
||||
## Architectural target
|
||||
|
||||
The intended dependency direction is:
|
||||
|
||||
```text
|
||||
Obsidian
|
||||
|
|
||||
v
|
||||
ExcalidrawPlugin (entry point and stable facade)
|
||||
|
|
||||
+--> explicitly ordered plugin managers/services
|
||||
|
|
||||
+--> PackageManager -- one Packages instance per Window
|
||||
|
|
||||
v
|
||||
ExcalidrawView (Obsidian TextFileView and stable facade)
|
||||
|
|
||||
+--> view-scoped controllers
|
||||
|
|
||||
+--> package-aware React root adapter
|
||||
|
|
||||
v
|
||||
Excalidraw and plugin React UI
|
||||
```
|
||||
|
||||
The target is not a strict line-count goal. It is successful when ownership is
|
||||
clear, lifecycle edges are explicit, and behavior can be changed in one
|
||||
subsystem without reading 9,000 lines first.
|
||||
|
||||
Suggested eventual source boundaries are:
|
||||
|
||||
```text
|
||||
src/core/
|
||||
main.ts Obsidian entry, ordered lifecycle, facades
|
||||
managers/
|
||||
PluginSettingsManager.ts Load/save/encryption/default assembly
|
||||
FontManager.ts Per-document fonts and package registration
|
||||
ViewportStyleManager.ts Phone/tablet safe-area behavior
|
||||
|
||||
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
|
||||
ViewPersistenceCoordinator.ts
|
||||
ViewInteractionController.ts
|
||||
ViewLifecycleResources.ts
|
||||
```
|
||||
|
||||
These names are provisional. Create a module only when a specific extraction
|
||||
is being implemented; do not scaffold empty abstractions in advance.
|
||||
|
||||
## Refactoring rules
|
||||
|
||||
Every step in this plan should follow these constraints:
|
||||
|
||||
1. One responsibility per change. Do not combine extraction, renaming, type
|
||||
tightening, timer changes, and behavior changes.
|
||||
2. Keep old public methods as forwarding facades until all internal and known
|
||||
external consumers have a migration path.
|
||||
3. Preserve command IDs, settings keys, frontmatter, scene serialization,
|
||||
hooks, class identity, import paths, and method signatures.
|
||||
4. Preserve startup and teardown order exactly unless a separate change is
|
||||
specifically testing an order change.
|
||||
5. Preserve `await`, fire-and-forget, timeout, debounce, and retry semantics
|
||||
during code moves.
|
||||
6. Preserve the choice of `window`, `ownerWindow`, `mainDocument`, and
|
||||
`ownerDocument`. Do not normalize them during extraction.
|
||||
7. Do not add a state-management library. It would add bundle weight and a
|
||||
second abstraction before the state domains are separated.
|
||||
8. Do not upgrade React, Excalidraw, Rollup, TypeScript, or Obsidian typings in
|
||||
the same change as a structural refactor.
|
||||
9. Do not change the custom Excalidraw fork as part of this source-structure
|
||||
effort unless a later, isolated requirement proves it necessary.
|
||||
10. Run `npm run build` immediately after every code change. Use targeted lint
|
||||
on touched files and run `npm run code` for visibility when appropriate.
|
||||
11. Preserve the complete ExcalidrawAutomate public surface. An internal move
|
||||
must retain forwarding members on `ExcalidrawView` or the plugin wherever
|
||||
scripts or plugins may rely on them.
|
||||
12. Add TSDoc to every new exported class/function and public method. Add
|
||||
module-level documentation and `@remarks` for ordering constraints,
|
||||
ownership, timers, observers, undocumented Obsidian behavior, popout
|
||||
runtime binding, and compatibility decisions. Avoid comments that merely
|
||||
restate the code.
|
||||
13. Search for exact and semantic duplicates before adding a helper. When
|
||||
consolidating existing duplicates, map every import and caller, select one
|
||||
canonical owner, preserve aliases where compatibility requires them, and
|
||||
validate behavior before deleting the alternatives.
|
||||
14. At the end of every refactor step, provide a risk-ranked test
|
||||
recommendation. Identify the behavior most likely to break, give concrete
|
||||
checks in priority order, state whether desktop, mobile, tablet, or popout
|
||||
coverage is warranted, and call out any high-risk path that was not tested.
|
||||
|
||||
## Implementation sequence
|
||||
|
||||
Each numbered sub-step should normally be its own commit or pull request.
|
||||
|
||||
### Phase 0: establish a behavioral baseline
|
||||
|
||||
Before moving runtime code:
|
||||
|
||||
1. Record production `main.js` byte size and the startup breakdown emitted by
|
||||
the existing startup instrumentation.
|
||||
2. Create a repeatable manual smoke-test vault or checklist covering the
|
||||
validation matrix later in this document.
|
||||
3. Record which tests are possible on desktop, mobile, and popout windows in
|
||||
the current development environment.
|
||||
4. Capture known warnings from `npm run build` so a later change can be judged
|
||||
on whether it introduced a new warning.
|
||||
5. For synchronization work, capture debug traces for open, edit, autosave,
|
||||
external modify, reload, leaf close, last-popout-leaf close, and plugin
|
||||
unload. This becomes the characterization oracle for later coordinator work.
|
||||
|
||||
No production behavior should change in this phase.
|
||||
|
||||
### Phase 1: retire legacy AI settings and fallbacks
|
||||
|
||||
This is the recommended first implementation change.
|
||||
|
||||
1. Define and document the current supported AI settings. Keep the profile and
|
||||
model maps, current default model IDs—including
|
||||
`aiDefaultMultimodalModel`—and current token limits.
|
||||
2. Remove `migrateLegacyAISettings()`, its URL/provider/capability helpers, and
|
||||
legacy-only types/constants from `main.ts`.
|
||||
3. Remove retired AI properties from `ExcalidrawSettings` and
|
||||
`DEFAULT_SETTINGS`, and remove fallback reads from `AIUtils.ts`. Search the
|
||||
full repository before deciding that a field is legacy.
|
||||
4. Preserve current fields even if they appear in the old legacy-key list.
|
||||
`aiDefaultMultimodalModel` is a confirmed example.
|
||||
5. Remove `stripLegacyAISettings()` and `LEGACY_AI_SETTING_KEYS` only after the
|
||||
legacy defaults and runtime fallbacks are gone.
|
||||
6. Retire the GPT-specific one-off startup reset if its only purpose is the old
|
||||
AI schema. Treat the unrelated compression reset separately.
|
||||
7. Do not introduce generic supported-key filtering, a settings schema
|
||||
version, or unknown-key deletion. Preserve unrelated persisted properties.
|
||||
8. Add fixtures covering a current profile/model configuration, encrypted
|
||||
current API keys, arbitrary script settings, and raw legacy AI fields.
|
||||
Confirm that legacy fields no longer influence resolved AI configuration
|
||||
and that unrelated properties remain untouched.
|
||||
9. Verify that loading and saving current settings remains behaviorally
|
||||
identical and that current AI defaults are still persisted.
|
||||
10. Add a concise 2.27.0 entry to `src/shared/Dialogs/Messages.ts` if the
|
||||
settings cleanup is observable to users. Do not add new UI copy merely to
|
||||
announce an internal refactor.
|
||||
|
||||
This is a deliberate retirement, not a compatibility migration: users who use
|
||||
ExcalidrawAI have already migrated, and obsolete AI-only values may be dropped.
|
||||
The implementation must nevertheless preserve every field in the current AI
|
||||
schema.
|
||||
|
||||
Implementation completed on 2026-08-08. The retired keys were removed from
|
||||
the TypeScript contract and defaults, and they no longer participate in AI
|
||||
configuration resolution. Existing unknown properties in `data.json` are not
|
||||
deleted; this intentionally preserves the no-sanitizer decision.
|
||||
|
||||
### Phase 2: introduce a settings implementation service
|
||||
|
||||
After Phase 1 is stable:
|
||||
|
||||
1. Create `PluginSettingsManager` to own load, default assembly, remaining
|
||||
migrations, encryption/decryption, save, and external-settings reload.
|
||||
2. Keep `plugin.settings` as the canonical externally visible settings object.
|
||||
3. Keep `ExcalidrawPlugin.loadSettings()`, `saveSettings()`, and
|
||||
`onExternalSettingsChange()` as delegates with their current signatures.
|
||||
4. Keep the one-off startup update and settings-tab readiness in the explicit
|
||||
startup flow until their timing is separately characterized.
|
||||
|
||||
Do not change persisted data format in this phase.
|
||||
|
||||
### Phase 3: audit and consolidate duplicate logic
|
||||
|
||||
Perform the audit in small families rather than a repository-wide rewrite:
|
||||
|
||||
1. Generate an inventory of duplicate exported names and textual clone
|
||||
candidates across `.ts` and `.tsx` files.
|
||||
2. For each candidate, compare implementation, types, null/falsy behavior,
|
||||
side effects, environment assumptions, and every import/call site.
|
||||
3. Classify it as exact duplicate, intentional variant, overload/re-export, or
|
||||
uncertain. Record the classification in the action log.
|
||||
4. Choose the canonical module using the repository placement rules. Scene
|
||||
data helpers belong in a scene-focused module; embedded asset helpers belong
|
||||
in an asset-focused module; lifecycle state does not belong in `utils`.
|
||||
5. Consolidate one helper family per change. Redirect imports first, retain a
|
||||
forwarding export when an import path may be public, then delete the old
|
||||
implementation only after validation.
|
||||
6. Add focused characterization tests for helpers whose copies have diverged.
|
||||
7. Check bundle byte impact: consolidation should normally be neutral or
|
||||
smaller, but Rollup tree shaking and circular imports can produce surprising
|
||||
results.
|
||||
8. Repeat the audit after the major file extractions so refactoring does not
|
||||
create new near-duplicates.
|
||||
|
||||
The initial candidates listed in the assessment are the starting queue, not a
|
||||
pre-approved deletion list.
|
||||
|
||||
### Phase 4: extract plugin-owned window assets
|
||||
|
||||
Do this in separate changes:
|
||||
|
||||
1. Extract font discovery, CJK loading, per-document style installation,
|
||||
per-window Excalidraw font registration, and cleanup into `FontManager`.
|
||||
2. Preserve plugin delegates used by settings and popout-view initialization:
|
||||
`initializeFonts()`, `loadFontFromFile()`, and related accessors.
|
||||
3. Extract phone/tablet footer safe-area style management into a small
|
||||
`ViewportStyleManager` or extend `StylesManager` if its ownership and
|
||||
teardown model match.
|
||||
4. Preserve the current document enumeration and deliberate style-element
|
||||
creation path.
|
||||
|
||||
Font initialization crosses `PackageManager`, open documents, settings, and
|
||||
popout creation, so it should not be combined with package-manager changes.
|
||||
|
||||
### Phase 5: slim `main.ts` while retaining explicit choreography
|
||||
|
||||
Candidates should be extracted one at a time:
|
||||
|
||||
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. 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. 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.
|
||||
|
||||
### Phase 6: extract low-risk `ExcalidrawView` subsystems
|
||||
|
||||
Start with cohesive operations that do not own mount/unmount ordering or save
|
||||
mutual exclusion. For every extraction, retain the current method on
|
||||
`ExcalidrawView` as a delegate.
|
||||
|
||||
Recommended order:
|
||||
|
||||
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.
|
||||
6. `MarkdownImageController`: deletion queue, edit handoff, conversion, and
|
||||
local-source operations.
|
||||
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
|
||||
than importing the concrete view if that can be done without a large rewrite.
|
||||
Avoid inventing a broad `IExcalidrawView` containing most of the current class;
|
||||
that merely duplicates the monolith as an interface.
|
||||
|
||||
### Phase 7: extract the React root without changing rendering syntax
|
||||
|
||||
The first renderer extraction should be a mechanical move, not a state rewrite
|
||||
or JSX conversion.
|
||||
|
||||
1. Define a narrow render-host contract containing runtime packages, refs,
|
||||
callbacks, and render slots required by the root.
|
||||
2. Move the body of `excalidrawRootElement()` to a component module.
|
||||
3. Pass the `Packages` instance resolved for `view.ownerWindow` into that
|
||||
component.
|
||||
4. Inside the component, call hooks and `createElement()` from that package's
|
||||
`react` object.
|
||||
5. Continue creating the root with that package's `reactDOM.createRoot()`.
|
||||
6. Keep API assignment, initialization callbacks, cleanup, and ref handoff
|
||||
behavior identical.
|
||||
7. Test main window, existing popout, moving a leaf to a popout, restored
|
||||
workspace popout, and closing the last popout leaf.
|
||||
|
||||
A safe conceptual shape is:
|
||||
|
||||
```ts
|
||||
const runtime = view.packages;
|
||||
const Root = createExcalidrawRootComponent(renderHost, runtime.react);
|
||||
view.excalidrawRoot = runtime.reactDOM.createRoot(view.contentEl);
|
||||
view.excalidrawRoot.render(runtime.react.createElement(Root));
|
||||
```
|
||||
|
||||
The exact API can differ, but it must not fall back to a module-global React or
|
||||
ReactDOM instance.
|
||||
|
||||
### Phase 8: convert the extracted root to TSX
|
||||
|
||||
Only after Phase 7 is stable should syntax change:
|
||||
|
||||
1. Rename the renderer to `.tsx` and convert a small render fragment at a time.
|
||||
2. Ensure the configured classic JSX transform resolves `React.createElement`
|
||||
to a lexically scoped, package-managed React object.
|
||||
3. Use module-level React imports for types only where possible.
|
||||
4. Do not combine JSX conversion with callback, prop, state, or menu changes.
|
||||
5. Compare behavior and bundle size after each fragment conversion.
|
||||
|
||||
TSX will improve readability, but it is not itself a state-management
|
||||
architecture. The package-runtime constraint matters more than the file
|
||||
extension.
|
||||
|
||||
### Phase 9: separate UI state from operational state
|
||||
|
||||
Introduce React state only where it eliminates imperative UI synchronization.
|
||||
|
||||
1. Define a small `ViewUiSnapshot` for values actually rendered by plugin UI,
|
||||
such as dirty indicator, fullscreen, preview mode, view mode, theme, and
|
||||
selected UI mode.
|
||||
2. If multiple components need the snapshot, implement a tiny plain
|
||||
TypeScript observable store owned by the view.
|
||||
3. Subscribe with the package-managed React instance, potentially through
|
||||
`useSyncExternalStore()` after verifying availability in every loaded
|
||||
runtime.
|
||||
4. Migrate one existing imperative `ToolsPanel.setState()` pathway at a time.
|
||||
5. Avoid copying Excalidraw `AppState` into another store. Read it from the API
|
||||
or consume the relevant callback value.
|
||||
|
||||
Do not put the following in React state:
|
||||
|
||||
- saving, autosaving, or force-saving;
|
||||
- reload suppression;
|
||||
- dirty file identity used during file switching;
|
||||
- unload or popout-unload state;
|
||||
- timers, observers, or loader ownership;
|
||||
- data needed after the React root has started unmounting.
|
||||
|
||||
React updates are asynchronous and the component can disappear while Obsidian
|
||||
still requires a final save. Those concerns must remain available independently
|
||||
of the mounted tree.
|
||||
|
||||
### Phase 10: replace `ViewSemaphores` incrementally
|
||||
|
||||
Do not replace the entire object in one change. First classify and encapsulate
|
||||
one cluster while preserving the existing storage and timing.
|
||||
|
||||
Suggested clusters:
|
||||
|
||||
| Coordinator | Initial fields/behavior |
|
||||
| --- | --- |
|
||||
| `ViewPersistenceCoordinator` | `saving`, `autosaving`, `forceSaving`, `dirty`, save wait behavior |
|
||||
| `ViewReloadGuard` | `preventReload`, `embeddableIsEditingSelf`, their reset timers |
|
||||
| `ViewLoadState` | `justLoaded`, `preventAutozoom`, initial `onChange` suppression |
|
||||
| `ViewLifecycleState` | `viewloaded`, `viewunload`, `popoutUnload`, `scriptsReady` |
|
||||
| `ViewInteractionThrottle` | `hoverSleep`, `wheelTimeout`, `isEditingText`, imported-image guard |
|
||||
|
||||
For each cluster:
|
||||
|
||||
1. Add named query and transition methods while still using the current fields.
|
||||
2. Replace direct writes in one call path at a time.
|
||||
3. Add debug assertions for impossible transitions without changing production
|
||||
recovery behavior.
|
||||
4. Compare characterization traces.
|
||||
5. Only then move storage into the coordinator.
|
||||
6. Keep compatibility accessors for known external reads or writes until their
|
||||
consumers are migrated.
|
||||
|
||||
Potential future improvements such as a single-flight save promise, abortable
|
||||
waits, or replacing polling loops are behavioral projects. They should follow,
|
||||
not accompany, the structural extraction. Existing watchdogs and sleeps must
|
||||
remain until device and Obsidian behavior has been tested against a replacement.
|
||||
|
||||
### Phase 11: narrow dependencies and clean up compatibility facades
|
||||
|
||||
After the major boundaries are stable:
|
||||
|
||||
1. Replace concrete plugin/view imports with small type-only capability
|
||||
contracts in newly extracted modules where this materially reduces cycles.
|
||||
2. Move repeated shared shapes to `src/types/`; do not create duplicate local
|
||||
aliases.
|
||||
3. Use deprecation comments and forwarding accessors before removing a facade
|
||||
used by scripts or companion plugins.
|
||||
4. Run `npm run madge` once its tooling is available and address new cycles
|
||||
introduced by the refactor. The command was not available in the installed
|
||||
dependencies during this assessment.
|
||||
5. Perform naming cleanup only in a dedicated compatibility-aware pass.
|
||||
|
||||
## Validation matrix
|
||||
|
||||
`npm run build` is mandatory after every code modification. In addition, each
|
||||
phase should select the relevant manual cases below. Every step's handoff must
|
||||
turn that selection into a risk-ranked test recommendation: lead with the
|
||||
highest-probability or highest-impact failure, name the required platforms and
|
||||
window modes, and distinguish automated validation from untested manual risk.
|
||||
|
||||
### Build and static checks
|
||||
|
||||
- Production build completes with no new errors or warnings.
|
||||
- Touched files pass targeted ESLint diagnostics.
|
||||
- `npm run code` is reviewed for newly introduced findings despite the existing
|
||||
repository backlog.
|
||||
- `npm run lib` is run when the public/library API is touched.
|
||||
- When a change can affect ExcalidrawAutomate, compare the generated library
|
||||
declarations/API docs with the baseline and run `npm run doc` as applicable.
|
||||
- `npm run madge` is run after structural import changes once available.
|
||||
- `dist/main.js` stays below 5 MiB and its byte delta is recorded.
|
||||
- No generated `dist/` or `lib/` file is edited manually.
|
||||
|
||||
### Startup and lifecycle
|
||||
|
||||
- Fresh plugin enable with no open drawing.
|
||||
- Restored workspace with one or multiple drawings.
|
||||
- Main-window view creation before and after plugin readiness.
|
||||
- Existing popout, restored popout, and leaf moved between windows.
|
||||
- Close normal leaf, close last popout leaf, close popout window, disable
|
||||
plugin, and reload plugin.
|
||||
- Confirm package cleanup does not break another leaf in the same window.
|
||||
- Confirm startup breakdown has no material regression.
|
||||
|
||||
### Persistence and synchronization
|
||||
|
||||
- Manual save and command-triggered force save.
|
||||
- Desktop and mobile autosave intervals.
|
||||
- Close while clean, dirty, already saving, and editing text.
|
||||
- External file modification and sync-style reload.
|
||||
- Same drawing open as Excalidraw and Markdown.
|
||||
- Same drawing open in multiple leaves/windows.
|
||||
- Embeddable or Markdown-image editor updates its owning drawing.
|
||||
- Initial `onChange` does not cause a false save or sync ping-pong.
|
||||
- Container-size update after load does not mark the scene incorrectly.
|
||||
|
||||
### Interaction and UI
|
||||
|
||||
- Desktop, phone, and tablet layouts.
|
||||
- Mobile on-screen keyboard open/close during text editing.
|
||||
- Resize, sliding panes, hover editor, canvas node, fullscreen, and popout.
|
||||
- Hover preview while scrolling/zooming.
|
||||
- Link click modifier combinations and view mode.
|
||||
- Tools panel, selected-element actions, embeddable menu, welcome screen,
|
||||
context menu, and custom actions.
|
||||
- Theme, canvas color, grid, handedness, UI mode, pinch zoom, and wheel zoom.
|
||||
|
||||
### Data and integrations
|
||||
|
||||
- Large drawing and many embedded files.
|
||||
- SVG, PNG, clipboard, PDF, and `.excalidraw` export.
|
||||
- Local images, Markdown images, PDFs, LaTeX, Mermaid, web embeds, and YouTube.
|
||||
- Excalidraw Automate calls and all view hooks.
|
||||
- Existing ExcalidrawAutomate function/property names, signatures, defaults,
|
||||
return values, hook timing, `targetView` behavior, and
|
||||
`instanceof ExcalidrawView` behavior remain unchanged.
|
||||
- Script engine startup, pinned scripts, and install-codeblock flow.
|
||||
- ExcaliBrain or another companion integration if available.
|
||||
|
||||
## Per-change review checklist
|
||||
|
||||
Before merging any refactor step, answer all of the following:
|
||||
|
||||
- What ownership boundary became clearer?
|
||||
- Which public methods and fields were preserved as facades?
|
||||
- Were all repository references searched before and after the change?
|
||||
- Did any `await`, timer, retry count, observer target, event target, or cleanup
|
||||
order change?
|
||||
- Did any use of `window`/`ownerWindow` or `mainDocument`/`ownerDocument`
|
||||
change?
|
||||
- Which manual lifecycle cases were exercised?
|
||||
- Did the production build pass, and what was the `main.js` byte delta?
|
||||
- Were any new warnings or circular dependencies introduced?
|
||||
- Were duplicate-name and semantic-clone searches performed before adding a
|
||||
new helper, and were intentional variants kept distinct?
|
||||
- Do all new modules, exports, public methods, compatibility shims, and
|
||||
non-obvious lifecycle constraints have useful TSDoc?
|
||||
- If the view or plugin facade moved, was ExcalidrawAutomate API and hook
|
||||
compatibility verified with library declarations and representative scripts?
|
||||
- What is the highest-risk regression, which concrete tests are recommended in
|
||||
priority order, and which devices, platforms, or popout configurations are
|
||||
necessary for this particular change?
|
||||
- Is the change independently reversible?
|
||||
|
||||
## Recommended first three implementation changes
|
||||
|
||||
1. Retire the complete legacy AI migration, fields, defaults, reset, and
|
||||
`AIUtils` fallback path without sanitizing unrelated persisted keys. This is
|
||||
the first 2.27.0 implementation target.
|
||||
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. Completed: extracted `ViewExportManager` while keeping all current
|
||||
`ExcalidrawView` export methods as delegates. This establishes the
|
||||
view-controller pattern away from lifecycle and synchronization.
|
||||
|
||||
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
|
||||
checkpoints rather than a promise to execute every proposed module unchanged.
|
||||
@@ -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="<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>"></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="<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>"></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="<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>"></svg>`);
|
||||
|
||||
await ea.addImage(0,0,file);
|
||||
await ea.addElementsToView(true,true);
|
||||
|
||||
leaf.setViewState({
|
||||
type: "diagram-edit",
|
||||
state: {
|
||||
file: filepath
|
||||
}
|
||||
});
|
||||
|
||||
```
|
||||
@@ -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="<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>"></svg>`);
|
||||
|
||||
await ea.addImage(0,0,file);
|
||||
await ea.addElementsToView(true,true);
|
||||
|
||||
leaf.setViewState({
|
||||
type: "diagram-edit",
|
||||
state: {
|
||||
file: filepath
|
||||
}
|
||||
});
|
||||
@@ -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,14 +8,14 @@ The following parameters can be set in 'Voronoi Settings' window pop-up once the
|
||||
- Grouping (default: checked)
|
||||
|
||||
Setting parameters could be set back to default values by click on button 'Default'.
|
||||
Check info button for howto help during applying the script.
|
||||
|
||||
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
|
||||
|
||||
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
|
||||
|
||||
```js*/
|
||||
|
||||
|
||||
// ExcalidrawAutomate: Voronoi Diagram Generator
|
||||
ea.clear();
|
||||
|
||||
const DEFAULTS = {
|
||||
@@ -27,45 +27,88 @@ const DEFAULTS = {
|
||||
|
||||
let config = ea.getScriptSettings() || { ...DEFAULTS };
|
||||
|
||||
// --- UI SETTINGS MODAL ---
|
||||
async function openSettings() {
|
||||
return new Promise((resolve) => {
|
||||
const modal = new ea.obsidian.Modal(app);
|
||||
modal.contentEl.style.frameWidth = "20px"; // External clearance of the entire window
|
||||
modal.contentEl.createEl("h2", { text: "Voronoi Settings" });
|
||||
modal.contentEl.style.padding = "20px";
|
||||
|
||||
// Header container with Title and Info Button
|
||||
const headerContainer = modal.contentEl.createDiv();
|
||||
headerContainer.style.display = "flex";
|
||||
headerContainer.style.justifyContent = "space-between";
|
||||
headerContainer.style.alignItems = "center";
|
||||
headerContainer.style.marginBottom = "20px";
|
||||
|
||||
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
|
||||
|
||||
// Info button using Obsidian's native icon
|
||||
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
|
||||
btnInfo.setAttribute("aria-label", "Information & Help");
|
||||
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
|
||||
|
||||
// Info modal content on click
|
||||
btnInfo.onclick = () => {
|
||||
const infoModal = new ea.obsidian.Modal(app);
|
||||
infoModal.contentEl.style.padding = "20px";
|
||||
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
|
||||
|
||||
// Native Obsidian Icon as HTML string
|
||||
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
|
||||
|
||||
const p = infoModal.contentEl.createEl("p");
|
||||
p.innerHTML = `
|
||||
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
|
||||
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
|
||||
<div line-height: 1.4;">
|
||||
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
|
||||
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
|
||||
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
|
||||
- <b>Frame width:</b> Spacing around the diagram.<br>
|
||||
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
|
||||
- <b>Stroke width:</b> Line thickness.<br>
|
||||
- <b>Grouping:</b> Group generated cells together.<br>
|
||||
</div>
|
||||
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
|
||||
</div><br>
|
||||
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
|
||||
</span>
|
||||
`;
|
||||
infoModal.open();
|
||||
};
|
||||
|
||||
const inputs = {};
|
||||
|
||||
// Support function with better layout
|
||||
// Helper function to create input rows
|
||||
const createInput = (label, key, type = "number") => {
|
||||
const container = modal.contentEl.createDiv();
|
||||
container.style.marginBottom = "15px"; // Distance between input blocks
|
||||
container.style.marginBottom = "15px";
|
||||
|
||||
container.createEl("label", { text: label, cls: "setting-item-name" });
|
||||
container.createEl("label", { text: label });
|
||||
const input = container.createEl("input", { type: type });
|
||||
input.style.display = "block";
|
||||
input.style.marginTop = "5px"; // Distance between label and input
|
||||
input.style.marginTop = "5px";
|
||||
input.value = config[key];
|
||||
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
|
||||
inputs[key] = input;
|
||||
};
|
||||
|
||||
createInput("Framing width:", "frameWidth");
|
||||
createInput("Frame width:", "frameWidth");
|
||||
createInput("Roughness (0-3):", "roughness");
|
||||
createInput("Stroke width:", "strokeWidth");
|
||||
|
||||
// Checkbox section
|
||||
const checkContainer = modal.contentEl.createDiv();
|
||||
checkContainer.style.marginBottom = "25px";
|
||||
const label = checkContainer.createEl("label", { text: "Grouping: " });
|
||||
checkContainer.createEl("label", { text: "Grouping: " });
|
||||
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
|
||||
inputs.groupVoronoi.checked = config.groupVoronoi;
|
||||
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
|
||||
|
||||
// Button section
|
||||
// Button container
|
||||
const btnContainer = modal.contentEl.createDiv();
|
||||
btnContainer.style.display = "flex";
|
||||
btnContainer.style.gap = "10px"; // Distance between buttons
|
||||
btnContainer.style.justifyContent = "flex-end"; // Buttons to the right
|
||||
btnContainer.style.gap = "10px";
|
||||
btnContainer.style.justifyContent = "flex-end";
|
||||
|
||||
const btnDefault = btnContainer.createEl("button", { text: "Default" });
|
||||
const btnOk = btnContainer.createEl("button", { text: "OK" });
|
||||
@@ -76,7 +119,7 @@ async function openSettings() {
|
||||
inputs.roughness.value = config.roughness;
|
||||
inputs.strokeWidth.value = config.strokeWidth;
|
||||
inputs.groupVoronoi.checked = config.groupVoronoi;
|
||||
new Notice("Values reset to default");
|
||||
new Notice("Settings reset to default");
|
||||
};
|
||||
|
||||
btnOk.onclick = () => {
|
||||
@@ -89,30 +132,42 @@ async function openSettings() {
|
||||
});
|
||||
}
|
||||
|
||||
// Waiting for dialog window
|
||||
await openSettings();
|
||||
// Wait for user to configure settings
|
||||
const proceed = await openSettings();
|
||||
if (!proceed) return;
|
||||
|
||||
// --- The actual algorithm ---
|
||||
// --- ALGORITHM & EXECUTION ---
|
||||
const els = ea.getViewSelectedElements();
|
||||
|
||||
if (els.length < 2) {
|
||||
new Notice("Please select at least two items!");
|
||||
return;
|
||||
}
|
||||
|
||||
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
|
||||
if (seeds.length < 2) { new Notice("Please select circles"); return; }
|
||||
|
||||
if (seeds.length < 2) {
|
||||
new Notice("Please select at least two items!");
|
||||
return;
|
||||
}
|
||||
|
||||
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
|
||||
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
|
||||
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
|
||||
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
|
||||
|
||||
const bbox = [{x:minX, y:minY}, {x:maxX, y:minY}, {x:maxX, y:maxY}, {x:minX, y:maxY}];
|
||||
const bbox = [
|
||||
{ x: minX, y: minY },
|
||||
{ x: maxX, y: minY },
|
||||
{ x: maxX, y: maxY },
|
||||
{ x: minX, y: maxY }
|
||||
];
|
||||
|
||||
function clipPolygon(poly, p1, p2) {
|
||||
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
|
||||
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
|
||||
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
|
||||
|
||||
const intersect = (a, b) => {
|
||||
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
|
||||
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
|
||||
@@ -120,21 +175,28 @@ function clipPolygon(poly, p1, p2) {
|
||||
const t = -num / den;
|
||||
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
|
||||
};
|
||||
|
||||
const result = [];
|
||||
for (let i = 0; i < poly.length; i++) {
|
||||
const cur = poly[i];
|
||||
const prev = poly[(i - 1 + poly.length) % poly.length];
|
||||
const curIn = isInside(cur);
|
||||
const prevIn = isInside(prev);
|
||||
if (curIn !== prevIn) { const ix = intersect(prev, cur); if (ix) result.push(ix); }
|
||||
|
||||
if (curIn !== prevIn) {
|
||||
const ix = intersect(prev, cur);
|
||||
if (ix) result.push(ix);
|
||||
}
|
||||
if (curIn) result.push(cur);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const polygons = seeds.map((_, i) => {
|
||||
const polygons = seeds.map((s, i) => {
|
||||
let poly = [...bbox];
|
||||
seeds.forEach((_, j) => { if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]); });
|
||||
seeds.forEach((_, j) => {
|
||||
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
|
||||
});
|
||||
return poly;
|
||||
});
|
||||
|
||||
@@ -143,6 +205,7 @@ ea.style.strokeWidth = config.strokeWidth;
|
||||
ea.style.backgroundColor = "transparent";
|
||||
|
||||
const ids = [];
|
||||
|
||||
for (const poly of polygons) {
|
||||
if (poly.length < 3) continue;
|
||||
const points = poly.map(p => [p.x, p.y]);
|
||||
@@ -150,6 +213,13 @@ for (const poly of polygons) {
|
||||
ids.push(ea.addLine(points));
|
||||
}
|
||||
|
||||
if (config.groupVoronoi && ids.length > 0) ea.addToGroup(ids);
|
||||
if (config.groupVoronoi && ids.length > 0) {
|
||||
ea.addToGroup(ids);
|
||||
}
|
||||
|
||||
await ea.addElementsToView(false, false);
|
||||
new Notice("Voronoi diagram created!");
|
||||
|
||||
// Clear selection so nothing remains selected on the canvas
|
||||
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
|
||||
|
||||
new Notice("Voronoi diagram created!");
|
||||
@@ -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
|
||||
@@ -705,10 +697,10 @@
|
||||
},
|
||||
{
|
||||
"fname": "VoronoiDiagramGenerator.md",
|
||||
"mtime": 1785564296587
|
||||
"mtime": 1785733307861
|
||||
},
|
||||
{
|
||||
"fname": "VoronoiDiagramGenerator.svg",
|
||||
"mtime": 1785564296587
|
||||
}
|
||||
]
|
||||
]
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.26.0-rc.2",
|
||||
"version": "2.26.4",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.25.3",
|
||||
"version": "2.26.4",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+9
-8
@@ -13,14 +13,14 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.116",
|
||||
"@zsviczian/excalidraw": "0.18.118",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
"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",
|
||||
@@ -5274,9 +5274,10 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/excalidraw": {
|
||||
"version": "0.18.116",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.116.tgz",
|
||||
"integrity": "sha512-cq/jChIEDdmWt/B1ZQUauMqi7wj/vNda0TZjqQ89ju9n8mLrvh9J7f3OZJQ+m/BYOesd1RrY8Nm4SZfBj37Ajg==",
|
||||
"version": "0.18.118",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.118.tgz",
|
||||
"integrity": "sha512-YhMaN3lQ3NjqMGHUSfIt9jipHZ+5sKdggWQPavxarWu7IjiQW7WFwBY9wucgBOBD+pzoya+1cXd22alDjHiDow==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@braintree/sanitize-url": "6.0.2",
|
||||
"@codemirror/commands": "^6.0.0",
|
||||
@@ -10238,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",
|
||||
|
||||
+3
-3
@@ -30,14 +30,14 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.116",
|
||||
"@zsviczian/excalidraw": "0.18.118",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
"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,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
-810
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
+16
-171
@@ -111,8 +111,6 @@ export interface ExcalidrawSettings {
|
||||
compress: boolean;
|
||||
decompressForMDView: boolean;
|
||||
onceOffCompressFlagReset: boolean; //used to reset compress to true in 2.2.0
|
||||
onceOffGPTVersionReset: boolean; //used to reset GPT version in 2.2.11
|
||||
autosave: boolean;
|
||||
autosaveIntervalDesktop: number;
|
||||
autosaveIntervalMobile: number;
|
||||
drawingFilenamePrefix: string;
|
||||
@@ -270,32 +268,12 @@ export interface ExcalidrawSettings {
|
||||
aiVerboseLogging: boolean;
|
||||
aiProviderProfiles: Record<string, AIProviderProfile>;
|
||||
aiTextModelConfigs: Record<string, AIModelConfig>;
|
||||
aiVisionModelConfigs: Record<string, AIModelConfig>;
|
||||
aiImageModelConfigs: Record<string, AIImageModelConfig>;
|
||||
aiProvider: "openai" | "anthropic" | "google" | "xai" | "openai-compatible";
|
||||
aiAPIKey: string;
|
||||
aiBaseURL: string;
|
||||
aiTextEndpoint: string;
|
||||
aiImageGenerationEndpoint: string;
|
||||
aiImageEditsEndpoint: string;
|
||||
aiImageVariationsEndpoint: string;
|
||||
aiDefaultTextModel: string;
|
||||
aiDefaultMultimodalModel: string;
|
||||
aiDefaultVisionModel: string;
|
||||
aiDefaultImageGenerationModel: string;
|
||||
aiImageModelCapabilities: Record<string, AIImageModelCapability>;
|
||||
aiDefaultMaxOutgoingTokens: number;
|
||||
aiDefaultMaxResponseTokens: number;
|
||||
aiDefaultMaxTokens: number; //legacy migration source, do not use directly
|
||||
openAIAPIToken: string;
|
||||
openAIDefaultTextModel: string;
|
||||
openAIDefaultTextModelMaxTokens: number;
|
||||
openAIDefaultVisionModel: string;
|
||||
openAIDefaultImageGenerationModel: string;
|
||||
openAIURL: string;
|
||||
openAIImageGenerationURL: string;
|
||||
openAIImageEditsURL: string;
|
||||
openAIImageVariationURL: string;
|
||||
modifierKeyConfig: {
|
||||
Mac: Record<ModifierSetType, ModifierKeySet>;
|
||||
Win: Record<ModifierSetType, ModifierKeySet>;
|
||||
@@ -394,21 +372,6 @@ const KNOWN_AI_IMAGE_MODEL_CAPABILITIES: Record<
|
||||
},
|
||||
};
|
||||
|
||||
const cloneKnownAIImageModelCapabilities = () =>
|
||||
Object.fromEntries(
|
||||
Object.entries(KNOWN_AI_IMAGE_MODEL_CAPABILITIES).map(
|
||||
([model, capability]) => [
|
||||
model,
|
||||
{
|
||||
supportedSizes: [...capability.supportedSizes],
|
||||
supportsPromptImageTransforms:
|
||||
capability.supportsPromptImageTransforms,
|
||||
supportsMaskImageEdits: capability.supportsMaskImageEdits,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
export const KNOWN_AI_PROVIDER_PROFILES: Record<string, AIProviderProfile> = {
|
||||
OpenAI: {
|
||||
provider: "openai",
|
||||
@@ -472,14 +435,6 @@ export const KNOWN_AI_TEXT_MODEL_CONFIGS: Record<string, AIModelConfig> = {
|
||||
},
|
||||
};
|
||||
|
||||
export const KNOWN_AI_VISION_MODEL_CONFIGS: Record<string, AIModelConfig> =
|
||||
Object.fromEntries(
|
||||
Object.entries(KNOWN_AI_TEXT_MODEL_CONFIGS).map(([modelId, config]) => [
|
||||
modelId,
|
||||
{ ...config },
|
||||
]),
|
||||
);
|
||||
|
||||
export const KNOWN_AI_IMAGE_MODEL_CONFIGS: Record<string, AIImageModelConfig> =
|
||||
{
|
||||
"dall-e-2": {
|
||||
@@ -602,8 +557,6 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
compress: true,
|
||||
decompressForMDView: false,
|
||||
onceOffCompressFlagReset: false,
|
||||
onceOffGPTVersionReset: false,
|
||||
autosave: true,
|
||||
autosaveIntervalDesktop: 60000,
|
||||
autosaveIntervalMobile: 30000,
|
||||
drawingFilenamePrefix: "Drawing ",
|
||||
@@ -807,32 +760,12 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
aiVerboseLogging: false,
|
||||
aiProviderProfiles: cloneKnownAIProviderProfiles(),
|
||||
aiTextModelConfigs: cloneModelConfigs(KNOWN_AI_TEXT_MODEL_CONFIGS),
|
||||
aiVisionModelConfigs: cloneModelConfigs(KNOWN_AI_VISION_MODEL_CONFIGS),
|
||||
aiImageModelConfigs: cloneModelConfigs(KNOWN_AI_IMAGE_MODEL_CONFIGS),
|
||||
aiProvider: "openai",
|
||||
aiAPIKey: "",
|
||||
aiBaseURL: "",
|
||||
aiTextEndpoint: "",
|
||||
aiImageGenerationEndpoint: "",
|
||||
aiImageEditsEndpoint: "",
|
||||
aiImageVariationsEndpoint: "",
|
||||
aiDefaultTextModel: "gpt-5-mini",
|
||||
aiDefaultMultimodalModel: "gpt-5-mini",
|
||||
aiDefaultVisionModel: "gpt-5-mini",
|
||||
aiDefaultImageGenerationModel: "gpt-image-1",
|
||||
aiImageModelCapabilities: cloneKnownAIImageModelCapabilities(),
|
||||
aiDefaultMaxOutgoingTokens: 0,
|
||||
aiDefaultMaxResponseTokens: 0,
|
||||
aiDefaultMaxTokens: 0,
|
||||
openAIAPIToken: "",
|
||||
openAIDefaultTextModel: "gpt-5-mini",
|
||||
openAIDefaultTextModelMaxTokens: 4096,
|
||||
openAIDefaultVisionModel: "gpt-5-mini",
|
||||
openAIDefaultImageGenerationModel: "gpt-image-1",
|
||||
openAIURL: URLs.API_OPENAI_COM_V1_CHAT_COMPLETIONS,
|
||||
openAIImageGenerationURL: URLs.API_OPENAI_COM_V1_IMAGES_GENERATIONS,
|
||||
openAIImageEditsURL: URLs.API_OPENAI_COM_V1_IMAGES_EDITS,
|
||||
openAIImageVariationURL: URLs.API_OPENAI_COM_V1_IMAGES_VARIATIONS,
|
||||
modifierKeyConfig: {
|
||||
Mac: {
|
||||
LocalFileDragAction: {
|
||||
@@ -1147,10 +1080,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
private requestReloadDrawings: boolean = false;
|
||||
private requestUpdatePinnedPens: boolean = false;
|
||||
private requestUpdateDynamicStyling: boolean = false;
|
||||
private settingsDirty: boolean = false;
|
||||
private settingsRevision: number = 0;
|
||||
private isPersistingSettings: boolean = false;
|
||||
private settingsFocusoutHandler: ((event: FocusEvent) => void) | null = null;
|
||||
private settingsPersistenceChain: Promise<void> = Promise.resolve();
|
||||
private hotkeyEditor: HotkeyEditor;
|
||||
private fontPickers: FontPickerComponent[] = [];
|
||||
//private reloadMathJax: boolean = false;
|
||||
@@ -1182,11 +1112,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
return [];
|
||||
}
|
||||
|
||||
private markSettingsDirty() {
|
||||
this.settingsDirty = true;
|
||||
this.settingsRevision += 1;
|
||||
}
|
||||
|
||||
private normalizeSettingsBeforeSave() {
|
||||
this.plugin.settings.scriptFolderPath = normalizePath(
|
||||
this.plugin.settings.scriptFolderPath,
|
||||
@@ -1273,70 +1198,16 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
updateWarning();
|
||||
}
|
||||
|
||||
private async persistDirtySettings() {
|
||||
if (!this.settingsDirty || this.isPersistingSettings) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isPersistingSettings = true;
|
||||
try {
|
||||
while (this.settingsDirty) {
|
||||
const revisionToSave = this.settingsRevision;
|
||||
this.normalizeSettingsBeforeSave();
|
||||
await this.plugin.saveSettings();
|
||||
if (this.settingsRevision === revisionToSave) {
|
||||
this.settingsDirty = false;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.isPersistingSettings = false;
|
||||
}
|
||||
}
|
||||
|
||||
private detachSettingsFocusoutHandler() {
|
||||
if (!this.settingsFocusoutHandler) {
|
||||
return;
|
||||
}
|
||||
this.containerEl.removeEventListener(
|
||||
"focusout",
|
||||
this.settingsFocusoutHandler,
|
||||
);
|
||||
this.settingsFocusoutHandler = null;
|
||||
}
|
||||
|
||||
private hasPendingActions(): boolean {
|
||||
return (
|
||||
this.requestUpdatePinnedPens ||
|
||||
this.requestUpdateDynamicStyling ||
|
||||
this.requestReloadDrawings ||
|
||||
this.requestEmbedUpdate
|
||||
);
|
||||
}
|
||||
|
||||
private attachSettingsFocusoutHandler() {
|
||||
this.detachSettingsFocusoutHandler();
|
||||
this.settingsFocusoutHandler = (event: FocusEvent) => {
|
||||
window.setTimeout(() => {
|
||||
if (!this.containerEl?.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextFocusTarget =
|
||||
(event.relatedTarget as Node | null) ??
|
||||
this.containerEl.ownerDocument.activeElement;
|
||||
if (nextFocusTarget && this.containerEl.contains(nextFocusTarget)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Execute pending actions if settings are dirty or if there are pending actions
|
||||
if (this.settingsDirty || this.hasPendingActions()) {
|
||||
void this.persistDirtySettings().then(() =>
|
||||
this.applyPendingActions(),
|
||||
);
|
||||
}
|
||||
}, 0);
|
||||
private persistSettingsAndApplyPendingActions() {
|
||||
const persistAndApply = async () => {
|
||||
this.normalizeSettingsBeforeSave();
|
||||
await this.plugin.saveSettings();
|
||||
await this.applyPendingActions();
|
||||
};
|
||||
this.containerEl.addEventListener("focusout", this.settingsFocusoutHandler);
|
||||
// Keep queuing updates even if an earlier save failed.
|
||||
this.settingsPersistenceChain = this.settingsPersistenceChain
|
||||
.catch((): void => undefined)
|
||||
.then(persistAndApply);
|
||||
}
|
||||
|
||||
private async applyPendingActions() {
|
||||
@@ -1374,14 +1245,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}
|
||||
|
||||
applySettingsUpdate(requestReloadDrawings: boolean = false) {
|
||||
this.markSettingsDirty();
|
||||
if (requestReloadDrawings) {
|
||||
this.requestReloadDrawings = true;
|
||||
}
|
||||
this.persistSettingsAndApplyPendingActions();
|
||||
}
|
||||
|
||||
hide() {
|
||||
this.detachSettingsFocusoutHandler();
|
||||
this.destroyFontPickers();
|
||||
if (this.plugin.settings.overrideObsidianFontSize) {
|
||||
setStyle(mainDocument.documentElement, { fontSize: "" });
|
||||
@@ -1395,15 +1265,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
setRootElementSize();
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
void (await this.persistDirtySettings());
|
||||
void (await this.applyPendingActions());
|
||||
this.hotkeyEditor.unload();
|
||||
if (this.hotkeyEditor.isDirty) {
|
||||
this.plugin.registerHotkeyOverrides();
|
||||
}
|
||||
this.plugin.scriptEngine.updateScriptPath();
|
||||
})();
|
||||
this.hotkeyEditor.unload();
|
||||
if (this.hotkeyEditor.isDirty) {
|
||||
this.plugin.registerHotkeyOverrides();
|
||||
}
|
||||
this.plugin.scriptEngine.updateScriptPath();
|
||||
/* if(this.reloadMathJax) {
|
||||
this.plugin.loadMathJax();
|
||||
}*/
|
||||
@@ -1413,14 +1279,12 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
let detailsEl: HTMLElement;
|
||||
|
||||
//await this.plugin.loadSettings(); //in case sync loaded changed settings in the background
|
||||
this.settingsDirty = false;
|
||||
this.requestEmbedUpdate = false;
|
||||
this.requestReloadDrawings = false;
|
||||
this.destroyFontPickers();
|
||||
const { containerEl } = this;
|
||||
containerEl.addClass("excalidraw-settings");
|
||||
this.containerEl.empty();
|
||||
this.attachSettingsFocusoutHandler();
|
||||
|
||||
// ------------------------------------------------
|
||||
// Search and Settings to Clipboard
|
||||
@@ -2157,9 +2021,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
Object.keys(this.plugin.settings.aiProviderProfiles ?? {})[0] || "OpenAI";
|
||||
let selectedTextModelConfig =
|
||||
this.plugin.settings.aiDefaultTextModel?.trim() ||
|
||||
this.plugin.settings.aiDefaultVisionModel?.trim() ||
|
||||
Object.keys(this.plugin.settings.aiTextModelConfigs ?? {})[0] ||
|
||||
Object.keys(this.plugin.settings.aiVisionModelConfigs ?? {})[0] ||
|
||||
"gpt-5-mini";
|
||||
let selectedImageModelConfig =
|
||||
this.plugin.settings.aiDefaultImageGenerationModel?.trim() ||
|
||||
@@ -2184,23 +2046,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
return this.plugin.settings.aiTextModelConfigs;
|
||||
}
|
||||
|
||||
if (
|
||||
this.plugin.settings.aiVisionModelConfigs &&
|
||||
Object.keys(this.plugin.settings.aiVisionModelConfigs).length > 0
|
||||
) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(this.plugin.settings.aiVisionModelConfigs).map(
|
||||
([modelId, config]) => [
|
||||
modelId,
|
||||
{
|
||||
...config,
|
||||
multimodalSupport: config.multimodalSupport ?? true,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return cloneModelConfigs(KNOWN_AI_TEXT_MODEL_CONFIGS);
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -17,35 +17,55 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
|
||||
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
|
||||
`,
|
||||
"2.26.0": `
|
||||
"2.27.0": `
|
||||
## Maintenance
|
||||
- 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": `
|
||||
## Fixed
|
||||
- Markdown-image edits could be lost in some usage scenarios, 2.26.3 did not provide a broad enough fix. [#2865](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2865)
|
||||
|
||||
`,
|
||||
"2.26.3": `
|
||||
## Fixed
|
||||
- Editing one Markdown image and immediately selecting another to edit could silently drop the first image's contents, both from memory and from the note on disk. Reported on the [Sketch Your Mind community](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}/t/excalidraw-2-26-0/7791/2). 🙏
|
||||
- Deleting the last local Markdown image via the Excalidraw properties panel's delete button no longer skips the prompt to keep or delete its Markdown content. Deletion detection now covers every trigger (keyboard, Cut, context menu, panel button, or scripts) uniformly.
|
||||
|
||||
## New from Excalidraw.com
|
||||
- New tool: Bucket fill. See more tools menu, or press B to toggle the bucket fill tool. [#11799](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11799)
|
||||
`,
|
||||
"2.26.2": `
|
||||
${getYouTubeDiv("p9MBFxUoOXQ")}
|
||||
|
||||
## New
|
||||
- Stencil libraries can now be stored as vault files instead of inside the plugin's data.json, improving settings save stability for large libraries. Existing users are offered a safe, merge-first migration. Enable **Sync all other types** in Obsidian Sync to synchronize library files, and enable **Show all file types** in Obsidian settings to see them in the file explorer.
|
||||
- Folder and file path settings in plugin setting now provide vault suggestions, warn when a configured path does not exist, and offer to create missing folders after confirmation.
|
||||
- Stencil libraries can now be stored as vault files instead of \`data.json\`, improving plugin settings stability. Existing users are offered a safe, merge-first migration. To sync libraries, enable **Sync all other types** in Obsidian Sync. To view library files, enable **Show all file types** in Obsidian settings.
|
||||
- Added editable Markdown images.
|
||||
- Their source can be stored locally as back-of-the-card markdown content in the drawing or linked to an external Markdown note, heading, or block, including an Excalidraw Markdown file.
|
||||
- Edit content and appearance in the Excalidraw sidepanel or use the action menu on a selected Markdown image; the editor supports standard Obsidian Markdown shortcuts and refreshes the image when focus leaves the editor.
|
||||
- Markdown images participate in normal canvas layering and image export.
|
||||
- Dropping a Markdown note as an image now offers its headings when available and lets you insert the selected source as an editable Markdown image or embeddable. Excalidraw notes offer their back-of-note headings while hiding Excalidraw Managed data sections.
|
||||
- Ordinary copies of a local Markdown image share its Markdown source; use **Duplicate selected image** to create an independent image ID and Markdown body. You can also convert interactive embeddables into images and back in the embeddable/image menu in the top left of the selected element, and control dark-mode image inversion from the context menu.
|
||||
- Store content locally (back-of-the-card) or link to a Markdown note, heading, or block.
|
||||
- Edit content and appearance from the Excalidraw side panel.
|
||||
- Supports canvas layering and image export.
|
||||
- Dragging a Markdown note as an image lets you choose a heading (when available) and insert it as either an editable Markdown image or embeddable.
|
||||
- Local Markdown image copies share the same source. Use **Duplicate selected image** to create an independent image and Markdown body. You can also convert between images and embeddables from the selected element's menu.
|
||||
- Image-reference embeds now support an optional \`padding=N\` parameter, e.g.: \`![[drawing#^area=xyz,padding=10]]\` [#2850](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2850) 🙏[@Evgene-Kopylov](${URLs.GITHUB_COM}/Evgene-Kopylov)
|
||||
- Added the Voronoi diagram script. 🙏[@FreeCutter](${URLs.GITHUB_COM}/FreeCutter) [#2845](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2845)
|
||||
- Image-reference embeds now accept an optional \`,padding=N\` link parameter to override their export padding, including \`area=\`, \`group=\`, \`frame=\`, and \`clippedframe=\` references. For \`area=\`, the value also controls how far around the target Excalidraw searches for surrounding elements. Use \`padding=0\` for no added margin. [#2850](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2850) 🙏[@Evgene-Kopylov](${URLs.GITHUB_COM}/Evgene-Kopylov)
|
||||
- Dragging a single external GIF, WebP, or APNG onto a drawing with the **Import external file** action now offers a choice between inserting it as an image or as an embeddable after importing it to the Vault. [#2848](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2848)
|
||||
- Dragging a single external GIF with the **Import external file** action now lets you import it as either an image or an embeddable. [#2848](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2848)
|
||||
- Folder and file path settings now provide vault suggestions, warn about missing paths, and can create missing folders after confirmation.
|
||||
|
||||
## New and fixed from Excalidraw.com
|
||||
- New: flowchart (CTRL/CMD+arrow keys) now intelligently routes new shapes to avoid overlap of flowchart children [#11532](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11532)
|
||||
- New Draw To Shape feature: Draw a shape freehand, and Excalidraw will automatically convert it to a perfect shape. [#9313](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/9313)
|
||||
- Fixed: Dragged arrow endpoint ignore grid and angle locks [#10972](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10972)
|
||||
- New: Double-click to toggle arrowhead [#11615](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11615)
|
||||
- New: Flowchart (CTRL/CMD+Arrow) now intelligently routes new shapes to avoid overlapping child nodes. [#11532](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11532)
|
||||
- New: Draw To Shape automatically converts freehand drawings into perfect shapes. [#9313](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/9313)
|
||||
- Fixed: Dragged arrow endpoints now respect grid and angle locks. [#10972](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10972)
|
||||
- New: Double-click an arrow to toggle its arrowhead. [#11615](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11615)
|
||||
|
||||
## Fixed
|
||||
- Custom freedraw pens now remain selected while temporarily using the eraser or another tool, and are restored when returning to freedraw. [#2859](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2859)
|
||||
- Markdown images now offer configurable bottom padding in the sidepanel Appearance section to prevent the final rendered line or border from being clipped.
|
||||
- Font selectors for Markdown images and font settings now preview each available font face and refresh the vault font list whenever opened.
|
||||
- Empty Markdown-image font colors now normalize to black when the editor loads or the color field loses focus. The CSS controls can also copy the selected image's generated SVG directly for inspection.
|
||||
- Dragging an external video or other non-image file with the **Import external file** action now offers the same use, overwrite, or import choice as images when a matching file already exists in the Vault. [#2851](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2851) 🙏[@WolfExplode](${URLs.GITHUB_COM}/WolfExplode)
|
||||
- Custom freedraw pens now remain selected after temporarily switching to the eraser or another tool, and are restored when returning to freedraw. [#2859](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2859)
|
||||
- Added configurable bottom padding for Markdown images to prevent clipped final lines or borders.
|
||||
- Markdown image font selectors now preview each font and refresh the vault font list whenever opened.
|
||||
- Empty Markdown image font colors now normalize to black when the editor opens or the color field loses focus. CSS controls can also copy the generated SVG for inspection.
|
||||
- Dragging an external video or other non-image file with the **Import external file** action now offers the same use, overwrite, or import options as images when a matching vault file already exists. [#2851](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2851) 🙏[@WolfExplode](${URLs.GITHUB_COM}/WolfExplode)
|
||||
|
||||
## Excalidraw Automate Breaking Change
|
||||
- Excalidraw component API has discontinued \`api.scrollToContent(target?, opts?)\` and replaced it with \`api.setViewport(opts | null)\`. You'll need to update MindMap Builder and Comic Strip Director scripts. If you have your own scripts using this API function you'll need to update them accordingly. For more information read the Excalidraw [Change Log](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_CHANGELOG}#viewport-control--scrollzoom-locking)
|
||||
- The Excalidraw API has replaced \`api.scrollToContent(target?, opts?)\` with \`api.setViewport(opts | null)\`. Update the MindMap Builder and Comic Strip Director scripts, along with any custom scripts using the old API. See the Excalidraw [Change Log](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_CHANGELOG}#viewport-control--scrollzoom-locking) for details.
|
||||
`,
|
||||
"2.25.3": `
|
||||
Minor maintenance release with two important fixes.
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { App, Component, MarkdownRenderer, Notice, TFile } from "obsidian";
|
||||
import {
|
||||
DEVICE,
|
||||
DEFAULT_MD_EMBED_CSS,
|
||||
fileid,
|
||||
IMAGE_TYPES,
|
||||
@@ -22,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,
|
||||
@@ -70,7 +71,7 @@ import {
|
||||
} from "src/types/embeddedFileLoaderTypes";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { setStyleText } from "src/utils/htmlUtils";
|
||||
import { hideElement, setStyle } from "src/utils/styleUtils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
import {
|
||||
isInstanceOfHTMLImageElement,
|
||||
isInstanceOfSVGElement,
|
||||
@@ -182,6 +183,131 @@ const waitForMarkdownPostProcessors = (
|
||||
});
|
||||
};
|
||||
|
||||
const waitForDocumentFonts = async (doc: Document): Promise<void> => {
|
||||
const fontSet = doc.fonts;
|
||||
if (!fontSet) {
|
||||
return;
|
||||
}
|
||||
// FontFaceSet.ready can hang on some environments if a face stalls.
|
||||
await Promise.race([
|
||||
fontSet.ready,
|
||||
new Promise<void>((resolve) => {
|
||||
window.setTimeout(resolve, 500);
|
||||
}),
|
||||
]);
|
||||
};
|
||||
|
||||
const measureElementHeight = (element: Element | null): number => {
|
||||
if (!element) {
|
||||
return 0;
|
||||
}
|
||||
const typedElement = element as HTMLElement;
|
||||
const rectHeight = Number(typedElement.getBoundingClientRect?.().height ?? 0);
|
||||
return Math.max(
|
||||
Number(typedElement.scrollHeight ?? 0),
|
||||
Number(typedElement.offsetHeight ?? 0),
|
||||
Number(typedElement.clientHeight ?? 0),
|
||||
Number.isFinite(rectHeight) ? rectHeight : 0,
|
||||
);
|
||||
};
|
||||
|
||||
const getCssPixelValue = (value: string | null | undefined): number => {
|
||||
if (!value) {
|
||||
return 0;
|
||||
}
|
||||
const parsed = Number.parseFloat(value);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
};
|
||||
|
||||
const measureRenderedContentHeight = (element: Element | null): number => {
|
||||
if (!element) {
|
||||
return 0;
|
||||
}
|
||||
const typedElement = element as HTMLElement;
|
||||
const ownerWindow = typedElement.ownerDocument.defaultView;
|
||||
const hostRect = typedElement.getBoundingClientRect();
|
||||
let maxContentBottom = 0;
|
||||
|
||||
typedElement.querySelectorAll("*").forEach((child) => {
|
||||
const childElement = child as HTMLElement;
|
||||
const childRect = childElement.getBoundingClientRect();
|
||||
if (!Number.isFinite(childRect.bottom)) {
|
||||
return;
|
||||
}
|
||||
maxContentBottom = Math.max(maxContentBottom, childRect.bottom - hostRect.top);
|
||||
});
|
||||
|
||||
const lastChild = typedElement.lastElementChild as HTMLElement | null;
|
||||
const lastChildMarginBottom =
|
||||
ownerWindow && lastChild
|
||||
? getCssPixelValue(ownerWindow.getComputedStyle(lastChild).marginBottom)
|
||||
: 0;
|
||||
const hostPaddingBottom = ownerWindow
|
||||
? getCssPixelValue(ownerWindow.getComputedStyle(typedElement).paddingBottom)
|
||||
: 0;
|
||||
|
||||
return Math.max(
|
||||
measureElementHeight(typedElement),
|
||||
maxContentBottom + lastChildMarginBottom,
|
||||
hostRect.height,
|
||||
) + hostPaddingBottom;
|
||||
};
|
||||
|
||||
const appendMarkdownBottomSpacer = (
|
||||
container: HTMLElement,
|
||||
paddingBottom: number,
|
||||
): void => {
|
||||
const existingSpacer = container.querySelector(
|
||||
".excalidraw-md-padding-spacer",
|
||||
);
|
||||
if (existingSpacer?.parentElement) {
|
||||
existingSpacer.parentElement.removeChild(existingSpacer);
|
||||
}
|
||||
if (!(paddingBottom > 0)) {
|
||||
return;
|
||||
}
|
||||
// FIX: WebKit/iOS will often return a 0 bounding client rect for completely empty divs.
|
||||
// We insert a zero-width space so the layout engine is forced to render the block and measure its height.
|
||||
const paddingSpacer = createDiv({text: "​"});
|
||||
paddingSpacer.setAttribute("class", "excalidraw-md-padding-spacer");
|
||||
|
||||
setStyle(paddingSpacer, {
|
||||
display: "block",
|
||||
width: "100%",
|
||||
height: `${paddingBottom}px`,
|
||||
minHeight: `${paddingBottom}px`,
|
||||
color: "transparent",
|
||||
lineHeight: "0px"
|
||||
});
|
||||
container.appendChild(paddingSpacer);
|
||||
};
|
||||
|
||||
const ISOLATED_MARKDOWN_RENDER_CSS = `
|
||||
.excalidraw-md-host,
|
||||
.excalidraw-md-host * {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.excalidraw-md-host {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
letter-spacing: 0px;
|
||||
word-spacing: 0px;
|
||||
text-rendering: geometricPrecision;
|
||||
-webkit-text-size-adjust: none;
|
||||
text-size-adjust: none;
|
||||
font-kerning: none;
|
||||
font-variant-ligatures: none;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-word;
|
||||
}
|
||||
`;
|
||||
|
||||
const snapshotRenderedCanvases = (container: HTMLElement): void => {
|
||||
container.querySelectorAll("canvas").forEach((canvas) => {
|
||||
try {
|
||||
@@ -1060,6 +1186,7 @@ export class EmbeddedFilesLoader {
|
||||
validationConcurrency,
|
||||
emitPolicy = "all",
|
||||
onDeferredValidationCandidates,
|
||||
sceneElements,
|
||||
}: {
|
||||
excalidrawData: ExcalidrawData;
|
||||
addFiles: (files: FileData[], isDark: boolean, final?: boolean) => void;
|
||||
@@ -1071,13 +1198,16 @@ export class EmbeddedFilesLoader {
|
||||
validationConcurrency?: number;
|
||||
emitPolicy?: LoadSceneEmitPolicy;
|
||||
onDeferredValidationCandidates?: (fileIds: Set<FileId>) => void;
|
||||
sceneElements?: readonly ExcalidrawElement[];
|
||||
}) {
|
||||
if (depth > 7) {
|
||||
new Notice(t("INFINITE_LOOP_WARNING") + depth.toString(), 6000);
|
||||
return;
|
||||
}
|
||||
const entries = Array.from(excalidrawData.getFileEntries());
|
||||
const markdownImageElements = excalidrawData.scene.elements.filter(
|
||||
const markdownImageElements = (
|
||||
sceneElements ?? excalidrawData.scene.elements
|
||||
).filter(
|
||||
(element: ExcalidrawElement) =>
|
||||
element.type === "image" &&
|
||||
Boolean(element.customData?.[MARKDOWN_IMAGE_CUSTOM_DATA_KEY]),
|
||||
@@ -1792,7 +1922,7 @@ export class EmbeddedFilesLoader {
|
||||
? `.excalidraw-md-host.theme-light{color-scheme:light;--background-primary:#ffffff;--background-secondary:#f5f5f5;--text-normal:#2e3338;--text-muted:#6b6b6b;--link-color:#086ddd}.excalidraw-md-host.theme-light a{color:var(--link-color)}.excalidraw-md-host.theme-light th{background-color:#dedede}.excalidraw-md-host.theme-light pre[class*=language-],.excalidraw-md-host.theme-light :not(pre)>code[class*=language-]{color:#393a34;background-color:#f5f5f5;border-color:#ddd}.excalidraw-md-host.theme-light blockquote{background-color:rgba(0,0,0,.06)}`
|
||||
: "";
|
||||
let style: string = overrides
|
||||
? `${DEFAULT_MD_EMBED_CSS}\n${markdownImageThemeCSS}\n${overrides.render.css}`
|
||||
? `${DEFAULT_MD_EMBED_CSS}\n${ISOLATED_MARKDOWN_RENDER_CSS}\n${markdownImageThemeCSS}\n${overrides.render.css}`
|
||||
: (safeFrontmatter[FRONTMATTER_KEYS["md-css"].name] ?? "");
|
||||
|
||||
let frontmatterCSSisAfile = false;
|
||||
@@ -1816,6 +1946,9 @@ export class EmbeddedFilesLoader {
|
||||
style += DEFAULT_MD_EMBED_CSS;
|
||||
}
|
||||
}
|
||||
if (!style.includes(ISOLATED_MARKDOWN_RENDER_CSS)) {
|
||||
style = `${ISOLATED_MARKDOWN_RENDER_CSS}\n${style}`;
|
||||
}
|
||||
|
||||
const borderColor: string = overrides
|
||||
? overrides.render.border.enabled
|
||||
@@ -1848,10 +1981,13 @@ export class EmbeddedFilesLoader {
|
||||
const svgClass = overrides?.isTransclusion
|
||||
? ' class="excalidraw-md-transclusion"'
|
||||
: "";
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg"${svgClass} width="${linkParts.width}px" height="${svgHeight}px">${
|
||||
|
||||
// FIX: Added viewBox="0 0 ${linkParts.width} ${svgHeight}"
|
||||
// This is mandatory for Safari to respect the width/height of the SVG when loaded as an image.
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg"${svgClass} width="${linkParts.width}px" height="${svgHeight}px" viewBox="0 0 ${linkParts.width} ${svgHeight}">${
|
||||
style ? `<style>${style}</style>` : ""
|
||||
}<foreignObject x="${inset}" y="${inset}" width="${width}px" height="${height}px">${xml}${
|
||||
xmlFooter //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/286#issuecomment-982179639
|
||||
xmlFooter
|
||||
}</foreignObject>${border}${
|
||||
fontDef !== "" ? `<defs><style>${fontDef}</style></defs>` : ""
|
||||
}</svg>`;
|
||||
@@ -1868,14 +2004,15 @@ export class EmbeddedFilesLoader {
|
||||
if (fontName !== "") {
|
||||
setStyle(mdDIV, { fontFamily: fontName });
|
||||
}
|
||||
const markdownImagePaddingBottom =
|
||||
overrides && !overrides.isTransclusion
|
||||
? overrides.render.paddingBottom
|
||||
: 0;
|
||||
setStyle(mdDIV, {
|
||||
overflow: "auto",
|
||||
overflow: "hidden",
|
||||
display: "block",
|
||||
color: fontColor && fontColor !== "" ? fontColor : "initial",
|
||||
paddingBottom:
|
||||
overrides && !overrides.isTransclusion
|
||||
? `${overrides.render.paddingBottom}px`
|
||||
: undefined,
|
||||
paddingBottom: undefined,
|
||||
});
|
||||
|
||||
const renderHost = mainDocument.body.createDiv();
|
||||
@@ -1890,6 +2027,27 @@ export class EmbeddedFilesLoader {
|
||||
zIndex: "-1",
|
||||
});
|
||||
renderHost.appendChild(mdDIV);
|
||||
const isolatedRenderStyleEl = deliberateCreateElement(
|
||||
mainDocument,
|
||||
"style",
|
||||
) as HTMLStyleElement;
|
||||
setStyleText(
|
||||
isolatedRenderStyleEl,
|
||||
ISOLATED_MARKDOWN_RENDER_CSS.replaceAll(
|
||||
".excalidraw-md-host",
|
||||
`.${MARKDOWN_TO_SVG_RENDER_CLASS}`,
|
||||
),
|
||||
);
|
||||
mainDocument.head.appendChild(isolatedRenderStyleEl);
|
||||
const isolatedFontStyleEl =
|
||||
fontDef !== ""
|
||||
? (deliberateCreateElement(mainDocument, "style") as HTMLStyleElement)
|
||||
: null;
|
||||
if (isolatedFontStyleEl) {
|
||||
setStyleText(isolatedFontStyleEl, fontDef);
|
||||
mainDocument.head.appendChild(isolatedFontStyleEl);
|
||||
await waitForDocumentFonts(mainDocument);
|
||||
}
|
||||
const renderComponent = new Component();
|
||||
renderComponent.load();
|
||||
let renderedDIV: HTMLDivElement | null = null;
|
||||
@@ -1908,10 +2066,13 @@ export class EmbeddedFilesLoader {
|
||||
} finally {
|
||||
renderComponent.unload();
|
||||
renderHost.remove();
|
||||
isolatedRenderStyleEl.remove();
|
||||
isolatedFontStyleEl?.remove();
|
||||
}
|
||||
if (renderedDIV) {
|
||||
mdDIV = renderedDIV;
|
||||
}
|
||||
appendMarkdownBottomSpacer(mdDIV, markdownImagePaddingBottom);
|
||||
if (this.terminate) {
|
||||
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
|
||||
}
|
||||
@@ -2059,18 +2220,65 @@ export class EmbeddedFilesLoader {
|
||||
//First I need to create a fully self contained copy of the document to convert
|
||||
//blank styles into inline styles using computedStyle
|
||||
const iframeHost = mainDocument.body.createDiv();
|
||||
hideElement(iframeHost);
|
||||
// Use a fixed off-screen container with STRICT width boundaries to defeat iOS iframe flattening.
|
||||
setStyle(iframeHost, {
|
||||
position: "fixed",
|
||||
left: "-100000px",
|
||||
top: "0",
|
||||
width: `${linkParts.width}px`,
|
||||
height: "10000px", // Give it plenty of room to render without scrollbars
|
||||
overflow: "hidden",
|
||||
visibility: "hidden",
|
||||
pointerEvents: "none",
|
||||
});
|
||||
let xmlINiframe = "";
|
||||
let xmlFooter = "";
|
||||
let iframeContentHeight = 0;
|
||||
let iframeFooterHeight = 0;
|
||||
try {
|
||||
const iframe = iframeHost.createEl("iframe");
|
||||
// FIX: Lock the iframe's internal dimensions
|
||||
setStyle(iframe, {
|
||||
width: `${linkParts.width}px`,
|
||||
height: "100%",
|
||||
border: "none",
|
||||
margin: "0",
|
||||
padding: "0"
|
||||
});
|
||||
|
||||
const iframeDoc = iframe.contentWindow.document;
|
||||
const iframeWindow = iframe.contentWindow;
|
||||
|
||||
// FIX: Force the iframe's body to respect the target width and prevent text inflation
|
||||
// Removed `overflow: hidden !important` so we don't accidentally clip valid heights on iOS measurement.
|
||||
const bodyReset = deliberateCreateElement(iframeDoc, "style") as HTMLStyleElement;
|
||||
setStyleText(bodyReset, `
|
||||
html, body {
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
width: ${linkParts.width}px !important;
|
||||
max-width: ${linkParts.width}px !important;
|
||||
overflow: visible !important;
|
||||
-webkit-text-size-adjust: none !important;
|
||||
text-size-adjust: none !important;
|
||||
}
|
||||
`);
|
||||
iframeDoc.head.appendChild(bodyReset);
|
||||
|
||||
if (style) {
|
||||
// Obsidian style.css does not good in this case, yet the code scanner enforces it
|
||||
const styleEl = deliberateCreateElement(iframeDoc, "style") as HTMLStyleElement;
|
||||
setStyleText(styleEl, style);
|
||||
iframeDoc.head.appendChild(styleEl);
|
||||
}
|
||||
if (fontDef !== "") {
|
||||
const fontStyleEl = deliberateCreateElement(
|
||||
iframeDoc,
|
||||
"style",
|
||||
) as HTMLStyleElement;
|
||||
setStyleText(fontStyleEl, fontDef);
|
||||
iframeDoc.head.appendChild(fontStyleEl);
|
||||
}
|
||||
// Inject the MathJax CHTML stylesheet into the iframe so that mjx-* custom elements
|
||||
// are styled correctly when measuring scroll height and computing inline styles.
|
||||
if (mjxCHtmlStyleContent) {
|
||||
@@ -2083,10 +2291,11 @@ export class EmbeddedFilesLoader {
|
||||
const footerDIV = createDiv();
|
||||
footerDIV.setAttribute("class", "excalidraw-md-footer");
|
||||
iframeDoc.body.appendChild(footerDIV);
|
||||
await waitForDocumentFonts(iframeDoc);
|
||||
|
||||
iframeDoc.body.querySelectorAll("*").forEach((el: HTMLElement) => {
|
||||
const elementStyle = el.style;
|
||||
const computedStyle = window.getComputedStyle(el);
|
||||
const computedStyle = iframeWindow.getComputedStyle(el);
|
||||
let style = "";
|
||||
for (const [prop] of Object.entries(elementStyle)) {
|
||||
if (Object.hasOwn(elementStyle ?? {}, prop)) {
|
||||
@@ -2097,6 +2306,9 @@ export class EmbeddedFilesLoader {
|
||||
el.setAttribute("style", style);
|
||||
});
|
||||
|
||||
iframeContentHeight = measureRenderedContentHeight(stylingDIV);
|
||||
iframeFooterHeight = measureRenderedContentHeight(footerDIV);
|
||||
|
||||
xmlINiframe = new XMLSerializer().serializeToString(stylingDIV);
|
||||
xmlFooter = new XMLSerializer().serializeToString(footerDIV);
|
||||
} finally {
|
||||
@@ -2123,11 +2335,20 @@ export class EmbeddedFilesLoader {
|
||||
try {
|
||||
host.appendChild(svgEl);
|
||||
mainDocument.body.appendChild(host);
|
||||
footerHeight = svgEl.querySelector(".excalidraw-md-footer").scrollHeight;
|
||||
const height =
|
||||
svgEl.querySelector(".excalidraw-md-host").scrollHeight + footerHeight;
|
||||
footerHeight = Math.max(
|
||||
measureRenderedContentHeight(svgEl.querySelector(".excalidraw-md-footer")),
|
||||
iframeFooterHeight,
|
||||
);
|
||||
const contentHeight = Math.max(
|
||||
measureRenderedContentHeight(svgEl.querySelector(".excalidraw-md-host")),
|
||||
iframeContentHeight,
|
||||
);
|
||||
const borderHeight = drawBorder ? 4 : 0;
|
||||
const measuredHeight = Math.ceil(height + borderHeight);
|
||||
// Safari on iOS under-reports foreignObject content height intermittently.
|
||||
const iOSSafetyPadding = DEVICE.isIOS ? 1 : 0;
|
||||
const measuredHeight = Math.ceil(
|
||||
contentHeight + footerHeight + borderHeight + iOSSafetyPadding,
|
||||
);
|
||||
svgHeight = overrides?.fullHeight
|
||||
? measuredHeight
|
||||
: measuredHeight <= linkParts.height
|
||||
|
||||
@@ -1155,9 +1155,19 @@ export class ExcalidrawData {
|
||||
/^((%%\n*)?# Excalidraw Data\n\n?## Text Elements(?:\n|$))/m,
|
||||
) ?? data.match(/^((%%\n*)?##? Text Elements(?:\n|$))/m);
|
||||
|
||||
// "# Excalidraw Data" (or equivalent) was found above, so `position` was
|
||||
// not -1 and we got here, but there may be no "## Text Elements" heading
|
||||
// anywhere in the remaining data (e.g. a hand-authored or externally
|
||||
// generated file with zero text elements, or one where the heading was
|
||||
// deleted while "## Element Links" / "## Embedded Files" / the block-ref
|
||||
// text below it were left in place). Falling back to "" instead of
|
||||
// throwing on a null match lets execution fall through to the existing
|
||||
// Element Links / Embedded Files / text-element parsing below, exactly as
|
||||
// happens today for a file with an empty "## Text Elements" section.
|
||||
// https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2871
|
||||
const textElementsMatch = normalMatch
|
||||
? normalMatch[0]
|
||||
: data.match(/(.*##? Text Elements(?:\n|$))/m)[0];
|
||||
: (data.match(/(.*##? Text Elements(?:\n|$))/m)?.[0] ?? "");
|
||||
|
||||
data = data.slice(textElementsMatch.length);
|
||||
this.textElementCommentedOut = textElementsMatch.startsWith("%%\n");
|
||||
|
||||
@@ -421,7 +421,7 @@ export async function insertMarkdownImage(
|
||||
view: ExcalidrawView,
|
||||
source: string | TFile | EmbeddedFile = "",
|
||||
position: { x: number; y: number } = view.currentPosition,
|
||||
): Promise<string | null> {
|
||||
): Promise<ExcalidrawImageElement | null> {
|
||||
if (!view.excalidrawAPI || !view.file) {
|
||||
return null;
|
||||
}
|
||||
@@ -476,13 +476,8 @@ export async function insertMarkdownImage(
|
||||
return null;
|
||||
}
|
||||
view.setDirty();
|
||||
const inserted = view
|
||||
.getViewElements()
|
||||
.find((candidate) => candidate.id === id);
|
||||
if (inserted) {
|
||||
view.excalidrawAPI.selectElements([inserted]);
|
||||
}
|
||||
return id;
|
||||
view.excalidrawAPI.selectElements([element]);
|
||||
return element;
|
||||
}
|
||||
|
||||
/** Duplicates a local Markdown image with independent element and file IDs. */
|
||||
@@ -584,5 +579,14 @@ export async function updateMarkdownImage(
|
||||
return false;
|
||||
}
|
||||
view.setDirty();
|
||||
// Persist right after every successful render instead of only on specific UI events (switching
|
||||
// elements, closing the sidepanel, etc.). Those events are not reliable signals of "the user is
|
||||
// done": the sidepanel can be hidden/collapsed (no close event fires) or be a popout window that
|
||||
// is moved out of view, and none of that tells us whether the editor is still visible. Saving
|
||||
// here ties persistence directly to the one thing we know for certain changed: the element in
|
||||
// the scene. forceSave's waitIfBusy avoids silently no-oping against a concurrent save, and the
|
||||
// override bypasses the embeddableIsEditingSelf debounce without touching it, so this does not
|
||||
// disrupt the ongoing edit the way a reload()-driven refresh would.
|
||||
await view.forceSave(true, true);
|
||||
return true;
|
||||
}
|
||||
+15
-101
@@ -24,7 +24,6 @@ import {
|
||||
} from "src/types/AIUtilTypes";
|
||||
import {
|
||||
decryptProviderProfiles,
|
||||
decryptStoredAPIKey,
|
||||
} from "src/utils/settingsKeyObfuscation";
|
||||
import {
|
||||
getGeminiImageRequestConfig,
|
||||
@@ -449,16 +448,6 @@ const joinURL = (baseURL: string, path: string): string => {
|
||||
return `${normalizeBaseURL(baseURL)}/${path.replace(/^\/+/, "")}`;
|
||||
};
|
||||
|
||||
const inferLegacyBaseURL = (url: string, suffix: string): string => {
|
||||
const normalized = normalizeBaseURL(url);
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
return normalized.endsWith(suffix)
|
||||
? normalized.slice(0, -suffix.length)
|
||||
: normalized;
|
||||
};
|
||||
|
||||
const inferConfiguredBaseURL = (url: string): string => {
|
||||
const normalized = normalizeBaseURL(url);
|
||||
if (!normalized) {
|
||||
@@ -473,13 +462,6 @@ const inferConfiguredBaseURL = (url: string): string => {
|
||||
: normalized;
|
||||
};
|
||||
|
||||
const getResolvedProvider = (
|
||||
request: AIRequest,
|
||||
plugin: ExcalidrawPlugin,
|
||||
): AIProvider => {
|
||||
return request.provider ?? plugin.settings.aiProvider ?? "openai";
|
||||
};
|
||||
|
||||
const getProviderProfiles = (
|
||||
plugin: ExcalidrawPlugin,
|
||||
): Record<string, AIProviderProfile> => {
|
||||
@@ -488,17 +470,9 @@ const getProviderProfiles = (
|
||||
? decryptProviderProfiles(plugin.settings.aiProviderProfiles)
|
||||
: {
|
||||
OpenAI: {
|
||||
provider: plugin.settings.aiProvider ?? "openai",
|
||||
apiKey: decryptStoredAPIKey(
|
||||
plugin.settings.aiAPIKey || plugin.settings.openAIAPIToken,
|
||||
),
|
||||
baseURL:
|
||||
inferConfiguredBaseURL(plugin.settings.aiBaseURL) ||
|
||||
inferLegacyBaseURL(
|
||||
plugin.settings.openAIURL,
|
||||
"/chat/completions",
|
||||
) ||
|
||||
DEFAULT_PROVIDER_BASE_URLS[plugin.settings.aiProvider ?? "openai"],
|
||||
provider: "openai",
|
||||
apiKey: "",
|
||||
baseURL: URLs.API_OPENAI_COM_V1,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -527,36 +501,15 @@ const getModelConfigs = (plugin: ExcalidrawPlugin, kind: "text" | "image") => {
|
||||
return plugin.settings.aiTextModelConfigs;
|
||||
}
|
||||
|
||||
if (
|
||||
plugin.settings.aiVisionModelConfigs &&
|
||||
Object.keys(plugin.settings.aiVisionModelConfigs).length > 0
|
||||
) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(plugin.settings.aiVisionModelConfigs).map(
|
||||
([modelId, config]) => [
|
||||
modelId,
|
||||
{
|
||||
...config,
|
||||
multimodalSupport: config.multimodalSupport ?? true,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const defaultTextModel =
|
||||
plugin.settings.aiDefaultTextModel ||
|
||||
plugin.settings.aiDefaultVisionModel ||
|
||||
plugin.settings.openAIDefaultTextModel ||
|
||||
plugin.settings.openAIDefaultVisionModel ||
|
||||
"gpt-5-mini";
|
||||
|
||||
return {
|
||||
[defaultTextModel]: {
|
||||
providerId: getDefaultProviderProfileId(plugin),
|
||||
model: defaultTextModel,
|
||||
endpoint:
|
||||
plugin.settings.aiTextEndpoint || plugin.settings.openAIURL || "",
|
||||
endpoint: "",
|
||||
multimodalSupport: true,
|
||||
},
|
||||
};
|
||||
@@ -564,18 +517,7 @@ const getModelConfigs = (plugin: ExcalidrawPlugin, kind: "text" | "image") => {
|
||||
|
||||
const defaultImageModel =
|
||||
plugin.settings.aiDefaultImageGenerationModel ||
|
||||
plugin.settings.openAIDefaultImageGenerationModel ||
|
||||
"gpt-image-1";
|
||||
const legacyCapability = plugin.settings.aiImageModelCapabilities?.[
|
||||
defaultImageModel
|
||||
] as
|
||||
| {
|
||||
supportedSizes?: string[];
|
||||
supportsPromptImageTransforms?: boolean;
|
||||
supportsMaskImageEdits?: boolean;
|
||||
supportsImageEdits?: boolean;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
return plugin.settings.aiImageModelConfigs &&
|
||||
Object.keys(plugin.settings.aiImageModelConfigs).length > 0
|
||||
@@ -584,15 +526,9 @@ const getModelConfigs = (plugin: ExcalidrawPlugin, kind: "text" | "image") => {
|
||||
[defaultImageModel]: {
|
||||
providerId: getDefaultProviderProfileId(plugin),
|
||||
model: defaultImageModel,
|
||||
supportedSizes: legacyCapability?.supportedSizes ?? ["1024x1024"],
|
||||
supportsPromptImageTransforms:
|
||||
legacyCapability?.supportsPromptImageTransforms ??
|
||||
legacyCapability?.supportsImageEdits ??
|
||||
true,
|
||||
supportsMaskImageEdits:
|
||||
legacyCapability?.supportsMaskImageEdits ??
|
||||
legacyCapability?.supportsImageEdits ??
|
||||
true,
|
||||
supportedSizes: ["1024x1024"],
|
||||
supportsPromptImageTransforms: true,
|
||||
supportsMaskImageEdits: true,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -611,13 +547,11 @@ const getSelectedModelConfigId = (
|
||||
request.textModelId,
|
||||
plugin.settings.aiDefaultMultimodalModel,
|
||||
plugin.settings.aiDefaultTextModel,
|
||||
plugin.settings.aiDefaultVisionModel,
|
||||
]
|
||||
: [
|
||||
request.textModelId,
|
||||
plugin.settings.aiDefaultTextModel,
|
||||
plugin.settings.aiDefaultMultimodalModel,
|
||||
plugin.settings.aiDefaultVisionModel,
|
||||
];
|
||||
|
||||
const normalizedConfiguredIds = configuredIds.filter(Boolean);
|
||||
@@ -682,7 +616,7 @@ const getResolvedModelConfig = (
|
||||
const provider =
|
||||
request.provider ??
|
||||
profile?.provider ??
|
||||
getResolvedProvider(request, plugin);
|
||||
"openai";
|
||||
const hasRequestBaseURL = Boolean(request.baseURL?.trim());
|
||||
const baseURL = normalizeBaseURL(
|
||||
(hasRequestBaseURL ? inferConfiguredBaseURL(request.baseURL) : "") ||
|
||||
@@ -705,8 +639,7 @@ const getResolvedModelConfig = (
|
||||
apiKey:
|
||||
request.apiKey?.trim() ||
|
||||
profile?.apiKey ||
|
||||
plugin.settings.aiAPIKey ||
|
||||
plugin.settings.openAIAPIToken,
|
||||
"",
|
||||
baseURL,
|
||||
endpoint,
|
||||
model: request.model?.trim() || selectedConfig?.model || "",
|
||||
@@ -718,9 +651,6 @@ const getResolvedModelConfig = (
|
||||
}
|
||||
|
||||
const imageConfig = selectedConfig as AIImageModelConfig;
|
||||
const legacySupportsImageEdits = (
|
||||
imageConfig as AIImageModelConfig & { supportsImageEdits?: boolean }
|
||||
).supportsImageEdits;
|
||||
const resolvedModel = request.model?.trim() || selectedConfig?.model || "";
|
||||
const geminiSupportedSizes = getGeminiSupportedSizes(provider, resolvedModel);
|
||||
return {
|
||||
@@ -730,11 +660,9 @@ const getResolvedModelConfig = (
|
||||
? geminiSupportedSizes
|
||||
: [...(imageConfig.supportedSizes ?? ["1024x1024"])],
|
||||
supportsPromptImageTransforms:
|
||||
imageConfig.supportsPromptImageTransforms ??
|
||||
legacySupportsImageEdits ??
|
||||
true,
|
||||
imageConfig.supportsPromptImageTransforms ?? true,
|
||||
supportsMaskImageEdits:
|
||||
imageConfig.supportsMaskImageEdits ?? legacySupportsImageEdits ?? true,
|
||||
imageConfig.supportsMaskImageEdits ?? true,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -754,10 +682,7 @@ const resolveAIConfig = (
|
||||
"image",
|
||||
request,
|
||||
) as ResolvedImageConfig,
|
||||
maxTokens:
|
||||
resolvedPlugin.settings.aiDefaultMaxResponseTokens ||
|
||||
resolvedPlugin.settings.aiDefaultMaxTokens ||
|
||||
resolvedPlugin.settings.openAIDefaultTextModelMaxTokens,
|
||||
maxTokens: resolvedPlugin.settings.aiDefaultMaxResponseTokens,
|
||||
maxOutgoingTokens: resolvedPlugin.settings.aiDefaultMaxOutgoingTokens || 0,
|
||||
};
|
||||
};
|
||||
@@ -2279,10 +2204,6 @@ const requestAI = async (
|
||||
"defaultMultimodalModel",
|
||||
plugin.settings.aiDefaultMultimodalModel || "<empty>",
|
||||
),
|
||||
debugValueLine(
|
||||
"legacyVisionDefault",
|
||||
plugin.settings.aiDefaultVisionModel || "<empty>",
|
||||
),
|
||||
debugValueLine("resolvedProvider", config.text.provider),
|
||||
debugValueLine("resolvedModel", config.text.model),
|
||||
debugValueLine("resolvedEndpoint", config.text.endpoint),
|
||||
@@ -2530,9 +2451,6 @@ export const getAISettings = (
|
||||
AIImageModelConfig
|
||||
>,
|
||||
).map(([modelId, config]) => {
|
||||
const legacySupportsImageEdits = (
|
||||
config as AIImageModelConfig & { supportsImageEdits?: boolean }
|
||||
).supportsImageEdits;
|
||||
const geminiSupportedSizes = getGeminiSupportedSizes(
|
||||
providerProfiles[config.providerId]?.provider,
|
||||
config.model,
|
||||
@@ -2546,11 +2464,9 @@ export const getAISettings = (
|
||||
? geminiSupportedSizes
|
||||
: [...(config.supportedSizes ?? ["1024x1024"])],
|
||||
supportsPromptImageTransforms:
|
||||
config.supportsPromptImageTransforms ??
|
||||
legacySupportsImageEdits ??
|
||||
true,
|
||||
config.supportsPromptImageTransforms ?? true,
|
||||
supportsMaskImageEdits:
|
||||
config.supportsMaskImageEdits ?? legacySupportsImageEdits ?? true,
|
||||
config.supportsMaskImageEdits ?? true,
|
||||
},
|
||||
];
|
||||
}),
|
||||
@@ -2583,9 +2499,7 @@ export const getAISettings = (
|
||||
defaultMaxOutgoingTokens:
|
||||
resolvedPlugin.settings.aiDefaultMaxOutgoingTokens || 0,
|
||||
defaultMaxResponseTokens:
|
||||
resolvedPlugin.settings.aiDefaultMaxResponseTokens ||
|
||||
resolvedPlugin.settings.aiDefaultMaxTokens ||
|
||||
resolvedPlugin.settings.openAIDefaultTextModelMaxTokens,
|
||||
resolvedPlugin.settings.aiDefaultMaxResponseTokens,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Converts identifiers or objects with identifiers into a keyed lookup map.
|
||||
*
|
||||
* @param items - Values to index, or an existing map to reuse.
|
||||
* @returns The original map when one is supplied; otherwise, a new map keyed
|
||||
* by each string value or object's `id` property.
|
||||
*/
|
||||
export function arrayToMap<T extends { id: string } | string>(
|
||||
items: readonly T[] | Map<string, T>,
|
||||
) {
|
||||
if (items instanceof Map) {
|
||||
return items;
|
||||
}
|
||||
return items.reduce((acc: Map<string, T>, element) => {
|
||||
acc.set(typeof element === "string" ? element : element.id, element);
|
||||
return acc;
|
||||
}, new Map());
|
||||
}
|
||||
@@ -77,10 +77,10 @@ export const patchMobileView = (
|
||||
view: ExcalidrawView,
|
||||
opts?: { keepAlive?: boolean; isActive?: () => boolean },
|
||||
): (() => void) | void => {
|
||||
if (!DEVICE.isPhone) {
|
||||
if (!DEVICE.isMobile) {
|
||||
return;
|
||||
}
|
||||
log("patching mobile view");
|
||||
// log("patching mobile view");
|
||||
const parent = getParentOfClass(view.containerEl, "mod-top");
|
||||
if (parent) {
|
||||
if (!parent.hasClass("mod-visible")) {
|
||||
|
||||
@@ -6,6 +6,19 @@ import { getDataURL } from "./coreUtils";
|
||||
|
||||
export { getEmbeddedFilenameParts } from "./embeddedFilenameParts";
|
||||
|
||||
/**
|
||||
* Loads a vault font and creates its data URL and `@font-face` definition.
|
||||
*
|
||||
* @param app - Obsidian application used to resolve and read the font file.
|
||||
* @param fontFileName - Vault link path or font filename to resolve.
|
||||
* @param sourcePath - Vault path from which the font link is resolved.
|
||||
* @param name - Optional font-family name overriding the file basename.
|
||||
* @returns The font definition, resolved family name, and encoded data URL.
|
||||
* Empty strings are returned when the font cannot be resolved.
|
||||
* @remarks
|
||||
* MIME types and CSS format names intentionally preserve the established
|
||||
* extension mapping used by plugin startup and embedded SVG font loading.
|
||||
*/
|
||||
export async function getFontDataURL(
|
||||
app: App,
|
||||
fontFileName: string,
|
||||
@@ -50,15 +63,36 @@ export async function getFontDataURL(
|
||||
return { fontDef, fontName, dataURL };
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes SVG markup as a base64 data URL.
|
||||
*
|
||||
* @param svg - Serialized SVG markup.
|
||||
* @returns A base64-encoded `data:image/svg+xml` URL.
|
||||
* @remarks
|
||||
* Literal ` ` entities are converted to spaces before encoding because
|
||||
* they are not valid predefined XML entities. URI encoding is converted to a
|
||||
* byte string before `btoa()` so non-Latin text remains UTF-8 safe.
|
||||
*/
|
||||
export function svgToBase64(svg: string): string {
|
||||
const cleanSvg = svg.replaceAll(" ", " ");
|
||||
const encodedData = encodeURIComponent(cleanSvg).replace(
|
||||
/%([0-9A-F]{2})/g,
|
||||
(_match, p1) => String.fromCharCode(parseInt(p1, 16)),
|
||||
(_match: string, hexByte: string) =>
|
||||
String.fromCharCode(parseInt(hexByte, 16)),
|
||||
);
|
||||
return `data:image/svg+xml;base64,${btoa(encodedData)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads an image source and reports its intrinsic dimensions.
|
||||
*
|
||||
* @param src - Image URL, blob URL, or data URL accepted by `HTMLImageElement`.
|
||||
* @returns The image's natural width and height after it loads.
|
||||
* @throws Rejects with the browser image error when loading fails.
|
||||
* @remarks
|
||||
* This intentionally preserves native image loading behavior without adding a
|
||||
* timeout, cross-origin mode, or rendered-size fallback.
|
||||
*/
|
||||
export async function getImageSize(
|
||||
src: string,
|
||||
): Promise<{ height: number; width: number }> {
|
||||
@@ -168,6 +202,18 @@ export function getExportPadding(
|
||||
return plugin.settings.exportPaddingSVG;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a rectangular canvas region into a new canvas, optionally scaling it.
|
||||
* Based on: https://stackoverflow.com/a/54555834
|
||||
*
|
||||
* @param srcCanvas - Source canvas to crop.
|
||||
* @param crop - Source rectangle in canvas coordinates.
|
||||
* @param output - Destination dimensions; defaults to the crop dimensions.
|
||||
* @returns A newly created canvas containing the cropped image.
|
||||
* @remarks
|
||||
* This preserves the existing `drawImage()` behavior without clamping the
|
||||
* source rectangle or changing browser interpolation and transparency rules.
|
||||
*/
|
||||
export function cropCanvas(
|
||||
srcCanvas: HTMLCanvasElement,
|
||||
crop: { left: number; top: number; width: number; height: number },
|
||||
@@ -195,6 +241,14 @@ export function cropCanvas(
|
||||
return dstCanvas;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a synchronous or asynchronous function through a promise boundary.
|
||||
*
|
||||
* @param fn - Function to invoke.
|
||||
* @param args - Arguments passed to `fn`.
|
||||
* @returns A promise that adopts the function's returned value or thenable.
|
||||
* @remarks Synchronous exceptions thrown by `fn` become promise rejections.
|
||||
*/
|
||||
export async function promiseTry<TValue, TArgs extends unknown[]>(
|
||||
fn: (...args: TArgs) => PromiseLike<TValue> | TValue,
|
||||
...args: TArgs
|
||||
|
||||
@@ -18,9 +18,7 @@ import { normalizePath, TFile } from "obsidian";
|
||||
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import {
|
||||
getCommonBoundingBox,
|
||||
IMAGE_TYPES,
|
||||
restoreElements,
|
||||
REG_LINKINDEX_INVALIDCHARS,
|
||||
THEME_FILTER,
|
||||
EXCALIDRAW_PLUGIN,
|
||||
@@ -60,6 +58,14 @@ import { ColorMap, FileData } from "src/types/embeddedFileLoaderTypes";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import type { StrokeWidthKey } from "@zsviczian/excalidraw/types/common/src/constants";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { cloneElement } from "./excalidrawElementUtils";
|
||||
|
||||
export {
|
||||
cloneElement,
|
||||
estimateBounds,
|
||||
getBoundTextElementId,
|
||||
repositionElementsToCursor,
|
||||
} from "./excalidrawElementUtils";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
|
||||
@@ -811,40 +817,6 @@ function estimateLineBound(
|
||||
return [minX, minY, maxX, maxY];
|
||||
}
|
||||
|
||||
export function estimateBounds(
|
||||
elements: ExcalidrawElement[],
|
||||
): [number, number, number, number] {
|
||||
const bb = getCommonBoundingBox(elements);
|
||||
return [bb.minX, bb.minY, bb.maxX, bb.maxY];
|
||||
}
|
||||
|
||||
export function repositionElementsToCursor(
|
||||
elements: ExcalidrawElement[],
|
||||
newPosition: { x: number; y: number },
|
||||
center: boolean = false,
|
||||
): ExcalidrawElement[] {
|
||||
const [x1, y1, x2, y2] = estimateBounds(elements);
|
||||
let [offsetX, offsetY] = [0, 0];
|
||||
if (center) {
|
||||
[offsetX, offsetY] = [
|
||||
newPosition.x - (x1 + x2) / 2,
|
||||
newPosition.y - (y1 + y2) / 2,
|
||||
];
|
||||
} else {
|
||||
[offsetX, offsetY] = [newPosition.x - x1, newPosition.y - y1];
|
||||
}
|
||||
|
||||
elements.forEach((element: Mutable<ExcalidrawElement>) => {
|
||||
element.x = element.x + offsetX;
|
||||
element.y = element.y + offsetY;
|
||||
});
|
||||
|
||||
return restoreElements(elements, null, {
|
||||
refreshDimensions: true,
|
||||
repairBindings: true,
|
||||
});
|
||||
}
|
||||
|
||||
export const search = async (view: ExcalidrawView) => {
|
||||
const ea = view.plugin.ea;
|
||||
ea.reset();
|
||||
@@ -1029,16 +1001,6 @@ export const getImagesMatchingQuery = (
|
||||
);
|
||||
};
|
||||
|
||||
export const cloneElement = (
|
||||
el: ExcalidrawElement,
|
||||
): Mutable<ExcalidrawElement> => {
|
||||
const newEl = JSON.parse(JSON.stringify(el)) as Mutable<ExcalidrawElement>;
|
||||
newEl.version = el.version + 1;
|
||||
newEl.updated = Date.now();
|
||||
newEl.versionNonce = Math.floor(Math.random() * 1000000000);
|
||||
return newEl;
|
||||
};
|
||||
|
||||
export const verifyMinimumPluginVersion = (
|
||||
requiredVersion: string,
|
||||
): boolean => {
|
||||
@@ -1048,12 +1010,6 @@ export const verifyMinimumPluginVersion = (
|
||||
);
|
||||
};
|
||||
|
||||
export const getBoundTextElementId = (container: ExcalidrawElement | null) => {
|
||||
return container?.boundElements?.length
|
||||
? container?.boundElements?.find((ele) => ele.type === "text")?.id || null
|
||||
: null;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* FixedPoint represents the fixed point binding information in form of a vertical and
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { getCommonBoundingBox, restoreElements } from "src/constants/constants";
|
||||
|
||||
/**
|
||||
* Calculates the axis-aligned bounds shared by a collection of elements.
|
||||
*
|
||||
* @param elements - Elements whose bounds should be measured.
|
||||
* @returns The minimum and maximum coordinates as `[minX, minY, maxX, maxY]`.
|
||||
*/
|
||||
export function estimateBounds(
|
||||
elements: ExcalidrawElement[],
|
||||
): [number, number, number, number] {
|
||||
const bb = getCommonBoundingBox(elements);
|
||||
return [bb.minX, bb.minY, bb.maxX, bb.maxY];
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves elements so their top-left corner or center is at a scene position.
|
||||
*
|
||||
* @param elements - Elements to reposition. Their coordinates are mutated.
|
||||
* @param newPosition - Target scene position.
|
||||
* @param center - Whether to align the combined center instead of the top-left.
|
||||
* @returns Restored elements with dimensions refreshed and bindings repaired.
|
||||
*/
|
||||
export function repositionElementsToCursor(
|
||||
elements: ExcalidrawElement[],
|
||||
newPosition: { x: number; y: number },
|
||||
center: boolean = false,
|
||||
): ExcalidrawElement[] {
|
||||
const [x1, y1, x2, y2] = estimateBounds(elements);
|
||||
let [offsetX, offsetY] = [0, 0];
|
||||
if (center) {
|
||||
[offsetX, offsetY] = [
|
||||
newPosition.x - (x1 + x2) / 2,
|
||||
newPosition.y - (y1 + y2) / 2,
|
||||
];
|
||||
} else {
|
||||
[offsetX, offsetY] = [newPosition.x - x1, newPosition.y - y1];
|
||||
}
|
||||
|
||||
elements.forEach((element: Mutable<ExcalidrawElement>) => {
|
||||
element.x = element.x + offsetX;
|
||||
element.y = element.y + offsetY;
|
||||
});
|
||||
|
||||
return restoreElements(elements, null, {
|
||||
refreshDimensions: true,
|
||||
repairBindings: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deep-clones an element while advancing its Excalidraw version metadata.
|
||||
*
|
||||
* @param element - Element to clone.
|
||||
* @returns A mutable clone with the same ID and refreshed version metadata.
|
||||
* @remarks This internal helper does not assign a new element ID.
|
||||
*/
|
||||
export function cloneElement(
|
||||
element: ExcalidrawElement,
|
||||
): Mutable<ExcalidrawElement> {
|
||||
const clone = JSON.parse(
|
||||
JSON.stringify(element),
|
||||
) as Mutable<ExcalidrawElement>;
|
||||
clone.version = element.version + 1;
|
||||
clone.updated = Date.now();
|
||||
clone.versionNonce = Math.floor(Math.random() * 1000000000);
|
||||
return clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the ID of the first text element bound to a container.
|
||||
*
|
||||
* @param container - Container element, or `null` when none is available.
|
||||
* @returns The bound text element ID, or `null` when no text is bound.
|
||||
*/
|
||||
export function getBoundTextElementId(
|
||||
container: ExcalidrawElement | null,
|
||||
): string | null {
|
||||
return container?.boundElements?.length
|
||||
? container.boundElements.find((element) => element.type === "text")?.id ||
|
||||
null
|
||||
: null;
|
||||
}
|
||||
@@ -1,63 +1,16 @@
|
||||
import type {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawImageElement,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import type { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { getCommonBoundingBox, restoreElements } from "src/constants/constants";
|
||||
import { getEA } from "src/core";
|
||||
import { t } from "src/lang/helpers";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { errorlog } from "./utils";
|
||||
|
||||
function estimateBounds(
|
||||
elements: ExcalidrawElement[],
|
||||
): [number, number, number, number] {
|
||||
const bb = getCommonBoundingBox(elements);
|
||||
return [bb.minX, bb.minY, bb.maxX, bb.maxY];
|
||||
}
|
||||
|
||||
export function repositionElementsToCursor(
|
||||
elements: ExcalidrawElement[],
|
||||
newPosition: { x: number; y: number },
|
||||
center: boolean = false,
|
||||
): ExcalidrawElement[] {
|
||||
const [x1, y1, x2, y2] = estimateBounds(elements);
|
||||
let [offsetX, offsetY] = [0, 0];
|
||||
if (center) {
|
||||
[offsetX, offsetY] = [
|
||||
newPosition.x - (x1 + x2) / 2,
|
||||
newPosition.y - (y1 + y2) / 2,
|
||||
];
|
||||
} else {
|
||||
[offsetX, offsetY] = [newPosition.x - x1, newPosition.y - y1];
|
||||
}
|
||||
|
||||
elements.forEach((element: Mutable<ExcalidrawElement>) => {
|
||||
element.x = element.x + offsetX;
|
||||
element.y = element.y + offsetY;
|
||||
});
|
||||
|
||||
return restoreElements(elements, null, {
|
||||
refreshDimensions: true,
|
||||
repairBindings: true,
|
||||
});
|
||||
}
|
||||
|
||||
export const cloneElement = (
|
||||
el: ExcalidrawElement,
|
||||
): Mutable<ExcalidrawElement> => {
|
||||
const newEl = JSON.parse(JSON.stringify(el)) as Mutable<ExcalidrawElement>;
|
||||
newEl.version = el.version + 1;
|
||||
newEl.updated = Date.now();
|
||||
newEl.versionNonce = Math.floor(Math.random() * 1000000000);
|
||||
return newEl;
|
||||
};
|
||||
|
||||
export const getBoundTextElementId = (container: ExcalidrawElement | null) => {
|
||||
return container?.boundElements?.length
|
||||
? container.boundElements.find((ele) => ele.type === "text")?.id || null
|
||||
: null;
|
||||
};
|
||||
export {
|
||||
cloneElement,
|
||||
getBoundTextElementId,
|
||||
repositionElementsToCursor,
|
||||
} from "./excalidrawElementUtils";
|
||||
|
||||
export const insertLaTeXToView = (
|
||||
view: ExcalidrawView,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
+36
-1
@@ -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,
|
||||
@@ -286,6 +286,41 @@ export const getDataURLFromURL = async (
|
||||
: (url as DataURL);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decodes a base64 data URL into binary data, fetching remote URLs first.
|
||||
*
|
||||
* @param dataURL - A base64 data URL or an HTTP, HTTPS, or FTP URL.
|
||||
* @returns The decoded bytes, or `null` when the input cannot be resolved to a
|
||||
* base64 payload.
|
||||
* @remarks
|
||||
* Remote URL handling intentionally preserves the existing MIME inference and
|
||||
* `getDataURLFromURL()` fallback behavior used on desktop and mobile.
|
||||
*/
|
||||
export async function getBinaryFileFromDataURL(
|
||||
dataURL: string,
|
||||
): Promise<ArrayBuffer> {
|
||||
if (!dataURL) {
|
||||
return null;
|
||||
}
|
||||
if (dataURL.match(/^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i)) {
|
||||
const hyperlink = dataURL;
|
||||
const extension = getURLImageExtension(hyperlink);
|
||||
const mimeType = getMimeType(extension);
|
||||
dataURL = await getDataURLFromURL(hyperlink, mimeType);
|
||||
}
|
||||
const base64Match = dataURL.match(/base64,(.*)/);
|
||||
if (!base64Match) {
|
||||
return null;
|
||||
}
|
||||
const binaryString = window.atob(base64Match[1]);
|
||||
const len = binaryString.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
export const blobToBase64 = async (blob: Blob): Promise<string> => {
|
||||
const arrayBuffer = await blob.arrayBuffer();
|
||||
const bytes = new Uint8Array(arrayBuffer);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { TFile } from "obsidian";
|
||||
import { cleanBlockRef, cleanSectionHeading } from "./pathUtils";
|
||||
|
||||
/** Parsed components of an Obsidian drawing or embedded-file link. */
|
||||
export type LinkParts = {
|
||||
original: string;
|
||||
path: string;
|
||||
isBlockRef: boolean;
|
||||
ref: string;
|
||||
width: number;
|
||||
height: number;
|
||||
page: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Splits a drawing or embedded-file link into its path, reference, dimensions,
|
||||
* and optional PDF page.
|
||||
*
|
||||
* @param filename - Link text to parse.
|
||||
* @param file - Current file, used when the link omits its path.
|
||||
* @returns Parsed link components with cleaned heading or block references.
|
||||
* @remarks
|
||||
* This preserves the existing permissive regular-expression parser. It is not
|
||||
* a general-purpose Obsidian link parser and intentionally retains its current
|
||||
* handling of malformed or partially specified links.
|
||||
*/
|
||||
export function getLinkParts(filename: string, file?: TFile): LinkParts {
|
||||
const linkPattern = /(^[^#|]*)#?(\^)?([^|]*)?\|?(\d*)x?(\d*)/;
|
||||
const parts = filename.match(linkPattern);
|
||||
const isBlockRef = parts[2] === "^";
|
||||
let page = parseInt(parts[3]?.match(/page=(\d*)/)?.[1]);
|
||||
page = isNaN(page) ? null : page;
|
||||
return {
|
||||
original: filename,
|
||||
path: file && parts[1] === "" ? file.path : parts[1],
|
||||
isBlockRef,
|
||||
ref: parts[3]?.match(/^page=\d*$/i)
|
||||
? parts[3]
|
||||
: isBlockRef
|
||||
? cleanBlockRef(parts[3])
|
||||
: cleanSectionHeading(parts[3]),
|
||||
width: parts[4] ? parseInt(parts[4]) : undefined,
|
||||
height: parts[5] ? parseInt(parts[5]) : undefined,
|
||||
page,
|
||||
};
|
||||
}
|
||||
+17
-145
@@ -7,108 +7,15 @@ import type { TFile } from "obsidian";
|
||||
import { FRONTMATTER_KEYS, getContainerElement } from "src/constants/constants";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import LZString from "lz-string";
|
||||
import {
|
||||
getDataURLFromURL,
|
||||
getMimeType,
|
||||
getURLImageExtension,
|
||||
} from "./fileUtils";
|
||||
import { cleanBlockRef, cleanSectionHeading } from "./pathUtils";
|
||||
import { runCompressionWorker } from "src/shared/Workers/compression-worker";
|
||||
import { arrayToMap } from "./collectionUtils";
|
||||
|
||||
export function wrapTextAtCharLength(
|
||||
text: string,
|
||||
lineLen: number,
|
||||
forceWrap: boolean = false,
|
||||
tolerance: number = 0,
|
||||
): string {
|
||||
if (!lineLen) {
|
||||
return text;
|
||||
}
|
||||
let outstring = "";
|
||||
if (forceWrap) {
|
||||
for (const t of text.split("\n")) {
|
||||
const v = t.match(new RegExp(`(.){1,${lineLen}}`, "g"));
|
||||
outstring += v ? `${v.join("\n")}\n` : "\n";
|
||||
}
|
||||
return outstring.replace(/\n$/, "");
|
||||
}
|
||||
|
||||
const reg = new RegExp(
|
||||
`(.{1,${lineLen}})(\\s+|$\\n?)|([^\\s]{1,${lineLen + tolerance}})(\\s+|$\\n?)?`,
|
||||
"gm",
|
||||
);
|
||||
const res = text.matchAll(reg);
|
||||
let parts;
|
||||
while (!(parts = res.next()).done) {
|
||||
outstring += parts.value[1]
|
||||
? parts.value[1].trimEnd()
|
||||
: parts.value[3].trimEnd();
|
||||
const newLine =
|
||||
(parts.value[2] ? parts.value[2].split("\n").length - 1 : 0) +
|
||||
(parts.value[4] ? parts.value[4].split("\n").length - 1 : 0);
|
||||
outstring += "\n".repeat(newLine);
|
||||
if (newLine === 0) {
|
||||
outstring += "\n";
|
||||
}
|
||||
}
|
||||
return outstring.replace(/\n$/, "");
|
||||
}
|
||||
|
||||
export async function getBinaryFileFromDataURL(
|
||||
dataURL: string,
|
||||
): Promise<ArrayBuffer> {
|
||||
if (!dataURL) {
|
||||
return null;
|
||||
}
|
||||
if (dataURL.match(/^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i)) {
|
||||
const hyperlink = dataURL;
|
||||
const extension = getURLImageExtension(hyperlink);
|
||||
const mimeType = getMimeType(extension);
|
||||
dataURL = await getDataURLFromURL(hyperlink, mimeType);
|
||||
}
|
||||
const parts = dataURL.matchAll(/base64,(.*)/g).next();
|
||||
if (!parts.value) {
|
||||
return null;
|
||||
}
|
||||
const binaryString = window.atob(parts.value[1]);
|
||||
const len = binaryString.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
export type LinkParts = {
|
||||
original: string;
|
||||
path: string;
|
||||
isBlockRef: boolean;
|
||||
ref: string;
|
||||
width: number;
|
||||
height: number;
|
||||
page: number;
|
||||
};
|
||||
|
||||
export function getLinkParts(fname: string, file?: TFile): LinkParts {
|
||||
const reg = /(^[^#|]*)#?(\^)?([^|]*)?\|?(\d*)x?(\d*)/;
|
||||
const parts = fname.match(reg);
|
||||
const isBlockRef = parts[2] === "^";
|
||||
let page = parseInt(parts[3]?.match(/page=(\d*)/)?.[1]);
|
||||
page = isNaN(page) ? null : page;
|
||||
return {
|
||||
original: fname,
|
||||
path: file && parts[1] === "" ? file.path : parts[1],
|
||||
isBlockRef,
|
||||
ref: parts[3]?.match(/^page=\d*$/i)
|
||||
? parts[3]
|
||||
: isBlockRef
|
||||
? cleanBlockRef(parts[3])
|
||||
: cleanSectionHeading(parts[3]),
|
||||
width: parts[4] ? parseInt(parts[4]) : undefined,
|
||||
height: parts[5] ? parseInt(parts[5]) : undefined,
|
||||
page,
|
||||
};
|
||||
}
|
||||
export { arrayToMap };
|
||||
export { getBinaryFileFromDataURL } from "./fileUtils";
|
||||
export { getLinkParts } from "./linkUtils";
|
||||
export type { LinkParts } from "./linkUtils";
|
||||
export { wrapTextAtCharLength } from "./textUtils";
|
||||
export { isVersionNewerThanOther } from "./versionUtils";
|
||||
|
||||
export async function compressAsync(data: string): Promise<string> {
|
||||
return await runCompressionWorker(data, "compress");
|
||||
@@ -179,52 +86,17 @@ export function getExportTheme(
|
||||
return plugin.settings.exportWithTheme ? theme : "light";
|
||||
}
|
||||
|
||||
export function isVersionNewerThanOther(
|
||||
version: string,
|
||||
otherVersion: string,
|
||||
): boolean {
|
||||
if (!version || !otherVersion) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const v = version.match(/(\d*)\.(\d*)\.(\d*)/);
|
||||
const o = otherVersion.match(/(\d*)\.(\d*)\.(\d*)/);
|
||||
|
||||
return Boolean(
|
||||
v &&
|
||||
v.length === 4 &&
|
||||
o &&
|
||||
o.length === 4 &&
|
||||
!(
|
||||
isNaN(parseInt(v[1])) ||
|
||||
isNaN(parseInt(v[2])) ||
|
||||
isNaN(parseInt(v[3]))
|
||||
) &&
|
||||
!(
|
||||
isNaN(parseInt(o[1])) ||
|
||||
isNaN(parseInt(o[2])) ||
|
||||
isNaN(parseInt(o[3]))
|
||||
) &&
|
||||
(parseInt(v[1]) > parseInt(o[1]) ||
|
||||
(parseInt(v[1]) >= parseInt(o[1]) && parseInt(v[2]) > parseInt(o[2])) ||
|
||||
(parseInt(v[1]) >= parseInt(o[1]) &&
|
||||
parseInt(v[2]) >= parseInt(o[2]) &&
|
||||
parseInt(v[3]) > parseInt(o[3]))),
|
||||
);
|
||||
}
|
||||
|
||||
export function arrayToMap<T extends { id: string } | string>(
|
||||
items: readonly T[] | Map<string, T>,
|
||||
) {
|
||||
if (items instanceof Map) {
|
||||
return items;
|
||||
}
|
||||
return items.reduce((acc: Map<string, T>, element) => {
|
||||
acc.set(typeof element === "string" ? element : element.id, element);
|
||||
return acc;
|
||||
}, new Map());
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates or inserts simple, single-line properties in serialized frontmatter.
|
||||
*
|
||||
* @param data - Markdown text whose frontmatter should be updated.
|
||||
* @param keyValuePairs - Property names and serialized values to apply.
|
||||
* @returns The updated text, or the original text when there is nothing to do.
|
||||
* @remarks
|
||||
* This intentionally preserves the existing string-based behavior: it does not
|
||||
* parse YAML, and insertion requires an opening `---` followed by a newline.
|
||||
*/
|
||||
export function updateFrontmatterInString(
|
||||
data: string,
|
||||
keyValuePairs?: [string, string][],
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Wraps text at an approximate character length while preserving line breaks.
|
||||
*
|
||||
* @param text - Text to wrap.
|
||||
* @param lineLen - Target line length. A falsy value disables wrapping.
|
||||
* @param forceWrap - Whether to split every input line into fixed-size chunks.
|
||||
* @param tolerance - Extra characters allowed for an unbroken word.
|
||||
* @returns The wrapped text without an additional trailing newline.
|
||||
*/
|
||||
export function wrapTextAtCharLength(
|
||||
text: string,
|
||||
lineLen: number,
|
||||
forceWrap: boolean = false,
|
||||
tolerance: number = 0,
|
||||
): string {
|
||||
if (!lineLen) {
|
||||
return text;
|
||||
}
|
||||
let outstring = "";
|
||||
if (forceWrap) {
|
||||
for (const inputLine of text.split("\n")) {
|
||||
const chunks = inputLine.match(new RegExp(`(.){1,${lineLen}}`, "g"));
|
||||
outstring += chunks ? `${chunks.join("\n")}\n` : "\n";
|
||||
}
|
||||
return outstring.replace(/\n$/, "");
|
||||
}
|
||||
|
||||
const wrappingPattern = new RegExp(
|
||||
`(.{1,${lineLen}})(\\s+|$\\n?)|([^\\s]{1,${lineLen + tolerance}})(\\s+|$\\n?)?`,
|
||||
"gm",
|
||||
);
|
||||
for (const match of text.matchAll(wrappingPattern)) {
|
||||
outstring += match[1] ? match[1].trimEnd() : match[3].trimEnd();
|
||||
const newLineCount =
|
||||
(match[2] ? match[2].split("\n").length - 1 : 0) +
|
||||
(match[4] ? match[4].split("\n").length - 1 : 0);
|
||||
outstring += "\n".repeat(newLineCount);
|
||||
if (newLineCount === 0) {
|
||||
outstring += "\n";
|
||||
}
|
||||
}
|
||||
return outstring.replace(/\n$/, "");
|
||||
}
|
||||
+16
-284
@@ -6,7 +6,7 @@ import {
|
||||
BinaryFiles,
|
||||
NormalizedZoomValue,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { errorlog, getDataURL } from "./coreUtils";
|
||||
import { errorlog } from "./coreUtils";
|
||||
import {
|
||||
exportToSvg,
|
||||
exportToBlob,
|
||||
@@ -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,
|
||||
@@ -27,20 +27,16 @@ import {
|
||||
ImageCrop,
|
||||
NonDeletedExcalidrawElement,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import {
|
||||
getDataURLFromURL,
|
||||
getIMGFilename,
|
||||
getMimeType,
|
||||
getURLImageExtension,
|
||||
} from "./fileUtils";
|
||||
import { getIMGFilename } from "./fileUtils";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import {
|
||||
getExcalidrawViews,
|
||||
getFileCSSClasses,
|
||||
getSafeFrontmatter,
|
||||
} from "./obsidianUtils";
|
||||
import { cleanBlockRef, cleanSectionHeading } from "./pathUtils";
|
||||
import { addAppendUpdateCustomData } from "./elementCustomDataUtils";
|
||||
import { arrayToMap } from "./collectionUtils";
|
||||
import { isVersionNewerThanOther } from "./versionUtils";
|
||||
import { updateElementLinksToObsidianLinks } from "./excalidrawAutomateUtils";
|
||||
import { CropImage } from "../shared/CropImage";
|
||||
import opentype from "opentype.js";
|
||||
@@ -58,8 +54,19 @@ import { getEmptyDrawingElementsRuntime } from "src/constants/emptydrawing";
|
||||
import { makeEntitiesXmlSafe, sanitizedFragment } from "./htmlUtils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { isInstanceOfSVGSVGElement } from "./typechecks";
|
||||
export { arrayToMap };
|
||||
export { errorlog, getDataURL } from "./coreUtils";
|
||||
export { addAppendUpdateCustomData } from "./elementCustomDataUtils";
|
||||
export { getBinaryFileFromDataURL } from "./fileUtils";
|
||||
export { cropCanvas } from "./embeddedAssetUtils";
|
||||
export { getFontDataURL } from "./embeddedAssetUtils";
|
||||
export { getImageSize } from "./embeddedAssetUtils";
|
||||
export { promiseTry } from "./embeddedAssetUtils";
|
||||
export { getLinkParts } from "./linkUtils";
|
||||
export type { LinkParts } from "./linkUtils";
|
||||
export { svgToBase64 } from "./embeddedAssetUtils";
|
||||
export { wrapTextAtCharLength } from "./textUtils";
|
||||
export { isVersionNewerThanOther };
|
||||
export {
|
||||
getEmbeddedFilenameParts,
|
||||
isImagePartRef,
|
||||
@@ -206,50 +213,6 @@ export function randomInteger() {
|
||||
return Math.floor(random.next() * 2 ** 31);
|
||||
}
|
||||
|
||||
//https://macromates.com/blog/2006/wrapping-text-with-regular-expressions/
|
||||
export function wrapTextAtCharLength(
|
||||
text: string,
|
||||
lineLen: number,
|
||||
forceWrap: boolean = false,
|
||||
tolerance: number = 0,
|
||||
): string {
|
||||
if (!lineLen) {
|
||||
return text;
|
||||
}
|
||||
let outstring = "";
|
||||
if (forceWrap) {
|
||||
for (const t of text.split("\n")) {
|
||||
const v = t.match(new RegExp(`(.){1,${lineLen}}`, "g"));
|
||||
outstring += v ? `${v.join("\n")}\n` : "\n";
|
||||
}
|
||||
return outstring.replace(/\n$/, "");
|
||||
}
|
||||
|
||||
// 1 2 3 4
|
||||
const reg = new RegExp(
|
||||
`(.{1,${lineLen}})(\\s+|$\\n?)|([^\\s]{1,${
|
||||
lineLen + tolerance
|
||||
}})(\\s+|$\\n?)?`,
|
||||
//`(.{1,${lineLen}})(\\s+|$\\n?)|([^\\s]+)(\\s+|$\\n?)`,
|
||||
"gm",
|
||||
);
|
||||
const res = text.matchAll(reg);
|
||||
let parts;
|
||||
while (!(parts = res.next()).done) {
|
||||
outstring += parts.value[1]
|
||||
? parts.value[1].trimEnd()
|
||||
: parts.value[3].trimEnd();
|
||||
const newLine =
|
||||
(parts.value[2] ? parts.value[2].split("\n").length - 1 : 0) +
|
||||
(parts.value[4] ? parts.value[4].split("\n").length - 1 : 0);
|
||||
outstring += "\n".repeat(newLine);
|
||||
if (newLine === 0) {
|
||||
outstring += "\n";
|
||||
}
|
||||
}
|
||||
return outstring.replace(/\n$/, "");
|
||||
}
|
||||
|
||||
export function rotatedDimensions(
|
||||
element: ExcalidrawElement,
|
||||
): [number, number, number, number] {
|
||||
@@ -257,50 +220,6 @@ export function rotatedDimensions(
|
||||
return [bb.minX, bb.minY, bb.maxX - bb.minX, bb.maxY - bb.minY];
|
||||
}
|
||||
|
||||
export async function getFontDataURL(
|
||||
app: App,
|
||||
fontFileName: string,
|
||||
sourcePath: string,
|
||||
name?: string,
|
||||
): Promise<{ fontDef: string; fontName: string; dataURL: string }> {
|
||||
let fontDef: string = "";
|
||||
let fontName = "";
|
||||
let dataURL = "";
|
||||
const f = app.metadataCache.getFirstLinkpathDest(fontFileName, sourcePath);
|
||||
if (f) {
|
||||
const ab = await app.vault.readBinary(f);
|
||||
let mimeType = "";
|
||||
let format = "";
|
||||
|
||||
switch (f.extension) {
|
||||
case "woff":
|
||||
mimeType = "application/font-woff";
|
||||
format = "woff";
|
||||
break;
|
||||
case "woff2":
|
||||
mimeType = "font/woff2";
|
||||
format = "woff2";
|
||||
break;
|
||||
case "ttf":
|
||||
mimeType = "font/ttf";
|
||||
format = "truetype";
|
||||
break;
|
||||
case "otf":
|
||||
mimeType = "font/otf";
|
||||
format = "opentype";
|
||||
break;
|
||||
default:
|
||||
mimeType = "application/octet-stream"; // Fallback if file type is unexpected
|
||||
}
|
||||
fontName = name ?? f.basename;
|
||||
dataURL = await getDataURL(ab, mimeType);
|
||||
const split = dataURL.split(";base64,", 2);
|
||||
dataURL = `${split[0]};charset=utf-8;base64,${split[1]}`;
|
||||
fontDef = ` @font-face {font-family: "${fontName}";src: url("${dataURL}") format("${format}")}`;
|
||||
}
|
||||
return { fontDef, fontName, dataURL };
|
||||
}
|
||||
|
||||
export function base64StringToBlob(
|
||||
base64String: string,
|
||||
mimeType: string,
|
||||
@@ -309,43 +228,6 @@ export function base64StringToBlob(
|
||||
return new Blob([buffer], { type: mimeType });
|
||||
}
|
||||
|
||||
export function svgToBase64(svg: string): string {
|
||||
const cleanSvg = svg.replaceAll(" ", " ");
|
||||
|
||||
// Convert the string to UTF-8 and handle non-Latin1 characters
|
||||
const encodedData = encodeURIComponent(cleanSvg).replace(
|
||||
/%([0-9A-F]{2})/g,
|
||||
(match, p1) => String.fromCharCode(parseInt(p1, 16)),
|
||||
);
|
||||
|
||||
return `data:image/svg+xml;base64,${btoa(encodedData)}`;
|
||||
}
|
||||
|
||||
export async function getBinaryFileFromDataURL(
|
||||
dataURL: string,
|
||||
): Promise<ArrayBuffer> {
|
||||
if (!dataURL) {
|
||||
return null;
|
||||
}
|
||||
if (dataURL.match(/^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i)) {
|
||||
const hyperlink = dataURL;
|
||||
const extension = getURLImageExtension(hyperlink);
|
||||
const mimeType = getMimeType(extension);
|
||||
dataURL = await getDataURLFromURL(hyperlink, mimeType);
|
||||
}
|
||||
const parts = dataURL.matchAll(/base64,(.*)/g).next();
|
||||
if (!parts.value) {
|
||||
return null;
|
||||
}
|
||||
const binary_string = window.atob(parts.value[1]);
|
||||
const len = binary_string.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binary_string.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports an Excalidraw scene to SVG.
|
||||
*
|
||||
@@ -546,20 +428,6 @@ export async function getQuickImagePreview(
|
||||
}
|
||||
}
|
||||
|
||||
export async function getImageSize(
|
||||
src: string,
|
||||
): Promise<{ height: number; width: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
//console.log({ height: img.naturalHeight, width: img.naturalWidth, img});
|
||||
resolve({ height: img.naturalHeight, width: img.naturalWidth });
|
||||
};
|
||||
img.onerror = reject;
|
||||
img.src = src;
|
||||
});
|
||||
}
|
||||
|
||||
export function scaleLoadedImage<T extends SceneWithElements>(
|
||||
scene: T,
|
||||
files: FileData[],
|
||||
@@ -747,38 +615,6 @@ export function setUIMode(app: App, settings: ExcalidrawSettings) {
|
||||
);
|
||||
}
|
||||
|
||||
export type LinkParts = {
|
||||
original: string;
|
||||
path: string;
|
||||
isBlockRef: boolean;
|
||||
ref: string;
|
||||
width: number;
|
||||
height: number;
|
||||
page: number;
|
||||
};
|
||||
|
||||
export function getLinkParts(fname: string, file?: TFile): LinkParts {
|
||||
// 1 2 3 4 5
|
||||
const REG = /(^[^#|]*)#?(\^)?([^|]*)?\|?(\d*)x?(\d*)/;
|
||||
const parts = fname.match(REG);
|
||||
const isBlockRef = parts[2] === "^";
|
||||
let page = parseInt(parts[3]?.match(/page=(\d*)/)?.[1]);
|
||||
page = isNaN(page) ? null : page;
|
||||
return {
|
||||
original: fname,
|
||||
path: file && parts[1] === "" ? file.path : parts[1],
|
||||
isBlockRef,
|
||||
ref: parts[3]?.match(/^page=\d*$/i)
|
||||
? parts[3]
|
||||
: isBlockRef
|
||||
? cleanBlockRef(parts[3])
|
||||
: cleanSectionHeading(parts[3]),
|
||||
width: parts[4] ? parseInt(parts[4]) : undefined,
|
||||
height: parts[5] ? parseInt(parts[5]) : undefined,
|
||||
page,
|
||||
};
|
||||
}
|
||||
|
||||
export function isMaskFile(
|
||||
plugin: ExcalidrawPlugin,
|
||||
file: TFile | null,
|
||||
@@ -976,40 +812,6 @@ export function getPNGScale(
|
||||
return plugin.settings.pngExportScale as NormalizedZoomValue;
|
||||
}
|
||||
|
||||
export function isVersionNewerThanOther(
|
||||
version: string,
|
||||
otherVersion: string,
|
||||
): boolean {
|
||||
if (!version || !otherVersion) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const v = version.match(/(\d*)\.(\d*)\.(\d*)/);
|
||||
const o = otherVersion.match(/(\d*)\.(\d*)\.(\d*)/);
|
||||
|
||||
return Boolean(
|
||||
v &&
|
||||
v.length === 4 &&
|
||||
o &&
|
||||
o.length === 4 &&
|
||||
!(
|
||||
isNaN(parseInt(v[1])) ||
|
||||
isNaN(parseInt(v[2])) ||
|
||||
isNaN(parseInt(v[3]))
|
||||
) &&
|
||||
!(
|
||||
isNaN(parseInt(o[1])) ||
|
||||
isNaN(parseInt(o[2])) ||
|
||||
isNaN(parseInt(o[3]))
|
||||
) &&
|
||||
(parseInt(v[1]) > parseInt(o[1]) ||
|
||||
(parseInt(v[1]) >= parseInt(o[1]) && parseInt(v[2]) > parseInt(o[2])) ||
|
||||
(parseInt(v[1]) >= parseInt(o[1]) &&
|
||||
parseInt(v[2]) >= parseInt(o[2]) &&
|
||||
parseInt(v[3]) > parseInt(o[3]))),
|
||||
);
|
||||
}
|
||||
|
||||
export function fragWithHTML(html: string) {
|
||||
return createFragment((frag) => frag.appendChild(sanitizedFragment(html)));
|
||||
}
|
||||
@@ -1041,38 +843,6 @@ export function _getContainerElement(
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms array of objects containing `id` attribute,
|
||||
* or array of ids (strings), into a Map, keyd by `id`.
|
||||
*/
|
||||
export function arrayToMap<T extends { id: string } | string>(
|
||||
items: readonly T[] | Map<string, T>,
|
||||
) {
|
||||
if (items instanceof Map) {
|
||||
return items;
|
||||
}
|
||||
return items.reduce((acc: Map<string, T>, element) => {
|
||||
acc.set(typeof element === "string" ? element : element.id, element);
|
||||
return acc;
|
||||
}, new Map());
|
||||
}
|
||||
|
||||
export function updateFrontmatterInString(
|
||||
data: string,
|
||||
keyValuePairs?: [string, string][],
|
||||
): string {
|
||||
if (!data || !keyValuePairs) {
|
||||
return data;
|
||||
}
|
||||
for (const kvp of keyValuePairs) {
|
||||
const r = new RegExp(`${kvp[0]}:\\s.*\\n`, "g");
|
||||
data = data.match(r)
|
||||
? data.replaceAll(r, `${kvp[0]}: ${kvp[1]}\n`)
|
||||
: data.replace(/^---\n/, `---\n${kvp[0]}: ${kvp[1]}\n`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function isHyperLink(link: string) {
|
||||
return (
|
||||
link &&
|
||||
@@ -1293,44 +1063,6 @@ export async function getFontMetrics(
|
||||
}
|
||||
}
|
||||
|
||||
// Thanks https://stackoverflow.com/a/54555834
|
||||
export function cropCanvas(
|
||||
srcCanvas: HTMLCanvasElement,
|
||||
crop: { left: number; top: number; width: number; height: number },
|
||||
output: { width: number; height: number } = {
|
||||
width: crop.width,
|
||||
height: crop.height,
|
||||
},
|
||||
) {
|
||||
const dstCanvas = createEl("canvas");
|
||||
dstCanvas.width = output.width;
|
||||
dstCanvas.height = output.height;
|
||||
dstCanvas
|
||||
.getContext("2d")
|
||||
.drawImage(
|
||||
srcCanvas,
|
||||
crop.left,
|
||||
crop.top,
|
||||
crop.width,
|
||||
crop.height,
|
||||
0,
|
||||
0,
|
||||
output.width,
|
||||
output.height,
|
||||
);
|
||||
return dstCanvas;
|
||||
}
|
||||
|
||||
// Promise.try, adapted from https://github.com/sindresorhus/p-try
|
||||
export async function promiseTry<TValue, TArgs extends unknown[]>(
|
||||
fn: (...args: TArgs) => PromiseLike<TValue> | TValue,
|
||||
...args: TArgs
|
||||
): Promise<TValue> {
|
||||
return new Promise((resolve) => {
|
||||
resolve(fn(...args));
|
||||
});
|
||||
}
|
||||
|
||||
// extending the missing types
|
||||
// relying on the [Index, T] to keep a correct order
|
||||
type TPromisePool<T, Index = number> = Pool<[Index, T][]> & {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Reports whether one semantic-style version is newer than another.
|
||||
*
|
||||
* @param version - Candidate version containing a `major.minor.patch` sequence.
|
||||
* @param otherVersion - Version to compare against.
|
||||
* @returns `true` when `version` is newer.
|
||||
* @remarks
|
||||
* Missing versions intentionally return `true` for backward compatibility.
|
||||
* Only the first three numeric components are compared; any surrounding
|
||||
* prerelease or build text is ignored.
|
||||
*/
|
||||
export function isVersionNewerThanOther(
|
||||
version: string,
|
||||
otherVersion: string,
|
||||
): boolean {
|
||||
if (!version || !otherVersion) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const v = version.match(/(\d*)\.(\d*)\.(\d*)/);
|
||||
const o = otherVersion.match(/(\d*)\.(\d*)\.(\d*)/);
|
||||
|
||||
return Boolean(
|
||||
v &&
|
||||
v.length === 4 &&
|
||||
o &&
|
||||
o.length === 4 &&
|
||||
!(
|
||||
isNaN(parseInt(v[1])) ||
|
||||
isNaN(parseInt(v[2])) ||
|
||||
isNaN(parseInt(v[3]))
|
||||
) &&
|
||||
!(
|
||||
isNaN(parseInt(o[1])) ||
|
||||
isNaN(parseInt(o[2])) ||
|
||||
isNaN(parseInt(o[3]))
|
||||
) &&
|
||||
(parseInt(v[1]) > parseInt(o[1]) ||
|
||||
(parseInt(v[1]) >= parseInt(o[1]) && parseInt(v[2]) > parseInt(o[2])) ||
|
||||
(parseInt(v[1]) >= parseInt(o[1]) &&
|
||||
parseInt(v[2]) >= parseInt(o[2]) &&
|
||||
parseInt(v[3]) > parseInt(o[3])))
|
||||
);
|
||||
}
|
||||
+306
-1573
File diff suppressed because it is too large.
Load diff
@@ -273,12 +273,12 @@ export class DropManager {
|
||||
f.extension.toLowerCase() === "md" &&
|
||||
!this.plugin.isExcalidrawFile(f)
|
||||
) {
|
||||
const id = await insertMarkdownImage(this.view, f, {
|
||||
const element = await insertMarkdownImage(this.view, f, {
|
||||
x: this.currentPosition.x + counter * 50,
|
||||
y: this.currentPosition.y + counter * 50,
|
||||
});
|
||||
if (id) {
|
||||
ids.push(id);
|
||||
if (element) {
|
||||
ids.push(element.id);
|
||||
counter++;
|
||||
ea.selectElementsInView(ids);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
type ColorComponent,
|
||||
type TFile,
|
||||
type WorkspaceLeaf,
|
||||
type WorkspaceSplit,
|
||||
type EventRef,
|
||||
type MarkdownFileInfo,
|
||||
} from "obsidian";
|
||||
@@ -47,6 +46,7 @@ import { showColorPicker } from "src/shared/Dialogs/ColorPicker";
|
||||
import { getBinaryFileFromDataURL } from "src/utils/utils";
|
||||
import {
|
||||
COLOR_NAMES,
|
||||
DEVICE,
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
} from "src/constants/constants";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
@@ -117,6 +117,7 @@ const getNativeColorValue = (color: string): string => {
|
||||
|
||||
class MarkdownFragmentView extends MarkdownView {
|
||||
private saveFragment: (markdown: string) => Promise<void>;
|
||||
private closing = false;
|
||||
|
||||
constructor(
|
||||
leaf: WorkspaceLeaf,
|
||||
@@ -129,8 +130,22 @@ class MarkdownFragmentView extends MarkdownView {
|
||||
this.saveFragment = saveFragment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks this fragment as done - called right after flushAndDetachEditor() has explicitly
|
||||
* flushed it and is about to detach its leaf. leaf.detach() is not awaited, and Obsidian's own
|
||||
* TextFileView teardown can still invoke save() on this instance later, after its CodeMirror
|
||||
* editor has already been torn down; at that point getViewData() returns an empty string, and
|
||||
* without this guard that empty content would silently overwrite the just-flushed Markdown.
|
||||
*/
|
||||
public markClosing(): void {
|
||||
this.closing = true;
|
||||
}
|
||||
|
||||
/** Redirects TextFileView autosave to the managed Markdown-image fragment. */
|
||||
public async save(): Promise<void> {
|
||||
if (this.closing) {
|
||||
return;
|
||||
}
|
||||
this.data = this.getViewData();
|
||||
await this.saveFragment(this.data);
|
||||
}
|
||||
@@ -145,19 +160,25 @@ class MarkdownImageEditorController {
|
||||
private element: ExcalidrawImageElement | null = null;
|
||||
private editorView: MarkdownView | null = null;
|
||||
private editorLeaf: WorkspaceLeaf | null = null;
|
||||
private editorRoot: WorkspaceSplit | null = null;
|
||||
private renderSettings: MarkdownImageRenderSettings | null = null;
|
||||
private renderTimer: number | null = null;
|
||||
private renderGeneration = 0;
|
||||
private closed = false;
|
||||
private editorChangeRef: EventRef | null = null;
|
||||
private selectionGeneration = 0;
|
||||
private initializing = false;
|
||||
private lastObservedSelectionId: string | null = null;
|
||||
private editorFocusHost: HTMLElement | null = null;
|
||||
private editorFocusInHandler: (() => void) | null = null;
|
||||
private editorFocusOutHandler: ((event: FocusEvent) => void) | null = null;
|
||||
private editorCommandView: MarkdownView | null = null;
|
||||
private previousActiveEditor: MarkdownFileInfo | null = null;
|
||||
private editorCommandRoutingActive = false;
|
||||
private editorCommandScopeActive = false;
|
||||
private focusEditorOnMount = false;
|
||||
private sidepanelRevealComplete = false;
|
||||
private editorFocusStabilizationWindow: Window | null = null;
|
||||
private editorFocusStabilizationFrame: number | null = null;
|
||||
private scenePointerDocument: Document | null = null;
|
||||
private scenePointerDownHandler: ((event: PointerEvent) => void) | null = null;
|
||||
private renderStatusEl: HTMLElement | null = null;
|
||||
@@ -168,6 +189,7 @@ class MarkdownImageEditorController {
|
||||
private ownerInvalid = false;
|
||||
private ownerInvalidation: Promise<void> | null = null;
|
||||
private ownerAttachmentGeneration = 0;
|
||||
private selectionSwitchQueue: Promise<void> = Promise.resolve();
|
||||
private activeLeafChangeRef: EventRef | null = null;
|
||||
private cssEditors: CSSCodeEditor[] = [];
|
||||
private fontPickers: FontPickerComponent[] = [];
|
||||
@@ -194,47 +216,88 @@ class MarkdownImageEditorController {
|
||||
if (!this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
if (!element) {
|
||||
const id = await insertMarkdownImage(this.view);
|
||||
if (!this.ensureOwnerValid()) {
|
||||
this.initializing = true;
|
||||
this.focusEditorOnMount = true;
|
||||
try {
|
||||
// Establish and reveal the feature tab before inserting a new image. The
|
||||
// insertion renders Markdown asynchronously; leaving the prior script tab
|
||||
// active during that work lets its delayed focus handlers win the race.
|
||||
patchMobileView(this.view);
|
||||
const sidepanel = await this.view.plugin.openSidepanel(false);
|
||||
if (!sidepanel || !this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
if (!id) {
|
||||
new Notice(t("MARKDOWN_IMAGE_INSERT_ERROR"));
|
||||
this.tab = await sidepanel.createTab({
|
||||
title: t("MARKDOWN_IMAGE_TITLE"),
|
||||
});
|
||||
this.tab.onClose = () => void this.close();
|
||||
this.tab.onFocus = (view) => void this.handleSidepanelFocus(view);
|
||||
this.tab.onWindowMigrated = () => void this.rebuildEditor();
|
||||
this.tab.onExcalidrawViewClosed = () => void this.invalidateOwner(false);
|
||||
this.watchActiveExcalidrawView();
|
||||
this.renderPanel();
|
||||
await this.app.workspace.revealLeaf(sidepanel.leaf);
|
||||
if (!this.tab || this.closed || !this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
element = this.view
|
||||
.getViewElements()
|
||||
.find((candidate) => candidate.id === id) as
|
||||
| ExcalidrawImageElement
|
||||
| undefined;
|
||||
this.sidepanelRevealComplete = true;
|
||||
|
||||
if (!element) {
|
||||
element = await insertMarkdownImage(this.view);
|
||||
if (!this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
if (!element) {
|
||||
new Notice(t("MARKDOWN_IMAGE_INSERT_ERROR"));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
this.element = element;
|
||||
this.lastObservedSelectionId = element.id;
|
||||
this.renderSettings = getMarkdownImageRenderSettings(
|
||||
this.view.plugin,
|
||||
element,
|
||||
);
|
||||
this.view.setMarkdownImageEditorIsEditing();
|
||||
this.renderPanel();
|
||||
this.focusEditorIfRequested();
|
||||
return true;
|
||||
} finally {
|
||||
this.initializing = false;
|
||||
}
|
||||
if (!element) {
|
||||
return false;
|
||||
}
|
||||
this.element = element;
|
||||
this.lastObservedSelectionId = element.id;
|
||||
this.renderSettings = getMarkdownImageRenderSettings(
|
||||
this.view.plugin,
|
||||
element,
|
||||
}
|
||||
|
||||
public isEditingElement(
|
||||
view: ExcalidrawView,
|
||||
element: ExcalidrawImageElement,
|
||||
): boolean {
|
||||
return (
|
||||
!this.closed &&
|
||||
this.tab !== null &&
|
||||
this.view === view &&
|
||||
this.element?.id === element.id &&
|
||||
this.isOwnerViewValid()
|
||||
);
|
||||
// Revealing a phone sidebar can coincide with Obsidian registering the
|
||||
// soon-to-be-created detached Markdown leaf as its active editor.
|
||||
patchMobileView(this.view);
|
||||
const sidepanel = await this.view.plugin.openSidepanel(true);
|
||||
if (!sidepanel || !this.ensureOwnerValid()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public async revealAndFocus(): Promise<void> {
|
||||
if (!this.tab || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
this.tab = await sidepanel.createTab({ title: t("MARKDOWN_IMAGE_TITLE") });
|
||||
this.view.setMarkdownImageEditorIsEditing();
|
||||
this.tab.onClose = () => this.close();
|
||||
this.tab.onFocus = (view) => void this.handleSidepanelFocus(view);
|
||||
this.tab.onWindowMigrated = () => void this.rebuildEditor();
|
||||
this.tab.onExcalidrawViewClosed = () => void this.invalidateOwner(false);
|
||||
this.watchActiveExcalidrawView();
|
||||
this.renderPanel();
|
||||
this.tab.open(true);
|
||||
return true;
|
||||
const sidepanel = await this.plugin.openSidepanel(false);
|
||||
if (!sidepanel || !this.tab || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
this.focusEditorOnMount = true;
|
||||
this.sidepanelRevealComplete = false;
|
||||
this.tab.open(false);
|
||||
await this.app.workspace.revealLeaf(sidepanel.leaf);
|
||||
if (!this.tab || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
this.sidepanelRevealComplete = true;
|
||||
this.focusEditorIfRequested();
|
||||
}
|
||||
|
||||
private renderPanel(): void {
|
||||
@@ -855,6 +918,21 @@ class MarkdownImageEditorController {
|
||||
this.ownerInvalidation = (async () => {
|
||||
try {
|
||||
await this.flushAndDetachEditor(saveEditor);
|
||||
// flushAndDetachEditor() only writes the flushed edit into excalidrawData (in memory).
|
||||
// This controller is about to stop tracking invalidatedView (it's being handed off to a
|
||||
// different view, or torn down), so nothing else is guaranteed to persist that edit to
|
||||
// disk afterward - force it now while we still have a definite reference to the view.
|
||||
if (saveEditor && canClearOwnerEditing) {
|
||||
await invalidatedView.forceSave(true, true);
|
||||
await invalidatedView.reload(false, invalidatedView.file);
|
||||
// reload() clears semaphores.embeddableIsEditingSelf as soon as a debounce timer is
|
||||
// pending, opening a window (spanning its vault.read() await) where a concurrently
|
||||
// polling autosave can slip in - see the matching comment in
|
||||
// persistOwnerAfterEditorFlush() for why this is a real, tight race. Re-arm it; the
|
||||
// finally block below calls clearEmbeddableNodeIsEditing() right after, which is the
|
||||
// intended graceful (debounced) wind-down instead of reload()'s abrupt one.
|
||||
invalidatedView.setMarkdownImageEditorIsEditing();
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "MarkdownImageEditorController.invalidateOwner",
|
||||
@@ -1365,7 +1443,7 @@ class MarkdownImageEditorController {
|
||||
elements: readonly ExcalidrawElement[],
|
||||
selectedElementIds: Record<string, boolean>,
|
||||
): void {
|
||||
if (!this.tab || this.closed) {
|
||||
if (!this.tab || this.closed || this.initializing) {
|
||||
return;
|
||||
}
|
||||
if (sourceView !== this.view || !this.isOwnerViewValid()) {
|
||||
@@ -1391,22 +1469,120 @@ class MarkdownImageEditorController {
|
||||
? selected
|
||||
: undefined;
|
||||
const generation = ++this.selectionGeneration;
|
||||
void this.switchElement(next, generation);
|
||||
this.selectionSwitchQueue = this.selectionSwitchQueue
|
||||
.catch(() => {
|
||||
// Keep the queue alive after any prior failure.
|
||||
})
|
||||
.then(() => this.switchElement(next, generation));
|
||||
}
|
||||
|
||||
private async waitForOwnerSaveIdle(maxFrames: number = 180): Promise<void> {
|
||||
const ownerView = this.view;
|
||||
const ownerWindow = ownerView.ownerWindow ?? window;
|
||||
for (let frame = 0; frame < maxFrames; frame++) {
|
||||
if (!this.ensureOwnerValid() || this.view !== ownerView) {
|
||||
return;
|
||||
}
|
||||
const semaphores = ownerView.semaphores;
|
||||
if (!semaphores?.saving && !semaphores?.autosaving) {
|
||||
return;
|
||||
}
|
||||
await new Promise<void>((resolve) => {
|
||||
ownerWindow.requestAnimationFrame(() => resolve());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forces a disk save of the owner view, retrying if a concurrent save (autosave, or another
|
||||
* controller flushing during a handoff) claims the saving semaphore between
|
||||
* waitForOwnerSaveIdle() resolving and the save() call below. save() silently no-ops when
|
||||
* semaphores.saving is already true when it is entered, and awaiting an already-resolved
|
||||
* promise still yields a microtask turn, so a single poll-then-call attempt cannot guarantee
|
||||
* persistence on its own.
|
||||
*/
|
||||
private async persistOwnerAfterEditorFlush(maxAttempts: number = 5): Promise<void> {
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
if (!this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
await this.waitForOwnerSaveIdle();
|
||||
if (!this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
if (this.view.semaphores.saving) {
|
||||
continue;
|
||||
}
|
||||
await this.view.save(true, true, true);
|
||||
// save() does not refresh view.data, so prepareGetViewData() would keep rebuilding the
|
||||
// Markdown-image header section from a stale copy on every later save in this same view
|
||||
// (e.g. switching directly from one Markdown image to another via switchElement()). Reuse
|
||||
// the same reload(false, file) call invalidateOwner() uses for the cross-view handoff case.
|
||||
if (this.ensureOwnerValid()) {
|
||||
await this.view.reload(false, this.view.file);
|
||||
// reload() clears semaphores.embeddableIsEditingSelf as soon as a debounce timer is
|
||||
// pending (it assumes editing has ended). It hasn't: flushCurrentElement() runs mid-session,
|
||||
// and switchElement()/flushPendingEditsBeforeHandoff() decide the real end state right
|
||||
// after this returns. Re-arm it immediately so nothing else can misread editing as finished
|
||||
// in that gap; the caller's own clear/set call right after this resolves is what should
|
||||
// decide the final state, not reload()'s side effect.
|
||||
if (this.ensureOwnerValid()) {
|
||||
this.view.setMarkdownImageEditorIsEditing();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes the current editor's content into excalidrawData and force-persists it to disk.
|
||||
* Shared by switchElement() (selection changes within this controller) and
|
||||
* flushPendingEditsBeforeHandoff() (handoff to a brand new controller in
|
||||
* openMarkdownImageEditor()) so a previous element's edits are always guaranteed to be flushed
|
||||
* and saved before anything else starts editing a different element.
|
||||
*/
|
||||
private async flushCurrentElement(): Promise<void> {
|
||||
await this.renderCurrentEditor();
|
||||
this.cancelScheduledRender();
|
||||
this.removeEditorFocusListener();
|
||||
await this.flushAndDetachEditor();
|
||||
await this.persistOwnerAfterEditorFlush();
|
||||
this.cancelScheduledRender();
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes and force-persists the currently edited element before this controller is replaced
|
||||
* by a brand new controller instance for a different element (see openMarkdownImageEditor()).
|
||||
* Without this, dispose()/close() detach and save the editor via a fire-and-forget call, so the
|
||||
* previous element's edits can still be in flight after the new controller has already started
|
||||
* editing (and locking, via embeddableIsEditingSelf) a different element.
|
||||
*/
|
||||
public async flushPendingEditsBeforeHandoff(): Promise<void> {
|
||||
if (this.closed || !this.element) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await this.flushCurrentElement();
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "MarkdownImageEditorController.flushPendingEditsBeforeHandoff",
|
||||
error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async switchElement(
|
||||
element: ExcalidrawImageElement | undefined,
|
||||
generation: number,
|
||||
): Promise<void> {
|
||||
await this.renderCurrentEditor();
|
||||
this.cancelScheduledRender();
|
||||
this.removeEditorFocusListener();
|
||||
this.renderSelectionPlaceholder();
|
||||
await this.flushAndDetachEditor();
|
||||
this.cancelScheduledRender();
|
||||
if (generation !== this.selectionGeneration || this.closed) {
|
||||
return;
|
||||
}
|
||||
await this.flushCurrentElement();
|
||||
if (generation !== this.selectionGeneration || this.closed) {
|
||||
return;
|
||||
}
|
||||
this.renderSelectionPlaceholder();
|
||||
this.element = element ?? null;
|
||||
this.renderSettings = element
|
||||
? getMarkdownImageRenderSettings(this.view.plugin, element)
|
||||
@@ -1430,14 +1606,18 @@ class MarkdownImageEditorController {
|
||||
nextView &&
|
||||
(!ownerIsValid || nextView === this.view || nextViewIsActive)
|
||||
) {
|
||||
void this.attachToView(nextView);
|
||||
void this.attachToView(nextView).then(() => {
|
||||
this.focusEditorIfRequested();
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Focusing the sidepanel makes its own leaf the most recent one. In that
|
||||
// transition, the plugin's last-active Excalidraw leaf can briefly be
|
||||
// stale. Keep the owner established by the active-leaf listener instead
|
||||
// of tearing down a valid editor in favor of the stale view.
|
||||
this.ensureOwnerValid();
|
||||
if (this.ensureOwnerValid()) {
|
||||
this.focusEditorIfRequested();
|
||||
}
|
||||
}
|
||||
|
||||
private async mountMarkdownView(host: HTMLElement): Promise<void> {
|
||||
@@ -1460,7 +1640,6 @@ class MarkdownImageEditorController {
|
||||
const elementFileId = element.fileId;
|
||||
const { leaf, rootSplit } = createLeaf(this.view, host.ownerDocument);
|
||||
this.editorLeaf = leaf;
|
||||
this.editorRoot = rootSplit;
|
||||
this.startMobileViewPatch(leaf);
|
||||
rootSplit.containerEl.addClass("mod-visible");
|
||||
setStyle(rootSplit.containerEl, { height: "100%", width: "100%" });
|
||||
@@ -1502,6 +1681,7 @@ class MarkdownImageEditorController {
|
||||
this.prepareEditorView(host, leaf.view);
|
||||
this.revealExternalSourceSubpath(leaf.view, sourceFile, ref);
|
||||
this.watchEditorChanges();
|
||||
this.focusEditorIfRequested(leaf.view);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1542,6 +1722,7 @@ class MarkdownImageEditorController {
|
||||
this.editorView = fragmentView;
|
||||
this.prepareEditorView(host, fragmentView);
|
||||
this.watchEditorChanges();
|
||||
this.focusEditorIfRequested(fragmentView);
|
||||
}
|
||||
|
||||
private revealExternalSourceSubpath(
|
||||
@@ -1579,29 +1760,29 @@ class MarkdownImageEditorController {
|
||||
this.editorFocusHost = host;
|
||||
this.editorCommandView = editorView;
|
||||
this.editorFocusInHandler = () => {
|
||||
if (this.app.workspace.activeEditor === editorView) {
|
||||
return;
|
||||
}
|
||||
this.previousActiveEditor = this.app.workspace.activeEditor;
|
||||
this.app.workspace.activeEditor = editorView;
|
||||
this.activateEditorCommandRouting(editorView);
|
||||
};
|
||||
this.editorFocusOutHandler = (event: FocusEvent) => {
|
||||
const nextTarget = event.relatedTarget;
|
||||
this.editorFocusOutHandler = () => {
|
||||
const finishFocusTransition = () => {
|
||||
if (this.editorView !== editorView || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
if (host.contains(host.ownerDocument.activeElement)) {
|
||||
this.activateEditorCommandRouting(editorView);
|
||||
return;
|
||||
}
|
||||
this.restorePreviousActiveEditor();
|
||||
void this.renderCurrentEditor();
|
||||
};
|
||||
const targetWindow = host.ownerDocument.defaultView;
|
||||
if (
|
||||
nextTarget &&
|
||||
targetWindow?.Node &&
|
||||
nextTarget instanceof targetWindow.Node &&
|
||||
host.contains(nextTarget)
|
||||
) {
|
||||
return;
|
||||
if (targetWindow) {
|
||||
targetWindow.setTimeout(finishFocusTransition, 0);
|
||||
} else {
|
||||
finishFocusTransition();
|
||||
}
|
||||
this.restorePreviousActiveEditor();
|
||||
void this.renderCurrentEditor();
|
||||
};
|
||||
host.addEventListener("focusin", this.editorFocusInHandler);
|
||||
host.addEventListener("focusout", this.editorFocusOutHandler);
|
||||
|
||||
const viewContainer = this.view.containerEl;
|
||||
if (!viewContainer) {
|
||||
void this.invalidateOwner(false);
|
||||
@@ -1632,7 +1813,106 @@ class MarkdownImageEditorController {
|
||||
);
|
||||
}
|
||||
|
||||
private activateEditorCommandRouting(editorView: MarkdownView): void {
|
||||
if (!this.editorCommandRoutingActive) {
|
||||
this.previousActiveEditor =
|
||||
this.app.workspace.activeEditor === editorView
|
||||
? null
|
||||
: this.app.workspace.activeEditor;
|
||||
this.editorCommandRoutingActive = true;
|
||||
}
|
||||
if (!this.editorCommandScopeActive && editorView.scope) {
|
||||
this.app.keymap.pushScope(editorView.scope);
|
||||
this.editorCommandScopeActive = true;
|
||||
}
|
||||
this.app.workspace.activeEditor = editorView;
|
||||
}
|
||||
|
||||
private focusEditorIfRequested(
|
||||
editorView: MarkdownView | null = this.editorView,
|
||||
): void {
|
||||
if (
|
||||
!this.focusEditorOnMount ||
|
||||
!this.sidepanelRevealComplete ||
|
||||
!editorView ||
|
||||
!this.tab?.isActiveTab()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (this.editorView !== editorView || !this.ensureOwnerValid()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Pre-emptively route commands and update Obsidian's active editor state.
|
||||
// This ensures the mobile toolbar sees the correct state the exact moment
|
||||
// the virtual keyboard starts opening, fixing the "first tap" bug.
|
||||
this.activateEditorCommandRouting(editorView);
|
||||
|
||||
if (DEVICE.isMobile) {
|
||||
this.app.workspace.setActiveLeaf(editorView.leaf, { focus: false });
|
||||
editorView.editor.focus();
|
||||
window.setTimeout(() => {
|
||||
this.focusEditorOnMount = false;
|
||||
}, 500);
|
||||
return;
|
||||
}
|
||||
|
||||
this.app.workspace.setActiveLeaf(editorView.leaf, { focus: true });
|
||||
editorView.editor.focus();
|
||||
const targetWindow = editorView.containerEl.ownerDocument.defaultView;
|
||||
if (targetWindow) {
|
||||
this.stabilizeActiveEditor(editorView, targetWindow);
|
||||
}
|
||||
}
|
||||
|
||||
private stabilizeActiveEditor(
|
||||
editorView: MarkdownView,
|
||||
targetWindow: Window,
|
||||
): void {
|
||||
this.stopEditorFocusStabilization();
|
||||
this.editorFocusStabilizationWindow = targetWindow;
|
||||
const deadline = targetWindow.performance.now() + 500;
|
||||
const stabilize = () => {
|
||||
if (
|
||||
this.editorView !== editorView ||
|
||||
!this.ensureOwnerValid() ||
|
||||
!this.tab?.isActiveTab() ||
|
||||
!this.editorFocusHost?.contains(
|
||||
editorView.containerEl.ownerDocument.activeElement,
|
||||
)
|
||||
) {
|
||||
this.stopEditorFocusStabilization();
|
||||
return;
|
||||
}
|
||||
this.activateEditorCommandRouting(editorView);
|
||||
if (targetWindow.performance.now() >= deadline) {
|
||||
this.editorFocusStabilizationFrame = null;
|
||||
this.editorFocusStabilizationWindow = null;
|
||||
this.focusEditorOnMount = false;
|
||||
return;
|
||||
}
|
||||
this.editorFocusStabilizationFrame = targetWindow.requestAnimationFrame(
|
||||
stabilize,
|
||||
);
|
||||
};
|
||||
stabilize();
|
||||
}
|
||||
|
||||
private stopEditorFocusStabilization(): void {
|
||||
if (
|
||||
this.editorFocusStabilizationWindow &&
|
||||
this.editorFocusStabilizationFrame !== null
|
||||
) {
|
||||
this.editorFocusStabilizationWindow.cancelAnimationFrame(
|
||||
this.editorFocusStabilizationFrame,
|
||||
);
|
||||
}
|
||||
this.editorFocusStabilizationWindow = null;
|
||||
this.editorFocusStabilizationFrame = null;
|
||||
}
|
||||
|
||||
private removeEditorFocusListener(): void {
|
||||
this.stopEditorFocusStabilization();
|
||||
if (this.editorFocusHost && this.editorFocusInHandler) {
|
||||
this.editorFocusHost.removeEventListener(
|
||||
"focusin",
|
||||
@@ -1662,13 +1942,19 @@ class MarkdownImageEditorController {
|
||||
}
|
||||
|
||||
private restorePreviousActiveEditor(): void {
|
||||
if (this.editorCommandScopeActive && this.editorCommandView?.scope) {
|
||||
this.app.keymap.popScope(this.editorCommandView.scope);
|
||||
}
|
||||
this.editorCommandScopeActive = false;
|
||||
if (
|
||||
this.editorCommandRoutingActive &&
|
||||
this.editorCommandView &&
|
||||
this.app.workspace.activeEditor === this.editorCommandView
|
||||
) {
|
||||
this.app.workspace.activeEditor = this.previousActiveEditor;
|
||||
}
|
||||
this.previousActiveEditor = null;
|
||||
this.editorCommandRoutingActive = false;
|
||||
}
|
||||
|
||||
private setupEditorResize(
|
||||
@@ -2006,7 +2292,6 @@ class MarkdownImageEditorController {
|
||||
this.stopMobileViewPatch();
|
||||
this.editorView = null;
|
||||
this.editorLeaf = null;
|
||||
this.editorRoot = null;
|
||||
this.editorContentDirty = false;
|
||||
this.removeEditorResizeListener();
|
||||
this.removeEditorFocusListener();
|
||||
@@ -2019,16 +2304,30 @@ class MarkdownImageEditorController {
|
||||
await editorView.save();
|
||||
}
|
||||
} finally {
|
||||
// leaf.detach() below is not awaited; Obsidian's own TextFileView teardown can still call
|
||||
// save() on editorView again afterward, once its CodeMirror editor is already gone. Without
|
||||
// markClosing(), that later call would silently overwrite the flush above with "".
|
||||
if (editorView instanceof MarkdownFragmentView) {
|
||||
editorView.markClosing();
|
||||
}
|
||||
editorLeaf?.detach();
|
||||
}
|
||||
}
|
||||
|
||||
private close(): void {
|
||||
/**
|
||||
* Flushes and force-persists the editing session, then tears down the controller. Awaited by
|
||||
* dispose() so that closing the sidepanel (the whole panel, not just switching elements/views)
|
||||
* reliably reaches disk even if the user never returns focus to the owning Excalidraw view -
|
||||
* previously this flushed into excalidrawData via a fire-and-forget call with no forced save,
|
||||
* so data could sit unsaved indefinitely, which is especially risky on mobile.
|
||||
*/
|
||||
private async close(): Promise<void> {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
const canClearOwnerEditing = this.isOwnerIdentityValid();
|
||||
this.closed = true;
|
||||
this.sidepanelRevealComplete = false;
|
||||
if (activeController === this) {
|
||||
activeController = null;
|
||||
}
|
||||
@@ -2043,21 +2342,32 @@ class MarkdownImageEditorController {
|
||||
this.destroyFontPickers();
|
||||
this.focusOwnerButtonEl = null;
|
||||
this.ownerStatusEl = null;
|
||||
void this.flushAndDetachEditor().finally(() => {
|
||||
try {
|
||||
await this.flushAndDetachEditor();
|
||||
if (canClearOwnerEditing) {
|
||||
await this.view.forceSave(true, true);
|
||||
await this.view.reload(false, this.view.file);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "MarkdownImageEditorController.close",
|
||||
error,
|
||||
});
|
||||
} finally {
|
||||
this.cancelScheduledRender();
|
||||
if (canClearOwnerEditing) {
|
||||
this.view.clearEmbeddableNodeIsEditing();
|
||||
}
|
||||
this.element = null;
|
||||
this.renderSettings = null;
|
||||
});
|
||||
}
|
||||
void this.plugin.saveSettings();
|
||||
this.tab = null;
|
||||
}
|
||||
|
||||
public dispose(): void {
|
||||
public async dispose(): Promise<void> {
|
||||
this.tab?.close();
|
||||
this.close();
|
||||
await this.close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2068,15 +2378,31 @@ export async function openMarkdownImageEditor(
|
||||
view: ExcalidrawView,
|
||||
element?: ExcalidrawImageElement,
|
||||
): Promise<void> {
|
||||
activeController?.dispose();
|
||||
if (element && activeController?.isEditingElement(view, element)) {
|
||||
await activeController.revealAndFocus();
|
||||
return;
|
||||
}
|
||||
const previousController = activeController;
|
||||
// Guarantee the previously edited element's changes are flushed and persisted before this
|
||||
// handoff: otherwise dispose() below would save the old element in the background while the
|
||||
// new controller has already started editing (and locking) a different element.
|
||||
await previousController?.flushPendingEditsBeforeHandoff();
|
||||
const controller = new MarkdownImageEditorController(view);
|
||||
activeController = controller;
|
||||
try {
|
||||
if (!(await controller.open(element))) {
|
||||
controller.dispose();
|
||||
void controller.dispose();
|
||||
if (activeController === null && previousController) {
|
||||
activeController = previousController;
|
||||
}
|
||||
return;
|
||||
}
|
||||
void previousController?.dispose();
|
||||
} catch (error: unknown) {
|
||||
controller.dispose();
|
||||
void controller.dispose();
|
||||
if (activeController === null && previousController) {
|
||||
activeController = previousController;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -2106,3 +2432,19 @@ export async function handleMarkdownImageEditorViewUnload(
|
||||
}
|
||||
await activeController.invalidateOwner(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes and force-persists the active Markdown-image editing session before the sidepanel view
|
||||
* itself closes. Without this, closing the whole side panel (e.g. collapsing it, or closing the
|
||||
* leaf) without ever returning focus to the owning Excalidraw view left the edit flushed only into
|
||||
* excalidrawData in memory, with no forced disk save - especially risky on mobile, where the app
|
||||
* can be suspended shortly after. The sidepanel is a plugin-wide singleton (see
|
||||
* ExcalidrawSidepanelView.getExisting()), and so is activeController, so there is no separate
|
||||
* "which sidepanel" identity to check here.
|
||||
*/
|
||||
export async function handleMarkdownImageEditorSidepanelClosing(): Promise<void> {
|
||||
if (!activeController) {
|
||||
return;
|
||||
}
|
||||
await activeController.dispose();
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { getLastActiveExcalidrawView } from "src/utils/excalidrawViewLookup";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { ExcalidrawSidepanelTab } from "./SidepanelTab";
|
||||
import { hideElement, showElement } from "src/utils/styleUtils";
|
||||
import { handleMarkdownImageEditorSidepanelClosing } from "./MarkdownImageEditor";
|
||||
|
||||
type TabCreationConfig = {
|
||||
title: string;
|
||||
@@ -223,6 +224,11 @@ export class ExcalidrawSidepanelView extends ItemView {
|
||||
this.app.workspace.offref(this.leafChangeRef);
|
||||
this.leafChangeRef = null;
|
||||
}
|
||||
// Flush and force-persist any in-progress Markdown-image edit before tearing down its tab
|
||||
// below - otherwise closing the whole side panel without ever refocusing the owning
|
||||
// Excalidraw view leaves the edit sitting unsaved on disk (see notifyWillClose()'s onClose()
|
||||
// cascade, which only flushes into memory in a fire-and-forget way).
|
||||
await handleMarkdownImageEditorSidepanelClosing();
|
||||
this.tabs.forEach((tab) => {
|
||||
tab.notifyWillClose();
|
||||
const hostEA = this.tabHosts.get(tab.id);
|
||||
|
||||
Reference in new issue
Block a user