mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-11-27 06:32:42 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
149e1e5bf0 | ||
|
|
0da7120a7d | ||
|
|
d94b3b19ad | ||
|
|
169ceb3cf3 | ||
|
|
ded91c6882 | ||
|
|
4ce81be081 | ||
|
|
740ee455d3 | ||
|
|
81fbbf42b7 | ||
|
|
ba6c45d621 |
No files matched your search
@@ -206,7 +206,7 @@ The build embeds or injects runtime code for:
|
||||
|
||||
These payloads are executed or unpacked at runtime. This is intentional.
|
||||
|
||||
React and the Excalidraw package are separate payloads. React must not be bundled into the Excalidraw artifact, because the plugin creates a matching private React runtime in every Obsidian window. Mermaid is also intentionally absent from the artifact and is loaded lazily at runtime through Excalidraw Extras. All other required Excalidraw assets are expected to work offline except the deliberately lazy CJK font subsets.
|
||||
React and the Excalidraw package are separate payloads. React must not be bundled into the Excalidraw artifact, because the plugin evaluates one matching private React runtime and supplies it to the single Excalidraw runtime used by every view. Mermaid is also intentionally absent from the artifact and is loaded lazily at runtime through Excalidraw Extras. All other required Excalidraw assets are expected to work offline except the deliberately lazy CJK font subsets.
|
||||
|
||||
### Two-Repository Excalidraw Workflow
|
||||
|
||||
@@ -233,9 +233,9 @@ The customized Excalidraw runtime receives Obsidian capabilities through typed h
|
||||
- Keep adapters narrow and semantic. They may expose operations such as reading a current limit or running a named action, but never the plugin instance, the complete settings object, or an active view.
|
||||
- Capabilities used by `@excalidraw/common` or lower layers belong in `ObsidianCommonHostAdapter`. Capabilities used only by the Excalidraw package belong in `ObsidianExcalidrawHostAdapter`.
|
||||
- View-specific state must remain instance-scoped. Do not put an active view into either window-runtime adapter; expose a semantic plugin-side action when the component genuinely requires such behavior.
|
||||
- `PackageManager` registers both adapters once per evaluated Excalidraw runtime and window. React components and individual `ExcalidrawView` instances must not configure or dispose them.
|
||||
- `PackageManager` registers both adapters once with the shared Excalidraw runtime. React components and individual `ExcalidrawView` instances must not configure or dispose them.
|
||||
- Adapter methods must read live plugin state instead of capturing settings snapshots during registration.
|
||||
- `PackageManager` owns the complete lifetime: dispose registrations before removing a package or window runtime, make cleanup idempotent, and roll back all registrations if configuring any adapter fails.
|
||||
- `PackageManager` owns the complete lifetime: dispose registrations before releasing the shared runtime, make cleanup idempotent, and roll back all registrations if configuring either adapter fails.
|
||||
|
||||
A closure that references the plugin is not itself a memory leak. The risk is allowing a registry, listener, or evaluated runtime retaining that closure to outlive its owning `PackageManager` registration.
|
||||
|
||||
@@ -252,11 +252,11 @@ The host adapters are an internal protocol between this plugin and its exact `@z
|
||||
|
||||
### Popout Window Support
|
||||
|
||||
- `src/core/managers/PackageManager.ts` manages window-scoped React/ReactDOM/Excalidraw packages.
|
||||
- This is necessary because the plugin must work in Obsidian/Electron popout windows.
|
||||
- Do not replace this with a naive global singleton approach.
|
||||
- `src/core/managers/PackageManager.ts` evaluates one private React/ReactDOM/Excalidraw runtime in the main application realm and leases that runtime to every view.
|
||||
- A lease retains the view's actual acquisition window for migration and persistence decisions; package evaluation ownership must never substitute for that identity.
|
||||
- Popouts receive only a temporary `window.ExcalidrawLib` compatibility alias. Remove it after the final lease for that window while keeping the shared runtime alive until plugin unload.
|
||||
- The runtime is built from official npm package entry points and kept in plugin/package lexical scope. Do not assign React or ReactDOM to `window`; only the documented `window.ExcalidrawLib` compatibility surface remains global.
|
||||
- Rendering, DOM ownership, events, observers, portals, and React roots must use the owning view window where appropriate.
|
||||
- Every Excalidraw root must receive its stable owning document. Rendering, DOM ownership, events, observers, portals, realm constructors, fonts, timers, and React roots must derive from the owning view document/window where appropriate; do not turn the shared runtime into a mutable "current window" singleton.
|
||||
- Treat `HTMLElement.onWindowMigrated()` as a destructive runtime boundary. Its callback runs after Obsidian has moved the view container to another document, while the existing React root and Excalidraw API still belong to the source window runtime.
|
||||
- For a dirty migration, synchronously capture every API-owned value needed for persistence and unmount the source React root **before the first `await`**. Do not move synchronization, compression, Vault/native file access, `closeLeafView()`, or another asynchronous step ahead of that unmount. On macOS/Electron, doing so reproducibly allowed the source popout window to be destroyed before `root.unmount()`, freezing Obsidian and disconnecting DevTools.
|
||||
- Cancel deferred initialization and scene-file loaders before migration unmount, and require delayed loader callbacks to match the exact API instance and file path that started them. Component-owned image decoding can still outlive a synchronous `addFiles()` call, so the Excalidraw runtime must also stop after an awaited decode when its editor has unmounted; never delay migration unmount to wait for image work.
|
||||
@@ -411,10 +411,10 @@ Backwards compatibility is a strong requirement in this repository.
|
||||
|
||||
## React Runtime Import Model
|
||||
|
||||
React usage in this repository is special because React and ReactDOM are package-managed per window to support Obsidian popout windows and runtime package injection.
|
||||
React usage in this repository is special because one private React/ReactDOM runtime is package-managed across main-window and popout roots.
|
||||
|
||||
- It is fine to import React for types, component definitions, JSX compilation, and nearby established patterns.
|
||||
- Do not assume a single global React/ReactDOM runtime is safe for rendering, root creation, or view-owned objects.
|
||||
- The shared runtime is safe only because each root and Excalidraw instance receives stable owner-document state. Never recover view ownership from the runtime's lexical main window.
|
||||
- For view-bound rendering and roots, follow `src/view/ExcalidrawView.ts` and use `view.packages.react` and `view.packages.reactDOM` through the package-manager flow.
|
||||
- For view-owned React objects such as refs or runtime-created elements, follow neighboring patterns such as `src/view/components/menu/ToolsPanel.tsx` and `src/view/components/CustomEmbeddable.tsx`, which intentionally use the package-managed React instance.
|
||||
- Do not introduce a new direct `ReactDOM.createRoot()` path outside the package-manager model unless you have verified popout-window safety.
|
||||
@@ -430,7 +430,7 @@ Use this routing guide before editing.
|
||||
- Commands and command registration: `src/core/managers/CommandManager.ts`
|
||||
- Vault or workspace event handling: `src/core/managers/EventManager.ts` and `src/core/managers/FileManager.ts`
|
||||
- Markdown rendering or markdown embeds: `src/core/managers/MarkdownPostProcessor.ts`
|
||||
- Package/runtime loading across windows: `src/core/managers/PackageManager.ts`
|
||||
- Shared package/runtime loading and per-window leases: `src/core/managers/PackageManager.ts`
|
||||
- Styling setup and style injection: `src/core/managers/StylesManager.ts`, `styles.css`, `src/utils/dynamicStyling.ts`
|
||||
- Main canvas/editor behavior: `src/view/ExcalidrawView.ts`
|
||||
- Sidepanel behavior: `src/view/sidepanel/`
|
||||
@@ -491,7 +491,7 @@ These areas require extra care:
|
||||
- `rollup.config.mjs`: payload injection, localization, manifest/versioning, CSS bundling
|
||||
- `src/core/main.ts`: lifecycle order, settings migration, startup initialization
|
||||
- `src/view/ExcalidrawView.ts`: very large, stateful, performance-sensitive, and central to user behavior
|
||||
- `src/core/managers/PackageManager.ts`: cross-window package loading and runtime evaluation
|
||||
- `src/core/managers/PackageManager.ts`: shared runtime evaluation, host registration, and cross-window lease/alias lifetime
|
||||
- `src/lang/helpers.ts`: build-token compatibility for compressed locales
|
||||
- AI/provider settings and persisted credentials handling
|
||||
- PDF/export code paths and Electron/Obsidian-specific integrations
|
||||
|
||||
+30
-3
@@ -57,6 +57,14 @@ validated, and what remains uncertain.
|
||||
| Skip duplicate Excalidraw SVG normalization during scene loading | Desktop warm performance validated; ordinary SVG, popout, and mobile remain | The paired component `addFiles` API accepts an optional one-argument object carrying a non-serialized `ReadonlySet<FileId>` of caller-certified SVGs. The plugin derives that set only from embedded files whose source is an Excalidraw drawing. Those generated SVGs skip the component's base64 decode, DOM parse, serialization, and base64 re-encode cycle; legacy array callers and direct/arbitrary SVG files retain normalization |
|
||||
| Investigate post-publication image decode/render latency | Pending; profile before changing behavior | The trusted-SVG bypass reduced synchronous `addFiles()` work from 12.76 seconds to 1.43 seconds, but the measured final batch still had roughly 3.2 seconds between publication and the next animation-frame callback. A future checkpoint should separate browser data-URL decoding, Excalidraw image-cache initialization, React/canvas work, and frame scheduling before selecting a fix; an animation-frame callback alone does not prove a completed paint |
|
||||
| Performance baseline diagnostics (Phase 0) | Complete; instrumentation archived and removed | The runtime captures established the Phase 1A/1B priorities and supplied the acceptance evidence recorded below. The exact final instrumented checkpoint is preserved on the local `performance-refactor-1b-instrumented` branch for the future persistent-main-runtime feasibility spike. All `performanceDiagnostics` imports, counters, console checkpoint hooks, diagnostic-only callback parameters, and the `EXCALIDRAW_PERF_PHASE0` source module have been removed from the delivery branch; the historical findings remain in this plan without shipping temporary observability in the plugin |
|
||||
| Share the main React/Excalidraw runtime with popouts (batch 2 checkpoint 1) | PackageManager simplification complete and lifecycle-validated | `PackageManager` now owns exactly one main-realm React/ReactDOM/Excalidraw package and one pair of typed host registrations. The strategy switch, per-window package map, fallback package, per-window evaluator, decompressed-source retention, and per-window host-disposer maps are gone. View leases still capture the real acquisition window for migration/persistence decisions and reference-count only the popout's temporary `ExcalidrawLib` alias. Custom font metrics register once with the shared runtime, while font styles remain per document. Upstream's stable `ownerDocument` boundary continues to own rendering, listeners, portals, fonts, timers, and realm constructors. This checkpoint deliberately does not change the destructive `onWindowMigrated` lifecycle, persistence handoff, React-root recreation, scene loading, or image transfer behavior |
|
||||
| Define bounded drawing-state handoffs (Phase 1C.1, batch 2) | Implemented; intentionally inert | Added a plugin-owned 15-second, one-shot registry for drawing-owned migration state. Entries are validated by token, leaf, path, and file mtime; a newer registration replaces the prior payload for the same leaf; consumption removes the candidate before validation; and plugin unload clears the sole timer and every retained payload. The contract carries scene/app state, current `BinaryFiles`, explicit `ExcalidrawData` metadata, and a settled save-revision baseline, but cannot retain an `ExcalidrawView`, React root, DOM node, `Window`, listener, or package lease. `ExcalidrawData` and `ViewSaveCoordinator` expose copy/adopt boundaries for the later destination-view checkpoint. No migration path calls these APIs yet, so the validated disk-backed migration lifecycle and image loading remain unchanged |
|
||||
| Adopt drawing-owned state during window migration (Phase 1C.2a, batch 2) | Complete | `onWindowMigrated()` now takes one synchronous pre-unmount scene/app/files snapshot, retains the established dirty-save snapshot and popout-safe serialized persistence handoff, and registers drawing state only after the save is settled and the old view has closed. The replacement view receives a one-shot token through its transient view state, consumes the handoff before a popout→main persistence write can intentionally change file mtime, and adopts scene/app state, current `BinaryFiles`, explicit `ExcalidrawData` metadata, text/compatibility mode, and the settled save revision. The new owner-document-bound React/Excalidraw tree is still recreated. This checkpoint deliberately retains the complete ordinary scene-file loader after initialization as a correctness fallback; skipping or narrowing work for already-transferred files is a separate measured checkpoint. Runtime validation covered dirty migration and durable reopen in both directions, destination interaction/undo, partial and complete MOC EA file transfer, and mid-load cancellation without a freeze, lost edit, fallback, or console error |
|
||||
| Measure post-handoff migration stages (Phase 1C.2b, batch 2) | Complete; diagnostics removed after Phase 1C.2c | Both measured directions showed that source teardown, handoff adoption, library access, destination readiness, and the ordinary scene-file loader complete in milliseconds. Passing all 46 transferred `BinaryFiles` through `initialData.files` instead blocked Excalidraw initialization for approximately 13–15 seconds and starved the zero-delay post-initialize callback for another approximately 4.45 seconds. The ordinary loader then emitted no files and completed in 3.5–24.6 ms. This selected destination image decoding/publication—not handoff validation, disk loading, or hashing—for Phase 1C.2c; the temporary trace was removed after that checkpoint's runtime acceptance |
|
||||
| Publish transferred migration files progressively (Phase 1C.2c, batch 2) | Complete; published dependency installed and runtime-validated | A migrated destination now initializes its owner-document-bound Excalidraw tree with the transferred scene but no initial files, then publishes the exact in-memory `BinaryFiles` in visible-first batches of four through Excalidraw's ordinary `addFiles()` path. A narrow fork API waits only for decoding already started by each batch; the plugin yields two destination frames before the next batch and invokes the disk-backed loader only for image IDs still absent afterward. Trusted transferred SVGs retain the existing normalization bypass. No decoded image, DOM node, `Window`, React object, data-URL cache, or unbounded new cache crosses the handoff. MOC EA now becomes interactive immediately, shows its first image within approximately two seconds, and completes in approximately four seconds main→popout and eight seconds popout→main. Dirty and mid-load transfers retained edits without slowing or destabilizing the load. The final plugin consumes the registry-published `@zsviczian/excalidraw@0.18.128`; temporary local artifact replacement is no longer involved, and all migration timing diagnostics are removed |
|
||||
| Complete upstream cross-document runtime ownership | Fork checkpoint committed; upstream PR #11997 open | The remaining generic gaps after upstream PR #11974 are one cohesive follow-up: empty scenes explicitly load the Welcome UI's Excalifont in the editor document; ordinary and hyperlink tooltips create, position, schedule, and clean up against the trigger/editor document and window; and image decoding constructs `HTMLImageElement`s through the mounted editor window. The existing modal portal already targets `excalidrawContainer.ownerDocument.body` and therefore requires no follow-up change. Fork-only highlighter, context-menu, panning, Obsidian WYSIWYG, and host-adapter paths remain locally fingerprinted rather than being proposed upstream |
|
||||
| Coalesce restored-view stencil-library initialization (batch 2 checkpoint 2) | Complete | Simultaneously restored main and popout views now share one in-flight vault-library load. The loader constructs an isolated item/source snapshot and publishes it atomically only if no vault invalidation occurred while files were being read; an invalidated load is discarded and retried. This preserves the existing plugin-global library cache and persistence behavior while preventing concurrent startup callers from clearing/populating the same map and reporting every item as a duplicate. The maintainer validated restored main/popout startup and library mutation with no new issue |
|
||||
| Make shared-runtime editor instances owner-document-aware (batch 2 spike checkpoint 2) | Accepted upstream and merged into the fork; focused popout behavior validated | Excalidraw now exposes the optional stable `ownerDocument` host prop upstream and derives the owning window from it for editor DOM, listeners, realm constructors, fonts, WYSIWYG, portals, and related browser APIs. The plugin continues to pass each view's actual document through its root. The fuller fork-only spike was preserved in recovery stashes and then removed before merging upstream PR #11974, avoiding permanent fingerprint and merge churn. Conflict resolution retained only existing Obsidian-fork behavior plus five owner-realm conversions on fork-only `App.tsx` lines that upstream could not modify. The maintainer confirmed the shared runtime works well in a popout; the tray-menu tooltip ordering remains a separate pre-existing z-index issue. PackageManager simplification, migration state handoff, MOC EA, and memory work remain separate follow-up checkpoints |
|
||||
| Explicit package/window runtime ownership (Phase 1A.1) | Ownership behavior validated; retained-heap investigation pending | `ExcalidrawView` now acquires an idempotent package lease that captures the package's owning window before any DOM migration. `PackageManager` reference-counts view leases per window, deletes a popout runtime after its final lease is released, and keeps the main startup/fallback runtime pinned. Five measured main↔popout round trips kept `packageWindows` bounded at 1–2 and produced five matching popout package creations/deletions. A two-view popout test then confirmed that the first close retains one lease and a usable sibling while only the final close deletes the runtime. Forced-GC heap nevertheless remained at the Phase 0 failure level, so deleting the map entry is necessary but not sufficient to release the retained runtime graph |
|
||||
| Use explicit window ownership in package and performance diagnostics | Complete | Removed every `globalThis` reference from runtime source. `PackageManager` now compares package windows with the plugin bundle's main `window` directly, matching its existing lease logic; its `setPackage()` parameter was renamed from `window` to `win` to avoid shadowing that owner. Phase 0 diagnostics now read main-window local storage/performance and install the manual checkpoint on a narrowly typed `window`. These are lexical equivalents in the plugin's main bundle realm, preserve plugin-global diagnostic aggregation and main/popout labels, and satisfy Obsidian's popout-safety scanner without hiding the references in Rollup |
|
||||
| Release individually removed Canvas nodes (Phase 1A.2) | Complete | `CanvasNodeFactory.removeNode()` now removes the map entry by its canonical Excalidraw element ID with a node-identity guard, and falls back to an identity lookup for compatibility with callers that omit the ID. Runtime validation confirmed individual removal `7→6`, undo recreation to 7, linear teardown to zero, a zero-node final purge, and complete close lifecycle with no console errors |
|
||||
@@ -73,7 +81,7 @@ validated, and what remains uncertain.
|
||||
| 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 |
|
||||
| In-memory popout migration handoff (Phase 1C) | Reverted and parked | The drawing-state handoff registry and ImageBitmap prototype were removed from the Phase 1A/1B delivery branch. Although state parsing and destination runtime initialization were fast, publishing transferred bitmaps through the newly created destination runtime blocked for roughly 17 seconds and drove heap use to roughly 2.19 GB; repeated MOC EA moves could freeze Obsidian after Electron destroyed the source window. The rejected work remains recoverable in local archival branch/stashes, but no fork API or plugin runtime dependency from that experiment is part of this checkpoint. A future branch should first spike whether one persistent main React object can create fresh roots across main/popout documents while preserving event, portal, observer, and owning-document behavior; only evidence from that spike may justify simplifying or removing `PackageManager`. Begin with small drawings before returning to MOC EA migration or drawing/image state transfer |
|
||||
| Ignore inline suggestion portals in the modal-save observer | Complete | `ObserverManager` now saves a dirty active drawing only when the direct body child added to the active view document is an actual `.modal-container`. The inline link suggester's body-portaled `.suggestion-container` no longer masquerades as Settings or the command palette and cannot trigger synchronization/reload while a text element is being edited. Real modal-open persistence, outside-canvas clicks, file menus, leaf changes, window blur, autosave, and view teardown retain their existing save paths. Runtime validation confirmed that `[[` opened and remained usable after duplicating an equation without changing the save counter, while the next real command-palette modal triggered the intended save and durable reopen restored the complete scene |
|
||||
| Distinguish real modal opens from inline suggestion portals | Complete | `ObserverManager` now saves dirty drawings for real Obsidian modals in both the main workspace and popouts while excluding inline suggestion portals. Popout traces proved the observer was correctly bound to the destination document but the shared `instanceof`-based element guard rejected its mutation nodes. Modal classification now uses a local realm-independent node check, scans every direct body addition and its subtree for `.modal-container`, and retains the observed destination view rather than looking it up again during the callback. Same-leaf replacement initialization rebinds the observer because window migration may not emit `active-leaf-change`. Production observation remains limited to direct body child additions; the temporary subtree/attribute observer and all modal diagnostics were removed after validation |
|
||||
| Stabilize known Excalidraw-file classification across metadata-cache refresh | Complete | Same-tab back navigation can begin loading a parent drawing immediately after its embedded child drawing finishes saving. During that interval Obsidian's metadata cache can temporarily lack the child's frontmatter. `PluginFileManager.isExcalidrawFile()` now treats parsed frontmatter as authoritative when present and otherwise falls back to the manager's existing set of previously confirmed Excalidraw files. Runtime validation reproduced the cache gap, exercised the fallback during both parent parsing and embedded-file loading, and immediately rendered the updated two-circle child correctly. The metadata `changed` event removed the remembered classification after deliberate frontmatter removal; the file then rendered as ordinary Markdown and no further fallback occurred. No vault reread, delay, retry, or navigation behavior was added |
|
||||
| Remaining view phases | Parked | `MarkdownImageController` and `ViewSceneFileManager` are both closed (user-confirmed manual testing, no issues). The Phase 7 React-root extraction (`ExcalidrawRoot.ts`) was never explicitly re-confirmed after its own checkpoint note was written and should be the first thing re-validated if this plan resumes. `ViewInteractionController` (hover preview + pointer/key handling) was explicitly declined by the user for now and remains the last Phase 6 controller candidate if resumed. Phase 8 (converting the extracted React root to TSX) should follow only after the React-root checkpoint is confirmed closed. See "Parked: next steps if resumed" |
|
||||
|
||||
@@ -81,13 +89,32 @@ validated, and what remains uncertain.
|
||||
|
||||
| Date | Action | Outcome | Validation |
|
||||
| --- | --- | --- | --- |
|
||||
| 2026-08-27 | Finalized the published Phase 1C.2c plugin checkpoint | Installed exact dependency `@zsviczian/excalidraw@0.18.128` after the accepted fork branch was merged to the fork's master. The package declarations expose `awaitImageFiles()`, so the plugin's bounded migration publication now rests on its committed internal protocol rather than a locally copied artifact. The dependency and lockfile contain only the expected `0.18.127`→`0.18.128` update | The maintainer ran `npm install`, a production build, and a plugin smoke test successfully. Independent final validation passed the production and library builds, bundle syntax, unused-symbol check, diagnostic-prefix absence, and Madge with no cycle. Scoped ESLint remains exactly at the established 18 `ExcalidrawView` unsafe-type findings and reports no finding in `ViewSceneFileManager` or the new migration code. The lockfile/manifest retain their intentional CRLF format |
|
||||
| 2026-08-27 | Finalized the fork's cross-document delta and opened upstream Excalidraw PR [#11997](https://github.com/excalidraw/excalidraw/pull/11997) | Committed the fork-only, line-fingerprinted tooltip and image-realm completion as `c8fd88729`; the earlier empty-scene font fix remains in `8a6202cae`. Recreated the complete generic delta without fingerprints or Obsidian-only code on a clean branch from merged upstream PR #11974. No modal code changed because its owner-document portal is already correct. The only retained performance opportunity from the discarded handoff notes is to prevent the filtered disk fallback loader from overlapping progressive in-memory publication when every required file is already transferred; decoded `imageCache` transfer remains explicitly rejected because it contains document-owned images and promises | The fork cross-document suite passes 3/3, its Obsidian artifact/declaration build passes, and the plugin production bundle builds against the four refreshed local artifacts. Fork-wide typecheck retains its established unrelated test backlog. On the clean upstream branch, all six touched files pass ESLint, the focused suite passes 2/2, full `yarn test:typecheck` passes, and GitHub reports PR #11997 mergeable with lint, coverage, semantic-title, and Vercel checks passing |
|
||||
| 2026-08-27 | Runtime-accepted and cleaned Phase 1C.2c | MOC EA's migration path is down from the pre-refactor 70–90 seconds to approximately 4–8 seconds. The empty editor appears immediately, the first image appears within approximately two seconds, and dirty or mid-load migration remains responsive and retains edits. Removed every `EXCALIDRAW_MIGRATION_TIMING_DIAG` source and manager hook after acceptance. Separating the plain `BinaryFiles` record from `App` would not improve this further because the exact record already crosses the handoff; the remaining decoded `imageCache` contains DOM-owned `HTMLImageElement` objects/in-flight promises and is cancelled and cleared on unmount. Making that cache transferable would require a new shared lifetime, cancellation, eviction, realm, and memory contract and is deliberately rejected as a non-targeted change | The final trace shows destination React initialization falling from 13–15 seconds to approximately 0.2–0.4 seconds and bounded publication of all 46 transferred files. One direction also started a filtered fallback loader during publication and completed more slowly; this is retained as a future narrow coalescing opportunity, not a reason to broaden the accepted checkpoint. The maintainer explicitly stress-tested edits and migration during loading in both directions without loss or slowdown. Production build, bundle syntax, targeted lint, unused-symbol lint, Madge, and diff checks pass after diagnostic removal |
|
||||
| 2026-08-27 | Implemented Phase 1C.2c progressive in-memory migration-file publication | The replacement editor no longer receives all transferred files in `initialData`, which was the blocking decode point. It paints the scene/runtime first, prioritizes files intersecting the current viewport, and publishes bounded batches without rereading or rebuilding transferred assets. The fork adds only `awaitImageFiles(fileIds)`, an imperative completion boundary over its existing private image-cache promises; it does not expose or transfer the DOM-owned cache. Cancellation checks stop publication when the editor migrates or unloads, and the established loader remains the missing-file/error fallback | The fork's focused cross-document test proves that `awaitImageFiles()` remains pending until decoding started by `addFiles()` completes. That test, targeted ESLint, the Node-22 Obsidian artifact build, the plugin production build against the four locally copied artifacts, bundle syntax, unused-symbol lint, Madge, and `git diff --check` pass. The fork's repository-wide `test:typecheck` remains unusable because of its established test backlog (missing `window.h`, implicit-any fixtures, and related failures outside this change); the focused test is deliberately housed in the currently runnable cross-document suite. Runtime acceptance is one complete MOC EA main→popout→main round trip with one unsaved edit: record loading/UI/first/all-image times in both directions, pan and zoom during progressive loading, verify the edit survives, exercise undo on a second destination edit, reopen for durability, and report the filtered timing trace plus any unfiltered Excalidraw error. A separate rapid-reversal cancellation test follows only if this first comparison passes |
|
||||
| 2026-08-27 | Closed Phase 1C.2b migration-stage measurement | In both directions the destination consumed the 246-element/46-file handoff in under 0.2 seconds and reached `reactRenderRequested` immediately. Excalidraw then took approximately 13.1 and 14.6 seconds to call `onInitialize`; during this interval its API changed from zero to all 46 files. The nominal zero-delay initialization callback was delayed approximately 4.46 and 4.45 seconds more, while the subsequent ordinary loader completed in approximately 3.5 and 24.6 ms without publishing a first batch. This directly attributes the long black loading and empty-editor intervals to all-at-once component image decoding/main-thread starvation | The maintainer's perceived timings matched the trace: 13–15 seconds of **Loading scene**, about 4 seconds of empty UI, then 2–3 seconds until all images appeared, with one direction briefly showing an unstyled editor. The next checkpoint therefore changes only how already-transferred files enter the new editor; it does not alter source capture, persistence, handoff identity, package loading, scene parsing, or normal non-migration loading |
|
||||
| 2026-08-27 | Instrumented Phase 1C.2b migration-stage timing | Added the temporary `EXCALIDRAW_MIGRATION_TIMING_DIAG` trace to distinguish the black loading-view interval from library/readiness work, React initialization, and scene-file publication. The first test is deliberately the known worst complete-file return from a settled MOC EA popout to main; no edits or round trip are needed | Production build and bundle syntax pass on Node 22.22.2 with the established 33 circular warnings. The diagnostic helper and scene-file manager are clean under targeted ESLint; `ExcalidrawView.ts` retains exactly its 18 pre-existing findings. Unused-symbol lint, Madge, and `git diff --check` pass. Runtime acceptance is one popout→main move after all MOC EA images are already visible. Record the approximate loading-text end, empty-editor appearance, first image, and final image times; copy the complete filtered timing trace and report any unfiltered Excalidraw error. This targets the unexplained 15-second pre-editor delay without repeating dirty-save, partial-load cancellation, undo, modal, library, memory, or multi-cycle stress tests |
|
||||
| 2026-08-27 | Runtime-validated and closed Phase 1C.2a drawing-state adoption | The small dirty round trip registered and adopted 13 elements main→popout and 14 elements popout→main; interaction, destination undo, both unsaved edits, and close/reopen durability passed without a freeze or console error. MOC EA migration interrupted the main loader after 2–3 seconds and adopted the 246-element scene plus its 24 currently available binary files in the popout; the retained loader completed the missing files. Returning the fully loaded scene adopted all 46 files in main. Removed the temporary `EXCALIDRAW_MIGRATION_HANDOFF_DIAG` trace after acceptance | Both directions reported registration followed by `found=true` adoption with no fallback. The partial round took roughly 17 seconds total; the complete return still showed approximately 15 seconds of loading view, 5–6 seconds of empty editor, and 3–4 seconds before images appeared. This proves the remaining latency is downstream of handoff validation and includes at least two stages: pre-editor initialization and destination image-cache decoding. The next checkpoint must measure those stages separately; merely reusing the exact `BinaryFiles` record cannot avoid decode work |
|
||||
| 2026-08-26 | Implemented the inert Phase 1C.1 drawing-handoff boundary | Re-established only the safe contract/registry portion of the archived experiment after the single-runtime and upstream `ownerDocument` work succeeded. Kept the existing serialized persistence handoff separate because it is the proven Electron popout-teardown safety path. Deliberately excluded the rejected `ImageBitmap` cache transfer and made no `onWindowMigrated`, view initialization, scene-loader, or package behavior change. The future behavior checkpoint must destroy/recreate the document-bound editor tree because upstream requires `ownerDocument` to remain stable for an editor lifetime; it may transfer drawing state only after identity/freshness and settled-save validation, with ordinary disk loading as fallback | Production, development, and library builds pass on Node 22.22.2 with the established 33 Rollup circular warnings. The new registry and save-coordinator additions are clean under targeted ESLint; `main.ts` and `ExcalidrawData.ts` retain only their unrelated pre-existing findings. Unused-symbol lint, Madge, bundle syntax, and `git diff --check` pass. Madge was installed locally without changing either package manifest or lockfile. No manual runtime test is required because no production caller registers or consumes the new handoff; the next behavior checkpoint requires focused main→popout and popout→main tests before MOC EA stress testing |
|
||||
| 2026-08-26 | Paused modal-observer changes and instrumented the unresolved popout path | Revisited the earlier inline-`[[` fix after an unsaved edit was lost when Restart Obsidian was selected from the command palette. Main-window modal saving and the LaTeX-duplicate `[[` regression both passed, but the popout command palette did not save. Subsequent attempts addressed batched mutation delivery, observing both documents, target-window `MutationObserver` construction, and explicit same-leaf destination-view rebinding. DevTools disproved the main-document placement hypothesis by showing both the command palette and Printable Layout Wizard modal in the popout DOM, and neither popout modal triggered saving after the latest attempt. No further behavioral hypothesis was applied without a trace. Temporary one-string diagnostics recorded view/leaf/document identity, observer lifetime, direct body additions, modal classification, dirty/unload/API guards, and save request/completion without filenames or scene data | The instrumented production build passed with the established circular-warning baseline; bundle syntax, scoped diagnostic-file ESLint, and `git diff --check` passed. Diagnostic reproduction used one small drawing without restarting Obsidian: main-window control followed by popout Printable Layout Wizard and command-palette attempts. The trace isolated the realm boundary recorded in the following action-log entry; all temporary diagnostics were later removed |
|
||||
| 2026-08-26 | Isolated, fixed, and validated popout modal-node classification | The current-build trace bound generation 1 to the live popout document/view and received the modal's direct body insertion with `dirty=1`, `unload=0`, and `api=1`. The same callback contained an attribute mutation but reported no element target, and the added node was reduced to bare `div`; the cross-window element guard was therefore the boundary suppressing `.modal-container` matching. Replaced it only in this observer with a realm-independent element-node check. The observer scans every direct body addition and its current subtree for `.modal-container`, so Obsidian modals/command palette qualify while the inline suggestion portal does not. Removed the temporary `subtree`/`attributes` observation that generated an 898-record callback, then removed all diagnostic logging after acceptance | Production build passes on Node 22.22.2 with the established 33 circular warnings. The maintainer confirmed real modal saves in both main and popout documents. The popout command palette (`.modal-container.mod-dim`) and Printable Layout Wizard (`.modal-container`) each produced one successful save; the Excalidraw tray and inline `[[` suggester did not save, and the suggester remained usable. Targeted lint, unused-symbol lint, bundle syntax, diagnostic-prefix absence, and `git diff --check` pass after cleanup |
|
||||
| 2026-08-26 | Coalesced concurrent stencil-library initialization during workspace restore | Traced the library host-adapter calls to the single plugin-owned `StencilLibraryManager`. Two views restored together could both observe `loaded=false`, enter `loadFromVault()`, and mutate the same `itemSource` map across awaited vault reads; sequential opens avoided the race. Added one shared in-flight promise and revision-checked snapshot publication. `invalidate()` now rejects an obsolete in-flight result, whose callers retry against current vault state. Persistence remains serialized by the existing save queue, and no runtime/package ownership changed | Production and library builds pass on Node 22.22.2; bundle syntax, scoped ESLint, unused-symbol lint, and `git diff --check` pass. No dependency/import graph changed, so the already-clean Madge result from the immediately preceding PackageManager checkpoint remains applicable. The maintainer confirmed restored main/popout startup, complete library contents, and the add/remove mutation safeguard with no new issue. No migration, MOC EA, memory, save, export, mobile, or broad performance rerun was required |
|
||||
| 2026-08-26 | Permanently simplified PackageManager around the validated single runtime | Removed the feature switch and all code capable of evaluating React/Excalidraw in a popout. Replaced package and adapter-disposer maps with one runtime package and one disposer per typed host boundary. Kept only per-window lease counts and alias ownership because those represent view lifecycle, not runtime evaluation. The decompressed React and Excalidraw source strings and outer JSX-runtime references are released immediately after the one successful evaluation. `FontManager` now registers local metrics once against that runtime but continues injecting font styles into every open document. Updated `AGENTS.md` so future work preserves the distinction between shared runtime ownership and per-view document/window ownership | Production, development, and library builds pass against the locally built fork artifact with the established circular-warning baseline; bundle syntax and both worktree diff checks pass. Scoped lint reports zero findings in the changed manager/type/root files; full-source unused-symbol lint reports none. A temporary unsaved Madge 8 install processed the repository's configured roots with no circular dependency, then a normal Node 22 `npm install` restored the locked dependency tree; no audit fix was run and package manifests/lockfile are unchanged. The maintainer's two-view alias-lifetime, dirty bidirectional migration, plugin-reload cleanup, and popout local-font tests all passed without new issues. Concurrent startup exposed a separately scoped pre-existing stencil-library load race, recorded for the next checkpoint |
|
||||
| 2026-08-26 | Added the empty-scene popout font checkpoint and completed the fork-only realm audit | A fresh editor had no scene font families, so the accepted owner-document path registered font faces in the correct document but never explicitly loaded Excalifont for the Welcome UI. The fork now adds Excalifont with a representative Latin glyph set only when the scene is empty. The accepted cross-document test forces the font-load path and proves it targets the supplied document. The post-merge fork delta audit also routed two fork-only delayed callbacks and the keyboard context menu's synthetic `MouseEvent` through `ownerWindow`. The generic follow-up findings were later consolidated into upstream PR #11997; fork-only paths remain locally fingerprinted | Focused common/cross-document tests pass (12 tests), targeted fork ESLint reports zero errors, and the fork Obsidian artifact/declaration build passes under explicit Node 22.22.2/Corepack Yarn. After copying only the four generated local artifacts, plugin development and production builds pass with the established circular-warning baseline. The maintainer confirmed that a fresh blank drawing opened directly in a popout renders the Welcome text in Excalifont and that the focused context-menu/owner-realm regression check passes |
|
||||
| 2026-08-26 | Replaced the fork-only owner-document spike with accepted upstream Excalidraw PR #11974 | Stashed the superseded uncommitted spike, fetched upstream, and merged the two missing upstream commits into `performance-refactor-batch2` as fork merge commit `76647ecd8`. Resolved the four conflicts by taking upstream's public owner-document boundary while preserving existing fork behavior in embeds, fonts, WYSIWYG link suggestions, shape-action handling, cleanup, and Obsidian-specific canvas interactions. Added a concise `AGENTS.md` invariant requiring future browser/DOM additions to derive their document/window from the mounted editor. Auditing the fork-only `App.tsx` delta found and corrected five ownership gaps outside upstream's source: highlighter pixel ratio, the migration document query, active-element lookup, context-menu suppression, and right-click panning listeners. The earlier stashes remain recovery-only and should not be reapplied | The accepted cross-document test and common utility suite pass (12 tests). Targeted fork ESLint reports zero errors; `build:obsidian` and declaration generation pass under explicit Node 22.22.2/Corepack Yarn. Full fork typecheck retains its established disabled-`createTestHook` test backlog and reports no production build failure. After copying only the four generated local artifacts, plugin production and development builds pass with the existing circular-warning baseline. Plugin source lint remains at its established 138-error backlog |
|
||||
| 2026-08-26 | Tightened fork fingerprinting, established a maintained fork test gate, and closed two remaining shared-runtime owner-document gaps | Replaced broad owner-document banners around existing upstream functions with line-local `// zsviczian -- reason` fingerprints; retained `START`/`END` only for cohesive fork-added units such as the host prop, owner-realm getter, DOM-realm helper, and empty-scene UI-font preload. Moved cross-realm utility coverage out of the upstream-owned `utils.test.ts` into clearly named fork-owned test files and added the explicit `yarn test:obsidian` command. `AGENTS.md` now requires line-local conflict fingerprints, restoration of formatter-only churn, a dedicated compatibility commit, a word-diff review, and the maintained fork gate during upstream merges. Empty scenes explicitly load Excalifont into the mounted editor's `FontFaceSet`; generic modal portal creation, dialog focus, and dialog timers now derive from the editor container's document/window, so reset and text-to-diagram dialogs no longer target the main document behind a popout. The hamburger/tray tooltip layering observation remains separately scoped because it is an existing z-index issue, not a document-ownership failure | `yarn test:obsidian` passes all 6 maintained files and 23 tests, including target-realm DOM guards, pointer/keyboard/clipboard/window-message/font listener ownership, explicit empty-scene Excalifont loading, tooltip placement, Radix portal behavior, and generic portal-container ownership. Targeted ESLint with `--quiet` reports zero errors. The fork Obsidian artifact and declaration build passes under explicit Node 22/Corepack Yarn; the four generated artifacts were refreshed locally and both plugin production and development builds pass with the established circular-warning baseline. Full fork `yarn test:typecheck` retains the documented historical test backlog and reports no changed-file diagnostic. Both worktree diff checks pass; focused manual popout validation remains required |
|
||||
| 2026-08-26 | Extracted the shared-runtime owner-document boundary into a minimal upstream Excalidraw proposal | Preserved the working customized-fork spike unchanged, created `support-owner-document-runtime` from current `excalidraw/excalidraw` master in an isolated worktree, and reduced the proposal to the generic public `ownerDocument` contract plus the core input/listener, cross-realm element guard, font, and WYSIWYG paths needed to render a fresh editor root in another browsing context. The prop defaults to the runtime document and must remain stable for the mounted editor's lifetime. Unrelated Obsidian adapters, package management, migration logic, tooltip/portal cleanup, and fork-only formatting are absent. Commit `11261d7b7` is pushed to `zsviczian/excalidraw:support-owner-document-runtime`; upstream PR [#11974](https://github.com/excalidraw/excalidraw/pull/11974) is open for review | With dependencies installed from current upstream's own frozen lockfile under Node 22.22.2/Yarn 1.22.22, all 123 test files passed (1,862 passed, 47 skipped, 1 todo). The new iframe test verifies that pointer, keyboard, clipboard, window-message, and font listeners bind to the supplied document/window; common utility tests verify cross-realm input/writable/interactive/tool guards and scroll-container ownership. `yarn test:typecheck`, targeted ESLint with zero findings, `yarn build:excalidraw`, and `git diff --check` pass. The maintainer's focused Obsidian test of the fuller reference spike reported the shared-runtime popout behavior works well |
|
||||
| 2026-08-26 | Added the explicit owner-document boundary required by the shared-runtime spike | The paired fork now accepts an optional per-instance `ownerDocument`; `App` derives its owner window and routes the input/history/clipboard/pointer listener lifecycle, DOM creation/lookups, cross-realm constructors, resize observer, pixel ratio, tooltip, and teardown through it. Font registration/loading and the text WYSIWYG's textarea, caret-measurement nodes, listeners, constructors, resize observer, and animation frame now belong to that document. Shared common input guards resolve constructors from the target's owner window, and scroll-container lookup returns the owning document. The plugin passes `view.ownerDocument` through its existing React root using a temporary widened local component type until the paired package is published. No migration/save/image/state-handoff logic changed | The fork Obsidian artifact/declaration build passes under explicit Node 22.22.2/Corepack Yarn 1.22.22. A new JSDOM iframe test proves input/writable/interactive/tool guards and scroll-container lookup accept nodes whose constructors differ from the main realm; all 11 focused utility tests pass. Only the four generated Obsidian artifacts were copied into the installed plugin package. The plugin production build passes with the established 33 circular warnings; bundle syntax, targeted plugin lint, unused-symbol lint, and both repositories' diff checks pass. Focused manual revalidation is required before expanding scope |
|
||||
| 2026-08-26 | Minimized and fingerprinted the fork-only owner-document fallback | Removed formatter-only churn from the working fork spike while preserving all owner-realm behavior, reducing `App.tsx` from 590 to 253 changed lines and the original nine tracked source/test files from 921 to 565 changed lines after adding the required fingerprints; the new standalone regression test is 142 lines. Added cross-document coverage for listener/font ownership and tooltip placement, plus an `AGENTS.md` upstream-merge audit that requires reviewing new `document`, `window`, constructor, observer, timer, and listener usages against the stable per-instance owner realm. The complete pre-cleanup spike remains recoverable in the named fork stash `owner-document spike before minimal fingerprint pass` | The two focused test files pass (13 tests); `yarn build:obsidian` and its declaration generation pass under explicit Node 22; plugin production and development builds pass against the four refreshed local artifacts (`dist/main.js` production size 4,828,452 bytes). Repository-wide `yarn test:typecheck` and `yarn test:update` retain unrelated fork-baseline failures (`window.h` typing and missing `createTestHook` export); the latter's two generated snapshot-file edits were removed. No changed production source remains in the typecheck diagnostics, and `git diff --check` passes |
|
||||
| 2026-08-26 | Started the batch-2 persistent-main-runtime feasibility spike | `PackageManager.getPackage()` now returns the already-evaluated main-window React/ReactDOM/Excalidraw package for a popout while preserving the popout as the lease's acquisition/migration window. It installs only a temporary `window.ExcalidrawLib` compatibility alias in the popout, removes that alias on the final popout lease, and leaves package-map and typed-host registration ownership with the single evaluated main runtime. The former per-window evaluation path remains intact behind one spike constant for immediate comparison or rollback. No fork source, root migration, save, scene/image loading, or drawing-state handoff changed. Static fork review found extensive lexical `window`/`document` use in `App.tsx`; therefore this checkpoint is only a feasibility probe, not evidence that PackageManager can yet be simplified | Node 22.22.2 production and library builds passed with the established 33 Rollup circular warnings; bundle syntax, targeted PackageManager/type lint, unused-symbol lint, `git diff --check`, and the repository Madge script passed. Full source lint remains exactly at the established 138-error/0-warning backlog, with no finding in either changed source/type file. Madge 8 was installed temporarily without saving it, the structural check processed its usual 8 roots with no cycle, and `npm install` restored the exact manifest dependency tree afterward; no audit fix was run and package manifests/lockfile are unchanged. The first small-drawing gate confirmed shared rendering and the owner-document Radix color picker, while pointer drawing and Cmd+Z failed and the active text editor used a fallback font until submission. Those failures match the audited lexical main-document listeners, cross-realm constructor checks, main-document WYSIWYG creation, and main-document font loading; the test correctly stopped before dirty migration, MOC EA, or memory work |
|
||||
| 2026-08-25 | Fenced progressive image loading across rapid runtime teardown | A stress test moved MOC EA repeatedly without waiting for image completion and preserved every edit, but once exposed `updateImageCache()` resuming after unmount and reading the fork's nulled store. The view now clears the zero-delay initialization timer before migration/close/unload; all immediate, deferred, queued, and retry scene-file paths reject a migrating/unloaded view, a replaced/destroyed API, or a changed file; and the shared publication helper rechecks the same boundary immediately before `api.addFiles()`. Because `addFiles()` starts component-owned asynchronous decoding and returns `void`, the fork also returns an empty result if decoding resumes after `componentWillUnmount()`. Waiting for decode before unmount was rejected because it violates the proven Electron freeze invariant | The paired fork `build:obsidian` passed under a deterministic Node 22.22.2/Yarn 1.22.22 PATH. Its repository-wide typecheck retained the existing test-typing backlog and reported no error in `App.tsx`. The maintainer repeated rapid MOC EA migrations several times, editing before image completion; all edits survived and the `scheduleAction` rejection could not be reproduced. Fork `0.18.127` was then published and installed as the plugin's exact dependency; its production and development artifacts hash-identically match the local runtime used for manual acceptance. The published-artifact plugin production/library builds, unused-symbol lint, bundle syntax, scoped manager lint, and source/documentation diff checks passed; package manifests retain the repository's existing CRLF endings. Full lint remains at the established 138-error/0-warning backlog, and `ExcalidrawView.ts` retains its same 18 pre-existing unsafe-type findings. No further stress loop, memory run, SYL, export, backup, missing-file, mobile, or PDF Plus test is required |
|
||||
| 2026-08-25 | Fenced null-API callbacks on the retired migration source | Moving the source React unmount before the first await eliminated the reproducible Electron freeze in both dirty popout→main and dirty main→popout tests, with edits preserved. The console then exposed two deterministic cleanup races: an already-started blur save reached autoexport after unmount, and the handoff's destination write caused `FileManager` to synchronize the still-discoverable retired source. Autoexport/dialog creation, blur post-save side effects, modify-event dispatch, and `synchronizeWithData()` now all reject a window-migrating/null-API source while leaving the replacement destination eligible. The crash invariant is also recorded in `AGENTS.md` and adjacent TSDoc so future lifecycle changes do not move unmount behind an asynchronous boundary | The final console-focused dirty round trip passed in both directions: no freeze, both edits persisted through close/reopen, destination interaction remained usable, and the `ExcalidrawView.save`/`synchronizeWithData` errors were gone. Existing PDF Plus errors were confirmed unrelated and remain out of scope |
|
||||
| 2026-08-25 | Moved migration React teardown ahead of all asynchronous save work | Debugger tracing established that dirty migration invoked `forceSaveIfRequired()` three times (migration callback, `onClose()`, then `onUnloadFile()`) and that the reproducible freeze began specifically at `excalidrawRoot.unmount()`. Moving unmount outside `closeLeafView()` still froze, disproving reentrancy as the root cause and isolating the unsafe interval to the awaited synchronization/compression before teardown. The migration callback now synchronously captures one coherent save snapshot, unmounts immediately, and performs its sole flush from captured drawing-owned data; `onClose()`/`onUnloadFile()` retain only non-save cleanup for that migration. All non-migration lifecycle paths keep their original save-before-unmount behavior | Static/build validation precedes one risk-limited dirty popout→main rerun. Acceptance requires exactly the previously failing workflow: the destination appears without a freeze, the unique edit is immediately present and survives close/reopen, and no new Excalidraw console error appears. Stop after the first attempt if Obsidian still freezes |
|
||||
| 2026-08-25 | Removed native file access from dirty popout→main teardown | The diagnostic-free smoke test first lost the popout edit and froze twice. Marking migration earlier and awaiting a main-realm Vault write made the edit durable but still froze twice, proving that any native write initiated by the old popout migration callback is unsafe. The source now performs serialization only and registers a bounded serialized-text handoff; after the old view closes, the replacement main view consumes and persists it before parsing. Main→popout keeps the simpler direct persistence path because the source main realm is not recycled | Production build, library build, unused-symbol lint, bundle syntax, scoped lint, and diff checking precede one focused rerun of the exact failing popout→main dirty migration. Acceptance requires no freeze, the edit to survive destination load and close/reopen, and no new Excalidraw console error. Also make one dirty main→popout move to confirm its already-working direction remains intact. No repeated cycles, memory, SYL, backup, export, missing-file, or mobile test is required |
|
||||
| 2026-08-25 | Removed temporary Phase 0 diagnostics from the delivery branch | Preserved the exact validated source and instrumentation on local branch `performance-refactor-1b-instrumented`, then removed diagnostic imports, events, counters, timing callbacks, reason-only parameters, and the manual console checkpoint from production source. The backup queue, save coordinator, package leases, loader termination, Canvas-node removal, save indexes/snapshot, classification fallback, modal observer fix, and progressive image batching remain intact. Removed the locally installed Madge dependency and generated lockfile churn from the PR while keeping master’s existing script entry and the independent repository-zip script requested for delivery. `PERFORMANCE_REFACTOR_HANDOFF/` remains untracked and excluded | Production and library builds, unused-symbol lint, targeted lint, bundle syntax, diagnostic-prefix search, and scoped diff checking passed. Full lint remains exactly at its established 138-error/0-warning backlog, and the diagnostic-free production bundle is 4,821,700 bytes. The final risk-based runtime smoke test is one MOC EA main→popout→main round trip with one edit, close/reopen durability, progressive image completion, and no freeze or new console error; repeated migration, memory, SYL, backup, export, missing-file, and mobile retests are not required for this cleanup |
|
||||
| 2026-08-25 | Removed temporary Phase 0 diagnostics from the delivery branch | Preserved the exact validated source and instrumentation on local branch `performance-refactor-1b-instrumented`, then removed diagnostic imports, events, counters, timing callbacks, reason-only parameters, and the manual console checkpoint from production source. The backup queue, save coordinator, package leases, loader termination, Canvas-node removal, save indexes/snapshot, classification fallback, modal observer fix, and progressive image batching remain intact. Removed the locally installed Madge dependency and generated lockfile churn from the PR while keeping master’s existing script entry and the independent repository-zip script requested for delivery. The untracked handoff folder was removed at the end of batch 2 after its durable decisions and sole remaining optimization opportunity were consolidated into this plan | Production and library builds, unused-symbol lint, targeted lint, bundle syntax, diagnostic-prefix search, and scoped diff checking passed. Full lint remains exactly at its established 138-error/0-warning backlog, and the diagnostic-free production bundle is 4,821,700 bytes. The final risk-based runtime smoke test is one MOC EA main→popout→main round trip with one edit, close/reopen durability, progressive image completion, and no freeze or new console error; repeated migration, memory, SYL, backup, export, missing-file, and mobile retests are not required for this cleanup |
|
||||
| 2026-08-25 | Restored bounded progressive image presentation and closed the pre-PR checkpoint | Live-view loads sort embedded-file work toward the image IDs intersecting the initial viewport, publish no more than eight files per batch, and wait for an owning-window paint opportunity before draining another immediately available batch. A 250 ms fallback prevents a hidden or destroyed window from holding loader completion. Non-view consumers do not opt in. The MOC EA viewport contained all 46 image IDs, so ordering did not distinguish them in this scene; bounded publication itself supplied the visible progress | Both MOC EA runs completed all 46 files in seven batches with `terminalState=completed`, scheduled background validation, emitted no changed files, and reported no errors. The startup-contention run took 9.16 seconds and first displayed an image at about four seconds; after settling, the first image appeared at about one second and completion took about eight seconds (diagnostic loader duration 9.84 seconds). The maximum synchronous batch fell from the earlier 37-file/628 ms publication to 346 ms, but total publication work increased and panning remained choppy. Cached SVG materialization, not hashing or save synchronization, is the remaining dominant interaction risk and stays parked until after the migration architecture decision |
|
||||
| 2026-08-25 | Reverted the Phase 1C migration prototype before preparing the Phase 1A/1B PR | Preserved committed 1C.1/1C.2 on the original `performance-refactor` branch, stashed the rejected plugin 1C.3 bitmap handoff and all sibling-fork bitmap changes under explicit names, and created the delivery branch at the validated end of Phase 1B. The sibling fork source is clean and master-equivalent, and its clean Obsidian artifact replaced the experimental local runtime. The handoff folder remains untracked and outside the delivery | This avoids carrying the prototype's 17-second destination `addFiles()` pause, approximately 2.19 GB heap peak, and source-window teardown freezes into the PR. The Phase 1A/1B commits and independent repository-zip script remain in history. Future work should begin on a separate branch with the persistent-main-runtime feasibility spike documented above |
|
||||
| 2026-08-25 | Reverted the Phase 1C migration prototype before preparing the Phase 1A/1B PR | Preserved committed 1C.1/1C.2 on the original `performance-refactor` branch, stashed the rejected plugin 1C.3 bitmap handoff and all sibling-fork bitmap changes under explicit names, and created the delivery branch at the validated end of Phase 1B. The sibling fork source was clean and master-equivalent, and its clean Obsidian artifact replaced the experimental local runtime. The handoff folder remained untracked and outside that delivery; it was removed after batch 2 was accepted and its durable conclusions were consolidated here | This avoided carrying the prototype's 17-second destination `addFiles()` pause, approximately 2.19 GB heap peak, and source-window teardown freezes into the PR. The Phase 1A/1B commits and independent repository-zip script remain in history. Future work resumed with the persistent-main-runtime feasibility spike documented above |
|
||||
| 2026-08-25 | Runtime-validated and closed Phase 1B.4b | SYL's asynchronous compression provided repeated in-flight edit windows. Each completed save advanced only its owned revision: when newer edits existed, diagnostics retained `dirty=1` and immediately consumed the single merged pending request. Continued drawing overlapped several successive 0.69–1.42 second saves, so the run produced nine trailing-queue updates and seven trailing executions rather than the single execution expected from three quick edits; this is correct one-active/one-pending behavior across multiple save generations, not an unbounded concurrent queue. Once editing stopped, revision 28 completed with `currentRevision=28`, `savedRevision=28`, and `dirty=0`. No request used the former `save.skipped reason=save-in-flight` path | The forced-save path waited through its trailing work before completing and its scene-file loaders reached `terminalState=completed`. Immediate close scheduled the established delayed view-unload write for revision 31; the same-revision overlapping request was recognized as satisfied, Canvas nodes were removed, and the reopened view accepted the delayed write update from 3,670 to 3,671 elements. The final checkpoint reports 14 actual saves, 13 completed backup writes before the checkpoint, one harmless same-revision coalescing event, and no failure/stall/timeout marker. No regression was reported while exercising the `[[` suggester and durable reopen workflow. No additional popout, MOC EA, memory, export, backup, or mobile test is required for this checkpoint |
|
||||
| 2026-08-25 | Implemented Phase 1B.4b revision tracking, bounded trailing saves, and teardown flush | Traced the old dirty boolean against every save completion/early return, `clearDirty()` load/reload path, durable Excalidraw increment, external synchronization semaphore, autosave timer, force-save busy policy, and unload/migration sequence. Durable increments provide the precise low-overhead edit boundary, including changes made after a save snapshot while compression is asynchronous; no new full-scene hashing was introduced. Requests execute through one promise loop, merge into one latest trailing request while preserving forced-save priority and autoexport requirements, and carry explicit terminal results so failed/skipped work cannot advance the saved revision. Save-triggered `loadDrawing()` cannot clear the active revision. Close/navigation waits for the loop, then persists only if a newer revision remains. The pre-existing 200 ms Electron popout-unload write workaround is retained | Production build passes with the unchanged 33 Rollup circular warnings. The new coordinator remains clean under targeted ESLint; `ExcalidrawView.ts` retains its exact 18 pre-existing unsafe-type findings, and full lint remains exactly 138 errors/0 warnings. `npm run code:unused`, `npm run madge`, bundle syntax, and `git diff --check` pass. The diagnostic bundle is 4,848,203 bytes, 4,433 bytes above Phase 1B.4a and 394,677 bytes below 5 MiB. Runtime acceptance uses SYL only to provide a reliable compression window: start one manual save, create another durable element while compression is active, and require `saveCoordinator.trailingQueued` followed by exactly one `saveCoordinator.trailingStart`; the first completion must remain dirty with `currentRevision>savedRevision`, the trailing completion must equalize revisions and clear dirty, and no `save.skipped reason=save-in-flight` may occur. Add one final element and immediately close/reopen to validate `flush()` durability. As a targeted text-edit regression, type `[[` once and confirm the suggester remains open without a save interrupting active text. No MOC EA, image-loader, backup, export-output, repeated migration, memory, mobile, or broad performance rerun is required |
|
||||
| 2026-08-25 | Runtime-validated and closed Phase 1B.4a | The disposable drawing produced an ordinary autosave with `reason=direct force=0 autosaving=1`, a manual titlebar force-save with `refreshSceneFiles=1`, and a window-blur force-save with `refreshSceneFiles=0`. Both migration directions rebuilt the appropriate window runtime; returning to main serialized the dirty four-element scene through the established `save.viewUnloadScheduled` path, deleted the abandoned popout package, and then accepted the delayed disk update. Final unsaved close serialized five elements through the same teardown path, and reopen parsed all five. All five scene-file loaders reached `terminalState=completed` | Public routing, timer ownership, force-save policy, teardown persistence, package ownership, and durable reopen all meet acceptance. One non-forced direct request arrived 8.4 ms after the final forced teardown save began and recorded `save.skipped reason=save-in-flight`; the winning save snapshot already contained the same five elements and reopened durably. This is the preserved pre-coordinator behavior and supplies a focused baseline for Phase 1B.4b trailing coalescing rather than blocking the mechanical checkpoint. The filtered trace contains no failure, stalled-loader, or timeout marker |
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.27.0-beta.5",
|
||||
"version": "2.27.0-beta.6",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+4
-4
@@ -13,7 +13,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.127",
|
||||
"@zsviczian/excalidraw": "0.18.128",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -5255,9 +5255,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/excalidraw": {
|
||||
"version": "0.18.127",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.127.tgz",
|
||||
"integrity": "sha512-iy7XIt5ZYWqA0bQ7Ah+POHtgHNypu2BmiXptFMRgVw62tcDQI+Ou1P7cep2AsbYPYKrj01MJ5AC2CU31dGxaEA==",
|
||||
"version": "0.18.128",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.128.tgz",
|
||||
"integrity": "sha512-qpFAx1mTDoHSWqWbRSDd4wXgejKMZewT1cD0Tn+xMnoVMLedFPpApl19GbubxT3/LN4BTqlQASgUX1IdtO7byA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@braintree/sanitize-url": "6.0.2",
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.127",
|
||||
"@zsviczian/excalidraw": "0.18.128",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
|
||||
+26
-3
@@ -116,6 +116,12 @@ import {
|
||||
ViewMigrationPersistenceHandoffManager,
|
||||
type ViewMigrationPersistenceHandoff,
|
||||
} from "./managers/ViewMigrationPersistenceHandoffManager";
|
||||
import {
|
||||
ViewMigrationHandoffManager,
|
||||
type ViewMigrationDrawingState,
|
||||
type ViewMigrationHandoffRegistration,
|
||||
type ViewMigrationHandoffRequest,
|
||||
} from "./managers/ViewMigrationHandoffManager";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
declare const INITIAL_TIMESTAMP: number;
|
||||
@@ -162,6 +168,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
private footerSafeAreaManager: FooterSafeAreaManager;
|
||||
private fontManager: FontManager;
|
||||
private startupTimer: StartupTimer;
|
||||
private viewMigrationHandoffManager: ViewMigrationHandoffManager;
|
||||
private viewMigrationPersistenceHandoffManager: ViewMigrationPersistenceHandoffManager;
|
||||
public stencilLibraryManager: StencilLibraryManager;
|
||||
public eaInstances = new WeakArray<ExcalidrawAutomate>();
|
||||
@@ -206,6 +213,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
super(app, manifest);
|
||||
this.loadTimestamp = INITIAL_TIMESTAMP;
|
||||
this.startupTimer = new StartupTimer(this.loadTimestamp, PLUGIN_VERSION);
|
||||
this.viewMigrationHandoffManager = new ViewMigrationHandoffManager();
|
||||
this.viewMigrationPersistenceHandoffManager =
|
||||
new ViewMigrationPersistenceHandoffManager();
|
||||
this.filesMaster = new Map<
|
||||
@@ -228,7 +236,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.settingsManager = new PluginSettingsManager(this);
|
||||
this.footerSafeAreaManager = new FooterSafeAreaManager(this);
|
||||
this.fontManager = new FontManager(this, () =>
|
||||
this.packageManager.getPackageMap(),
|
||||
this.packageManager.getRuntimePackage(),
|
||||
);
|
||||
|
||||
setExcalidrawPlugin(this);
|
||||
@@ -984,6 +992,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
//PLUGIN_VERSION = null;
|
||||
delete window.PolyBool;
|
||||
this.packageManager.destroy();
|
||||
this.viewMigrationHandoffManager.destroy();
|
||||
this.viewMigrationPersistenceHandoffManager.destroy();
|
||||
this.commandManager?.destroy();
|
||||
this.eventManager.destroy();
|
||||
@@ -1232,8 +1241,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.observerManager.removeThemeObserver();
|
||||
}
|
||||
|
||||
public addModalContainerObserver() {
|
||||
this.observerManager.addModalContainerObserver();
|
||||
public addModalContainerObserver(view?: ExcalidrawView) {
|
||||
this.observerManager.addModalContainerObserver(view);
|
||||
}
|
||||
|
||||
public removeModalContainerObserver() {
|
||||
@@ -1257,6 +1266,20 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.packageManager.deletePackage(win);
|
||||
}
|
||||
|
||||
/** Registers drawing-owned runtime state for one recreated view. */
|
||||
public registerViewMigrationHandoff(
|
||||
registration: ViewMigrationHandoffRegistration,
|
||||
): string {
|
||||
return this.viewMigrationHandoffManager.register(registration);
|
||||
}
|
||||
|
||||
/** Consumes validated drawing-owned runtime state for one recreated view. */
|
||||
public consumeViewMigrationHandoff(
|
||||
request: ViewMigrationHandoffRequest,
|
||||
): ViewMigrationDrawingState | null {
|
||||
return this.viewMigrationHandoffManager.consume(request);
|
||||
}
|
||||
|
||||
/** Registers serialized drawing text for a popout-to-main migration. */
|
||||
public registerViewMigrationPersistenceHandoff(
|
||||
handoff: ViewMigrationPersistenceHandoff,
|
||||
|
||||
@@ -349,7 +349,7 @@ export class EventManager {
|
||||
this.previouslyActiveLeaf = leaf;
|
||||
|
||||
if (newActiveviewEV) {
|
||||
this.plugin.addModalContainerObserver();
|
||||
this.plugin.addModalContainerObserver(newActiveviewEV);
|
||||
this.plugin.lastActiveExcalidrawFilePath = newActiveviewEV.file?.path;
|
||||
} else {
|
||||
this.plugin.removeModalContainerObserver();
|
||||
|
||||
@@ -17,7 +17,7 @@ declare const deliberateCreateElement: (
|
||||
tagName: string,
|
||||
) => HTMLStyleElement;
|
||||
|
||||
type PackageMapProvider = () => Map<Window, Packages>;
|
||||
type RuntimePackageProvider = () => Packages;
|
||||
|
||||
/**
|
||||
* Owns CJK and custom-font discovery, registration, document stylesheets, and
|
||||
@@ -30,7 +30,7 @@ export class FontManager {
|
||||
|
||||
public constructor(
|
||||
private readonly plugin: ExcalidrawPlugin,
|
||||
private readonly getPackageMap: PackageMapProvider,
|
||||
private readonly getRuntimePackage: RuntimePackageProvider,
|
||||
) {}
|
||||
|
||||
/** Whether font initialization permits the plugin readiness wait to finish. */
|
||||
@@ -76,7 +76,7 @@ export class FontManager {
|
||||
|
||||
/**
|
||||
* Loads configured CJK and custom fonts into every open Obsidian document
|
||||
* and registers custom font metrics with each window-scoped Excalidraw package.
|
||||
* and registers custom font metrics with the shared Excalidraw runtime.
|
||||
*/
|
||||
public async initializeFonts(): Promise<void> {
|
||||
const cjkFontDataURLs = await getCJKDataURLs(this.plugin);
|
||||
@@ -128,15 +128,13 @@ export class FontManager {
|
||||
lineHeight: 1.2,
|
||||
};
|
||||
}
|
||||
this.getPackageMap().forEach(({ excalidrawLib }) => {
|
||||
if (!fontMetrics) {
|
||||
return;
|
||||
}
|
||||
const { excalidrawLib } = this.getRuntimePackage();
|
||||
if (fontMetrics) {
|
||||
excalidrawLib.registerLocalFont(
|
||||
{ metrics: fontMetrics },
|
||||
fourthFontDataURL,
|
||||
);
|
||||
});
|
||||
}
|
||||
for (const ownerDocument of this.getOpenObsidianDocuments()) {
|
||||
await this.addFonts(
|
||||
[
|
||||
|
||||
@@ -12,14 +12,30 @@ import {
|
||||
isInstanceOfDocumentFragment,
|
||||
isInstanceOfElement,
|
||||
} from "src/utils/typechecks";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
const MODAL_CONTAINER_SELECTOR = ".modal-container";
|
||||
|
||||
/**
|
||||
* Checks an observed DOM node without relying on cross-window constructors.
|
||||
*
|
||||
* Mutation records can contain nodes from an Obsidian popout realm whose
|
||||
* `instanceof Element` identity is not reliable after window migration.
|
||||
*/
|
||||
const isObservedElement = (node: Node): node is Element =>
|
||||
node.nodeType === 1 && typeof (node as Element).matches === "function";
|
||||
|
||||
export class ObserverManager {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private app: App;
|
||||
private themeObserver: MutationObserver | CustomMutationObserver;
|
||||
private fileExplorerObserver: MutationObserver | CustomMutationObserver;
|
||||
private modalContainerObserver: MutationObserver | CustomMutationObserver;
|
||||
private modalContainerObserver:
|
||||
| MutationObserver
|
||||
| CustomMutationObserver
|
||||
| null = null;
|
||||
private modalObservedView: ExcalidrawView | null = null;
|
||||
private workspaceDrawerLeftObserver:
|
||||
| MutationObserver
|
||||
| CustomMutationObserver;
|
||||
@@ -267,16 +283,19 @@ export class ObserverManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Monitors if the user clicks outside the Excalidraw view, and saves the drawing if it's dirty
|
||||
* @returns
|
||||
* Saves a dirty drawing when an Obsidian modal opens in its live document.
|
||||
*
|
||||
* @param view - The active or same-leaf replacement view to observe.
|
||||
*/
|
||||
public addModalContainerObserver() {
|
||||
if (!this.plugin.activeExcalidrawView) {
|
||||
public addModalContainerObserver(view = this.plugin.activeExcalidrawView) {
|
||||
if (!view) {
|
||||
return;
|
||||
}
|
||||
const activeViewDoc = view.containerEl.ownerDocument;
|
||||
if (this.modalContainerObserver) {
|
||||
if (
|
||||
this.activeViewDoc === this.plugin.activeExcalidrawView.ownerDocument
|
||||
this.activeViewDoc === activeViewDoc &&
|
||||
this.modalObservedView === view
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -285,36 +304,49 @@ export class ObserverManager {
|
||||
//The user clicks settings, or "open another vault", or the command palette.
|
||||
//Other body portals, including inline suggestions, must not interrupt editing with a save.
|
||||
const modalContainerObserverFn: MutationCallback = (
|
||||
m: MutationRecord[],
|
||||
mutations: MutationRecord[],
|
||||
) => {
|
||||
const view = this.plugin.activeExcalidrawView;
|
||||
const observedView = this.modalObservedView;
|
||||
const addedNodes = mutations.flatMap((mutation) =>
|
||||
mutation.type === "childList"
|
||||
? Array.from(mutation.addedNodes)
|
||||
: [],
|
||||
);
|
||||
const modalOpened = addedNodes.some(
|
||||
(node) =>
|
||||
isObservedElement(node) &&
|
||||
(node.matches(MODAL_CONTAINER_SELECTOR) ||
|
||||
node.querySelector(MODAL_CONTAINER_SELECTOR) !== null),
|
||||
);
|
||||
if (
|
||||
m.length !== 1 ||
|
||||
m[0].type !== "childList" ||
|
||||
m[0].addedNodes.length !== 1 ||
|
||||
!isInstanceOfElement(m[0].addedNodes[0]) ||
|
||||
!m[0].addedNodes[0].matches(".modal-container") ||
|
||||
!view ||
|
||||
view.semaphores?.viewunload ||
|
||||
!view.isDirty()
|
||||
!modalOpened ||
|
||||
!observedView ||
|
||||
observedView.semaphores?.viewunload ||
|
||||
!observedView.isDirty() ||
|
||||
!observedView.excalidrawAPI
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { errorMessage } = view.excalidrawAPI.getAppState();
|
||||
const { errorMessage } = observedView.excalidrawAPI.getAppState();
|
||||
if (!errorMessage) {
|
||||
void this.plugin.activeExcalidrawView.save();
|
||||
void observedView.save();
|
||||
}
|
||||
};
|
||||
|
||||
this.activeViewDoc = activeViewDoc;
|
||||
this.modalObservedView = view;
|
||||
// Keep the observer constructor and target in the same window realm so a
|
||||
// migrated view never depends on its destroyed source window.
|
||||
this.modalContainerObserver = DEBUGGING
|
||||
? new CustomMutationObserver(
|
||||
modalContainerObserverFn,
|
||||
"modalContainerObserver",
|
||||
)
|
||||
: new MutationObserver(modalContainerObserverFn);
|
||||
this.activeViewDoc = this.plugin.activeExcalidrawView.ownerDocument;
|
||||
this.modalContainerObserver.observe(this.activeViewDoc.body, {
|
||||
: new (activeViewDoc.defaultView?.MutationObserver ?? MutationObserver)(
|
||||
modalContainerObserverFn,
|
||||
);
|
||||
this.modalContainerObserver.observe(activeViewDoc.body, {
|
||||
childList: true,
|
||||
});
|
||||
}
|
||||
@@ -324,8 +356,9 @@ export class ObserverManager {
|
||||
return;
|
||||
}
|
||||
this.modalContainerObserver.disconnect();
|
||||
this.activeViewDoc = null;
|
||||
this.modalContainerObserver = null;
|
||||
this.modalObservedView = null;
|
||||
this.activeViewDoc = null;
|
||||
}
|
||||
|
||||
private addWorkspaceDrawerObserver() {
|
||||
|
||||
@@ -22,20 +22,26 @@ const normalizeError = (error: unknown): Error =>
|
||||
? error
|
||||
: new Error(typeof error === "string" ? error : "Unknown error");
|
||||
|
||||
/**
|
||||
* Owns the plugin's single private React/Excalidraw runtime.
|
||||
*
|
||||
* Each view receives the same package but retains an idempotent lease keyed by
|
||||
* its actual window. The window key governs migration persistence and the
|
||||
* temporary `ExcalidrawLib` compatibility alias only; rendering ownership is
|
||||
* supplied independently through each Excalidraw instance's `ownerDocument`.
|
||||
*/
|
||||
export class PackageManager {
|
||||
private packageMap: Map<Window, Packages> = new Map<Window, Packages>();
|
||||
private EXCALIDRAW_PACKAGE: string;
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private fallbackPackage: Packages | null = null;
|
||||
private runtimePackage: Packages | null = null;
|
||||
private packageLeaseCountMap = new Map<Window, number>();
|
||||
private commonHostDisposerMap = new Map<Window, () => void>();
|
||||
private excalidrawHostDisposerMap = new Map<Window, () => void>();
|
||||
private commonHostDisposer: (() => void) | null = null;
|
||||
private excalidrawHostDisposer: (() => void) | null = null;
|
||||
private runtimeAliasWindows = new Set<Window>();
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.plugin = plugin;
|
||||
constructor(private readonly plugin: ExcalidrawPlugin) {
|
||||
let excalidrawPackage = "";
|
||||
|
||||
try {
|
||||
this.EXCALIDRAW_PACKAGE = unpackExcalidraw();
|
||||
excalidrawPackage = unpackExcalidraw();
|
||||
|
||||
// Evaluate Excalidraw in the main window with the same private React
|
||||
// instance used by the plugin bundle. The runtime is passed explicitly
|
||||
@@ -49,7 +55,7 @@ export class PackageManager {
|
||||
) => typeof ExcalidrawLib
|
||||
>(
|
||||
`(function(React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime) {
|
||||
${this.EXCALIDRAW_PACKAGE};
|
||||
${excalidrawPackage};
|
||||
return ExcalidrawLib;
|
||||
})`,
|
||||
"PackageManager constructor - excalidrawLib initialization",
|
||||
@@ -74,8 +80,7 @@ export class PackageManager {
|
||||
|
||||
// Validate the package before storing
|
||||
if (this.validatePackage(initialPackage)) {
|
||||
this.setPackage(window, initialPackage);
|
||||
this.fallbackPackage = initialPackage; // Store a valid package as fallback
|
||||
this.setRuntimePackage(initialPackage);
|
||||
} else {
|
||||
throw new Error("Invalid initial package");
|
||||
}
|
||||
@@ -89,6 +94,14 @@ export class PackageManager {
|
||||
10000,
|
||||
);
|
||||
console.error("Error loading the Excalidraw package", e);
|
||||
} finally {
|
||||
// Per-window evaluation has been removed. Release the decompressed source
|
||||
// strings after the one runtime is initialized instead of retaining them
|
||||
// for hypothetical future popouts.
|
||||
excalidrawPackage = "";
|
||||
REACT_PACKAGES = "";
|
||||
ReactJSXRuntime = null;
|
||||
ReactJSXDevRuntime = null;
|
||||
}
|
||||
|
||||
plugin.logStartupEvent("Excalidraw package unpacked");
|
||||
@@ -120,9 +133,9 @@ export class PackageManager {
|
||||
/**
|
||||
* Registers plugin capabilities with one evaluated Excalidraw runtime.
|
||||
*/
|
||||
private configureObsidianCommonHost(win: Window, pkg: Packages): void {
|
||||
this.commonHostDisposerMap.get(win)?.();
|
||||
this.commonHostDisposerMap.delete(win);
|
||||
private configureObsidianCommonHost(pkg: Packages): void {
|
||||
this.commonHostDisposer?.();
|
||||
this.commonHostDisposer = null;
|
||||
|
||||
const lib = pkg.excalidrawLib;
|
||||
if (
|
||||
@@ -137,16 +150,13 @@ export class PackageManager {
|
||||
this.plugin,
|
||||
lib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION,
|
||||
);
|
||||
this.commonHostDisposerMap.set(
|
||||
win,
|
||||
lib.configureObsidianCommonHost(adapter),
|
||||
);
|
||||
this.commonHostDisposer = lib.configureObsidianCommonHost(adapter);
|
||||
}
|
||||
|
||||
/** Registers plugin-wide settings with one evaluated Excalidraw runtime. */
|
||||
private configureObsidianExcalidrawHost(win: Window, pkg: Packages): void {
|
||||
this.excalidrawHostDisposerMap.get(win)?.();
|
||||
this.excalidrawHostDisposerMap.delete(win);
|
||||
private configureObsidianExcalidrawHost(pkg: Packages): void {
|
||||
this.excalidrawHostDisposer?.();
|
||||
this.excalidrawHostDisposer = null;
|
||||
|
||||
const lib = pkg.excalidrawLib;
|
||||
if (
|
||||
@@ -163,57 +173,52 @@ export class PackageManager {
|
||||
this.plugin,
|
||||
lib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION,
|
||||
);
|
||||
this.excalidrawHostDisposerMap.set(
|
||||
win,
|
||||
lib.configureObsidianExcalidrawHost(adapter),
|
||||
);
|
||||
this.excalidrawHostDisposer =
|
||||
lib.configureObsidianExcalidrawHost(adapter);
|
||||
}
|
||||
|
||||
/** Disposes every host registration owned by an evaluated window runtime. */
|
||||
private disposeObsidianHosts(win: Window): void {
|
||||
this.commonHostDisposerMap.get(win)?.();
|
||||
this.commonHostDisposerMap.delete(win);
|
||||
this.excalidrawHostDisposerMap.get(win)?.();
|
||||
this.excalidrawHostDisposerMap.delete(win);
|
||||
/** Disposes the plugin capabilities registered with the shared runtime. */
|
||||
private disposeObsidianHosts(): void {
|
||||
this.commonHostDisposer?.();
|
||||
this.commonHostDisposer = null;
|
||||
this.excalidrawHostDisposer?.();
|
||||
this.excalidrawHostDisposer = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a package for a specific window
|
||||
*/
|
||||
public setPackage(win: Window, pkg: Packages) {
|
||||
/** Stores and configures the plugin's single evaluated runtime package. */
|
||||
private setRuntimePackage(pkg: Packages): void {
|
||||
if (this.validatePackage(pkg)) {
|
||||
try {
|
||||
this.configureObsidianCommonHost(win, pkg);
|
||||
this.configureObsidianExcalidrawHost(win, pkg);
|
||||
this.configureObsidianCommonHost(pkg);
|
||||
this.configureObsidianExcalidrawHost(pkg);
|
||||
} catch (error: unknown) {
|
||||
this.disposeObsidianHosts(win);
|
||||
this.disposeObsidianHosts();
|
||||
throw normalizeError(error);
|
||||
}
|
||||
this.packageMap.set(win, pkg);
|
||||
|
||||
// Update fallback if we don't have one
|
||||
if (!this.fallbackPackage) {
|
||||
this.fallbackPackage = pkg;
|
||||
}
|
||||
this.runtimePackage = pkg;
|
||||
} else {
|
||||
errorHandler.handleError(
|
||||
"Attempted to set invalid package",
|
||||
"PackageManager.setPackage",
|
||||
"PackageManager.setRuntimePackage",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public getPackageMap() {
|
||||
return this.packageMap;
|
||||
/** Returns the one runtime used by every main-window and popout view. */
|
||||
public getRuntimePackage(): Packages {
|
||||
if (!this.runtimePackage || !this.validatePackage(this.runtimePackage)) {
|
||||
throw new Error("Excalidraw runtime package is unavailable");
|
||||
}
|
||||
return this.runtimePackage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Acquires an idempotent lease for the package owned by `win`.
|
||||
* Acquires the shared runtime while retaining the view's actual window.
|
||||
*
|
||||
* @remarks
|
||||
* Popout packages are deleted when their last lease is released. The main
|
||||
* package remains pinned for the plugin lifetime because it is also the
|
||||
* fallback runtime and is initialized as part of plugin startup.
|
||||
* Window identity remains view-owned migration/persistence state. Popout
|
||||
* leases additionally own the temporary `window.ExcalidrawLib` compatibility
|
||||
* alias and remove it when the final view in that window releases its lease.
|
||||
*/
|
||||
public acquirePackage(win: Window): PackageLease {
|
||||
const packages = this.getPackage(win);
|
||||
@@ -245,100 +250,49 @@ export class PackageManager {
|
||||
if (remainingLeases === 0) {
|
||||
this.packageLeaseCountMap.delete(win);
|
||||
if (win !== window) {
|
||||
this.deletePackage(win);
|
||||
this.removeRuntimeAlias(win);
|
||||
}
|
||||
} else {
|
||||
this.packageLeaseCountMap.set(win, remainingLeases);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a package for a window, creating it if necessary
|
||||
* with robust error handling
|
||||
* Returns the shared runtime and exposes its compatibility API in `win`.
|
||||
*
|
||||
* @remarks
|
||||
* The runtime is never evaluated in the supplied window. Rendering ownership
|
||||
* is provided separately through Excalidraw's stable `ownerDocument` prop.
|
||||
*/
|
||||
public getPackage(win: Window): Packages {
|
||||
try {
|
||||
// Return existing package if available
|
||||
if (this.packageMap.has(win)) {
|
||||
const pkg = this.packageMap.get(win);
|
||||
if (this.validatePackage(pkg)) {
|
||||
return pkg;
|
||||
}
|
||||
// If package exists but is invalid, delete it so we can recreate it
|
||||
this.deletePackage(win);
|
||||
}
|
||||
|
||||
// Create new package
|
||||
return errorHandler.wrapWithTryCatch(
|
||||
() => {
|
||||
// Use safe evaluation to load packages in the window context
|
||||
const evalResult = errorHandler.safeEval<{
|
||||
react: typeof React;
|
||||
reactDOM: typeof ReactDOM;
|
||||
excalidrawLib: typeof ExcalidrawLib;
|
||||
}>(
|
||||
`(function() {
|
||||
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
|
||||
return {
|
||||
react: React,
|
||||
reactDOM: ReactDOM,
|
||||
excalidrawLib: ExcalidrawLib,
|
||||
};
|
||||
})()`,
|
||||
"PackageManager.getPackage - package evaluation",
|
||||
win,
|
||||
);
|
||||
|
||||
if (!evalResult || !this.validatePackage(evalResult)) {
|
||||
throw new Error("Failed to create valid package");
|
||||
}
|
||||
|
||||
const newPackage = {
|
||||
react: evalResult.react,
|
||||
reactDOM: evalResult.reactDOM,
|
||||
excalidrawLib: evalResult.excalidrawLib,
|
||||
};
|
||||
|
||||
this.setPackage(win, newPackage);
|
||||
return newPackage;
|
||||
},
|
||||
"PackageManager.getPackage",
|
||||
this.fallbackPackage,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
errorHandler.handleError(
|
||||
normalizeError(error),
|
||||
"PackageManager.getPackage",
|
||||
);
|
||||
|
||||
// Return fallback package if available to prevent data loss
|
||||
if (this.fallbackPackage) {
|
||||
return this.fallbackPackage;
|
||||
}
|
||||
|
||||
// If no fallback, throw error to prevent undefined behavior
|
||||
throw new Error("Failed to get package and no fallback available");
|
||||
const pkg = this.getRuntimePackage();
|
||||
if (win !== window) {
|
||||
win.ExcalidrawLib = pkg.excalidrawLib;
|
||||
this.runtimeAliasWindows.add(win);
|
||||
}
|
||||
return pkg;
|
||||
}
|
||||
|
||||
/** Removes only the window-local alias; the shared runtime remains alive. */
|
||||
private removeRuntimeAlias(win: Window): void {
|
||||
const packageLib = this.runtimePackage?.excalidrawLib;
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
if (packageLib && win.ExcalidrawLib === packageLib) {
|
||||
delete win.ExcalidrawLib;
|
||||
}
|
||||
}, "PackageManager.removeRuntimeAlias");
|
||||
this.runtimeAliasWindows.delete(win);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compatibility facade retained for callers that explicitly clean a window.
|
||||
* The plugin-wide runtime and host registrations live until `destroy()`.
|
||||
*/
|
||||
public deletePackage(win: Window) {
|
||||
try {
|
||||
this.disposeObsidianHosts(win);
|
||||
|
||||
const pkg = this.packageMap.get(win);
|
||||
if (!pkg) {
|
||||
return;
|
||||
if (win !== window) {
|
||||
this.removeRuntimeAlias(win);
|
||||
}
|
||||
|
||||
const { excalidrawLib } = pkg;
|
||||
if (win.ExcalidrawLib === excalidrawLib) {
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
delete win.ExcalidrawLib;
|
||||
}, "PackageManager.deletePackage - cleanup ExcalidrawLib");
|
||||
}
|
||||
|
||||
this.packageMap.delete(win);
|
||||
} catch (error: unknown) {
|
||||
errorHandler.handleError(
|
||||
normalizeError(error),
|
||||
@@ -347,24 +301,19 @@ export class PackageManager {
|
||||
}
|
||||
}
|
||||
|
||||
public setExcalidrawPackage(pkg: string) {
|
||||
this.EXCALIDRAW_PACKAGE = pkg;
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
try {
|
||||
REACT_PACKAGES = "";
|
||||
|
||||
Array.from(this.packageMap.entries()).forEach(([win, _]) => {
|
||||
this.deletePackage(win);
|
||||
Array.from(this.runtimeAliasWindows).forEach((win) => {
|
||||
this.removeRuntimeAlias(win);
|
||||
});
|
||||
this.removeRuntimeAlias(window);
|
||||
|
||||
this.packageMap.clear();
|
||||
this.packageLeaseCountMap.clear();
|
||||
this.commonHostDisposerMap.clear();
|
||||
this.excalidrawHostDisposerMap.clear();
|
||||
this.EXCALIDRAW_PACKAGE = "";
|
||||
this.fallbackPackage = null;
|
||||
this.runtimeAliasWindows.clear();
|
||||
this.disposeObsidianHosts();
|
||||
this.runtimePackage = null;
|
||||
|
||||
react = null;
|
||||
reactDOM = null;
|
||||
|
||||
@@ -38,6 +38,8 @@ export class StencilLibraryManager {
|
||||
private itemSource = new Map<LibraryItem["id"], string>();
|
||||
private currentItems: LibraryItems = [];
|
||||
private loaded = false;
|
||||
private loadRevision = 0;
|
||||
private loadPromise: Promise<void> | null = null;
|
||||
private migrationPrompt: Promise<void> | null = null;
|
||||
private saveQueue: Promise<void> = Promise.resolve();
|
||||
private reloadTimer: number | null = null;
|
||||
@@ -86,6 +88,7 @@ export class StencilLibraryManager {
|
||||
}
|
||||
|
||||
public invalidate(): void {
|
||||
this.loadRevision++;
|
||||
this.loaded = false;
|
||||
this.itemSource.clear();
|
||||
this.currentItems = [];
|
||||
@@ -109,7 +112,7 @@ export class StencilLibraryManager {
|
||||
await this.migrateLegacyLibrary();
|
||||
}
|
||||
if (!this.loaded) {
|
||||
await this.loadFromVault();
|
||||
await this.ensureLoaded();
|
||||
}
|
||||
return this.currentItems;
|
||||
}
|
||||
@@ -156,7 +159,7 @@ export class StencilLibraryManager {
|
||||
}
|
||||
await this.saveQueue;
|
||||
this.invalidate();
|
||||
await this.loadFromVault();
|
||||
await this.ensureLoaded();
|
||||
this.isUpdatingOpenViews = true;
|
||||
try {
|
||||
for (const view of getExcalidrawViews(this.plugin.app, true)) {
|
||||
@@ -286,8 +289,39 @@ export class StencilLibraryManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async loadFromVault(): Promise<void> {
|
||||
this.itemSource.clear();
|
||||
/** Coalesces concurrent view initialization into one vault-library load. */
|
||||
private async ensureLoaded(): Promise<void> {
|
||||
while (!this.loaded) {
|
||||
if (this.loadPromise === null) {
|
||||
const revision = this.loadRevision;
|
||||
this.loadPromise = this.loadFromVault().then(
|
||||
({ itemSource, items }) => {
|
||||
if (revision !== this.loadRevision) {
|
||||
return;
|
||||
}
|
||||
this.itemSource = itemSource;
|
||||
this.currentItems = items;
|
||||
this.loaded = true;
|
||||
},
|
||||
);
|
||||
}
|
||||
const activeLoad: Promise<void> = this.loadPromise;
|
||||
try {
|
||||
await activeLoad;
|
||||
} finally {
|
||||
if (this.loadPromise === activeLoad) {
|
||||
this.loadPromise = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a coherent library snapshot without mutating the active cache. */
|
||||
private async loadFromVault(): Promise<{
|
||||
itemSource: Map<LibraryItem["id"], string>;
|
||||
items: LibraryItems;
|
||||
}> {
|
||||
const itemSource = new Map<LibraryItem["id"], string>();
|
||||
const folderPath = this.getFolderPath();
|
||||
const localPath = this.getLocalLibraryPath();
|
||||
const files = this.plugin.app.vault
|
||||
@@ -315,25 +349,24 @@ export class StencilLibraryManager {
|
||||
isLocalFile ? "unpublished" : "published",
|
||||
);
|
||||
for (const item of items) {
|
||||
if (this.itemSource.has(item.id)) {
|
||||
if (itemSource.has(item.id)) {
|
||||
console.warn(
|
||||
`Duplicate stencil library item id '${item.id}' in ${file.path}; keeping the first occurrence.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
this.itemSource.set(item.id, file.path);
|
||||
itemSource.set(item.id, file.path);
|
||||
combined.push(
|
||||
isLocalFile ? item : { ...item, status: "published" as const },
|
||||
);
|
||||
}
|
||||
}
|
||||
this.currentItems = combined;
|
||||
this.loaded = true;
|
||||
return { itemSource, items: combined };
|
||||
}
|
||||
|
||||
private async persistChanges(nextItems: LibraryItems): Promise<void> {
|
||||
if (!this.loaded) {
|
||||
await this.loadFromVault();
|
||||
await this.ensureLoaded();
|
||||
}
|
||||
const previousById = new Map(
|
||||
this.currentItems.map((item) => [item.id, item]),
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import type {
|
||||
AppState,
|
||||
BinaryFiles,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
|
||||
import type { ExcalidrawDataMigrationState } from "../../shared/ExcalidrawData";
|
||||
import type { TextMode } from "../../shared/TextMode";
|
||||
import type { ViewSaveMigrationState } from "../../view/managers/ViewSaveCoordinator";
|
||||
|
||||
const DEFAULT_HANDOFF_TTL_MS = 15_000;
|
||||
|
||||
/** Drawing-owned runtime state that may cross an Obsidian window migration. */
|
||||
export interface ViewMigrationDrawingState {
|
||||
elements: readonly ExcalidrawElement[];
|
||||
appState: AppState;
|
||||
files: BinaryFiles;
|
||||
textMode: TextMode;
|
||||
compatibilityMode: boolean;
|
||||
excalidrawData: ExcalidrawDataMigrationState;
|
||||
save: ViewSaveMigrationState;
|
||||
}
|
||||
|
||||
/** Metadata used to register one transient migration handoff. */
|
||||
export interface ViewMigrationHandoffRegistration {
|
||||
leafId: string;
|
||||
filePath: string;
|
||||
fileMtime: number;
|
||||
drawing: ViewMigrationDrawingState;
|
||||
}
|
||||
|
||||
/** Identity and freshness checks required to consume a migration handoff. */
|
||||
export interface ViewMigrationHandoffRequest {
|
||||
token: string;
|
||||
leafId: string;
|
||||
filePath: string;
|
||||
fileMtime: number;
|
||||
}
|
||||
|
||||
interface ViewMigrationHandoffEntry extends ViewMigrationHandoffRegistration {
|
||||
token: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
interface ViewMigrationHandoffScheduler {
|
||||
now: () => number;
|
||||
setTimeout: (callback: () => void, delay: number) => number;
|
||||
clearTimeout: (timer: number) => void;
|
||||
}
|
||||
|
||||
interface ViewMigrationHandoffManagerOptions {
|
||||
ttlMs?: number;
|
||||
scheduler?: ViewMigrationHandoffScheduler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns bounded, one-shot drawing handoffs between recreated views.
|
||||
*
|
||||
* Entries contain drawing state only. They never retain an `ExcalidrawView`,
|
||||
* React root, DOM node, `Window`, listener, or package lease. Consumption
|
||||
* removes the entry before validation so stale or mismatched state cannot be
|
||||
* retried, and a single expiry timer bounds abandoned payload lifetime.
|
||||
*/
|
||||
export class ViewMigrationHandoffManager {
|
||||
private readonly ttlMs: number;
|
||||
private readonly scheduler: ViewMigrationHandoffScheduler;
|
||||
private readonly entries = new Map<string, ViewMigrationHandoffEntry>();
|
||||
private readonly tokensByLeaf = new Map<string, string>();
|
||||
private cleanupTimer: number | null = null;
|
||||
private tokenSequence = 0;
|
||||
|
||||
public constructor(options: ViewMigrationHandoffManagerOptions = {}) {
|
||||
this.ttlMs = options.ttlMs ?? DEFAULT_HANDOFF_TTL_MS;
|
||||
if (!Number.isFinite(this.ttlMs) || this.ttlMs <= 0) {
|
||||
throw new Error("View migration handoff TTL must be positive");
|
||||
}
|
||||
this.scheduler =
|
||||
options.scheduler ??
|
||||
{
|
||||
now: () => Date.now(),
|
||||
setTimeout: (callback, delay) => window.setTimeout(callback, delay),
|
||||
clearTimeout: (timer) => window.clearTimeout(timer),
|
||||
};
|
||||
}
|
||||
|
||||
/** Registers a handoff, replacing any older payload for the same leaf. */
|
||||
public register(registration: ViewMigrationHandoffRegistration): string {
|
||||
this.pruneExpired();
|
||||
const previousToken = this.tokensByLeaf.get(registration.leafId);
|
||||
if (previousToken) {
|
||||
this.deleteEntry(previousToken);
|
||||
}
|
||||
|
||||
const now = this.scheduler.now();
|
||||
const token = `view-migration-${now.toString(36)}-${(++this.tokenSequence).toString(36)}`;
|
||||
this.entries.set(token, {
|
||||
...registration,
|
||||
token,
|
||||
expiresAt: now + this.ttlMs,
|
||||
});
|
||||
this.tokensByLeaf.set(registration.leafId, token);
|
||||
this.scheduleCleanup();
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a matching handoff exactly once.
|
||||
*
|
||||
* A token mismatch, leaf/path mismatch, file modification, or TTL expiry
|
||||
* returns `null` and discards the candidate so the caller must use its
|
||||
* ordinary disk-backed load path.
|
||||
*/
|
||||
public consume(
|
||||
request: ViewMigrationHandoffRequest,
|
||||
): ViewMigrationDrawingState | null {
|
||||
this.pruneExpired();
|
||||
const entry = this.entries.get(request.token);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
this.deleteEntry(request.token);
|
||||
this.scheduleCleanup();
|
||||
|
||||
if (
|
||||
entry.leafId !== request.leafId ||
|
||||
entry.filePath !== request.filePath ||
|
||||
entry.fileMtime !== request.fileMtime
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return entry.drawing;
|
||||
}
|
||||
|
||||
/** Drops all retained drawing state and cancels expiry work. */
|
||||
public destroy(): void {
|
||||
if (this.cleanupTimer !== null) {
|
||||
this.scheduler.clearTimeout(this.cleanupTimer);
|
||||
this.cleanupTimer = null;
|
||||
}
|
||||
this.entries.clear();
|
||||
this.tokensByLeaf.clear();
|
||||
}
|
||||
|
||||
private deleteEntry(token: string): void {
|
||||
const entry = this.entries.get(token);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
this.entries.delete(token);
|
||||
if (this.tokensByLeaf.get(entry.leafId) === token) {
|
||||
this.tokensByLeaf.delete(entry.leafId);
|
||||
}
|
||||
}
|
||||
|
||||
private pruneExpired(): void {
|
||||
const now = this.scheduler.now();
|
||||
for (const [token, entry] of this.entries) {
|
||||
if (entry.expiresAt <= now) {
|
||||
this.deleteEntry(token);
|
||||
}
|
||||
}
|
||||
if (this.entries.size === 0 && this.cleanupTimer !== null) {
|
||||
this.scheduler.clearTimeout(this.cleanupTimer);
|
||||
this.cleanupTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleCleanup(): void {
|
||||
if (this.cleanupTimer !== null) {
|
||||
this.scheduler.clearTimeout(this.cleanupTimer);
|
||||
this.cleanupTimer = null;
|
||||
}
|
||||
if (this.entries.size === 0) {
|
||||
return;
|
||||
}
|
||||
let nextExpiry = Number.POSITIVE_INFINITY;
|
||||
for (const entry of this.entries.values()) {
|
||||
nextExpiry = Math.min(nextExpiry, entry.expiresAt);
|
||||
}
|
||||
this.cleanupTimer = this.scheduler.setTimeout(() => {
|
||||
this.cleanupTimer = null;
|
||||
this.pruneExpired();
|
||||
this.scheduleCleanup();
|
||||
}, Math.max(0, nextExpiry - this.scheduler.now()));
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
|
||||
## Fixed
|
||||
- Moving a dirty drawing out of a popout window now safely transfers and persists its latest edits from the replacement main-window view.
|
||||
- Opening inline link suggestions while editing text no longer triggers a save that can end text editing, including after duplicating a LaTeX formula.
|
||||
- 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.
|
||||
- Settings changes are saved promptly without collapsing sections or interrupting fast typing. Writes are serialized, and Excalidraw keeps a device-local recovery copy so an empty or corrupted synchronized **data.json** cannot silently erase a large settings configuration.
|
||||
- Interdependent settings now initialize and refresh consistently, including TODO icons, auto-export formats, Taskbone credentials, filename previews, and custom grid colors. Built-in font previews also use the correct typeface in secondary Obsidian windows.
|
||||
- Applying a rendering-related setting no longer resets the live zoom and scroll position of an open drawing. New configurations use ☑ as the completed-TODO marker.
|
||||
|
||||
@@ -120,7 +120,7 @@ type LegacyGridColor = NonNullable<
|
||||
* `.find()` call on `scene.elements` to `any`. Omitting them first makes
|
||||
* this an actual override.
|
||||
*/
|
||||
type ExcalidrawDataScene = Omit<
|
||||
export type ExcalidrawDataScene = Omit<
|
||||
SceneDataWithFiles,
|
||||
"elements" | "appState"
|
||||
> & {
|
||||
@@ -251,11 +251,37 @@ export const REG_LINKINDEX_HYPERLINK = /^\w+:\/\//;
|
||||
export type EquationItem = { latex: string; isLoaded: boolean };
|
||||
export type MermaidItem = { mermaid: string; isLoaded: boolean };
|
||||
|
||||
type TextElementData = {
|
||||
raw: string;
|
||||
parsed: string;
|
||||
hasTextLink: boolean;
|
||||
};
|
||||
|
||||
/** Drawing-owned metadata transferred without retaining an old view. */
|
||||
export interface ExcalidrawDataMigrationState {
|
||||
sourceFilePath: string;
|
||||
textElements: ReadonlyMap<string, TextElementData>;
|
||||
scene: ExcalidrawDataScene;
|
||||
deletedElements: readonly ExcalidrawElement[];
|
||||
showLinkBrackets: boolean;
|
||||
linkPrefix: string;
|
||||
embeddableTheme: "light" | "dark" | "auto" | "default";
|
||||
urlPrefix: string;
|
||||
autoexportPreference: AutoexportPreference;
|
||||
textMode: TextMode;
|
||||
loaded: boolean;
|
||||
elementLinks: ReadonlyMap<string, string>;
|
||||
files: ReadonlyMap<FileId, EmbeddedFile>;
|
||||
markdownImages: ReadonlyMap<FileId, MarkdownImageData>;
|
||||
equations: ReadonlyMap<FileId, EquationItem>;
|
||||
mermaids: ReadonlyMap<FileId, MermaidItem>;
|
||||
compatibilityMode: boolean;
|
||||
textElementCommentedOut: boolean;
|
||||
selectedElementIds: Readonly<Record<string, boolean>>;
|
||||
}
|
||||
|
||||
export class ExcalidrawData {
|
||||
public textElements: Map<
|
||||
string,
|
||||
{ raw: string; parsed: string; hasTextLink: boolean }
|
||||
> = null;
|
||||
public textElements: Map<string, TextElementData> = null;
|
||||
public scene: ExcalidrawDataScene = null;
|
||||
public deletedElements: ExcalidrawElement[] = [];
|
||||
public file: TFile = null;
|
||||
@@ -317,6 +343,110 @@ export class ExcalidrawData {
|
||||
this.selectedElementIds = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports drawing-owned state for a one-shot window migration.
|
||||
*
|
||||
* Collection containers and mutable metadata records are copied. Immutable
|
||||
* Excalidraw elements and `EmbeddedFile` descriptors are transferred by
|
||||
* reference: neither owns a view, DOM node, `Window`, React runtime, or
|
||||
* package lease, and retaining their cached asset metadata is intentional.
|
||||
*/
|
||||
public exportMigrationState(): ExcalidrawDataMigrationState | null {
|
||||
if (
|
||||
!this.loaded ||
|
||||
!this.file ||
|
||||
!this.scene ||
|
||||
!this.textElements ||
|
||||
!this.elementLinks ||
|
||||
!this.files ||
|
||||
!this.markdownImages ||
|
||||
!this.equations ||
|
||||
!this.mermaids
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
sourceFilePath: this.file.path,
|
||||
textElements: new Map(
|
||||
Array.from(this.textElements, ([id, value]) => [id, { ...value }]),
|
||||
),
|
||||
scene: {
|
||||
...this.scene,
|
||||
elements: [...this.scene.elements],
|
||||
appState: { ...this.scene.appState },
|
||||
files: { ...(this.scene.files ?? {}) },
|
||||
},
|
||||
deletedElements: [...this.deletedElements],
|
||||
showLinkBrackets: this.showLinkBrackets,
|
||||
linkPrefix: this.linkPrefix,
|
||||
embeddableTheme: this.embeddableTheme,
|
||||
urlPrefix: this.urlPrefix,
|
||||
autoexportPreference: this.autoexportPreference,
|
||||
textMode: this.textMode,
|
||||
loaded: this.loaded,
|
||||
elementLinks: new Map(this.elementLinks),
|
||||
files: new Map(this.files),
|
||||
markdownImages: new Map(
|
||||
Array.from(this.markdownImages, ([id, value]) => [
|
||||
id,
|
||||
{ ...value },
|
||||
]),
|
||||
),
|
||||
equations: new Map(
|
||||
Array.from(this.equations, ([id, value]) => [id, { ...value }]),
|
||||
),
|
||||
mermaids: new Map(
|
||||
Array.from(this.mermaids, ([id, value]) => [id, { ...value }]),
|
||||
),
|
||||
compatibilityMode: this.compatibilityMode,
|
||||
textElementCommentedOut: this.textElementCommentedOut,
|
||||
selectedElementIds: { ...this.selectedElementIds },
|
||||
};
|
||||
}
|
||||
|
||||
/** Adopts a validated drawing-state export into this new view-owned model. */
|
||||
public adoptMigrationState(
|
||||
state: ExcalidrawDataMigrationState,
|
||||
file: TFile,
|
||||
): boolean {
|
||||
if (!file || state.sourceFilePath !== file.path || !state.loaded) {
|
||||
return false;
|
||||
}
|
||||
this.textElements = new Map(
|
||||
Array.from(state.textElements, ([id, value]) => [id, { ...value }]),
|
||||
);
|
||||
this.scene = {
|
||||
...state.scene,
|
||||
elements: [...state.scene.elements],
|
||||
appState: { ...state.scene.appState },
|
||||
files: { ...(state.scene.files ?? {}) },
|
||||
};
|
||||
this.deletedElements = [...state.deletedElements];
|
||||
this.file = file;
|
||||
this.showLinkBrackets = state.showLinkBrackets;
|
||||
this.linkPrefix = state.linkPrefix;
|
||||
this.embeddableTheme = state.embeddableTheme;
|
||||
this.urlPrefix = state.urlPrefix;
|
||||
this.autoexportPreference = state.autoexportPreference;
|
||||
this.textMode = state.textMode;
|
||||
this.loaded = state.loaded;
|
||||
this.elementLinks = new Map(state.elementLinks);
|
||||
this.files = new Map(state.files);
|
||||
this.markdownImages = new Map(
|
||||
Array.from(state.markdownImages, ([id, value]) => [id, { ...value }]),
|
||||
);
|
||||
this.equations = new Map(
|
||||
Array.from(state.equations, ([id, value]) => [id, { ...value }]),
|
||||
);
|
||||
this.mermaids = new Map(
|
||||
Array.from(state.mermaids, ([id, value]) => [id, { ...value }]),
|
||||
);
|
||||
this.compatibilityMode = state.compatibilityMode;
|
||||
this.textElementCommentedOut = state.textElementCommentedOut;
|
||||
this.selectedElementIds = { ...state.selectedElementIds };
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1.5.4: for backward compatibility following the release of container bound text elements and the depreciation boundElementIds field
|
||||
*/
|
||||
|
||||
Vendored
+5
-3
@@ -150,11 +150,13 @@ export type Packages = {
|
||||
};
|
||||
|
||||
/**
|
||||
* An idempotent ownership handle for one window-scoped runtime package.
|
||||
* An idempotent handle for the shared runtime acquired by one view.
|
||||
*
|
||||
* @remarks
|
||||
* The captured window remains the package owner even if Obsidian reparents the
|
||||
* consuming view's DOM into another window before view teardown completes.
|
||||
* The captured window remains the view's acquisition window even if Obsidian
|
||||
* reparents its DOM before teardown completes. All leases share the one package
|
||||
* evaluated in the main application realm, so lifecycle code must use `window`
|
||||
* for migration ownership and never infer package evaluation ownership from it.
|
||||
*/
|
||||
export type PackageLease = {
|
||||
readonly window: Window;
|
||||
|
||||
@@ -57,7 +57,9 @@ export class CustomMutationObserver {
|
||||
}
|
||||
};
|
||||
|
||||
this.observer = new MutationObserver(wrappedCallback);
|
||||
const Observer =
|
||||
target.ownerDocument?.defaultView?.MutationObserver ?? MutationObserver;
|
||||
this.observer = new Observer(wrappedCallback);
|
||||
|
||||
// Start observing with the modified callback
|
||||
this.observer.observe(target, options);
|
||||
|
||||
+277
-20
@@ -245,13 +245,18 @@ import { ViewFullscreenManager } from "./managers/ViewFullscreenManager";
|
||||
import { ViewLinkNavigationManager } from "./managers/ViewLinkNavigationManager";
|
||||
import { ViewExcalidrawExtensionRenderer } from "./managers/ViewExcalidrawExtensionRenderer";
|
||||
import { MarkdownImageController } from "./managers/MarkdownImageController";
|
||||
import { ViewSceneFileManager } from "./managers/ViewSceneFileManager";
|
||||
import {
|
||||
getVisibleImageFileIds,
|
||||
ViewSceneFileManager,
|
||||
waitForWindowPaint,
|
||||
} from "./managers/ViewSceneFileManager";
|
||||
import {
|
||||
type SaveExecutionResult,
|
||||
type SaveSideEffectPolicy,
|
||||
ViewSaveCoordinator,
|
||||
WINDOW_BLUR_FORCE_SAVE_POLICY,
|
||||
} from "./managers/ViewSaveCoordinator";
|
||||
import type { ViewMigrationDrawingState } from "../core/managers/ViewMigrationHandoffManager";
|
||||
import { ImageInfo } from "src/types/excalidrawAutomateTypes";
|
||||
import { PageOrientation, PageSize } from "src/types/exportUtilTypes";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
@@ -280,8 +285,13 @@ import { setElementDisplay } from "src/utils/htmlUtils";
|
||||
|
||||
const EMBEDDABLE_SEMAPHORE_TIMEOUT = 2000;
|
||||
const PREVENT_RELOAD_TIMEOUT = 2000;
|
||||
const MIGRATION_BINARY_FILE_BATCH_SIZE = 4;
|
||||
const RE_TAIL = /^## Drawing\n[\s\S]*\n%%$(.*)/ms;
|
||||
|
||||
type MigrationImageAPI = ExcalidrawImperativeAPI & {
|
||||
awaitImageFiles?: (fileIds: readonly FileId[]) => Promise<void>;
|
||||
};
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
declare const mainDocument: Document;
|
||||
|
||||
@@ -538,6 +548,9 @@ export default class ExcalidrawView
|
||||
private packageLease: PackageLease | null = null;
|
||||
private lastAppState: AppState | null = null;
|
||||
private lastElementsVersion: number = -1;
|
||||
private pendingMigrationHandoffToken: string | null = null;
|
||||
private pendingMigrationBinaryFiles: BinaryFiles | null = null;
|
||||
private migrationBinaryFilePublication: Promise<void> | null = null;
|
||||
|
||||
constructor(leaf: WorkspaceLeaf, plugin: ExcalidrawPlugin) {
|
||||
super(leaf);
|
||||
@@ -1686,14 +1699,17 @@ export default class ExcalidrawView
|
||||
this.containerEl.onWindowMigrated(async () => {
|
||||
const f = this.file;
|
||||
const l = this.leaf;
|
||||
const plugin = this.plugin;
|
||||
// Obsidian may destroy the source Electron window before the normal
|
||||
// unload callbacks select detached-view persistence. Capture every
|
||||
// API-owned value synchronously, then unmount before the first await.
|
||||
this.semaphores.windowMigrating = true;
|
||||
this.clearExcalidrawInitializeTimer();
|
||||
this.sceneFileManager.terminateActiveLoaders();
|
||||
this.windowMigrationSaveSnapshot = null;
|
||||
const migrationSnapshot = this.captureWindowMigrationSnapshot();
|
||||
const migrationSaveRequired =
|
||||
this.captureWindowMigrationSaveSnapshot();
|
||||
this.windowMigrationSaveSnapshot !== null;
|
||||
this.unmountExcalidrawRoot();
|
||||
if (migrationSaveRequired) {
|
||||
await this.saveCoordinator.flush();
|
||||
@@ -1703,20 +1719,32 @@ export default class ExcalidrawView
|
||||
warningUnknowSeriousError();
|
||||
return;
|
||||
}
|
||||
const migrationDrawingState = migrationSnapshot
|
||||
? this.createWindowMigrationDrawingState(migrationSnapshot)
|
||||
: null;
|
||||
this.windowMigrationSaveSnapshot = null;
|
||||
try {
|
||||
await closeLeafView(l);
|
||||
} catch (error: unknown) {
|
||||
this.plugin.discardViewMigrationPersistenceHandoff(l.id);
|
||||
plugin.discardViewMigrationPersistenceHandoff(l.id);
|
||||
this.setDirty();
|
||||
this.semaphores.windowMigrating = false;
|
||||
throw error;
|
||||
}
|
||||
const handoffToken = migrationDrawingState
|
||||
? plugin.registerViewMigrationHandoff({
|
||||
leafId: l.id,
|
||||
filePath: f.path,
|
||||
fileMtime: f.stat.mtime,
|
||||
drawing: migrationDrawingState,
|
||||
})
|
||||
: null;
|
||||
windowMigratedDisableZoomOnce = true;
|
||||
void l.setViewState({
|
||||
type: VIEW_TYPE_EXCALIDRAW,
|
||||
state: {
|
||||
file: f.path,
|
||||
...(handoffToken ? { migrationHandoffToken: handoffToken } : {}),
|
||||
},
|
||||
});
|
||||
}),
|
||||
@@ -2090,8 +2118,7 @@ export default class ExcalidrawView
|
||||
}
|
||||
|
||||
/**
|
||||
* Captures all API-owned save inputs before a window migration tears down
|
||||
* the source runtime.
|
||||
* Captures all API-owned drawing and save inputs before window teardown.
|
||||
*
|
||||
* @remarks
|
||||
* The caller must unmount the source React root immediately after this
|
||||
@@ -2099,28 +2126,56 @@ export default class ExcalidrawView
|
||||
* until after synchronization, compression, or native file access can let
|
||||
* Electron destroy the source popout window first and freeze Obsidian.
|
||||
*/
|
||||
private captureWindowMigrationSaveSnapshot(): boolean {
|
||||
private captureWindowMigrationSnapshot(): {
|
||||
scene: NonNullable<ReturnType<ExcalidrawView["getScene"]>>;
|
||||
files: BinaryFiles;
|
||||
} | null {
|
||||
const api = this.excalidrawAPI;
|
||||
if (!api) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
this.checkSceneVersion(api.getSceneElements());
|
||||
if (!this.isDirty()) {
|
||||
return false;
|
||||
}
|
||||
const appState = api.getAppState();
|
||||
const scene = this.getSceneWithAppState(undefined, appState);
|
||||
if (!scene) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
this.windowMigrationSaveSnapshot = {
|
||||
const files = { ...(scene.files ?? {}) };
|
||||
if (this.isDirty()) {
|
||||
this.windowMigrationSaveSnapshot = {
|
||||
scene,
|
||||
deletedElements: api
|
||||
.getSceneElementsIncludingDeleted()
|
||||
.filter((element: ExcalidrawElement) => element.isDeleted),
|
||||
selectedElementIds: appState.selectedElementIds,
|
||||
};
|
||||
}
|
||||
return {
|
||||
scene,
|
||||
deletedElements: api
|
||||
.getSceneElementsIncludingDeleted()
|
||||
.filter((element: ExcalidrawElement) => element.isDeleted),
|
||||
selectedElementIds: appState.selectedElementIds,
|
||||
files,
|
||||
};
|
||||
}
|
||||
|
||||
/** Creates a transferable drawing after any required save has settled. */
|
||||
private createWindowMigrationDrawingState(snapshot: {
|
||||
scene: NonNullable<ReturnType<ExcalidrawView["getScene"]>>;
|
||||
files: BinaryFiles;
|
||||
}): ViewMigrationDrawingState | null {
|
||||
const excalidrawData = this.excalidrawData.exportMigrationState();
|
||||
const save = this.saveCoordinator.exportMigrationState();
|
||||
if (!excalidrawData || !save) {
|
||||
return null;
|
||||
}
|
||||
const scene = this.windowMigrationSaveSnapshot?.scene ?? snapshot.scene;
|
||||
return {
|
||||
elements: [...scene.elements],
|
||||
appState: { ...scene.appState } as AppState,
|
||||
files: { ...snapshot.files },
|
||||
textMode: this.textMode,
|
||||
compatibilityMode: this.compatibilityMode,
|
||||
excalidrawData,
|
||||
save,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
private unmountExcalidrawRoot(): void {
|
||||
@@ -2622,7 +2677,22 @@ export default class ExcalidrawView
|
||||
}
|
||||
|
||||
public isLoaded: boolean = false;
|
||||
|
||||
/** Captures the one-shot handoff token before the base view loads data. */
|
||||
public async setState(
|
||||
state: Record<string, unknown>,
|
||||
result: ViewStateResult,
|
||||
): Promise<void> {
|
||||
this.pendingMigrationHandoffToken =
|
||||
typeof state?.migrationHandoffToken === "string"
|
||||
? state.migrationHandoffToken
|
||||
: null;
|
||||
await super.setState(state, result);
|
||||
}
|
||||
|
||||
setViewData(data: string, clear: boolean = false) {
|
||||
const migrationHandoffToken = this.pendingMigrationHandoffToken;
|
||||
this.pendingMigrationHandoffToken = null;
|
||||
//I am using last loaded file to control when the view reloads.
|
||||
//It seems text file view gets the modified file event after sync before the modifyEventHandler in main.ts
|
||||
//reload can only be triggered via reload()
|
||||
@@ -2635,6 +2705,14 @@ export default class ExcalidrawView
|
||||
if (!this.file) {
|
||||
return;
|
||||
}
|
||||
const migrationDrawingHandoff = migrationHandoffToken
|
||||
? this.plugin.consumeViewMigrationHandoff({
|
||||
token: migrationHandoffToken,
|
||||
leafId: this.leaf.id,
|
||||
filePath: this.file.path,
|
||||
fileMtime: this.file.stat.mtime,
|
||||
})
|
||||
: null;
|
||||
const migrationHandoffData = this.isInMainObsidianWorkspace
|
||||
? this.plugin.consumeViewMigrationPersistenceHandoff(
|
||||
this.leaf.id,
|
||||
@@ -2706,8 +2784,54 @@ export default class ExcalidrawView
|
||||
return;
|
||||
}
|
||||
this.compatibilityMode = this.file.extension === "excalidraw";
|
||||
let migrationDrawingAdopted = false;
|
||||
if (
|
||||
migrationDrawingHandoff &&
|
||||
migrationDrawingHandoff.compatibilityMode ===
|
||||
this.compatibilityMode &&
|
||||
this.excalidrawData.adoptMigrationState(
|
||||
migrationDrawingHandoff.excalidrawData,
|
||||
this.file,
|
||||
) &&
|
||||
this.saveCoordinator.adoptMigrationState(
|
||||
migrationDrawingHandoff.save,
|
||||
)
|
||||
) {
|
||||
this.excalidrawData.scene = {
|
||||
...this.excalidrawData.scene,
|
||||
elements: [...migrationDrawingHandoff.elements],
|
||||
appState: {
|
||||
...this.excalidrawData.scene.appState,
|
||||
...migrationDrawingHandoff.appState,
|
||||
},
|
||||
files: { ...migrationDrawingHandoff.files },
|
||||
};
|
||||
this.textMode = migrationDrawingHandoff.textMode;
|
||||
this.prevTextMode =
|
||||
migrationDrawingHandoff.excalidrawData.scene.prevTextMode ??
|
||||
migrationDrawingHandoff.textMode;
|
||||
this.pendingMigrationBinaryFiles = {
|
||||
...migrationDrawingHandoff.files,
|
||||
};
|
||||
migrationDrawingAdopted = true;
|
||||
}
|
||||
//await this.plugin.loadSettings();
|
||||
if (this.compatibilityMode) {
|
||||
if (migrationDrawingAdopted) {
|
||||
if (this.compatibilityMode) {
|
||||
this.plugin.enableLegacyFilePopoverObserver();
|
||||
this.actionButtons?.isRaw?.hide();
|
||||
this.actionButtons?.link?.hide();
|
||||
this.excalidrawData.disableCompression = true;
|
||||
} else {
|
||||
this.actionButtons?.link?.show();
|
||||
this.excalidrawData.disableCompression = false;
|
||||
if (this.textMode === TextMode.parsed) {
|
||||
this.actionButtons?.isRaw?.hide();
|
||||
} else {
|
||||
this.actionButtons?.isRaw?.show();
|
||||
}
|
||||
}
|
||||
} else if (this.compatibilityMode) {
|
||||
this.plugin.enableLegacyFilePopoverObserver();
|
||||
this.actionButtons?.isRaw?.hide();
|
||||
// this.actionButtons.isParsed.hide();
|
||||
@@ -3367,7 +3491,13 @@ export default class ExcalidrawView
|
||||
),
|
||||
gridDirection: this.plugin.settings.gridSettings.GRID_DIRECTION,
|
||||
},
|
||||
files: excalidrawData.files,
|
||||
// A migration publishes its already-transferred files progressively
|
||||
// after initialization so one all-at-once decode cannot block the
|
||||
// replacement editor's first paint.
|
||||
files:
|
||||
this.pendingMigrationBinaryFiles === null
|
||||
? excalidrawData.files
|
||||
: {},
|
||||
libraryItems: await this.getLibrary(),
|
||||
});
|
||||
//files are loaded when excalidrawAPI is mounted
|
||||
@@ -3392,6 +3522,110 @@ export default class ExcalidrawView
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes transferred migration files in visible-first bounded batches.
|
||||
*
|
||||
* The replacement editor starts without `initialData.files` because the
|
||||
* component otherwise decodes every transferred data URL before its first
|
||||
* useful paint. Each batch still uses Excalidraw's ordinary `addFiles()`
|
||||
* and image-cache path; the fork's narrow await boundary only lets this host
|
||||
* wait for that work before yielding two destination-window frames.
|
||||
*/
|
||||
private async publishMigrationBinaryFiles(
|
||||
api: ExcalidrawImperativeAPI,
|
||||
): Promise<void> {
|
||||
const files = this.pendingMigrationBinaryFiles;
|
||||
this.pendingMigrationBinaryFiles = null;
|
||||
if (files === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const migrationAPI = api as MigrationImageAPI;
|
||||
if (typeof migrationAPI.awaitImageFiles !== "function") {
|
||||
errorlog({
|
||||
where: "ExcalidrawView.publishMigrationBinaryFiles",
|
||||
message: "The installed Excalidraw runtime cannot pace migration files",
|
||||
});
|
||||
if (this.excalidrawAPI === api && !api.isDestroyed) {
|
||||
void this.loadSceneFiles(false, undefined, undefined, undefined);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const isCurrent = () =>
|
||||
this.excalidrawAPI === api &&
|
||||
!api.isDestroyed &&
|
||||
!this.semaphores?.windowMigrating &&
|
||||
!this.semaphores?.viewunload;
|
||||
const visibleFileIds = getVisibleImageFileIds(this);
|
||||
const allFiles = Object.values(files);
|
||||
const orderedFiles = [
|
||||
...allFiles.filter((file) => visibleFileIds.has(file.id)),
|
||||
...allFiles.filter((file) => !visibleFileIds.has(file.id)),
|
||||
];
|
||||
|
||||
try {
|
||||
for (
|
||||
let offset = 0;
|
||||
offset < orderedFiles.length;
|
||||
offset += MIGRATION_BINARY_FILE_BATCH_SIZE
|
||||
) {
|
||||
if (!isCurrent()) {
|
||||
return;
|
||||
}
|
||||
const batch = orderedFiles.slice(
|
||||
offset,
|
||||
offset + MIGRATION_BINARY_FILE_BATCH_SIZE,
|
||||
);
|
||||
const fileIds = batch.map((file) => file.id);
|
||||
const skipSvgNormalization = new Set(
|
||||
batch
|
||||
.filter((file) => file.mimeType === "image/svg+xml")
|
||||
.map((file) => file.id),
|
||||
);
|
||||
api.addFiles({ files: batch, skipSvgNormalization });
|
||||
await migrationAPI.awaitImageFiles(fileIds);
|
||||
if (!isCurrent()) {
|
||||
return;
|
||||
}
|
||||
await waitForWindowPaint(() => this.ownerWindow ?? window);
|
||||
}
|
||||
|
||||
if (!isCurrent()) {
|
||||
return;
|
||||
}
|
||||
const loadedFiles = api.getFiles();
|
||||
const missingFileIds = new Set<FileId>();
|
||||
for (const element of api.getSceneElements()) {
|
||||
if (
|
||||
element.type === "image" &&
|
||||
element.fileId &&
|
||||
!loadedFiles[element.fileId]
|
||||
) {
|
||||
missingFileIds.add(element.fileId);
|
||||
}
|
||||
}
|
||||
if (missingFileIds.size > 0) {
|
||||
void this.loadSceneFiles(
|
||||
false,
|
||||
missingFileIds,
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
} else {
|
||||
this.lastSceneLoadTime = Date.now();
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "ExcalidrawView.publishMigrationBinaryFiles",
|
||||
error,
|
||||
});
|
||||
if (isCurrent()) {
|
||||
void this.loadSceneFiles(false, undefined, undefined, undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private onAfterLoadScene(justloaded: boolean) {
|
||||
const api = this.excalidrawAPI;
|
||||
if (
|
||||
@@ -3402,7 +3636,19 @@ export default class ExcalidrawView
|
||||
) {
|
||||
return;
|
||||
}
|
||||
void this.loadSceneFiles(false, undefined, undefined, undefined);
|
||||
if (
|
||||
this.pendingMigrationBinaryFiles !== null ||
|
||||
this.migrationBinaryFilePublication !== null
|
||||
) {
|
||||
if (this.migrationBinaryFilePublication === null) {
|
||||
this.migrationBinaryFilePublication =
|
||||
this.publishMigrationBinaryFiles(api).finally(() => {
|
||||
this.migrationBinaryFilePublication = null;
|
||||
});
|
||||
}
|
||||
} else {
|
||||
void this.loadSceneFiles(false, undefined, undefined, undefined);
|
||||
}
|
||||
this.updateContainerSize(null, true, justloaded);
|
||||
void this.initializeToolsIconPanelAfterLoading();
|
||||
const uiMode = calculateUIModeValue(this.plugin.settings);
|
||||
@@ -6646,6 +6892,17 @@ export default class ExcalidrawView
|
||||
// Ensure we keep the latest editor API reference before running scene-dependent setup.
|
||||
this.clearExcalidrawInitializeTimer();
|
||||
this.setExcalidrawAPI(api);
|
||||
const activeLeafMatches =
|
||||
this.app.workspace.getMostRecentLeaf() === this.leaf;
|
||||
const replacementLeafMatches =
|
||||
this.plugin.activeExcalidrawView?.leaf === this.leaf;
|
||||
if (activeLeafMatches || replacementLeafMatches) {
|
||||
// Rebuilding a view in the same leaf during window migration may not emit
|
||||
// active-leaf-change. Refresh the plugin's active instance and bind its
|
||||
// modal observer from the live destination document.
|
||||
this.plugin.activeExcalidrawView = this;
|
||||
this.plugin.addModalContainerObserver(this);
|
||||
}
|
||||
this.excalidrawInitializeTimer = window.setTimeout(() => {
|
||||
this.excalidrawInitializeTimer = null;
|
||||
// window migration scenario
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
ExcalidrawInitialDataState,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import type { ComponentProps, ComponentType } from "react";
|
||||
|
||||
import { DEVICE, obsidianToExcalidrawMap } from "../../constants/constants";
|
||||
import { t } from "../../lang/helpers";
|
||||
@@ -53,6 +54,9 @@ export function createExcalidrawRootElement(
|
||||
) {
|
||||
const React = view.packages.react;
|
||||
const { Excalidraw } = view.packages.excalidrawLib;
|
||||
const OwnerDocumentAwareExcalidraw = Excalidraw as ComponentType<
|
||||
ComponentProps<typeof Excalidraw> & { ownerDocument?: Document }
|
||||
>;
|
||||
|
||||
const excalidrawWrapperRef = React.useRef<HTMLDivElement>(null);
|
||||
const toolsPanelRef = React.useRef<ToolsPanel>(null);
|
||||
@@ -161,8 +165,9 @@ export function createExcalidrawRootElement(
|
||||
onDragLeave: view.dropManager?.onDragLeave.bind(view.dropManager),
|
||||
},
|
||||
React.createElement(
|
||||
Excalidraw,
|
||||
OwnerDocumentAwareExcalidraw,
|
||||
{
|
||||
ownerDocument: view.ownerDocument,
|
||||
onExcalidrawAPI: (api) => view.setExcalidrawAPI(api),
|
||||
onInitialize: (api) => view.onExcalidrawInitialize(api),
|
||||
UIOptions: {
|
||||
|
||||
@@ -24,6 +24,12 @@ export interface SaveExecutionResult {
|
||||
status: SaveExecutionStatus;
|
||||
}
|
||||
|
||||
/** Clean durability baseline transferred with a migrated drawing. */
|
||||
export interface ViewSaveMigrationState {
|
||||
currentRevision: number;
|
||||
savedRevision: number;
|
||||
}
|
||||
|
||||
/** Side effects selected for one forced-save request. */
|
||||
export interface ForceSavePolicy {
|
||||
refreshSceneFiles: boolean;
|
||||
@@ -482,4 +488,42 @@ export class ViewSaveCoordinator {
|
||||
this.view.semaphores.dirty = null;
|
||||
this.dependencies.clearDirtyVisuals();
|
||||
}
|
||||
|
||||
/** Exports a settled revision baseline for a migration handoff. */
|
||||
public exportMigrationState(): ViewSaveMigrationState | null {
|
||||
if (
|
||||
this.saveLoopPromise !== null ||
|
||||
this.activeSaveRevision !== null ||
|
||||
this.pendingSaveRequest !== null ||
|
||||
this.currentRevision !== this.savedRevision ||
|
||||
this.isDirty()
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
currentRevision: this.currentRevision,
|
||||
savedRevision: this.savedRevision,
|
||||
};
|
||||
}
|
||||
|
||||
/** Adopts a validated, settled durability baseline in a new view. */
|
||||
public adoptMigrationState(state: ViewSaveMigrationState): boolean {
|
||||
if (
|
||||
this.saveLoopPromise !== null ||
|
||||
this.activeSaveRevision !== null ||
|
||||
this.pendingSaveRequest !== null ||
|
||||
!Number.isSafeInteger(state.currentRevision) ||
|
||||
!Number.isSafeInteger(state.savedRevision) ||
|
||||
state.currentRevision < 0 ||
|
||||
state.savedRevision < 0 ||
|
||||
state.currentRevision !== state.savedRevision
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
this.currentRevision = state.currentRevision;
|
||||
this.savedRevision = state.savedRevision;
|
||||
this.view.semaphores.dirty = null;
|
||||
this.dependencies.clearDirtyVisuals();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,10 @@ export interface ViewSceneFileManagerDependencies {
|
||||
addFiles: typeof import("../ExcalidrawView").addFiles;
|
||||
}
|
||||
|
||||
const waitForWindowPaint = (getOwnerWindow: () => Window): Promise<void> =>
|
||||
/** Waits for two frames in the current view window, with a bounded fallback. */
|
||||
export const waitForWindowPaint = (
|
||||
getOwnerWindow: () => Window,
|
||||
): Promise<void> =>
|
||||
new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = () => {
|
||||
@@ -49,7 +52,10 @@ const waitForWindowPaint = (getOwnerWindow: () => Window): Promise<void> =>
|
||||
}
|
||||
});
|
||||
|
||||
const getVisibleImageFileIds = (view: ExcalidrawView): Set<FileId> => {
|
||||
/** Returns image file IDs intersecting the view's current scene viewport. */
|
||||
export const getVisibleImageFileIds = (
|
||||
view: ExcalidrawView,
|
||||
): Set<FileId> => {
|
||||
const visibleFileIds = new Set<FileId>();
|
||||
const appState = view.excalidrawAPI?.getAppState();
|
||||
if (!appState) {
|
||||
|
||||
Reference in new issue
Block a user