Compare commits

...
Author SHA1 Message Date
zsviczian 149e1e5bf0 perf: publish migrated files progressively 2026-08-27 16:15:33 +02:00
zsviczian 0da7120a7d perf: adopt drawing state across window migration 2026-08-27 07:48:38 +02:00
zsviczian d94b3b19ad refactor: define drawing migration handoff 2026-08-26 22:18:24 +02:00
zsviczian 169ceb3cf3 fix: save dirty drawings for popout modals 2026-08-26 21:55:32 +02:00
zsviczian ded91c6882 fix: coalesce stencil library loading 2026-08-26 19:49:52 +02:00
zsviczian 4ce81be081 refactor: simplify shared runtime ownership 2026-08-26 19:33:33 +02:00
zsviczian 740ee455d3 refactor: share Excalidraw runtime across windows 2026-08-26 18:45:57 +02:00
zsviczian 81fbbf42b7 2.27.0-beta.6, 0.18.127 2026-08-26 07:20:52 +02:00
zsviczian ba6c45d621 Merge pull request #2908 from zsviczian/performance-refactor-pr
Improve save and popout lifecycle performance
2026-08-26 07:18:39 +02:00
zsviczian 1c76170bad fix: cancel image loading across popout teardown 2026-08-25 23:00:59 +02:00
zsviczian 4d60ce9263 fix: preserve dirty popout migrations 2026-08-25 21:02:50 +02:00
zsviczian d513935523 chore: remove local madge dependency 2026-08-25 15:26:00 +02:00
zsviczian 01fcb09f83 chore: remove performance refactor diagnostics 2026-08-25 15:25:19 +02:00
zsviczian 57240da793 perf: restore progressive scene image loading 2026-08-25 14:45:03 +02:00
zsviczian 91e78ec1ae perf: coalesce in-flight view saves 2026-08-25 08:19:13 +02:00
zsviczian 648a2a8ed8 refactor: extract view save coordinator 2026-08-25 07:45:56 +02:00
zsviczian 83c8493c02 chore: use explicit window globals 2026-08-25 06:10:39 +02:00
zsviczian 67352c9952 perf: define save side-effect policy 2026-08-24 23:03:28 +02:00
zsviczian b4170ac68c perf: coalesce drawing backup writes 2026-08-24 22:37:09 +02:00
zsviczian 767cacbcdc perf: reuse coherent save snapshots 2026-08-24 22:19:58 +02:00
zsviczian b708883e13 perf: index images during save synchronization 2026-08-24 21:51:24 +02:00
zsviczian ded19ad510 perf: linearize save synchronization indexes 2026-08-24 21:06:09 +02:00
zsviczian 3579dbf245 fix: retain Excalidraw classification during cache refresh 2026-08-24 20:39:03 +02:00
zsviczian 8a0714104a perf: decouple blur saves from scene refresh 2026-08-24 20:27:51 +02:00
zsviczian 61817b01c6 WIP: validate performance refactor phase 1A lifecycle fixes 2026-08-24 20:01:36 +02:00
zsviczian d3e7182ff2 generate repository zip 2026-08-24 18:09:31 +02:00
zsviczian 6a50ccd271 updated agents.md and contributing.md 2026-08-23 22:02:38 +02:00
zsviczian f4ff25f308 fixed tootltip appearing twice - registerElementActionProvider 2026-08-23 20:04:25 +02:00
zsviczian df95e5f2b0 fixed settings breadcrumbs on Obsidian Mobile (touch) 2026-08-23 19:23:04 +02:00
zsviczian b6e98a8231 Merge pull request #2905 from theslyprofessor/fix/stale-canvas-offsets-1544
Fix stale canvas offsets when the view moves without resizing
2026-08-23 18:57:55 +02:00
zsviczian 48a35c7982 Merge pull request #2906 from zsviczian/declarative-settings
Migrate Excalidraw settings to Obsidian's declarative settings API
2026-08-23 18:55:13 +02:00
Nakul Tiruviluamala 8bfcd23b77 Flush offset refresh synchronously on the pointerdown path
Per review: api.refresh() only enqueues a React state update, so the
capture-phase pointerdown guard alone could not correct the SAME event's
coordinates - the first tap after a layout shift with the pointer already
inside the view still used stale offsets. Wrap the pointerdown-path
refresh in flushSync (available on the plugin's private react-dom
runtime) so the corrected offsets are committed before React's delegated
handlers process the event. Falls back to the async refresh if flushSync
is unavailable or throws.
2026-08-23 03:32:46 -07:00
Nakul Tiruviluamala 74429eb4eb Fix stale canvas offsets when the view moves without resizing (#1544)
Excalidraw caches offsetLeft/offsetTop and recalculates on container
resize or scroll, but nothing above the canvas changing height (an
injected toolbar row, tab-header wrap) moves the canvas WITHOUT a size
change, so pointer and selection events land a few pixels off until the
next autosave tick refreshes offsets (up to 60s on desktop).

Adds a throttled drift guard on pointerenter/pointerdown that compares
the container's bounding rect to the cached appState offsets and calls
refreshCanvasOffset() when they disagree by more than 1px, plus a
css-change hook mirroring the existing layout-change refresh.
2026-08-23 03:10:30 -07:00
34 changed files with 3257 additions and 645 deletions

No files matched your search

+35 -11
View File
@@ -73,9 +73,12 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- Prefer Obsidian's established classes such as `mod-warning` before adding plugin-specific CSS. Consult the Obsidian CSS variables and component conventions when styling settings or dialogs.
- Never use `document.createElement()`, `Document.createElement()`, or `Document.createDocumentFragment()`. Always use Obsidian's `createEl()`, `createDiv()`, `createSpan()`, `createSvg()`, and `createFragment()` helpers. When an element must deliberately belong to a specific document that Obsidian's helpers cannot target, such as a canvas used for drawing or an element inside an iframe, use the `deliberateCreateElement` function injected by `rollup.config.mjs` and declare it in the consuming module, for example `declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;`.
- Use semantic interactive elements and Obsidian's event helpers. Link-like navigation should use a real anchor, not a button merely styled as a link; use `onClickEvent` when applying custom navigation behavior. Validate touch interactions on a physical mobile device because desktop mobile emulation proves layout, not native touch activation.
- When a control already has a styled tooltip, do not also set an HTML `title` attribute. Keep its accessible name in `aria-label`; `title` produces a second native Chromium/Electron tooltip and must not replace accessible labeling.
- Do not write an element's `style` attribute directly. Use `setStyle` and `removeStyle` from `src/utils/styleUtils.ts` when a dynamic inline style is genuinely necessary.
- Use the existing visibility helpers instead of the native `hidden` property or attribute, which is not reliable in Obsidian's styled UI. Choose `hideElement`/`showElement` or `setComponentVisibility` from `src/utils/styleUtils.ts`, or `setElementHidden`/`setElementDisplay` from `src/utils/htmlUtils.ts` when a boolean/display-oriented API is clearer.
- Search `src/utils/styleUtils.ts` and `src/utils/htmlUtils.ts` before introducing new DOM styling helpers or display classes.
- Run Obsidian CodeScanner after CSS changes. Preserve compatibility with the declared minimum Obsidian version and prefer a widely supported property when it provides the same result; for example, a basic underline is preferable to optional underline-thickness/offset styling.
- For a known vault path, use the most specific synchronous lookup: `app.vault.getFolderByPath()` for folders and `app.vault.getFileByPath()` for files. Use `getAbstractFileByPath()` only when either type is intentionally accepted, and avoid adapter-level existence checks when the Vault API already models the target.
- Radix content in the customized Excalidraw package may be rendered through `ObsidianRadixPortal` directly under the owning document's body. A body portal escapes component ancestor selectors and modal stacking contexts. When a trigger is visible but its menu or popover is not, first inspect whether the content mounted behind a modal or lost ancestor-scoped styles. Use a class on the portaled content, a portal-safe selector, and an explicit stacking level when required; validate main-window, popout, click-outside, and Escape behavior.
@@ -111,6 +114,7 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
- Don't assume desktop-only behavior unless `isDesktopOnly` is `true`.
- Avoid using desktop only objects and functions such as Node Buffer, SharedArrayBuffer, etc. For the special case when this is required, make proper mobile safe guards.
- Avoid large in-memory structures; be mindful of memory and storage constraints.
- Treat a physical phone or tablet as a separate validation environment for touch targets, synthesized clicks, scrolling gestures, focus, and the mobile WebView. Desktop mobile emulation is useful for responsive layout checks but is not a substitute for real touch testing.
## Agent do/don't
@@ -202,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
@@ -229,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.
@@ -248,11 +252,16 @@ 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.
- The migration callback owns the single persistence flush. Generic `onClose()` and `onUnloadFile()` safeguards must not start duplicate migration saves, and the retired source view must reject blur-save side effects and vault-modify synchronization after its API is unmounted.
- A popout-to-main migration may serialize from a synchronously captured drawing snapshot, but the replacement main-window view must perform the final drawing-file write. Never initiate the final Vault/native write from the source popout callback.
### Main-Window Persistent Storage
@@ -402,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.
@@ -421,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/`
@@ -444,6 +453,21 @@ If a task changes persisted settings, inspect all relevant pieces.
Settings changes are often incomplete if only one of these surfaces is updated.
## Declarative Settings And Persistence
The plugin supports Obsidian 1.8.7 while optionally using the declarative settings API introduced in Obsidian 1.13. Preserve both compatibility paths.
- Do not bump the `obsidian` dependency or `minAppVersion` merely to consume declarative settings. Gate the runtime path with `requireApiVersion("1.13.0")` and keep conservative placeholder declarations for the newer API.
- `getSettingDefinitions()` must return the complete tree only when the runtime supports declarative settings and the restart-applied compatibility preference enables them. Returning an empty array is the intentional fallback to the legacy renderer.
- The settings page model is the canonical hierarchy for declarative rendering, legacy single-page rendering, descriptions, search aliases, breadcrumbs, cross-page navigation, and Markdown export. Do not create separate setting lists or behavior implementations for the two layouts.
- Controls that change each other's options, visibility, or disabled state must share one integrated component or one shared configurator. Apply dependent state during initial render as well as after changes. Scope captured control references to one rendered definition tree; generating an export-only tree must never replace bindings used by the mounted UI.
- On Obsidian 1.13+, do not call `display()` to refresh a declarative page. Update the mounted controls through their binding/configurator path or ask Obsidian to rebuild definitions only when the definition tree itself changed.
- Declarative page navigation uses guarded unpublished Obsidian APIs. Prefer `openPagePath`; retain the checked `findTabById`/`navigateToPage` fallback, derive localized paths from the canonical page model, and degrade to non-navigating text when the API is unavailable.
- Route all settings writes through `PluginSettingsManager` and its serialized stable-snapshot writer. Save when values change; never make plugin shutdown or settings-tab closure the primary persistence boundary because Obsidian may not await asynchronous writes during termination. Avoid competing direct `saveData()` calls.
- Missing and invalid `data.json` states are different. A first installation with no file is valid; a missing file with a recovery snapshot requires a restore-or-defaults choice; invalid startup data should restore a valid device-local snapshot or ask the user how to proceed; invalid data arriving during a running session must be rejected and repaired from the valid in-memory settings.
- The last-known-good recovery snapshot is durable, device-local IndexedDB data owned by the main application window. Refresh it after every valid load or save, do not store large snapshots in `localStorage`, and do not create independent recovery databases for popouts.
- Preserve unknown persisted keys. Do not derive a sanitizer from the TypeScript settings interface or treat unfamiliar keys as corruption.
## Script Engine And Automation Notes
- Excalidraw Automate is a major public surface of this project.
@@ -467,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
+18
View File
@@ -35,6 +35,8 @@ Because Obsidian runs across a variety of environments, please manually test you
- Desktop: Mac, Windows, Linux
- Mobile: Android, iOS (Test on both Phones and Tablets)
Desktop mobile emulation is useful for checking responsive layout, but it does not reproduce every touch event, synthesized click, focus, scroll gesture, or mobile WebView behavior. If a change affects an interactive mobile control, validate it on at least one physical phone or tablet.
Use a risk-based test plan rather than a generic smoke test. Every change should identify the most likely regression and whether it needs separate coverage in:
- the main Obsidian window
@@ -43,6 +45,12 @@ Use a risk-based test plan rather than a generic smoke test. Every change should
- desktop and mobile layouts
- offline mode, when the change affects packaged assets or runtime loading
For UI and CSS changes:
- Use semantic controls and Obsidian's event helpers. Link-like navigation should use a real anchor; custom navigation handlers should use `onClickEvent`.
- Keep accessible names in `aria-label`. If a styled tooltip is already present, omit the HTML `title` attribute to avoid a second native browser tooltip.
- Run Obsidian CodeScanner and resolve compatibility warnings against the supported Obsidian baseline. Prefer simple, broadly supported CSS when advanced styling is only decorative.
Timers, observers, autosave coordination, and undocumented Obsidian API workarounds may exist for platform behavior outside the plugin's control. Trace their purpose before simplifying them.
## 🪵 Logging Requirement
@@ -156,6 +164,16 @@ Use `RefactorPlan.md` as the living record for ongoing structural work. Refactor
`ExcalidrawView` must remain an Obsidian `TextFileView`; it should not be converted wholesale into React. React owns the child UI, while the view remains the Obsidian lifecycle and compatibility boundary. ExcalidrawAutomate, command IDs, settings, serialized data, and existing plugin integrations must remain backwards compatible.
### 6. Settings UI and persistence
The plugin keeps Obsidian 1.8.7 compatibility while using searchable declarative settings on Obsidian 1.13 and newer.
- Do not bump the Obsidian dependency or minimum version just to use the declarative API. Gate it at runtime; returning an empty definition array is the intentional legacy fallback.
- Maintain one canonical settings hierarchy and shared control behavior for both the declarative multi-page and legacy single-page layouts, including descriptions and Markdown export. Do not fork the two experiences into independent implementations.
- Keep interdependent controls together and apply their visibility, options, and disabled state during initial render as well as after changes.
- Persist settings through `PluginSettingsManager`; do not add independent `saveData()` calls or rely on plugin shutdown to finish an asynchronous save.
- Treat a missing `data.json`, invalid/corrupted data, and a valid externally synchronized update as separate cases. Preserve the device-local recovery workflow and unknown forward-compatible setting keys.
## 🌍 Localization & User-Facing Text
- **No hardcoded strings:** There should be no hardcoded English strings directly in the UI components or logic.
+85
View File
@@ -56,12 +56,97 @@ validated, and what remains uncertain.
| Prioritize cached and direct scene assets before generated SVG misses | Desktop warm reopen validated; cancellation, popout, and mobile remain | Scene loading now treats Excalidraw cache lookup and SVG generation as separate priority tiers. Cache hits and direct vault assets finish in the first pool; Excalidraw cache misses and known bypasses such as color-mapped drawings are recorded without generating, the completed fast batch is sent to Excalidraw, and the loader yields a browser task before starting a second generation pool. Ordinary PNG/JPEG/SVG reads keep their existing order, while uncached generated drawings no longer begin early enough to prevent cached results from painting |
| 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 |
| Bound scene-file loader stalls (Phase 1A.3) | Complete for the observed failure scene; forced-timeout branch not triggered | Each scene-file task pool now has a 30-second inactivity watchdog reset whenever a task settles. A stalled pool records `terminalState=timed-out`, terminates remaining work, and guarantees exactly one final callback so the view releases `activeLoader` and advances its coalesced next request. Completed, externally terminated, depth-limited, and unexpected-failure paths also expose a terminal state. Missing-vault-file retries retain the existing 30-attempt bound but now whitelist only those missing file IDs; URL/local-link entries cannot turn recovery into repeated full-scene reloads. The prior 169-file SYL failure scene completed with all 169 files in 7.51 seconds; its three initially unresolved entries were external/local rather than missing vault files, and no loader remained active or stalled. The 46-file MOC EA regression scene and a subsequent forced save also completed normally |
| Decouple blur persistence from scene-file refresh (Phase 1B.1a) | Complete | The public `forceSave()` facade keeps its historical save-plus-scene-refresh behavior for scripts, manual save, and recovery callers. Its implementation now delegates to a private policy method, and only the window-blur path selects persistence without `loadSceneFiles()`. Runtime validation confirmed that blur persisted the edit with `refreshSceneFiles=0` and no blur-attributed scene-file request, while manual titlebar save retained `refreshSceneFiles=1` and its matching scene-file request. Disk serialization, backup scheduling, autoexport policy, embed-update notification, busy-save handling, active image/embeddable guards, and public method arguments remain unchanged |
| Linearize save synchronization and metadata lookup (Phase 1B.2a) | Complete | Save synchronization now indexes current linked non-text and text elements in one scene pass instead of filtering the full scene once per stored link/text entry. Markdown metadata generation builds a unique-ID index once, retaining the previous exactly-one-match rule for text-element links. Binary-file cleanup uses `Set<FileId>` membership in both the view snapshot and embedded-data registries. Map iteration and serialized section ordering, first-match behavior, save APIs, scene mutation ordering, compression, and persistence policy are unchanged. MOC EA testing exercised deletion cleanup, linked-text/image persistence, classification fallback, loader completion, and Canvas teardown. A Sidecar-off SYL run at the original 3,654-element/1,734-text/169-file scale reduced average synchronization from 183.96 ms to 37.20 ms and metadata generation from 76.44 ms to 2.60 ms. Coherent snapshot plumbing and mutation-sensitive duplicate-image grouping remain separate checkpoints |
| Index image elements by current file ID during save synchronization (Phase 1B.2b) | Complete | `syncFiles()` now builds its image list, original file-ID iteration snapshot, registry-membership set, and `FileId → image elements` groups in one scene traversal. Duplicate splitting keeps the historical original-ID iteration order and newest-element comparator while moving each reassigned element between live groups, so later duplicates see only elements that still carry the original ID. The final scene-file/Mermaid classification pass reads the same mutation-aware groups rather than filtering the full scene once per binary file. Registry rules for ordinary embedded files, equations, Mermaid, Markdown images, hyperlinks/local links, and fresh pasted images are unchanged. Runtime testing split three ordinary duplicates of one equation into three durable registry entries, then removed one cleanly. Sidecar-off SYL synchronization fell from the Phase 1B.2a 37.20 ms average/52.10 ms maximum to 15.50/19.60 ms |
| Reuse one coherent save snapshot through synchronization and serialization (Phase 1B.2c) | Complete | Each actual save now captures app state, the scene, selected-element IDs, and deleted elements once. Synchronization consumes the selected IDs from that app-state capture; a synchronization-triggered `loadDrawing()` and Markdown serialization consume the same deleted-element set; serialization consumes the same scene object that synchronization updates. The public `getScene()` and `prepareGetViewData()` signatures and fallback behavior remain unchanged through private helpers. The popout/view-unload workaround deliberately retains its second serialization call and delayed vault write, but both serializations now use the same save-owned snapshot. Compatibility-mode saves also serialize that one snapshot. Runtime validation covered the mutation-sensitive equation split, popout delayed-write workaround, deleted-element cleanup, compatibility serialization, and same-scale SYL save/reopen. The observed inline-link-suggester interruption was traced to the pre-existing body mutation observer saving when the suggester mounts, outside this snapshot checkpoint |
| Coalesce drawing-backup persistence by vault path (Phase 1B.3a) | Complete | The main-window-owned `ImageCache` now delegates delayed drawing backups to a plugin-global `BackupPersistenceQueue`. Each path retains at most one active IndexedDB transaction and the latest trailing payload; a new queued payload replaces an obsolete one while preserving the existing 50 ms post-save delay. Backup writes now resolve on transaction completion rather than request scheduling. Rename flushes queued data before moving the backup key, deletion and backup-cache clearing cancel queued data after any active transaction settles, and plugin unload drops timers/references without starting new writes. Image-cache clearing remains independent. Save diagnostics distinguish scheduling, coalescing, and completed physical writes. Runtime validation covered popout/main timer ownership, two completed IndexedDB transactions, rename/save/reopen, deletion, and package/loader lifecycle. Timing-sensitive replacement, trailing-write, flush, and pending-cancellation branches are covered by the deterministic queue harness. Autoexport policy and general save-reason semantics remain separate Phase 1B.3 checkpoints |
| Make save side-effect policy explicit (Phase 1B.3b) | Complete | The public `save()` and `forceSave()` facades retain their signatures and behavior while delegating to private policy-aware implementations. A force-save policy now independently states whether to refresh scene files and whether to run save-time autoexport; save diagnostics carry the originating reason and selected autoexport policy through request, export scheduling, and completion. The window-blur path remains persistence-only with respect to scene-file loading, but deliberately retains SVG/PNG/Excalidraw autoexport and `onTriggerAutoexportHook`: repository documentation promises autoexport each time a drawing is saved, so the handoff's contract exception applies. Runtime validation confirmed that blur persisted and autoexported without a scene-file refresh, manual save retained both behaviors, and close/reopen restored all edits |
| Extract view save coordination without changing semantics (Phase 1B.4a) | Complete | Added a view-scoped `ViewSaveCoordinator` that owns the existing public-save and force-save routing, explicit side-effect policies, dirty-state transitions, autosave timer/function, and teardown/navigation force-save orchestration. `ExcalidrawView` retains compatibility delegates and its `TextFileView`-bound serialization/disk-write body; the externally accessed `autosaveTimer` and `autosaveFunction` properties remain available through accessors. The shared save/autosave/dirty semaphores, timer intervals, busy-wait limits, notices, Excalibrain unload exception, blur/manual policies, loader refresh behavior, and close ordering are mechanically unchanged. Runtime validation covered autosave, manual and blur force-save policies, main↔popout migration, teardown persistence, runtime deletion, and durable reopen with all five edits. Revision tracking, in-flight coalescing, and `flush()` remain the separate Phase 1B.4b checkpoint |
| Preserve edits made during persistence with revision/coalescing semantics (Phase 1B.4b) | Complete | `ViewSaveCoordinator` now advances a monotonic current revision from Excalidraw durable store increments and existing explicit dirty calls, records the revision owned by each save request, and advances the saved revision only after persistence, an unchanged terminal result, or the established view-unload scheduled-write handoff. One save loop owns at most one active request and one merged trailing request. Edits during synchronization/compression remain dirty and update that trailing request; an overlapping request already satisfied by the active revision is discarded without reaching the old `save.skipped` path. Manual force-save busy/notice behavior remains compatible. `flush()` waits for the loop and force-persists any revision still dirty before close or migration; the Electron delayed view-unload write remains intact. Runtime validation on SYL exercised a manual save followed by edits during compression, continued editing across successive trailing saves, final convergence to the newest revision, immediate close/reopen, and the inline `[[` regression. Serialization snapshots, side-effect policies, loader behavior, and popout runtime ownership are unchanged |
| Persist dirty window migrations before source teardown | Complete | `onWindowMigrated()` now marks migration and terminates view loaders before closing the old view. It synchronously captures the coherent scene, deleted elements, files, app-state subset, and selected-element IDs while the source API is valid, then unmounts the source React root before the first asynchronous synchronization/compression step. Main→popout may persist through the stable main realm. Popout→main performs no final drawing-file write from the source callback: it registers only serialized drawing text and stable leaf/path identifiers in a bounded 15-second, one-shot plugin manager; the replacement main-window view consumes and persists that text before parsing it. No view, DOM node, Window, React runtime, or package lease crosses the boundary. The migration callback owns the single teardown flush; later generic `onClose()` and `onUnloadFile()` safeguards skip their redundant migration saves. Retired sources reject blur-save side effects and vault-modify synchronization after unmount. Runtime validation confirmed dirty migration in both directions without freezes, lost edits, unusable replacement views, or Excalidraw console errors; close/reopen confirmed durable persistence. Ordinary autosave, manual save, file navigation, public facades, and the existing delayed non-migration unload workaround remain unchanged |
| Cancel image-loading work across runtime teardown | Complete | Rapid migration before MOC EA finished loading exposed one non-fatal `null.scheduleAction` rejection. A progressive `addFiles()` call had already started component-owned image decoding when the old runtime unmounted; the fork's Obsidian teardown nulled its store before that decode resumed. The plugin now cancels its deferred initialization callback, rejects loader work unless the initiating API identity and file path are still current, and fences `addFiles()` immediately before publication. Published fork version `0.18.127` stops a completed decode from touching store/scene state after `componentWillUnmount()`. Migration still unmounts before its first await; it never waits for image completion. No persisted data, file format, batching size, or public API changed. Repeated rapid MOC EA migration attempts with edits before image completion preserved all data and did not reproduce the console rejection; the plugin's installed production and development artifacts exactly match the locally validated fork build |
| Restore progressive live-view image presentation | Complete; deeper warm-cache work parked | The live view now prioritizes image file IDs intersecting the initial viewport and publishes loaded assets in batches of at most eight, allowing the owning window two animation frames between immediately available batches. Export, automation, and deferred-validation loaders retain their existing unbounded collection behavior. MOC EA displayed its first image after about one second in the settled run and completed after about eight seconds; the startup-contention run displayed the first image after about four seconds and completed after about ten. Panning remains choppy while loading because later `addFiles()` calls still block for up to 346 ms and individual cached SVG materialization waits reached 1.25 seconds. Do not broaden this checkpoint into image-payload caching; profile and address warm-cache materialization only after the window-runtime migration direction is settled |
| 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 |
| 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" |
### Action log
| 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. 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 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 |
| 2026-08-25 | Implemented Phase 1B.4a mechanical `ViewSaveCoordinator` extraction | Audited public and internal `save()`, `forceSave()`, `forceSaveIfRequired()`, dirty-state, autosave, unload/close, window-blur, link-navigation, synchronization, and external timer call sites before editing. The new view-scoped coordinator owns orchestration while the view retains the `super.save()`-dependent serialization implementation and thin compatibility delegates. `FileManager` can still read, clear, and invoke `autosaveTimer`/`autosaveFunction`; all paths still share the existing view semaphores. Internal autosave and teardown requests still re-enter the public `save()` facade, preserving interception compatibility. No revision, coalescing, cache, migration, loader, export, or serialization behavior was added | Production build and bundle syntax pass with the unchanged 33 Rollup circular warnings. The new coordinator has zero targeted ESLint findings; `ExcalidrawView.ts` retains its exact 18 pre-existing unsafe-type findings, and full lint remains exactly 138 errors/0 warnings. `npm run code:unused`, the repository `npm run madge`, and `git diff --check` pass. The diagnostic bundle is 4,843,770 bytes, 1,785 bytes above the preceding scanner-cleanup checkpoint and 399,110 bytes below 5 MiB. Runtime acceptance is one small disposable drawing: validate one autosave, one manual titlebar force-save, one window-blur save, one unsaved close/reopen, and one main-to-popout-to-main migration with a dirty edit during the return. The trace must retain the expected direct/manual reasons and blur/manual scene-refresh policy; each save must reach either normal completion or the existing view-unload scheduled-write terminal path, every force-save and loader must complete, the dirty indicator must clear after ordinary completed persistence, and every edit must survive reopen. This targets coordinator routing, public facade compatibility, timer ownership, and the teardown path without repeating MOC EA/SYL performance, missing-asset, backup-queue, autoexport-output, or repeated memory-cycle tests |
| 2026-08-25 | Cleared Obsidian CodeScanner's nine `globalThis` popout warnings | Audited all four `PackageManager` and five Phase 0 diagnostic references against the per-window runtime architecture and the existing Rollup-injected `mainDocument`/`deliberateFetch` exceptions. No injection workaround was needed. Package comparison requires the plugin bundle's main realm, already represented by unqualified `window` throughout the same manager; renaming `setPackage(window, ...)` to `setPackage(win, ...)` makes that comparison unambiguous. Performance diagnostics are intentionally one main-window-owned singleton, so local-storage enablement, heap/timing reads, and the manual console checkpoint now use `window` with a narrow `PerformanceDiagnosticsWindow` extension. No package ownership, host-adapter lifetime, persistence, timing, or diagnostic payload changed | Targeted ESLint passes with zero findings in both changed files; `rg globalThis src` returns no matches. Full `npm run code` improved from 138 errors/9 warnings to the same 138-error backlog and zero warnings. Production build, bundle syntax, `npm run code:unused`, `npm run madge`, and `git diff --check` pass with the unchanged 33 Rollup circular warnings. The bundle is 4,841,985 bytes, 60 bytes smaller than commit `67352c99` and 400,895 bytes below 5 MiB. A separate manual test is not warranted for scanner-only lexical substitutions; the next popout-bearing runtime test should simply retain the existing diagnostic assertions that the main package is labelled `main`, a migrated runtime is labelled `popout`, the popout package is deleted on return, and `EXCALIDRAW_PERF_PHASE0_CHECKPOINT()` remains callable from the main DevTools console |
| 2026-08-24 | Runtime-validated and closed the inline `[[` suggester/save race | During the original reproduction, two equations and an actively edited text/link produced numerous scene changes while `saveRequest.count` remained at its earlier value of one; opening and using the body-portaled link suggester therefore caused no observer save or synchronization reload. After the text was committed and the final dirty edit was made, opening the real command-palette modal produced the expected `save.request reason=direct force=0 preventReload=1 dirty=1`. Synchronization deliberately reported `changed=1`, reloaded outside text-edit mode, serialized two equations plus one text element, completed the disk/backup writes, and the subsequent reopen parsed all four scene elements and loaded both equation files | The fix covers the reported interruption and preserves the adjacent modal durability safeguard. The modal-triggered save completed in 163.80 ms; its scene loader and the reopen loader both reached `terminalState=completed`. Teardown released the main package lease and purged Canvas nodes to zero. The filtered trace contains no failure marker. No further MOC EA, SYL, popout, export, backup, or mobile test is required before Phase 1B.4 |
| 2026-08-24 | Fixed the pre-Phase-1B.4 inline `[[` suggester/save race | Reconfirmed the exact lifecycle before editing. `SuggestionModal.open()` appends `.suggestion-container` directly to the input's document body. `ObserverManager` observed every direct body child addition and, despite its modal-specific name and comment, never checked the added node's identity; on a dirty drawing it called `save()`. After an equation duplicate made synchronization report a change, that unintended save called `loadDrawing()` and ended text editing before the suggester could be used. The observer now requires the sole added node to be a cross-window-safe `Element` matching `.modal-container`. This preserves the intended pre-modal save for Settings, command palette, and other Obsidian modals while excluding suggestion, menu, popover, and other body portals. Added a concise 2.27.0 release-note fix; no locale string or public API changed | Targeted ESLint is clean for `ObserverManager.ts` and `Messages.ts`. Production build and bundle syntax pass with the unchanged 33 Rollup circular warnings; `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains exactly 138 errors/9 warnings. The combined diagnostic bundle is 4,842,045 bytes, 243 bytes above the runtime-validated Phase 1B.3b build and 400,835 bytes below 5 MiB. Runtime acceptance must pair the original reproduction with the adjacent high-risk safeguard: create and duplicate a LaTeX formula, begin a text element, type `[[`, confirm the suggester opens without any save or loss of text editing, choose one suggestion, and continue typing; then commit the text, make one more dirty edit, immediately open the command palette, and confirm the real modal still triggers and completes a save. Close/reopen must retain the link and final edit. No MOC EA, SYL, popout, loader, export, backup, or mobile rerun is required |
| 2026-08-24 | Runtime-validated and closed Phase 1B.3b | The small SVG-autoexport drawing exercised one window-blur save and one titlebar save between the supplied checkpoints. Blur recorded `refreshSceneFiles=0 triggerAutoexport=1`, persisted two elements, scheduled/completed SVG export in 20.40 ms, and issued no `force-save:window-blur` scene-file request. Manual titlebar save recorded `refreshSceneFiles=1 triggerAutoexport=1`, persisted three elements, scheduled/completed SVG export in 17.00 ms, and completed the matching scene-file request. Closing and reopening parsed all three elements | The trace meets both policy branches and the documented autoexport contract. All three physical saves and SVG exports completed; every scene loader reached `terminalState=completed`; the main package lease released/reacquired normally; no failure marker appears. The initial setup save used the public default `reason=unspecified`, which is expected and outside the two policy assertions. The user separately confirmed the previously diagnosed inline `[[` race remained present; it is now the isolated correctness checkpoint immediately above, before Phase 1B.4 |
| 2026-08-24 | Implemented Phase 1B.3b explicit save side-effect policy | Audited every `save()`, `forceSave()`, private force-save-policy call, autoexport branch, export-manager delegate, and `onTriggerAutoexportHook` reference before editing. The first candidate was to suppress autoexport on window blur, but the README and hook TSDoc establish that autoexport is a save-time user contract. The implementation therefore separates `refreshSceneFiles` from `triggerAutoexport` without changing either public facade: ordinary/public force saves select both; window blur selects no scene-file refresh but retains autoexport. The save-owned diagnostic reason now reaches `save.request`, `autoexport.scheduled`, and `save.complete`, while force-save request/completion records both policy dimensions. A private suppression path exists for a future genuinely internal durability reason, but no existing save category is silently opted into it | Production build and `node --check dist/main.js` pass on Node 22.22.2 with the unchanged 33 Rollup circular warnings. `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains at exactly 138 errors and 9 warnings; targeted `ExcalidrawView.ts` lint retains its exact 18 pre-existing unsafe-type findings with none on a changed line. The diagnostic bundle is 4,841,802 bytes, 915 bytes above Phase 1B.3a and 401,078 bytes below 5 MiB. Runtime acceptance is deliberately one small main-window drawing with SVG autoexport enabled: establish its SVG with a manual save, edit once and blur the Obsidian window, then confirm the edit persists and the SVG updates. The trace must show `reason=window-blur refreshSceneFiles=0 triggerAutoexport=1`, `autoexport.scheduled reason=window-blur kind=svg`, and no `sceneFiles.request reason=force-save:window-blur`. Make a second edit and use the titlebar save once; confirm `reason=manual-titlebar refreshSceneFiles=1 triggerAutoexport=1`, a matching forced scene-file request, an SVG update, and durable reopen. This targets the highest-risk public autoexport regression without repeating MOC EA, SYL, popout, loader, backup, or mobile tests |
| 2026-08-24 | Runtime-validated and closed Phase 1B.3a | A manual popout titlebar save scheduled a 9,430-byte backup with `coalesced=0`; the IndexedDB transaction completed 3.50 ms after its 50 ms delay, and the drawing returned to main/reopened with all eight elements. After the file was renamed, a second main-window titlebar save scheduled 9,756 bytes and completed its backup transaction in 4.80 ms; close/reopen parsed all nine elements. The disposable drawing then deleted and closed normally. Final diagnostics reported exactly two backup schedules and two physical writes, with no `backupCoalesced` count, `ImageCache.backupWrites` failure, or other error | Runtime integration confirms that the main-window-owned queue continues after a popout save, transaction-completion callbacks fire, renamed drawings persist, and deletion does not introduce a lifecycle error. The run did not place a second payload inside the 50 ms pending window and deletion occurred after the second write completed, so runtime did not exercise `coalesced=1` or pending cancellation; the deterministic harness remains the evidence for latest-payload replacement, one-active/one-trailing ordering, maximum concurrency one, flush, and pending cancellation. All seven scene loaders reached `terminalState=completed`; the popout package was deleted on return to main; Canvas purges reached zero. No SYL/MOC timing or export retest was required |
| 2026-08-24 | Implemented Phase 1B.3a plugin-global drawing-backup queue | Audited all backup reads/writes/removals, save scheduling, file rename/delete handlers, cache clearing, plugin unload, and autoexport side effects before editing. Added a dependency-injected `BackupPersistenceQueue` keyed by vault path rather than by view, because the same drawing can be represented by multiple views or migrate between windows. Scheduling replaces the pending payload/callback, permits only one IndexedDB transaction plus one trailing latest payload, and keeps the historical 50 ms delay. `ImageCache.addBAKToCache()` now awaits transaction completion. File rename flushes the path first; deletion and backup-cache clear cancel queued data and wait for an active write; image-cache clear deliberately does not touch backups; unload clears timers without starting more persistence. The view's existing backup diagnostics now emit `coalesced=0/1` and count physical writes separately. Export behavior is unchanged | A deterministic queue harness passed latest-payload replacement, one-active/one-trailing ordering, maximum concurrency of one, callback replacement, pending cancellation, and immediate flush. Targeted ESLint passes for the new queue, `ImageCache.ts`, and `FileManager.ts`; `ExcalidrawView.ts` retains exactly its 18 pre-existing findings. Production build and bundle syntax pass with the unchanged 33 Rollup circular warnings. `npm run code:unused`, `npm run madge`, and `git diff --check` pass; full lint remains exactly 138 errors/9 warnings. The final build is 4,840,887 bytes, 2,360 bytes above Phase 1B.2c and 401,993 bytes below 5 MiB. Runtime acceptance is intentionally small: use one disposable non-empty drawing, move it to a popout, make one edit and manually save, and wait for matching `backup.scheduled coalesced=0` plus `backup.complete`; return it to main and reopen to confirm persistence. Make another edit/manual save and immediately rename the file; after 200 ms, close/reopen the renamed drawing and confirm the edit. Finally make one more edit/manual save and immediately delete the disposable drawing; there must be no unfiltered error or later backup completion for that canceled save. Share the filtered Phase 0 trace and report any unfiltered error. This covers the highest-risk main-window timer ownership, transaction completion, rename flush, and delete cancellation without repeating SYL, MOC EA, loader, export, or repeated-migration tests |
| 2026-08-24 | Runtime-validated and closed Phase 1B.2c | In a popout disposable drawing, equation creation/duplication caused the expected synchronization change, and both retained view-unload serialization calls reported `snapshotReused=1`/`snapshotMs=0`; reopening in main restored all three equations and the linked text. After deleting one equation and blur-saving, serialization reused the snapshot with one deleted element, and reopen restored the two remaining equations. A compatibility-mode blur save serialized one reused snapshot and reopened all eight elements. The Sidecar-off SYL save serialized/reopened 3,655 elements, 1,734 text entries, and 169 embedded files | SYL synchronization was 22.40 ms and metadata generation 5.40 ms: modestly above the Phase 1B.2b two-run averages but below its 37.20/52.10 ms pre-indexing acceptance reference, and respectively 87.8%/92.9% below the Phase 0 baselines. `save.serialize` reported `snapshotReused=1 snapshotMs=0`; all relevant loaders completed, the popout package was deleted, and the user reported no unfiltered errors. The user also reproduced an inline `[[` suggester interruption after duplicating an equation. Its trace shows `save.request force=0 preventReload=1 autosaving=0`, followed by `syncChanged=1` and `save.syncLoadDrawing`. Code tracing identifies the broad pre-existing `ObserverManager` body-child mutation hook: the suggester appends its `.suggestion-container` to `body`, the observer saves the dirty drawing, and equation duplicate synchronization reloads the scene, ending text editing. Snapshot reuse occurs only after that reload decision and did not cause the race; any fix belongs in a separate correctness checkpoint with modal/command-palette regression coverage |
| 2026-08-24 | Implemented Phase 1B.2c coherent save snapshot plumbing | Traced every `prepareGetViewData()`, `getScene()`, and `syncElements()` caller, the Markdown/compatibility serialization branches, synchronization-triggered `loadDrawing()`, selected-ID mutation, deleted-element concatenation, Markdown-image forced persistence, and the long-standing Electron popout-unload workaround. `save()` now obtains one app-state object, builds its scene from that object, and captures deleted elements in the same measured snapshot stage. It reuses those values for synchronization, reload, and serialization. `getSceneWithAppState()` and `prepareGetViewDataFromSnapshot()` are private; existing public facades retain their exact signatures and still capture current state when called independently. The view-unload path retains both compression calls and the 200 ms delayed write rather than removing an incompletely understood workaround | Production build and bundle syntax pass on Node 22.22.2 with the unchanged 33 Rollup circular warnings. `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains at exactly 138 errors and 9 warnings; targeted `ExcalidrawView.ts` lint retains its 18 pre-existing unsafe-type findings with none on a changed line. The diagnostic bundle is 4,838,527 bytes, 296 bytes above Phase 1B.2b and 404,353 bytes below 5 MiB. Runtime acceptance is risk-based: in a disposable Markdown drawing already moved to a popout, create one equation, ordinarily duplicate it twice, add linked text, and immediately close the popout without a deliberate save; after the delayed write, reopen in main and verify all three equations and the linked text. Delete one equation, make another visible edit, blur-save, and reopen to verify two equations plus the edit. This covers synchronization change, deleted elements, metadata, and view-unload persistence. Then make/save/reopen one edit in a disposable legacy `.excalidraw` file to guard compatibility serialization. Finally, after a plugin reload, make one Sidecar-off SYL blur save: its `save.serialize` record must show `snapshotReused=1 snapshotMs=0`, synchronization must remain near the Phase 1B.2b 15.50 ms average/19.60 ms maximum, and the drawing must reopen with the edit. In Markdown mode `save.serialize files=0` is expected because the reused sync-owned scene has already cleared transient binary payloads; embedded-file registries and reopened images must remain intact. No MOC EA, broad loader, package-lease, or repeated save test is required |
| 2026-08-24 | Runtime-validated and closed Phase 1B.2b | In a disposable drawing, one equation was ordinarily duplicated twice before the first save. Synchronization reported `changed=1` for three elements, serialization recorded `equations=3`, the synchronization reload reached `terminalState=completed` with all three binary files, and close/reopen parsed three elements and emitted all three equations. After deleting one, synchronization again reported `changed=1`, serialization recorded two active equations plus one deleted element, and the final close/reopen parsed and emitted exactly two. On SYL, two Sidecar-off blur saves at 3,655–3,656 elements/1,734 texts/169 embedded files averaged 15.50 ms in `saveSyncElements` with a 19.60 ms maximum | Duplicate split and cleanup behavior passed the mutation-sensitive regression. SYL synchronization improved 58.3% from Phase 1B.2a's 37.20 ms average and 62.4% from its 52.10 ms maximum; relative to Phase 0's 183.96 ms average, the combined 1B.2 indexing work is 91.6% lower. Metadata remained stable at 2.30 ms average. Both blur saves retained `refreshSceneFiles=0`, completed in 762.10/780.10 ms, and compression was stable at 676.40/676.20 ms. The initial 169-file loader and later 14-file synchronization loader both completed, and the filtered traces contain no failure marker |
| 2026-08-24 | Implemented Phase 1B.2b mutation-aware image grouping | Audited `syncFiles()` and all duplicate-image, equation, Mermaid, Markdown-image, pasted-image, URL/local-file, registry, loader, and explicit independent-duplicate paths before editing. One initial scene pass now constructs ordered images, the immutable original `fileIds` traversal, the membership set, and live file-ID groups. When the legacy duplicate logic assigns a new ID, it still sorts a copy of the current original-ID group with the exact prior comparator, mutates the same newest element, removes it from that group, and adds it to the new-ID group. This preserves repeated-duplicate behavior while eliminating both filter-inside-loop scene scans. A deterministic 5,000-case comparison, including equal timestamps and groups of two through nine duplicates, produced identical final element-to-file-ID assignments | Production build and bundle syntax pass on Node 22.22.2 with the unchanged 33 Rollup circular warnings. `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains at exactly 138 errors and 9 warnings; targeted `ExcalidrawData.ts` lint retains its 16 pre-existing unsafe-type findings with none on a changed line. The diagnostic bundle is 4,838,231 bytes, 145 bytes above Phase 1B.2a and 404,649 bytes below 5 MiB. Runtime acceptance is deliberately narrow: in a disposable drawing create one LaTeX equation and use ordinary Excalidraw duplication twice so three elements initially share its file ID; blur-save, close/reopen, verify all three render, delete one, blur-save, close/reopen, and verify two remain. This targets the mutation-sensitive registry split and cleanup behavior. Then run two small-edit blur saves on SYL with Sidecar off; `saveSyncElements` should not exceed the Phase 1B.2a 37.20 ms average/52.10 ms maximum and should improve if the removed file scans were material. No MOC EA, popout, general loader, linked-text, or ordinary image-deletion retest is required. Share the filtered diagnostic trace and whether any unfiltered errors appeared |
| 2026-08-24 | Runtime-validated and closed Phase 1B.2a on SYL without iPad Sidecar | Two blur saves on SYL contained 3,655–3,656 elements, 1,734 text entries, and 169 embedded files, matching the Phase 0 scale. `saveSyncElements` averaged 37.20 ms (52.10 ms maximum), down 79.8% from the 183.96 ms baseline. `serializeMetadata` averaged 2.60 ms (3.70 ms maximum), down 96.6% from 76.44 ms. Both saves persisted and completed; blur retained `refreshSceneFiles=0`; the initial 169-file load and subsequent 14-file synchronization load both reached `terminalState=completed` | The two changed hot paths comfortably beat the predefined 92/38 ms acceptance thresholds. Stringify averaged 40.55 ms versus the earlier 19.22 ms despite being untouched. Compression was 1,808.50 ms on its first worker use and 742.10 ms on the second, making total-save averages unsuitable for attributing this checkpoint; the warm second compression is near the historical 654.54 ms average. The filtered trace contains no lifecycle failure marker. Use the maintainer's drawing names going forward: MOC EA is the image-focused 245-element/46-file regression drawing; SYL is the text-heavy 3,654-element/1,734-text/169-file performance drawing |
| 2026-08-24 | Runtime-validated Phase 1B.2a correctness on MOC EA | Four completed saves on the 245–246-element/131-text MOC EA scene averaged 2.90 ms in `saveSyncElements`, 1.55 ms in `serializeMetadata`, 10.92 ms in stringify, 162.05 ms in compression, and 226.85 ms total. The first deletion save correctly reported `changed=1`, serialized 45 rather than 46 embedded files, and preserved one deleted element through its synchronization reload. After close/reopen the scene parsed with 246 elements and 45 embedded files. Three window-blur saves retained `refreshSceneFiles=0`; all seven loader runs reached `terminalState=completed`; both view teardowns removed Canvas nodes linearly to zero; the previously fixed transient classification fallback was exercised once | The changed registry-cleanup and durable-reopen paths are accepted on MOC EA, and the trace contains no lifecycle failure marker. This run is correctness evidence rather than the Phase 0 timing comparison; performance closure came from the separate same-scale SYL run |
| 2026-08-24 | Implemented Phase 1B.2a single-pass save indexes | Traced all `syncElements()`, `generateMD*()`, `prepareGetViewData()`, and scene snapshot call sites before changing the hot loops. `updateElementLinksFromScene()` and `updateTextElementsFromScene()` now share indexes built in one scene traversal; each index keeps the first eligible element for an ID, matching the former filtered-array `[0]` behavior. Metadata generation uses a fresh unique-ID index and stores `null` for duplicate IDs, preserving the prior requirement that a text-element link is serialized only when exactly one scene element has that ID. File registry and scene snapshot cleanup use sets rather than repeated array membership scans. No async boundary, save facade, output-section iteration order, duplicate-image mutation, or snapshot ownership changed | The raw Phase 0 round-2 source log establishes the comparison point on SYL at 3,654 elements/1,734 texts/169 files: five saves averaged 183.96 ms in `saveSyncElements`, 76.44 ms in `serializeMetadata`, 19.22 ms in stringify, 654.54 ms in compression, and 969.00 ms total. Production build passes on Node 22.22.2 with the unchanged 33 Rollup circular warnings; `node --check dist/main.js`, `npm run code:unused`, `npm run madge`, and `git diff --check` pass. Full lint remains at the exact 138-error/9-warning baseline with no finding on a changed line. The diagnostic bundle is 4,838,086 bytes, 260 bytes above the preceding checkpoint and 404,794 bytes below 5 MiB. Runtime acceptance deliberately splits risk coverage: MOC EA covers linked-text/image deletion and durable reopen; SYL provides the same-scale hot-path timing comparison |
| 2026-08-24 | Runtime-validated stable known-file classification and declassification | In the exact deconstruct/close/same-tab-edit/Back reproduction, the child save completed at 32,380.5 ms and parent loading began at 32,392.9 ms while metadata frontmatter was unavailable. `file.classificationFallback extension=md` fired once during parent parsing and once when the scene-file loader classified the embedded child; `knownExcalidrawFileFallback.count=2`. The loader then emitted the updated Excalidraw image normally, and the maintainer confirmed that the parent immediately displayed both circles instead of a Markdown embeddable. After removing the Excalidraw frontmatter from the disposable child and allowing metadata to refresh, it rendered as ordinary Markdown | The declassification checkpoint retained `knownExcalidrawFileFallback.count=2` with no third fallback, proving the metadata event removed the stable-set entry rather than leaving a stale Excalidraw classification. The declassified Markdown asset still loaded normally through the Markdown-rendering path. Every loader reached a terminal state and there was no `sceneFiles.loaderStalled`. The maintainer reported the issue resolved. This closes the separate correctness checkpoint without changing Phase 1B save policy |
| 2026-08-24 | Stabilized previously confirmed Excalidraw-file classification during transient metadata-cache gaps | Traced the exact deconstruct/save/back-navigation reproduction through file creation, metadata registration, same-leaf unload save, parent parsing, embedded-file classification, targeted dependency refresh, rename/delete handling, and every `isExcalidrawFile()` caller. The existing `excalidrawFiles` set already records files confirmed by metadata and removes them on a metadata `changed` event without Excalidraw frontmatter or on deletion. `isExcalidrawFile()` now consults live parsed frontmatter first; only when frontmatter is unavailable does it use that stable set. This avoids the observed Markdown misclassification without turning raw vault reads or arbitrary filename heuristics into a synchronous classification path. A temporary path-free diagnostic records fallback use | Production build passes with the unchanged 33 Rollup circular warnings; targeted `FileManager.ts` ESLint, `npm run code:unused`, `npm run madge`, bundle syntax, and `git diff --check` pass. Full lint remains at the exact 138-error/9-warning baseline. The bundle is 4,837,826 bytes, 173 bytes above Phase 1B.1a and 405,054 bytes below 5 MiB. Runtime acceptance: repeat the exact deconstruct → close child → same-tab open → add an unsaved second circle → Back sequence; the parent must immediately render the child as an Excalidraw image with both circles, and the trace should contain `file.classificationFallback extension=md` or `knownExcalidrawFileFallback.count>=1`. Then verify an ordinary Markdown embed still renders as Markdown. Finally, in a disposable drawing remove the `excalidraw-plugin` frontmatter, wait for metadata refresh, and confirm it is no longer opened/rendered as Excalidraw; this is the highest-risk stale-classification regression |
| 2026-08-24 | Runtime-validated Phase 1B.1a and isolated a pre-existing metadata-classification race | Window blur produced a forced disk write in 186.7 ms, completed with `refreshSceneFiles=0`/`loadSceneFilesMs=0`, and did not issue `sceneFiles.request reason=force-save:window-blur`. After reopen, the persisted scene contained the edit. Manual titlebar save then completed in 81.2 ms with `refreshSceneFiles=1` and a matching `force-save:manual-titlebar` loader run, preserving the compatibility path. The backing-image regression exercise uncovered a separate reproducible same-tab navigation race: the child save completed at 61,853.8 ms and parent `setViewData` began at 61,854.7 ms. The parent initially rendered the child as Markdown, then rendered it correctly after close/reopen | Phase 1B.1a acceptance passed for both the changed blur path and the preserved public/manual path. The race is not caused by Phase 1A/1B: navigation saved through the long-standing `forceSaveIfRequired()` path, while `PluginFileManager.isExcalidrawFile()` has relied solely on the live metadata cache since 2024. At the failing load, the parent parsed nine elements/one embedded file and its loader completed normally, consistent with a wrong transient file classification rather than a stalled loader or lost child save. The child was durably saved with two elements before navigation, explaining why reopening after metadata-cache convergence renders both circles correctly. Treat the classification fix as its own checkpoint rather than combining it with save-path optimization |
| 2026-08-24 | Decoupled window-blur persistence from scene-file refresh while preserving the public force-save facade (performance Phase 1B.1a) | Audited every `forceSave()`, `save()`, and `loadSceneFiles()` caller plus script/documentation references before changing behavior. Public and internal callers use `forceSave()` primarily as a disk-persistence guarantee, but some manual/recovery paths may depend on its historical refresh side effect. To avoid changing that compatibility surface, `forceSave()` still selects the original policy. A private policy method now makes the refresh decision explicit, and only the measured persistence-only window-blur callback selects `refreshSceneFiles=false`. The blur save still performs forced serialization, backup/autoexport behavior, embed-update notification, semaphore handling, and all existing active-tool guards | Production build passes with the unchanged 33 Rollup circular warnings; `node --check dist/main.js`, `npm run code:unused`, and `npm run madge` pass. Full lint retains the exact 138-error/9-warning baseline; targeted `ExcalidrawView.ts` lint retains its prior 18 unsafe-type errors with none on the new lines. The bundle is 4,837,653 bytes, 137 bytes above the Phase 1A.3 diagnostic bundle and 405,227 bytes below 5 MiB. Runtime acceptance is deliberately narrow and risk-based: edit a drawing, blur Obsidian, wait for the save, reopen it and confirm the edit persisted; the trace must contain `forceSave.request reason=window-blur refreshSceneFiles=0` and a completed forced save, with no `sceneFiles.request reason=force-save:window-blur`. Then use the manual save button once and confirm it still records `refreshSceneFiles=1` plus a matching `sceneFiles.request`, protecting the public/manual compatibility path. Finally change one already-visible backing image file and confirm the existing targeted synchronization refresh updates it; this guards the highest-impact adjacent regression without repeating broad image/popout testing |
| 2026-08-24 | Validated the Phase 1A.3 loader checkpoint on SYL and MOC EA | The first capture, despite its `large-terminal` checkpoint label, was MOC EA: it emitted all 46 files and completed normally in 9.05 seconds. Its subsequent command-save request started with no active loader and completed in 1.6 ms, demonstrating that completion released the loader and later work could advance. The later capture, despite its `normal` label, was SYL, the prior failure scene: it emitted all 169 files in five batches and completed normally in 7.51 seconds. The new diagnostic split identified zero missing vault files and three external/local entries, explaining why the missing-vault retry path was not applicable | All three `sceneFiles.runStart` records have matching `sceneFiles.runComplete terminalState=completed` records; there is no `sceneFiles.loaderStalled`, MOC EA closed cleanly to zero Canvas nodes, and the maintainer reported no unfiltered errors. This validates the normal terminal path, guards against false timeouts on both workloads, and shows SYL no longer leaves the manager wedged. Because every task settled, this run did not force the 30-second watchdog or exercise a missing-vault-file retry; those branches retain structural/build validation and should be targeted if an actual stalled or missing-vault case recurs rather than manufacturing another broad manual test now |
| 2026-08-24 | Bounded stalled scene-file loaders and isolated missing-file recovery (performance Phase 1A.3) | The raw 169-file capture published 168 files within about 16 seconds, then left one PromisePool task and `activeLoader` alive for the remainder of the run while six later requests queued. `EmbeddedFilesLoader` now resets a 30-second watchdog whenever any pool task settles; no-progress expiry marks the loader timed out, prevents late task results from being published, emits one final callback, clears PDF resources, and lets `ViewSceneFileManager` release the exact active loader and run its latest coalesced request. Every normal/failure/termination path records a terminal state. The retry loop now distinguishes missing vault files from URL/local-link entries and reloads only the missing IDs, preserving sync recovery without repeatedly touching a stalled external asset | Repeated production builds pass with the unchanged 33 Rollup circular warnings. Targeted ESLint is clean for `EmbeddedFileLoader.ts` and `ViewSceneFileManager.ts`; `npm run code:unused`, `npm run madge`, bundle syntax, and CRLF-aware `git diff --check` pass. Full `npm run code` retains the exact repository baseline of 138 errors and 9 warnings, with no finding in either changed loader file. The diagnostic bundle is 4,837,516 bytes, 405,364 bytes below 5 MiB. Runtime validation must use the same 169-file drawing: the initial request must reach `sceneFiles.runComplete terminalState=completed` or `timed-out`, `activeLoader` must be zero on a later checkpoint, a subsequent targeted/sync request must start rather than remain queued, and the 168 resolvable images must stay visible. Then make one missing vault image available and confirm its whitelisted retry loads it without a full-scene reload. The highest-risk regression is a false timeout during legitimate slow generation, so also open the fully resolvable 46-file representative drawing and confirm it completes normally without `sceneFiles.loaderStalled` |
| 2026-08-24 | Closed Phase 1A.2 and the Phase 1A.1 multi-view ownership risk after maintainer validation | Individual deletion emitted `before=7 after=6 mapEntryDeleted=1`; undo recreated node 7 and the embed remained usable. Main-window and both popout teardowns removed all seven nodes in order down to zero, after which purge remained zero. The added lifecycle markers showed unload, close request, and close completion with live file/root state. In the shared popout, acquiring the second view raised leases to 2; closing the first emitted `leases=1` with no package deletion and left the sibling usable; closing the second emitted exactly one popout deletion and `leases=0` | All requested diagnostic criteria passed and the maintainer reported no unfiltered console errors. Phase 1A.2 is complete and the explicit lease mechanism is validated for both repeated single-view migration and multiple views sharing one popout runtime. The separate retained-heap result remains open. The maintainer explicitly directed that `npm audit fix` must not be run because it previously caused runtime problems; the reported audit findings are believed to be development dependencies |
| 2026-08-24 | Fixed individual Canvas-node retention (performance Phase 1A.2) | Traced the sole `removeNode()` call from `CustomEmbeddable` plus the duplicate-ID replacement, clear, unload, migration, and destroy/purge paths. Individual cleanup now deletes the entry keyed by the Excalidraw element ID instead of incorrectly using `node.file.path`. It checks node identity before deleting that key so a stale effect cleanup cannot remove a newer replacement, and retains an identity-scan fallback for compatibility. No loader, save, package, or migration-handoff behavior was combined into this checkpoint. Added timing-only close/unload entry records because the supplied capture contained no final-tab-close marker, and installed the maintainer-authorized Madge development dependency without changing the existing script | Production builds pass with the unchanged 33 Rollup circular warnings; `node --check dist/main.js`, `npm run code:unused`, and CRLF-aware `git diff --check` pass. The diagnostic bundle is 4,835,882 bytes, 406,998 bytes below 5 MiB. Targeted lint is clean for `CanvasNodeFactory.ts`; the combined check reports only the pre-existing unsafe ref assignment at `CustomEmbeddable.tsx:1480`, outside the changed cleanup, while `ExcalidrawView.ts` retains exactly its existing 18 unsafe-type findings with none on the new diagnostic lines. The repository Madge script passes but covers only 8 root files; a supplemental TypeScript-aware run processes 229 source files and records a structural inventory of 46 cycles. Runtime acceptance requires one individual embedded Canvas/Markdown deletion to change the diagnostic map size by exactly one, undo to recreate a usable node, and final view teardown to leave zero nodes without a double-dispose error |
| 2026-08-24 | Reviewed the maintainer's Phase 1A.1 five-round-trip runtime capture | Across ten migrations the trace records five popout package creations and five deletions; `packageWindows` oscillates between 1 and 2 and every final popout lease reaches zero, validating explicit map/lease ownership for the single-view path. All ten post-baseline scene-file runs reached `runComplete`, so there is no new loader regression in this fully resolvable 46-file scene. Individual Canvas cleanup still remained `before=7 after=7 mapEntryDeleted=0`, confirming the separate Phase 1A.2 defect | The pre-test checkpoint was 841.95 MB and post-close forced GC was 1278.84 MB, a +436.89 MB delta versus the Phase 0 +435.63 MB result; retained-heap acceptance therefore did not improve. The capture has no final main-view `view.closeComplete` marker after cycle 5, so it cannot cleanly distinguish a missed final close from other retained popout/runtime references. The drawing had zero unresolved embedded files and therefore does not validate the Phase 1A.3 missing-asset path. Before closing 1A.1, run one two-view/same-popout lease test: closing the first view must leave one lease and a usable sibling; only the final release may delete the package |
| 2026-08-24 | Implemented explicit per-view ownership for window-scoped React/Excalidraw packages (performance Phase 1A.1) | Added a documented `PackageLease` contract and `PackageManager.acquirePackage()`. Each view captures its acquisition window and releases the lease after its React root and other window-bound resources are torn down. Releases are idempotent; multiple Excalidraw views in one window share a reference count; the last popout release disposes both typed host registrations and removes that window's package; the main runtime remains pinned for startup/fallback use. Removed the lifecycle decision that used the view's mutable post-migration `ownerWindow`, while retaining `getPackage()`/`deletePackage()` compatibility facades. No Canvas-node, loader, save, or migration-handoff behavior was combined into this checkpoint | The pre-change production build passed on Node 22.22.2 with the established 33 circular warnings and produced a 4,834,315-byte diagnostic bundle. Post-change production builds and `node --check dist/main.js` pass with the same warning baseline; `npm run code:unused` and `git diff --check` pass. Full `npm run code` retains the recorded repository baseline of 138 errors and 9 warnings, with no finding on a new lease/type/facade/view line. Targeted lint leaves only four Phase 0 `globalThis` diagnostic warnings in `PackageManager.ts`; `main.ts`/`ExcalidrawView.ts` retain their pre-existing no-unsafe findings. `npm run madge` remains unavailable because the dependency is not installed. The final bundle is 4,835,213 bytes (+898 bytes, 407,667 bytes below 5 MiB). Required runtime validation is five main↔popout round trips with Phase 0 diagnostics: package windows must oscillate with the active window set, every abandoned popout must emit final-lease/package deletion, sibling views in one popout must keep the runtime until the last closes, and final close plus forced GC must return heap substantially closer to the 842.00 MB baseline than the prior 1277.63 MB result. Also smoke-test cold startup, plugin reload, a restored popout, and moving a leaf in both directions; cross-window runtime deletion while a sibling view is still active is the highest-impact risk. Mobile needs only a basic open/close regression because native popout migration is desktop-specific |
| 2026-08-24 | Added Phase 0 performance diagnostics before the save/memory/popout optimization work | Added an opt-in `performanceDiagnostics` utility and instrumented the existing save, serialization/compression, image/scene-file, export, package, Canvas-node, view lifecycle, and window-migration paths. All records are emitted through the existing debug logger as one flat string prefixed `EXCALIDRAW_PERF_PHASE0`; no vault contents or file paths are logged. High-frequency `onChange`/full-scene-hash measurements are aggregated instead of logging per callback, and summaries are activity-driven rather than timer-driven to avoid introducing a diagnostic lifecycle leak | Full runtime validation requires the repository dependencies and Obsidian. In the provided VM, dependency installation remains blocked by registry DNS (`EAI_AGAIN`), so the production Rollup build cannot be completed here. Global TypeScript parsing reaches only the missing `node` type-definition blocker (`TS2688`) with no syntax diagnostics in the modified sources. Runtime capture is the next checkpoint and should cover continuous drawing/autosave, manual/blur save, image-heavy cold/warm load, main↔popout migration, and repeated open/close/migration memory behavior |
| 2026-08-24 | Extended Phase 0 diagnostics after reviewing the four baseline captures | Added stable scene-file `reason=` attribution across initial/reload, forced-save, sync, theme, ExcalidrawAutomate, retry, and active-leaf-validation paths; request records now include current API binary-file count, missing API files, unresolved embedded-file count, and explicit retry scheduling/execution. Warm cache reads now aggregate IndexedDB-read, dependency-check, cache-resolution, SVG Blob-read/parse/data-URL, raster object-URL, and total materialization durations plus cache-rejection reasons. `EXCALIDRAW_PERF_PHASE0_CHECKPOINT(label)` emits an on-demand flat-text summary/heap checkpoint for use immediately after DevTools forced GC. No save/image/migration behavior was optimized or fixed in this step | Local full build remains unavailable in the provided VM because the dependency tree cannot be completed through the blocked npm registry. Validate in the maintainer environment with `npm run dev`/`npm run build`, then rerun the focused save/reason, warm-cache, popout, and forced-GC lifecycle captures described with this checkpoint |
| 2026-08-23 | Removed duplicate native tooltips from registered element actions | Stopped assigning an HTML `title` attribute to buttons created for `registerElementActionProvider()` while retaining the action title as the button's `aria-label`. This follows the existing Excalidraw icon-button behavior: the styled tooltip remains, Chromium no longer creates a second native tooltip, and assistive technology keeps the accessible name | Targeted lint, production build, bundle syntax, and `git diff --check` are required before handoff. Highest-risk manual check: hover a registered action long enough for the browser tooltip delay and confirm exactly one styled tooltip appears; then inspect the button and confirm it has `aria-label` but no `title`. Also activate the action once to confirm pointer handling is unchanged |
| 2026-08-23 | Made declarative-settings breadcrumbs touch-accessible on Obsidian Mobile | Replaced the link-styled breadcrumb buttons with native anchors using Obsidian's `onClickEvent` convention, prevented the shared internal-hash delegate from processing the same activation, and added manipulation touch behavior plus mobile/tablet-only tap-target padding. Desktop remains visually compact, keyboard activation remains native, and failed unpublished navigation disables the anchor without leaving a live hash target. Removed the advanced underline thickness/offset styling flagged by Obsidian CodeScanner while retaining the basic underline on internal settings links | Targeted lint, production build, bundle syntax, and `git diff --check` are required before handoff. Highest-risk validation is unintended duplicate navigation or page jumps: tap a parent and the Excalidraw root breadcrumb on one physical phone, then click both once on desktop and activate one with the keyboard. Mobile emulation alone is insufficient because it did not reproduce the reported issue |
| 2026-08-23 | Finalized the 2.27.0 beta.5 release notes and declarative-settings handoff | Reordered the release notes to lead with user-visible settings improvements, followed by upstream Excalidraw features, fixes, maintenance, and Excalidraw Automate APIs. Consolidated implementation-heavy wording into a concise explanation that this is one of the plugin's largest internal maintenance releases, covering the settings and persistence architecture, lifecycle and manager boundaries, runtime packaging, React 19, and cache performance. Preserved the maintainer's `manifest-beta.json` bump to `2.27.0-beta.5` | Targeted release-note ESLint, production build, bundle syntax, and `git diff --check` pass. The leaner release notes reduce the final bundle by a further 1,722 bytes. The exact beta.5 build is 4,798,339 bytes, 73,417 bytes raw and 24,492 bytes gzip above a clean `master` build, and remains 444,541 bytes below 5 MiB |
| 2026-08-23 | Implemented declarative-settings checkpoint 7 and reviewed the complete branch against `master` | Removed the five checkpoint-numbered page factories in favor of semantic page-family names and made legacy rendering consume one `getSettingsPages()` result. Moved filename, grid, TODO, and embed/auto-export component references from tab lifetime into a state object owned by one generated settings tree, preserving live cross-control behavior without retaining detached controls after a rebuild. Removed the unused cached declaration array, the unused adapter batch method, unused action/group/file/folder/color/textarea compatibility branches, the unused `navigateToSearchResult` declaration, an unnecessary changed return type, and an unreferenced toolbar class. Deduplicated the recovery prompt's button construction. Review also found that Markdown export rebuilt declarations through the live binding adapter; separated export-only builds from live binding registration so selecting **Copy settings** cannot redirect later changes to an unmounted tree. Retained the default-enabled `useDeclarativeSettings` compatibility preference, legacy DOM Markdown export, persistence/recovery safeguards, guarded unpublished navigation, and custom integrated renderers because each remains actively required. Final source-map attribution shows that the branch's raw bundle growth is primarily `settings.ts` (about 35.6 KB), compressed/generated payloads including maintained locale additions (about 12.1 KB), English setting text (about 6.9 KB), settings recovery management (about 7.9 KB across manager/store/prompt/writer/validation), the binding and dual-render adapters (about 5.7 KB), Markdown export/navigation (about 2.2 KB), and release notes (about 0.7 KB); no new runtime dependency accounts for the increase | A clean `master` production build is 4,724,922 bytes. After final release-note cleanup, the branch build is 4,798,339 bytes: +73,417 bytes raw and +24,492 bytes gzip, while remaining 444,541 bytes below 5 MiB. Cleanup reduced the branch by 2,450 bytes from 4,800,789. Targeted ESLint and private-member/reference audits pass for every cleanup file; `npm run code:unused`, `npm run build`, `npm run lib`, bundle syntax, `git diff --check`, and unchanged Obsidian `1.8.7` pins pass. Full `npm run code` retains the established 138-error repository backlog with no finding in a cleanup file; the production build retains the established 33 circular-dependency warnings. Maintainer authorized the final commit; the most focused post-commit smoke scenarios remain copying declarative settings before mutating a dependent control, exercising auto-export/embed-option and dynamic-grid dependencies in legacy mode, and confirming filename-preview updates from both filename controls and Compatibility mode |
| 2026-08-23 | Combined declarative-settings checkpoints 5 and 6: final layout/search and activation audit | Confirmed the hierarchy already follows the approved grouping rule and retained the persisted compatibility preference as a supported debugging/user fallback rather than transitional code. The complete non-empty definition tree is returned only on Obsidian 1.13+ when that preference is enabled; otherwise the empty-array contract deliberately invokes the shared legacy renderer. Renamed the last `Converted` helpers and replaced their obsolete pre-activation TSDoc. Audited sibling page names across every shipped locale and found no collisions. Russian alone lacked four maintained page metadata strings, so Fonts, its description, Offline CJK support, and PDF Export Settings now remain localized instead of falling back to English. Audited rendered/integrated declarations for aliases and confirmed utilities, breadcrumbs, videos, descriptions, and Mastery are marked non-searchable so filtered results are not crowded | Targeted ESLint, `npm run code:unused`, production build, bundle syntax, `git diff --check`, the locale-path audit, and unchanged Obsidian `1.8.7` pins pass. `dist/main.js` is 4,800,789 bytes, only 79 bytes larger than the completed 4E build. Maintainer validation confirmed ordinary and integrated search results, deep page navigation and clickable breadcrumbs, and restart switching between searchable and legacy layouts in both directions. The final checkpoint will compare the complete branch against `master` and attribute/remediate bundle growth |
+1 -1
View File
@@ -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",
+4 -4
View File
@@ -13,7 +13,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.126",
"@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.126",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.126.tgz",
"integrity": "sha512-0uxBrGHO53VBVcESjtXGxJpGenyQfEDzdYskOS75rENrx/Z/pcZ0WGSiMmrEmYSgNKKwcIioivwREzjL4kSxow==",
"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
View File
@@ -30,7 +30,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.126",
"@zsviczian/excalidraw": "0.18.128",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
+304
View File
@@ -0,0 +1,304 @@
#!/usr/bin/env bash
# generate-repository-zip.sh
#
# Run from the root of a repository:
#
# bash generate-repository-zip.sh
#
# Generates:
# ./repository.zip
#
# The ZIP preserves the repository-relative directory structure while excluding:
# - node_modules, dist, and other ignored folders
# - __MACOSX folders
# - .DS_Store and other ignored filenames
# - common binary/media/archive/executable file types
# - files detected as binary even if their extension is unknown
#
# Requirements:
# - bash
# - find
# - file
# - zip
#
# Edit IGNORE_DIRS, IGNORE_FILENAMES, and IGNORE_EXTENSIONS below to customize.
set -euo pipefail
OUTPUT="repository.zip"
# ---------------------------------------------------------------------------
# Folder exclusions
# ---------------------------------------------------------------------------
# Folder names are matched at any depth.
IGNORE_DIRS=(
".git"
".svn"
".hg"
"node_modules"
"dist"
".next"
".nuxt"
".cache"
".parcel-cache"
".turbo"
".idea"
".vscode"
".tools"
"coverage"
"build"
"out"
"output"
"secrets"
".claude"
"__MACOSX"
)
# ---------------------------------------------------------------------------
# Filename exclusions
# ---------------------------------------------------------------------------
# Exact filenames are matched at any depth.
IGNORE_FILENAMES=(
".DS_Store"
"Thumbs.db"
"REPOSITORY_STRUCTURE.md"
"REPOSITORY_CONTENTS.md"
# Never package a previously generated repository archive.
"repository.zip"
)
# ---------------------------------------------------------------------------
# File-type exclusions
# ---------------------------------------------------------------------------
# Extensions are lowercase and include the leading dot.
IGNORE_EXTENSIONS=(
# Images
".png"
".jpg"
".jpeg"
".gif"
".webp"
".bmp"
".tif"
".tiff"
".ico"
".icns"
".avif"
".heic"
".heif"
".svg"
".svgz"
# PDF / ebook / office containers
".pdf"
".epub"
".doc"
".docx"
".xls"
".xlsx"
".ppt"
".pptx"
# Audio
".mp3"
".wav"
".flac"
".aac"
".m4a"
".ogg"
".opus"
".wma"
# Video
".mp4"
".mov"
".mkv"
".avi"
".webm"
".m4v"
".mpeg"
".mpg"
# Fonts
".ttf"
".otf"
".woff"
".woff2"
".eot"
# Archives / compressed files
".zip"
".tar"
".gz"
".tgz"
".bz2"
".xz"
".7z"
".rar"
# Native binaries / executables / compiled objects
".exe"
".dll"
".so"
".dylib"
".bin"
".com"
".app"
".msi"
".o"
".obj"
".a"
".lib"
".class"
".jar"
".war"
".wasm"
".node"
# Binary databases / data formats
".db"
".sqlite"
".sqlite3"
".parquet"
".arrow"
".feather"
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
contains_exact() {
local needle="$1"
shift
local item
for item in "$@"; do
[[ "$needle" == "$item" ]] && return 0
done
return 1
}
path_has_ignored_dir() {
local relative_path="$1"
local dir
for dir in "${IGNORE_DIRS[@]}"; do
if [[ "$relative_path" == "$dir/"* || "$relative_path" == *"/$dir/"* ]]; then
return 0
fi
done
return 1
}
is_ignored_filename() {
local filename="$1"
contains_exact "$filename" "${IGNORE_FILENAMES[@]}"
}
is_ignored_extension() {
local filename="$1"
local lower
lower="$(printf '%s' "$filename" | tr '[:upper:]' '[:lower:]')"
local ext
for ext in "${IGNORE_EXTENSIONS[@]}"; do
[[ "$lower" == *"$ext" ]] && return 0
done
return 1
}
looks_binary() {
local file_path="$1"
# Empty files are harmless text-like repository artifacts.
[[ ! -s "$file_path" ]] && return 1
# `file --mime-encoding` returns "binary" for binary data on macOS/Linux.
local encoding
encoding="$(file -b --mime-encoding "$file_path" 2>/dev/null || true)"
[[ "$encoding" == "binary" ]]
}
# ---------------------------------------------------------------------------
# Build file list
# ---------------------------------------------------------------------------
command -v zip >/dev/null 2>&1 || {
echo "Error: 'zip' is required but was not found." >&2
exit 1
}
command -v file >/dev/null 2>&1 || {
echo "Error: 'file' is required but was not found." >&2
exit 1
}
TMP_LIST="$(mktemp)"
trap 'rm -f "$TMP_LIST"' EXIT
included=0
skipped_binary=0
skipped_type=0
skipped_name=0
skipped_dir=0
while IFS= read -r -d '' full_path; do
relative_path="${full_path#./}"
filename="${relative_path##*/}"
if path_has_ignored_dir "$relative_path"; then
((skipped_dir += 1))
continue
fi
if is_ignored_filename "$filename"; then
((skipped_name += 1))
continue
fi
if is_ignored_extension "$filename"; then
((skipped_type += 1))
continue
fi
if looks_binary "$full_path"; then
((skipped_binary += 1))
continue
fi
printf '%s\n' "$relative_path" >> "$TMP_LIST"
((included += 1))
done < <(find . -type f -print0)
# Remove any previous archive before creating the new one.
rm -f "$OUTPUT"
if [[ ! -s "$TMP_LIST" ]]; then
echo "No files matched the inclusion rules; no ZIP created."
exit 0
fi
# -q quiet
# -@ read file paths from stdin
#
# Repository-relative paths are stored in the archive, not absolute paths.
zip -q "$OUTPUT" -@ < "$TMP_LIST"
echo "Created $OUTPUT"
echo "Included files: $included"
echo "Skipped because of ignored folders: $skipped_dir"
echo "Skipped because of ignored filenames: $skipped_name"
echo "Skipped because of ignored file types: $skipped_type"
echo "Skipped because binary content was detected: $skipped_binary"
+63 -4
View File
@@ -66,7 +66,7 @@ import {
} from "./managers/MarkdownPostProcessor";
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes";
import { DeviceType, Packages } from "../types/types";
import { DeviceType, PackageLease, Packages } from "../types/types";
import { PaneTarget } from "../types/utilTypes";
import {
emulateCTRLClickForLinks,
@@ -112,6 +112,16 @@ import { PluginSettingsManager } from "./managers/PluginSettingsManager";
import { FooterSafeAreaManager } from "./managers/FooterSafeAreaManager";
import { FontManager } from "./managers/FontManager";
import { StartupTimer } from "./managers/StartupTimer";
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;
@@ -158,6 +168,8 @@ 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>();
public fourthFontLoaded: boolean = false;
@@ -201,6 +213,9 @@ 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<
FileId,
{
@@ -221,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);
@@ -977,6 +992,8 @@ 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();
terminateCompressionWorker();
@@ -1224,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() {
@@ -1240,10 +1257,52 @@ export default class ExcalidrawPlugin extends Plugin {
return this.packageManager.getPackage(win);
}
/** Acquires explicit ownership of the runtime package for one view window. */
public acquirePackage(win: Window): PackageLease {
return this.packageManager.acquirePackage(win);
}
public deletePackage(win: Window) {
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,
): void {
this.viewMigrationPersistenceHandoffManager.register(handoff);
}
/** Consumes serialized drawing text for the replacement main-window view. */
public consumeViewMigrationPersistenceHandoff(
leafId: string,
filePath: string,
): string | null {
return this.viewMigrationPersistenceHandoffManager.consume(
leafId,
filePath,
);
}
/** Discards a handoff when the old view could not be replaced. */
public discardViewMigrationPersistenceHandoff(leafId: string): void {
this.viewMigrationPersistenceHandoffManager.discard(leafId);
}
get taskbone() {
return this.commandManager?.taskbone;
}
+7 -1
View File
@@ -136,6 +136,12 @@ export class EventManager {
),
);
//theme/snippet toggles can change header/toolbar heights and shift the canvas
//without firing layout-change; refresh cached canvas offsets the same way
this.registerEvent(
this.app.workspace.on("css-change", () => this.onLayoutChangeHandler()),
);
//File Save Trigger Handlers
//Save the drawing if the user clicks outside the Excalidraw Canvas
const onClickEventSaveActiveDrawing = (e: PointerEvent) =>
@@ -343,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();
+24 -9
View File
@@ -79,6 +79,16 @@ export class PluginFileManager {
});
}
/**
* Returns whether a vault file is an Excalidraw drawing.
*
* Parsed frontmatter is authoritative when available. During a vault write,
* Obsidian can temporarily remove that frontmatter from the metadata cache;
* in that gap, retain the last confirmed classification from
* {@link excalidrawFiles}. The metadata `changed` event updates that set, so
* deliberately removing the Excalidraw frontmatter still declassifies the
* file once the replacement metadata is published.
*/
public isExcalidrawFile(f: TFile): boolean {
if (!f) {
return false;
@@ -86,11 +96,12 @@ export class PluginFileManager {
if (f.extension === "excalidraw") {
return true;
}
const fileCache = f ? this.plugin.app.metadataCache.getFileCache(f) : null;
return (
!!fileCache?.frontmatter &&
!!fileCache.frontmatter[FRONTMATTER_KEYS.plugin.name]
);
const frontmatter = this.plugin.app.metadataCache.getFileCache(f)?.frontmatter;
if (frontmatter) {
return !!frontmatter[FRONTMATTER_KEYS.plugin.name];
}
return this.excalidrawFiles.has(f);
}
//managing my own list of Excalidraw files because in the onDelete event handler
@@ -622,7 +633,10 @@ export class PluginFileManager {
const excalidrawViews = getExcalidrawViews(this.app);
excalidrawViews.forEach((excalidrawView) => {
void (async () => {
if (excalidrawView.semaphores?.viewunload) {
if (
excalidrawView.semaphores?.viewunload ||
excalidrawView.semaphores?.windowMigrating
) {
return;
}
if (
@@ -718,12 +732,13 @@ export class PluginFileManager {
return;
}
//this will not work in the short period when Obsidian is starting up, however
//this will only effect a very few files, statistically unlikely to cause
//much/any real user impact.
//a proper queuing feels overkill for this.
//this will only affect very few files, statistically unlikely to cause
//much/any real user impact. Flush the shared queue so a recently scheduled
//backup is moved with the drawing instead of later recreating the old key.
if (!getImageCache().isReady()) {
return;
}
await getImageCache().flushPendingBAK(oldPath);
const backup = await getImageCache().getBAKFromCache(oldPath);
if (backup) {
await getImageCache().addBAKToCache(newPath, `${backup}`);
+6 -8
View File
@@ -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(
[
+57 -21
View File
@@ -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,51 +283,70 @@ 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;
}
this.removeModalContainerObserver();
}
//The user clicks settings, or "open another vault", or the command palette
//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 ||
!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,
});
}
@@ -321,8 +356,9 @@ export class ObserverManager {
return;
}
this.modalContainerObserver.disconnect();
this.activeViewDoc = null;
this.modalContainerObserver = null;
this.modalObservedView = null;
this.activeViewDoc = null;
}
private addWorkspaceDrawerObserver() {
+133 -136
View File
@@ -1,6 +1,6 @@
import { updateExcalidrawLib } from "src/constants/constants";
import { ExcalidrawLib } from "../../types/excalidrawLib";
import { Packages } from "../../types/types";
import { PackageLease, Packages } from "../../types/types";
import { Notice } from "obsidian";
import type ExcalidrawPlugin from "src/core/main";
import { errorHandler } from "../../utils/ErrorHandler";
@@ -22,19 +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 commonHostDisposerMap = new Map<Window, () => void>();
private excalidrawHostDisposerMap = new Map<Window, () => void>();
private runtimePackage: Packages | null = null;
private packageLeaseCountMap = new Map<Window, number>();
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
@@ -48,7 +55,7 @@ export class PackageManager {
) => typeof ExcalidrawLib
>(
`(function(React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime) {
${this.EXCALIDRAW_PACKAGE};
${excalidrawPackage};
return ExcalidrawLib;
})`,
"PackageManager constructor - excalidrawLib initialization",
@@ -73,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");
}
@@ -88,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");
@@ -119,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 (
@@ -136,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 (
@@ -162,136 +173,126 @@ 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(window: 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(window, pkg);
this.configureObsidianExcalidrawHost(window, pkg);
this.configureObsidianCommonHost(pkg);
this.configureObsidianExcalidrawHost(pkg);
} catch (error: unknown) {
this.disposeObsidianHosts(window);
this.disposeObsidianHosts();
throw normalizeError(error);
}
this.packageMap.set(window, 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;
}
/**
* Gets a package for a window, creating it if necessary
* with robust error handling
* Acquires the shared runtime while retaining the view's actual window.
*
* @remarks
* 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 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;
public acquirePackage(win: Window): PackageLease {
const packages = this.getPackage(win);
const leaseCount = (this.packageLeaseCountMap.get(win) ?? 0) + 1;
this.packageLeaseCountMap.set(win, leaseCount);
let released = false;
return {
window: win,
packages,
release: () => {
if (released) {
return;
}
// If package exists but is invalid, delete it so we can recreate it
this.deletePackage(win);
released = true;
this.releasePackageLease(win);
},
};
}
/** Releases one view-owned package lease without consulting mutable DOM. */
private releasePackageLease(win: Window): void {
const leaseCount = this.packageLeaseCountMap.get(win);
if (leaseCount === undefined) {
return;
}
const remainingLeases = Math.max(0, leaseCount - 1);
if (remainingLeases === 0) {
this.packageLeaseCountMap.delete(win);
if (win !== window) {
this.removeRuntimeAlias(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");
} else {
this.packageLeaseCountMap.set(win, remainingLeases);
}
}
/**
* 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 {
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),
@@ -300,23 +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.commonHostDisposerMap.clear();
this.excalidrawHostDisposerMap.clear();
this.EXCALIDRAW_PACKAGE = "";
this.fallbackPackage = null;
this.packageLeaseCountMap.clear();
this.runtimeAliasWindows.clear();
this.disposeObsidianHosts();
this.runtimePackage = null;
react = null;
reactDOM = null;
+42 -9
View File
@@ -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()));
}
}
@@ -0,0 +1,95 @@
const DEFAULT_HANDOFF_TTL_MS = 15_000;
export interface ViewMigrationPersistenceHandoff {
leafId: string;
filePath: string;
data: string;
}
interface ViewMigrationPersistenceHandoffEntry extends ViewMigrationPersistenceHandoff {
expiresAt: number;
}
/**
* Owns bounded serialized drawing handoffs from a destroyed popout view to
* the replacement view in Obsidian's main window.
*
* Entries contain drawing text and stable identifiers only. They never retain
* a view, DOM node, React runtime, package lease, or Window. Consumption is
* one-shot, and abandoned entries expire promptly.
*/
export class ViewMigrationPersistenceHandoffManager {
private readonly entries = new Map<
string,
ViewMigrationPersistenceHandoffEntry
>();
private cleanupTimer: number | null = null;
/** Registers or replaces the pending drawing text for one workspace leaf. */
public register(handoff: ViewMigrationPersistenceHandoff): void {
this.pruneExpired();
this.entries.set(handoff.leafId, {
...handoff,
expiresAt: Date.now() + DEFAULT_HANDOFF_TTL_MS,
});
this.scheduleCleanup();
}
/** Consumes matching drawing text exactly once. */
public consume(leafId: string, filePath: string): string | null {
this.pruneExpired();
const entry = this.entries.get(leafId);
if (!entry) {
return null;
}
this.entries.delete(leafId);
this.scheduleCleanup();
return entry.filePath === filePath ? entry.data : null;
}
/** Discards an abandoned handoff after a failed view replacement. */
public discard(leafId: string): void {
this.entries.delete(leafId);
this.scheduleCleanup();
}
/** Clears retained text and its main-window cleanup timer. */
public destroy(): void {
if (this.cleanupTimer !== null) {
window.clearTimeout(this.cleanupTimer);
this.cleanupTimer = null;
}
this.entries.clear();
}
private pruneExpired(): void {
const now = Date.now();
for (const [leafId, entry] of this.entries) {
if (entry.expiresAt <= now) {
this.entries.delete(leafId);
}
}
}
private scheduleCleanup(): void {
if (this.cleanupTimer !== null) {
window.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 = window.setTimeout(
() => {
this.cleanupTimer = null;
this.pruneExpired();
this.scheduleCleanup();
},
Math.max(0, nextExpiry - Date.now()),
);
}
}
+8 -4
View File
@@ -596,12 +596,14 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}
const targetPath = pagePath.slice(0, index);
const link = breadcrumbs.createEl("button", {
const link = breadcrumbs.createEl("a", {
text: segment,
href: "#",
cls: "excalidraw-settings-breadcrumbs__link",
attr: { type: "button" },
});
link.addEventListener("click", () => {
link.onClickEvent((event) => {
event.preventDefault();
event.stopPropagation();
if (
!navigateToSettingsPage(
this.app,
@@ -609,7 +611,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
targetPath,
)
) {
link.disabled = true;
link.removeAttribute("href");
link.setAttribute("aria-disabled", "true");
link.addClass("is-disabled");
}
});
});
+165
View File
@@ -0,0 +1,165 @@
type PendingBackup = {
data: string;
};
type BackupWriteState = {
timer: number | null;
inFlight: Promise<void> | null;
pending: PendingBackup | null;
};
type BackupPersistenceQueueOptions = {
ownerWindow: Window;
write: (filepath: string, data: string) => Promise<void>;
onError?: (error: unknown, stage: "write") => void;
};
/**
* Coalesces plugin-global drawing backups by vault path.
*
* @remarks
* Each path owns at most one IndexedDB write and one latest trailing payload.
* The timer belongs to the main application window because persistent plugin
* storage is shared by main and popout views.
*/
export class BackupPersistenceQueue {
private readonly ownerWindow: Window;
private readonly write: BackupPersistenceQueueOptions["write"];
private readonly onError?: BackupPersistenceQueueOptions["onError"];
private readonly writes = new Map<string, BackupWriteState>();
constructor(options: BackupPersistenceQueueOptions) {
this.ownerWindow = options.ownerWindow;
this.write = options.write;
this.onError = options.onError;
}
/**
* Schedules the latest payload for a path.
*
* @returns `true` when an older pending payload was replaced or the new
* payload was coalesced behind an active write.
*/
public schedule(filepath: string, data: string, delayMs: number): boolean {
let state = this.writes.get(filepath);
if (!state) {
state = { timer: null, inFlight: null, pending: null };
this.writes.set(filepath, state);
}
const coalesced = state.pending !== null || state.inFlight !== null;
state.pending = { data };
this.clearTimer(state);
if (state.inFlight === null) {
this.scheduleDrain(filepath, state, delayMs);
}
return coalesced;
}
/** Writes all currently pending data for one path without the normal delay. */
public async flush(filepath: string): Promise<void> {
const state = this.writes.get(filepath);
if (!state) {
return;
}
this.clearTimer(state);
while (this.writes.get(filepath) === state) {
this.clearTimer(state);
if (state.inFlight !== null) {
try {
await state.inFlight;
} catch {
// The owning drain reports the write failure and releases state.
}
continue;
}
if (state.pending === null) {
break;
}
await this.drain(filepath, state, 0);
}
}
/** Cancels queued data and waits for an already-active write to settle. */
public async cancel(filepath: string): Promise<void> {
const state = this.writes.get(filepath);
if (!state) {
return;
}
this.clearTimer(state);
state.pending = null;
this.writes.delete(filepath);
if (state.inFlight !== null) {
try {
await state.inFlight;
} catch {
// The owning drain reports the write failure; cancellation still wins.
}
}
}
/** Cancels every queued backup before the backup store is cleared. */
public async cancelAll(): Promise<void> {
await Promise.all(
Array.from(this.writes.keys(), (filepath) => this.cancel(filepath)),
);
}
/** Drops timers and references during plugin unload without starting writes. */
public destroy(): void {
this.writes.forEach((state) => this.clearTimer(state));
this.writes.clear();
}
private clearTimer(state: BackupWriteState): void {
if (state.timer !== null) {
this.ownerWindow.clearTimeout(state.timer);
state.timer = null;
}
}
private scheduleDrain(
filepath: string,
state: BackupWriteState,
delayMs: number,
): void {
state.timer = this.ownerWindow.setTimeout(() => {
state.timer = null;
void this.drain(filepath, state, delayMs);
}, delayMs);
}
private async drain(
filepath: string,
state: BackupWriteState,
trailingDelayMs: number,
): Promise<void> {
if (
this.writes.get(filepath) !== state ||
state.inFlight !== null ||
state.pending === null
) {
return;
}
const pending = state.pending;
state.pending = null;
const write = this.write(filepath, pending.data);
state.inFlight = write;
try {
await write;
} catch (error: unknown) {
this.onError?.(error, "write");
} finally {
if (this.writes.get(filepath) === state) {
state.inFlight = null;
if (state.pending !== null) {
this.scheduleDrain(filepath, state, trailingDelayMs);
} else {
this.writes.delete(filepath);
}
}
}
}
}
+2
View File
@@ -29,6 +29,8 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
- Customize color-picker top picks by dragging colors onto the strip; right-click the strip to reset it. [#11872](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11872)
## Fixed
- Moving a dirty drawing out of a popout window now safely transfers and persists its latest edits from the replacement main-window view.
- Opening the command palette or another Obsidian modal reliably saves dirty drawings, while inline link suggestions no longer trigger a save that can end text editing.
- 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.
+217 -40
View File
@@ -103,6 +103,16 @@ declare const mainDocument: Document;
const markdownRendererRecursionWatcthdog = new Set<TFile>();
type CacheValidationMode = "validated" | "stale-first";
const SCENE_FILE_LOAD_STALL_TIMEOUT_MS = 30_000;
const SCENE_FILE_PROGRESSIVE_BATCH_SIZE = 8;
export type EmbeddedFilesLoaderTerminalState =
| "idle"
| "running"
| "completed"
| "terminated"
| "timed-out"
| "failed";
/** Describes the lightweight work required after a stale-first cache hit. */
export type DeferredCacheValidation =
@@ -681,6 +691,7 @@ export class EmbeddedFilesLoader {
private plugin: ExcalidrawPlugin;
private isDark: boolean;
public terminate = false;
public terminalState: EmbeddedFilesLoaderTerminalState = "idle";
public uid: string;
constructor(plugin: ExcalidrawPlugin, isDark?: boolean) {
@@ -868,7 +879,6 @@ export class EmbeddedFilesLoader {
},
})
: undefined;
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
@@ -893,38 +903,39 @@ export class EmbeddedFilesLoader {
};
}
const generatedSVG = await createSVG(
hasFilenameParts
? filenameParts.hasGroupref ||
filenameParts.hasBlockref ||
filenameParts.hasSectionref ||
filenameParts.hasFrameref ||
filenameParts.hasClippedFrameref
? filenameParts.filepath + filenameParts.linkpartReference
: file.path
: file?.path,
false, //false
hasFilenameParts && filenameParts.hasClippedFrameref
? {
...exportSettings,
frameRendering: {
enabled: true,
name: false,
outline: false,
clip: true,
},
}
: exportSettings,
this,
forceTheme,
null,
null,
elements,
this.plugin,
depth + 1,
getExportPadding(this.plugin, file),
);
const svg = replaceSVGColors(
await createSVG(
hasFilenameParts
? filenameParts.hasGroupref ||
filenameParts.hasBlockref ||
filenameParts.hasSectionref ||
filenameParts.hasFrameref ||
filenameParts.hasClippedFrameref
? filenameParts.filepath + filenameParts.linkpartReference
: file.path
: file?.path,
false, //false
hasFilenameParts && filenameParts.hasClippedFrameref
? {
...exportSettings,
frameRendering: {
enabled: true,
name: false,
outline: false,
clip: true,
},
}
: exportSettings,
this,
forceTheme,
null,
null,
elements,
this.plugin,
depth + 1,
getExportPadding(this.plugin, file),
),
generatedSVG,
inFile instanceof EmbeddedFile ? inFile.colorMap : null,
) as SVGSVGElement;
if (this.terminate) {
@@ -1212,14 +1223,15 @@ export class EmbeddedFilesLoader {
? inFile.filenameparts?.linkpartReference
: undefined,
));
const loadedFromCache = isExcalidrawFile
? excalidrawLoadedFromCache
: pdfLoadedFromCache;
return {
mimeType,
fileId: generatedFileId,
dataURL,
created: isHyperLink || isLocalLink ? 0 : file.stat.mtime,
loadedFromCache: isExcalidrawFile
? excalidrawLoadedFromCache
: pdfLoadedFromCache,
loadedFromCache,
hasSVGwithBitmap,
size,
pdfPageViewProps,
@@ -1256,6 +1268,8 @@ export class EmbeddedFilesLoader {
onDeferredValidationCandidates,
deferredCacheValidation,
sceneElements,
waitForRender,
prioritizedFileIds,
}: {
excalidrawData: ExcalidrawData;
addFiles: (files: FileData[], isDark: boolean, final?: boolean) => void;
@@ -1271,12 +1285,36 @@ export class EmbeddedFilesLoader {
) => void;
deferredCacheValidation?: ReadonlyMap<FileId, DeferredCacheValidation>;
sceneElements?: readonly ExcalidrawElement[];
waitForRender?: () => Promise<void>;
prioritizedFileIds?: ReadonlySet<FileId>;
}) {
this.terminalState = "running";
if (this.isDark === undefined) {
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
}
if (depth > 7) {
this.terminalState = "failed";
new Notice(t("INFINITE_LOOP_WARNING") + depth.toString(), 6000);
try {
addFiles([], this.isDark, true);
} catch (error: unknown) {
errorlog({
where: "EmbeddedFileLoader.loadSceneFiles",
uid: this.uid,
phase: "depth-limit",
error,
});
}
return;
}
const entries = Array.from(excalidrawData.getFileEntries());
if (prioritizedFileIds?.size) {
entries.sort(
([fileIdA], [fileIdB]) =>
Number(prioritizedFileIds.has(fileIdB)) -
Number(prioritizedFileIds.has(fileIdA)),
);
}
const markdownImageElements = (
sceneElements ?? excalidrawData.scene.elements
).filter(
@@ -1288,9 +1326,7 @@ export class EmbeddedFilesLoader {
markdownImageElements.map((element) => element.fileId),
);
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,isDark:this.isDark,sceneTheme:excalidrawData.scene.appState.theme});
if (this.isDark === undefined) {
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
}
let onLoadTaskSettled: (() => void) | null = null;
const createSafeLoadTask = (
task: () => Promise<void>,
context: Record<string, unknown>,
@@ -1305,6 +1341,8 @@ export class EmbeddedFilesLoader {
...context,
error,
});
} finally {
onLoadTaskSettled?.();
}
});
const files: FileData[][] = [];
@@ -1637,10 +1675,55 @@ export class EmbeddedFilesLoader {
}
}
const runLoadPool = async (
iterator: Generator<Promise<void>>,
concurrency: number,
): Promise<boolean> => {
let stallTimer: number | null = null;
let resolveStall!: () => void;
const stalled = new Promise<"stalled">((resolve) => {
resolveStall = () => resolve("stalled");
});
const resetStallTimer = () => {
if (stallTimer !== null) {
window.clearTimeout(stallTimer);
}
stallTimer = window.setTimeout(
resolveStall,
SCENE_FILE_LOAD_STALL_TIMEOUT_MS,
);
};
onLoadTaskSettled = resetStallTimer;
resetStallTimer();
const poolCompleted = new PromisePool(iterator, concurrency)
.all()
.then(() => "completed" as const);
const result = await Promise.race([poolCompleted, stalled]);
onLoadTaskSettled = null;
if (stallTimer !== null) {
window.clearTimeout(stallTimer);
}
if (result === "completed") {
return true;
}
this.terminalState = "timed-out";
this.terminate = true;
return false;
};
let finalFlushed = false;
const flushFiles = (
batchFiles: FileData[] | undefined,
final: boolean,
) => {
if (final && finalFlushed) {
return;
}
if (final) {
finalFlushed = true;
}
try {
addFiles(batchFiles, this.isDark, final);
} catch (e: unknown) {
@@ -1648,6 +1731,61 @@ export class EmbeddedFilesLoader {
}
};
let progressivePaintPromise: Promise<void> | null = null;
const flushProgressiveBatch = (): boolean => {
if (
!waitForRender ||
files[batch].length <= SCENE_FILE_PROGRESSIVE_BATCH_SIZE
) {
return false;
}
if (prioritizedFileIds?.size) {
files[batch].sort(
(fileA, fileB) =>
Number(prioritizedFileIds.has(fileB.id)) -
Number(prioritizedFileIds.has(fileA.id)),
);
}
const batchFiles = files[batch]
.splice(0, SCENE_FILE_PROGRESSIVE_BATCH_SIZE)
.filter((f) => emitPolicy === "all" || !f.loadedFromCache);
if (batchFiles.length === 0) {
return false;
}
flushFiles(batchFiles, false);
const paintPromise = Promise.resolve()
.then(waitForRender)
.catch((error: unknown) => {
errorlog({
where: "EmbeddedFileLoader.loadSceneFiles",
phase: "progressive-batch-paint",
error,
});
});
progressivePaintPromise = paintPromise;
void paintPromise.finally(() => {
if (progressivePaintPromise === paintPromise) {
progressivePaintPromise = null;
}
});
return true;
};
const waitForProgressivePaint = async () => {
if (progressivePaintPromise !== null) {
await progressivePaintPromise;
}
};
const drainProgressiveBatches = async () => {
await waitForProgressivePaint();
while (flushProgressiveBatch()) {
await waitForProgressivePaint();
}
};
const addFilesTimer = window.setInterval(() => {
if (this.terminate) {
window.clearInterval(addFilesTimer);
@@ -1656,6 +1794,12 @@ export class EmbeddedFilesLoader {
if (files[batch].length === 0) {
return;
}
if (progressivePaintPromise !== null) {
return;
}
if (flushProgressiveBatch()) {
return;
}
// During deferred validation, only regenerated results should reach addFiles.
const batchFiles = files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
@@ -1670,16 +1814,20 @@ export class EmbeddedFilesLoader {
validationConcurrency ?? this.plugin.settings.renderingConcurrency;
const iterator = loadIterator(this, entries, true, true);
if (!this.terminate) {
await new PromisePool(iterator, concurency).all();
await runLoadPool(iterator, concurency);
}
if (this.terminate) {
if (this.terminalState === "running") {
this.terminalState = "terminated";
}
flushFiles(undefined, true);
return;
}
if (deferredGenerationEntries.length > 0) {
// Publish everything that was available from cache or direct file reads
// before expensive generated SVG work can monopolize the main thread.
await drainProgressiveBatches();
const fastFiles = files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
);
@@ -1699,11 +1847,14 @@ export class EmbeddedFilesLoader {
false,
false,
);
await new PromisePool(deferredIterator, concurency).all();
await runLoadPool(deferredIterator, concurency);
}
}
if (this.terminate) {
if (this.terminalState === "running") {
this.terminalState = "terminated";
}
flushFiles(undefined, true);
return;
}
@@ -1711,15 +1862,41 @@ export class EmbeddedFilesLoader {
if (deferredValidationCandidates.size > 0) {
onDeferredValidationCandidates?.(deferredValidationCandidates);
}
await drainProgressiveBatches();
// Same filter for the final flush so validated cache hits remain a no-op.
const batchFiles = files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
);
// The helper retains the try/catch because the user may have closed the
// view by the time the asynchronous image work completes.
this.terminalState = "completed";
flushFiles(batchFiles, true);
} catch (error: unknown) {
this.terminalState = "failed";
errorlog({
where: "EmbeddedFileLoader.loadSceneFiles",
uid: this.uid,
phase: "pool",
error,
});
const batchFiles = files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
);
flushFiles(batchFiles, true);
} finally {
onLoadTaskSettled = null;
window.clearInterval(addFilesTimer);
if (!finalFlushed) {
if (this.terminalState === "running") {
this.terminalState = this.terminate ? "terminated" : "failed";
}
const batchFiles = this.terminate
? undefined
: files[batch].filter(
(f) => emitPolicy === "all" || !f.loadedFromCache,
);
flushFiles(batchFiles, true);
}
this.emptyPDFDocsMap();
}
}
+6 -1
View File
@@ -3406,7 +3406,12 @@ export class ExcalidrawAutomate {
if (fileIDWhiteList.size > 0) {
this.targetView.setDirty();
await new Promise<void>((resolve) => {
void this.targetView.loadSceneFiles(false, fileIDWhiteList, resolve);
void this.targetView.loadSceneFiles(
false,
fileIDWhiteList,
resolve,
undefined,
);
});
}
}
+247 -60
View File
@@ -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"
> & {
@@ -139,6 +139,11 @@ type ExcalidrawDataScene = Omit<
type RegExpMatchIteratorResult = IteratorResult<RegExpMatchArray, undefined>;
type SceneElementIndexes = {
linkedNonTextElementsById: Map<string, ExcalidrawElement>;
textElementsById: Map<string, Mutable<ExcalidrawTextElement>>;
};
type MarkdownBlockNode = {
type: string;
id?: string;
@@ -246,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;
@@ -312,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
*/
@@ -1111,17 +1246,35 @@ export class ExcalidrawData {
return dirty;
}
private updateElementLinksFromScene() {
private getSceneElementIndexes(): SceneElementIndexes {
const linkedNonTextElementsById = new Map<string, ExcalidrawElement>();
const textElementsById = new Map<
string,
Mutable<ExcalidrawTextElement>
>();
for (const element of this.scene.elements) {
if (element.type === "text") {
if (!textElementsById.has(element.id)) {
textElementsById.set(element.id, element);
}
} else if (element.link && !linkedNonTextElementsById.has(element.id)) {
linkedNonTextElementsById.set(element.id, element);
}
}
return { linkedNonTextElementsById, textElementsById };
}
private updateElementLinksFromScene(
linkedNonTextElementsById: Map<string, ExcalidrawElement>,
) {
for (const key of this.elementLinks.keys()) {
//find element in the scene
const el = this.scene.elements?.filter(
(el: ExcalidrawElement) =>
el.type !== "text" && el.id === key && el.link, //&&
);
if (el.length === 0) {
const element = linkedNonTextElementsById.get(key);
if (!element) {
this.elementLinks.delete(key); //if no longer in the scene, delete the text element
} else {
this.elementLinks.set(key, el[0].link);
this.elementLinks.set(key, element.link);
}
}
}
@@ -1130,21 +1283,20 @@ export class ExcalidrawData {
* update text element map by deleting entries that are no long in the scene
* and updating the textElement map based on the text updated in the scene
*/
private async updateTextElementsFromScene() {
private async updateTextElementsFromScene(
sceneTextElementsById: Map<string, Mutable<ExcalidrawTextElement>>,
) {
for (const key of this.textElements.keys()) {
//find text element in the scene
const el = this.scene.elements?.filter(
(el: ExcalidrawElement) => el.type === "text" && el.id === key,
) as Mutable<ExcalidrawTextElement>[];
if (el.length === 0) {
const element = sceneTextElementsById.get(key);
if (!element) {
this.textElements.delete(key); //if no longer in the scene, delete the text element
} else {
const text = await this.getText(key);
const raw =
this.scene.prevTextMode === TextMode.parsed
? el[0].rawText
: (el[0].originalText ?? el[0].text);
if (text !== (el[0].originalText ?? el[0].text)) {
? element.rawText
: (element.originalText ?? element.text);
if (text !== (element.originalText ?? element.text)) {
const parseRes = await this.parse(text);
this.textElements.set(key, {
raw,
@@ -1384,20 +1536,29 @@ export class ExcalidrawData {
outString += `\n^_dummy!_\n\n`;
}
const textElementLinks = new Map<string, string>();
const uniqueSceneElementsById = new Map<
string,
ExcalidrawElement | null
>();
for (const element of this.scene.elements) {
uniqueSceneElementsById.set(
element.id,
uniqueSceneElementsById.has(element.id) ? null : element,
);
}
for (const key of this.textElements.keys()) {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/566
const element = this.scene.elements.filter(
(el: ExcalidrawElement) => el.id === key,
) as Mutable<ExcalidrawTextElement>[];
const element = uniqueSceneElementsById.get(key) as Mutable<
ExcalidrawTextElement
> | null;
const elementString = this.textElements.get(key).raw;
if (
element &&
element.length === 1 &&
element[0].link &&
(!syncTextLinks || element[0].rawText === element[0].originalText)
element.link &&
(!syncTextLinks || element.rawText === element.originalText)
) {
//if(element[0].link.match(/^\[\[[^\]]*]]$/g)) { //apply this only to markdown links
textElementLinks.set(key, element[0].link);
textElementLinks.set(key, element.link);
//elementString = `%%***>>>text element-link:${element[0].link}<<<***%%` + elementString;
//}
}
@@ -1475,11 +1636,11 @@ export class ExcalidrawData {
sceneJSONstring,
this.disableCompression ? false : this.plugin.settings.compress,
);
const result =
return (
outString +
(this.textElementCommentedOut ? "" : "%%\n") +
drawingSection;
return result;
drawingSection
);
}
generateMDSync(deletedElements: ExcalidrawElement[] = []): string {
@@ -1488,11 +1649,11 @@ export class ExcalidrawData {
sceneJSONstring,
this.disableCompression ? false : this.plugin.settings.compress,
);
const result =
return (
outString +
(this.textElementCommentedOut ? "" : "%%\n") +
drawingSection;
return result;
drawingSection
);
}
public async saveDataURLtoVault(
@@ -1601,33 +1762,49 @@ export class ExcalidrawData {
const scene = this.scene;
//remove files and equations that no longer have a corresponding image element
const images = scene.elements.filter(
(e) => e.type === "image",
) as ExcalidrawImageElement[];
const fileIds = images.map((e) => e.fileId);
const images: Mutable<ExcalidrawImageElement>[] = [];
const fileIds: FileId[] = [];
const imagesByFileId = new Map<
FileId,
Mutable<ExcalidrawImageElement>[]
>();
for (const element of scene.elements) {
if (element.type !== "image") {
continue;
}
images.push(element);
fileIds.push(element.fileId);
const imagesForFile = imagesByFileId.get(element.fileId);
if (imagesForFile) {
imagesForFile.push(element);
} else {
imagesByFileId.set(element.fileId, [element]);
}
}
const fileIdSet = new Set(imagesByFileId.keys());
this.files.forEach((value, key) => {
if (!fileIds.contains(key)) {
if (!fileIdSet.has(key)) {
this.files.delete(key);
dirty = true;
}
});
this.equations.forEach((value, key) => {
if (!fileIds.contains(key)) {
if (!fileIdSet.has(key)) {
this.equations.delete(key);
dirty = true;
}
});
this.mermaids.forEach((value, key) => {
if (!fileIds.contains(key)) {
if (!fileIdSet.has(key)) {
this.mermaids.delete(key);
dirty = true;
}
});
this.markdownImages.forEach((value, key) => {
if (!fileIds.contains(key)) {
if (!fileIdSet.has(key)) {
this.markdownImages.delete(key);
dirty = true;
}
@@ -1644,6 +1821,9 @@ export class ExcalidrawData {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/601
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/593
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/297
// Keep fileIds as the original iteration snapshot, while imagesByFileId
// follows mutations so each later duplicate selects only elements that
// still carry the original ID and the scene.files pass sees current IDs.
const processedIds = new Set<string>();
fileIds.forEach((fileId, idx) => {
if (processedIds.has(fileId)) {
@@ -1683,19 +1863,24 @@ export class ExcalidrawData {
return;
}
const newId = fileid();
(
scene.elements
.filter((el: ExcalidrawImageElement) => el.fileId === fileId)
.sort((a, b) =>
a.updated < b.updated ? 1 : -1,
)[0] as Mutable<ExcalidrawImageElement>
).fileId = newId as FileId;
const newId = fileid() as FileId;
const imagesForFile = imagesByFileId.get(fileId);
const newestImage = imagesForFile
.slice()
.sort((a, b) => (a.updated < b.updated ? 1 : -1))[0];
newestImage.fileId = newId;
imagesForFile.splice(imagesForFile.indexOf(newestImage), 1);
const imagesForNewId = imagesByFileId.get(newId);
if (imagesForNewId) {
imagesForNewId.push(newestImage);
} else {
imagesByFileId.set(newId, [newestImage]);
}
dirty = true;
processedIds.add(newId);
if (embeddedFile) {
this.setFile(
newId as FileId,
newId,
new EmbeddedFile(
this.plugin,
this.file.path,
@@ -1704,7 +1889,7 @@ export class ExcalidrawData {
);
}
if (equation) {
this.setEquation(newId as FileId, {
this.setEquation(newId, {
latex: equation.latex,
isLoaded: false,
});
@@ -1718,9 +1903,7 @@ export class ExcalidrawData {
name?: string;
};
const mermaidElements = getMermaidImageElements(
scene.elements.filter(
(el: ExcalidrawImageElement) => el.fileId === key,
),
imagesByFileId.get(key as FileId) ?? [],
);
if (
!(
@@ -1754,7 +1937,9 @@ export class ExcalidrawData {
result = await this.syncFiles();
this.scene.files = {}; //files contains the dataURLs of files. Once synced these are all saved to disk
}
this.updateElementLinksFromScene();
const { linkedNonTextElementsById, textElementsById } =
this.getSceneElementIndexes();
this.updateElementLinksFromScene(linkedNonTextElementsById);
result =
result ||
this.syncCroppedPDFs() ||
@@ -1762,21 +1947,23 @@ export class ExcalidrawData {
this.setUrlPrefix() ||
this.setShowLinkBrackets() ||
this.findNewElementLinksInScene();
await this.updateTextElementsFromScene();
await this.updateTextElementsFromScene(textElementsById);
return result || this.findNewTextElementsInScene(selectedElementIds);
}
public async updateScene(newScene: string) {
//console.log("Excalidraw.Data.updateScene()");
this.scene = JSON_parse(newScene);
this.updateElementLinksFromScene();
const { linkedNonTextElementsById, textElementsById } =
this.getSceneElementIndexes();
this.updateElementLinksFromScene(linkedNonTextElementsById);
const result =
this.setLinkPrefix() ||
this.setUrlPrefix() ||
this.setShowLinkBrackets() ||
this.setembeddableThemePreference() ||
this.findNewElementLinksInScene();
await this.updateTextElementsFromScene();
await this.updateTextElementsFromScene(textElementsById);
if (result || this.findNewTextElementsInScene()) {
await this.updateSceneTextElements();
return true;
+63 -13
View File
@@ -9,6 +9,7 @@ import { hasExcalidrawEmbeddedImagesTreeChanged } from "../utils/fileUtils";
import { EXCALIDRAW_PLUGIN } from "src/constants/constants";
import { blobToDataURL } from "../utils/coreUtils";
import { isInstanceOfSVGSVGElement } from "../utils/typechecks";
import { BackupPersistenceQueue } from "./BackupPersistenceQueue";
type FileCacheData = {
schemaVersion: 2;
@@ -87,6 +88,16 @@ class ImageCache {
private purgeInvalidBackupTimer: number = null;
private touchedCacheKeys = new Set<string>();
private cacheReadinessPromise: Promise<void> | null = null;
private backupWrites = new BackupPersistenceQueue({
ownerWindow: window,
write: (filepath, data) => this.addBAKToCache(filepath, data),
onError: (error, stage) =>
errorlog({
where: "ImageCache.backupWrites",
fn: stage,
error,
}),
});
private getCacheRetentionCutoff(): number {
const retentionDays = Math.max(
@@ -128,6 +139,7 @@ class ImageCache {
if (this.purgeInvalidBackupTimer) {
window.clearTimeout(this.purgeInvalidBackupTimer);
}
this.backupWrites.destroy();
this.db?.close();
this.db = null;
this.plugin = null;
@@ -519,6 +531,7 @@ class ImageCache {
try {
await this.ensureCacheStoreReady();
const cachedData = await this.getCacheData(key);
if (!cachedData) {
return undefined;
@@ -541,15 +554,15 @@ class ImageCache {
if (cachedData.mtime < file.stat.mtime) {
return undefined;
}
if (
!options?.skipDependencyCheck &&
hasExcalidrawEmbeddedImagesTreeChanged(
if (!options?.skipDependencyCheck) {
const dependencyChanged = hasExcalidrawEmbeddedImagesTreeChanged(
file,
cachedData.mtime,
this.plugin,
)
) {
return undefined;
);
if (dependencyChanged) {
return undefined;
}
}
// Validated reads can require a minimum render scale so lower-resolution PDF
// snapshots are upgraded in the background without blocking the first paint.
@@ -614,7 +627,8 @@ class ImageCache {
if (options?.svgFormat === "data-url") {
return blobToDataURL(cacheData.blob);
}
return convertSVGStringToElement(await cacheData.blob.text());
const svgText = await cacheData.blob.text();
return convertSVGStringToElement(svgText);
}
if (this.obsidanURLCache.has(key)) {
return this.obsidanURLCache.get(key);
@@ -624,6 +638,11 @@ class ImageCache {
return obsidianURL;
}
/** Returns the number of live raster blob URLs retained by the session cache. */
public getObsidianURLCacheSize(): number {
return this.obsidanURLCache?.size ?? 0;
}
public releaseObsidianURL(url: string): void {
if (!url || !this.obsidanURLCache) {
return;
@@ -667,12 +686,11 @@ class ImageCache {
const isSVGElement = isInstanceOfSVGSVGElement(image);
const payloadKind =
isSVGElement || image.type === "image/svg+xml" ? "svg" : "raster";
const blob =
isSVGElement
? new Blob([image.outerHTML.replaceAll("&nbsp;", " ")], {
type: "image/svg+xml",
})
: image;
const blob = isSVGElement
? new Blob([image.outerHTML.replaceAll("&nbsp;", " ")], {
type: "image/svg+xml",
})
: image;
const now = Date.now();
const data: FileCacheData = {
schemaVersion: 2,
@@ -713,9 +731,40 @@ class ImageCache {
const transaction = this.db.transaction(this.backupStoreName, "readwrite");
const store = transaction.objectStore(this.backupStoreName);
store.put(data, filepath);
return new Promise<void>((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onerror = () =>
reject(
transaction.error ??
new Error(`Failed to update backup file with key: ${filepath}`),
);
transaction.onabort = () =>
reject(
transaction.error ??
new Error(`Backup update aborted for key: ${filepath}`),
);
});
}
/**
* Schedules the latest backup payload through the plugin-global queue.
*/
public scheduleBAKToCache(
filepath: string,
data: BackupData,
delayMs: number,
): boolean {
return this.backupWrites.schedule(filepath, data, delayMs);
}
/** Flushes any queued backup before a drawing path is renamed. */
public async flushPendingBAK(filepath: string): Promise<void> {
await this.backupWrites.flush(filepath);
}
public async removeBAKFromCache(filepath: string): Promise<void> {
await this.backupWrites.cancel(filepath);
if (!this.isReady()) {
return; // Database not initialized yet
}
@@ -750,6 +799,7 @@ class ImageCache {
}
public async clearBackupCache(): Promise<void> {
await this.backupWrites.cancelAll();
if (!this.isReady()) {
return; // Database not initialized yet
}
+1
View File
@@ -105,6 +105,7 @@ export interface ViewSemaphores {
//flag to prevent overwriting the changes the user makes in an embeddable view editing the back side of the drawing
embeddableIsEditingSelf: boolean;
popoutUnload: boolean; //the unloaded Excalidraw view was the last leaf in the popout window
windowMigrating: boolean; //the current runtime is being replaced after its container moved between windows
viewloaded: boolean; //onLayoutReady in view.onload has completed.
viewunload: boolean;
//first time initialization of the view
+15
View File
@@ -149,6 +149,21 @@ export type Packages = {
excalidrawLib: typeof ExcalidrawLib | null;
};
/**
* An idempotent handle for the shared runtime acquired by one view.
*
* @remarks
* 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;
readonly packages: Packages;
release(): void;
};
export type ValueOf<T> = T[keyof T];
export type DynamicStyle = "none" | "gray" | "colorful";
+3 -1
View File
@@ -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);
+718 -265
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -956,7 +956,7 @@ function RenderObsidianView({
if (!leafRef.current) {
return;
}
view.canvasNodeFactory.removeNode(leafRef.current.node);
view.canvasNodeFactory.removeNode(leafRef.current.node, element.id);
leafRef.current.leaf?.detach();
leafRef.current = null;
}; //cleanup on unmount
+6 -1
View File
@@ -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: {
@@ -148,7 +148,8 @@ export class SelectedElementActionsMenu {
cls: "ToolIcon_type_button ToolIcon_size_small ToolIcon_type_button--show ToolIcon",
attr: {
type: "button",
title: action.title,
// A title attribute adds a native browser tooltip alongside the
// styled Excalidraw tooltip. Keep the accessible name only.
"aria-label": action.title,
},
});
+18 -2
View File
@@ -207,11 +207,27 @@ export class CanvasNodeFactory {
}
}
removeNode(node: ObsidianCanvasNode) {
/**
* Removes a Canvas node and releases the factory's reference to it.
*
* The optional element ID is the map's canonical key. The identity check
* prevents a stale React cleanup from deleting a replacement node that was
* already registered for the same Excalidraw element.
*/
public removeNode(node: ObsidianCanvasNode, elementId?: string) {
if (!this.initialized || !node) {
return;
}
this.nodes.delete(node.file.path);
if (elementId && this.nodes.get(elementId) === node) {
this.nodes.delete(elementId);
} else {
for (const [registeredElementId, registeredNode] of this.nodes) {
if (registeredNode === node) {
this.nodes.delete(registeredElementId);
break;
}
}
}
this.canvas.removeNode(node);
node.detach();
}
+529
View File
@@ -0,0 +1,529 @@
import { Notice } from "obsidian";
import type { AppState } from "@zsviczian/excalidraw/types/excalidraw/types";
import { t } from "../../lang/helpers";
import type ExcalidrawView from "../ExcalidrawView";
/** Side effects selected for one save request. */
export interface SaveSideEffectPolicy {
triggerAutoexport: boolean;
}
/** Terminal outcome reported by the view-owned persistence implementation. */
export type SaveExecutionStatus =
| "persisted"
| "window-migration-handed-off"
| "window-migration-persisted"
| "view-unload-scheduled"
| "unchanged"
| "skipped"
| "failed";
/** Result used by the coordinator to advance the saved revision safely. */
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;
triggerAutoexport: boolean;
}
export const DIRECT_SAVE_SIDE_EFFECT_POLICY: Readonly<SaveSideEffectPolicy> = {
triggerAutoexport: true,
};
export const PUBLIC_FORCE_SAVE_POLICY: Readonly<ForceSavePolicy> = {
refreshSceneFiles: true,
triggerAutoexport: true,
};
export const WINDOW_BLUR_FORCE_SAVE_POLICY: Readonly<ForceSavePolicy> = {
refreshSceneFiles: false,
// Autoexport is a documented save-time contract, including for blur-triggered saves.
triggerAutoexport: true,
};
/** Private view operations retained by the composition root during the
* mechanical coordinator extraction. */
export interface ViewSaveCoordinatorDependencies {
performSave: (
preventReload: boolean,
forcesave: boolean,
overrideEmbeddableIsEditingSelfDebounce: boolean,
sideEffectPolicy: Readonly<SaveSideEffectPolicy>,
) => Promise<SaveExecutionResult>;
requestSave: (
preventReload?: boolean,
forcesave?: boolean,
overrideEmbeddableIsEditingSelfDebounce?: boolean,
) => Promise<void>;
isDirty: () => boolean;
checkSceneVersion: () => void;
refreshCanvasOffset: () => void;
getFreedrawLastActiveTimestamp: () => number;
markDirtyVisuals: () => void;
clearDirtyVisuals: () => void;
}
interface SaveRequest {
preventReload: boolean;
forcesave: boolean;
overrideEmbeddableIsEditingSelfDebounce: boolean;
sideEffectPolicy: Readonly<SaveSideEffectPolicy>;
revision: number;
}
/**
* Coordinates persistence entry points, dirty state, and autosave scheduling
* for one Excalidraw view.
*
* The view retains its public facade and the `TextFileView.save()` disk-write
* implementation. Durable edit revisions prevent a completed save from
* clearing newer changes, and one merged trailing request bounds concurrent
* persistence work without dropping edits made while a save is in flight.
*/
export class ViewSaveCoordinator {
public autosaveTimer: number | null = null;
public autosaveFunction: (() => void) | null = null;
private currentRevision = 0;
private savedRevision = 0;
private activeSaveRevision: number | null = null;
private pendingSaveRequest: SaveRequest | null = null;
private saveLoopPromise: Promise<void> | null = null;
public constructor(
private readonly view: ExcalidrawView,
private readonly dependencies: ViewSaveCoordinatorDependencies,
) {}
/** Runs the historical public save policy. */
public async save(
preventReload: boolean = true,
forcesave: boolean = false,
overrideEmbeddableIsEditingSelfDebounce: boolean = false,
): Promise<void> {
await this.enqueueSave({
preventReload,
forcesave,
overrideEmbeddableIsEditingSelfDebounce,
sideEffectPolicy: DIRECT_SAVE_SIDE_EFFECT_POLICY,
revision: this.currentRevision,
});
}
private enqueueSave(request: SaveRequest): Promise<void> {
if (this.pendingSaveRequest) {
this.pendingSaveRequest = this.mergeSaveRequests(
this.pendingSaveRequest,
request,
);
} else {
this.pendingSaveRequest = request;
}
if (this.saveLoopPromise !== null) {
return this.saveLoopPromise;
}
const loop = Promise.resolve().then(() => this.drainSaveQueue());
const trackedLoop = loop.finally(() => {
if (this.saveLoopPromise === trackedLoop) {
this.saveLoopPromise = null;
}
});
this.saveLoopPromise = trackedLoop;
return trackedLoop;
}
private mergeSaveRequests(
current: SaveRequest,
incoming: SaveRequest,
): SaveRequest {
const selected =
current.forcesave && !incoming.forcesave ? current : incoming;
return {
...selected,
forcesave: current.forcesave || incoming.forcesave,
overrideEmbeddableIsEditingSelfDebounce:
current.overrideEmbeddableIsEditingSelfDebounce ||
incoming.overrideEmbeddableIsEditingSelfDebounce,
sideEffectPolicy: {
triggerAutoexport:
current.sideEffectPolicy.triggerAutoexport ||
incoming.sideEffectPolicy.triggerAutoexport,
},
revision: Math.max(current.revision, incoming.revision),
};
}
private async drainSaveQueue(): Promise<void> {
let completedRequest = false;
while (this.pendingSaveRequest) {
const request = this.pendingSaveRequest;
this.pendingSaveRequest = null;
if (
completedRequest &&
!request.forcesave &&
request.revision <= this.savedRevision
) {
continue;
}
this.activeSaveRevision = request.revision;
try {
const result = await this.dependencies.performSave(
request.preventReload,
request.forcesave,
request.overrideEmbeddableIsEditingSelfDebounce,
request.sideEffectPolicy,
);
this.completeSaveRevision(request, result);
} finally {
this.activeSaveRevision = null;
}
completedRequest = true;
}
}
private completeSaveRevision(
request: SaveRequest,
result: SaveExecutionResult,
): void {
if (
result.status === "persisted" ||
result.status === "window-migration-handed-off" ||
result.status === "window-migration-persisted" ||
result.status === "view-unload-scheduled" ||
result.status === "unchanged"
) {
this.savedRevision = Math.max(this.savedRevision, request.revision);
this.reconcileDirtyState();
}
}
private queueTrailingSave(): void {
const request: SaveRequest = {
preventReload: true,
forcesave: false,
overrideEmbeddableIsEditingSelfDebounce: false,
sideEffectPolicy: DIRECT_SAVE_SIDE_EFFECT_POLICY,
revision: this.currentRevision,
};
this.pendingSaveRequest = this.pendingSaveRequest
? this.mergeSaveRequests(this.pendingSaveRequest, request)
: request;
}
private reconcileDirtyState(): void {
if (this.currentRevision > this.savedRevision) {
this.view.semaphores.dirty = this.view.file?.path;
this.dependencies.markDirtyVisuals();
return;
}
if (this.view.semaphores.viewunload || !this.view.excalidrawAPI) {
return;
}
this.view.semaphores.dirty = null;
this.dependencies.clearDirtyVisuals();
}
/** Runs the historical public force-save policy. */
public async forceSave(
silent: boolean = false,
waitIfBusy: boolean = false,
): Promise<void> {
await this.forceSaveWithPolicy(
silent,
waitIfBusy,
PUBLIC_FORCE_SAVE_POLICY,
);
}
/** Runs a forced save with an explicitly selected side-effect policy. */
public async forceSaveWithPolicy(
silent: boolean,
waitIfBusy: boolean,
policy: Readonly<ForceSavePolicy>,
): Promise<void> {
if (waitIfBusy) {
let counter = 0;
while (
(this.view.semaphores.autosaving ||
this.view.semaphores.saving ||
this.saveLoopPromise !== null) &&
counter++ < 100
) {
await sleep(50);
}
}
if (
this.view.semaphores.autosaving ||
this.view.semaphores.saving ||
this.saveLoopPromise !== null
) {
if (!silent) {
new Notice(t("FORCE_SAVE_ABORTED"));
}
return;
}
this.view.clearPreventReloadTimer();
this.view.semaphores.preventReload = false;
this.view.semaphores.forceSaving = true;
await this.enqueueSave({
preventReload: false,
forcesave: true,
overrideEmbeddableIsEditingSelfDebounce: true,
sideEffectPolicy: {
triggerAutoexport: policy.triggerAutoexport,
},
revision: this.currentRevision,
});
if (this.view.semaphores.windowMigrating) {
this.view.semaphores.forceSaving = false;
return;
}
this.view.plugin.triggerEmbedUpdates();
if (policy.refreshSceneFiles) {
await this.view.loadSceneFiles();
}
this.view.semaphores.forceSaving = false;
if (!silent) {
new Notice("Save successful", 1000);
}
}
/** Saves scene changes found during view teardown or navigation. */
public async forceSaveIfRequired(): Promise<boolean> {
let watchdog = 0;
let dirty = false;
if (!this.view.excalidrawAPI) {
return false;
}
this.dependencies.checkSceneVersion();
if (!this.dependencies.isDirty()) {
if (!this.view.semaphores.saving && this.saveLoopPromise === null) {
return false;
}
// Preserve the existing Excalibrain unload compatibility check.
if (
this.view.hookServer &&
this.view.hookServer.onViewUnloadHook?.toString() ===
"e=>{this.scene&&this.scene.leaf===e.leaf&&this.stop()}"
) {
return false;
}
}
if (this.saveLoopPromise !== null) {
dirty = true;
await this.saveLoopPromise;
} else {
while (this.view.semaphores.saving && watchdog++ < 200) {
dirty = true;
await sleep(40);
}
}
if (this.view.excalidrawAPI) {
this.dependencies.checkSceneVersion();
if (this.dependencies.isDirty()) {
const path = this.view.file?.path;
const plugin = this.view.plugin;
window.setTimeout(() => {
plugin.triggerEmbedUpdates(path);
}, 400);
dirty = true;
await this.flush();
}
}
return dirty;
}
/** Waits for queued saves, then persists any revision still left dirty. */
public async flush(): Promise<void> {
if (this.saveLoopPromise !== null) {
await this.saveLoopPromise;
}
if (!this.isDirty()) {
return;
}
await this.enqueueSave({
preventReload: true,
forcesave: true,
overrideEmbeddableIsEditingSelfDebounce: true,
sideEffectPolicy: DIRECT_SAVE_SIDE_EFFECT_POLICY,
revision: this.currentRevision,
});
}
/** Starts the recursive autosave timer with the existing scheduling rules. */
public setupAutosaveTimer(): void {
const timer = () => {
void (async () => {
if (!this.view.isLoaded) {
this.autosaveTimer = window.setTimeout(
timer,
this.view.autosaveInterval,
);
return;
}
const api = this.view.excalidrawAPI;
if (!api) {
new Notice(t("WARNING_SERIOUS_ERROR"), 60000);
return;
}
const st = api.getAppState() as AppState;
const isFreedrawActive =
st.activeTool?.type === "freedraw" &&
this.dependencies.getFreedrawLastActiveTimestamp() >
Date.now() - 2000;
const isEditingText = st.editingTextElement !== null;
const isEditingNewElement = st.newElement !== null;
this.dependencies.refreshCanvasOffset();
if (
this.dependencies.isDirty() &&
this.view.plugin.autosaveEnabled &&
!this.view.semaphores.forceSaving &&
!this.view.semaphores.autosaving &&
!this.view.semaphores.embeddableIsEditingSelf &&
!isFreedrawActive &&
!isEditingText &&
!isEditingNewElement
) {
this.autosaveTimer = null;
if (this.view.excalidrawAPI) {
this.view.semaphores.autosaving = true;
// Preserve the non-blocking save used to avoid lag on large files.
void this.dependencies
.requestSave()
.then(() => (this.view.semaphores.autosaving = false));
}
this.autosaveTimer = window.setTimeout(
timer,
this.view.autosaveInterval,
);
} else {
this.autosaveTimer = window.setTimeout(
timer,
this.view.plugin.activeExcalidrawView === this.view &&
this.view.semaphores.dirty &&
this.view.plugin.autosaveEnabled
? 1000
: this.view.autosaveInterval,
);
}
})();
};
this.autosaveFunction = timer;
this.resetAutosaveTimer();
}
/** Restarts the autosave interval after a completed save or first edit. */
public resetAutosaveTimer(): void {
if (!this.autosaveFunction) {
return;
}
if (this.autosaveTimer) {
window.clearTimeout(this.autosaveTimer);
this.autosaveTimer = null;
}
this.autosaveTimer = window.setTimeout(
this.autosaveFunction,
this.view.autosaveInterval,
);
}
/** Cancels autosave work owned by this view. */
public destroy(): void {
if (this.autosaveTimer) {
window.clearTimeout(this.autosaveTimer);
this.autosaveTimer = null;
}
this.autosaveFunction = null;
}
/** Advances the edit revision and queues one trailing save when necessary. */
public setDirty(): void {
if (this.view.semaphores.saving && this.activeSaveRevision === null) {
return;
}
if (!this.dependencies.isDirty()) {
this.resetAutosaveTimer();
}
this.currentRevision += 1;
this.view.semaphores.dirty = this.view.file?.path;
this.dependencies.markDirtyVisuals();
if (this.saveLoopPromise !== null) {
this.queueTrailingSave();
}
}
/** Returns whether the dirty marker belongs to the current file. */
public isDirty(): boolean {
return (
this.currentRevision > this.savedRevision &&
Boolean(this.view.semaphores?.dirty) &&
this.view.semaphores.dirty === this.view.file?.path
);
}
/** Clears the current file's dirty marker and updates its clean baseline. */
public clearDirty(): void {
if (
this.saveLoopPromise !== null ||
this.view.semaphores.viewunload ||
!this.view.excalidrawAPI
) {
return;
}
this.currentRevision += 1;
this.savedRevision = this.currentRevision;
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;
}
}
+180 -48
View File
@@ -1,4 +1,7 @@
import type { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import type {
ExcalidrawImperativeAPI,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import type {
DeferredCacheValidation,
@@ -23,6 +26,63 @@ export interface ViewSceneFileManagerDependencies {
addFiles: typeof import("../ExcalidrawView").addFiles;
}
/** 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 = () => {
if (settled) {
return;
}
settled = true;
window.clearTimeout(fallbackTimer);
resolve();
};
const fallbackTimer = window.setTimeout(finish, 250);
try {
const ownerWindow = getOwnerWindow();
ownerWindow.requestAnimationFrame(() => {
ownerWindow.requestAnimationFrame(finish);
});
} catch {
finish();
}
});
/** 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) {
return visibleFileIds;
}
const zoom = appState.zoom.value;
const left = -appState.scrollX;
const top = -appState.scrollY;
const right = left + appState.width / zoom;
const bottom = top + appState.height / zoom;
for (const element of view.getViewElements()) {
if (
element.type === "image" &&
!element.isDeleted &&
element.fileId &&
element.x + element.width >= left &&
element.y + element.height >= top &&
element.x <= right &&
element.y <= bottom
) {
visibleFileIds.add(element.fileId);
}
}
return visibleFileIds;
};
/**
* Owns the embedded-file loading pipeline (RefactorPlan.md Phase 6,
* "ViewSceneFileManager"): the active/next loader pair, the deferred
@@ -65,6 +125,21 @@ export class ViewSceneFileManager {
private readonly dependencies: ViewSceneFileManagerDependencies,
) {}
private isRuntimeCurrent(
api: ExcalidrawImperativeAPI,
filePath: string | null,
): boolean {
// A replacement view can open the same file while callbacks from the
// source window are still queued, so file identity alone is insufficient.
return (
this.view.excalidrawAPI === api &&
!api.isDestroyed &&
!this.view.semaphores?.windowMigrating &&
!this.view.semaphores?.viewunload &&
(this.view.file?.path ?? null) === filePath
);
}
/** Terminates any in-flight loaders and cancels deferred validation. Called
* from `ExcalidrawView.onClose()`, `onunload()`, and `clear()`. */
public terminateActiveLoaders(): void {
@@ -112,11 +187,15 @@ export class ViewSceneFileManager {
emitPolicy: "changed-only" | "all" = "changed-only",
) {
this.cancelDeferredSceneFileValidation();
const api = this.view.excalidrawAPI;
if (
!candidates ||
candidates.size === 0 ||
!this.view.file ||
!this.view.excalidrawAPI
!api ||
api.isDestroyed ||
this.view.semaphores?.windowMigrating ||
this.view.semaphores?.viewunload
) {
return;
}
@@ -127,11 +206,9 @@ export class ViewSceneFileManager {
this.deferredValidationFilePath = currentFile;
this.deferredValidationTimer = window.setTimeout(() => {
this.deferredValidationTimer = null;
if (
!this.view.file ||
!this.view.excalidrawAPI ||
this.view.file.path !== currentFile
) {
if (!this.isRuntimeCurrent(api, currentFile)) {
loader.terminate = true;
loader.emptyPDFDocsMap();
this.deferredValidationFilePath = null;
return;
}
@@ -147,12 +224,10 @@ export class ViewSceneFileManager {
isDark: boolean,
final: boolean = true,
) => {
if (
!this.view.file ||
!this.view.excalidrawAPI ||
this.view.file.path !== currentFile
) {
if (final && this.deferredValidationLoader === loader) {
if (!this.isRuntimeCurrent(api, currentFile)) {
loader.terminate = true;
loader.emptyPDFDocsMap();
if (this.deferredValidationLoader === loader) {
this.deferredValidationLoader = null;
this.deferredValidationFilePath = null;
}
@@ -197,7 +272,15 @@ export class ViewSceneFileManager {
isThemeChange: boolean = false,
forceEmitFromCache: boolean = false,
) {
if (!this.view.excalidrawAPI || !fileIDs || fileIDs.size === 0) {
const api = this.view.excalidrawAPI;
if (
!api ||
api.isDestroyed ||
this.view.semaphores?.windowMigrating ||
this.view.semaphores?.viewunload ||
!fileIDs ||
fileIDs.size === 0
) {
return;
}
if (this.activeLoader) {
@@ -229,11 +312,19 @@ export class ViewSceneFileManager {
callback?: () => void,
forceReloadFileIDs?: Set<FileId>,
) {
if (!this.view.excalidrawAPI) {
const requestAPI = this.view.excalidrawAPI;
if (
!requestAPI ||
requestAPI.isDestroyed ||
this.view.semaphores?.windowMigrating ||
this.view.semaphores?.viewunload
) {
return;
}
const requestFilePath = this.view.file?.path ?? null;
const requestIsCurrent = () =>
this.isRuntimeCurrent(requestAPI, requestFilePath);
const deferredValidationForSameFile =
!!requestFilePath &&
this.deferredValidationFilePath === requestFilePath &&
@@ -259,8 +350,20 @@ export class ViewSceneFileManager {
const loader = this.dependencies.createEmbeddedFilesLoader();
const runLoader = (l: EmbeddedFilesLoader) => {
if (!requestIsCurrent()) {
l.terminate = true;
l.emptyPDFDocsMap();
if (this.activeLoader === l) {
this.activeLoader = null;
}
if (this.nextLoader === l) {
this.nextLoader = null;
}
return;
}
this.nextLoader = null;
this.activeLoader = l;
const prioritizedFileIds = getVisibleImageFileIds(this.view);
void l.loadSceneFiles({
excalidrawData: this.view.excalidrawData,
sceneElements: this.view.getViewElements(),
@@ -269,12 +372,20 @@ export class ViewSceneFileManager {
isDark: boolean,
final: boolean = true,
) => {
if (!requestIsCurrent()) {
l.terminate = true;
l.emptyPDFDocsMap();
if (this.activeLoader === l) {
this.activeLoader = null;
}
if (this.nextLoader === l) {
this.nextLoader = null;
}
return;
}
if (callback && final) {
callback();
}
if (!this.view.file || !this.view.excalidrawAPI) {
return; //The view was closed in the mean time
}
if (files && files.length > 0) {
void this.dependencies.addFiles(files, this.view, isDark);
}
@@ -282,9 +393,12 @@ export class ViewSceneFileManager {
return;
}
this.view.lastSceneLoadTime = Date.now();
this.activeLoader = null;
if (this.activeLoader === l) {
this.activeLoader = null;
}
if (this.nextLoader) {
runLoader(this.nextLoader);
const nextLoader = this.nextLoader;
runLoader(nextLoader);
} else {
// Once the scene is painted, validate cached candidates in the background
// so unchanged cache hits do not delay the initial scene load.
@@ -292,39 +406,54 @@ export class ViewSceneFileManager {
this.scheduleDeferredSceneFileValidation(
new Map(this.pendingDeferredValidationCandidates),
isThemeChange,
"changed-only",
);
this.pendingDeferredValidationCandidates.clear();
}
//in case one or more files have not loaded retry later hoping that sync has delivered the file in the mean time.
this.view.excalidrawData.getFiles().some((ef) => {
if (ef && !ef.file && ef.attemptCounter < 30) {
const currentFile = this.view.file.path;
const retryLoadSceneFiles = () => {
if (
!this ||
!this.view.excalidrawAPI ||
currentFile !== this.view.file.path
) {
return;
}
// Keep deferred validation uninterrupted. If it is running,
// retry again once it completes.
if (
this.deferredValidationLoader ||
this.deferredValidationTimer
) {
window.setTimeout(retryLoadSceneFiles, 500);
return;
}
void this.loadSceneFiles();
};
window.setTimeout(() => {
retryLoadSceneFiles();
}, 2000);
return true;
}
return false;
});
const retryCandidates = Array.from(
this.view.excalidrawData.getFileEntries(),
).filter(
([, embeddedFile]) =>
embeddedFile &&
!embeddedFile.file &&
!embeddedFile.isHyperLink &&
!embeddedFile.isLocalLink &&
embeddedFile.attemptCounter < 30,
);
if (retryCandidates.length > 0) {
const retryFileIDs = new Set(
retryCandidates.map(([fileId]) => fileId),
);
const currentFile = this.view.file.path;
const retryLoadSceneFiles = () => {
if (
!this ||
!requestIsCurrent() ||
currentFile !== this.view.file.path
) {
return;
}
// Keep deferred validation uninterrupted. If it is running,
// retry again once it completes.
if (
this.deferredValidationLoader ||
this.deferredValidationTimer
) {
window.setTimeout(retryLoadSceneFiles, 500);
return;
}
void this.loadSceneFiles(
false,
retryFileIDs,
undefined,
undefined,
);
};
window.setTimeout(() => {
retryLoadSceneFiles();
}, 2000);
}
}
},
depth: 0,
@@ -335,6 +464,9 @@ export class ViewSceneFileManager {
onDeferredValidationCandidates: (candidates) => {
this.addDeferredValidationCandidates(candidates);
},
waitForRender: () =>
waitForWindowPaint(() => this.view.ownerWindow ?? window),
prioritizedFileIds,
});
};
if (!this.activeLoader) {
+15 -3
View File
@@ -1667,8 +1667,11 @@ button.excalidraw-font-picker {
background: transparent;
box-shadow: none;
color: var(--text-accent);
cursor: pointer;
font-size: inherit;
font-weight: inherit;
text-decoration: none;
touch-action: manipulation;
}
.excalidraw-settings-breadcrumbs__link:hover {
@@ -1678,6 +1681,18 @@ button.excalidraw-font-picker {
text-decoration: underline;
}
.excalidraw-settings-breadcrumbs__link.is-disabled {
color: var(--text-muted);
cursor: default;
pointer-events: none;
}
.is-mobile .excalidraw-settings-breadcrumbs__link,
.is-tablet .excalidraw-settings-breadcrumbs__link {
min-height: var(--interactive-normal);
padding-inline: var(--size-2-2);
}
.excalidraw-settings-breadcrumbs__current {
color: var(--text-normal);
font-weight: var(--font-semibold);
@@ -1692,14 +1707,11 @@ button.excalidraw-font-picker {
color: var(--text-accent);
font-weight: var(--font-medium);
text-decoration: underline;
text-decoration-thickness: max(1px, 0.08em);
text-underline-offset: 0.15em;
}
.excalidraw-settings .setting-item-description a[href^="#"]:hover,
.excalidraw-settings-page .setting-item-description a[href^="#"]:hover {
color: var(--text-accent-hover);
text-decoration-thickness: max(2px, 0.12em);
}
.excalidraw-filename-information {