Compare commits

...
Author SHA1 Message Date
zsviczian 371fa7a254 removing duplicate functions 2026-08-08 22:09:23 +02:00
zsviczian 00a1bed763 de-duplicated getFontDataURL, svgToBase64, and cropCanvas 2026-08-08 21:45:19 +02:00
zsviczian ff2c8536ce PR #2872 2026-08-08 20:24:05 +02:00
zsviczian eee975c44d refactor: consolidate text link and binary helpers 2026-08-08 20:04:06 +02:00
zsviczian 95d89f2fed refactor: consolidate duplicate utility helpers 2026-08-08 11:17:32 +02:00
zsviczian c86db2152e refactor: retire legacy AI settings compatibility 2026-08-08 11:03:45 +02:00
zsviczian 7caf768b8f 2.26.4 2026-08-05 21:51:46 +02:00
zsviczian b295723780 fixed markdown image presistance 2026-08-05 21:35:16 +02:00
zsviczian 40e747c3bd 2.26.3 2026-08-04 19:02:32 +02:00
zsviczian dd06b07a12 updated to 0.18.117 2026-08-04 18:11:06 +02:00
zsviczian b4df1d8e5b Detect Markdown-image deletion via onIncrement instead of guessing trigger
Deleting the last local Markdown image via the Excalidraw properties
panel's trash button skipped the keep-or-delete-file prompt, because
detection only watched specific triggers: the Backspace/Delete/Cut keys
and a data-testid selector that only matches the context-menu delete
item, not the panel button (which the fork never gives a testid).

Replace that trigger-guessing with Excalidraw's onIncrement API: durable
store increments expose exactly which elements were soft-deleted
(isDeleted flipped true) in that action, regardless of what triggered
it. This uniformly covers keyboard, Cut, context menu, the panel
button, undo/redo, and scripts, and removes the old capture/timer/
candidate-matching scaffolding entirely.
2026-08-04 15:43:05 +02:00
zsviczian 614f0fbab0 Fix Markdown image edits lost when switching between images
Editing one Markdown image and immediately selecting or opening another
could drop the first image's edits, both in memory and on disk. Two
distinct races caused this: switchElement()'s force-persist could
silently no-op if a concurrent save claimed the saving semaphore between
the idle-wait and the save() call, and openMarkdownImageEditor()'s
handoff to a brand new controller disposed the previous one via a
fire-and-forget flush instead of awaiting it. Both paths now share a
single flushCurrentElement() helper and persistOwnerAfterEditorFlush()
retries instead of silently giving up.
2026-08-04 14:13:50 +02:00
zsviczian 07ff3b7e96 2.26.2 2026-08-03 22:32:35 +02:00
zsviczian 75940d6173 2.26.1 2026-08-03 22:08:26 +02:00
zsviczian 8ba60c43e8 2.26.0 2026-08-03 22:06:28 +02:00
zsviczian ae73115e9c fixed code scanner findings 2026-08-03 21:59:12 +02:00
zsviczian 723c7c5de2 fixed css editor looses focus on mobile 2026-08-03 21:36:24 +02:00
zsviczian 680ae101cb align markdown SVG image rendering on iOS, android and desktop 2026-08-03 20:54:39 +02:00
zsviczian 82578a0a58 fix Markdown Image sidepanel on mobiles 2026-08-03 18:02:29 +02:00
zsviczian 8c2da6a1c3 markdown toolbar visible in sidepanel on Obsidian Mobile 2026-08-03 15:22:45 +02:00
zsviczian b09fa3b1ed 2.26.0-rc.4 . settings persist immediately (Obsidian 1.13.x compatibility issue), MarkdownImage editor did not open on Mobiles. 2026-08-03 12:53:50 +02:00
zsviczian 6001ef3f1f Merge pull request #2863 from FreeCutter/master
Updated script VoronoiDiagramGenerator
2026-08-03 09:43:46 +02:00
zsviczian 40e204c2d9 2.26.0-rc.3 - fixed auto activation of markdown editor 2026-08-03 09:16:46 +02:00
zsviczian e6c07bb615 updated messages for 2.26 2026-08-03 08:45:35 +02:00
FreeCutter 7aa3f044cf Enhance Voronoi Diagram Generator UI and functionality
Updated UI settings modal for Voronoi Diagram Generator, improved layout and added info button functionality.
2026-08-03 07:31:38 +02:00
FreeCutter b901bfbcac Update mtime for VoronoiDiagramGenerator files 2026-08-03 07:26:30 +02:00
zsviczian 642ba63a9f 2.26.0-rc.2 2026-08-02 19:20:35 +02:00
zsviczian c0ab59c3aa pre-release 2026-08-02 19:20:06 +02:00
zsviczian fd62c158db Fix sections in commented sections. 2026-08-02 19:13:03 +02:00
zsviczian cabe90927d 2.26.0-rc.1 2026-08-02 17:18:57 +02:00
zsviczian 3220889563 Fixed Markdown Image large file editing issue - file jumping around 2026-08-02 17:03:03 +02:00
zsviczian 907e2267d5 FileAndFolderSelectorModal 2026-08-02 16:43:45 +02:00
39 changed files with 2549 additions and 1969 deletions

No files matched your search

+742
View File
@@ -0,0 +1,742 @@
# Incremental refactor assessment and plan
Status: active plan for the 2.27.0 refactor, last updated 2026-08-08
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 |
| Audit and consolidate duplicate logic | In progress | Consolidated `updateFrontmatterInString()`, `arrayToMap()`, `wrapTextAtCharLength()`, `getLinkParts()`/`LinkParts`, `getBinaryFileFromDataURL()`, `svgToBase64()`, `getFontDataURL()`, `cropCanvas()`, `getImageSize()`, `promiseTry()`, `isVersionNewerThanOther()`, `repositionElementsToCursor()`, the internal `cloneElement()`, and `getBoundTextElementId()`; continue one independently testable helper family at a time |
| All later phases | Planned | Begin only after the preceding checkpoint is validated |
### 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 |
## 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
MarkdownIntegrationManager.ts Post processors and install code blocks
src/view/
ExcalidrawView.ts Obsidian host, public facade, composition
components/
ExcalidrawRoot.tsx Package-aware render tree, eventually TSX
managers/
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. Move install-codeblock registration and Markdown integration setup behind a
`MarkdownIntegrationManager`, while still registering the Markdown post
processor from `onload()`.
2. Move startup-script execution behind a focused runner owned by the script
subsystem.
3. Move startup timing storage/formatting into a small `StartupTimer` while
retaining `plugin.logStartupEvent()` as a delegate if consumers need it.
4. Group initialization and cleanup of managers, but keep a readable ordered
list in `onloadOnLayoutReady()` and `onunload()`.
5. Only after reference searches and runtime validation, remove confirmed dead
members. Current review candidates include the unused private
`registerEventListeners()` and a `fileExplorerObserver` field in `main.ts`
that appears separate from the observer owned by `ObserverManager`.
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. `ViewExportManager`: export preference resolution, file collection, SVG,
PNG, PDF, clipboard, and save-to-file operations.
2. `ViewLinkNavigationManager`: link parsing, hook invocation, navigation, and
link click handling.
3. `ViewSceneFileManager`: active/next/deferred embedded-file loaders and
deferred validation scheduling.
4. `MarkdownImageController`: deletion queue, edit handoff, conversion, and
local-source operations.
5. `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. Extract `ViewExportManager` while keeping all current `ExcalidrawView`
export methods as delegates. This establishes the view-controller pattern
away from lifecycle and synchronization.
The next checkpoint is extracting the package-aware React root using
`createElement()` without TSX or state changes, followed by popout validation.
Convert to TSX only in the subsequent change.
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.
+95 -25
View File
@@ -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!");
+2 -2
View File
@@ -705,10 +705,10 @@
},
{
"fname": "VoronoiDiagramGenerator.md",
"mtime": 1785564296587
"mtime": 1785733307861
},
{
"fname": "VoronoiDiagramGenerator.svg",
"mtime": 1785564296587
}
]
]
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.26.0-beta.8",
"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
View File
@@ -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",
+5 -4
View File
@@ -13,7 +13,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.116",
"@zsviczian/excalidraw": "0.18.118",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -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",
+1 -1
View File
@@ -30,7 +30,7 @@
"@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",
+7 -433
View File
@@ -41,10 +41,6 @@ import {
ExcalidrawSettings,
DEFAULT_SETTINGS,
ExcalidrawSettingTab,
cloneKnownAIProviderProfiles,
cloneModelConfigs,
KNOWN_AI_TEXT_MODEL_CONFIGS,
KNOWN_AI_IMAGE_MODEL_CONFIGS,
} from "./settings";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import { initExcalidrawAutomate } from "src/utils/excalidrawAutomateUtils";
@@ -151,59 +147,6 @@ const PHONE_FOOTER_SAFE_AREA_CSS = `
type PersistedExcalidrawSettings = Partial<ExcalidrawSettings> &
Record<string, unknown>;
const LEGACY_AI_SETTING_KEYS: (keyof ExcalidrawSettings)[] = [
"aiDefaultMaxTokens",
"aiDefaultMultimodalModel",
"aiDefaultVisionModel",
"aiProvider",
"aiAPIKey",
"aiBaseURL",
"aiTextEndpoint",
"aiImageGenerationEndpoint",
"aiImageEditsEndpoint",
"aiImageVariationsEndpoint",
"aiImageModelCapabilities",
"aiVisionModelConfigs",
"openAIAPIToken",
"openAIDefaultTextModel",
"openAIDefaultTextModelMaxTokens",
"openAIDefaultVisionModel",
"openAIDefaultImageGenerationModel",
"openAIURL",
"openAIImageGenerationURL",
"openAIImageEditsURL",
"openAIImageVariationURL",
];
const AI_TEXT_SUFFIX = "/chat/completions";
const normalizeAISettingURL = (value: unknown): string => {
return typeof value === "string" ? value.trim().replace(/\/+$/, "") : "";
};
const joinAISettingURL = (baseURL: string, path: string): string => {
if (!baseURL) {
return "";
}
return `${baseURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
};
const hasNonEmptyString = (value: unknown): value is string => {
return typeof value === "string" && value.trim() !== "";
};
const hasPositiveNumber = (value: unknown): value is number => {
return typeof value === "number" && value > 0;
};
const LEGACY_PROVIDER_LABELS: Record<string, string> = {
openai: "OpenAI",
anthropic: "Anthropic",
google: "Google Gemini",
xai: "xAI",
"openai-compatible": "OpenAI-compatible",
};
/**
* Compatibility labels consumed by upstream Excalidraw via ExcalidrawPlugin.getLabel().
* Keep these keys present in `en.ts`, and keep maintained locales in sync.
@@ -223,362 +166,6 @@ const EXCALIDRAW_EXTERNAL_GET_LABEL_KEY_SET = new Set<keyof typeof en>(
EXCALIDRAW_EXTERNAL_GET_LABEL_KEYS,
);
const stripLegacyAISettings = <T extends PersistedExcalidrawSettings>(
settings: T,
): T => {
const sanitized = { ...settings };
LEGACY_AI_SETTING_KEYS.forEach((key) => {
delete sanitized[key];
});
return sanitized;
};
const migrateLegacyAISettings = (
settings: PersistedExcalidrawSettings,
): { settings: PersistedExcalidrawSettings; didMigrate: boolean } => {
const migrated = { ...settings };
const migratedRecord = migrated as Record<string, unknown>;
let didMigrate = false;
const assignStringIfMissing = (
key: keyof ExcalidrawSettings,
value: unknown,
) => {
if (!hasNonEmptyString(value) || hasNonEmptyString(migrated[key])) {
return;
}
migratedRecord[key] = value.trim();
didMigrate = true;
};
const assignPositiveNumberIfMissing = (
key: keyof ExcalidrawSettings,
value: unknown,
) => {
if (!hasPositiveNumber(value) || hasPositiveNumber(migrated[key])) {
return;
}
migratedRecord[key] = value;
didMigrate = true;
};
assignStringIfMissing("aiAPIKey", settings.openAIAPIToken);
assignStringIfMissing(
"aiDefaultMultimodalModel",
settings.aiDefaultVisionModel,
);
assignStringIfMissing(
"aiDefaultMultimodalModel",
settings.openAIDefaultVisionModel,
);
assignStringIfMissing("aiDefaultTextModel", settings.openAIDefaultTextModel);
assignStringIfMissing("aiDefaultTextModel", settings.aiDefaultVisionModel);
assignStringIfMissing(
"aiDefaultTextModel",
settings.openAIDefaultVisionModel,
);
assignStringIfMissing(
"aiDefaultImageGenerationModel",
settings.openAIDefaultImageGenerationModel,
);
assignPositiveNumberIfMissing(
"aiDefaultMaxResponseTokens",
settings.aiDefaultMaxTokens,
);
assignPositiveNumberIfMissing(
"aiDefaultMaxResponseTokens",
settings.openAIDefaultTextModelMaxTokens,
);
const legacyTextEndpoint = normalizeAISettingURL(settings.openAIURL);
const inferredLegacyBaseURL = legacyTextEndpoint.endsWith(AI_TEXT_SUFFIX)
? legacyTextEndpoint.slice(0, -AI_TEXT_SUFFIX.length)
: legacyTextEndpoint;
assignStringIfMissing("aiBaseURL", inferredLegacyBaseURL);
const effectiveBaseURL =
normalizeAISettingURL(migrated.aiBaseURL) || inferredLegacyBaseURL;
const derivedTextEndpoint = joinAISettingURL(
effectiveBaseURL,
AI_TEXT_SUFFIX,
);
if (
hasNonEmptyString(legacyTextEndpoint) &&
!hasNonEmptyString(migrated.aiTextEndpoint) &&
legacyTextEndpoint !== derivedTextEndpoint
) {
migrated.aiTextEndpoint = legacyTextEndpoint;
didMigrate = true;
}
const assignEndpointOverrideIfNeeded = (
key: keyof ExcalidrawSettings,
legacyValue: unknown,
suffix: string,
) => {
const normalizedLegacyValue = normalizeAISettingURL(legacyValue);
if (!normalizedLegacyValue || hasNonEmptyString(migrated[key])) {
return;
}
const derivedEndpoint = joinAISettingURL(effectiveBaseURL, suffix);
if (!derivedEndpoint || normalizedLegacyValue !== derivedEndpoint) {
migratedRecord[key] = normalizedLegacyValue;
didMigrate = true;
}
};
assignEndpointOverrideIfNeeded(
"aiImageGenerationEndpoint",
settings.openAIImageGenerationURL,
"/images/generations",
);
assignEndpointOverrideIfNeeded(
"aiImageEditsEndpoint",
settings.openAIImageEditsURL,
"/images/edits",
);
assignEndpointOverrideIfNeeded(
"aiImageVariationsEndpoint",
settings.openAIImageVariationURL,
"/images/variations",
);
const hadProviderProfiles = Boolean(
migrated.aiProviderProfiles &&
Object.keys(migrated.aiProviderProfiles).length > 0,
);
const hadTextModelConfigs = Boolean(
migrated.aiTextModelConfigs &&
Object.keys(migrated.aiTextModelConfigs).length > 0,
);
const hadVisionModelConfigs = Boolean(
migrated.aiVisionModelConfigs &&
Object.keys(migrated.aiVisionModelConfigs).length > 0,
);
const hadImageModelConfigs = Boolean(
migrated.aiImageModelConfigs &&
Object.keys(migrated.aiImageModelConfigs).length > 0,
);
const ensureProviderProfiles = () => {
if (
migrated.aiProviderProfiles &&
Object.keys(migrated.aiProviderProfiles).length > 0
) {
return migrated.aiProviderProfiles;
}
migrated.aiProviderProfiles = cloneKnownAIProviderProfiles();
didMigrate = true;
return migrated.aiProviderProfiles;
};
const ensureModelConfigs = (kind: "text" | "vision" | "image") => {
if (
kind === "text" &&
migrated.aiTextModelConfigs &&
Object.keys(migrated.aiTextModelConfigs).length > 0
) {
return migrated.aiTextModelConfigs;
}
if (
kind === "image" &&
migrated.aiImageModelConfigs &&
Object.keys(migrated.aiImageModelConfigs).length > 0
) {
return migrated.aiImageModelConfigs;
}
const defaults =
kind === "text"
? cloneModelConfigs(KNOWN_AI_TEXT_MODEL_CONFIGS)
: cloneModelConfigs(KNOWN_AI_IMAGE_MODEL_CONFIGS);
if (kind === "text") {
migrated.aiTextModelConfigs = defaults;
}
if (kind === "image") {
migrated.aiImageModelConfigs =
defaults as typeof migrated.aiImageModelConfigs;
}
didMigrate = true;
return defaults;
};
const providerProfiles = ensureProviderProfiles();
const legacyProviderType = migrated.aiProvider ?? "openai";
const providerProfileId =
LEGACY_PROVIDER_LABELS[legacyProviderType] ?? "OpenAI";
if (!hadProviderProfiles) {
providerProfiles[providerProfileId] = {
provider: legacyProviderType,
apiKey: migrated.aiAPIKey ?? "",
baseURL:
normalizeAISettingURL(migrated.aiBaseURL) ||
providerProfiles[providerProfileId]?.baseURL ||
"",
};
didMigrate = true;
}
const textModelId = (
migrated.aiDefaultTextModel ||
settings.aiDefaultVisionModel ||
settings.openAIDefaultTextModel ||
settings.openAIDefaultVisionModel ||
"gpt-5-mini"
).trim();
const multimodalTextModelId = (
migrated.aiDefaultMultimodalModel ||
settings.aiDefaultVisionModel ||
settings.openAIDefaultVisionModel ||
textModelId
).trim();
const imageModelId = (
migrated.aiDefaultImageGenerationModel ||
settings.openAIDefaultImageGenerationModel ||
"gpt-image-1"
).trim();
const legacyCapabilities = settings.aiImageModelCapabilities as
| Record<
string,
{
supportedSizes?: string[];
supportsPromptImageTransforms?: boolean;
supportsMaskImageEdits?: boolean;
supportsImageEdits?: boolean;
}
>
| undefined;
const textModels = ensureModelConfigs("text");
if (!hadTextModelConfigs) {
textModels[textModelId] = {
providerId: providerProfileId,
model: textModelId,
endpoint: migrated.aiTextEndpoint ?? "",
multimodalSupport: true,
};
}
if (hadVisionModelConfigs && migrated.aiVisionModelConfigs) {
Object.entries(migrated.aiVisionModelConfigs).forEach(
([modelId, config]) => {
const existingConfig = textModels[modelId];
if (!existingConfig) {
textModels[modelId] = {
...config,
multimodalSupport: config.multimodalSupport ?? true,
};
didMigrate = true;
return;
}
if (existingConfig.multimodalSupport === undefined) {
existingConfig.multimodalSupport = config.multimodalSupport ?? true;
didMigrate = true;
}
},
);
}
Object.values(textModels).forEach((config) => {
if (config.multimodalSupport === undefined) {
config.multimodalSupport = true;
didMigrate = true;
}
});
const imageModels = ensureModelConfigs("image") as Record<
string,
(typeof KNOWN_AI_IMAGE_MODEL_CONFIGS)[string]
>;
if (!hadImageModelConfigs) {
const legacySupportsImageEdits =
legacyCapabilities?.[imageModelId]?.supportsImageEdits;
imageModels[imageModelId] = {
providerId: providerProfileId,
model: imageModelId,
supportedSizes: [
...(legacyCapabilities?.[imageModelId]?.supportedSizes?.length
? legacyCapabilities[imageModelId].supportedSizes
: (imageModels[imageModelId]?.supportedSizes ?? ["1024x1024"])),
],
supportsPromptImageTransforms:
legacyCapabilities?.[imageModelId]?.supportsPromptImageTransforms ??
imageModels[imageModelId]?.supportsPromptImageTransforms ??
legacySupportsImageEdits ??
true,
supportsMaskImageEdits:
legacyCapabilities?.[imageModelId]?.supportsMaskImageEdits ??
imageModels[imageModelId]?.supportsMaskImageEdits ??
legacySupportsImageEdits ??
true,
};
}
Object.entries(imageModels).forEach(([modelId, config]) => {
const legacyConfig = config as typeof config & {
supportsImageEdits?: boolean;
};
const legacySupportsImageEdits =
legacyCapabilities?.[modelId]?.supportsImageEdits ??
legacyConfig.supportsImageEdits;
const nextConfig = {
...config,
supportsPromptImageTransforms:
config.supportsPromptImageTransforms ??
legacyCapabilities?.[modelId]?.supportsPromptImageTransforms ??
legacySupportsImageEdits ??
true,
supportsMaskImageEdits:
config.supportsMaskImageEdits ??
legacyCapabilities?.[modelId]?.supportsMaskImageEdits ??
legacySupportsImageEdits ??
true,
};
if (
nextConfig.supportsPromptImageTransforms !==
config.supportsPromptImageTransforms ||
nextConfig.supportsMaskImageEdits !== config.supportsMaskImageEdits ||
legacyConfig.supportsImageEdits !== undefined
) {
imageModels[modelId] = nextConfig;
delete (
imageModels[modelId] as typeof nextConfig & {
supportsImageEdits?: boolean;
}
).supportsImageEdits;
didMigrate = true;
}
});
if (!migrated.aiDefaultTextModel) {
migrated.aiDefaultTextModel = textModelId;
}
if (!migrated.aiDefaultMultimodalModel) {
migrated.aiDefaultMultimodalModel = multimodalTextModelId;
}
if (!migrated.aiDefaultImageGenerationModel) {
migrated.aiDefaultImageGenerationModel = imageModelId;
}
if (migrated.aiDefaultVisionModel !== undefined) {
delete migratedRecord.aiDefaultVisionModel;
didMigrate = true;
}
if (migrated.aiVisionModelConfigs !== undefined) {
delete migratedRecord.aiVisionModelConfigs;
didMigrate = true;
}
return { settings: migrated, didMigrate };
};
export default class ExcalidrawPlugin extends Plugin {
public extrasGateway: ExcalidrawExtrasGateway;
private fileManager: PluginFileManager;
@@ -844,20 +431,9 @@ export default class ExcalidrawPlugin extends Plugin {
}
private async onloadCheckForOnceOffSettingsUpdates() {
const updateSettings =
!this.settings.onceOffCompressFlagReset ||
!this.settings.onceOffGPTVersionReset;
if (!this.settings.onceOffCompressFlagReset) {
this.settings.compress = true;
this.settings.onceOffCompressFlagReset = true;
}
if (!this.settings.onceOffGPTVersionReset) {
this.settings.onceOffGPTVersionReset = true;
if (this.settings.openAIDefaultVisionModel === "gpt-4-vision-preview") {
this.settings.openAIDefaultVisionModel = "gpt-4o";
}
}
if (updateSettings) {
await this.saveSettings();
}
this.addSettingTab(new ExcalidrawSettingTab(this.app, this));
@@ -1621,11 +1197,8 @@ export default class ExcalidrawPlugin extends Plugin {
if (typeof opts.reEnableAutosave === "undefined") {
opts.reEnableAutosave = false;
}
const rawSettings = ((await this.loadData()) ??
const persistedSettings = ((await this.loadData()) ??
{}) as PersistedExcalidrawSettings;
const { settings: migratedSettings, didMigrate } =
migrateLegacyAISettings(rawSettings);
const persistedSettings = stripLegacyAISettings(migratedSettings);
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
let didSettingsMigration = false;
this.settings = Object.assign({}, DEFAULT_SETTINGS, decryptedSettings);
@@ -1725,12 +1298,12 @@ export default class ExcalidrawPlugin extends Plugin {
}
}
const encryptedPersistedSettings = encryptPersistedAPIKeys(
stripLegacyAISettings(this.settings as PersistedExcalidrawSettings),
this.settings as PersistedExcalidrawSettings,
);
const shouldPersistEncryptedSettings =
JSON.stringify(encryptedPersistedSettings) !==
JSON.stringify(persistedSettings);
if (didMigrate || didSettingsMigration || shouldPersistEncryptedSettings) {
if (didSettingsMigration || shouldPersistEncryptedSettings) {
await this.saveData(encryptedPersistedSettings);
}
if (opts.reEnableAutosave) {
@@ -1739,10 +1312,11 @@ export default class ExcalidrawPlugin extends Plugin {
}
async saveSettings() {
const persistedSettings = stripLegacyAISettings(
this.settings as PersistedExcalidrawSettings,
await this.saveData(
encryptPersistedAPIKeys(
this.settings as PersistedExcalidrawSettings,
),
);
await this.saveData(encryptPersistedAPIKeys(persistedSettings));
}
async onExternalSettingsChange() {
+26 -23
View File
@@ -20,7 +20,8 @@ import {
nanoid,
VIEW_TYPE_EXCALIDRAW,
} from "src/constants/constants";
import { Prompt, templatePromt } from "src/shared/Dialogs/Prompt";
import { templatePromt } from "src/shared/Dialogs/Prompt";
import { FileAndFolderSelectorModal } from "src/shared/Dialogs/FileAndFolderSelectorModal";
import {
changeThemeOfExcalidrawMD,
ExcalidrawData,
@@ -32,6 +33,7 @@ import ExcalidrawPlugin from "src/core/main";
import {
checkAndCreateFolder,
createFileAndAwaitMetacacheUpdate,
createOrOverwriteFile,
download,
getIMGFilename,
getLink,
@@ -47,6 +49,7 @@ import {
import { errorlog, getExportTheme } from "src/utils/utils";
import { getImageCache } from "src/shared/ImageCache";
import { PaneTarget } from "src/types/utilTypes";
import { t } from "src/lang/helpers";
export class PluginFileManager {
private plugin: ExcalidrawPlugin;
@@ -384,29 +387,29 @@ export class PluginFileManager {
public async exportLibrary() {
if (DEVICE.isMobile) {
const prompt = new Prompt(
this.app,
"Please provide a filename",
"my-library",
"filename, leave blank to cancel action",
const location = await new FileAndFolderSelectorModal(this.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: normalizePath(this.settings.folder),
fileName: "my-library.excalidrawlib",
}).start();
if (!location) {
return;
}
const filename = location.fileName
.toLowerCase()
.endsWith(".excalidrawlib")
? location.fileName
: `${location.fileName}.excalidrawlib`;
const fname = getNewUniqueFilepath(
this.app.vault,
filename,
location.folderPath,
);
void prompt.openAndGetValue((filename: string) => {
void (async () => {
if (!filename) {
return;
}
filename = `${filename}.excalidrawlib`;
const folderpath = normalizePath(this.settings.folder);
await checkAndCreateFolder(folderpath); //create folder if it does not exist
const fname = getNewUniqueFilepath(
this.app.vault,
filename,
folderpath,
);
await this.app.vault.create(fname, this.settings.library);
new Notice(`Exported library to ${fname}`, 6000);
})();
});
await createOrOverwriteFile(this.app, fname, this.settings.library);
new Notice(`Exported library to ${fname}`, 6000);
return;
}
download(
+16 -169
View File
@@ -111,7 +111,6 @@ export interface ExcalidrawSettings {
compress: boolean;
decompressForMDView: boolean;
onceOffCompressFlagReset: boolean; //used to reset compress to true in 2.2.0
onceOffGPTVersionReset: boolean; //used to reset GPT version in 2.2.11
autosave: boolean;
autosaveIntervalDesktop: number;
autosaveIntervalMobile: number;
@@ -270,32 +269,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 +373,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 +436,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,7 +558,6 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
compress: true,
decompressForMDView: false,
onceOffCompressFlagReset: false,
onceOffGPTVersionReset: false,
autosave: true,
autosaveIntervalDesktop: 60000,
autosaveIntervalMobile: 30000,
@@ -807,32 +762,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 +1082,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 +1114,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 +1200,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 +1247,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 +1267,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 +1281,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 +2023,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 +2048,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);
}
+6 -6
View File
@@ -145,11 +145,10 @@ export default {
MARKDOWN_IMAGE_BORDER: "Border",
MARKDOWN_IMAGE_BORDER_COLOR: "Border color",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC: "CSS rules applied only to this Markdown image.",
MARKDOWN_IMAGE_CSS_DESC:
"CSS for this Markdown image only. Copy the SVG below and ask your preferred LLM for the CSS you need.",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"If a rule has no effect, add !important to the declaration.",
MARKDOWN_IMAGE_CSS_SVG_COPY_HINT:
"Use the copy button below to copy the generated SVG for inspection.",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "CSS editor for this Markdown image",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"CSS editor for transcluded Markdown",
@@ -190,7 +189,10 @@ export default {
"Could not change the Markdown image source",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "Could not create a local Markdown copy",
MARKDOWN_IMAGE_EXTRACT_TITLE: "Extract Markdown image to note",
MARKDOWN_IMAGE_EXTRACT_PATH: "Path to the new Markdown note",
FILE_AND_FOLDER_SELECTOR_FOLDER: "Folder",
FILE_AND_FOLDER_SELECTOR_FILENAME: "File name",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "Export to Vault",
FILE_AND_FOLDER_SELECTOR_EXPORT: "Export",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown image.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "Could not create Markdown note",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "Unknown error",
@@ -292,8 +294,6 @@ export default {
"Inverted Mode: Default arrow binding is now disabled. Use CTRL/CMD to temporarily enable binding when needed.",
ARROW_BINDING_NORMAL_MODE:
"Normal Mode: Arrow binding is now enabled. Use CTRL/CMD to temporarily disable binding when needed.",
EXPORT_FILENAME_PROMPT: "Please provide filename",
EXPORT_FILENAME_PROMPT_PLACEHOLDER: "filename, leave blank to cancel action",
WARNING_SERIOUS_ERROR:
"WARNING: Excalidraw ran into an unknown problem!\n\n" +
"There is a risk that your most recent changes cannot be saved.\n\n" +
+6 -7
View File
@@ -146,11 +146,10 @@ export default {
MARKDOWN_IMAGE_BORDER: "Borde",
MARKDOWN_IMAGE_BORDER_COLOR: "Color del borde",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC: "Reglas CSS aplicadas solo a esta imagen Markdown.",
MARKDOWN_IMAGE_CSS_DESC:
"CSS solo para esta imagen Markdown. Copia el SVG de abajo y pide a tu LLM preferido el CSS que necesitas.",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"Si una regla no tiene efecto, añade !important a la declaración.",
MARKDOWN_IMAGE_CSS_SVG_COPY_HINT:
"Usa el botón de copia de abajo para copiar el SVG generado y examinarlo.",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "Editor CSS para esta imagen Markdown",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"Editor CSS para Markdown transcluido",
@@ -190,7 +189,10 @@ export default {
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "No se pudo cambiar la fuente de la imagen Markdown",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "No se pudo crear una copia Markdown local",
MARKDOWN_IMAGE_EXTRACT_TITLE: "Extraer imagen Markdown a una nota",
MARKDOWN_IMAGE_EXTRACT_PATH: "Ruta de la nueva nota Markdown",
FILE_AND_FOLDER_SELECTOR_FOLDER: "Carpeta",
FILE_AND_FOLDER_SELECTOR_FILENAME: "Nombre del archivo",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "Exportar a la bóveda",
FILE_AND_FOLDER_SELECTOR_EXPORT: "Exportar",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Imagen Markdown.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "No se pudo crear la nota Markdown",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "Error desconocido",
@@ -282,9 +284,6 @@ export default {
"Modo Invertido: La vinculación de flechas predeterminada está ahora deshabilitada. Usa CTRL/CMD para habilitar temporalmente la vinculación cuando sea necesario.",
ARROW_BINDING_NORMAL_MODE:
"Modo Normal: La vinculación de flechas está ahora habilitada. Usa CTRL/CMD para deshabilitar temporalmente la vinculación cuando sea necesario.",
EXPORT_FILENAME_PROMPT: "Por favor, ingresa el nombre de archivo",
EXPORT_FILENAME_PROMPT_PLACEHOLDER:
"nombre de archivo, dejar en blanco para cancelar la acción",
WARNING_SERIOUS_ERROR:
"ADVERTENCIA: ¡Excalidraw encontró un problema desconocido!\n\n" +
"Existe el riesgo de que tus cambios más recientes no se puedan guardar.\n\n" +
+5 -7
View File
@@ -138,11 +138,9 @@ export default {
MARKDOWN_IMAGE_BORDER_COLOR: "Цвет рамки",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC:
"Правила CSS применяются только к этому Markdown-изображению.",
"CSS только для этого Markdown-изображения. Скопируйте SVG ниже и попросите предпочитаемую LLM подобрать нужный CSS.",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"Если правило не действует, добавьте !important к объявлению.",
MARKDOWN_IMAGE_CSS_SVG_COPY_HINT:
"Используйте кнопку копирования ниже, чтобы скопировать созданный SVG для проверки.",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "Редактор CSS для этого Markdown-изображения",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"Редактор CSS для встроенного Markdown",
@@ -182,7 +180,10 @@ export default {
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "Не удалось изменить источник Markdown-изображения",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "Не удалось создать локальную копию Markdown",
MARKDOWN_IMAGE_EXTRACT_TITLE: "Извлечь Markdown-изображение в заметку",
MARKDOWN_IMAGE_EXTRACT_PATH: "Путь к новой Markdown-заметке",
FILE_AND_FOLDER_SELECTOR_FOLDER: "Папка",
FILE_AND_FOLDER_SELECTOR_FILENAME: "Имя файла",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "Экспорт в хранилище",
FILE_AND_FOLDER_SELECTOR_EXPORT: "Экспортировать",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown-изображение.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "Не удалось создать Markdown-заметку",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "Неизвестная ошибка",
@@ -284,9 +285,6 @@ export default {
"Инвертированный режим: Привязка стрелок по умолчанию теперь отключена. Используйте CTRL/CMD, чтобы временно включить привязку, когда это необходимо.",
ARROW_BINDING_NORMAL_MODE:
"Обычный режим: Привязка стрелок теперь включена. Используйте CTRL/CMD, чтобы временно отключить привязку при необходимости.",
EXPORT_FILENAME_PROMPT: "Пожалуйста, укажите имя файла",
EXPORT_FILENAME_PROMPT_PLACEHOLDER:
"имя файла, оставьте пустым, чтобы отменить действие",
WARNING_SERIOUS_ERROR:
"ПРЕДУПРЕЖДЕНИЕ: Excalidraw столкнулся с неизвестной проблемой!\n\n" +
"Есть риск, что последние изменения не будут сохранены.\n\n" +
+6 -6
View File
@@ -125,11 +125,10 @@ export default {
MARKDOWN_IMAGE_BORDER: "边框",
MARKDOWN_IMAGE_BORDER_COLOR: "边框颜色",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC: "仅应用于此 Markdown 图像的 CSS 规则。",
MARKDOWN_IMAGE_CSS_DESC:
"CSS 仅应用于此 Markdown 图像。复制下方的 SVG,让你选择的 LLM 生成所需的 CSS。",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"如果规则没有效果,请在声明中添加 !important。",
MARKDOWN_IMAGE_CSS_SVG_COPY_HINT:
"使用下方的复制按钮复制生成的 SVG 以供检查。",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "此 Markdown 图像的 CSS 编辑器",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"嵌入 Markdown 的 CSS 编辑器",
@@ -164,7 +163,10 @@ export default {
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "无法更改 Markdown 图像来源",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "无法创建本地 Markdown 副本",
MARKDOWN_IMAGE_EXTRACT_TITLE: "将 Markdown 图像提取到笔记",
MARKDOWN_IMAGE_EXTRACT_PATH: "新 Markdown 笔记的路径",
FILE_AND_FOLDER_SELECTOR_FOLDER: "文件夹",
FILE_AND_FOLDER_SELECTOR_FILENAME: "文件名",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "导出到仓库",
FILE_AND_FOLDER_SELECTOR_EXPORT: "导出",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown 图像.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "无法创建 Markdown 笔记",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "未知错误",
@@ -255,8 +257,6 @@ export default {
"反转模式:默认方向按键已禁用。需要时请使用 Ctrl/CMD 临时启用。",
ARROW_BINDING_NORMAL_MODE:
"正常模式:方向键已启用。需要时请使用 Ctrl/CMD 临时禁用。",
EXPORT_FILENAME_PROMPT: "请提供文件名",
EXPORT_FILENAME_PROMPT_PLACEHOLDER: "请输入文件名,留空以取消操作",
WARNING_SERIOUS_ERROR:
"警告:Excalidraw 遇到了未知的问题!\n\n" +
"您最近的更改可能无法保存。\n\n" +
+6 -6
View File
@@ -125,11 +125,10 @@ export default {
MARKDOWN_IMAGE_BORDER: "邊框",
MARKDOWN_IMAGE_BORDER_COLOR: "邊框顏色",
MARKDOWN_IMAGE_CSS: "CSS",
MARKDOWN_IMAGE_CSS_DESC: "僅套用於此 Markdown 圖像的 CSS 規則。",
MARKDOWN_IMAGE_CSS_DESC:
"CSS 僅套用於此 Markdown 圖像。複製下方的 SVG,讓你選擇的 LLM 產生所需的 CSS。",
MARKDOWN_IMAGE_CSS_IMPORTANT_HINT:
"如果規則沒有作用,請在宣告中加入 !important。",
MARKDOWN_IMAGE_CSS_SVG_COPY_HINT:
"使用下方的複製按鈕複製產生的 SVG 以供檢查。",
MARKDOWN_IMAGE_CSS_EDITOR_ARIA: "此 Markdown 圖像的 CSS 編輯器",
MARKDOWN_IMAGE_TRANSCLUSION_CSS_EDITOR_ARIA:
"嵌入 Markdown 的 CSS 編輯器",
@@ -164,7 +163,10 @@ export default {
MARKDOWN_IMAGE_CHANGE_SOURCE_ERROR: "無法變更 Markdown 圖像來源",
MARKDOWN_IMAGE_LOCAL_COPY_ERROR: "無法建立本機 Markdown 副本",
MARKDOWN_IMAGE_EXTRACT_TITLE: "將 Markdown 圖像擷取到筆記",
MARKDOWN_IMAGE_EXTRACT_PATH: "新 Markdown 筆記的路徑",
FILE_AND_FOLDER_SELECTOR_FOLDER: "資料夾",
FILE_AND_FOLDER_SELECTOR_FILENAME: "檔案名稱",
FILE_AND_FOLDER_SELECTOR_EXPORT_TITLE: "匯出到儲存庫",
FILE_AND_FOLDER_SELECTOR_EXPORT: "匯出",
MARKDOWN_IMAGE_DEFAULT_NOTE: "Markdown 圖像.md",
MARKDOWN_IMAGE_CREATE_NOTE_ERROR: "無法建立 Markdown 筆記",
MARKDOWN_IMAGE_UNKNOWN_ERROR: "未知錯誤",
@@ -255,8 +257,6 @@ export default {
"反轉模式:預設方向按鍵已停用。需要時請使用 Ctrl/CMD 臨時啟用。",
ARROW_BINDING_NORMAL_MODE:
"正常模式:方向鍵已啟用。需要時請使用 Ctrl/CMD 臨時停用。",
EXPORT_FILENAME_PROMPT: "請提供檔名",
EXPORT_FILENAME_PROMPT_PLACEHOLDER: "請輸入檔名,留空以取消操作",
WARNING_SERIOUS_ERROR:
"警告:Excalidraw 遇到了未知的問題!\n\n" +
"您最近的更改可能無法儲存。\n\n" +
@@ -0,0 +1,107 @@
import { Modal, Setting, type App, type ButtonComponent } from "obsidian";
import { t } from "src/lang/helpers";
import { VaultPathSuggest } from "src/shared/Suggesters/VaultPathSuggest";
/** Folder and filename selected in a {@link FileAndFolderSelectorModal}. */
export type FileAndFolderSelection = {
folderPath: string;
fileName: string;
};
/** Labels and initial values for a {@link FileAndFolderSelectorModal}. */
export type FileAndFolderSelectorOptions = FileAndFolderSelection & {
title: string;
folderLabel: string;
fileNameLabel: string;
submitButtonText: string;
};
/** Prompts for a Vault folder and filename. */
export class FileAndFolderSelectorModal extends Modal {
private resolvePromise: (
selection: FileAndFolderSelection | null,
) => void;
private result: FileAndFolderSelection | null = null;
constructor(
app: App,
private readonly options: FileAndFolderSelectorOptions,
) {
super(app);
}
/** Opens the modal and resolves with the selection or null when cancelled. */
public start(): Promise<FileAndFolderSelection | null> {
const result = new Promise<FileAndFolderSelection | null>((resolve) => {
this.resolvePromise = resolve;
});
this.open();
return result;
}
public onOpen(): void {
this.titleEl.setText(this.options.title);
this.contentEl.addClass("excalidraw-file-and-folder-selector");
let folderPath = this.options.folderPath;
let fileName = this.options.fileName;
let submitButton: ButtonComponent | null = null;
const updateSubmitButton = (): void => {
submitButton?.setDisabled(fileName.trim().length === 0);
};
const folderSetting = new Setting(this.contentEl)
.setClass("excalidraw-file-and-folder-selector__field")
.setName(this.options.folderLabel)
.addText((text) => {
text.setValue(folderPath).onChange((value) => {
folderPath = value.trim();
});
new VaultPathSuggest(this.app, text.inputEl, "folder");
});
folderSetting.controlEl.addClass("excalidraw-folder-path-control");
let fileNameInput: HTMLInputElement | null = null;
new Setting(this.contentEl)
.setClass("excalidraw-file-and-folder-selector__field")
.setName(this.options.fileNameLabel)
.addText((text) => {
fileNameInput = text.inputEl;
text.setValue(fileName).onChange((value) => {
fileName = value;
updateSubmitButton();
});
});
new Setting(this.contentEl)
.addButton((button) =>
button
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
.onClick(() => this.close()),
)
.addButton((button) => {
submitButton = button;
button
.setCta()
.setButtonText(this.options.submitButtonText)
.onClick(() => {
this.result = {
folderPath,
fileName: fileName.trim(),
};
this.close();
});
updateSubmitButton();
});
this.containerEl.ownerDocument.defaultView?.setTimeout(
() => fileNameInput?.focus(),
0,
);
}
public onClose(): void {
this.contentEl.empty();
this.resolvePromise?.(this.result);
}
}
+40 -268
View File
@@ -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
- Retired obsolete pre-profile ExcalidrawAI settings migration and fallback handling. Current provider profiles and model configurations are unchanged.
`,
"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.
@@ -437,253 +457,5 @@ async addImage(
anchor: boolean = true,
): Promise<string>;
\`\`\`
`,
"2.22.3": `
Feeling overwhelmed by Excalidraw's endless features?
It's not just a drawing tool. Inside Obsidian, it becomes a thinking tool.
To unlock linking, embedding, and referencing, you need a mindset shift.
**Join Excalidraw Mastery** to make that shift.
Courses, live Q&As, and deep dives to help you move into true 4D Visual PKM. 👉 https://community.sketch-your-mind.com/em
<div style="text-align:center;margin-top:10px;">
<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank"><img src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EM_PNG}" style="width:50%"></a>
</div>
Excalidraw Mastery is part of the **Sketch Your Mind Community**—a space for visual thinkers.
Share your work. Ask questions. Learn from others. 👉 https://community.sketch-your-mind.com
Curious about the philosophy behind it?
${getYouTubeDiv("TnwRlaIdhSU")}
`,
"2.22.1": `
## New
- Added a command palette action to switch all currently open Excalidraw drawings to view mode.
- While this temporary mode is enabled, any Excalidraw drawing opened afterward will also open in view mode.
- This is useful when presenting multiple drawings and you want to avoid accidentally moving elements, and when you don't want the tools to be in the way.
- Added an optional phone-only layout setting to push Excalidraw's footer controls above the system navigation bar on some Android devices [#2688](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2688), [#2652](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2652), [#798](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/798)
- Look for ""Extra bottom padding for phone controls" in the plugin settings.
## Fixed
- invisible cursor color in color picker, mermaid chat, in text elements in dark mode [#2739](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2739)
- image sizing issue when embedding image type "SVG Image" to markdown
- copying a nested image fragment in Excalidraw and pasting to markdown lost the image block reference
- modifier keys conflicted with Excalidraw alt-select (lasso) behavior
`,
"2.22.0": `
## Fixed
- Fixed misaligned panel buttons in tray mode [#2718](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2718) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
- Improved loading of nested Excalidraw files within a scene, with some additional performance gains.
- Fixed an issue where the caret color did not match the text color [#11018](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/11018)
## New from Excalidraw.com
- Added several text editing improvements, including a right-side handle on wrapped text for easier auto-resizing without opening the context menu [#10979](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10979)
- Added support for Mermaid state diagrams [#11031](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11031)
- There is a new Preferences menu above the Dark/Light mode switch in the main menu [#10760](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10760)
- Added a new Preferences option to switch between Wrap and Overlap selection modes. Overlap mode behaves similarly to the lasso selection tool available under More Tools [#11053](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11053)
## New
- Added support for embedding the [Sheet Plus](obsidian://show-plugin?id=sheet-plus) plugin as an active embeddable element in Excalidraw. At the moment, changing the canvas theme between dark and light mode does not automatically re-render embedded sheets. To apply the theme change, close and reopen the drawing. This will likely be improved in a future update.
`,
"2.21.3": `
## Fixed
- Caret color for link editor, text elemnts in dark mode, color picker input element.
- Link click behavior modifier keys setting in plugin settings now enforces CTRL/CMD for link clicks and improves on clarity of setting UI by adding a header row
- Link click conbinations that included ALT/OPT did not work because they trigger lasso selection in Excalidraw. This is now fixed, if you CTRL+ALT click a link it will navigate while retaining the lasso select feature when pressing ALT/OPT.
- Copying an image block embed (e.g. \`![[drawing#^frame=my_frame]]\`) from the excalidraw scene and pasting it to markdown no longer loses the frame reference
- Embed "SVG Image" to markdown should size correctly now when setting a percentage \`![[drawing|50%]]\` where 50% is relative to the width of the markdown note.
`,
"2.21.2": `
## Fixed
- The new ExcalidrawAutomate function \`parseText()\` broke if the text was a transcluded image or PDF document, causing downstream paste issues in MindMap Builder.
- Custom pen sloppiness not being saved to a template drawing [#2715](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2715) 🙏[@sreedharsreeram](${URLs.GITHUB_COM_SREEDHARSREERAM})
`,
"2.21.1": `
## Fixed
- Drawing and editor fails to initialize in a new window [#2713](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2713)
- Duplicate selected image with a different image ID command palette action did not duplicate cropped PDF images.
- Memory leak issue with PDF import as images.
## New
- Put caret at pointer position when clicking on selected text element [#10970](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10970)
`,
"2.21.0": `
## New
- LaTeX editor is now floating [#2684](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2684) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1}), [#2698](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2698) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
- Inline link suggester supports new triggers \`![[drawing#^frame=\` and \`![[drawing#^clippedframe=\`, thus it is easy to reference frames like pdf pages, slides or other parts of your scene marked using marker frames.
- Support for mermaid Entity Relationship Diagrams, and new ERD/cardinality arrowheads [#10940](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10940)
- New Context Menu options to disable arrow binding and midpoint snapping [#10906](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10906)
- Improved UI styling and icons are better aligned with Obsidian [#2703](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2703), [#2687](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2687), [#2697](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2697) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
## Fixed
- Sizing of embedded images in Markdown when image type is set to SVG [#2685](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2685)
- Fixed Enter, Up/Down arrows, and TAB keys stopped working in text elements after deleting the \`#\` character [#2704](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2704)
## MindMap Builder
- Fixed navigation (arrow keys) scoping and recognition
- Added new feature to paste images and single Excalidraw elements like container with text, text element, or image element directly as a map leaf (using the MindMap Builder default paste shortcut: ALT/OPT+V)
- Added new action to toggle a markdown link between markdown embeddable and link as text. Default shortcut is ALT/OPT+E.
## New in ExcalidrawAutomate
\`\`\`ts
/**
* Parses text using the target view's ExcalidrawData parser.
*
* This reuses ExcalidrawData parsing logic directly, including transclusion
* resolution, link bracket rendering, and link/url prefixes based on the
* target file's frontmatter.
*
* @param {string} text - Raw text to parse.
* @returns {Promise<string | undefined>} Parsed text, or undefined when input/view is unavailable.
*/
public async parseText (text: string): Promise<string | undefined>;
\`\`\`
`,
"2.20.6": `
${getYouTubeDiv("g-BiyQ7TJTM")}
## New
- Inline suggester now supports searching for tags in addition to files. Trigger with "#".
- In Mindmap Builder
- Added Up-Facing, Down-Facing, and Up-Down maps
- Added submaps. You can now promote any node to be a new mindmap root (a sub-map). Sub-maps can have different layout settings such as different growth strategies, different colors, etc.
- Added experimental MindMap Builder API, accessible via \`window.MindMapBuilderAPI\`. See [MindMap Builder API documentation](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPT_DOCS_MINDMAPBUILDERAPI_MD}) for more. Essentially, the API allows mindmaps to be created using the Obsidian CLI.
## New from Excalidraw.com
- Allow clicking on links and embeds with laser tool [#10797](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10797)
- Improved paste text to diagram with more options and support for more data [#10824](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10824)
try copy/pasting this into Excalidraw:
\`\`\`
skill, junior, medior, senior
business_analysis, 2, 6, 9
business_writing, 3, 7, 9
stakeholder_mgmt, 1, 6, 10
\`\`\`
## New in ExcalidrawAutomate
- Added \`skipScriptRestore(scriptName?: string): boolean\` function to the API. This allows scripts to queue a one-time skip marker so sidepanel persisted restoration will not re-run the script. Intended for startup race conditions where a script is started from the Command Palette/hotkey before the sidepanel has opened. If scriptName is omitted, the function uses ea.activeScript.
## Fixed
- Significant performance improvement of MindMap Builder and all other scripts modifying elements in large scenes containing thousands of elements.
- Multiple arrow related updates and fixes from Excalidraw.com [#10832](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10832) [#10831](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10831) [#10816](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10816)
- Hide MindMap Builder and other floating tools when creating a screenshot
`,
"2.20.5": `
## Fixed
- Obsidian Mobile: The floating navigation bar got stuck at the bottom after closing Excalidraw or switching to a markdown note. [#2673](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2673)
- "Toggle UI Mode" now includes a preference setting for Obsidian Phone as well. You can now set different default layouts for phone, tablet, and desktop. [#2670](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2670)
## New
- Added "Toggle Full Screen" button to toolbar right next to the "Obsidian menu", and the "Insert Any File" button.
`,
"2.20.4": `
## Fixed
- Fix NativeSVG embed mode into Markdown documents, ahead of the Obsidian 1.12.1 release. [#2665](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2665)
- Color picker once again supports 8-digit hex codes (Hex color string with an opacity). [#10772](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/10772)
- Fixed regression that removed LaTeX scaling. [#2668](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2668) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1})
- Corrected malformed frame embeds when using marker frames.
- Context menu options **“Do not invert image(s) in dark mode”** and **“Invert image(s) in dark mode”** now properly cascade when drawings are nested as images inside other drawings.
- Improved performance of the [MindMap Builder script](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}).
## New
- [Deconstruct Selected Elements script](${getYouTubeUrl("HRtaaD34Zzg")}) now includes a folder selection option, allowing you to choose the destination folder for the generated image.
- Arrow binding midpoints. When the projected point is close to center, snap it to the exact center. This way it's easier to create neat(er) simple arrow connections. [#10611](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10611)
`,
"2.20.3": `
## Fixed
- Hover preview when hovering an element with a link in the scene was unreliable
- If a text element had a link in the text body, in some situations, the link became unresponsive to clicks. [#2660](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2660)
## New
- Added default keymap to latex editor [#2655](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2655) 🙏[superle3](${URLs.GITHUB_COM_SUPERLE3})
`,
"2.20.2": `
## New from Excalidraw.com
- Arrow focus indicator [#10613](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10613)
## Fixed
- Experimental file type display now also works in Obsidian Mobile. (Reported on Discord)
- Text to Mermaid stores chat history locally (i.e. not synchronized between devices).
- Image positioning in crop editor [#2589](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2589), [#10726](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10726)
## MindMap Builder
- Implemented better undo support (effective only for the very last MindMap Builder action). Additionally, CMD/CTRL+Z and CTRL+Y, CMD+SHIFT+Z now work when the MindMap input window is focused.
- Fixed: Double character input issue (IME Composition Error) when creating nodes [#2647](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2647)
- Fixed: More robust error handling when the MindMap is corrupted or invalid.
- Updated Excalidraw Writing Machine to support document generation from MindMaps. Writing Machine will honor the branch order. Requires update of the Writing Machine Script.
## New in ExcalidrawAutomate
- \`getBoundTextElement()\` now also accepts an \`ExcalidrawElement[]\` (2-element selection: container + text) in addition to a single element.
- \`addElementsToView()\` extended with \`captureUpdate\` parameter (default: "IMMEDIATELY"). When set to false, the addition of elements will not be recorded in the view's history.
\`\`\`ts
async addElementsToView(
repositionToCursor: boolean = false,
save: boolean = true,
newElementsOnTop: boolean = false,
shouldRestoreElements: boolean = false,
captureUpdate: CaptureUpdateActionType = CaptureUpdateAction.IMMEDIATELY,
): Promise<boolean>
\`\`\`
`,
"2.20.1": `
## Fixed
- Fixed Experimental file type display, available under miscellaneous settings. (Reported on Discord)
- Fixed image inversion in dark mode on iOS devices. [#2636](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2636)
- Fixed UI Mode switching on tablets was unreliable.
## New/Fixed in MindMap Builder
- **Connector Ontology**: Added support for labeling connection lines. A secondary input field (accessible via Shift+Tab) is now available in both docked and floating modes. Labels are preserved during copy/paste operations using inline Dataview syntax (e.g., link ontology:: node content).
- **Connector Styling**: Introduced configuration settings for branch thickness and scaling strategies, allowing a choice between Hierarchical (tapering width by depth) or Uniform connector widths.
- **Smart Resume**: The Focus and Zoom actions now target the most recently active node if no current selection is made. This automatically focuses the input field, allowing you to quickly resume mapping from where you left off.
- **Radial Fill Sweep**: Added a "Fill Sweep Angle" option for Radial layouts. When enabled, nodes are distributed evenly across the full configured arc range, even when there are only a few nodes. (Visible only when Growth Strategy is set to "Radial").
- **Radial Navigation**: Updated Level 1 node navigation in Radial maps to follow visual vertical alignment instead of rotational order. Up/Down keys now consistently move the selection visually up or down on both sides of the circle, matching the behavior of Right-Left layouts.
- **Fixed**:
- Sidepanel opens on activation of MindMap Builder even in floating mode. Requires update of both Excalidraw and the MindMap Builder script.
- **Node Reordering**: Overhauled the logic for moving nodes via CMD/CTRL+Arrow to resolve unpredictability; nodes now move consistently to the intended locations.
- **iOS Navigation**: Resolved an issue where using the Tab key to cycle focus between components in the floating input window did not work reliably on iOS.
- **Boundary Layering**: Fixed an issue where sub-branch boundaries were placed above text elements when pasting a map; they now correctly render on the layer below the text.
- **Layout Stability**: Fixed an issue where the viewport would shift unexpectedly when pasting multiple elements onto an existing node in large scenes.
> [!Tip]- Learn MindMap Builder
> Learn it fast with the low-cost [MindMap Builder course](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}). Register before **31 Jan** to join a live Q&A:
> - Sat Jan 31 @ 18:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML}))
> - Sun Feb 1 @ 09:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML_1}))
`,
"2.20.0": `
${getYouTubeDiv("5G9QF-u9w0Q")}
> [!Tip]- Learn MindMap Builder
> Learn it fast with the low-cost [MindMap Builder course](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}). Register before **31 Jan** to join a live Q&A:
> - Sat Jan 31 @ 18:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML}))
> - Sun Feb 1 @ 09:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML_1}))
## Scripts
- Moved [Shade Master](${getYouTubeUrl("ISuORbVKyhQ")}) to use the new Excalidraw Sidepanel API (just like MindMap Builder).
## New
- Dark theme from Excalidraw.com [#10578](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10578) (including correct emoji rendering in dark mode 😍).
- New image context-menu option (right-click an image) to control whether that image inverts in dark mode
- Default behavior: SVG-based images (including LaTeX, Mermaid, and nested Excalidraw images) invert in dark mode; bitmap images (PNG/JPG) do not.
- New from Excalidraw.com: chat-style interface for Mermaid TextToDiagrams (requires an OpenAI API key configured in Excalidraw plugin settings). [#10530](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10530)
- Breaking change: the legacy “force SVG” option for Mermaid diagrams is no longer supported. If a diagram can be rendered as Excalidraw, it will be; otherwise, an SVG will be used.
- Moved the Shade Master script to use the new Sidepanel (just like MindMap Builder).
## Fixed
- In full-screen mode on phones, a large area at the top of the screen was left unused. Also fixed an issue where the Obsidian Mobile navigation bar could overlap the Excalidraw toolbar.
- The link indicator in the top-right corner would remain visible even when an element was set to transparent [#2625](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2625)
- Importing PDFs with mixed page sizes could produce distorted pages [#2578](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2578)
- Some PDFs failed to load when importing PDFs as images (notably documents using JPEG2000-compressed images). Also improved handling of certain color profiles and cases where text rendered with missing/incorrect glyphs.
- A long-standing export issue: when exporting in a theme different from the current view (e.g., viewing in dark mode but exporting in light mode), nested Excalidraw images containing bitmap images could export with inverted colors.
`,
};
+237 -16
View File
@@ -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,
@@ -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: "&#8203;"});
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
+32 -14
View File
@@ -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");
@@ -2753,7 +2763,7 @@ export const getTransclusion = async (
if (!para) {
return { contents: linkParts.original.trim(), lineNum: 0 };
}
if (["blockquote"].includes(para.type)) {
if (para.type === "blockquote" && para.children?.[0]) {
para = para.children[0];
} //blockquotes are special, they have one child, which has the paragraph
const startPos = para.position.start.offset;
@@ -2770,38 +2780,46 @@ export const getTransclusion = async (
}
const headings = blocks.filter(
(block: MarkdownBlockCacheEntry) => block.display.search(/^#+\s/) === 0,
(block: MarkdownBlockCacheEntry) =>
block.node.type === "heading" &&
block.display.search(/^#+\s/) === 0 &&
Boolean(block.node.children?.[0]?.position?.start),
); // startsWith("#"));
let startPos: number = null;
let lineNum: number = 0;
let endPos: number = null;
let depth: number = 1;
for (let i = 0; i < headings.length; i++) {
if (startPos && !endPos) {
if (startPos !== null) {
let j = i;
while (j < headings.length && headings[j].node.depth > depth) {
while (
j < headings.length &&
(headings[j].node.depth ?? 1) > depth
) {
j++;
}
if (j === headings.length && headings[j - 1].node.depth > depth) {
if (j === headings.length) {
return {
leadingHashes: `${"#".repeat(depth)} `,
contents: contents.substring(startPos).trim(),
lineNum,
};
}
endPos = headings[j].node.position.start.offset - 1;
const endPos = headings[j].node.position.start.offset - 1;
return {
leadingHashes: `${"#".repeat(depth)} `,
contents: contents.substring(startPos, endPos).trim(),
lineNum,
};
}
const c = headings[i].node.children[0];
const c = headings[i].node.children?.[0];
if (!c) {
continue;
}
const dataHeading = headings[i].node.data?.hProperties?.dataHeading;
const cc = c?.children;
//const refNoSpace = linkParts.ref.replaceAll(" ","");
if (
!startPos &&
startPos === null &&
(cleanBlockRef(c?.value) === linkParts.ref ||
cleanBlockRef(c?.title) === linkParts.ref ||
cleanBlockRef(dataHeading) === linkParts.ref ||
@@ -2811,12 +2829,12 @@ export const getTransclusion = async (
cleanSectionHeading(dataHeading) === linkParts.ref ||
(cc ? cleanSectionHeading(cc[0]?.value) === linkParts.ref : false))
) {
startPos = headings[i].node.children[0]?.position.start.offset; //
depth = headings[i].node.depth;
lineNum = headings[i].node.children[0]?.position.start.line; //
startPos = c.position.start.offset;
depth = headings[i].node.depth ?? 1;
lineNum = c.position.start.line;
}
}
if (startPos) {
if (startPos !== null) {
return {
leadingHashes: `${"#".repeat(depth)} `,
contents: contents.substring(startPos).trim(),
+12 -8
View File
@@ -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;
}
@@ -1,4 +1,4 @@
import type { App, TFile } from "obsidian";
import { resolveSubpath, type App, type TFile } from "obsidian";
import { MD_EX_SECTIONS, nanoid } from "src/constants/constants";
import { t } from "src/lang/helpers";
import { ScriptEngine } from "src/shared/Scripts";
@@ -35,7 +35,7 @@ export async function getMarkdownHeadingSubpaths(
file: TFile,
isExcalidrawFile: boolean,
): Promise<MarkdownHeadingSubpath[]> {
return (
const sections = (
await app.metadataCache.blockCache.getForFile(
{ isCancelled: () => false },
file,
@@ -50,6 +50,13 @@ export async function getMarkdownHeadingSubpaths(
display: entry.display,
subpath: `#${cleanSectionHeading(entry.display)}`,
}));
const fileCache = app.metadataCache.getFileCache(file);
return fileCache
? sections.filter(
(section) =>
resolveSubpath(fileCache, section.subpath)?.type === "heading",
)
: [];
}
function isParagraphLikeBlockEntry(
+15 -101
View File
@@ -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,
};
};
+18
View File
@@ -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());
}
+2 -2
View File
@@ -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")) {
+55 -1
View File
@@ -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 `&nbsp;` 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("&nbsp;", " ");
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
+8 -52
View File
@@ -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
+85
View File
@@ -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;
}
+5 -52
View File
@@ -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,
+35
View File
@@ -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);
+46
View File
@@ -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
View File
@@ -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][],
+43
View File
@@ -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$/, "");
}
+15 -283
View File
@@ -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,
@@ -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("&nbsp;", " ");
// 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][]> & {
+44
View File
@@ -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])))
);
}
+234 -181
View File
@@ -82,7 +82,6 @@ import {
unwrapMarkdownImageBlock,
} from "../shared/ExcalidrawData";
import {
checkAndCreateFolder,
createFileAndAwaitMetacacheUpdate,
createOrOverwriteFile,
download,
@@ -143,7 +142,6 @@ import {
LaTexPrompt,
MultiOptionConfirmationPrompt,
NewFileActions,
Prompt,
linkPrompt,
} from "../shared/Dialogs/Prompt";
import {
@@ -188,6 +186,7 @@ import {
SwordColors,
} from "../constants/actionIcons";
import { ExportDialog } from "../shared/Dialogs/ExportDialog";
import { FileAndFolderSelectorModal } from "../shared/Dialogs/FileAndFolderSelectorModal";
import { getEA } from "src/core";
import {
anyModifierKeysPressed,
@@ -277,7 +276,11 @@ import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
import { copyLinkToSelectedElementToClipboard } from "src/shared/Dialogs/copyLinkToSelectedElement";
import { getPDFCropRect } from "src/utils/PDFUtils";
import { ttdPersistenceAdapter } from "src/shared/TTDDialogPersistanceAdater";
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
import {
CaptureUpdateActionType,
DurableIncrement,
EphemeralIncrement,
} from "@zsviczian/excalidraw/types/element/src";
import {
getTextElementsMatchingQuery,
getFrameElementsMatchingQuery,
@@ -495,11 +498,6 @@ export default class ExcalidrawView
private preventReloadResetTimer: number | null = null;
private editingSelfResetTimer: number | null = null;
private colorChangeTimer: number | null = null;
private markdownImageDeleteCandidateTimer: number | null = null;
private markdownImageDeleteCandidates = new Map<
ExcalidrawElement["id"],
ExcalidrawImageElement
>();
private markdownImageDeletionQueue: Array<{
element: ExcalidrawImageElement;
filePath: string;
@@ -617,34 +615,32 @@ export default class ExcalidrawView
return;
}
if (DEVICE.isMobile) {
const prompt = new Prompt(
this.app,
t("EXPORT_FILENAME_PROMPT"),
this.file.basename,
t("EXPORT_FILENAME_PROMPT_PLACEHOLDER"),
const location = await new FileAndFolderSelectorModal(this.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.file.path).folderpath,
fileName: `${this.file.basename}.excalidraw`,
}).start();
if (!location) {
return;
}
const filename = location.fileName.toLowerCase().endsWith(".excalidraw")
? location.fileName
: `${location.fileName}.excalidraw`;
const path = getNewUniqueFilepath(
this.app.vault,
filename,
location.folderPath,
);
void prompt.openAndGetValue((filename: string) => {
if (!filename) {
return;
}
void (async () => {
filename = `${filename}.excalidraw`;
const folderpath = splitFolderAndFilename(this.file?.path).folderpath;
await checkAndCreateFolder(folderpath); //create folder if it does not exist
const path = getNewUniqueFilepath(
this.app.vault,
filename,
folderpath,
);
const file = await exportImageToFile(
this,
path,
JSON.stringify(this.getScene(), null, "\t"),
".excalidraw",
);
new Notice(`Exported to ${file?.name}`, 6000);
})();
});
const file = await exportImageToFile(
this,
path,
JSON.stringify(this.getScene(), null, "\t"),
".excalidraw",
);
new Notice(`Exported to ${file?.name}`, 6000);
return;
}
download(
@@ -763,6 +759,7 @@ export default class ExcalidrawView
void (await new Promise<void>((resolve) => {
void loader.loadSceneFiles({
excalidrawData: this.excalidrawData,
sceneElements: this.getViewElements(),
addFiles: (
files: FileData[],
_isDark: boolean,
@@ -1108,7 +1105,11 @@ export default class ExcalidrawView
public async setEmbeddableNodeIsEditing() {
this.clearEmbeddableNodeIsEditingTimer();
this.semaphores.embeddableIsEditingSelf = true;
await this.forceSave(true);
// Wait for any in-flight save (e.g. a Markdown-image editor flush) rather than silently
// aborting: a same-file back-of-the-note embeddable is about to open its own editor on this
// same file, so the disk copy must be current or the embeddable's editor will load a stale
// version and a later save from it can clobber pending Markdown-image edits.
await this.forceSave(true, true);
}
/** Debounces self-edit reloads without forcing a disk save. */
@@ -2335,7 +2336,23 @@ export default class ExcalidrawView
);
}
public async forceSave(silent: boolean = false) {
/**
* @param waitIfBusy - When true, waits (up to ~5s) for an in-flight save/autosave to clear
* instead of immediately aborting. Callers that need a guaranteed fresh disk write before
* handing off to a different editor of the same file (e.g. setEmbeddableNodeIsEditing) should
* pass true; the default preserves the existing "abort and notify" behavior for callers such as
* the manual save button, where an immediate abort is the expected feedback.
*/
public async forceSave(silent: boolean = false, waitIfBusy: boolean = false) {
if (waitIfBusy) {
let counter = 0;
while (
(this.semaphores.autosaving || this.semaphores.saving) &&
counter++ < 100
) {
await sleep(50);
}
}
if (this.semaphores.autosaving || this.semaphores.saving) {
if (!silent) {
new Notice(t("FORCE_SAVE_ABORTED"));
@@ -3032,11 +3049,6 @@ export default class ExcalidrawView
window.clearTimeout(this.colorChangeTimer);
this.colorChangeTimer = null;
}
if (this.markdownImageDeleteCandidateTimer) {
window.clearTimeout(this.markdownImageDeleteCandidateTimer);
this.markdownImageDeleteCandidateTimer = null;
this.markdownImageDeleteCandidates.clear();
}
if (this.semaphores?.wheelTimeout) {
window.clearTimeout(this.semaphores.wheelTimeout);
this.semaphores.wheelTimeout = null;
@@ -3743,6 +3755,7 @@ export default class ExcalidrawView
// candidates, run one at a time, and emit only regenerated images.
void loader.loadSceneFiles({
excalidrawData: this.excalidrawData,
sceneElements: this.getViewElements(),
addFiles: (
files: FileData[],
isDark: boolean,
@@ -3851,6 +3864,7 @@ export default class ExcalidrawView
this.activeLoader = l;
void l.loadSceneFiles({
excalidrawData: this.excalidrawData,
sceneElements: this.getViewElements(),
addFiles: (
files: FileData[],
isDark: boolean,
@@ -3956,6 +3970,51 @@ export default class ExcalidrawView
const reloadFiles = new Set<FileId>();
try {
const syncMarkdownImageSource = (
incomingElement: ExcalidrawImageElement,
): boolean => {
const customData = getMarkdownImageCustomData(incomingElement);
if (!customData) {
return false;
}
if (customData.source === "local") {
const incomingSource = inData.getMarkdownImage(
incomingElement.fileId,
);
if (!incomingSource) {
return false;
}
const currentSource = this.excalidrawData.getMarkdownImage(
incomingElement.fileId,
);
if (currentSource?.markdown === incomingSource.markdown) {
return false;
}
this.excalidrawData.setMarkdownImage(
incomingElement.fileId,
incomingSource,
);
return true;
}
const incomingFile = inData.getFile(incomingElement.fileId);
if (!incomingFile) {
return false;
}
const currentFile = this.excalidrawData.getFile(
incomingElement.fileId,
);
if (
currentFile?.file === incomingFile.file &&
currentFile?.hyperlink === incomingFile.hyperlink &&
currentFile?.linkParts?.original === incomingFile.linkParts?.original
) {
return false;
}
this.excalidrawData.setFile(incomingElement.fileId, incomingFile);
return true;
};
const deletedIds = inData.deletedElements.map((el) => el.id);
const sceneElements = this.excalidrawAPI
.getSceneElementsIncludingDeleted()
@@ -3974,7 +4033,10 @@ export default class ExcalidrawView
);
break;
case "image":
if (inData.getFile(incomingElement.fileId)) {
if (getMarkdownImageCustomData(incomingElement)) {
syncMarkdownImageSource(incomingElement);
reloadFiles.add(incomingElement.fileId);
} else if (inData.getFile(incomingElement.fileId)) {
this.excalidrawData.setFile(
incomingElement.fileId,
inData.getFile(incomingElement.fileId),
@@ -4049,6 +4111,15 @@ export default class ExcalidrawView
sceneElementIds.splice(parentLayer + 1, 0, incomingElement.id);
}
} else if (sceneElement && incomingElement.type === "image") {
if (getMarkdownImageCustomData(incomingElement)) {
if (
syncMarkdownImageSource(incomingElement) ||
!this.excalidrawAPI.getFiles()[incomingElement.fileId]
) {
reloadFiles.add(incomingElement.fileId);
}
return;
}
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/632
const incomingFile = inData.getFile(incomingElement.fileId);
const sceneFile = this.excalidrawData.getFile(
@@ -4075,6 +4146,17 @@ export default class ExcalidrawView
}
},
);
const loadedFiles = this.excalidrawAPI.getFiles();
sceneElements.forEach((element) => {
if (
element.type === "image" &&
getMarkdownImageCustomData(element) &&
!loadedFiles[element.fileId]
) {
syncMarkdownImageSource(element);
reloadFiles.add(element.fileId);
}
});
this.previousSceneVersion = this.getSceneVersion(sceneElements);
//changing files could result in a race condition for sync. If at the end of sync there are differences
//set dirty will trigger an autosave
@@ -4529,94 +4611,94 @@ export default class ExcalidrawView
if (!textElement) {
return;
}
const prompt = new Prompt(
this.app,
"Filename",
"",
"Leave blank to cancel this action",
);
void prompt.openAndGetValue((filename: string) => {
void (async () => {
if (!filename) {
return;
}
filename = `${filename}.md`;
const folderpath = splitFolderAndFilename(this.file.path).folderpath;
await checkAndCreateFolder(folderpath); //create folder if it does not exist
const fname = getNewUniqueFilepath(
this.app.vault,
filename,
folderpath,
);
const text: string[] = [];
if (containerElement && containerElement.link) {
text.push(containerElement.link);
}
text.push(textElement.rawText);
const f = await createOrOverwriteFile(this.app, fname, text.join("\n"));
if (f) {
const ea: ExcalidrawAutomate = getEA(this);
const elements = containerElement
? [textElement, containerElement]
: [textElement];
ea.copyViewElementsToEAforEditing(elements);
ea.getElements().forEach((el) => (el.isDeleted = true));
const [x, y, w, h] = containerElement
? [
containerElement.x,
containerElement.y,
containerElement.width,
containerElement.height,
]
: [textElement.x, textElement.y, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE];
const id = ea.addEmbeddable(x, y, w, h, undefined, f);
if (containerElement) {
const props: (keyof ExcalidrawElement)[] = [
"backgroundColor",
"fillStyle",
"roughness",
"roundness",
"strokeColor",
"strokeStyle",
"strokeWidth",
];
props.forEach((prop) => {
const element = ea.getElement(id);
if (prop in element) {
const mutableElement = element as Mutable<ExcalidrawElement>;
switch (prop) {
case "backgroundColor":
mutableElement.backgroundColor =
containerElement.backgroundColor;
break;
case "fillStyle":
mutableElement.fillStyle = containerElement.fillStyle;
break;
case "roughness":
mutableElement.roughness = containerElement.roughness;
break;
case "roundness":
mutableElement.roundness = containerElement.roundness;
break;
case "strokeColor":
mutableElement.strokeColor = containerElement.strokeColor;
break;
case "strokeStyle":
mutableElement.strokeStyle = containerElement.strokeStyle;
break;
case "strokeWidth":
mutableElement.strokeWidth = containerElement.strokeWidth;
break;
}
void (async () => {
const location = await new FileAndFolderSelectorModal(this.app, {
title: t("CONVERT_TO_MARKDOWN"),
folderLabel: t("FILE_AND_FOLDER_SELECTOR_FOLDER"),
fileNameLabel: t("FILE_AND_FOLDER_SELECTOR_FILENAME"),
submitButtonText: t("PROMPT_BUTTON_CREATE_MARKDOWN"),
folderPath: splitFolderAndFilename(this.file.path).folderpath,
fileName: "",
}).start();
if (!location) {
return;
}
const filename = location.fileName.toLowerCase().endsWith(".md")
? location.fileName
: `${location.fileName}.md`;
const fname = getNewUniqueFilepath(
this.app.vault,
filename,
location.folderPath,
);
const text: string[] = [];
if (containerElement && containerElement.link) {
text.push(containerElement.link);
}
text.push(textElement.rawText);
const f = await createOrOverwriteFile(this.app, fname, text.join("\n"));
if (f) {
const ea: ExcalidrawAutomate = getEA(this);
const elements = containerElement
? [textElement, containerElement]
: [textElement];
ea.copyViewElementsToEAforEditing(elements);
ea.getElements().forEach((el) => (el.isDeleted = true));
const [x, y, w, h] = containerElement
? [
containerElement.x,
containerElement.y,
containerElement.width,
containerElement.height,
]
: [textElement.x, textElement.y, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE];
const id = ea.addEmbeddable(x, y, w, h, undefined, f);
if (containerElement) {
const props: (keyof ExcalidrawElement)[] = [
"backgroundColor",
"fillStyle",
"roughness",
"roundness",
"strokeColor",
"strokeStyle",
"strokeWidth",
];
props.forEach((prop) => {
const element = ea.getElement(id);
if (prop in element) {
const mutableElement = element as Mutable<ExcalidrawElement>;
switch (prop) {
case "backgroundColor":
mutableElement.backgroundColor =
containerElement.backgroundColor;
break;
case "fillStyle":
mutableElement.fillStyle = containerElement.fillStyle;
break;
case "roughness":
mutableElement.roughness = containerElement.roughness;
break;
case "roundness":
mutableElement.roundness = containerElement.roundness;
break;
case "strokeColor":
mutableElement.strokeColor = containerElement.strokeColor;
break;
case "strokeStyle":
mutableElement.strokeStyle = containerElement.strokeStyle;
break;
case "strokeWidth":
mutableElement.strokeWidth = containerElement.strokeWidth;
break;
}
});
}
ea.getElement(id);
await ea.addElementsToView();
ea.destroy();
}
});
}
})();
});
ea.getElement(id);
await ea.addElementsToView();
ea.destroy();
}
})();
}
async addYouTubeThumbnail(link: string) {
@@ -5590,34 +5672,6 @@ export default class ExcalidrawView
this.lastKeyDownPosition = { x: 0, y: 0 };
};
private excalidrawDIVonKeyDownCapture(event: KeyboardEvent): void {
if (
this.semaphores?.viewunload ||
(event.key !== "Backspace" && event.key !== "Delete")
) {
return;
}
this.markdownImageDeleteCandidates.clear();
this.getViewSelectedElements()
.filter(
(element): element is ExcalidrawImageElement =>
element.type === "image" &&
getMarkdownImageCustomData(element)?.source === "local" &&
this.excalidrawData.hasMarkdownImage(element.fileId),
)
.forEach((element) =>
this.markdownImageDeleteCandidates.set(element.id, element),
);
if (this.markdownImageDeleteCandidateTimer) {
window.clearTimeout(this.markdownImageDeleteCandidateTimer);
}
this.markdownImageDeleteCandidateTimer = window.setTimeout(() => {
this.markdownImageDeleteCandidates.clear();
this.markdownImageDeleteCandidateTimer = null;
}, 1000);
}
private excalidrawDIVonKeyDown(event: KeyboardEvent) {
//(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.excalidrawDIVonKeyDown, "ExcalidrawView.excalidrawDIVonKeyDown", event);
if (this.semaphores?.viewunload) {
@@ -5837,30 +5891,32 @@ export default class ExcalidrawView
}
}
private handleDeletedMarkdownImageCandidates(
elements: readonly ExcalidrawElement[],
/**
* Detects local Markdown-image elements that were just soft-deleted (isDeleted flipped to
* true) in a durable Excalidraw history increment and queues them for the keep-or-delete-file
* prompt. Unlike watching specific keyboard/pointer gestures, this catches every way an element
* can be deleted - Backspace/Delete, Cut, the Excalidraw properties-panel trash icon, the
* context menu, undo/redo, or a script - because they all funnel through the same durable
* store increment.
*/
private onExcalidrawIncrement(
event: DurableIncrement | EphemeralIncrement,
): void {
if (this.markdownImageDeleteCandidates.size === 0) {
if (event.type !== "durable") {
return;
}
const currentElements = new Map(
elements.map((element) => [element.id, element]),
);
this.markdownImageDeleteCandidates.forEach((candidate, elementId) => {
const current = currentElements.get(elementId);
if (current && !current.isDeleted) {
Object.values(event.change.elements).forEach((element) => {
if (element.type !== "image" || !element.isDeleted) {
return;
}
this.markdownImageDeleteCandidates.delete(elementId);
this.queueMarkdownImageDeletion(candidate);
if (
getMarkdownImageCustomData(element)?.source !== "local" ||
!this.excalidrawData.hasMarkdownImage(element.fileId)
) {
return;
}
this.queueMarkdownImageDeletion(element);
});
if (
this.markdownImageDeleteCandidates.size === 0 &&
this.markdownImageDeleteCandidateTimer
) {
window.clearTimeout(this.markdownImageDeleteCandidateTimer);
this.markdownImageDeleteCandidateTimer = null;
}
}
private queueMarkdownImageDeletion(element: ExcalidrawImageElement): void {
@@ -5953,7 +6009,6 @@ export default class ExcalidrawView
private onChange(et: ExcalidrawElement[], st: AppState, files: BinaryFiles) {
this.selectedElementActionsMenu?.update(et, st);
this.handleDeletedMarkdownImageCandidates(et);
if (st.activeTool?.type) {
if (st.activeTool.type === "image") {
if (
@@ -6863,13 +6918,11 @@ export default class ExcalidrawView
selectCardDialog.start(center);
}
/** Opens the sidepanel editor for a selected image or inserts a new one. */
/** Opens an image by ID for editing, or inserts a new Markdown image. */
public async openMarkdownImageEditor(elementId?: string): Promise<void> {
const selected = elementId
? this.getViewElements().find((element) => element.id === elementId)
: this.getViewSelectedElements().length === 1
? this.getViewSelectedElements()[0]
: undefined;
: undefined;
const image = selected?.type === "image" ? selected : undefined;
if (image && !isMarkdownImageElement(this, image)) {
new Notice(t("MARKDOWN_IMAGE_SELECT_ERROR"));
@@ -8458,7 +8511,6 @@ export default class ExcalidrawView
ref: excalidrawWrapperRef,
key: "abc",
tabIndex: 0,
onKeyDownCapture: this.excalidrawDIVonKeyDownCapture.bind(this),
onKeyDown: this.excalidrawDIVonKeyDown.bind(this),
onKeyUp: this.excalidrawDIVonKeyUp.bind(this),
onPointerDown: this.onPointerDown.bind(this),
@@ -8498,6 +8550,7 @@ export default class ExcalidrawView
aiEnabled: this.plugin.settings.aiEnabled ?? true,
onChange: (et, st, files) =>
this.onChange(et as ExcalidrawElement[], st, files),
onIncrement: (event) => this.onExcalidrawIncrement(event),
onLibraryChange: (libraryItems) =>
this.onLibraryChange(libraryItems),
renderTopRightUI: (isMobile: boolean, appState: AppState) =>
+3 -3
View File
@@ -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);
}
+479 -92
View File
@@ -3,12 +3,12 @@ import {
ButtonComponent,
MarkdownView,
Notice,
resolveSubpath,
Setting,
type App,
type ColorComponent,
type TFile,
type WorkspaceLeaf,
type WorkspaceSplit,
type EventRef,
type MarkdownFileInfo,
} from "obsidian";
@@ -35,17 +35,18 @@ import {
} from "src/utils/customEmbeddableUtils";
import { setStyle } from "src/utils/styleUtils";
import { EmbeddedFile } from "src/shared/EmbeddedFileLoader";
import { ScriptEngine } from "src/shared/Scripts";
import {
createOrOverwriteFile,
getNewUniqueFilepath,
splitFolderAndFilename,
} from "src/utils/fileUtils";
import { getAttachmentsFolderAndFilePath } from "src/utils/pathUtils";
import { t } from "src/lang/helpers";
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";
@@ -67,6 +68,7 @@ import {
BLOCK_REFERENCE_ICON_ID,
BLOCK_REFERENCE_ICON_REGISTRY_SVG,
} from "src/constants/blockReferenceIcon";
import { FileAndFolderSelectorModal } from "src/shared/Dialogs/FileAndFolderSelectorModal";
let blockReferenceIconRegistered = false;
@@ -115,6 +117,7 @@ const getNativeColorValue = (color: string): string => {
class MarkdownFragmentView extends MarkdownView {
private saveFragment: (markdown: string) => Promise<void>;
private closing = false;
constructor(
leaf: WorkspaceLeaf,
@@ -127,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);
}
@@ -143,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;
@@ -166,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[] = [];
@@ -192,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 {
@@ -383,7 +448,7 @@ class MarkdownImageEditorController {
this.renderAppearanceControls(appearance, {
scope: "image",
cssName: t("MARKDOWN_IMAGE_CSS"),
cssDescription: `${t("MARKDOWN_IMAGE_CSS_DESC")} ${t("MARKDOWN_IMAGE_CSS_IMPORTANT_HINT")} ${t("MARKDOWN_IMAGE_CSS_SVG_COPY_HINT")}`,
cssDescription: `${t("MARKDOWN_IMAGE_CSS_DESC")} ${t("MARKDOWN_IMAGE_CSS_IMPORTANT_HINT")}`,
cssEditorAria: t("MARKDOWN_IMAGE_CSS_EDITOR_ARIA"),
cssBoilerplate: MARKDOWN_IMAGE_CSS_BOILERPLATE,
cssBoilerplateMarker: MARKDOWN_IMAGE_CSS_BOILERPLATE_MARKER,
@@ -853,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",
@@ -1285,26 +1365,36 @@ class MarkdownImageEditorController {
if (!this.ensureOwnerValid() || !source || source.source !== "local") {
return;
}
let path = await ScriptEngine.inputPrompt(
this.view,
this.view.plugin,
this.view.app,
t("MARKDOWN_IMAGE_EXTRACT_TITLE"),
t("MARKDOWN_IMAGE_EXTRACT_PATH"),
const attachmentLocation = await getAttachmentsFolderAndFilePath(
this.app,
this.view.file.path,
t("MARKDOWN_IMAGE_DEFAULT_NOTE"),
);
if (!path || !this.ensureOwnerValid()) {
if (!this.ensureOwnerValid()) {
return;
}
if (!path.toLowerCase().endsWith(".md")) {
path += ".md";
const defaultLocation = splitFolderAndFilename(
attachmentLocation.filepath,
);
const location = await new FileAndFolderSelectorModal(this.app, {
title: t("MARKDOWN_IMAGE_EXTRACT_TITLE"),
folderLabel: t("FILE_AND_FOLDER_SELECTOR_FOLDER"),
fileNameLabel: t("FILE_AND_FOLDER_SELECTOR_FILENAME"),
submitButtonText: t("MARKDOWN_IMAGE_EXTRACT"),
folderPath: defaultLocation.folderpath,
fileName: defaultLocation.filename,
}).start();
if (!location || !this.ensureOwnerValid()) {
return;
}
try {
const { folderpath, filename } = splitFolderAndFilename(path);
path = getNewUniqueFilepath(
const filename = location.fileName.toLowerCase().endsWith(".md")
? location.fileName
: `${location.fileName}.md`;
const path = getNewUniqueFilepath(
this.view.app.vault,
filename,
folderpath,
location.folderPath,
);
const file = await createOrOverwriteFile(
this.view.app,
@@ -1353,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()) {
@@ -1379,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)
@@ -1418,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> {
@@ -1448,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%" });
@@ -1471,13 +1662,9 @@ class MarkdownImageEditorController {
{ history: false },
);
await leaf.loadIfDeferred();
if (ref) {
leaf.setEphemeralState({ subpath: ref });
}
} else {
await leaf.openFile(sourceFile, {
active: false,
...(ref ? { eState: { subpath: ref } } : {}),
});
}
if (
@@ -1492,7 +1679,9 @@ class MarkdownImageEditorController {
if (leaf.view instanceof MarkdownView) {
this.editorView = leaf.view;
this.prepareEditorView(host, leaf.view);
this.revealExternalSourceSubpath(leaf.view, sourceFile, ref);
this.watchEditorChanges();
this.focusEditorIfRequested(leaf.view);
}
return;
}
@@ -1533,6 +1722,30 @@ class MarkdownImageEditorController {
this.editorView = fragmentView;
this.prepareEditorView(host, fragmentView);
this.watchEditorChanges();
this.focusEditorIfRequested(fragmentView);
}
private revealExternalSourceSubpath(
editorView: MarkdownView,
sourceFile: TFile,
subpath: string,
): void {
if (!subpath) {
return;
}
const cache = this.app.metadataCache.getFileCache(sourceFile);
const location = cache ? resolveSubpath(cache, subpath) : null;
if (!location) {
return;
}
const position = {
line: location.start.line,
ch: location.start.col,
};
// A collapsed cursor reveals the referenced content without leaving the
// detached MarkdownView in Obsidian's persistent subpath-selection state.
editorView.editor.setCursor(position);
editorView.editor.scrollIntoView({ from: position, to: position }, true);
}
private prepareEditorView(host: HTMLElement, editorView: MarkdownView): void {
@@ -1547,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);
@@ -1600,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",
@@ -1630,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(
@@ -1780,11 +2098,24 @@ class MarkdownImageEditorController {
if (!source || this.closed || !this.ensureOwnerValid()) {
return;
}
let renderMarkdown = markdown;
if (source.source === "external") {
await editorView.save();
if (!this.ensureOwnerValid()) {
return;
}
const refreshedSource = await getMarkdownImageSource(
this.view,
element,
);
if (
!refreshedSource ||
refreshedSource.source !== "external" ||
!this.ensureOwnerValid()
) {
return;
}
renderMarkdown = refreshedSource.markdown;
} else {
this.view.excalidrawData.setMarkdownImage(element.fileId, {
markdown,
@@ -1794,7 +2125,7 @@ class MarkdownImageEditorController {
const updated = await updateMarkdownImage(
this.view,
element,
markdown,
renderMarkdown,
renderSettings,
source.source,
);
@@ -1961,7 +2292,6 @@ class MarkdownImageEditorController {
this.stopMobileViewPatch();
this.editorView = null;
this.editorLeaf = null;
this.editorRoot = null;
this.editorContentDirty = false;
this.removeEditorResizeListener();
this.removeEditorFocusListener();
@@ -1974,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;
}
@@ -1998,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();
}
}
@@ -2023,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;
}
}
@@ -2061,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();
}
+6
View File
@@ -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);
+77 -58
View File
@@ -366,21 +366,40 @@ textarea.excalidraw-wysiwyg {
min-width: 10em;
}
.excalidraw-folder-path-control {
flex-wrap: wrap;
}
.excalidraw-folder-create-row {
display: flex;
flex: 0 0 100%;
justify-content: flex-end;
width: 100%;
}
.excalidraw-folder-create-row > button:not(.excalidraw-display-none) {
margin-top: var(--size-2-2);
}
.excalidraw-folder-path-control {
flex-wrap: wrap;
}
.excalidraw-file-and-folder-selector__field {
flex-wrap: wrap;
}
.excalidraw-file-and-folder-selector__field>.setting-item-control {
flex: 1 1 18rem;
min-width: 0;
}
.excalidraw-file-and-folder-selector__field input[type="text"] {
flex: 1 1 auto;
min-width: 0;
width: 100%;
}
.is-mobile .excalidraw-file-and-folder-selector .setting-item-control {
flex: 0 0 auto;
}
.excalidraw-folder-create-row {
display: flex;
flex: 0 0 100%;
justify-content: flex-end;
width: 100%;
}
.excalidraw-folder-create-row>button:not(.excalidraw-display-none) {
margin-top: var(--size-2-2);
}
.excalidraw-ai-provider-table {
margin: auto;
width: 80%;
@@ -1352,9 +1371,9 @@ End Obsidian Sheets Plus support
flex: 1 1 64px;
}
.excalidraw-markdown-image-editor__source .setting-item-control select,
.excalidraw-markdown-image-editor__appearance .setting-item-control select,
.excalidraw-markdown-image-editor__appearance .setting-item-control .excalidraw-font-picker {
.excalidraw-markdown-image-editor__source .setting-item-control select,
.excalidraw-markdown-image-editor__appearance .setting-item-control select,
.excalidraw-markdown-image-editor__appearance .setting-item-control .excalidraw-font-picker {
min-width: 0;
max-width: 100%;
}
@@ -1395,8 +1414,8 @@ End Obsidian Sheets Plus support
flex: 0 0 var(--input-height, 32px);
}
.excalidraw-markdown-image-editor__setting--font>.setting-item-control select,
.excalidraw-markdown-image-editor__setting--font>.setting-item-control .excalidraw-font-picker {
.excalidraw-markdown-image-editor__setting--font>.setting-item-control select,
.excalidraw-markdown-image-editor__setting--font>.setting-item-control .excalidraw-font-picker {
width: min(240px, 100%);
}
@@ -1447,8 +1466,8 @@ End Obsidian Sheets Plus support
justify-content: flex-start;
}
.excalidraw-markdown-image-editor__setting--font>.setting-item-control select,
.excalidraw-markdown-image-editor__setting--font>.setting-item-control .excalidraw-font-picker {
.excalidraw-markdown-image-editor__setting--font>.setting-item-control select,
.excalidraw-markdown-image-editor__setting--font>.setting-item-control .excalidraw-font-picker {
width: 100%;
}
@@ -1576,45 +1595,45 @@ End Obsidian Sheets Plus support
flex: 0 0 var(--input-height, 32px);
}
.excalidraw-markdown-image-editor__placeholder {
.excalidraw-markdown-image-editor__placeholder {
margin: auto;
max-width: 28em;
padding: 32px 20px;
border: 1px dashed var(--background-modifier-border);
border-radius: var(--radius-m);
color: var(--text-muted);
text-align: center;
}
button.excalidraw-font-picker {
display: flex;
align-items: center;
width: min(240px, 100%);
min-width: 0;
max-width: 100%;
text-align: start;
}
.excalidraw-font-picker__label {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.excalidraw-font-picker__option {
display: block;
min-width: min(12rem, calc(100vw - 4rem));
max-width: calc(100vw - 4rem);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--font-ui-medium);
}
.excalidraw-font-picker-menu-opening .menu,
.menu.excalidraw-font-picker-menu--desktop {
max-height: min(420px, 60vh);
overflow-y: auto;
}
text-align: center;
}
button.excalidraw-font-picker {
display: flex;
align-items: center;
width: min(240px, 100%);
min-width: 0;
max-width: 100%;
text-align: start;
}
.excalidraw-font-picker__label {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.excalidraw-font-picker__option {
display: block;
min-width: min(12rem, calc(100vw - 4rem));
max-width: calc(100vw - 4rem);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--font-ui-medium);
}
.excalidraw-font-picker-menu-opening .menu,
.menu.excalidraw-font-picker-menu--desktop {
max-height: min(420px, 60vh);
overflow-y: auto;
}