mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-11-27 06:32:42 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9be221a313 | ||
|
|
58081803a1 | ||
|
|
ba0e66888c | ||
|
|
0a92beec06 | ||
|
|
c1d471bb1f | ||
|
|
529d584f01 | ||
|
|
98b8aa2eba |
No files matched your search
+3
-1
@@ -78,7 +78,7 @@ validated, and what remains uncertain.
|
||||
| Coalesce drawing-backup persistence by vault path (Phase 1B.3a) | Complete | The main-window-owned `ImageCache` now delegates delayed drawing backups to a plugin-global `BackupPersistenceQueue`. Each path retains at most one active IndexedDB transaction and the latest trailing payload; a new queued payload replaces an obsolete one while preserving the existing 50 ms post-save delay. Backup writes now resolve on transaction completion rather than request scheduling. Rename flushes queued data before moving the backup key, deletion and backup-cache clearing cancel queued data after any active transaction settles, and plugin unload drops timers/references without starting new writes. Image-cache clearing remains independent. Save diagnostics distinguish scheduling, coalescing, and completed physical writes. Runtime validation covered popout/main timer ownership, two completed IndexedDB transactions, rename/save/reopen, deletion, and package/loader lifecycle. Timing-sensitive replacement, trailing-write, flush, and pending-cancellation branches are covered by the deterministic queue harness. Autoexport policy and general save-reason semantics remain separate Phase 1B.3 checkpoints |
|
||||
| Make save side-effect policy explicit (Phase 1B.3b) | Complete | The public `save()` and `forceSave()` facades retain their signatures and behavior while delegating to private policy-aware implementations. A force-save policy now independently states whether to refresh scene files and whether to run save-time autoexport; save diagnostics carry the originating reason and selected autoexport policy through request, export scheduling, and completion. The window-blur path remains persistence-only with respect to scene-file loading, but deliberately retains SVG/PNG/Excalidraw autoexport and `onTriggerAutoexportHook`: repository documentation promises autoexport each time a drawing is saved, so the handoff's contract exception applies. Runtime validation confirmed that blur persisted and autoexported without a scene-file refresh, manual save retained both behaviors, and close/reopen restored all edits |
|
||||
| Extract view save coordination without changing semantics (Phase 1B.4a) | Complete | Added a view-scoped `ViewSaveCoordinator` that owns the existing public-save and force-save routing, explicit side-effect policies, dirty-state transitions, autosave timer/function, and teardown/navigation force-save orchestration. `ExcalidrawView` retains compatibility delegates and its `TextFileView`-bound serialization/disk-write body; the externally accessed `autosaveTimer` and `autosaveFunction` properties remain available through accessors. The shared save/autosave/dirty semaphores, timer intervals, busy-wait limits, notices, Excalibrain unload exception, blur/manual policies, loader refresh behavior, and close ordering are mechanically unchanged. Runtime validation covered autosave, manual and blur force-save policies, main↔popout migration, teardown persistence, runtime deletion, and durable reopen with all five edits. Revision tracking, in-flight coalescing, and `flush()` remain the separate Phase 1B.4b checkpoint |
|
||||
| Preserve edits made during persistence with revision/coalescing semantics (Phase 1B.4b) | Complete | `ViewSaveCoordinator` now advances a monotonic current revision from Excalidraw durable store increments and existing explicit dirty calls, records the revision owned by each save request, and advances the saved revision only after persistence, an unchanged terminal result, or the established view-unload scheduled-write handoff. One save loop owns at most one active request and one merged trailing request. Edits during synchronization/compression remain dirty and update that trailing request; an overlapping request already satisfied by the active revision is discarded without reaching the old `save.skipped` path. Manual force-save busy/notice behavior remains compatible. `flush()` waits for the loop and force-persists any revision still dirty before close or migration; the Electron delayed view-unload write remains intact. Runtime validation on SYL exercised a manual save followed by edits during compression, continued editing across successive trailing saves, final convergence to the newest revision, immediate close/reopen, and the inline `[[` regression. Serialization snapshots, side-effect policies, loader behavior, and popout runtime ownership are unchanged |
|
||||
| Preserve edits made during persistence with revision/coalescing semantics (Phase 1B.4b) | Complete; dirty-signal correction awaiting manual validation | `ViewSaveCoordinator` advances a monotonic current revision from actual element increments, explicitly tracked drawing app-state changes, and existing explicit dirty calls; selection-only history increments no longer mark the drawing dirty. Each save request records its revision and advances the saved revision only after persistence, an unchanged terminal result, or the established view-unload scheduled-write handoff. One save loop owns at most one active request and one merged trailing request. Edits during synchronization/compression remain dirty and update that trailing request; an overlapping request already satisfied by the active revision is discarded without reaching the old `save.skipped` path. Manual force-save busy/notice behavior remains compatible. `flush()` waits for the loop and force-persists any revision still dirty before close or migration; the Electron delayed view-unload write remains intact. The original runtime validation on SYL exercised a manual save followed by edits during compression, continued editing across successive trailing saves, final convergence to the newest revision, immediate close/reopen, and the inline `[[` regression. The corrected dirty-input policy requires the focused 2026-09-02 validation recorded below |
|
||||
| Persist dirty window migrations before source teardown | Complete | `onWindowMigrated()` now marks migration and terminates view loaders before closing the old view. It synchronously captures the coherent scene, deleted elements, files, app-state subset, and selected-element IDs while the source API is valid, then unmounts the source React root before the first asynchronous synchronization/compression step. Main→popout may persist through the stable main realm. Popout→main performs no final drawing-file write from the source callback: it registers only serialized drawing text and stable leaf/path identifiers in a bounded 15-second, one-shot plugin manager; the replacement main-window view consumes and persists that text before parsing it. No view, DOM node, Window, React runtime, or package lease crosses the boundary. The migration callback owns the single teardown flush; later generic `onClose()` and `onUnloadFile()` safeguards skip their redundant migration saves. Retired sources reject blur-save side effects and vault-modify synchronization after unmount. Runtime validation confirmed dirty migration in both directions without freezes, lost edits, unusable replacement views, or Excalidraw console errors; close/reopen confirmed durable persistence. Ordinary autosave, manual save, file navigation, public facades, and the existing delayed non-migration unload workaround remain unchanged |
|
||||
| Cancel image-loading work across runtime teardown | Complete | Rapid migration before MOC EA finished loading exposed one non-fatal `null.scheduleAction` rejection. A progressive `addFiles()` call had already started component-owned image decoding when the old runtime unmounted; the fork's Obsidian teardown nulled its store before that decode resumed. The plugin now cancels its deferred initialization callback, rejects loader work unless the initiating API identity and file path are still current, and fences `addFiles()` immediately before publication. Published fork version `0.18.127` stops a completed decode from touching store/scene state after `componentWillUnmount()`. Migration still unmounts before its first await; it never waits for image completion. No persisted data, file format, batching size, or public API changed. Repeated rapid MOC EA migration attempts with edits before image completion preserved all data and did not reproduce the console rejection; the plugin's installed production and development artifacts exactly match the locally validated fork build |
|
||||
| Restore progressive live-view image presentation | Complete; deeper warm-cache work parked | The live view now prioritizes image file IDs intersecting the initial viewport and publishes loaded assets in batches of at most eight, allowing the owning window two animation frames between immediately available batches. Export, automation, and deferred-validation loaders retain their existing unbounded collection behavior. MOC EA displayed its first image after about one second in the settled run and completed after about eight seconds; the startup-contention run displayed the first image after about four seconds and completed after about ten. Panning remains choppy while loading because later `addFiles()` calls still block for up to 346 ms and individual cached SVG materialization waits reached 1.25 seconds. Do not broaden this checkpoint into image-payload caching; profile and address warm-cache materialization only after the window-runtime migration direction is settled |
|
||||
@@ -200,6 +200,8 @@ final upstream work is merged into the fork and installed in the plugin.
|
||||
|
||||
| Date | Action | Outcome | Validation |
|
||||
| --- | --- | --- | --- |
|
||||
| 2026-09-02 | Separated Excalidraw history increments from drawing dirty state | Corrected the Phase 1B.4b assumption that every durable Excalidraw store increment represents a persistence-relevant edit. Selection is intentionally captured by Excalidraw history, but now advances the save revision only when the increment contains element changes. Added an explicit app-state dirty projection for theme, canvas background, grid size/step/mode, custom palettes/top picks, frame rendering, object snapping, the durable binding preference, midpoint snapping, and box-selection mode. Scroll and zoom participate only when **Zoom to fit on file open** is disabled. Transient selection/editor state is excluded. Effective `isBindingEnabled` is neither tracked nor serialized because Excalidraw temporarily derives it from modifier-key state; `bindingPreference` remains the persisted source of truth. Generated `gridColor` does not independently mark the drawing dirty, but remains serialized because `getSceneWithAppState()` also backs the public `getScene()` contract; removing it requires a separate compatibility decision | Production build passes under Node 22.22.2 with the established 33 circular-dependency warnings. Direct tracker assertions cover selection exclusion, equivalent nested values, grid changes, conditional viewport changes, exclusion of modifier-derived `isBindingEnabled`, and inclusion of the durable `bindingPreference`. The new tracker has no ESLint findings; `ExcalidrawView.ts` retains exactly its 18 pre-existing findings. Full source lint retains the established 123-error/0-warning backlog with no finding in the new module. Unused-symbol lint, bundle syntax, Madge, and `git diff --check` pass. Focused runtime validation is pending: selection-only and modifier-only clean state, one real element edit, each tracked app-state family, viewport behavior with zoom-to-fit both enabled and disabled, save/reopen durability, and one dirty popout round trip |
|
||||
| 2026-09-01 | Made the default startup-script asset build-generated | Renamed the misspelled `starutpscript.ts` module to `startupScript.ts` and removed its hand-maintained Base64 literal and Obsidian-console conversion recipe. Every plugin build now reads `src/constants/assets/startupScript.md`, Base64-encodes it in Rollup, and embeds the payload while preserving the existing `startupScript()` runtime contract. Library builds do not read or embed the asset | Production and library builds, Rollup/bundle syntax, exact source-to-embedded-Base64 parity, scoped ESLint, unused-symbol lint, Madge, and `git diff --check` pass. Full source lint retains exactly the established 123-error/0-warning backlog with no finding in either touched TypeScript file. Focused runtime validation should delete or temporarily clear the configured startup-script path, select the settings action that creates the default script, and confirm the created file exactly includes the current lifecycle/cleanup header from the asset |
|
||||
| 2026-09-01 | Synchronized the 2.27 EA lifecycle contract into `ea-script-template` and `ea-scripts` | Updated both repositories' ambient execution-source typings, added `registerCleanup()`, documented lifecycle ownership and manual-repeatability semantics, and refreshed their complete `.ai/excalidraw-automate` snapshots from the plugin's generated source. The only Slideshow source-adjacent change is its test fixture rename from the unreleased `autostart` value to `view-autostart`; the Slideshow runner and Mindmap Builder remain unchanged | Both repositories typecheck. Under Node 22, all `ea-script-template` tests pass (4/4) and all `ea-scripts` tests pass (91/91). Changed source files pass Prettier and `git diff --check`, and no stale literal `"autostart"` execution-source value remains outside excluded build/dependency artifacts. `ea-script-template` full lint passes; `ea-scripts` retains its pre-existing Slideshow lint backlog (105 findings, including seven errors) with no finding on the changed lifecycle fixture line |
|
||||
| 2026-09-01 | Implemented the 2.27 EA script lifecycle and autostart execution refactor | Added compiled-file caching and concurrent compilation sharing without caching EAs or script runtime state; six explicit execution sources; per-view/path automatic-attachment deduplication with failure retry and unrestricted manual bypass; startup execution through ScriptEngine with the global EA; sidepanel restore/reload distinction; EA-owned synchronous cleanup; and a diagnostic for duplicate persistent-sidepanel creation from view autostart. Updated source API help, release notes, scripting documentation/template, and the documentation generator. Slideshow and Mindmap Builder source were inspected but intentionally not modified | `npm run build`, `npm run lib`, bundle syntax, touched-file ESLint, unused-symbol lint, `git diff --check`, and `npm run madge` pass. The established production build retains 33 circular-dependency warnings; full source lint reports 123 existing errors/0 warnings in 19 untouched files, and TypeScript reports 28 existing errors with none in touched files. `dist/main.js` is 4,975,687 bytes, 4,343 bytes above clean HEAD and 267,193 bytes below 5 MiB. Local generated documentation was refreshed and the two external script-authoring repositories were subsequently synchronized through their own `sync-refs` commands. Focused Obsidian runtime acceptance remains pending: cleanup across plugin reload/view close, `.md` and `.js` cache invalidation, the permission/view-initialization race, Slideshow mixed automatic/manual behavior, Mindmap Builder persistent-sidepanel re-entry, sidepanel restore/reload, drawing on-load, main/popout views, and failure retry |
|
||||
| 2026-09-01 | Re-audited #11997 and final #12018 head `ab6f203e9` after Márk's fixes | Confirmed that the previously reported public-prop and retained-image-cache wiring gaps are resolved. The final abstraction also adds environment-scoped paths, weak cache isolation, and owner-window-aware throttling needed by concurrent main/popout Apps. Code review now supports confirming the Obsidian multi-window contract, while explicitly reserving runtime acceptance for the published-fork plugin smoke test | Verified the current GitHub heads and green checks, reviewed the final wiring and focused render-environment tests, and retained the existing risk-based adoption gate below. No plugin or fork runtime source changed; documentation-only validation uses `git diff --check` |
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
/* ************************************** */
|
||||
type MutableElementMapEntry = Mutable<ExcalidrawElement> & Record<string, unknown>;
|
||||
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
|
||||
import { FloatingModal } from "./Dialogs/FloatingModal";
|
||||
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
|
||||
@@ -611,30 +611,28 @@ export declare class ExcalidrawAutomate {
|
||||
pageProps?: PDFPageProperties;
|
||||
filename: string;
|
||||
}): Promise<void>;
|
||||
private prepareViewImageExport;
|
||||
/**
|
||||
* Creates an SVG representation of the current view.
|
||||
*
|
||||
* @param {Object} options - The options for creating the SVG.
|
||||
* @param {boolean} [options.withBackground=true] - Whether to include the background in the SVG.
|
||||
* @param {"light" | "dark"} [options.theme] - The theme to use for the SVG.
|
||||
* @param {FrameRenderingOptions} [options.frameRendering={enabled: true, name: true, outline: true, clip: true}] - The frame rendering options.
|
||||
* @param {number} [options.padding] - The padding to apply around the SVG.
|
||||
* @param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.
|
||||
* @param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.
|
||||
* @param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.
|
||||
* @param {readonly ExcalidrawElement[]} [options.elementsOverride] - Optional complete replacement for the view's exported elements. This array is not merged with the current scene or treated as a patch by ID: when supplied, only its non-deleted elements are exported. Include every element that should appear in the SVG.
|
||||
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to the exported SVG, or `undefined` when no
|
||||
* loaded target view is available.
|
||||
*/
|
||||
createViewSVG({ withBackground, theme, frameRendering, padding, selectedOnly, skipInliningFonts, embedScene, elementsOverride, }: {
|
||||
withBackground?: boolean;
|
||||
theme?: "light" | "dark";
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
skipInliningFonts?: boolean;
|
||||
embedScene?: boolean;
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
}): Promise<SVGSVGElement>;
|
||||
createViewSVG(options?: ViewSVGExportOptions): Promise<SVGSVGElement>;
|
||||
/**
|
||||
* Creates a PNG representation of the current view without using or mutating
|
||||
* the EA workbench.
|
||||
*
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to a PNG blob, or `undefined` when no loaded
|
||||
* target view is available.
|
||||
*/
|
||||
createViewPNG(options?: ViewPNGExportOptions): Promise<Blob>;
|
||||
/**
|
||||
* Creates an SVG image from the ExcalidrawAutomate elements and the template provided.
|
||||
* @param {string} [templatePath] - The template path to use for the SVG.
|
||||
@@ -1454,12 +1452,27 @@ export declare class ExcalidrawAutomate {
|
||||
*/
|
||||
getExportSettings(withBackground: boolean, withTheme: boolean, isMask?: boolean): ExportSettings;
|
||||
/**
|
||||
* Gets the elements within a specific area.
|
||||
* @param elements - The elements to check.
|
||||
* @param param1 - The area to check against.
|
||||
* @returns The elements within the area.
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsInArea(elements: readonly ExcalidrawElement[], element: ExcalidrawElement): ExcalidrawElement[];
|
||||
getElementsInArea(elements: readonly ExcalidrawElement[], area: SceneArea, options?: ElementsInAreaOptions): ExcalidrawElement[];
|
||||
/**
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @remarks
|
||||
* This explicit name is preferred for new code. `getElementsInArea()` remains
|
||||
* available as a backward-compatible alias and uses the same implementation.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsIntersectionArea(elements: readonly ExcalidrawElement[], area: SceneArea, options?: ElementsInAreaOptions): ExcalidrawElement[];
|
||||
/**
|
||||
* Gets the bounding box of the specified elements.
|
||||
* The bounding box is the box encapsulating all of the elements completely.
|
||||
@@ -1992,6 +2005,58 @@ export interface AddImageOptions {
|
||||
anchor?: boolean;
|
||||
colorMap?: ColorMap;
|
||||
}
|
||||
/** A rectangular region in Excalidraw scene coordinates. */
|
||||
export interface SceneArea {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
/** Optional ID of an element representing the area. */
|
||||
id?: string;
|
||||
}
|
||||
/** Controls how {@link ExcalidrawAutomate.getElementsInArea} selects elements. */
|
||||
export interface ElementsInAreaOptions {
|
||||
/** Expands the area by this many scene units on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames. Existing behavior excludes them by default. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/** Includes containers, bound elements, and arrow binding targets needed by the result. */
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
/** Restricts a view image export to a rectangular scene region. */
|
||||
export interface ViewExportArea extends SceneArea {
|
||||
/** Expands both the selected content and exported viewport on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames in the export candidate set. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/**
|
||||
* Includes containers, bound elements, and arrow binding targets needed to
|
||||
* render intersecting elements. Defaults to `true` for area exports.
|
||||
*/
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
/** Options shared by view-based SVG and PNG exports. */
|
||||
export interface ViewImageExportOptions {
|
||||
withBackground?: boolean;
|
||||
theme?: AppState["theme"];
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
embedScene?: boolean;
|
||||
/** Complete replacement for the view elements used by the export. */
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
/** Filters and anchors the export to an exact scene rectangle. */
|
||||
exportArea?: ViewExportArea;
|
||||
}
|
||||
/** Options for {@link ExcalidrawAutomate.createViewSVG}. */
|
||||
export interface ViewSVGExportOptions extends ViewImageExportOptions {
|
||||
skipInliningFonts?: boolean;
|
||||
}
|
||||
/** Options for {@link ExcalidrawAutomate.createViewPNG}. */
|
||||
export interface ViewPNGExportOptions extends ViewImageExportOptions {
|
||||
/** Raster scale applied to the exported viewport. */
|
||||
scale?: number;
|
||||
}
|
||||
|
||||
/* ************************************** */
|
||||
/* lib/types/excalidrawElementTypes.d.ts */
|
||||
|
||||
@@ -12,7 +12,7 @@ Content structure:
|
||||
2. The curated script overview (index-new.md)
|
||||
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
|
||||
|
||||
Generated on: 2026-08-30T12:07:47.389Z
|
||||
Generated on: 2026-09-01T18:22:12.027Z
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -97,7 +97,8 @@ To keep this training file concise, large external type definitions are not incl
|
||||
ea.clear();
|
||||
}
|
||||
```
|
||||
* **`elementsOverride` is a complete replacement:** In `createViewSVG()`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the SVG. When temporarily modifying an existing scene for export, the simplest safe workflow is to copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
|
||||
* **`elementsOverride` is a complete replacement:** In `createViewSVG()` and `createViewPNG()`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the image. When temporarily modifying an existing scene for export, copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
|
||||
* **Use `exportArea` for bounded view exports:** Both view export methods accept `exportArea: {x, y, width, height}`. EA filters the candidate elements with the same logic exposed as `getElementsIntersectionArea()` (and its backward-compatible `getElementsInArea()` alias), retains required bound elements, and anchors the result to that exact viewport. This prevents a small preview or PDF page from retaining every image in a large scene.
|
||||
* **Identity is the boundary:** `copyViewElementsToEAforEditing()` is the standard way to obtain mutable, identity-preserving copies of existing scene elements for both persistent edits and temporary EA operations. By contrast, `ea.cloneElement()` and `ea.cloneElements()` deliberately generate new IDs and are only for creating genuine duplicate scene elements. Never use them to obtain editable workbench copies of existing elements.
|
||||
* **One workbench transaction at a time:** The workbench is shared mutable state on an EA instance. Do not interleave asynchronous preview/export preparation and scene mutation through the same workbench. Await the operation, then clear the workbench before starting another transaction.
|
||||
* **Deletion:** To delete an element, set its `isDeleted` property to `true` on the workbench copy (`ea.getElement(id).isDeleted = true;`) and then commit with `await ea.addElementsToView()`.
|
||||
@@ -174,7 +175,7 @@ To keep this training file concise, large external type definitions are not incl
|
||||
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
|
||||
1. **Exporting elements currently in the EA workbench:** Use `await ea.createSVG(null, ...)` or `await ea.createPNG(null, ...)` (passing `null` as the `templatePath`).
|
||||
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to `createSVG` or `createPNG` (e.g., `await ea.createSVG(file.path, ...)`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
|
||||
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)`. This is specifically for the open view. Its `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or a patch by ID. If supplied, include every existing or temporary element that should appear in the SVG. For temporary changes to existing elements, copy the complete desired export set into the EA workbench, modify it there, and pass `ea.getElements()`.
|
||||
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)` for vector output or `await ea.createViewPNG(...)` for raster output. Their `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or patch by ID. Use `exportArea` when only a rectangular viewport is needed; it filters out off-area elements and their unused image payloads instead of exporting the full scene and merely changing the SVG viewBox. For temporary changes, copy the complete desired export set into the EA workbench, modify it there, and pass `ea.getElements()`.
|
||||
|
||||
#### **8. Custom Pens and Perfect Freehand**
|
||||
|
||||
@@ -283,7 +284,7 @@ Example freedraw element carrying `customData.strokeOptions`:
|
||||
/* ************************************** */
|
||||
type MutableElementMapEntry = Mutable<ExcalidrawElement> & Record<string, unknown>;
|
||||
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
|
||||
import { FloatingModal } from "./Dialogs/FloatingModal";
|
||||
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
|
||||
@@ -888,30 +889,28 @@ export declare class ExcalidrawAutomate {
|
||||
pageProps?: PDFPageProperties;
|
||||
filename: string;
|
||||
}): Promise<void>;
|
||||
private prepareViewImageExport;
|
||||
/**
|
||||
* Creates an SVG representation of the current view.
|
||||
*
|
||||
* @param {Object} options - The options for creating the SVG.
|
||||
* @param {boolean} [options.withBackground=true] - Whether to include the background in the SVG.
|
||||
* @param {"light" | "dark"} [options.theme] - The theme to use for the SVG.
|
||||
* @param {FrameRenderingOptions} [options.frameRendering={enabled: true, name: true, outline: true, clip: true}] - The frame rendering options.
|
||||
* @param {number} [options.padding] - The padding to apply around the SVG.
|
||||
* @param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.
|
||||
* @param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.
|
||||
* @param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.
|
||||
* @param {readonly ExcalidrawElement[]} [options.elementsOverride] - Optional complete replacement for the view's exported elements. This array is not merged with the current scene or treated as a patch by ID: when supplied, only its non-deleted elements are exported. Include every element that should appear in the SVG.
|
||||
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to the exported SVG, or `undefined` when no
|
||||
* loaded target view is available.
|
||||
*/
|
||||
createViewSVG({ withBackground, theme, frameRendering, padding, selectedOnly, skipInliningFonts, embedScene, elementsOverride, }: {
|
||||
withBackground?: boolean;
|
||||
theme?: "light" | "dark";
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
skipInliningFonts?: boolean;
|
||||
embedScene?: boolean;
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
}): Promise<SVGSVGElement>;
|
||||
createViewSVG(options?: ViewSVGExportOptions): Promise<SVGSVGElement>;
|
||||
/**
|
||||
* Creates a PNG representation of the current view without using or mutating
|
||||
* the EA workbench.
|
||||
*
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to a PNG blob, or `undefined` when no loaded
|
||||
* target view is available.
|
||||
*/
|
||||
createViewPNG(options?: ViewPNGExportOptions): Promise<Blob>;
|
||||
/**
|
||||
* Creates an SVG image from the ExcalidrawAutomate elements and the template provided.
|
||||
* @param {string} [templatePath] - The template path to use for the SVG.
|
||||
@@ -1731,12 +1730,27 @@ export declare class ExcalidrawAutomate {
|
||||
*/
|
||||
getExportSettings(withBackground: boolean, withTheme: boolean, isMask?: boolean): ExportSettings;
|
||||
/**
|
||||
* Gets the elements within a specific area.
|
||||
* @param elements - The elements to check.
|
||||
* @param param1 - The area to check against.
|
||||
* @returns The elements within the area.
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsInArea(elements: readonly ExcalidrawElement[], element: ExcalidrawElement): ExcalidrawElement[];
|
||||
getElementsInArea(elements: readonly ExcalidrawElement[], area: SceneArea, options?: ElementsInAreaOptions): ExcalidrawElement[];
|
||||
/**
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @remarks
|
||||
* This explicit name is preferred for new code. `getElementsInArea()` remains
|
||||
* available as a backward-compatible alias and uses the same implementation.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsIntersectionArea(elements: readonly ExcalidrawElement[], area: SceneArea, options?: ElementsInAreaOptions): ExcalidrawElement[];
|
||||
/**
|
||||
* Gets the bounding box of the specified elements.
|
||||
* The bounding box is the box encapsulating all of the elements completely.
|
||||
@@ -2269,6 +2283,58 @@ export interface AddImageOptions {
|
||||
anchor?: boolean;
|
||||
colorMap?: ColorMap;
|
||||
}
|
||||
/** A rectangular region in Excalidraw scene coordinates. */
|
||||
export interface SceneArea {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
/** Optional ID of an element representing the area. */
|
||||
id?: string;
|
||||
}
|
||||
/** Controls how {@link ExcalidrawAutomate.getElementsInArea} selects elements. */
|
||||
export interface ElementsInAreaOptions {
|
||||
/** Expands the area by this many scene units on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames. Existing behavior excludes them by default. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/** Includes containers, bound elements, and arrow binding targets needed by the result. */
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
/** Restricts a view image export to a rectangular scene region. */
|
||||
export interface ViewExportArea extends SceneArea {
|
||||
/** Expands both the selected content and exported viewport on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames in the export candidate set. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/**
|
||||
* Includes containers, bound elements, and arrow binding targets needed to
|
||||
* render intersecting elements. Defaults to `true` for area exports.
|
||||
*/
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
/** Options shared by view-based SVG and PNG exports. */
|
||||
export interface ViewImageExportOptions {
|
||||
withBackground?: boolean;
|
||||
theme?: AppState["theme"];
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
embedScene?: boolean;
|
||||
/** Complete replacement for the view elements used by the export. */
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
/** Filters and anchors the export to an exact scene rectangle. */
|
||||
exportArea?: ViewExportArea;
|
||||
}
|
||||
/** Options for {@link ExcalidrawAutomate.createViewSVG}. */
|
||||
export interface ViewSVGExportOptions extends ViewImageExportOptions {
|
||||
skipInliningFonts?: boolean;
|
||||
}
|
||||
/** Options for {@link ExcalidrawAutomate.createViewPNG}. */
|
||||
export interface ViewPNGExportOptions extends ViewImageExportOptions {
|
||||
/** Raster scale applied to the exported viewport. */
|
||||
scale?: number;
|
||||
}
|
||||
|
||||
/* ************************************** */
|
||||
/* lib/types/excalidrawElementTypes.d.ts */
|
||||
@@ -6693,7 +6759,7 @@ Content structure:
|
||||
2. The curated script overview (index-new.md)
|
||||
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
|
||||
|
||||
Generated on: 2026-08-30T12:07:47.389Z
|
||||
Generated on: 2026-09-01T18:22:12.027Z
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -102,7 +102,8 @@ To keep this training file concise, large external type definitions are not incl
|
||||
ea.clear();
|
||||
}
|
||||
```
|
||||
* **`elementsOverride` is a complete replacement:** In `createViewSVG()`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the SVG. When temporarily modifying an existing scene for export, the simplest safe workflow is to copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
|
||||
* **`elementsOverride` is a complete replacement:** In `createViewSVG()` and `createViewPNG()`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the image. When temporarily modifying an existing scene for export, copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
|
||||
* **Use `exportArea` for bounded view exports:** Both view export methods accept `exportArea: {x, y, width, height}`. EA filters the candidate elements with the same logic exposed as `getElementsIntersectionArea()` (and its backward-compatible `getElementsInArea()` alias), retains required bound elements, and anchors the result to that exact viewport. This prevents a small preview or PDF page from retaining every image in a large scene.
|
||||
* **Identity is the boundary:** `copyViewElementsToEAforEditing()` is the standard way to obtain mutable, identity-preserving copies of existing scene elements for both persistent edits and temporary EA operations. By contrast, `ea.cloneElement()` and `ea.cloneElements()` deliberately generate new IDs and are only for creating genuine duplicate scene elements. Never use them to obtain editable workbench copies of existing elements.
|
||||
* **One workbench transaction at a time:** The workbench is shared mutable state on an EA instance. Do not interleave asynchronous preview/export preparation and scene mutation through the same workbench. Await the operation, then clear the workbench before starting another transaction.
|
||||
* **Deletion:** To delete an element, set its `isDeleted` property to `true` on the workbench copy (`ea.getElement(id).isDeleted = true;`) and then commit with `await ea.addElementsToView()`.
|
||||
@@ -179,7 +180,7 @@ To keep this training file concise, large external type definitions are not incl
|
||||
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
|
||||
1. **Exporting elements currently in the EA workbench:** Use `await ea.createSVG(null, ...)` or `await ea.createPNG(null, ...)` (passing `null` as the `templatePath`).
|
||||
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to `createSVG` or `createPNG` (e.g., `await ea.createSVG(file.path, ...)`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
|
||||
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)`. This is specifically for the open view. Its `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or a patch by ID. If supplied, include every existing or temporary element that should appear in the SVG. For temporary changes to existing elements, copy the complete desired export set into the EA workbench, modify it there, and pass `ea.getElements()`.
|
||||
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)` for vector output or `await ea.createViewPNG(...)` for raster output. Their `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or patch by ID. Use `exportArea` when only a rectangular viewport is needed; it filters out off-area elements and their unused image payloads instead of exporting the full scene and merely changing the SVG viewBox. For temporary changes, copy the complete desired export set into the EA workbench, modify it there, and pass `ea.getElements()`.
|
||||
|
||||
#### **8. Custom Pens and Perfect Freehand**
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
/* ************************************** */
|
||||
type MutableElementMapEntry = Mutable<ExcalidrawElement> & Record<string, unknown>;
|
||||
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
|
||||
import { FloatingModal } from "./Dialogs/FloatingModal";
|
||||
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
|
||||
@@ -611,30 +611,28 @@ export declare class ExcalidrawAutomate {
|
||||
pageProps?: PDFPageProperties;
|
||||
filename: string;
|
||||
}): Promise<void>;
|
||||
private prepareViewImageExport;
|
||||
/**
|
||||
* Creates an SVG representation of the current view.
|
||||
*
|
||||
* @param {Object} options - The options for creating the SVG.
|
||||
* @param {boolean} [options.withBackground=true] - Whether to include the background in the SVG.
|
||||
* @param {"light" | "dark"} [options.theme] - The theme to use for the SVG.
|
||||
* @param {FrameRenderingOptions} [options.frameRendering={enabled: true, name: true, outline: true, clip: true}] - The frame rendering options.
|
||||
* @param {number} [options.padding] - The padding to apply around the SVG.
|
||||
* @param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.
|
||||
* @param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.
|
||||
* @param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.
|
||||
* @param {readonly ExcalidrawElement[]} [options.elementsOverride] - Optional complete replacement for the view's exported elements. This array is not merged with the current scene or treated as a patch by ID: when supplied, only its non-deleted elements are exported. Include every element that should appear in the SVG.
|
||||
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to the exported SVG, or `undefined` when no
|
||||
* loaded target view is available.
|
||||
*/
|
||||
createViewSVG({ withBackground, theme, frameRendering, padding, selectedOnly, skipInliningFonts, embedScene, elementsOverride, }: {
|
||||
withBackground?: boolean;
|
||||
theme?: "light" | "dark";
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
skipInliningFonts?: boolean;
|
||||
embedScene?: boolean;
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
}): Promise<SVGSVGElement>;
|
||||
createViewSVG(options?: ViewSVGExportOptions): Promise<SVGSVGElement>;
|
||||
/**
|
||||
* Creates a PNG representation of the current view without using or mutating
|
||||
* the EA workbench.
|
||||
*
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to a PNG blob, or `undefined` when no loaded
|
||||
* target view is available.
|
||||
*/
|
||||
createViewPNG(options?: ViewPNGExportOptions): Promise<Blob>;
|
||||
/**
|
||||
* Creates an SVG image from the ExcalidrawAutomate elements and the template provided.
|
||||
* @param {string} [templatePath] - The template path to use for the SVG.
|
||||
@@ -1454,12 +1452,27 @@ export declare class ExcalidrawAutomate {
|
||||
*/
|
||||
getExportSettings(withBackground: boolean, withTheme: boolean, isMask?: boolean): ExportSettings;
|
||||
/**
|
||||
* Gets the elements within a specific area.
|
||||
* @param elements - The elements to check.
|
||||
* @param param1 - The area to check against.
|
||||
* @returns The elements within the area.
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsInArea(elements: readonly ExcalidrawElement[], element: ExcalidrawElement): ExcalidrawElement[];
|
||||
getElementsInArea(elements: readonly ExcalidrawElement[], area: SceneArea, options?: ElementsInAreaOptions): ExcalidrawElement[];
|
||||
/**
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @remarks
|
||||
* This explicit name is preferred for new code. `getElementsInArea()` remains
|
||||
* available as a backward-compatible alias and uses the same implementation.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsIntersectionArea(elements: readonly ExcalidrawElement[], area: SceneArea, options?: ElementsInAreaOptions): ExcalidrawElement[];
|
||||
/**
|
||||
* Gets the bounding box of the specified elements.
|
||||
* The bounding box is the box encapsulating all of the elements completely.
|
||||
@@ -1992,6 +2005,58 @@ export interface AddImageOptions {
|
||||
anchor?: boolean;
|
||||
colorMap?: ColorMap;
|
||||
}
|
||||
/** A rectangular region in Excalidraw scene coordinates. */
|
||||
export interface SceneArea {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
/** Optional ID of an element representing the area. */
|
||||
id?: string;
|
||||
}
|
||||
/** Controls how {@link ExcalidrawAutomate.getElementsInArea} selects elements. */
|
||||
export interface ElementsInAreaOptions {
|
||||
/** Expands the area by this many scene units on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames. Existing behavior excludes them by default. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/** Includes containers, bound elements, and arrow binding targets needed by the result. */
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
/** Restricts a view image export to a rectangular scene region. */
|
||||
export interface ViewExportArea extends SceneArea {
|
||||
/** Expands both the selected content and exported viewport on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames in the export candidate set. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/**
|
||||
* Includes containers, bound elements, and arrow binding targets needed to
|
||||
* render intersecting elements. Defaults to `true` for area exports.
|
||||
*/
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
/** Options shared by view-based SVG and PNG exports. */
|
||||
export interface ViewImageExportOptions {
|
||||
withBackground?: boolean;
|
||||
theme?: AppState["theme"];
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
embedScene?: boolean;
|
||||
/** Complete replacement for the view elements used by the export. */
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
/** Filters and anchors the export to an exact scene rectangle. */
|
||||
exportArea?: ViewExportArea;
|
||||
}
|
||||
/** Options for {@link ExcalidrawAutomate.createViewSVG}. */
|
||||
export interface ViewSVGExportOptions extends ViewImageExportOptions {
|
||||
skipInliningFonts?: boolean;
|
||||
}
|
||||
/** Options for {@link ExcalidrawAutomate.createViewPNG}. */
|
||||
export interface ViewPNGExportOptions extends ViewImageExportOptions {
|
||||
/** Raster scale applied to the exported viewport. */
|
||||
scale?: number;
|
||||
}
|
||||
|
||||
/* ************************************** */
|
||||
/* lib/types/excalidrawElementTypes.d.ts */
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.27.0-rc.2",
|
||||
"version": "2.27.0-rc.3",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
@@ -108,6 +108,12 @@ if (!isLib) {
|
||||
|
||||
const manifestStr = isLib ? "" : fs.readFileSync("manifest-beta.json", "utf-8");
|
||||
const manifest = isLib ? {} : JSON.parse(manifestStr);
|
||||
const startupScriptBase64 = isLib
|
||||
? ""
|
||||
: Buffer.from(
|
||||
fs.readFileSync("src/constants/assets/startupScript.md", "utf-8"),
|
||||
"utf-8",
|
||||
).toString("base64");
|
||||
if (!isLib) {
|
||||
console.log(manifest.version);
|
||||
}
|
||||
@@ -149,6 +155,7 @@ const packageString = isLib
|
||||
//https://github.com/obsidianmd/eslint-plugin/issues/176
|
||||
`const deliberateFetch = async (payload, init) => await fetch(payload, init);\n` +
|
||||
`const PLUGIN_VERSION="${manifest.version}";\n` +
|
||||
`const STARTUP_SCRIPT_BASE64="${startupScriptBase64}";\n` +
|
||||
//Moved here since the Obsidian code scanner warning to avoid unnecessary logging appears
|
||||
//to users, creating the impression that there is unnecessary logging. There isn't.
|
||||
//Errors and debug information is logged. Nothing else.
|
||||
|
||||
@@ -120,7 +120,8 @@ To keep this training file concise, large external type definitions are not incl
|
||||
ea.clear();
|
||||
}
|
||||
\`\`\`
|
||||
* **\`elementsOverride\` is a complete replacement:** In \`createViewSVG()\`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the SVG. When temporarily modifying an existing scene for export, the simplest safe workflow is to copy the complete desired export set into EA, modify the workbench copy, and pass \`ea.getElements()\` as the override.
|
||||
* **\`elementsOverride\` is a complete replacement:** In \`createViewSVG()\` and \`createViewPNG()\`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the image. When temporarily modifying an existing scene for export, copy the complete desired export set into EA, modify the workbench copy, and pass \`ea.getElements()\` as the override.
|
||||
* **Use \`exportArea\` for bounded view exports:** Both view export methods accept \`exportArea: {x, y, width, height}\`. EA filters the candidate elements with the same logic exposed as \`getElementsIntersectionArea()\` (and its backward-compatible \`getElementsInArea()\` alias), retains required bound elements, and anchors the result to that exact viewport. This prevents a small preview or PDF page from retaining every image in a large scene.
|
||||
* **Identity is the boundary:** \`copyViewElementsToEAforEditing()\` is the standard way to obtain mutable, identity-preserving copies of existing scene elements for both persistent edits and temporary EA operations. By contrast, \`ea.cloneElement()\` and \`ea.cloneElements()\` deliberately generate new IDs and are only for creating genuine duplicate scene elements. Never use them to obtain editable workbench copies of existing elements.
|
||||
* **One workbench transaction at a time:** The workbench is shared mutable state on an EA instance. Do not interleave asynchronous preview/export preparation and scene mutation through the same workbench. Await the operation, then clear the workbench before starting another transaction.
|
||||
* **Deletion:** To delete an element, set its \`isDeleted\` property to \`true\` on the workbench copy (\`ea.getElement(id).isDeleted = true;\`) and then commit with \`await ea.addElementsToView()\`.
|
||||
@@ -197,7 +198,7 @@ To keep this training file concise, large external type definitions are not incl
|
||||
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
|
||||
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
|
||||
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
|
||||
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. Its \`elementsOverride\` parameter is a complete replacement for the exported element array, not an additive injection or a patch by ID. If supplied, include every existing or temporary element that should appear in the SVG. For temporary changes to existing elements, copy the complete desired export set into the EA workbench, modify it there, and pass \`ea.getElements()\`.
|
||||
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\` for vector output or \`await ea.createViewPNG(...)\` for raster output. Their \`elementsOverride\` parameter is a complete replacement for the exported element array, not an additive injection or patch by ID. Use \`exportArea\` when only a rectangular viewport is needed; it filters out off-area elements and their unused image payloads instead of exporting the full scene and merely changing the SVG viewBox. For temporary changes, copy the complete desired export set into the EA workbench, modify it there, and pass \`ea.getElements()\`.
|
||||
|
||||
#### **8. Custom Pens and Perfect Freehand**
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
declare const STARTUP_SCRIPT_BASE64: string;
|
||||
|
||||
/**
|
||||
* Returns the default startup script embedded from the authoritative Markdown
|
||||
* asset by the Rollup build.
|
||||
*/
|
||||
export const startupScript = (): string => atob(STARTUP_SCRIPT_BASE64);
|
||||
@@ -1,13 +0,0 @@
|
||||
/*
|
||||
f = app.vault.getFileByPath("startuphooks.md");
|
||||
s = await app.vault.read(f);
|
||||
ea = ExcalidrawAutomate;
|
||||
url = await ea.convertStringToDataURL(s);
|
||||
window.navigator.clipboard.writeText(`export const startupScript = () => atob("${url.split("data:text/html;base64,")[1]}");`);
|
||||
console.log("String copied to clipboard");
|
||||
*/
|
||||
|
||||
export const startupScript = () =>
|
||||
atob(
|
||||
"LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIHRoZSB1c2VyIGNsb3NlcyBhbiBFeGNhbGlkcmF3IHZpZXcuCiAqICAgb25WaWV3VW5sb2FkSG9vazogKHZpZXc6IEV4Y2FsaWRyYXdWaWV3KSA9PiB2b2lkID0gbnVsbDsKICovCi8vZWEub25WaWV3VW5sb2FkSG9vayA9ICh2aWV3KSA9PiB7fTsKCi8qKgogKiBJZiBzZXQsIHRoaXMgY2FsbGJhY2sgaXMgdHJpZ2dlcmVkLCB3aGVuIHRoZSB1c2VyIGNoYW5nZXMgdGhlIHZpZXcgbW9kZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIHVzZXIgc3dpdGNoZXMgdG8gdmlldyBtb2RlIGFuZCBiYWNrLgogKiAgIG9uVmlld01vZGVDaGFuZ2VIb29rOiAoaXNWaWV3TW9kZUVuYWJsZWQ6Ym9vbGVhbiwgdmlldzogRXhjYWxpZHJhd1ZpZXcsIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUpID0+IHZvaWQgPSBudWxsOwogKi8KLy9lYS5vblZpZXdNb2RlQ2hhbmdlSG9vayA9IChpc1ZpZXdNb2RlRW5hYmxlZCwgdmlldywgZWEpID0+IHt9OwoKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gdGhlIHVzZXIgaG92ZXJzIGEgbGluayBpbiB0aGUgc2NlbmUuCiAqIFlvdSBjYW4gdXNlIHRoaXMgY2FsbGJhY2sgaW4gY2FzZSB5b3Ugd2FudCB0byBkbyBzb21ldGhpbmcgYWRkaXRpb25hbCB3aGVuIHRoZSBvbkxpbmtIb3ZlciBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25MaW5rSG92ZXIgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkxpbmtIb3ZlciBtYW5hZ2VtZW50IGZsb3cuCiAqICAgb25MaW5rSG92ZXJIb29rOiAoCiAqICAgICBlbGVtZW50OiBOb25EZWxldGVkRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXcsCiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlCiAqICAgKSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25MaW5rSG92ZXJIb29rID0gKGVsZW1lbnQsIGxpbmtUZXh0LCB2aWV3LCBlYSkgPT4ge307CiAgIAovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiB0aGUgdXNlciBjbGlja3MgYSBsaW5rIGluIHRoZSBzY2VuZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIG9uTGlua0NsaWNrIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkxpbmtDbGljayBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLCBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uTGlua0NsaWNrIG1hbmFnZW1lbnQgZmxvdy4KICogICBvbkxpbmtDbGlja0hvb2s6KAogKiAgICAgZWxlbWVudDogRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgZXZlbnQ6IE1vdXNlRXZlbnQsCiAqICAgICB2aWV3OiBFeGNhbGlkcmF3VmlldywKICogICAgIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUKICogICApID0+IGJvb2xlYW4gPSBudWxsOwogKi8KLy9lYS5vbkxpbmtDbGlja0hvb2sgPSAoZWxlbWVudCxsaW5rVGV4dCxldmVudCwgdmlldywgZWEpID0+IHt9OwogICAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvbkRyb3AgZXZlbnQuIAogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUgb25Ecm9wIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkRyb3AgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkRyb3AgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uRHJvcEhvb2s6IChkYXRhOiB7CiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlOwogKiAgICAgZXZlbnQ6IFJlYWN0LkRyYWdFdmVudDxIVE1MRGl2RWxlbWVudD47CiAqICAgICBkcmFnZ2FibGU6IGFueTsgLy9PYnNpZGlhbiBkcmFnZ2FibGUgb2JqZWN0CiAqICAgICB0eXBlOiAiZmlsZSIgfCAidGV4dCIgfCAidW5rbm93biI7CiAqICAgICBwYXlsb2FkOiB7CiAqICAgICAgIGZpbGVzOiBURmlsZVtdOyAvL1RGaWxlW10gYXJyYXkgb2YgZHJvcHBlZCBmaWxlcwogKiAgICAgICB0ZXh0OiBzdHJpbmc7IC8vc3RyaW5nCiAqICAgICB9OwogKiAgICAgZXhjYWxpZHJhd0ZpbGU6IFRGaWxlOyAvL3RoZSBmaWxlIHJlY2VpdmluZyB0aGUgZHJvcCBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIGRyb3AKICogICAgIHBvaW50ZXJQb3NpdGlvbjogeyB4OiBudW1iZXI7IHk6IG51bWJlciB9OyAvL3RoZSBwb2ludGVyIHBvc2l0aW9uIG9uIGNhbnZhcyBhdCB0aGUgdGltZSBvZiBkcm9wCiAqICAgfSkgPT4gYm9vbGVhbiA9IG51bGw7CiAqLwovL2VhLm9uRHJvcEhvb2sgPSAoZGF0YSkgPT4ge307CiAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvblBhc3RlIGV2ZW50LgogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUKICogb25QYXN0ZSBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25QYXN0ZSBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLAogKiBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uUGFzdGUgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uUGFzdGVIb29rOiAoZGF0YTogewogKiAgICAgZWE6IEV4Y2FsaWRyYXdBdXRvbWF0ZTsKICogICAgIHBheWxvYWQ6IENsaXBib2FyZERhdGE7CiAqICAgICBldmVudDogQ2xpcGJvYXJkRXZlbnQ7CiAqICAgICBleGNhbGlkcmF3RmlsZTogVEZpbGU7IC8vdGhlIGZpbGUgcmVjZWl2aW5nIHRoZSBwYXN0ZSBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIHBhc3RlCiAqICAgICBwb2ludGVyUG9zaXRpb246IHsgeDogbnVtYmVyOyB5OiBudW1iZXIgfTsgLy90aGUgcG9pbnRlciBwb3NpdGlvbiBvbiBjYW52YXMKICogICB9KSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25QYXN0ZUhvb2sgPSAoZGF0YSkgPT4ge307CgovKioKICogaWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiBhbiBFeGNhbGlkcmF3IGZpbGUgaXLine truncated
|
||||
);
|
||||
@@ -35,7 +35,7 @@ import { getImageCache } from "src/shared/ImageCache";
|
||||
import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt";
|
||||
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "src/shared/Dialogs/EmbeddableMDFileCustomDataSettingsComponent";
|
||||
import { AutostartScriptsSettingsComponent } from "src/shared/Dialogs/AutostartScriptsSettingsComponent";
|
||||
import { startupScript } from "src/constants/starutpscript";
|
||||
import { startupScript } from "src/constants/startupScript";
|
||||
import {
|
||||
getModifierKeyCategoryName,
|
||||
MODIFIER_KEY_CATEGORIES,
|
||||
|
||||
@@ -31,6 +31,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
- Customize color-picker top picks by dragging colors onto the strip; right-click the strip to reset it. [#11872](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11872)
|
||||
|
||||
## Fixed
|
||||
- Downloading very large SVG or PNG exports now avoids base64 conversion, substantially reducing peak memory use and preventing Electron renderer crashes on image-heavy drawings.
|
||||
- Moving a dirty drawing out of a popout window now safely transfers and persists its latest edits from the replacement main-window view.
|
||||
- Opening the command palette or another Obsidian modal reliably saves dirty drawings, while inline link suggestions no longer trigger a save that can end text editing.
|
||||
- Converting a legacy ".excalidraw" drawing now persists its embedded images as vault attachments during conversion, before the source file can be removed. [#2898](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2898)
|
||||
@@ -50,6 +51,8 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
- Removed unused code and the obsolete Draw.io/Diagram integration, and retired the non-functional Create DrawIO file script.
|
||||
|
||||
## New in Excalidraw Automate
|
||||
- Added area-bounded view exports for image-heavy scenes. \`createViewSVG()\` and the new \`createViewPNG()\` accept \`exportArea: {x, y, width, height}\`, filter out off-area elements and unused image payloads, retain required bound elements, and crop to the requested viewport. Both methods also support a complete \`elementsOverride\` export set.
|
||||
- Added \`getElementsIntersectionArea()\` for explicitly selecting elements whose rendered bounds intersect an area. The existing \`getElementsInArea()\` method remains available as a backward-compatible alias.
|
||||
- \`setView(null)\` now explicitly clears \`ea.targetView\`. Use \`setView()\` or \`setView("auto")\` when you want EA to select a sensible default drawing.
|
||||
- Scripts can register custom buttons in the selected-element context menu:
|
||||
\`\`\`ts
|
||||
|
||||
@@ -287,7 +287,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "createViewSVG",
|
||||
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean, elementsOverride?: readonly ExcalidrawElement[]}): Promise<SVGSVGElement>",
|
||||
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean, elementsOverride?: readonly ExcalidrawElement[], exportArea?: ViewExportArea}): Promise<SVGSVGElement>",
|
||||
desc:
|
||||
"Creates an SVG representation of the current view with specified options.\n" +
|
||||
"\n" +
|
||||
@@ -300,6 +300,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
"@param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.\n" +
|
||||
"@param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.\n" +
|
||||
"@param {readonly ExcalidrawElement[]} [options.elementsOverride] - Complete replacement for the exported elements. It is not merged with the current scene or treated as a patch by ID. Include every element that should appear in the SVG.\n" +
|
||||
"@param {ViewExportArea} [options.exportArea] - Filters elements to an exact scene rectangle and anchors the SVG to that viewport.\n" +
|
||||
"@returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} FrameRenderingOptions\n" +
|
||||
@@ -317,6 +318,20 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
" skipInliningFonts: false,\n" +
|
||||
" embedScene: false,\n" +
|
||||
" // elementsOverride: ea.getElements(), // Must contain the complete export set.\n" +
|
||||
" // exportArea: { x: 0, y: 0, width: 1920, height: 1080 },\n" +
|
||||
"});",
|
||||
},
|
||||
{
|
||||
field: "createViewPNG",
|
||||
code: "async createViewPNG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, embedScene?: boolean, elementsOverride?: readonly ExcalidrawElement[], exportArea?: ViewExportArea, scale?: number}): Promise<Blob>",
|
||||
desc:
|
||||
"Creates a PNG from the currently active Excalidraw view without using or modifying the EA workbench.\n" +
|
||||
"elementsOverride is a complete replacement for the view elements. exportArea filters that candidate set and anchors the image to an exact scene rectangle. The optional scale controls raster resolution.",
|
||||
after:
|
||||
"({\n" +
|
||||
" withBackground: true,\n" +
|
||||
" exportArea: { x: 0, y: 0, width: 1920, height: 1080 },\n" +
|
||||
" scale: 0.5,\n" +
|
||||
"});",
|
||||
},
|
||||
{
|
||||
@@ -690,8 +705,14 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "getElementsInArea",
|
||||
code: "getElementsInArea(elements: ExcalidrawElement[], area: {x: number, y: number, width: number, height: number}): ExcalidrawElement[];",
|
||||
desc: "Filter the elements and returns only those within the specific area.",
|
||||
code: "getElementsInArea(elements: readonly ExcalidrawElement[], area: {x: number, y: number, width: number, height: number, id?: string}, options?: {margin?: number, includeMarkerFrames?: boolean, includeBoundElements?: boolean}): ExcalidrawElement[];",
|
||||
desc: "Returns elements whose rendered bounds intersect the area, preserving source stacking order. Marker frames remain excluded by default for backward compatibility. Optional binding expansion includes containers, bound elements, and arrow binding targets.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getElementsIntersectionArea",
|
||||
code: "getElementsIntersectionArea(elements: readonly ExcalidrawElement[], area: {x: number, y: number, width: number, height: number, id?: string}, options?: {margin?: number, includeMarkerFrames?: boolean, includeBoundElements?: boolean}): ExcalidrawElement[];",
|
||||
desc: "Preferred explicit name for selecting elements whose rendered bounds intersect an area. It shares the implementation and behavior of the backward-compatible getElementsInArea() API.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -62,6 +62,7 @@ import {
|
||||
import {
|
||||
//debug,
|
||||
getImageSize,
|
||||
getPNG,
|
||||
isMaskFile,
|
||||
wrapTextAtCharLength,
|
||||
arrayToMap,
|
||||
@@ -154,10 +155,15 @@ import { log } from "../utils/debugHelper";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
import {
|
||||
AddImageOptions,
|
||||
ElementsInAreaOptions,
|
||||
ImageInfo,
|
||||
KeyBlocker,
|
||||
SceneArea,
|
||||
ScriptSettingValue,
|
||||
SVGColorInfo,
|
||||
ViewImageExportOptions,
|
||||
ViewPNGExportOptions,
|
||||
ViewSVGExportOptions,
|
||||
} from "src/types/excalidrawAutomateTypes";
|
||||
import {
|
||||
_measureText,
|
||||
@@ -205,9 +211,12 @@ import {
|
||||
PDFPageProperties,
|
||||
ExportSettings,
|
||||
} from "src/types/exportUtilTypes";
|
||||
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
|
||||
import {
|
||||
AutoexportConfig,
|
||||
ExcalidrawViewScene,
|
||||
} from "src/types/excalidrawViewTypes";
|
||||
import { FloatingModal } from "./Dialogs/FloatingModal";
|
||||
import { ExcalidrawSidepanelView } from "src/view/sidepanel/Sidepanel";
|
||||
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
|
||||
@@ -219,6 +228,12 @@ import { getPDFCropRect } from "src/utils/PDFUtils";
|
||||
import type { SelectedElementMenuAction } from "src/types/elementActionTypes";
|
||||
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
|
||||
import { URL_REGISTRY, URLs } from "src/constants/safeUrls";
|
||||
import {
|
||||
createExportAreaAnchor,
|
||||
getElementsIntersectionArea as selectElementsIntersectionArea,
|
||||
normalizeSceneArea,
|
||||
} from "src/utils/excalidrawElementUtils";
|
||||
import { cropPNGBlob } from "src/utils/imageExportUtils";
|
||||
|
||||
type ExcalidrawAutomateHelpTarget = ((...args: unknown[]) => unknown) | string;
|
||||
|
||||
@@ -1707,78 +1722,165 @@ export class ExcalidrawAutomate {
|
||||
await exportToPDF({ SVG, scale, pageProps, filename });
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an SVG representation of the current view.
|
||||
*
|
||||
* @param {Object} options - The options for creating the SVG.
|
||||
* @param {boolean} [options.withBackground=true] - Whether to include the background in the SVG.
|
||||
* @param {"light" | "dark"} [options.theme] - The theme to use for the SVG.
|
||||
* @param {FrameRenderingOptions} [options.frameRendering={enabled: true, name: true, outline: true, clip: true}] - The frame rendering options.
|
||||
* @param {number} [options.padding] - The padding to apply around the SVG.
|
||||
* @param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.
|
||||
* @param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.
|
||||
* @param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.
|
||||
* @param {readonly ExcalidrawElement[]} [options.elementsOverride] - Optional complete replacement for the view's exported elements. This array is not merged with the current scene or treated as a patch by ID: when supplied, only its non-deleted elements are exported. Include every element that should appear in the SVG.
|
||||
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
|
||||
*/
|
||||
async createViewSVG({
|
||||
withBackground = true,
|
||||
theme,
|
||||
frameRendering = { enabled: true, name: true, outline: true, clip: true },
|
||||
padding,
|
||||
selectedOnly = false,
|
||||
skipInliningFonts = false,
|
||||
embedScene = false,
|
||||
elementsOverride,
|
||||
}: {
|
||||
withBackground?: boolean;
|
||||
theme?: "light" | "dark";
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
skipInliningFonts?: boolean;
|
||||
embedScene?: boolean;
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
}): Promise<SVGSVGElement> {
|
||||
private prepareViewImageExport(
|
||||
options: ViewImageExportOptions,
|
||||
): {
|
||||
scene: ExcalidrawViewScene;
|
||||
exportSettings: ExportSettings;
|
||||
padding: number;
|
||||
sourceFile: TFile;
|
||||
ownerDocument: Document;
|
||||
exportArea?: SceneArea;
|
||||
exportBounds?: ReturnType<typeof getCommonBoundingBox>;
|
||||
} | null {
|
||||
if (!this.targetView || !this.targetView.file || !this.targetView._loaded) {
|
||||
log("No view loaded");
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
const view = this.targetView;
|
||||
const scene = this.targetView.getScene(selectedOnly);
|
||||
const scene = this.targetView.getScene(options.selectedOnly ?? false);
|
||||
let elements: readonly ExcalidrawElement[] = scene.elements;
|
||||
let files = scene.files;
|
||||
let exportArea: SceneArea | undefined;
|
||||
let exportBounds: ReturnType<typeof getCommonBoundingBox> | undefined;
|
||||
|
||||
if (elementsOverride) {
|
||||
scene.elements = elementsOverride.filter(
|
||||
(el): el is NonDeletedExcalidrawElement => !el.isDeleted,
|
||||
if (options.elementsOverride) {
|
||||
elements = options.elementsOverride;
|
||||
}
|
||||
elements = elements.filter(
|
||||
(el): el is NonDeletedExcalidrawElement => !el.isDeleted,
|
||||
);
|
||||
|
||||
if (options.exportArea) {
|
||||
exportArea = normalizeSceneArea(
|
||||
options.exportArea,
|
||||
options.exportArea.margin,
|
||||
);
|
||||
elements = selectElementsIntersectionArea(elements, exportArea, {
|
||||
includeMarkerFrames: options.exportArea.includeMarkerFrames,
|
||||
includeBoundElements:
|
||||
options.exportArea.includeBoundElements ?? true,
|
||||
});
|
||||
const referencedFileIds = new Set(
|
||||
elements
|
||||
.filter(
|
||||
(element): element is ExcalidrawImageElement =>
|
||||
element.type === "image" && Boolean(element.fileId),
|
||||
)
|
||||
.map((element) => element.fileId),
|
||||
);
|
||||
files = Object.fromEntries(
|
||||
Object.entries(scene.files).filter(([fileId]) =>
|
||||
referencedFileIds.has(fileId as FileId),
|
||||
),
|
||||
);
|
||||
elements = [...elements, createExportAreaAnchor(exportArea)];
|
||||
exportBounds = getCommonBoundingBox(elements);
|
||||
}
|
||||
|
||||
if (!view.getViewExportIncludeInternalLinks()) {
|
||||
scene.elements = sceneRemoveInternalLinks(scene);
|
||||
elements = sceneRemoveInternalLinks({ elements });
|
||||
}
|
||||
|
||||
const exportSettings: ExportSettings = {
|
||||
withBackground: view.getViewExportWithBackground(withBackground),
|
||||
withTheme: true,
|
||||
isMask: isMaskFile(this.plugin, view.file),
|
||||
skipInliningFonts,
|
||||
frameRendering,
|
||||
};
|
||||
|
||||
return await getSVG(
|
||||
{
|
||||
const theme = view.getViewExportTheme(options.theme) as "dark" | "light";
|
||||
return {
|
||||
scene: {
|
||||
...scene,
|
||||
...{
|
||||
appState: {
|
||||
...scene.appState,
|
||||
theme: view.getViewExportTheme(theme) as "dark" | "light",
|
||||
exportEmbedScene: view.getViewExportEmbedScene(embedScene),
|
||||
},
|
||||
elements,
|
||||
files,
|
||||
appState: {
|
||||
...scene.appState,
|
||||
theme,
|
||||
exportEmbedScene: view.getViewExportEmbedScene(options.embedScene),
|
||||
},
|
||||
},
|
||||
exportSettings,
|
||||
view.getViewExportPadding(padding),
|
||||
view.file,
|
||||
exportSettings: {
|
||||
withBackground: view.getViewExportWithBackground(
|
||||
options.withBackground ?? true,
|
||||
),
|
||||
withTheme: true,
|
||||
isMask: isMaskFile(this.plugin, view.file),
|
||||
frameRendering:
|
||||
options.frameRendering ??
|
||||
({ enabled: true, name: true, outline: true, clip: true } as const),
|
||||
},
|
||||
padding: view.getViewExportPadding(options.padding),
|
||||
sourceFile: view.file,
|
||||
ownerDocument: view.ownerDocument,
|
||||
exportArea,
|
||||
exportBounds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an SVG representation of the current view.
|
||||
*
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to the exported SVG, or `undefined` when no
|
||||
* loaded target view is available.
|
||||
*/
|
||||
async createViewSVG(
|
||||
options: ViewSVGExportOptions = {},
|
||||
): Promise<SVGSVGElement> {
|
||||
const prepared = this.prepareViewImageExport(options);
|
||||
if (!prepared) return;
|
||||
prepared.exportSettings.skipInliningFonts =
|
||||
options.skipInliningFonts ?? false;
|
||||
const svg = await getSVG(
|
||||
prepared.scene,
|
||||
prepared.exportSettings,
|
||||
prepared.padding,
|
||||
prepared.sourceFile,
|
||||
);
|
||||
if (svg && prepared.exportArea && prepared.exportBounds) {
|
||||
const originalViewBox = svg.viewBox.baseVal;
|
||||
const exportScale = originalViewBox.width
|
||||
? Number(svg.getAttribute("width")) / originalViewBox.width
|
||||
: 1;
|
||||
const width = prepared.exportArea.width + prepared.padding * 2;
|
||||
const height = prepared.exportArea.height + prepared.padding * 2;
|
||||
svg.setAttribute(
|
||||
"viewBox",
|
||||
`${prepared.exportArea.x - prepared.exportBounds.minX} ${prepared.exportArea.y - prepared.exportBounds.minY} ${width} ${height}`,
|
||||
);
|
||||
svg.setAttribute("width", `${width * exportScale}`);
|
||||
svg.setAttribute("height", `${height * exportScale}`);
|
||||
}
|
||||
return svg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a PNG representation of the current view without using or mutating
|
||||
* the EA workbench.
|
||||
*
|
||||
* @param options - View export options. `elementsOverride`, when supplied, is
|
||||
* a complete replacement rather than a patch. `exportArea` filters that
|
||||
* candidate set and anchors the result to an exact scene rectangle.
|
||||
* @returns A promise resolving to a PNG blob, or `undefined` when no loaded
|
||||
* target view is available.
|
||||
*/
|
||||
async createViewPNG(options: ViewPNGExportOptions = {}): Promise<Blob> {
|
||||
const prepared = this.prepareViewImageExport(options);
|
||||
if (!prepared) return;
|
||||
const png = await getPNG(
|
||||
prepared.scene,
|
||||
prepared.exportSettings,
|
||||
prepared.padding,
|
||||
options.scale ?? 1,
|
||||
);
|
||||
if (!png || !prepared.exportArea || !prepared.exportBounds) return png;
|
||||
const scale = options.scale ?? 1;
|
||||
return await cropPNGBlob(
|
||||
png,
|
||||
{
|
||||
x: (prepared.exportArea.x - prepared.exportBounds.minX) * scale,
|
||||
y: (prepared.exportArea.y - prepared.exportBounds.minY) * scale,
|
||||
width: (prepared.exportArea.width + prepared.padding * 2) * scale,
|
||||
height: (prepared.exportArea.height + prepared.padding * 2) * scale,
|
||||
},
|
||||
prepared.ownerDocument,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4339,36 +4441,39 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the elements within a specific area.
|
||||
* @param elements - The elements to check.
|
||||
* @param param1 - The area to check against.
|
||||
* @returns The elements within the area.
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsInArea(
|
||||
elements: readonly ExcalidrawElement[],
|
||||
element: ExcalidrawElement,
|
||||
area: SceneArea,
|
||||
options: ElementsInAreaOptions = {},
|
||||
): ExcalidrawElement[] {
|
||||
const { x, y, width, height, id } = element;
|
||||
return elements.filter((el) => {
|
||||
if (el.type === "frame" && el.frameRole === "marker") {
|
||||
return false;
|
||||
}
|
||||
if (el.id === id) {
|
||||
return true;
|
||||
}
|
||||
const { topX, topY, width: w, height: h } = this.getBoundingBox([el]);
|
||||
const elLeft = topX;
|
||||
const elTop = topY;
|
||||
const elRight = topX + w;
|
||||
const elBottom = topY + h;
|
||||
// overlap exists if rectangles intersect
|
||||
return !(
|
||||
elLeft >= x + width ||
|
||||
elRight <= x ||
|
||||
elTop >= y + height ||
|
||||
elBottom <= y
|
||||
);
|
||||
});
|
||||
return this.getElementsIntersectionArea(elements, area, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets elements whose rendered bounds intersect a scene area.
|
||||
*
|
||||
* @remarks
|
||||
* This explicit name is preferred for new code. `getElementsInArea()` remains
|
||||
* available as a backward-compatible alias and uses the same implementation.
|
||||
*
|
||||
* @param elements - Elements to test, in scene stacking order.
|
||||
* @param area - Rectangle or element defining the scene area.
|
||||
* @param options - Optional margin, marker-frame, and binding expansion rules.
|
||||
* @returns Intersecting elements in their original stacking order.
|
||||
*/
|
||||
getElementsIntersectionArea(
|
||||
elements: readonly ExcalidrawElement[],
|
||||
area: SceneArea,
|
||||
options: ElementsInAreaOptions = {},
|
||||
): ExcalidrawElement[] {
|
||||
return selectElementsIntersectionArea(elements, area, options);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -954,13 +954,14 @@ export class ScriptEngine {
|
||||
): Promise<unknown> {
|
||||
//addresses the situation when after paste text element IDs are not updated to 8 characters
|
||||
//linked to onPaste save issue with the false parameter
|
||||
//The Excalidraw API can briefly be null while React replaces the canvas
|
||||
//during a view transition. This legacy save preflight is optional; script
|
||||
//execution itself must continue so view-autostart can attach to the new view.
|
||||
const scene = view?.getScene();
|
||||
if (
|
||||
view &&
|
||||
view
|
||||
.getScene()
|
||||
.elements.some(
|
||||
(el) => !el.isDeleted && el.type === "text" && el.id.length > 8,
|
||||
)
|
||||
scene?.elements.some(
|
||||
(el) => !el.isDeleted && el.type === "text" && el.id.length > 8,
|
||||
)
|
||||
) {
|
||||
await view.save(false, true);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import {
|
||||
AppState,
|
||||
DataURL,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { TFile } from "obsidian";
|
||||
import { FileId } from "src/core";
|
||||
import type { FrameRenderingOptions } from "./utilTypes";
|
||||
import {
|
||||
ColorMap,
|
||||
PDFPageViewProps,
|
||||
@@ -58,3 +63,61 @@ export interface AddImageOptions {
|
||||
anchor?: boolean;
|
||||
colorMap?: ColorMap;
|
||||
}
|
||||
|
||||
/** A rectangular region in Excalidraw scene coordinates. */
|
||||
export interface SceneArea {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
/** Optional ID of an element representing the area. */
|
||||
id?: string;
|
||||
}
|
||||
|
||||
/** Controls how {@link ExcalidrawAutomate.getElementsInArea} selects elements. */
|
||||
export interface ElementsInAreaOptions {
|
||||
/** Expands the area by this many scene units on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames. Existing behavior excludes them by default. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/** Includes containers, bound elements, and arrow binding targets needed by the result. */
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
|
||||
/** Restricts a view image export to a rectangular scene region. */
|
||||
export interface ViewExportArea extends SceneArea {
|
||||
/** Expands both the selected content and exported viewport on every side. */
|
||||
margin?: number;
|
||||
/** Includes marker frames in the export candidate set. */
|
||||
includeMarkerFrames?: boolean;
|
||||
/**
|
||||
* Includes containers, bound elements, and arrow binding targets needed to
|
||||
* render intersecting elements. Defaults to `true` for area exports.
|
||||
*/
|
||||
includeBoundElements?: boolean;
|
||||
}
|
||||
|
||||
/** Options shared by view-based SVG and PNG exports. */
|
||||
export interface ViewImageExportOptions {
|
||||
withBackground?: boolean;
|
||||
theme?: AppState["theme"];
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
embedScene?: boolean;
|
||||
/** Complete replacement for the view elements used by the export. */
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
/** Filters and anchors the export to an exact scene rectangle. */
|
||||
exportArea?: ViewExportArea;
|
||||
}
|
||||
|
||||
/** Options for {@link ExcalidrawAutomate.createViewSVG}. */
|
||||
export interface ViewSVGExportOptions extends ViewImageExportOptions {
|
||||
skipInliningFonts?: boolean;
|
||||
}
|
||||
|
||||
/** Options for {@link ExcalidrawAutomate.createViewPNG}. */
|
||||
export interface ViewPNGExportOptions extends ViewImageExportOptions {
|
||||
/** Raster scale applied to the exported viewport. */
|
||||
scale?: number;
|
||||
}
|
||||
@@ -59,7 +59,10 @@ 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";
|
||||
import {
|
||||
cloneElement,
|
||||
getElementsInArea,
|
||||
} from "./excalidrawElementUtils";
|
||||
|
||||
export {
|
||||
cloneElement,
|
||||
@@ -382,9 +385,7 @@ export async function getTemplate(
|
||||
rect.strokeWidth = 0.1;
|
||||
rect.fillStyle = "solid";
|
||||
scene.elements.push(rect);
|
||||
groupElements = plugin.ea
|
||||
.getElementsInArea(scene.elements, rect)
|
||||
.concat(el);
|
||||
groupElements = getElementsInArea(scene.elements, rect).concat(el);
|
||||
} else {
|
||||
groupElements = plugin.ea.getElementsInFrame(
|
||||
el,
|
||||
@@ -409,7 +410,7 @@ export async function getTemplate(
|
||||
width: el.width + 2 * padding,
|
||||
height: el.height + 2 * padding,
|
||||
};
|
||||
groupElements = plugin.ea.getElementsInArea(scene.elements, areaElement);
|
||||
groupElements = getElementsInArea(scene.elements, areaElement);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
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";
|
||||
import {
|
||||
getCommonBoundingBox,
|
||||
nanoid,
|
||||
restoreElements,
|
||||
} from "src/constants/constants";
|
||||
import type {
|
||||
ElementsInAreaOptions,
|
||||
SceneArea,
|
||||
} from "src/types/excalidrawAutomateTypes";
|
||||
|
||||
/**
|
||||
* Calculates the axis-aligned bounds shared by a collection of elements.
|
||||
@@ -15,6 +23,159 @@ export function estimateBounds(
|
||||
return [bb.minX, bb.minY, bb.maxX, bb.maxY];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a normalized copy of a scene area, optionally inflated on every side.
|
||||
*
|
||||
* @param area - Scene rectangle to normalize.
|
||||
* @param margin - Scene-unit margin added around the rectangle.
|
||||
*/
|
||||
export function normalizeSceneArea(
|
||||
area: SceneArea,
|
||||
margin: number = 0,
|
||||
): SceneArea {
|
||||
const left = Math.min(area.x, area.x + area.width) - margin;
|
||||
const top = Math.min(area.y, area.y + area.height) - margin;
|
||||
const right = Math.max(area.x, area.x + area.width) + margin;
|
||||
const bottom = Math.max(area.y, area.y + area.height) + margin;
|
||||
return {
|
||||
x: left,
|
||||
y: top,
|
||||
width: right - left,
|
||||
height: bottom - top,
|
||||
...(area.id ? { id: area.id } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function expandBoundElementIds(
|
||||
selectedIds: Set<string>,
|
||||
elements: readonly ExcalidrawElement[],
|
||||
): void {
|
||||
const elementsById = new Map(elements.map((element) => [element.id, element]));
|
||||
const queue = [...selectedIds];
|
||||
while (queue.length > 0) {
|
||||
const id = queue.shift();
|
||||
if (!id) continue;
|
||||
const element = elementsById.get(id);
|
||||
if (!element) continue;
|
||||
const relatedIds: string[] = [];
|
||||
if (element.type === "text" && element.containerId) {
|
||||
relatedIds.push(element.containerId);
|
||||
}
|
||||
for (const boundElement of element.boundElements ?? []) {
|
||||
relatedIds.push(boundElement.id);
|
||||
}
|
||||
if (element.type === "arrow") {
|
||||
if (element.startBinding?.elementId) {
|
||||
relatedIds.push(element.startBinding.elementId);
|
||||
}
|
||||
if (element.endBinding?.elementId) {
|
||||
relatedIds.push(element.endBinding.elementId);
|
||||
}
|
||||
}
|
||||
for (const id of relatedIds) {
|
||||
if (!selectedIds.has(id) && elementsById.has(id)) {
|
||||
selectedIds.add(id);
|
||||
queue.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns elements whose axis-aligned rendered bounds intersect a scene area.
|
||||
*
|
||||
* @remarks
|
||||
* Results preserve the source array's stacking order. Marker frames are
|
||||
* excluded by default to preserve the historical ExcalidrawAutomate behavior.
|
||||
*/
|
||||
export function getElementsIntersectionArea(
|
||||
elements: readonly ExcalidrawElement[],
|
||||
area: SceneArea,
|
||||
options: ElementsInAreaOptions = {},
|
||||
): ExcalidrawElement[] {
|
||||
const normalizedArea = normalizeSceneArea(area, options.margin);
|
||||
const areaRight = normalizedArea.x + normalizedArea.width;
|
||||
const areaBottom = normalizedArea.y + normalizedArea.height;
|
||||
const selectedIds = new Set<string>();
|
||||
|
||||
for (const element of elements) {
|
||||
if (
|
||||
!options.includeMarkerFrames &&
|
||||
element.type === "frame" &&
|
||||
element.frameRole === "marker"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (normalizedArea.id && element.id === normalizedArea.id) {
|
||||
selectedIds.add(element.id);
|
||||
continue;
|
||||
}
|
||||
const bounds = getCommonBoundingBox([element]);
|
||||
if (
|
||||
bounds.minX < areaRight &&
|
||||
bounds.maxX > normalizedArea.x &&
|
||||
bounds.minY < areaBottom &&
|
||||
bounds.maxY > normalizedArea.y
|
||||
) {
|
||||
selectedIds.add(element.id);
|
||||
}
|
||||
}
|
||||
|
||||
if (options.includeBoundElements) {
|
||||
expandBoundElementIds(selectedIds, elements);
|
||||
}
|
||||
return elements.filter((element) => selectedIds.has(element.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compatible name for {@link getElementsIntersectionArea}.
|
||||
*/
|
||||
export function getElementsInArea(
|
||||
elements: readonly ExcalidrawElement[],
|
||||
area: SceneArea,
|
||||
options: ElementsInAreaOptions = {},
|
||||
): ExcalidrawElement[] {
|
||||
return getElementsIntersectionArea(elements, area, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an invisible rectangle that pins an export to an exact scene area.
|
||||
*
|
||||
* @remarks The returned element is detached data and never enters the EA workbench.
|
||||
*/
|
||||
export function createExportAreaAnchor(area: SceneArea): ExcalidrawElement {
|
||||
const normalizedArea = normalizeSceneArea(area);
|
||||
return {
|
||||
id: nanoid(),
|
||||
type: "rectangle",
|
||||
x: normalizedArea.x,
|
||||
y: normalizedArea.y,
|
||||
width: normalizedArea.width,
|
||||
height: normalizedArea.height,
|
||||
angle: 0,
|
||||
strokeColor: "#000000",
|
||||
backgroundColor: "transparent",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 0.01,
|
||||
strokeStyle: "solid",
|
||||
roughness: 0,
|
||||
opacity: 0,
|
||||
groupIds: [],
|
||||
frameId: null,
|
||||
index: "a0",
|
||||
roundness: null,
|
||||
seed: 1,
|
||||
version: 1,
|
||||
versionNonce: 1,
|
||||
isDeleted: false,
|
||||
boundElements: [],
|
||||
updated: Date.now(),
|
||||
link: null,
|
||||
locked: false,
|
||||
hasTextLink: false,
|
||||
} as unknown as ExcalidrawElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves elements so their top-left corner or center is at a scene position.
|
||||
*
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Notice } from "obsidian";
|
||||
import { DEVICE, EXCALIDRAW_PLUGIN } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { download } from "./fileUtils";
|
||||
import { svgToBase64 } from "./embeddedAssetUtils";
|
||||
import { downloadBlob } from "./fileUtils";
|
||||
import {
|
||||
PageDimensions,
|
||||
PageOrientation,
|
||||
@@ -618,14 +617,12 @@ export async function exportPNGToClipboard(png: Blob) {
|
||||
}
|
||||
|
||||
export function exportPNG(png: Blob, filename: string) {
|
||||
const reader = new FileReader();
|
||||
reader.readAsDataURL(png);
|
||||
reader.onloadend = () => {
|
||||
const base64data = reader.result;
|
||||
download(null, base64data, `${filename}.png`);
|
||||
};
|
||||
downloadBlob(png, `${filename}.png`);
|
||||
}
|
||||
|
||||
export function exportSVG(svg: SVGSVGElement, filename: string) {
|
||||
download(null, svgToBase64(svg.outerHTML), `${filename}.svg`);
|
||||
downloadBlob(
|
||||
new Blob([svg.outerHTML], { type: "image/svg+xml;charset=utf-8" }),
|
||||
`${filename}.svg`,
|
||||
);
|
||||
}
|
||||
@@ -57,6 +57,26 @@ export const download = (
|
||||
mainDocument.body.removeChild(element);
|
||||
};
|
||||
|
||||
/**
|
||||
* Downloads a blob without converting it to a base64 data URL.
|
||||
*
|
||||
* @remarks
|
||||
* Object URLs avoid the large temporary strings and 33% base64 expansion that
|
||||
* can otherwise exhaust Electron's renderer process for large SVG or PNG files.
|
||||
*/
|
||||
export const downloadBlob = (blob: Blob, filename: string): void => {
|
||||
const ownerWindow = mainDocument.defaultView;
|
||||
const urlApi = ownerWindow?.URL ?? URL;
|
||||
const objectUrl = urlApi.createObjectURL(blob);
|
||||
const element = mainDocument.body.createEl("a");
|
||||
setElementDisplay(element, "none");
|
||||
element.setAttribute("href", objectUrl);
|
||||
element.setAttribute("download", filename);
|
||||
element.click();
|
||||
mainDocument.body.removeChild(element);
|
||||
(ownerWindow ?? window).setTimeout(() => urlApi.revokeObjectURL(objectUrl), 1000);
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates the image filename based on the excalidraw filename
|
||||
* @param excalidrawPath - Full filepath of ExclidrawFile
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
declare const deliberateCreateElement: (
|
||||
document: Document,
|
||||
tagName: string,
|
||||
) => HTMLElement;
|
||||
|
||||
export interface RasterCropRegion {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Crops a PNG blob without converting it through a base64 data URL. */
|
||||
export async function cropPNGBlob(
|
||||
blob: Blob,
|
||||
crop: RasterCropRegion,
|
||||
ownerDocument: Document,
|
||||
): Promise<Blob> {
|
||||
const ownerWindow = ownerDocument.defaultView ?? window;
|
||||
const urlApi = ownerWindow.URL;
|
||||
const objectUrl = urlApi.createObjectURL(blob);
|
||||
const image = deliberateCreateElement(
|
||||
ownerDocument,
|
||||
"img",
|
||||
) as HTMLImageElement;
|
||||
try {
|
||||
image.src = objectUrl;
|
||||
await image.decode();
|
||||
const canvas = deliberateCreateElement(
|
||||
ownerDocument,
|
||||
"canvas",
|
||||
) as HTMLCanvasElement;
|
||||
canvas.width = Math.max(1, Math.round(crop.width));
|
||||
canvas.height = Math.max(1, Math.round(crop.height));
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) throw new Error("Could not create a 2D export canvas.");
|
||||
context.drawImage(
|
||||
image,
|
||||
crop.x,
|
||||
crop.y,
|
||||
crop.width,
|
||||
crop.height,
|
||||
0,
|
||||
0,
|
||||
canvas.width,
|
||||
canvas.height,
|
||||
);
|
||||
return await new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob((result) => {
|
||||
if (result) resolve(result);
|
||||
else reject(new Error("Could not encode the cropped PNG."));
|
||||
}, "image/png");
|
||||
});
|
||||
} finally {
|
||||
urlApi.revokeObjectURL(objectUrl);
|
||||
}
|
||||
}
|
||||
+46
-25
@@ -282,6 +282,11 @@ import { getYouTubeUrl, URLs } from "src/constants/safeUrls";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
import { isInstanceOfHTMLElement } from "src/utils/typechecks";
|
||||
import { setElementDisplay } from "src/utils/htmlUtils";
|
||||
import {
|
||||
captureTrackedAppState,
|
||||
didTrackedAppStateChange,
|
||||
type TrackedAppStateSnapshot,
|
||||
} from "./trackedAppState";
|
||||
|
||||
const EMBEDDABLE_SEMAPHORE_TIMEOUT = 2000;
|
||||
const PREVENT_RELOAD_TIMEOUT = 2000;
|
||||
@@ -519,6 +524,7 @@ export default class ExcalidrawView
|
||||
private editingSelfResetTimer: number | null = null;
|
||||
private colorChangeTimer: number | null = null;
|
||||
private previousSceneVersion = 0;
|
||||
private previousTrackedAppState: TrackedAppStateSnapshot | null = null;
|
||||
public previousBackgroundColor = "";
|
||||
public previousTheme = "";
|
||||
private pendingUIMode: UIMode | null = null;
|
||||
@@ -2674,6 +2680,7 @@ export default class ExcalidrawView
|
||||
this.lastSceneLoadTime = 0;
|
||||
(api.resetScene as () => void)();
|
||||
this.previousSceneVersion = 0;
|
||||
this.previousTrackedAppState = null;
|
||||
}
|
||||
|
||||
public isLoaded: boolean = false;
|
||||
@@ -3697,6 +3704,7 @@ export default class ExcalidrawView
|
||||
if (el) {
|
||||
this.previousSceneVersion = this.getSceneVersion(el);
|
||||
}
|
||||
this.setTrackedAppStateBaseline(api.getAppState());
|
||||
this.actionButtons?.save
|
||||
?.querySelector("svg")
|
||||
.removeClass("excalidraw-dirty");
|
||||
@@ -4670,7 +4678,6 @@ export default class ExcalidrawView
|
||||
activeTool,
|
||||
disableContextMenu: st.disableContextMenu,
|
||||
bindingPreference: st.bindingPreference,
|
||||
isBindingEnabled: st.isBindingEnabled,
|
||||
isMidpointSnappingEnabled: st.isMidpointSnappingEnabled,
|
||||
boxSelectionMode: st.boxSelectionMode,
|
||||
},
|
||||
@@ -5201,6 +5208,12 @@ export default class ExcalidrawView
|
||||
}
|
||||
}
|
||||
|
||||
private setTrackedAppStateBaseline(appState: AppState): void {
|
||||
this.previousTrackedAppState = captureTrackedAppState(appState);
|
||||
this.previousBackgroundColor = appState.viewBackgroundColor;
|
||||
this.previousTheme = appState.theme;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -5215,11 +5228,14 @@ export default class ExcalidrawView
|
||||
if (event.type !== "durable") {
|
||||
return;
|
||||
}
|
||||
// Durable increments are the precise edit boundary needed by the save
|
||||
// coordinator. Unlike the legacy dirty boolean, they continue to arrive
|
||||
// while compression or disk persistence is in flight.
|
||||
this.setDirty();
|
||||
Object.values(event.change.elements).forEach((element) => {
|
||||
const changedElements = Object.values(event.change.elements);
|
||||
// Durable increments also contain undoable selection/app-state changes.
|
||||
// Only element changes advance the persistence revision here; tracked
|
||||
// drawing app state is handled explicitly in onChange().
|
||||
if (changedElements.length > 0) {
|
||||
this.setDirty();
|
||||
}
|
||||
changedElements.forEach((element) => {
|
||||
if (element.type !== "image" || !element.isDeleted) {
|
||||
return;
|
||||
}
|
||||
@@ -5289,31 +5305,36 @@ export default class ExcalidrawView
|
||||
}
|
||||
}
|
||||
this.previousSceneVersion = this.getSceneVersion(et);
|
||||
this.previousBackgroundColor = st.viewBackgroundColor;
|
||||
this.previousTheme = st.theme;
|
||||
this.setTrackedAppStateBaseline(st);
|
||||
this.canvasColorChangeHook(st);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
st.theme !== this.previousTheme &&
|
||||
this.file === this.excalidrawData.file
|
||||
) {
|
||||
if (this.file === this.excalidrawData.file) {
|
||||
const nextTrackedAppState = captureTrackedAppState(st);
|
||||
const backgroundChanged =
|
||||
st.viewBackgroundColor !== this.previousBackgroundColor;
|
||||
if (
|
||||
this.previousTrackedAppState !== null &&
|
||||
didTrackedAppStateChange(
|
||||
this.previousTrackedAppState,
|
||||
nextTrackedAppState,
|
||||
!this.plugin.settings.zoomToFitOnOpen,
|
||||
)
|
||||
) {
|
||||
this.setDirty();
|
||||
}
|
||||
this.previousTrackedAppState = nextTrackedAppState;
|
||||
this.previousTheme = st.theme;
|
||||
this.setDirty();
|
||||
}
|
||||
if (
|
||||
st.viewBackgroundColor !== this.previousBackgroundColor &&
|
||||
this.file === this.excalidrawData.file
|
||||
) {
|
||||
this.previousBackgroundColor = st.viewBackgroundColor;
|
||||
this.setDirty();
|
||||
if (this.colorChangeTimer) {
|
||||
window.clearTimeout(this.colorChangeTimer);
|
||||
if (backgroundChanged) {
|
||||
if (this.colorChangeTimer) {
|
||||
window.clearTimeout(this.colorChangeTimer);
|
||||
}
|
||||
this.colorChangeTimer = window.setTimeout(() => {
|
||||
this.canvasColorChangeHook(st);
|
||||
this.colorChangeTimer = null;
|
||||
}, 50); //just enough time if the user is playing with color picker, the change is not too frequent.
|
||||
}
|
||||
this.colorChangeTimer = window.setTimeout(() => {
|
||||
this.canvasColorChangeHook(st);
|
||||
this.colorChangeTimer = null;
|
||||
}, 50); //just enough time if the user is playing with color picker, the change is not too frequent.
|
||||
}
|
||||
if (
|
||||
!this.semaphores.dirty &&
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { AppState } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
|
||||
/** App-state values whose changes are meaningful to drawing persistence. */
|
||||
export interface TrackedAppStateSnapshot {
|
||||
theme: AppState["theme"];
|
||||
viewBackgroundColor: AppState["viewBackgroundColor"];
|
||||
gridSize: AppState["gridSize"];
|
||||
gridStep: AppState["gridStep"];
|
||||
gridModeEnabled: AppState["gridModeEnabled"];
|
||||
colorPalette: AppState["colorPalette"];
|
||||
colorTopPicks: AppState["colorTopPicks"];
|
||||
frameRendering: AppState["frameRendering"];
|
||||
objectsSnapModeEnabled: AppState["objectsSnapModeEnabled"];
|
||||
bindingPreference: AppState["bindingPreference"];
|
||||
isMidpointSnappingEnabled: AppState["isMidpointSnappingEnabled"];
|
||||
boxSelectionMode: AppState["boxSelectionMode"];
|
||||
scrollX: AppState["scrollX"];
|
||||
scrollY: AppState["scrollY"];
|
||||
zoom: AppState["zoom"]["value"];
|
||||
}
|
||||
|
||||
/** Captures only app state that can independently require drawing persistence. */
|
||||
export function captureTrackedAppState(
|
||||
appState: AppState,
|
||||
): TrackedAppStateSnapshot {
|
||||
return {
|
||||
theme: appState.theme,
|
||||
viewBackgroundColor: appState.viewBackgroundColor,
|
||||
gridSize: appState.gridSize,
|
||||
gridStep: appState.gridStep,
|
||||
gridModeEnabled: appState.gridModeEnabled,
|
||||
colorPalette: appState.colorPalette,
|
||||
colorTopPicks: appState.colorTopPicks,
|
||||
frameRendering: appState.frameRendering,
|
||||
objectsSnapModeEnabled: appState.objectsSnapModeEnabled,
|
||||
bindingPreference: appState.bindingPreference,
|
||||
isMidpointSnappingEnabled: appState.isMidpointSnappingEnabled,
|
||||
boxSelectionMode: appState.boxSelectionMode,
|
||||
scrollX: appState.scrollX,
|
||||
scrollY: appState.scrollY,
|
||||
zoom: appState.zoom.value,
|
||||
};
|
||||
}
|
||||
|
||||
function areStructuredValuesEqual(left: unknown, right: unknown): boolean {
|
||||
if (Object.is(left, right)) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
left === null ||
|
||||
right === null ||
|
||||
typeof left !== "object" ||
|
||||
typeof right !== "object"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (Array.isArray(left) || Array.isArray(right)) {
|
||||
return (
|
||||
Array.isArray(left) &&
|
||||
Array.isArray(right) &&
|
||||
left.length === right.length &&
|
||||
left.every((value, index) =>
|
||||
areStructuredValuesEqual(value, right[index]),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const leftRecord = left as Record<string, unknown>;
|
||||
const rightRecord = right as Record<string, unknown>;
|
||||
const leftKeys = Object.keys(leftRecord);
|
||||
const rightKeys = Object.keys(rightRecord);
|
||||
return (
|
||||
leftKeys.length === rightKeys.length &&
|
||||
leftKeys.every(
|
||||
(key) =>
|
||||
Object.hasOwn(rightRecord, key) &&
|
||||
areStructuredValuesEqual(leftRecord[key], rightRecord[key]),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether drawing-owned app state changed. Viewport state participates
|
||||
* only when opening the drawing will not replace it with zoom-to-fit.
|
||||
*/
|
||||
export function didTrackedAppStateChange(
|
||||
previous: TrackedAppStateSnapshot,
|
||||
next: TrackedAppStateSnapshot,
|
||||
trackViewport: boolean,
|
||||
): boolean {
|
||||
return (
|
||||
previous.theme !== next.theme ||
|
||||
previous.viewBackgroundColor !== next.viewBackgroundColor ||
|
||||
previous.gridSize !== next.gridSize ||
|
||||
previous.gridStep !== next.gridStep ||
|
||||
previous.gridModeEnabled !== next.gridModeEnabled ||
|
||||
!areStructuredValuesEqual(previous.colorPalette, next.colorPalette) ||
|
||||
!areStructuredValuesEqual(previous.colorTopPicks, next.colorTopPicks) ||
|
||||
!areStructuredValuesEqual(previous.frameRendering, next.frameRendering) ||
|
||||
previous.objectsSnapModeEnabled !== next.objectsSnapModeEnabled ||
|
||||
previous.bindingPreference !== next.bindingPreference ||
|
||||
previous.isMidpointSnappingEnabled !== next.isMidpointSnappingEnabled ||
|
||||
previous.boxSelectionMode !== next.boxSelectionMode ||
|
||||
(trackViewport &&
|
||||
(previous.scrollX !== next.scrollX ||
|
||||
previous.scrollY !== next.scrollY ||
|
||||
previous.zoom !== next.zoom))
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user