Compare commits

...
Author SHA1 Message Date
zsviczian 479ecaab33 2.27.0-beta.3 2026-08-16 10:55:46 +02:00
zsviczian 044d39badb fix code scanner findings 2026-08-16 10:46:49 +02:00
zsviczian c6ab40470f updated agents.md and contributing.md 2026-08-16 10:23:18 +02:00
zsviczian d68d23a989 Merge pull request #2895 from zsviczian/new-excalidraw-boundary
Register typed Excalidraw host adapters
2026-08-15 22:43:52 +02:00
zsviczian 8025e1ed1a Complete typed Excalidraw host boundary 2026-08-15 22:40:44 +02:00
zsviczian 57dac2e523 Register Excalidraw package settings adapter 2026-08-15 21:26:09 +02:00
zsviczian c3834b3ed3 Record common host-boundary completion 2026-08-15 20:59:31 +02:00
zsviczian 87f3d863b7 Record desktop UI-mode boundary checkpoint 2026-08-15 20:18:52 +02:00
zsviczian a23ccee9ad Record device-info boundary checkpoint 2026-08-15 20:12:44 +02:00
zsviczian 6c413038f9 Register typed Excalidraw host adapter 2026-08-15 19:58:44 +02:00
zsviczian 4f32647d6f Merge pull request #2893 from zsviczian/excalidraw-automate-cleanup
ExcalidrawAutomate and ExcalidrawView Utils cleanup
2026-08-14 19:16:43 +02:00
zsviczian b0d3125c37 0.18.123 2026-08-14 19:14:52 +02:00
zsviczian 9daa9fa936 typefix on excalidrawViewUtils.ts 2026-08-14 19:00:12 +02:00
zsviczianandClaude Sonnet 5 efb00d1d83 Eliminate remaining any-collapse in ExcalidrawAutomate.ts
cloneElement()/cloneElements() both deep-clone via
JSON.parse(JSON.stringify(el)), which is implicitly any; cast to the
already-known shape (Mutable<ExcalidrawElement>, plus a small local
type for the two cross-element-type relationship fields the generic
remap logic probes). Swapped a same-shape-but-looser inline
boundElements callback annotation for the real BoundElement type, and
gave an untyped new Promise((resolve) => ...) its actual
Promise<string | null>.

The two remaining clusters were genuine external boundaries, fixed at
the source rather than cast around:
- addMermaid()'s result.files traced to mermaidToExcalidraw()'s own
  declared return type in the fork (files?: any). Fixed upstream
  (files?: BinaryFiles) and rebuilt; the suppression is now simply
  unnecessary and removed.
- cloneElements()'s JSON.parse(elementsOrClipboard) now uses the real
  envelope shape confirmed against serializeAsClipboardJSON()/
  actionCopy in the fork's clipboard.ts, instead of a suppression.

Zero eslint-disable comments remain in this file. Confirmed via a
git-stash ESLint diff: 229 -> 172 findings repo-wide, zero regressions,
entire delta contained to this one file. Build, lib, and node --check
all pass clean; dist/main.js unchanged from this repo's side (the fork
rebuild's own +19 bytes aside).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-14 18:40:32 +02:00
15 changed files with 469 additions and 72 deletions

No files matched your search

+33 -23
View File
@@ -206,6 +206,31 @@ The customized component lives in the sibling `zsviczian/excalidraw` repository.
- Never hand-edit or commit generated `dist/`, `lib/`, or `node_modules` artifacts as source fixes.
- Treat the repositories as separate Git histories. Check branch, status, diff, build, and commit state independently in each one, and do not commit or publish unless explicitly requested.
### Typed Excalidraw Host Boundary
The customized Excalidraw runtime receives Obsidian capabilities through typed host adapters. Treat this as the only supported plugin-to-fork dependency-inversion boundary.
- Do not expose or recover the plugin through component props, `appState`, `window`, `globalThis`, `app.plugins`, or fork-side `hostPlugin` variables.
- 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.
- 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.
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.
The fork is the source of truth for host-adapter contracts and protocol constants. Import or derive types from its published declarations where possible. If the evaluated `window.ExcalidrawLib` surface requires an ambient declaration, derive that declaration from the fork types instead of restating property lists or unions locally.
### Coordinated Internal Protocol And Release
The host adapters are an internal protocol between this plugin and its exact `@zsviczian/excalidraw` dependency. They are not a compatibility surface between arbitrary historical plugin and fork versions.
- A breaking adapter change must increment the relevant protocol version and update the fork implementation, fork tests, plugin adapter, and plugin ambient runtime declaration in one coordinated checkpoint.
- Fail fast during package loading when a required boundary is absent or incompatible. Do not retain global-plugin discovery or legacy bridge fallbacks solely to support mismatched plugin and fork versions.
- Preserve the general backwards-compatibility requirements for persisted settings, serialized scenes, scripts, commands, and public APIs; this exception applies only to the paired internal host protocol.
- For a maintainer-coordinated release, build and verify the fork package first, publish it, update the plugin's exact dependency, run `npm install`, and rebuild and smoke-test against the published artifact before committing the plugin handoff.
### Popout Window Support
- `src/core/managers/PackageManager.ts` manages window-scoped React/ReactDOM/Excalidraw packages.
@@ -328,6 +353,7 @@ Backwards compatibility is a strong requirement in this repository.
- If a rename reaches beyond a purely internal import graph, prefer temporary aliases, re-exports, or compatibility wrappers during migration.
- If settings shape or stored values change, update defaults, settings UI, load/save flow, and migration logic together.
- Assume user scripts, vault content, templates, embeds, release-note references, and community documentation may depend on existing names and behavior.
- The paired plugin-to-fork host protocol is the deliberate exception described above: coordinate and version breaking contract changes instead of preserving fallbacks for mismatched package versions.
## User-Facing Change Workflow
@@ -439,6 +465,7 @@ npm run doc
Validation guidance:
- After every code modification, run `npm run build` before starting the next checkpoint. Treat new build errors or warnings relative to the recorded baseline as blockers and report relevant existing warnings accurately.
- Treat `eslint.config.cjs` as the quality bar for all new and modified code.
- Use lint results to avoid introducing new violations in touched files, even if repo-wide lint still fails because of unrelated backlog.
- `npm run code` is useful for visibility, but a failing repo-wide run does not by itself mean your change is invalid if the failures are pre-existing and unrelated.
@@ -446,7 +473,9 @@ Validation guidance:
- Run `npm run lib` if you touch the public/library API surface.
- Run `npm run build:mathjax` or `npm run build:all` if you edit `MathjaxToSVG/`.
- Run `npm run madge` after structural import changes or when touching shared architecture.
- Compare Madge and Rollup circular-dependency results only with their own baselines. Madge enumerates overlapping elementary paths and can include type-only imports, while Rollup reports runtime bundle cycles; their raw counts are not directly comparable.
- When the customized Excalidraw source changes, run its `yarn build:obsidian`, refresh the four local package artifacts, and then run this repository's production and relevant development builds. A plugin build against the old installed artifact does not validate the component change.
- For host-boundary changes, run the fork's focused adapter tests without Obsidian, then validate plugin registration and teardown through cold startup, plugin reload, the main window, a new and restored popout, and window removal. Confirm adapter methods observe settings changed after registration.
- After React/package-loading changes, validate cold startup, plugin reload, the main window, new and restored popouts, and moving a leaf between windows. Confirm that no `window.React` or `window.ReactDOM` global was introduced.
- After Radix/portal changes, validate visibility, positioning, stacking, click-outside, and Escape handling in both the main window and a popout; include mobile when viewport collision behavior can differ.
- Record `dist/main.js` byte size after packaging changes and report remaining headroom under the release limit.
@@ -464,7 +493,7 @@ Validation guidance:
- Considering both direct and indirect consumers of the changed code or types
- Reviewing all files that may be impacted by a type, interface, or API change
- Never assume a change is local unless you have verified, by search or analysis, that no other code is affected.
- After making a change, always validate that the build passes and that no new errors or warnings are introduced anywhere in the codebase.
- After making a change, validate the relevant build and compare errors and warnings with the recorded baseline. Touched files must not introduce new diagnostics.
- Prefer minimal, local changes when possible, but never at the expense of breaking global correctness or introducing subtle bugs elsewhere.
- Avoid reformatting large files unless necessary.
- Do not edit generated `dist/` or `lib/` outputs by hand.
@@ -473,26 +502,6 @@ Validation guidance:
- When a change looks odd, search for the constraint that explains it before removing it.
- When in doubt, preserve startup performance, popout support, and existing vault compatibility.
### Additional Guidance for Global Impact
- When changing types, interfaces, or exported APIs, always search for all references and usages across the codebase and update them as needed.
- When tightening types (e.g., replacing `any`), ensure all code that accesses the affected values is type-safe and will continue to work as before.
- If a change introduces new type errors elsewhere, you must fix those errors or revert the change.
- Always run `npm run build` after changes, and do not consider a change complete until the build passes with no new errors.
- If a change could affect runtime behavior, validate by running the plugin in Obsidian if possible.
### MANDATORY: Build Validation After Every Change
**Build validation is not optional and must be run immediately after every code change.**
- After you complete any code modification, you **must** immediately run `npm run build` before proceeding to the next task.
- Do not consider a change complete, correct, or ready to return to the user until `npm run build` passes with no new errors or warnings.
- If the build fails, fix all errors in your code and run `npm run build` again.
- Report all build output (including warnings and circular dependency notices) to the user if relevant to your changes.
- Build validation is not a final polish step—it is part of the core work.
- Treat any new build errors as blockers that must be resolved before considering the task done.
- If a type change or code edit introduces new build failures anywhere in the codebase, those are your responsibility to fix.
### Type Consolidation Follow-through
- Treat user requests like "tiny follow-up" or "do this consolidation" as end-to-end tasks: complete extraction, replace all known duplicates, and remove local leftovers in the same pass.
@@ -581,13 +590,14 @@ Before replacing an `any` type:
### Type Files And Responsibilities
- **`src/types/types.d.ts`**: Ambient module declarations and Obsidian unpublished API types. This is the standard location for extending Obsidian's type system and for global type declarations. Use the existing patterns (interfaces extending `obsidian` module interfaces) consistently.
- **`src/types/excalidrawLib.ts`** (or similar): When creating new type files for project-specific types, place them in `src/types/` and use PascalCase for files that export types or interfaces.
- **`src/types/excalidrawLib.d.ts`**: Ambient declarations for the evaluated `window.ExcalidrawLib` runtime. Derive declarations from published fork types where possible, and keep the file lowerCamelCase in line with grouped type-module naming.
- **Type files in subsystem directories**: Files like `src/shared/ExcalidrawAutomate.ts` may carry substantial type definitions and exports alongside implementation. Do not move these without evaluating the impact on the public API surface.
- **Leverage existing type files**: Consult `src/types/excalidrawLib.ts` for the current Excalidraw type model before adding new Excalidraw-derived types.
- **Leverage existing type files**: Consult `src/types/excalidrawLib.d.ts` and the installed fork declarations for the current Excalidraw type model before adding new Excalidraw-derived types.
### Excalidraw Type Integration
- Do not invent wrapper types for Excalidraw entities. Reference the customized `@zsviczian/excalidraw` types directly.
- Before defining a plugin-local union or interface for a fork concept, search the published fork declarations and import or alias the canonical type. Ambient runtime bridges should reuse those types rather than duplicate their structure.
- Build on existing type extensions in the codebase (e.g., `src/types/types.d.ts` may already extend Excalidraw types).
- When a type depends on Excalidraw internals, document the dependency clearly so future changes to the fork are visible.
- Obsidian unpublished API types often interact with Excalidraw components; model these intersections carefully in `src/types/types.d.ts`.
+9 -1
View File
@@ -63,6 +63,12 @@ Because the plugin must support Obsidian's native popout windows, React and Exca
Rendering and persistence have different window-ownership rules. DOM, events, portals, and React roots should use the owning view window. Existing plugin-level IndexedDB and local-storage data belongs to the main Obsidian application window and is shared with popouts; do not move it to `view.ownerWindow` without an explicit storage design and migration.
#### Typed Excalidraw host boundary
Obsidian-specific capabilities used inside the customized component must cross the typed host-adapter boundary configured by `PackageManager`. Do not pass the plugin, its settings object, or an active view through Excalidraw props or `appState`, and do not recover them through globals. Adapters should expose small semantic operations, read current plugin state, and remain owned by the evaluated window runtime. View-specific behavior must stay instance-scoped.
The fork is the source of truth for adapter contracts and protocol versions. Reuse its published types instead of defining parallel plugin-local unions or interfaces. The adapters are an internal protocol paired with this plugin's exact Excalidraw dependency: coordinate breaking changes across both repositories and fail fast on a missing or incompatible boundary rather than retaining legacy global bridges.
### 2. MathjaxToSVG
LaTeX support is provided by the `MathjaxToSVG` library, which is packaged as a separate sub-component (located in the `MathjaxToSVG/` folder).
- It is compressed using `LZString` during build time.
@@ -119,6 +125,8 @@ From `../excalidraw/packages/excalidraw`, `yarn build:obsidian` produces four co
For an unpublished integration test, you may temporarily copy those four generated files into the installed package under this repository's ignored `node_modules`. Keep the declared npm dependency unchanged. Running `npm install` restores the published package. The durable workflow is to publish a new component version, update the plugin dependency, run `npm install`, and rebuild.
For a maintainer-coordinated host-protocol release, update and test the fork contract first, inspect the package tarball, publish the fork package, then update this repository's exact dependency and lockfile. The final production build and smoke test must use the published package installed by `npm install`, not the temporary copied artifacts. Unit tests in the fork use structural fake adapters and do not require Obsidian; integration testing here must cover startup, reload, the main window, and popout creation and teardown.
The Excalidraw Obsidian artifact has strict runtime constraints:
- one function-evaluable JavaScript file, with no runtime chunks
@@ -139,7 +147,7 @@ Use `RefactorPlan.md` as the living record for ongoing structural work. Refactor
- **No hardcoded strings:** There should be no hardcoded English strings directly in the UI components or logic.
- **Language files:** All strings must be added to the localization files located in `src/lang/locale/`.
- **Translations:** At a minimum, you must add your new keys and strings to `en.ts`. However, it is highly appreciated if you can provide translated strings for all of our actively maintained translations (`es.ts`, `ru.ts`, `zh-cn.ts`, `zh-tw.ts`) using a translation tool.
- **Translations:** Add every new key and string to `en.ts` and the actively maintained translations (`es.ts`, `ru.ts`, `zh-cn.ts`, `zh-tw.ts`) in the same change.
## 📦 Pull Requests & Versioning
+118 -5
View File
@@ -46,12 +46,21 @@ validated, and what remains uncertain.
| Extract the React root (Phase 7) | Implemented; awaiting manual validation | `src/view/components/ExcalidrawRoot.ts` now owns the mechanical body of the former `excalidrawRootElement()`: menu/observer mount and teardown, and the full Excalidraw prop wiring. `ExcalidrawView` keeps `excalidrawRoot`/`createRoot()` ownership and the bound-function render call; ~30 previously private members the render tree touches were widened to `public` (type-only, no logic change) following the precedent already set by `packages`/`plugin`/`excalidrawAPI` |
| Extract `MarkdownImageController` (Phase 6 item 6) | Complete | `src/view/managers/MarkdownImageController.ts` now owns the deletion queue (`queueMarkdownImageDeletion`/`processMarkdownImageDeletionQueue` + its 3 state fields) and the edit/convert trio (`openMarkdownImageEditor`, `convertEmbeddableToMarkdownImage`, `convertMarkdownImageToEmbeddable`). `ExcalidrawView` keeps all three as public delegates (called from `CommandManager`, `ExcalidrawRoot`, and `EmbeddableActionsMenu`), calls `queueMarkdownImageDeletion` from `onExcalidrawIncrement`, and reads `markdownImageController.markdownImageDeletionPrompt` from `save()` exactly where it read the field directly before. Cross-module functions from the existing `ExcalidrawData`/`MarkdownImage`/`MarkdownImageEditor`/`Dialogs/Prompt`/`excalidrawViewUtils` cycle are constructor-injected rather than imported directly, matching the `ViewLinkNavigationManager`/`ViewExcalidrawExtensionRenderer` precedent. Manual testing found no issues |
| Extract `ViewSceneFileManager` (Phase 6 item 5) | Complete | `src/view/managers/ViewSceneFileManager.ts` now owns the active/next loader pair, the deferred background revalidation pass and its timer, the request-coalescing queue, and the stale-image retry loop (7 state fields, 5 methods). `loadSceneFiles()` and `scheduleSceneFileDeferredValidation()` stay as public delegates on `ExcalidrawView` (external callers: `ExcalidrawAutomate.ts`'s scripting surface and `EventManager.ts`'s leaf-switch handler, neither of which needed edits). The three byte-for-byte-duplicated loader-teardown blocks in `onClose()`, `onunload()`, and `clear()` collapsed to one call each to a new `terminateActiveLoaders()` method. A previously-missed direct external read of `activeLoader` in `EventManager.ts:387` is preserved via a pass-through getter on `ExcalidrawView`. `EmbeddedFilesLoader` and the shared `addFiles()` helper (still `ExcalidrawView`-owned, since it's also used by the unrelated LaTeX-equation-editing flow) are constructor-injected, matching the `ViewExportManager`/`MarkdownImageController` precedent |
| Establish a typed Excalidraw/Obsidian host boundary | Complete | `commonObsidianUtils.ts` and `obsidianUtils.ts` no longer discover, cache, expose, or call the plugin directly. The common and Excalidraw-package adapters now own every live setting and plugin-service capability, are installed transactionally per evaluated main/popout runtime, and are independently disposed on package teardown. Missing adapters use safe defaults for optional UI/settings reads and explicit errors for Mermaid/link-suggester services. Dead active-view/AI helpers were deleted; the sole live active-view layout lookup now uses the owning component's container ref. The registered adapters are the only remaining strong plugin references inside each evaluated runtime, with package-manager-owned lifetimes. Manual validation found no issues |
| 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-15 | Closed the raw-plugin bridge removal checkpoint | Manual testing of the complete typed boundary found no issues | User confirmed the implementation works; ready for the coordinated fork package release and plugin dependency handoff |
| 2026-08-15 | Removed the raw `hostPlugin` bridge from the fork | Deleted `hostPlugin`, its lazy global-`app` discovery, initialization/destruction APIs, all legacy fallbacks, and the `App` constructor initialization. Extended `ObsidianExcalidrawHostAdapter` protocol 2 with vault-font loading, shared Mermaid loading, plugin actions, compatibility labels, and inline-link suggester attachment. Removed unused `isExcaliBrainView()`/`getOpenAIDefaultVisionModel()`; replaced `getExcalidrawContentEl()` with the component's own container ref; made both host boundaries mandatory during coordinated package loading; removed the obsolete teardown export/call | Common ESM/type build, fork Obsidian artifact/declarations, and coordinated plugin production build passed under Node 22; focused Vitest passed 18/18 without an Obsidian/plugin runtime, including all service routes, missing-host behavior, protocol rejection, and disposer safety. Targeted fork boundary lint is clean; plugin adapter and `PackageManager` lint are clean. The existing plugin/fork backlog remains outside touched logic, and the production build retains the unchanged 33 circular-dependency warnings. `dist/main.js` is 4,720,214 bytes. Manual validation should prioritize local vault fonts, Mermaid through Excalidraw Extras, the Any file/LaTeX/Card insert actions, compatibility labels, inline link suggestion in both hyperlink and text editors, frame-name editing near the right edge, and plugin reload/popout teardown; main window and popout need separate coverage |
| 2026-08-15 | Added the Excalidraw-package host boundary and migrated active settings-only helpers | Added the versioned `ObsidianExcalidrawHostAdapter` registry with semantic scalar methods for double-tap erasing, right-button panning, zoom-to-fit maximum, pen crosshair, single-finger pen panning, double-click text editing, zoom step/min/max, context-menu disabling, and element-link/text synchronization. Production helpers prefer the adapter and retain their existing defaults plus legacy fallback. `PackageManager` installs a live plugin-side adapter per window, disposes it with the corresponding package, and treats common/package registrations transactionally so a protocol failure cannot leave a partial host installed. Plugin services and active-view operations remain outside this contract | Focused Vitest passed 15/15 across the common and package registries; the new package suite exercises the actual production helpers with a structural fake and no Obsidian/plugin runtime. Both new fork files, the artifact export, the plugin adapter, and `PackageManager` pass targeted ESLint with zero diagnostics; `obsidianUtils.ts` retains exactly its ten pre-existing formatting warnings and has no findings on migrated lines. Fork Obsidian artifact/declarations and the coordinated plugin production build passed under Node 22 with the unchanged 33 circular-dependency warnings. `dist/main.js` is 4,720,214 bytes and contains the new protocol/capabilities. User confirmed the desktop, popout, pen/mobile, zoom, context-menu, and link-sync validation completed successfully with no issues |
| 2026-08-15 | Completed and validated the modern common-package host path by migrating preferred UI mode and highlight color | `getPreferredUIMode(formFactor)` now delegates phone/tablet/desktop selection to the registered host, and `getHighlightColor(background, opacity)` delegates both arguments while preserving the existing blue fallback. Together with the prior checkpoints, every configured-runtime consumer in `commonObsidianUtils.ts` now resolves through the typed adapter. No `obsidianUtils.ts`, component, app-state, or package-manager surface changed | Focused Vitest passed 10/10 with structural-fake coverage for all three form factors, explicit/default highlight opacity, and argument forwarding; targeted ESLint passed with zero diagnostics in both touched fork files; common ESM/type build, fork Obsidian artifact and declarations, and coordinated plugin production build passed under Node 22. The existing 33 circular-dependency warnings are unchanged; `dist/main.js` is 4,718,330 bytes and contains both capability routes. User confirmed main-window/popout UI modes, applicable phone/tablet layouts, and light/dark selection, hover, binding, and frame highlights all checked out successfully |
| 2026-08-15 | Migrated and validated `getDesktopUIMode()` through the typed host boundary | A configured runtime now obtains the desktop-mode candidate from `host.getDesktopUIMode()` and does not consult global `app`. The existing runtime normalization is preserved: `full`, `compact`, `tray`, and `mobile` pass through, while any unsupported value falls back to `tray`. Older artifacts with no registered host retain the legacy lookup | Focused Vitest passed 8/8, including no-plugin assertions for both a valid `compact` mode and an invalid host value normalized to `tray`; targeted ESLint passed with zero diagnostics in both touched fork files; common ESM/type build, fork Obsidian artifact and declarations, and the coordinated plugin production build passed under Node 22. The existing 33 circular-dependency warnings are unchanged; `dist/main.js` is 4,718,290 bytes. User confirmed `full`, `compact`, and `tray` behavior in the main window and popout, including close/reopen initialization |
| 2026-08-15 | Migrated and validated `getObsidianDeviceInfo()` through the typed host boundary | A configured runtime now returns `host.getDeviceInfo()` directly and does not consult or populate the legacy module cache/global `app` path. The fallback is retained only for older artifacts with no registered adapter. This changes one getter and no component, app-state, plugin, or package-manager surface | Focused Vitest passed 7/7, including a structural-fake assertion that calls the production getter with no Obsidian/plugin runtime; targeted ESLint passed with zero diagnostics in both touched fork files; common ESM/type build, fork Obsidian artifact and declarations, and coordinated plugin production build passed under Node 22. The existing 33 circular-dependency warnings are unchanged; `dist/main.js` is 4,718,306 bytes and contains the device capability route. User confirmed main-window and popout layout, desktop UI-mode changes, and applicable form-factor behavior all checked out successfully |
| 2026-08-15 | Migrated and validated the render-canvas limits through the typed host boundary | Exported the common-host registration API from the Obsidian artifact; added a plugin-side structural adapter whose getters read current configuration; registered one adapter per evaluated window runtime in `PackageManager`; and dispose it before package teardown. `getAreaLimit()` and `getWidthHeightLimit()` now prefer the adapter while retaining the legacy bridge as a coordinated-version fallback. No component prop or app-state field was added, and the adapter's plugin reference has exactly the existing package-manager lifetime. Follow-up type cleanup made Excalidraw's `StylesPanelMode` the single union definition and retained the plugin's `UIMode` name as a type-only alias | Focused Vitest passed 6/6 using an in-memory fake with no Obsidian/plugin runtime; targeted fork and plugin ESLint passed with zero diagnostics on the boundary implementation files; common ESM/type build, fork `build:obsidian` plus declarations, and the coordinated plugin production build passed under Node 22. The plugin build retains the existing 33 circular-dependency warnings and produces a 4,718,286-byte `dist/main.js` containing the protocol, registration API, and canvas capability. Full plugin `npm run code` still reports its pre-existing backlog (147 errors and one warning), with no findings in the two touched manager/adapter implementation files. User confirmed the limit values, render behavior, main/popout adapter counts, and cleanup all checked out successfully; iOS intentionally retains the default limits |
| 2026-08-15 | Established the first isolated Excalidraw/Obsidian host-boundary checkpoint | Added the fork-only `packages/common/src/commonObsidianHost.ts` contract and registry without importing Obsidian or the plugin, and without wiring any production caller. Registration is protocol-checked; cleanup is idempotent; an older disposer cannot clear a newer registration. Moved the existing `ObsidianDeviceType` definition to the new canonical module and re-exported it from the old path, preserving imports and runtime behavior. Added five tests driven by an in-memory structural fake rather than a running plugin | Fork `build:obsidian`, declaration generation, and the common-package ESM/type build passed under Node 22; the focused Vitest file passed 5/5; targeted ESLint reported zero errors/warnings in all four touched fork files; `git diff --check` passed. Baseline plugin production build passed with the existing 33 circular-dependency warnings and produced a 4,716,880-byte `dist/main.js`. Repository-wide fork typecheck remains non-blocking because its pre-existing test-harness backlog includes the disabled `createTestHook`/`window.h`, implicit-`any` cascades, and stale fixtures; the new files are clean under targeted validation. No manual runtime test is required yet because the registry has no production consumer |
| 2026-08-08 | Reviewed `AGENTS.md`, `CONTRIBUTING.md`, plugin lifecycle, view lifecycle, package loading, rendering, and Rollup packaging | Established the hybrid Obsidian-host/React-child target and incremental implementation sequence | `npm run build` passed; existing circular dependency warnings recorded |
| 2026-08-08 | Refined scope for 2.27.0 | Legacy AI migration will be retired; generic top-level settings normalization, ExcalidrawAutomate compatibility, duplicate-logic review, and TSDoc are now explicit requirements | Settings and utility reference searches completed; documentation-only build passed |
| 2026-08-08 | Assessed automatic supported-key settings sanitization | Confirmed that removing `stripLegacyAISettings()` alone would re-persist legacy defaults; a shallow replacement is viable only with a cleaned runtime schema and forward-version protection | TypeScript AST check confirmed 204 interface keys and 204 matching `DEFAULT_SETTINGS` keys; load/save, migration, encryption, and dynamic-settings writes reviewed |
@@ -1556,11 +1565,115 @@ grouped with a text element, e.g. via a script calling
changes elsewhere, including `getViewColorPalette()` since its logic itself
was already confirmed correct and unchanged.
**If resumed:** `ExcalidrawAutomate.ts` (57) is the natural next file-by-file
triage target, followed by re-checking `AIUtils.ts` (46, previously declined
as external-boundary — worth confirming that conclusion still holds now
that so much else has changed) and a final full-repo sweep once the large
clusters are gone.
**Done (2026-08-14, session 4): `ExcalidrawAutomate.ts` fully triaged, 57 → 0.**
On `master` (the `excalidraw-type-import-fix` PR was merged as #2892 in the
interim; `master` is now at `2.27.0-beta.2`). Same methodology, three
clusters:
1. **Safe, fixed (49 of 57).** `cloneElement()`/`cloneElements()`'s inner
map both do `JSON.parse(JSON.stringify(el))` to deep-clone an already-known
`ExcalidrawElement` — cast to `Mutable<ExcalidrawElement>` (`cloneElement`)
and a small local `ClonedElementDraft = Mutable<ExcalidrawElement> &
{containerId?; startBinding?; endBinding?}` (`cloneElements`, since the
remap logic generically probes text/arrow-only relationship fields across
whatever element variant it receives — matches the union's actual base
fields plus the two Excalidraw-typed cross-cutting ones, not an invented
shape). One follow-on: `newEl.boundElements.map((bound: {id: string; type:
string}) => ...)` had a same-shape-but-looser-than-necessary inline
annotation; swapped for the real imported `BoundElement` type. Also a
`new Promise((resolve) => ...)` with no generic, resolved with `string |
null` in different branches — TS had defaulted the whole chain to
`unknown`; added the explicit `Promise<string | null>`.
2. **Initially suppressed as external-boundary (8), then genuinely fixed
once the actual sources became available — 0 suppressions remain.** Two
distinct sources, both traced to their exact origin before touching
anything: `addMermaid()`'s `result.files` traced to the upstream
`mermaidToExcalidraw()` function's own declared return type (`{
elements?: ExcalidrawElement[]; files?: any; error?: string } | undefined`
in `@zsviczian/excalidraw`'s `MermaidToExcalidrawLib.d.ts`) — `files?:
any` was the *library's own* declared type, not something the earlier
`@excalidraw/common` fix masked or could improve from this side. First
pass suppressed both with `eslint-disable-next-line` plus a one-line
justification per site, matching this repo's documented suppression
format. The user then fixed it at the actual source: updated
`mermaidToExcalidraw`'s declaration in the fork
(`packages/excalidraw/components/TTDDialog/MermaidToExcalidrawLib.ts`)
to `files?: BinaryFiles`, rebuilt, and refreshed this repo's installed
`node_modules` copy — both suppressions simply deleted, no cast needed,
the value is now genuinely typed. For `cloneElements()`'s
`JSON.parse(elementsOrClipboard)`, the user pointed at the authoritative
source instead of accepting the suppression: `actionCopy`/
`serializeAsClipboardJSON()` in the fork's own
`packages/excalidraw/clipboard.ts` show the real envelope Excalidraw's
own copy action produces (`{type: "excalidraw/clipboard", elements,
files}`, `EXPORT_DATA_TYPES.excalidrawClipboard === "excalidraw/clipboard"`
confirmed against `packages/common/src/constants.ts`, matching the
plugin's own runtime check exactly). Replaced the suppressions with a real
union type (`{type: string; elements: ExcalidrawElement[]} |
ExcalidrawElement[]`, the second arm being this method's own added
convenience for a bare JSON-stringified array, not an Excalidraw-produced
format) and one added `!Array.isArray(parsed)` guard ahead of the
`.type` check purely to let the union narrow before that property access
— logically a no-op versus the original runtime behavior, since a bare
array was already implicitly guaranteed to fail the `.type ===
"excalidraw/clipboard"` comparison (arrays have no `.type`).
`npm run build`/`npm run lib`/`node --check dist/main.js` all pass clean
with **zero `eslint-disable` suppressions anywhere in this file**;
33-warning circular-dependency baseline unchanged; `dist/main.js` is
4,716,872 bytes (+19 bytes from the prior checkpoint, from the fork's own
rebuild — this repo's change is compile-time only). Confirmed via
`git stash`/pop full-repo ESLint diff: 229 → 172 (57 fewer), zero
regressions, the entire delta contained to this one file. Committed
(`efb00d1d`) on branch `excalidraw-automate-cleanup`, pushed; PR not yet
opened (`gh` unavailable in this environment — no token/CLI to author it
directly, link and prepared title/body handed to the user instead).
**Done (2026-08-14, session 5): `excalidrawViewUtils.ts` fully triaged,
20 → 0.** On branch `excalidraw-automate-cleanup` (continued rather than
starting a new branch). Two clusters:
1. **The exact `RegExpMatchIteratorResult`-shaped bug again (16 of 20).**
`isTextImageTransclusion()`'s `const match = text.trim().matchAll(...).next();`
— a bare `let`/`const` with no annotation, assigned via `.next()` on a
`matchAll()` iterator, collapsing to implicit `any` and cascading through
16 downstream accesses. Same exact shape as the very first fix in this
whole `no-unsafe-*` effort (`ExcalidrawData.ts`, session predating this
page's start) — annotated `IteratorResult<RegExpMatchArray, undefined>`.
The plan's own "if resumed" note several sections up predicted exactly
this: "look for more `ExcalidrawData.ts`-shaped cases... a local variable
whose real type is already known... just missing on one declaration."
2. **`Function.prototype.bind()` degrading a real signature to `any` (4).**
`getViewColorPalette()`'s `cmFactory = view.hookServer?.getCM?.bind(...) ??
view.plugin.ea.getCM.bind(...)`. Probed each side independently
(throwaway type-probes, added and reverted): `view.hookServer?.getCM` and
`view.plugin.ea.getCM` both resolve cleanly to their real declared
signature, `(color: TInput) => ColorMaster` — the `any` is introduced
exclusively by `.bind()`'s own type declaration failing to preserve it.
A plain variable type annotation on `cmFactory` satisfied `tsc` but
*not* `eslint`'s `no-unsafe-assignment` (which still flags assigning a
provably-`any`-typed expression regardless of the target annotation);
switched to an explicit `as (color: TInput) => ColorMaster` cast instead,
which both tools accept. Imported the real `TInput`/`ColorMaster` types
from `@zsviczian/colormaster` — the file's own pre-existing local
`ColorMasterLike` structural type and `isColorMasterLike()` guard (used
for everything *after* the `cmFactory(...)` call) were left untouched,
since only the call signature itself needed fixing.
`npm run build`/`npm run lib`/`node --check dist/main.js` all pass clean;
33-warning circular-dependency baseline and `dist/main.js` byte size both
unchanged (4,716,872 bytes — compile-time only). Confirmed via `git
stash`/pop full-repo ESLint diff: 172 → 152 (20 fewer), zero regressions,
entire delta contained to this one file.
**If resumed:** `AIUtils.ts` (46, previously declined as external-boundary)
is the natural next target — worth confirming that conclusion still holds
given how many things in this effort turned out to have a real fix hiding
behind what first looked like a boundary, rather than assuming. After that,
a final full-repo sweep once the remaining clusters are gone. Realistic
floor is still not 0 — `AIUtils.ts`'s provider-JSON boundary and Obsidian's
own `FrontMatterCache: {[key: string]: any}` remain genuine, unavoidable
external boundaries by their own nature, not by insufficient effort.
## Related, separate effort: `ExcalidrawData.ts` structural extraction
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.27.0-beta.2",
"version": "2.27.0-beta.3",
"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.122",
"@zsviczian/excalidraw": "0.18.124",
"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.122",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.122.tgz",
"integrity": "sha512-eiZ/dwjSF6w0Liwj9HJTQreW88VQdc9KjbWS3ITj3cAhLKEdPZInVPsnQ9nHD6WXNTJVnj90yLb+6QKYOJK1kA==",
"version": "0.18.124",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.124.tgz",
"integrity": "sha512-iVWGXAqXvYhf46HMDQnT9sY4x2CPKlimrKOFkiF5R6ba2Sz8qLpoZM01diUyIPfUU3rDNWtZKC34PQYx8r9qGg==",
"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.122",
"@zsviczian/excalidraw": "0.18.124",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
+2 -2
View File
@@ -1312,14 +1312,14 @@ export default class ExcalidrawPlugin extends Plugin {
/**
* Attaches an inline link suggester to the specified input element.
* @param inputEl The HTML input element to attach the suggester to.
* @param inputEl The text input element to attach the suggester to.
* @param widthWrapper Optional HTML element to wrap the width of suggester element.
* @param containerEl Optional container element used as collision boundary.
* @param surpessPlaceholder Whether to suppress the placeholder text. Defaults to true.
* @returns A KeyBlocker instance for managing keyboard input.
*/
public attachInlineLinkSuggester(
inputEl: HTMLInputElement,
inputEl: HTMLInputElement | HTMLTextAreaElement,
widthWrapper?: HTMLElement,
containerEl?: HTMLDivElement,
surpessPlaceholder: boolean = true,
+102 -16
View File
@@ -6,6 +6,8 @@ import type ExcalidrawPlugin from "src/core/main";
import { errorHandler } from "../../utils/ErrorHandler";
import React from "react";
import ReactDOM from "react-dom/client";
import { createObsidianCommonHostAdapter } from "./obsidianCommonHostAdapter";
import { createObsidianExcalidrawHostAdapter } from "./obsidianExcalidrawHostAdapter";
declare let REACT_PACKAGES: string;
declare let react: typeof React;
@@ -15,11 +17,18 @@ declare let ReactJSXRuntime: unknown;
declare let ReactJSXDevRuntime: unknown;
declare const unpackExcalidraw: () => string;
const normalizeError = (error: unknown): Error =>
error instanceof Error
? error
: new Error(typeof error === "string" ? error : "Unknown error");
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>();
constructor(plugin: ExcalidrawPlugin) {
this.plugin = plugin;
@@ -69,8 +78,11 @@ export class PackageManager {
} else {
throw new Error("Invalid initial package");
}
} catch (e) {
errorHandler.handleError(e, "PackageManager constructor");
} catch (e: unknown) {
errorHandler.handleError(
normalizeError(e),
"PackageManager constructor",
);
new Notice(
"Error loading the Excalidraw package. Some features may not work correctly.",
10000,
@@ -104,11 +116,78 @@ 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);
const lib = pkg.excalidrawLib;
if (
!lib ||
typeof lib.configureObsidianCommonHost !== "function" ||
typeof lib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION !== "number"
) {
throw new Error("Excalidraw package is missing the common host boundary");
}
const adapter = createObsidianCommonHostAdapter(
this.plugin,
lib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION,
);
this.commonHostDisposerMap.set(
win,
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);
const lib = pkg.excalidrawLib;
if (
!lib ||
typeof lib.configureObsidianExcalidrawHost !== "function" ||
typeof lib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION !== "number"
) {
throw new Error(
"Excalidraw package is missing the package host boundary",
);
}
const adapter = createObsidianExcalidrawHostAdapter(
this.plugin,
lib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION,
);
this.excalidrawHostDisposerMap.set(
win,
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);
}
/**
* Store a package for a specific window
*/
public setPackage(window: Window, pkg: Packages) {
if (this.validatePackage(pkg)) {
try {
this.configureObsidianCommonHost(window, pkg);
this.configureObsidianExcalidrawHost(window, pkg);
} catch (error: unknown) {
this.disposeObsidianHosts(window);
throw normalizeError(error);
}
this.packageMap.set(window, pkg);
// Update fallback if we don't have one
@@ -140,7 +219,7 @@ export class PackageManager {
return pkg;
}
// If package exists but is invalid, delete it so we can recreate it
this.packageMap.delete(win);
this.deletePackage(win);
}
// Create new package
@@ -174,14 +253,17 @@ export class PackageManager {
excalidrawLib: evalResult.excalidrawLib,
};
this.packageMap.set(win, newPackage);
this.setPackage(win, newPackage);
return newPackage;
},
"PackageManager.getPackage",
this.fallbackPackage,
);
} catch (error) {
errorHandler.handleError(error, "PackageManager.getPackage");
} catch (error: unknown) {
errorHandler.handleError(
normalizeError(error),
"PackageManager.getPackage",
);
// Return fallback package if available to prevent data loss
if (this.fallbackPackage) {
@@ -195,6 +277,8 @@ export class PackageManager {
public deletePackage(win: Window) {
try {
this.disposeObsidianHosts(win);
const pkg = this.packageMap.get(win);
if (!pkg) {
return;
@@ -203,19 +287,16 @@ export class PackageManager {
const { excalidrawLib } = pkg;
if (win.ExcalidrawLib === excalidrawLib) {
errorHandler.wrapWithTryCatch(() => {
if (
excalidrawLib &&
typeof excalidrawLib.destroyObsidianUtils === "function"
) {
excalidrawLib.destroyObsidianUtils();
}
delete win.ExcalidrawLib;
}, "PackageManager.deletePackage - cleanup ExcalidrawLib");
}
this.packageMap.delete(win);
} catch (error) {
errorHandler.handleError(error, "PackageManager.deletePackage");
} catch (error: unknown) {
errorHandler.handleError(
normalizeError(error),
"PackageManager.deletePackage",
);
}
}
@@ -232,14 +313,19 @@ export class PackageManager {
});
this.packageMap.clear();
this.commonHostDisposerMap.clear();
this.excalidrawHostDisposerMap.clear();
this.EXCALIDRAW_PACKAGE = "";
this.fallbackPackage = null;
react = null;
reactDOM = null;
excalidrawLib = null;
} catch (error) {
errorHandler.handleError(error, "PackageManager.destroy");
} catch (error: unknown) {
errorHandler.handleError(
normalizeError(error),
"PackageManager.destroy",
);
}
}
}
@@ -0,0 +1,41 @@
import type ExcalidrawPlugin from "src/core/main";
import { ExcalidrawLib } from "../../types/excalidrawLib";
const DEFAULT_AREA_LIMIT = 16_777_216;
const DEFAULT_WIDTH_HEIGHT_LIMIT = 32_767;
/**
* Creates the narrow, window-runtime host adapter consumed by the Excalidraw
* fork's common and element packages.
*
* @remarks
* Capability methods read current plugin state rather than capturing settings
* values. The package manager owns both this adapter and its disposer, so the
* adapter cannot outlive the corresponding evaluated Excalidraw runtime.
*/
export const createObsidianCommonHostAdapter = (
plugin: ExcalidrawPlugin,
protocolVersion: typeof ExcalidrawLib.OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION,
): ExcalidrawLib.ObsidianCommonHostAdapter => ({
protocolVersion,
getDeviceInfo: () => plugin.getObsidianDevice(),
getDesktopUIMode: () => plugin.getPreferredUIMode(),
getPreferredUIMode: (formFactor) => {
if (formFactor === "phone") {
return plugin.settings.phoneUIMode;
}
if (formFactor === "tablet") {
return plugin.settings.tabletUIMode;
}
return plugin.settings.desktopUIMode;
},
getCanvasLimits: () => ({
areaLimit: plugin.excalidrawConfig?.areaLimit ?? DEFAULT_AREA_LIMIT,
widthHeightLimit:
plugin.excalidrawConfig?.widthHeightLimit ?? DEFAULT_WIDTH_HEIGHT_LIMIT,
}),
getHighlightColor: (sceneBackgroundColor, opacity) =>
plugin.getHighlightColor(sceneBackgroundColor, opacity),
});
@@ -0,0 +1,48 @@
import type ExcalidrawPlugin from "src/core/main";
import { ExcalidrawLib } from "../../types/excalidrawLib";
/**
* Creates the plugin-wide capability adapter consumed by the evaluated
* Excalidraw package runtime.
*
* @remarks
* Settings methods read current values rather than capturing a stale snapshot.
* The adapter exposes only semantic operations and never the plugin instance,
* settings object, or active-view state.
*/
export const createObsidianExcalidrawHostAdapter = (
plugin: ExcalidrawPlugin,
protocolVersion: typeof ExcalidrawLib.OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION,
): ExcalidrawLib.ObsidianExcalidrawHostAdapter => ({
protocolVersion,
isDoubleTapEraserEnabled: () => plugin.settings.penModeDoubleTapEraser,
isRightClickPanEnabled: () => plugin.settings.panWithRightMouseButton,
getZoomToFitMaxLevel: () => plugin.settings.zoomToFitMaxLevel,
isPenModeCrosshairVisible: () => plugin.settings.penModeCrosshairVisible,
isSingleFingerPanningEnabled: () =>
plugin.settings.penModeSingleFingerPanning,
isDoubleClickTextEditingDisabled: () =>
plugin.settings.disableDoubleClickTextEditing,
getZoomStep: () => plugin.settings.zoomStep,
getZoomMin: () => plugin.settings.zoomMin,
getZoomMax: () => plugin.settings.zoomMax,
isContextMenuDisabled: () => plugin.settings.disableContextMenu,
shouldSyncElementLinkWithText: () => plugin.settings.syncElementLinkWithText,
loadFontFromFile: (filename) => plugin.loadFontFromFile(filename),
getMermaid: () => plugin.getMermaid(),
runAction: (action) => plugin.runAction(action),
getLabel: (key) =>
plugin.getLabel(key as Parameters<ExcalidrawPlugin["getLabel"]>[0]),
attachInlineLinkSuggester: (
inputEl,
widthWrapper,
container,
suppressPlaceholder,
) =>
plugin.attachInlineLinkSuggester(
inputEl,
widthWrapper,
container ?? undefined,
suppressPlaceholder,
),
});
+2 -1
View File
@@ -1,10 +1,11 @@
import { Setting, DropdownComponent, App } from "obsidian";
import type { StylesPanelMode } from "@zsviczian/excalidraw/types/common/src/editorInterface";
import { t } from "src/lang/helpers";
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
import { fragWithHTML, setLeftHandedMode, setUIMode } from "src/utils/utils";
import { DEVICE } from "src/constants/constants";
export type UIMode = "full" | "compact" | "tray" | "mobile";
export type UIMode = StylesPanelMode;
//setDesktopUIMode(this.app, this.plugin.settings);
+24 -5
View File
@@ -17,6 +17,8 @@ import {
ExcalidrawFrameElement,
ExcalidrawTextContainer,
ElementsMap,
FixedPointBinding,
BoundElement,
} from "@zsviczian/excalidraw/types/element/src/types";
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
import {
@@ -581,7 +583,7 @@ export class ExcalidrawAutomate {
const blob = new Blob([data], { type });
// Read the blob as Data URL
const base64String = await new Promise((resolve) => {
const base64String = await new Promise<string | null>((resolve) => {
const reader = new FileReader();
reader.onload = () => {
if (typeof reader.result === "string") {
@@ -4712,7 +4714,7 @@ export class ExcalidrawAutomate {
* @returns {ExcalidrawElement} The cloned element with a new ID.
*/
cloneElement(element: ExcalidrawElement): ExcalidrawElement {
const newEl = JSON.parse(JSON.stringify(element));
const newEl = JSON.parse(JSON.stringify(element)) as Mutable<ExcalidrawElement>;
newEl.id = nanoid();
return newEl;
}
@@ -4733,8 +4735,16 @@ export class ExcalidrawAutomate {
// 1. Parse the input
if (typeof elementsOrClipboard === "string") {
try {
const parsed = JSON.parse(elementsOrClipboard);
// Matches the envelope serializeAsClipboardJSON()/actionCopy produce
// upstream (packages/excalidraw/clipboard.ts): {type: "excalidraw/clipboard",
// elements, files}. The bare-array branch below is this method's own
// convenience for a plain JSON-stringified element array, not an
// Excalidraw-produced format.
const parsed = JSON.parse(elementsOrClipboard) as
| { type: string; elements: ExcalidrawElement[] }
| ExcalidrawElement[];
if (
!Array.isArray(parsed) &&
parsed.type === "excalidraw/clipboard" &&
Array.isArray(parsed.elements)
) {
@@ -4779,9 +4789,18 @@ export class ExcalidrawAutomate {
});
// 3. Clone and remap relationships
// Deep-cloned elements are probed for relationship fields (containerId,
// startBinding, endBinding) that only exist on some ExcalidrawElement
// union members -- widened here so the generic remap logic below can
// read/write them regardless of which variant a given element actually is.
type ClonedElementDraft = Mutable<ExcalidrawElement> & {
containerId?: string | null;
startBinding?: FixedPointBinding | null;
endBinding?: FixedPointBinding | null;
};
const clonedElements: ExcalidrawElement[] = elements.map((el) => {
// Deep clone the element
const newEl = JSON.parse(JSON.stringify(el));
const newEl = JSON.parse(JSON.stringify(el)) as ClonedElementDraft;
// Update element ID
newEl.id = idMap.get(el.id)!;
@@ -4801,7 +4820,7 @@ export class ExcalidrawAutomate {
// Remap Bound Elements (e.g., the rectangle holding the text, or arrows attached to a shape)
if (newEl.boundElements && Array.isArray(newEl.boundElements)) {
newEl.boundElements = newEl.boundElements.map(
(bound: { id: string; type: string }) => ({
(bound: BoundElement) => ({
...bound,
id: idMap.get(bound.id) || bound.id, // Fallback to original ID if bound element wasn't cloned
}),
+66 -2
View File
@@ -82,6 +82,63 @@ type EmbeddedLink =
| null;
declare namespace ExcalidrawLib {
type ObsidianCommonHostUIMode = "full" | "compact" | "tray" | "mobile";
type ObsidianCommonHostAdapter = Readonly<{
protocolVersion: 1;
getDeviceInfo: () => Readonly<{
isDesktop: boolean;
isPhone: boolean;
isTablet: boolean;
isMobile: boolean;
isLinux: boolean;
isMacOS: boolean;
isWindows: boolean;
isIOS: boolean;
isAndroid: boolean;
}> | null;
getDesktopUIMode: () => ObsidianCommonHostUIMode;
getPreferredUIMode: (
formFactor: "phone" | "tablet" | "desktop",
) => ObsidianCommonHostUIMode;
getCanvasLimits: () => Readonly<{
areaLimit: number;
widthHeightLimit: number;
}>;
getHighlightColor: (
sceneBackgroundColor: string,
opacity: number,
) => string;
}>;
type ObsidianExcalidrawHostAdapter = Readonly<{
protocolVersion: 2;
isDoubleTapEraserEnabled: () => boolean;
isRightClickPanEnabled: () => boolean;
getZoomToFitMaxLevel: () => number;
isPenModeCrosshairVisible: () => boolean;
isSingleFingerPanningEnabled: () => boolean;
isDoubleClickTextEditingDisabled: () => boolean;
getZoomStep: () => number;
getZoomMin: () => number;
getZoomMax: () => number;
isContextMenuDisabled: () => boolean;
shouldSyncElementLinkWithText: () => boolean;
loadFontFromFile: (filename: string) => Promise<ArrayBuffer | undefined>;
getMermaid: () => Promise<MermaidToExcalidrawLibProps>;
runAction: (action: "anyFile" | "LaTeX" | "card") => void;
getLabel: (key: string) => string;
attachInlineLinkSuggester: (
inputEl: HTMLInputElement | HTMLTextAreaElement,
widthWrapper?: HTMLElement,
container?: HTMLDivElement | null,
suppressPlaceholder?: boolean,
) => Readonly<{
isBlockingKeys: () => boolean;
close: () => void;
}>;
}>;
type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
Partial<TElement>,
"id" | "updated"
@@ -245,7 +302,7 @@ declare namespace ExcalidrawLib {
error?: string;
} | undefined>;*/
let getSceneVersion: typeof import("@zsviczian/excalidraw/types/excalidraw").getSceneVersion;
let hashElementsVersion: typeof import("@zsviczian/excalidraw/types/excalidraw").hashElementsVersion;
let Excalidraw: typeof import("@zsviczian/excalidraw").Excalidraw;
let MainMenu: typeof import("@zsviczian/excalidraw").MainMenu;
let WelcomeScreen: typeof import("@zsviczian/excalidraw").WelcomeScreen;
@@ -254,7 +311,14 @@ declare namespace ExcalidrawLib {
let DiagramToCodePlugin: typeof import("@zsviczian/excalidraw").DiagramToCodePlugin;
function getDataURL(file: Blob | File): Promise<DataURL>;
function destroyObsidianUtils(): void;
const OBSIDIAN_COMMON_HOST_PROTOCOL_VERSION: 1;
function configureObsidianCommonHost(
adapter: ObsidianCommonHostAdapter,
): () => void;
const OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION: 2;
function configureObsidianExcalidrawHost(
adapter: ObsidianExcalidrawHostAdapter,
): () => void;
function registerLocalFont(fontMetrics: FontMetadata, uri: string): void;
function getFontFamilies(): string[];
function registerFontsInCSS(): Promise<void>;
+11 -6
View File
@@ -1,3 +1,5 @@
import type { ColorMaster } from "@zsviczian/colormaster";
import type { TInput } from "@zsviczian/colormaster/types";
import {
MAX_IMAGE_SIZE,
IMAGE_TYPES,
@@ -810,7 +812,10 @@ export function isTextImageTransclusion(
callback: (link: string, file: TFile) => void,
): boolean {
const REG_TRANSCLUSION = /^!\[\[([^|\]]*)?.*?]]$|^!\[[^\]]*?]\((.*?)\)$/g;
const match = text.trim().matchAll(REG_TRANSCLUSION).next(); //reset the iterator
const match: IteratorResult<RegExpMatchArray, undefined> = text
.trim()
.matchAll(REG_TRANSCLUSION)
.next(); //reset the iterator
if (match?.value?.[0]) {
const link = match.value[1] ?? match.value[2];
const file = view.app.metadataCache.getFirstLinkpathDest(
@@ -948,9 +953,9 @@ export function getViewColorPalette(
return [basePalette as string];
}
const cmFactory =
view.hookServer?.getCM?.bind(view.hookServer) ??
view.plugin.ea.getCM.bind(view.plugin.ea);
const hookServer = view.hookServer;
const cmFactory = (color: TInput): ColorMaster =>
hookServer?.getCM ? hookServer.getCM(color) : view.plugin.ea.getCM(color);
type ColorMasterLike = {
lightness?: number;
alpha?: number;
@@ -965,7 +970,7 @@ export function getViewColorPalette(
);
};
const getLightness = (color: string): number => {
const cm = cmFactory?.(color) as unknown;
const cm = cmFactory(color) as unknown;
const value = isColorMasterLike(cm) ? cm.lightness : undefined;
return typeof value === "number" ? value : Number.POSITIVE_INFINITY;
};
@@ -976,7 +981,7 @@ export function getViewColorPalette(
if (color.toLowerCase() === "transparent") {
return "transparent";
}
const cm = cmFactory?.(color) as unknown;
const cm = cmFactory(color) as unknown;
if (isColorMasterLike(cm) && typeof cm.stringHEX === "function") {
try {
const alpha = cm.alpha;
+7 -5
View File
@@ -1438,13 +1438,15 @@ export default class ExcalidrawView
this.zoomToFit(false);
}
excalidrawGetSceneVersion: (elements: ExcalidrawElement[]) => number;
excalidrawHashElementsVersion: (
elements: readonly ExcalidrawElement[],
) => number;
getSceneVersion(elements: readonly ExcalidrawElement[]): number {
if (!this.excalidrawGetSceneVersion) {
this.excalidrawGetSceneVersion =
this.packages.excalidrawLib.getSceneVersion;
if (!this.excalidrawHashElementsVersion) {
this.excalidrawHashElementsVersion =
this.packages.excalidrawLib.hashElementsVersion;
}
return this.excalidrawGetSceneVersion(
return this.excalidrawHashElementsVersion(
elements.filter((el) => !el.isDeleted),
);
}