mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
103
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
479ecaab33 | ||
|
|
044d39badb | ||
|
|
c6ab40470f | ||
|
|
d68d23a989 | ||
|
|
8025e1ed1a | ||
|
|
57dac2e523 | ||
|
|
c3834b3ed3 | ||
|
|
87f3d863b7 | ||
|
|
a23ccee9ad | ||
|
|
6c413038f9 | ||
|
|
4f32647d6f | ||
|
|
b0d3125c37 | ||
|
|
9daa9fa936 | ||
|
|
efb00d1d83 | ||
|
|
d5e2467966 | ||
|
|
ccb1f975f4 | ||
|
|
8d06fe1ee2 | ||
|
|
b7472cb8ad | ||
|
|
eb02975bfc | ||
|
|
6b2b2592e4 | ||
|
|
2ea7cf5513 | ||
|
|
07b16330d6 | ||
|
|
d0898f9fb9 | ||
|
|
dbb9a7dc0b | ||
|
|
9390dec8e2 | ||
|
|
a8e2b0984a | ||
|
|
c78cfcc1e5 | ||
|
|
7067336d0d | ||
|
|
e176d96c97 | ||
|
|
1df7a47832 | ||
|
|
4fcb50b53a | ||
|
|
7b25cfca86 | ||
|
|
b1dd56ddfe | ||
|
|
3c49aba91c | ||
|
|
d2fe360c71 | ||
|
|
d55826a5ac | ||
|
|
f39db658db | ||
|
|
ca6ddb6de8 | ||
|
|
077bbca649 | ||
|
|
b04d56091a | ||
|
|
a397b4a776 | ||
|
|
bc7b8cee44 | ||
|
|
40e2120041 | ||
|
|
3a7b23779e | ||
|
|
f8f8a4e542 | ||
|
|
fcee1f64ae | ||
|
|
bed3b1f26c | ||
|
|
e6b4b77c98 | ||
|
|
86e1e67b8d | ||
|
|
d736e7018e | ||
|
|
6ef6fb8aa8 | ||
|
|
8fb91655c7 | ||
|
|
4b6d8e3a3c | ||
|
|
6362b7d162 | ||
|
|
19a694260d | ||
|
|
dbbc7b3f48 | ||
|
|
5108dd3397 | ||
|
|
133ff8219b | ||
|
|
164a37fd88 | ||
|
|
88e7b47c43 | ||
|
|
1616a72344 | ||
|
|
47b853b3b3 | ||
|
|
2da017b5d3 | ||
|
|
39964d4d70 | ||
|
|
04869e821f | ||
|
|
b35fea7eb7 | ||
|
|
3ceed630b7 | ||
|
|
ee223fa239 | ||
|
|
f1e089930b | ||
|
|
da9dd0fa0b | ||
|
|
04f38a6455 | ||
|
|
6976d0969c | ||
|
|
b196ac3de6 | ||
|
|
776b32216d | ||
|
|
5843e88e6f | ||
|
|
e0c4eecef4 | ||
|
|
fd9090562e | ||
|
|
1a78992ef1 | ||
|
|
703355f036 | ||
|
|
371fa7a254 | ||
|
|
00a1bed763 | ||
|
|
ff2c8536ce | ||
|
|
eee975c44d | ||
|
|
150f5ccbea | ||
|
|
4f5d913004 | ||
|
|
64be1aee1e | ||
|
|
acf7b8d642 | ||
|
|
95d89f2fed | ||
|
|
c86db2152e | ||
|
|
7caf768b8f | ||
|
|
b295723780 | ||
|
|
40e747c3bd | ||
|
|
dd06b07a12 | ||
|
|
b4df1d8e5b | ||
|
|
614f0fbab0 | ||
|
|
07ff3b7e96 | ||
|
|
75940d6173 | ||
|
|
8ba60c43e8 | ||
|
|
ae73115e9c | ||
|
|
723c7c5de2 | ||
|
|
680ae101cb | ||
|
|
82578a0a58 | ||
|
|
8c2da6a1c3 |
No files matched your search
@@ -37,24 +37,16 @@ Use https://github.com/obsidian-typings/obsidian-typings as a reference when dea
|
||||
|
||||
Treat build code and runtime code as one system.
|
||||
|
||||
## Project overview
|
||||
## Project Overview And Tooling
|
||||
|
||||
- Target: Obsidian Community Plugin (TypeScript → bundled JavaScript).
|
||||
- Entry point: `src/main.ts` compiled to `main.js` and loaded by Obsidian.
|
||||
- Required release artifacts: `main.js`, `manifest.json`, and optional `styles.css`.
|
||||
|
||||
## Environment & tooling
|
||||
|
||||
- Node.js: use current LTS (Node 22+).
|
||||
- **Package manager: npm** (required for this sample - `package.json` defines npm scripts and dependencies).
|
||||
- **Bundler: esbuild** (required for this sample - `esbuild.config.mjs` and build scripts depend on it). Alternative bundlers like Rollup or webpack are acceptable for other projects if they bundle all external dependencies into `main.js`.
|
||||
- Types: `obsidian` type definitions.
|
||||
|
||||
## Linting
|
||||
|
||||
- ESLint is preconfigured with `eslint-plugin-obsidianmd` for Obsidian-specific rules.
|
||||
- Run `npm run lint` to lint the project.
|
||||
- A GitHub Action automatically lints every commit on all branches.
|
||||
- Runtime entry point: `src/core/main.ts`, compiled by `rollup.config.mjs` to `dist/main.js`.
|
||||
- Required release artifacts: `main.js`, `manifest.json`, and `styles.css`.
|
||||
- Node.js: use Node 22 or newer. Check `node --version` before diagnosing build-tool failures; mixed Node/Corepack installations can produce misleading errors.
|
||||
- Package manager: npm. Use `npm install` and the scripts in this repository's `package.json`.
|
||||
- Runtime bundler: Rollup. Do not replace this build with a sample-plugin esbuild setup; Rollup also assembles compressed runtime payloads and merged CSS.
|
||||
- Primary lint command: `npm run code`. `npm run lint` is broader and may expose unrelated repository backlog.
|
||||
- Types: Obsidian type definitions plus conservative declarations for intentionally used unpublished APIs.
|
||||
|
||||
## Security, privacy, and compliance
|
||||
|
||||
@@ -85,6 +77,7 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
## Performance
|
||||
|
||||
@@ -191,20 +184,69 @@ This project uses a non-trivial Rollup build because startup time, popout-window
|
||||
|
||||
The build embeds or injects runtime code for:
|
||||
|
||||
- React and ReactDOM
|
||||
- a JSX runtime shim for compatibility
|
||||
- the customized `@zsviczian/excalidraw` package
|
||||
- React, ReactDOM/client, and the official JSX runtime entry points built from the installed npm packages
|
||||
- the customized `@zsviczian/excalidraw` Obsidian artifact built from Excalidraw's ESM source graph
|
||||
- `MathjaxToSVG`
|
||||
- `lz-string`
|
||||
- selected compressed locale payloads
|
||||
|
||||
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.
|
||||
|
||||
### Two-Repository Excalidraw Workflow
|
||||
|
||||
The customized component lives in the sibling `zsviczian/excalidraw` repository. When both repositories are available locally, it is normally at `../excalidraw`; verify the actual workspace path and branch instead of assuming it.
|
||||
|
||||
- The Excalidraw repository uses Yarn and builds the consumer-specific payload from `packages/excalidraw` with `yarn build:obsidian`.
|
||||
- That build emits four files under `packages/excalidraw/dist/obsidian/`: production and development JavaScript plus production and development CSS.
|
||||
- This plugin consumes the same four paths from `node_modules/@zsviczian/excalidraw/dist/obsidian/` in `rollup.config.mjs`.
|
||||
- For a temporary unpublished integration test, build the sibling package and copy only those four generated files into the installed package under `node_modules`. Do not change `package.json` or `package-lock.json` to a local `file:` dependency merely for this handoff. A later `npm install` restores the published package.
|
||||
- For the durable handoff, publish a new `@zsviczian/excalidraw` version, update this repository's dependency, run `npm install`, and rebuild the plugin.
|
||||
- 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.
|
||||
- This is necessary because the plugin must work in Obsidian/Electron popout windows.
|
||||
- Do not replace this with a naive global singleton approach.
|
||||
- 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.
|
||||
|
||||
### Main-Window Persistent Storage
|
||||
|
||||
Window ownership for rendering is not the same as ownership for persistent plugin data.
|
||||
|
||||
- Existing plugin-level IndexedDB and local-storage data belongs to Obsidian's main application window and must remain shared across normal views and popouts.
|
||||
- Do not change persistent storage to `view.ownerWindow`, create one database per popout, or infer a storage migration from a rendering bug unless the task explicitly requires that behavior.
|
||||
- Diagnose persistence and presentation separately. For example, a visible history button conditioned on loaded records proves the load path worked even when a portaled history menu is hidden.
|
||||
- If a new feature is intentionally view-local, document that exception and test window migration and popout teardown explicitly.
|
||||
|
||||
### MathJax Subproject
|
||||
|
||||
@@ -244,6 +286,16 @@ These payloads are executed or unpacked at runtime. This is intentional.
|
||||
- Preserve existing abstractions unless the task clearly requires a redesign.
|
||||
- Avoid broad refactors unless there is strong evidence they are necessary.
|
||||
|
||||
### Incremental Refactoring Protocol
|
||||
|
||||
- Use `RefactorPlan.md` as the living architectural record. Update the progress table and append an action-log entry after each completed or reverted checkpoint.
|
||||
- Make one independently testable behavior change or mechanical extraction at a time. Prefer moving code intact before simplifying it.
|
||||
- Preserve timers, observers, semaphores, lifecycle ordering, and unpublished-API workarounds unless their purpose has been traced and an equivalent behavior has been verified across affected platforms.
|
||||
- Do not convert `ExcalidrawView` wholesale into React. It must remain an Obsidian `TextFileView`; React is the child rendering runtime. Extract cohesive view-scoped controllers and components while retaining compatibility delegates on the view.
|
||||
- For duplicate utilities, compare every implementation and caller before consolidation. Marginal behavior differences must be shown unused or deliberately preserved.
|
||||
- Do not derive a runtime settings sanitizer from the TypeScript interface. Interfaces do not exist at runtime, settings evolve frequently, and unknown keys may belong to a newer or companion version. Remove obsolete keys only through an explicit, reviewed migration or retirement decision.
|
||||
- End every checkpoint with risk-based manual test recommendations: identify the highest-probability failure, the affected workflow, and whether main-window, popout, desktop operating systems, and mobile need separate coverage.
|
||||
|
||||
## Naming And Placement Conventions
|
||||
|
||||
Treat the following as the target convention for all new code and for any future naming-cleanup pass. The current repository contains legacy exceptions. Do not rename files opportunistically inside behavior changes; do naming cleanup in a dedicated, compatibility-aware refactor.
|
||||
@@ -301,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
|
||||
|
||||
@@ -412,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.
|
||||
@@ -419,6 +473,12 @@ 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.
|
||||
- Prefer targeted diagnostics for the files you touched when repo-wide lint noise obscures signal.
|
||||
- Prefer `npm run build` plus targeted file diagnostics over raw `tsc --noEmit` as the primary gate. Standalone `tsc` can surface large volumes of dependency-typing noise unrelated to touched files.
|
||||
- Do not treat `dist/` output edits as source fixes.
|
||||
@@ -433,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.
|
||||
@@ -442,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.
|
||||
@@ -550,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`.
|
||||
@@ -611,7 +652,7 @@ In some cases, `@typescript-eslint/no-explicit-any` or `@typescript-eslint/no-un
|
||||
|
||||
- **Provider-specific dynamic payloads**: AI providers, image APIs, and other external services return schemas that vary by provider. Normalizing these requires accepting `any` properties or using type assertions on the `item` parameter to access provider-specific fields.
|
||||
- Example: `(item: Record<string, any>) => item.image?.url || item.image?.b64_json` normalizes images from different providers into a common schema.
|
||||
|
||||
|
||||
- **Mutation-path type casts**: When updating scene elements or bound references, Excalidraw type definitions may return readonly or union types, but the mutation path requires the mutable variant. The assertion is necessary and doesn't bypass a real type mismatch.
|
||||
- Example: `sceneElements.find(...) as unknown as Mutable<ExcalidrawElement>` during ID migration where the lookup guarantees the mutable variant exists.
|
||||
|
||||
|
||||
+65
-9
@@ -1,6 +1,6 @@
|
||||
# Contributing to Obsidian Excalidraw Plugin
|
||||
|
||||
First off, thank you for considering contributing to the Obsidian Excalidraw plugin! This project integrates a heavily customized Excalidraw fork into Obsidian.
|
||||
First off, thank you for considering contributing to the Obsidian Excalidraw plugin! This project integrates a heavily customized Excalidraw fork into Obsidian.
|
||||
|
||||
Because this is not a generic React canvas app, but rather a deeply integrated Obsidian plugin with popout window support, mobile compatibility constraints, and performance optimizations, please read the following guidelines carefully before making any changes.
|
||||
|
||||
@@ -11,25 +11,40 @@ Before spending your valuable time writing code for a new feature or significant
|
||||
## 🚀 Getting Started
|
||||
|
||||
1. Fork the repository and clone it locally.
|
||||
2. Run `npm install` in the root directory to install the main dependencies.
|
||||
2. Use Node.js 22 or newer and verify it with `node --version`. A shell that mixes a different Node binary with another installation's Corepack can fail before a build starts.
|
||||
3. Run `npm install` in the root directory to install the main dependencies.
|
||||
*(Note: The `MathjaxToSVG` sub-component has its own separate dependencies. You do not need to install them manually; the first time you run `npm run build`, it will take care of this automatically).*
|
||||
3. To test your changes locally, we recommend symlinking your cloned repository folder into a test Obsidian vault's `.obsidian/plugins/obsidian-excalidraw-plugin` directory. (Using a community plugin like [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) will make local development much faster).
|
||||
4. To test your changes locally, we recommend symlinking your cloned repository folder into a test Obsidian vault's `.obsidian/plugins/obsidian-excalidraw-plugin` directory. (Using a community plugin like [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) will make local development much faster).
|
||||
|
||||
## 🛠️ Build and Lint Commands
|
||||
|
||||
- **Build the project:** Run `npm run build`
|
||||
*(Note: Our Rollup build is non-trivial as it merges CSS, handles MathjaxToSVG dependencies, and embeds runtime payloads. Run this command frequently to validate your changes).*
|
||||
- **Build readable development payloads:** Run `npm run dev`
|
||||
- **Build the public library API:** Run `npm run lib` when changing exports or ExcalidrawAutomate APIs
|
||||
- **Run ESLint:** Run `npm run code`
|
||||
- **Fix ESLint Warnings:** Run `node ./scripts/fix-eslint-warnings.mjs`
|
||||
|
||||
The shipped plugin is `dist/main.js`, `dist/styles.css`, and `dist/manifest.json`. Keep `main.js` below the release size limit and report its byte size after dependency or packaging changes.
|
||||
|
||||
## 🧪 Testing
|
||||
|
||||
At this time, the project **has no automated tests**. As a contributor, you are responsible for testing your changes thoroughly.
|
||||
At this time, the project **has no comprehensive automated test suite**. As a contributor, you are responsible for testing your changes thoroughly.
|
||||
|
||||
Because Obsidian runs across a variety of environments, please manually test your changes on as many of the following platforms as possible to avoid breaking the plugin for other users:
|
||||
- Desktop: Mac, Windows, Linux
|
||||
- Mobile: Android, iOS (Test on both Phones and Tablets)
|
||||
|
||||
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
|
||||
- a newly opened and restored popout window
|
||||
- plugin reload and cold application startup
|
||||
- desktop and mobile layouts
|
||||
- offline mode, when the change affects packaged assets or runtime loading
|
||||
|
||||
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
|
||||
|
||||
- **Do not use direct `console.log(...)` calls in project code.** Use the shared logging helper exported as `log` from `src/utils/debugHelper.ts`.
|
||||
@@ -40,9 +55,19 @@ Because Obsidian runs across a variety of environments, please manually test you
|
||||
This project consists of multiple sub-components and non-standard integrations to support Obsidian-specific features.
|
||||
|
||||
### 1. React & Package Manager
|
||||
Because the plugin must support Obsidian's native popout windows, React and Excalidraw cannot be loaded as simple global singletons.
|
||||
Because the plugin must support Obsidian's native popout windows, React and Excalidraw cannot be loaded as simple global singletons.
|
||||
- References to React and ReactDOM are handled via `PackageManager.ts` (`src/core/managers/PackageManager.ts`).
|
||||
- They are loaded to Obsidian popout windows separately during runtime. Do not introduce direct `ReactDOM.createRoot()` or similar global React calls outside of this package manager model.
|
||||
- The runtime is assembled from official React npm entry points and loaded separately for each Obsidian window.
|
||||
- Do not introduce direct `ReactDOM.createRoot()` calls outside this package-manager model.
|
||||
- Do not publish React or ReactDOM on `window`. The documented `window.ExcalidrawLib` scripting surface is the deliberate exception.
|
||||
|
||||
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).
|
||||
@@ -50,7 +75,7 @@ LaTeX support is provided by the `MathjaxToSVG` library, which is packaged as a
|
||||
- It is decompressed and executed dynamically during runtime only when needed, maintaining optimal Obsidian startup times.
|
||||
|
||||
### 3. Excalidraw Fork Guidelines
|
||||
This plugin relies on a custom Excalidraw component fork: [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/).
|
||||
This plugin relies on a custom Excalidraw component fork: [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/).
|
||||
|
||||
If you must submit a PR to the Excalidraw fork, **keep changes to the absolute minimum**. Compounding changes to the fork make merging upstream updates from `excalidraw/excalidraw` exponentially harder.
|
||||
|
||||
@@ -87,11 +112,42 @@ If you must submit a PR to the Excalidraw fork, **keep changes to the absolute m
|
||||
private startRightClickPanning(event) { ... }
|
||||
```
|
||||
|
||||
### 4. Working Across Both Repositories
|
||||
|
||||
The customized component is maintained in the separate [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/) repository. When both repositories are checked out as siblings, the usual path is `../excalidraw`.
|
||||
|
||||
The repositories deliberately use different package managers:
|
||||
|
||||
- `obsidian-excalidraw-plugin`: npm
|
||||
- `zsviczian/excalidraw`: Yarn
|
||||
|
||||
From `../excalidraw/packages/excalidraw`, `yarn build:obsidian` produces four consumer-specific files in `dist/obsidian`: development and production JavaScript and CSS. This plugin reads the corresponding four files from `node_modules/@zsviczian/excalidraw/dist/obsidian/`.
|
||||
|
||||
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
|
||||
- React, ReactDOM, and their JSX runtimes remain external and are supplied by this plugin
|
||||
- Mermaid remains external and is loaded lazily through Excalidraw Extras
|
||||
- all required assets work offline except deliberately lazy CJK font subsets
|
||||
- production is minified; development retains debugger-friendly source information
|
||||
|
||||
Radix menus and popovers may be portaled to the owning document body by `ObsidianRadixPortal`. Portaled content no longer has its original component ancestors and can sit behind modal stacking contexts. Style portaled content through a class that survives the portal, and test visibility, positioning, click-outside, and Escape behavior in the main window and a popout.
|
||||
|
||||
### 5. Incremental Refactoring
|
||||
|
||||
Use `RefactorPlan.md` as the living record for ongoing structural work. Refactors should be small enough to build and test independently. Move cohesive code intact before redesigning it, update the progress table and action log, and provide a risk-based test checklist at the end of each step.
|
||||
|
||||
`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.
|
||||
|
||||
## 🌍 Localization & User-Facing Text
|
||||
|
||||
- **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.
|
||||
- **Language files:** All strings must be added to the localization files located in `src/lang/locale/`.
|
||||
- **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
|
||||
|
||||
|
||||
+1805
File diff suppressed because it is too large.
Load diff
@@ -182,7 +182,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.svg"/></div>|[[#Create DrawIO file]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
|
||||
@@ -358,12 +357,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
|
||||
|
||||
## Create DrawIO file
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="https://www.youtube.com/watch?v=DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
|
||||
|
||||
## Create new markdown file and embed into active drawing
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
|
||||
@@ -7837,46 +7830,6 @@ if(element.type === 'arrow') {
|
||||
|
||||
---
|
||||
|
||||
## Create DrawIO file.md
|
||||
<!-- Source: ea-scripts/Create DrawIO file.md -->
|
||||
|
||||
/*
|
||||
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
|
||||
```js*/
|
||||
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
|
||||
const drawIO = app.plugins.plugins["drawio-obsidian"];
|
||||
if(!drawIO || !drawIO?._loaded) {
|
||||
new Notice("Can't find the draw.io diagram plugin");
|
||||
}
|
||||
|
||||
filename = await utils.inputPrompt("Diagram name?");
|
||||
if(!filename) return;
|
||||
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
|
||||
const filepath = await ea.getAttachmentFilepath(filename);
|
||||
if(!filepath) return;
|
||||
const leaf = app.workspace.getLeaf('tab')
|
||||
if(!leaf) return;
|
||||
|
||||
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>"></svg>`);
|
||||
|
||||
await ea.addImage(0,0,file);
|
||||
await ea.addElementsToView(true,true);
|
||||
|
||||
leaf.setViewState({
|
||||
type: "diagram-edit",
|
||||
state: {
|
||||
file: filepath
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Create new markdown file and embed into active drawing.md
|
||||
<!-- Source: ea-scripts/Create new markdown file and embed into active drawing.md -->
|
||||
|
||||
|
||||
@@ -4796,7 +4796,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.svg"/></div>|[[#Create DrawIO file]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
|
||||
@@ -4972,12 +4971,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
|
||||
|
||||
## Create DrawIO file
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="YouTube: DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
|
||||
|
||||
## Create new markdown file and embed into active drawing
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
|
||||
@@ -12451,46 +12444,6 @@ if(element.type === 'arrow') {
|
||||
|
||||
---
|
||||
|
||||
## Create DrawIO file.md
|
||||
<!-- Source: ea-scripts/Create DrawIO file.md -->
|
||||
|
||||
/*
|
||||
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
|
||||
```js*/
|
||||
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
|
||||
const drawIO = app.plugins.plugins["drawio-obsidian"];
|
||||
if(!drawIO || !drawIO?._loaded) {
|
||||
new Notice("Can't find the draw.io diagram plugin");
|
||||
}
|
||||
|
||||
filename = await utils.inputPrompt("Diagram name?");
|
||||
if(!filename) return;
|
||||
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
|
||||
const filepath = await ea.getAttachmentFilepath(filename);
|
||||
if(!filepath) return;
|
||||
const leaf = app.workspace.getLeaf('tab')
|
||||
if(!leaf) return;
|
||||
|
||||
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>"></svg>`);
|
||||
|
||||
await ea.addImage(0,0,file);
|
||||
await ea.addElementsToView(true,true);
|
||||
|
||||
leaf.setViewState({
|
||||
type: "diagram-edit",
|
||||
state: {
|
||||
file: filepath
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Create new markdown file and embed into active drawing.md
|
||||
<!-- Source: ea-scripts/Create new markdown file and embed into active drawing.md -->
|
||||
|
||||
@@ -46316,4 +46269,3 @@ ea.onSceneChangeHook = {
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -9,11 +9,11 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
|
||||
- **addAppendUpdateCustomData**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
|
||||
- **addArrow**: [Concatenate lines.md](scripts/Concatenate%20lines.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md)
|
||||
- **addDiamond**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **addElementsToView**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%20selected%20elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Icon Library.md](scripts/Icon%20Library.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md), [Uniform sizLine truncated
|
||||
- **addElementsToView**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Change shape of selected elements.md](scripts/Change%20shape%20of%20selected%20elements.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Convert text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Elbow connectors.md](scripts/Elbow%20connectors.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Expand rectangles horizontally keep text centered.md](scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.md), [Expand rectangles horizontally.md](scripts/Expand%20rectangles%20horizontally.md), [Expand rectangles vertically keep text centered.md](scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md), [Expand rectangles vertically.md](scripts/Expand%20rectangles%20vertically.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Icon Library.md](scripts/Icon%20Library.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Mindmap format.md](scripts/Mindmap%20format.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Rename Image.md](scripts/Rename%20Image.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Reverse arrows.md](scripts/Reverse%20arrows.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Dimensions.md](scripts/Set%20Dimensions.md), [Set Font Family.md](scripts/Set%20Font%20Family.md), [Set Link Alias.md](scripts/Set%20Link%20Alias.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Set Text Alignment.md](scripts/Set%20Text%20Alignment.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [To Line.md](scripts/To%20Line.md), [Uniform size.md](scripts/Uniform%20size.md)
|
||||
- **addEllipse**: [Add Connector Point.md](scripts/Add%20Connector%20Point.md), [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **addEmbeddable**: [Capture Note.md](scripts/Capture%20Note.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Collaboration Frame.md](scripts/Excalidraw%20Collaboration%20Frame.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **addFrame**: [Capture Note.md](scripts/Capture%20Note.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
|
||||
- **addImage**: [Capture Note.md](scripts/Capture%20Note.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **addImage**: [Capture Note.md](scripts/Capture%20Note.md), [Create new markdown file and embed into active drawing.md](scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **addLaTex**: [ExcaliMath.md](scripts/ExcaliMath.md)
|
||||
- **addLine**: [Boolean Operations.md](scripts/Boolean%20Operations.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Concatenate lines.md](scripts/Concatenate%20lines.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap connector.md](scripts/Mindmap%20connector.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [To Line.md](scripts/To%20Line.md)
|
||||
- **addMermaid**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
@@ -46,10 +46,10 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
|
||||
- **formatAIUsageLabel**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
- **generateAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
- **generateAIText**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
- **generateElementId**: [Capture Note.md](scripts/Capture%20Note.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
|
||||
- **generateElementId**: [Capture Note.md](scripts/Capture%20Note.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
|
||||
- **getAISettings**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
- **getAPI**: [Capture Note.md](scripts/Capture%20Note.md)
|
||||
- **getAttachmentFilepath**: [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
|
||||
- **getAttachmentFilepath**: [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
|
||||
- **getBoundingBox**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Grid Selected Images.md](scripts/Grid%20Selected%20Images.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Slideshow.md](scripts/Slideshow.md)
|
||||
- **getBoundTextElement**: [Capture Note.md](scripts/Capture%20Note.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **getCM**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Invert colors.md](scripts/Invert%20colors.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Shade Master.md](scripts/Shade%20Master.md), [Text Aura.md](scripts/Text%20Aura.md)
|
||||
@@ -116,7 +116,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
|
||||
- **toggleSidepanelView**: [Capture Note.md](scripts/Capture%20Note.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
|
||||
- **transformAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
- **updateViewSVGImageColorMap**: [Shade Master.md](scripts/Shade%20Master.md)
|
||||
- **verifyMinimumPluginVersion**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Create DrawIO file.md](scripts/Create%20DrawIO%20file.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
|
||||
- **verifyMinimumPluginVersion**: [Add Link to Existing File and Open.md](scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md), [Add Link to New Page and Open.md](scripts/Add%20Link%20to%20New%20Page%20and%20Open.md), [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Auto Layout.md](scripts/Auto%20Layout.md), [Boolean Operations.md](scripts/Boolean%20Operations.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Connect elements.md](scripts/Connect%20elements.md), [Convert freedraw to line.md](scripts/Convert%20freedraw%20to%20line.md), [Convert selected text elements to sticky notes.md](scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Darken background color.md](scripts/Darken%20background%20color.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Fixed horizontal distance between centers.md](scripts/Fixed%20horizontal%20distance%20between%20centers.md), [Fixed inner distance.md](scripts/Fixed%20inner%20distance.md), [Fixed spacing.md](scripts/Fixed%20spacing.md), [Fixed vertical distance between centers.md](scripts/Fixed%20vertical%20distance%20between%20centers.md), [Fixed vertical distance.md](scripts/Fixed%20vertical%20distance.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Modify background color opacity.md](scripts/Modify%20background%20color%20opacity.md), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md), [Organic Line.md](scripts/Organic%20Line.md), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Set background color of unclosed line object by adding a shadow clone.md](scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md), [Set Grid.md](scripts/Set%20Grid.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
|
||||
- **viewToggleFullScreen**: [Slideshow.md](scripts/Slideshow.md)
|
||||
- **viewUpdateScene**: [Invert colors.md](scripts/Invert%20colors.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palette loader.md](scripts/Palette%20loader.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Relative Font Size Cycle.md](scripts/Relative%20Font%20Size%20Cycle.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Toggle Grid.md](scripts/Toggle%20Grid.md)
|
||||
- **viewZoomToElements**: [Capture Note.md](scripts/Capture%20Note.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md)
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
/*
|
||||
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
|
||||
```js*/
|
||||
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
|
||||
const drawIO = app.plugins.plugins["drawio-obsidian"];
|
||||
if(!drawIO || !drawIO?._loaded) {
|
||||
new Notice("Can't find the draw.io diagram plugin");
|
||||
}
|
||||
|
||||
filename = await utils.inputPrompt("Diagram name?");
|
||||
if(!filename) return;
|
||||
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
|
||||
const filepath = await ea.getAttachmentFilepath(filename);
|
||||
if(!filepath) return;
|
||||
const leaf = app.workspace.getLeaf('tab')
|
||||
if(!leaf) return;
|
||||
|
||||
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>"></svg>`);
|
||||
|
||||
await ea.addImage(0,0,file);
|
||||
await ea.addElementsToView(true,true);
|
||||
|
||||
leaf.setViewState({
|
||||
type: "diagram-edit",
|
||||
state: {
|
||||
file: filepath
|
||||
}
|
||||
});
|
||||
|
||||
```
|
||||
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
Creates a new draw.io diagram file and opens the file in the [Diagram plugin](https://github.com/zapthedingbat/drawio-obsidian) in a new tab.
|
||||
```js*/
|
||||
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.7")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
|
||||
const drawIO = app.plugins.plugins["drawio-obsidian"];
|
||||
if(!drawIO || !drawIO?._loaded) {
|
||||
new Notice("Can't find the draw.io diagram plugin");
|
||||
}
|
||||
|
||||
filename = await utils.inputPrompt("Diagram name?");
|
||||
if(!filename) return;
|
||||
filename = filename.toLowerCase().endsWith(".svg") ? filename : filename + ".svg";
|
||||
const filepath = await ea.getAttachmentFilepath(filename);
|
||||
if(!filepath) return;
|
||||
const leaf = app.workspace.getLeaf('tab')
|
||||
if(!leaf) return;
|
||||
|
||||
const file = await this.app.vault.create(filepath, `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><!--${ea.generateElementId()}--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="300px" height="300px" viewBox="-0.5 -0.5 1 1" content="<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>"></svg>`);
|
||||
|
||||
await ea.addImage(0,0,file);
|
||||
await ea.addElementsToView(true,true);
|
||||
|
||||
leaf.setViewState({
|
||||
type: "diagram-edit",
|
||||
state: {
|
||||
file: filepath
|
||||
}
|
||||
});
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" viewBox="24 26 68 68" stroke="#000"><path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3.553" d="m58.069 43.384-17.008 29.01"/><path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="3.501" d="m58.068 43.384 17.008 29.01"/><path fill="#000" d="M52.773 77.084a3.564 3.564 0 0 1-3.553 3.553H36.999a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553h12.222a3.564 3.564 0 0 1 3.553 3.553v9.379zM67.762 48.074a3.564 3.564 0 0 1-3.553 3.553H51.988a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553H64.21a3.564 3.564 0 0 1 3.553 3.553v9.379zM82.752 77.084a3.564 3.564 0 0 1-3.553 3.553H66.977a3.564 3.564 0 0 1-3.553-3.553v-9.379a3.564 3.564 0 0 1 3.553-3.553h12.222a3.564 3.564 0 0 1 3.553 3.553v9.379z"/></svg>
|
||||
|
Before Width: | Height: | Size: 830 B |
@@ -471,14 +471,6 @@
|
||||
"fname": "Excalidraw Collaboration Frame.svg",
|
||||
"mtime": 1687881495985
|
||||
},
|
||||
{
|
||||
"fname": "Create DrawIO file.md",
|
||||
"mtime": 1688243858267
|
||||
},
|
||||
{
|
||||
"fname": "Create DrawIO file.svg",
|
||||
"mtime": 1688243858267
|
||||
},
|
||||
{
|
||||
"fname": "Ellipse Selected Elements.md",
|
||||
"mtime": 1690131476331
|
||||
|
||||
@@ -164,7 +164,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.svg"/></div>|[[#Create DrawIO file]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
|
||||
@@ -340,12 +339,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
|
||||
|
||||
## Create DrawIO file
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="https://www.youtube.com/watch?v=DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
|
||||
|
||||
## Create new markdown file and embed into active drawing
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
|
||||
|
||||
@@ -28,6 +28,20 @@ export default tseslint.config(
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
// Buffer/NodeJS/BufferEncoding: genuine ambient Node types available
|
||||
// in Obsidian's Electron environment (used e.g. in DataAdapter.fs
|
||||
// callbacks in src/types/types.d.ts).
|
||||
...globals.node,
|
||||
// @types/react/global.d.ts declares this as a bare top-level
|
||||
// `interface` (an ambient script, not a module), so it becomes a
|
||||
// real global type alongside HTMLDivElement etc. -- not something
|
||||
// that can be imported.
|
||||
HTMLWebViewElement: 'readonly',
|
||||
// NodeJS/BufferEncoding: ambient @types/node type/namespace names
|
||||
// (globals.node above only covers runtime values like `Buffer`,
|
||||
// not these TS-only type names).
|
||||
NodeJS: 'readonly',
|
||||
BufferEncoding: 'readonly',
|
||||
},
|
||||
parserOptions: {
|
||||
projectService: {
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.26.0-rc.4",
|
||||
"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",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.25.3",
|
||||
"version": "2.26.4",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+52
-102
@@ -13,22 +13,20 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.116",
|
||||
"@zsviczian/excalidraw": "0.18.124",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
"gl-matrix": "^3.4.3",
|
||||
"lz-string": "^1.5.0",
|
||||
"monkey-around": "^2.3.0",
|
||||
"nanoid": "^5.1.11",
|
||||
"opentype.js": "^1.3.4",
|
||||
"nanoid": "^5.1.16",
|
||||
"pako": "^2.1.0",
|
||||
"points-on-path": "^0.2.1",
|
||||
"polybooljs": "^1.2.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"roughjs": "^4.5.2",
|
||||
"yaml": "^2.9.0"
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8",
|
||||
"roughjs": "^4.5.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.22.9",
|
||||
@@ -52,9 +50,8 @@
|
||||
"@types/chroma-js": "^3.1.1",
|
||||
"@types/js-beautify": "^1.14.0",
|
||||
"@types/node": "^22.19.19",
|
||||
"@types/opentype.js": "^1.3.8",
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
"@types/react": "19.2.18",
|
||||
"@types/react-dom": "19.2.4",
|
||||
"@zsviczian/excalidraw-extras-api": "^0.0.13",
|
||||
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
|
||||
"cross-env": "^7.0.3",
|
||||
@@ -64,7 +61,6 @@
|
||||
"eslint-plugin-obsidianmd": "^0.4.0",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"jiti": "^2.6.1",
|
||||
"jsesc": "^3.0.2",
|
||||
"obsidian": "1.8.7",
|
||||
"postcss": "^8.5.25",
|
||||
"prettier": "^3.0.1",
|
||||
@@ -2088,31 +2084,31 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/core": {
|
||||
"version": "1.7.5",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz",
|
||||
"integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==",
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz",
|
||||
"integrity": "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/utils": "^0.2.11"
|
||||
"@floating-ui/utils": "^0.2.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/dom": {
|
||||
"version": "1.7.6",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz",
|
||||
"integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==",
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.8.0.tgz",
|
||||
"integrity": "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/core": "^1.7.5",
|
||||
"@floating-ui/utils": "^0.2.11"
|
||||
"@floating-ui/core": "^1.8.0",
|
||||
"@floating-ui/utils": "^0.2.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/react-dom": {
|
||||
"version": "2.1.8",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.8.tgz",
|
||||
"integrity": "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==",
|
||||
"version": "2.1.9",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.9.tgz",
|
||||
"integrity": "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@floating-ui/dom": "^1.7.6"
|
||||
"@floating-ui/dom": "^1.8.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
@@ -2120,9 +2116,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@floating-ui/utils": {
|
||||
"version": "0.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz",
|
||||
"integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==",
|
||||
"version": "0.2.12",
|
||||
"resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz",
|
||||
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@humanfs/core": {
|
||||
@@ -4891,39 +4887,24 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/opentype.js": {
|
||||
"version": "1.3.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/opentype.js/-/opentype.js-1.3.10.tgz",
|
||||
"integrity": "sha512-F67EFyk6j02okHz5JCgata3ZRAcZi9GLnzmkHw/rzJq3OCc8/ZVdoKrxMTYjcQP6IYHGBz2cav1cpzkOkPiPCQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/prop-types": {
|
||||
"version": "15.7.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
|
||||
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "18.3.31",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
|
||||
"integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
|
||||
"version": "19.2.18",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz",
|
||||
"integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react-dom": {
|
||||
"version": "18.3.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"version": "19.2.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.4.tgz",
|
||||
"integrity": "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.0.0"
|
||||
"@types/react": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/resolve": {
|
||||
@@ -5274,9 +5255,10 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/excalidraw": {
|
||||
"version": "0.18.116",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.116.tgz",
|
||||
"integrity": "sha512-cq/jChIEDdmWt/B1ZQUauMqi7wj/vNda0TZjqQ89ju9n8mLrvh9J7f3OZJQ+m/BYOesd1RrY8Nm4SZfBj37Ajg==",
|
||||
"version": "0.18.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",
|
||||
"@codemirror/commands": "^6.0.0",
|
||||
@@ -9652,6 +9634,7 @@
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
|
||||
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
@@ -9988,6 +9971,7 @@
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
||||
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"js-tokens": "^3.0.0 || ^4.0.0"
|
||||
@@ -10238,9 +10222,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "5.1.11",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.11.tgz",
|
||||
"integrity": "sha512-v+KEsUv2ps74PaSKv0gHTxTCgMXOIfBEbaqa6w6ISIGC7ZsvHN4N9oJ8d4cmf0n5oTzQz2SLmThbQWhjd/8eKg==",
|
||||
"version": "5.1.16",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.16.tgz",
|
||||
"integrity": "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -10481,22 +10465,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/opentype.js": {
|
||||
"version": "1.3.4",
|
||||
"resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-1.3.4.tgz",
|
||||
"integrity": "sha512-d2JE9RP/6uagpQAVtJoF0pJJA/fgai89Cc50Yp0EJHk+eLp6QQ7gBoblsnubRULNY132I0J1QKMJ+JTbMqz4sw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"string.prototype.codepointat": "^0.2.1",
|
||||
"tiny-inflate": "^1.0.3"
|
||||
},
|
||||
"bin": {
|
||||
"ot": "bin/ot"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/optionator": {
|
||||
"version": "0.9.4",
|
||||
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
|
||||
@@ -11409,28 +11377,24 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react": {
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"version": "19.2.8",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz",
|
||||
"integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-dom": {
|
||||
"version": "18.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"version": "19.2.8",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz",
|
||||
"integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^18.3.1"
|
||||
"react": "^19.2.8"
|
||||
}
|
||||
},
|
||||
"node_modules/react-is": {
|
||||
@@ -12011,13 +11975,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
"version": "0.23.2",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
|
||||
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
}
|
||||
"version": "0.27.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
|
||||
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "6.3.1",
|
||||
@@ -12291,12 +12252,6 @@
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/string.prototype.codepointat": {
|
||||
"version": "0.2.1",
|
||||
"resolved": "https://registry.npmjs.org/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz",
|
||||
"integrity": "sha512-2cBVCj6I4IOvEnjgO/hWqXjqBGsY+zwPmHl12Srk9IXSZ56Jwwmy+66XO5Iut/oQVR7t5ihYdLB0GMa4alEUcg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/string.prototype.matchall": {
|
||||
"version": "4.0.12",
|
||||
"resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz",
|
||||
@@ -12574,12 +12529,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tiny-inflate": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz",
|
||||
"integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinyexec": {
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.4.tgz",
|
||||
@@ -13282,6 +13231,7 @@
|
||||
"version": "2.9.0",
|
||||
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
|
||||
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"yaml": "bin.mjs"
|
||||
|
||||
+8
-12
@@ -30,22 +30,20 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.116",
|
||||
"@zsviczian/excalidraw": "0.18.124",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
"gl-matrix": "^3.4.3",
|
||||
"lz-string": "^1.5.0",
|
||||
"monkey-around": "^2.3.0",
|
||||
"nanoid": "^5.1.11",
|
||||
"opentype.js": "^1.3.4",
|
||||
"nanoid": "^5.1.16",
|
||||
"pako": "^2.1.0",
|
||||
"points-on-path": "^0.2.1",
|
||||
"polybooljs": "^1.2.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"roughjs": "^4.5.2",
|
||||
"yaml": "^2.9.0"
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8",
|
||||
"roughjs": "^4.5.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.22.9",
|
||||
@@ -69,9 +67,8 @@
|
||||
"@types/chroma-js": "^3.1.1",
|
||||
"@types/js-beautify": "^1.14.0",
|
||||
"@types/node": "^22.19.19",
|
||||
"@types/opentype.js": "^1.3.8",
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
"@types/react": "19.2.18",
|
||||
"@types/react-dom": "19.2.4",
|
||||
"@zsviczian/excalidraw-extras-api": "^0.0.13",
|
||||
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
|
||||
"cross-env": "^7.0.3",
|
||||
@@ -81,7 +78,6 @@
|
||||
"eslint-plugin-obsidianmd": "^0.4.0",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"jiti": "^2.6.1",
|
||||
"jsesc": "^3.0.2",
|
||||
"obsidian": "1.8.7",
|
||||
"postcss": "^8.5.25",
|
||||
"prettier": "^3.0.1",
|
||||
@@ -96,7 +92,7 @@
|
||||
"lodash": "^4.18.1",
|
||||
"lodash-es": "^4.18.1",
|
||||
"serialize-javascript": "^7.0.5",
|
||||
"nanoid": "^5.1.11",
|
||||
"nanoid": "^5.1.16",
|
||||
"dompurify": "^3.4.12",
|
||||
"fast-uri": "^3.1.4",
|
||||
"immutable": "^4.3.9",
|
||||
|
||||
+32
-39
@@ -10,10 +10,10 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
import postprocess from '@zsviczian/rollup-plugin-postprocess';
|
||||
import cssnano from 'cssnano';
|
||||
import jsesc from 'jsesc';
|
||||
import { minify } from 'uglify-js';
|
||||
import json from '@rollup/plugin-json';
|
||||
import { parseEnv } from 'node:util';
|
||||
import { buildReactRuntime } from './scripts/buildReactRuntime.mjs';
|
||||
|
||||
function compressDeflateBase64(code) {
|
||||
// Compress using Node's native zlib at maximum compression
|
||||
@@ -35,26 +35,6 @@ const isLib = (process.env.NODE_ENV === "lib");
|
||||
console.log(`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}`);
|
||||
|
||||
|
||||
// Excalidraw React 19 compatiblity shim
|
||||
// Create JSX runtime compatibility layer
|
||||
const jsxRuntimeShim = `
|
||||
const jsx = (type, props, key) => {
|
||||
return React.createElement(type, props);
|
||||
};
|
||||
const jsxs = (type, props, key) => {
|
||||
return React.createElement(type, props);
|
||||
};
|
||||
const Fragment = React.Fragment;
|
||||
React.jsx = jsx;
|
||||
React.jsxs = jsxs;
|
||||
React.Fragment = Fragment;
|
||||
React.jsxRuntime = { jsx, jsxs, Fragment };
|
||||
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ = { jsx, jsxs, Fragment };
|
||||
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_dev_runtime__ = { jsx, jsxs, Fragment, jsxDEV: jsx };
|
||||
window['react/jsx-runtime'] = { jsx, jsxs, Fragment };
|
||||
window['react/jsx-dev-runtime'] = { jsx, jsxs, Fragment, jsxDEV: jsx };
|
||||
`;
|
||||
|
||||
// Add non-English locales here to embed them as compressed payloads in main.js.
|
||||
// When adding a locale file:
|
||||
// 1) add its code to this list, 2) build once, 3) if build fails because the locale
|
||||
@@ -94,22 +74,35 @@ function compressLanguageFile(lang) {
|
||||
return compressDeflateBase64(minifyCode(`x = ${content};`));
|
||||
}
|
||||
|
||||
const excalidraw_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/excalidraw.development.js", "utf8"));
|
||||
const react_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/react/umd/react.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/react/umd/react.development.js", "utf8"));
|
||||
const reactdom_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/react-dom/umd/react-dom.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/react-dom/umd/react-dom.development.js", "utf8"));
|
||||
const excalidrawSource = isLib ? "" : fs.readFileSync(
|
||||
isProd
|
||||
? "./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.production.min.js"
|
||||
: "./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.development.js",
|
||||
"utf8",
|
||||
);
|
||||
const excalidraw_pkg = isLib
|
||||
? ""
|
||||
: isProd
|
||||
? minifyCode(excalidrawSource)
|
||||
: `${excalidrawSource}\n//# sourceURL=obsidian-excalidraw-runtime.development.js\n`;
|
||||
const reactRuntimeSource = isLib
|
||||
? ""
|
||||
: await buildReactRuntime({ isProduction: isProd });
|
||||
const reactRuntime = isLib || !isProd
|
||||
? reactRuntimeSource
|
||||
: minifyCode(reactRuntimeSource);
|
||||
const reactPackagesCompressed = isLib
|
||||
? ""
|
||||
: compressDeflateBase64(reactRuntime);
|
||||
|
||||
const pako_pkg = isLib ? "" : fs.readFileSync("./node_modules/pako/dist/pako.min.js", "utf8");
|
||||
// Runtime payloads are only decompressed; including Pako's deflate implementation
|
||||
// would add unused code to the size-constrained Obsidian plugin bundle.
|
||||
const pako_pkg = isLib ? "" : fs.readFileSync("./node_modules/pako/dist/pako_inflate.min.js", "utf8");
|
||||
|
||||
if (!isLib) {
|
||||
const excalidraw_styles = isProd
|
||||
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.production.css", "utf8")
|
||||
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.development.css", "utf8");
|
||||
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.production.min.css", "utf8")
|
||||
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/obsidian/excalidraw.development.css", "utf8");
|
||||
const plugin_styles = fs.readFileSync("./styles.css", "utf8");
|
||||
const styles = excalidraw_styles + plugin_styles;
|
||||
cssnano()
|
||||
@@ -140,10 +133,7 @@ const packageString = isLib
|
||||
' ' + pako_pkg + '\n' +
|
||||
' return module.exports;\n' +
|
||||
'})();\n' +
|
||||
'\nlet REACT_PACKAGES = `' +
|
||||
jsesc(react_pkg + reactdom_pkg + jsxRuntimeShim, { quotes: 'backtick' }) +
|
||||
'`;\n' +
|
||||
// NEW: Fast, mobile-compatible runtime decompression
|
||||
// Define the dependency-free inflater before React participates in bootstrap.
|
||||
'const unpackBase64Deflate = (b64) => {\n' +
|
||||
' const binStr = atob(b64);\n' +
|
||||
' const len = binStr.length;\n' +
|
||||
@@ -152,8 +142,11 @@ const packageString = isLib
|
||||
' return new TextDecoder().decode(pako.inflate(bytes));\n' +
|
||||
'};\n' +
|
||||
'window.unpackBase64Deflate = unpackBase64Deflate;\n' +
|
||||
'let REACT_PACKAGES = unpackBase64Deflate("' + reactPackagesCompressed + '");\n' +
|
||||
'const unpackExcalidraw = () => unpackBase64Deflate("' + compressDeflateBase64(excalidraw_pkg) + '");\n' +
|
||||
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
|
||||
'let {React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime} = new Function(`${REACT_PACKAGES}; return {React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime};`)();\n' +
|
||||
'let react = React;\n' +
|
||||
'let reactDOM = ReactDOM;\n' +
|
||||
'let excalidrawLib = {};\n' +
|
||||
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
|
||||
//These declarations were moved here because Obsidian code scanner incorrectly flags them with a warning,
|
||||
@@ -292,4 +285,4 @@ if (process.env.NODE_ENV === "lib") {
|
||||
config.push(BUILD_CONFIG);
|
||||
}
|
||||
|
||||
export default config;
|
||||
export default config;
|
||||
@@ -0,0 +1,45 @@
|
||||
import commonjs from "@rollup/plugin-commonjs";
|
||||
import { nodeResolve } from "@rollup/plugin-node-resolve";
|
||||
import replace from "@rollup/plugin-replace";
|
||||
import { rollup } from "rollup";
|
||||
|
||||
/**
|
||||
* Bundles the official React package entrypoints into one window-evaluable
|
||||
* artifact for the Obsidian main window and popouts.
|
||||
*
|
||||
* @param {{ isProduction: boolean }} options Build-mode selection.
|
||||
* @returns {Promise<string>} Generated browser runtime source.
|
||||
*/
|
||||
export const buildReactRuntime = async ({ isProduction }) => {
|
||||
const mode = isProduction ? "production" : "development";
|
||||
const bundle = await rollup({
|
||||
input: "scripts/reactRuntimeEntry.mjs",
|
||||
treeshake: true,
|
||||
plugins: [
|
||||
replace({
|
||||
preventAssignment: true,
|
||||
"process.env.NODE_ENV": JSON.stringify(mode),
|
||||
}),
|
||||
nodeResolve({ browser: true, preferBuiltins: false }),
|
||||
commonjs(),
|
||||
],
|
||||
});
|
||||
|
||||
try {
|
||||
const { output } = await bundle.generate({
|
||||
format: "iife",
|
||||
name: "ObsidianExcalidrawReactRuntime",
|
||||
inlineDynamicImports: true,
|
||||
compact: isProduction,
|
||||
generatedCode: "es2015",
|
||||
});
|
||||
const chunk = output.find((item) => item.type === "chunk");
|
||||
if (!chunk) {
|
||||
throw new Error("React runtime build did not emit a JavaScript chunk");
|
||||
}
|
||||
return `${chunk.code}
|
||||
var { React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime } = ObsidianExcalidrawReactRuntime;`;
|
||||
} finally {
|
||||
await bundle.close();
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Browser entry for the private React runtime used by Excalidraw.
|
||||
*
|
||||
* The plugin evaluates the generated artifact in a private function scope once
|
||||
* per Obsidian window. Keep these exports aligned with the lexical externals
|
||||
* configured by the Excalidraw `build:obsidian` package target.
|
||||
*/
|
||||
import React from "react";
|
||||
import ReactDOMLegacy from "react-dom";
|
||||
import * as ReactDOMClient from "react-dom/client";
|
||||
import * as jsxDevRuntime from "react/jsx-dev-runtime";
|
||||
import * as jsxRuntime from "react/jsx-runtime";
|
||||
|
||||
const ReactDOM = Object.assign({}, ReactDOMLegacy, ReactDOMClient);
|
||||
const ReactJSXRuntime = jsxRuntime;
|
||||
const ReactJSXDevRuntime = Object.assign({}, jsxDevRuntime, {
|
||||
// Keep a callable production fallback for bundles compiled against the
|
||||
// development JSX runtime entrypoint.
|
||||
jsxDEV: jsxDevRuntime.jsxDEV || jsxRuntime.jsx,
|
||||
});
|
||||
|
||||
export { React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime };
|
||||
@@ -1,6 +1,6 @@
|
||||
import { customAlphabet } from "nanoid";
|
||||
import { ExcalidrawLib } from "../types/excalidrawLib";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { DeviceType } from "src/types/types";
|
||||
import { errorHandler } from "../utils/ErrorHandler";
|
||||
import { getLanguage } from "obsidian";
|
||||
|
||||
+59
-816
File diff suppressed because it is too large.
Load diff
@@ -23,7 +23,7 @@ import {
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import { TextMode } from "../../shared/TextMode";
|
||||
import { REGEX_LINK } from "../../shared/ExcalidrawData";
|
||||
import { ExcalidrawSettings } from "../settings";
|
||||
import type { ExcalidrawSettings } from "../settingsDefaults";
|
||||
import {
|
||||
openDialogAction,
|
||||
OpenFileDialog,
|
||||
@@ -66,6 +66,7 @@ import {
|
||||
FileId,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ReleaseNotes } from "../../shared/Dialogs/ReleaseNotes";
|
||||
import { AutostartScriptsModal } from "../../shared/Dialogs/AutostartScriptsSettingsComponent";
|
||||
import { ScriptInstallPrompt } from "../../shared/Dialogs/ScriptInstallPrompt";
|
||||
import Taskbone from "../../shared/OCR/Taskbone";
|
||||
import {
|
||||
@@ -87,7 +88,7 @@ import {
|
||||
} from "../../utils/carveout";
|
||||
import { showFrameSettings } from "../../shared/Dialogs/FrameSettings";
|
||||
import { insertImageToView } from "../../utils/excalidrawViewUtils";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
import { decompress } from "src/utils/sceneDataUtils";
|
||||
@@ -485,13 +486,13 @@ export class CommandManager {
|
||||
id: "excalidraw-disable-autosave",
|
||||
name: t("TEMPORARY_DISABLE_AUTOSAVE"),
|
||||
checkCallback: (checking) => {
|
||||
if (!this.settings.autosave) {
|
||||
if (!this.plugin.autosaveEnabled) {
|
||||
return false;
|
||||
} //already disabled
|
||||
if (checking) {
|
||||
return true;
|
||||
}
|
||||
this.settings.autosave = false;
|
||||
this.plugin.autosaveEnabled = false;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
@@ -500,13 +501,13 @@ export class CommandManager {
|
||||
id: "excalidraw-enable-autosave",
|
||||
name: t("TEMPORARY_ENABLE_AUTOSAVE"),
|
||||
checkCallback: (checking) => {
|
||||
if (this.settings.autosave) {
|
||||
if (this.plugin.autosaveEnabled) {
|
||||
return false;
|
||||
} //already enabled
|
||||
if (checking) {
|
||||
return true;
|
||||
}
|
||||
this.settings.autosave = true;
|
||||
this.plugin.autosaveEnabled = true;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
@@ -2301,6 +2302,14 @@ export class CommandManager {
|
||||
},
|
||||
});
|
||||
|
||||
this.addCommand({
|
||||
id: "view-autostart-scripts",
|
||||
name: t("AUTOSTART_SCRIPTS_HEAD"),
|
||||
callback: () => {
|
||||
new AutostartScriptsModal(this.plugin).open();
|
||||
},
|
||||
});
|
||||
|
||||
this.addCommand({
|
||||
id: "tray-mode",
|
||||
name: t("UI_MODE"),
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
isUnwantedLeaf,
|
||||
setExcalidrawView,
|
||||
} from "../../utils/obsidianUtils";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import {
|
||||
FRONTMATTER_KEYS,
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
} from "../../shared/ExcalidrawData";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { getTextMode } from "src/shared/TextMode";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import {
|
||||
checkAndCreateFolder,
|
||||
createFileAndAwaitMetacacheUpdate,
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import type { Packages } from "src/types/types";
|
||||
import { Notice, normalizePath, TFile } from "obsidian";
|
||||
import {
|
||||
CJK_STYLE_ID,
|
||||
DEVICE,
|
||||
FONTS_STYLE_ID,
|
||||
} from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { getCJKDataURLs } from "src/utils/CJKLoader";
|
||||
import { getFontDataURL } from "src/utils/utils";
|
||||
import { getFontMetrics } from "src/utils/fontMetrics";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
declare const deliberateCreateElement: (
|
||||
document: Document,
|
||||
tagName: string,
|
||||
) => HTMLStyleElement;
|
||||
|
||||
type PackageMapProvider = () => Map<Window, Packages>;
|
||||
|
||||
/**
|
||||
* Owns CJK and custom-font discovery, registration, document stylesheets, and
|
||||
* readiness state while preserving the plugin's existing public font facade.
|
||||
*/
|
||||
export class FontManager {
|
||||
private isLocalCJKFontAvailabe: boolean = undefined;
|
||||
// Intentionally true to preserve the existing startup race behavior.
|
||||
private fontsReady = true;
|
||||
|
||||
public constructor(
|
||||
private readonly plugin: ExcalidrawPlugin,
|
||||
private readonly getPackageMap: PackageMapProvider,
|
||||
) {}
|
||||
|
||||
/** Whether font initialization permits the plugin readiness wait to finish. */
|
||||
public get isReady(): boolean {
|
||||
return this.fontsReady;
|
||||
}
|
||||
|
||||
/** Returns the enabled CJK ranges when local CJK font assets are available. */
|
||||
public getCJKFontSettings(): { c: boolean; j: boolean; k: boolean } {
|
||||
const assetsFoler = this.plugin.settings.fontAssetsPath;
|
||||
if (typeof this.isLocalCJKFontAvailabe === "undefined") {
|
||||
this.isLocalCJKFontAvailabe = this.plugin.app.vault
|
||||
.getFiles()
|
||||
.some((file) => file.path.startsWith(assetsFoler));
|
||||
}
|
||||
if (!this.isLocalCJKFontAvailabe) {
|
||||
return { c: false, j: false, k: false };
|
||||
}
|
||||
return {
|
||||
c: this.plugin.settings.loadChineseFonts,
|
||||
j: this.plugin.settings.loadJapaneseFonts,
|
||||
k: this.plugin.settings.loadKoreanFonts,
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads a configured CJK font asset from the vault. */
|
||||
public async loadFontFromFile(
|
||||
fontName: string,
|
||||
): Promise<ArrayBuffer | undefined> {
|
||||
const assetsFoler = this.plugin.settings.fontAssetsPath;
|
||||
|
||||
if (!this.isLocalCJKFontAvailabe) {
|
||||
return;
|
||||
}
|
||||
const file = this.plugin.app.vault.getFileByPath(
|
||||
normalizePath(`${assetsFoler}/${fontName}`),
|
||||
);
|
||||
if (!file || !(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
return await this.plugin.app.vault.readBinary(file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads configured CJK and custom fonts into every open Obsidian document
|
||||
* and registers custom font metrics with each window-scoped Excalidraw package.
|
||||
*/
|
||||
public async initializeFonts(): Promise<void> {
|
||||
const cjkFontDataURLs = await getCJKDataURLs(this.plugin);
|
||||
if (typeof cjkFontDataURLs === "boolean" && !cjkFontDataURLs) {
|
||||
new Notice(
|
||||
t("FONTS_LOAD_ERROR") + this.plugin.settings.fontAssetsPath,
|
||||
6000,
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof cjkFontDataURLs === "object") {
|
||||
const fontDeclarations = cjkFontDataURLs.map(
|
||||
(dataURL) =>
|
||||
`@font-face { font-family: 'Xiaolai'; src: url("${dataURL}"); font-display: swap; font-weight: 400; }`,
|
||||
);
|
||||
for (const ownerDocument of this.getOpenObsidianDocuments()) {
|
||||
await this.addFonts(fontDeclarations, ownerDocument, CJK_STYLE_ID);
|
||||
}
|
||||
new Notice(t("FONTS_LOADED"));
|
||||
}
|
||||
|
||||
const font = await getFontDataURL(
|
||||
this.plugin.app,
|
||||
this.plugin.settings.experimantalFourthFont,
|
||||
"",
|
||||
"Local Font",
|
||||
);
|
||||
|
||||
if (font.dataURL === "") {
|
||||
this.plugin.fourthFontLoaded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const fourthFontDataURL = font.dataURL;
|
||||
|
||||
const file = this.plugin.app.metadataCache.getFirstLinkpathDest(
|
||||
this.plugin.settings.experimantalFourthFont,
|
||||
"",
|
||||
);
|
||||
let fontMetrics = file.extension.startsWith("woff") || !font.arrayBuffer
|
||||
? undefined
|
||||
: getFontMetrics(font.arrayBuffer);
|
||||
|
||||
if (!fontMetrics) {
|
||||
fontMetrics = {
|
||||
unitsPerEm: 1000,
|
||||
ascender: 750,
|
||||
descender: -250,
|
||||
lineHeight: 1.2,
|
||||
};
|
||||
}
|
||||
this.getPackageMap().forEach(({ excalidrawLib }) => {
|
||||
if (!fontMetrics) {
|
||||
return;
|
||||
}
|
||||
excalidrawLib.registerLocalFont(
|
||||
{ metrics: fontMetrics },
|
||||
fourthFontDataURL,
|
||||
);
|
||||
});
|
||||
for (const ownerDocument of this.getOpenObsidianDocuments()) {
|
||||
await this.addFonts(
|
||||
[
|
||||
`@font-face{font-family:'Local Font';src:url("${fourthFontDataURL}");font-display: swap;font-weight: 400;`,
|
||||
],
|
||||
ownerDocument,
|
||||
);
|
||||
}
|
||||
if (!this.plugin.fourthFontLoaded) {
|
||||
window.setTimeout(() => {
|
||||
this.plugin.fourthFontLoaded = true;
|
||||
}, 100);
|
||||
}
|
||||
this.fontsReady = true;
|
||||
}
|
||||
|
||||
/** Replaces a plugin-owned font stylesheet and waits for the font to load. */
|
||||
public async addFonts(
|
||||
declarations: string[],
|
||||
ownerDocument: Document = mainDocument,
|
||||
styleId: string = FONTS_STYLE_ID,
|
||||
): Promise<void> {
|
||||
const newStylesheet = deliberateCreateElement(ownerDocument, "style");
|
||||
newStylesheet.id = styleId;
|
||||
newStylesheet.textContent = declarations.join("");
|
||||
const oldStylesheet = ownerDocument.getElementById(styleId);
|
||||
ownerDocument.head.appendChild(newStylesheet);
|
||||
if (oldStylesheet) {
|
||||
ownerDocument.head.removeChild(oldStylesheet);
|
||||
}
|
||||
await ownerDocument.fonts.load("20px Local Font");
|
||||
}
|
||||
|
||||
/** Removes custom and CJK font stylesheets from all open documents. */
|
||||
public removeFonts(): void {
|
||||
this.getOpenObsidianDocuments().forEach((ownerDocument) => {
|
||||
const oldCustomFontStylesheet =
|
||||
ownerDocument.getElementById(FONTS_STYLE_ID);
|
||||
if (oldCustomFontStylesheet) {
|
||||
ownerDocument.head.removeChild(oldCustomFontStylesheet);
|
||||
}
|
||||
const oldCJKFontStylesheet = ownerDocument.getElementById(CJK_STYLE_ID);
|
||||
if (oldCJKFontStylesheet) {
|
||||
ownerDocument.head.removeChild(oldCJKFontStylesheet);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getOpenObsidianDocuments(): Document[] {
|
||||
const visitedDocuments = new Set<Document>();
|
||||
this.plugin.app.workspace.iterateAllLeaves((leaf) => {
|
||||
const ownerDocument = DEVICE.isMobile
|
||||
? mainDocument
|
||||
: leaf.view.containerEl.ownerDocument;
|
||||
if (!ownerDocument || visitedDocuments.has(ownerDocument)) {
|
||||
return;
|
||||
}
|
||||
visitedDocuments.add(ownerDocument);
|
||||
});
|
||||
return Array.from(visitedDocuments);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { App } from "obsidian";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
|
||||
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
declare const deliberateCreateElement: (
|
||||
document: Document,
|
||||
tagName: string,
|
||||
) => HTMLStyleElement;
|
||||
|
||||
const FOOTER_SAFE_AREA_STYLE_ID = "excalidraw-phone-footer-safe-area";
|
||||
const FOOTER_SAFE_AREA_CSS = `
|
||||
.excalidraw .App-bottom-bar {
|
||||
padding-bottom: 50px;
|
||||
}
|
||||
`;
|
||||
|
||||
interface FooterSafeAreaHost {
|
||||
app: App;
|
||||
settings: ExcalidrawSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the optional phone and tablet footer-padding stylesheet across Obsidian
|
||||
* documents, including cleanup when the plugin unloads.
|
||||
*/
|
||||
export class FooterSafeAreaManager {
|
||||
public constructor(private readonly host: FooterSafeAreaHost) {}
|
||||
|
||||
/** Applies or removes footer padding according to the current device and settings. */
|
||||
public updateFooterSafeAreaPadding(): void {
|
||||
const documents = new Set<Document>([
|
||||
mainDocument,
|
||||
...this.getOpenObsidianDocuments(),
|
||||
]);
|
||||
const shouldEnable =
|
||||
(DEVICE.isPhone && this.host.settings?.phoneFooterSafeAreaPadding) ||
|
||||
(DEVICE.isTablet && this.host.settings?.tabletFooterSafeAreaPadding);
|
||||
|
||||
documents.forEach((ownerDocument) => {
|
||||
const existingStylesheet = ownerDocument.getElementById(
|
||||
FOOTER_SAFE_AREA_STYLE_ID,
|
||||
);
|
||||
if (!shouldEnable) {
|
||||
if (existingStylesheet) {
|
||||
ownerDocument.head.removeChild(existingStylesheet);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (isInstanceOfHTMLStyleElement(existingStylesheet)) {
|
||||
existingStylesheet.textContent = FOOTER_SAFE_AREA_CSS;
|
||||
return;
|
||||
}
|
||||
|
||||
const stylesheet = deliberateCreateElement(ownerDocument, "style");
|
||||
stylesheet.id = FOOTER_SAFE_AREA_STYLE_ID;
|
||||
stylesheet.textContent = FOOTER_SAFE_AREA_CSS;
|
||||
ownerDocument.head.appendChild(stylesheet);
|
||||
});
|
||||
}
|
||||
|
||||
/** Removes every footer-padding stylesheet owned by the plugin. */
|
||||
public destroy(): void {
|
||||
const documents = new Set<Document>([
|
||||
mainDocument,
|
||||
...this.getOpenObsidianDocuments(),
|
||||
]);
|
||||
documents.forEach((ownerDocument) => {
|
||||
const existingStylesheet = ownerDocument.getElementById(
|
||||
FOOTER_SAFE_AREA_STYLE_ID,
|
||||
);
|
||||
if (existingStylesheet) {
|
||||
ownerDocument.head.removeChild(existingStylesheet);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getOpenObsidianDocuments(): Document[] {
|
||||
const visitedDocuments = new Set<Document>();
|
||||
this.host.app.workspace.iterateAllLeaves((leaf) => {
|
||||
const ownerDocument = DEVICE.isMobile
|
||||
? mainDocument
|
||||
: leaf.view.containerEl.ownerDocument;
|
||||
if (!ownerDocument || visitedDocuments.has(ownerDocument)) {
|
||||
return;
|
||||
}
|
||||
visitedDocuments.add(ownerDocument);
|
||||
});
|
||||
return Array.from(visitedDocuments);
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
} from "../../constants/constants";
|
||||
import { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader";
|
||||
import { createPNG, createSVG } from "../../utils/excalidrawAutomateUtils";
|
||||
import ExcalidrawPlugin from "../main";
|
||||
import type ExcalidrawPlugin from "../main";
|
||||
import { getIMGFilename } from "../../utils/fileUtils";
|
||||
import {
|
||||
getEmbeddedFilenameParts,
|
||||
|
||||
@@ -43,6 +43,10 @@ export class MonkeyPatchManager {
|
||||
T extends View,
|
||||
>(this: Workspace, type: ViewConstructor<T>): T | null {
|
||||
const result = old.call(this, type) as T | null;
|
||||
const stackTrace = new Error().stack ?? "";
|
||||
if (!MonkeyPatchManager.isCallerFromTemplaterPlugin(stackTrace)) {
|
||||
return result;
|
||||
}
|
||||
const maybeEAView = this.getMostRecentLeaf()?.view;
|
||||
if (
|
||||
!maybeEAView ||
|
||||
@@ -50,10 +54,6 @@ export class MonkeyPatchManager {
|
||||
) {
|
||||
return result;
|
||||
}
|
||||
const stackTrace = new Error().stack ?? "";
|
||||
if (!MonkeyPatchManager.isCallerFromTemplaterPlugin(stackTrace)) {
|
||||
return result;
|
||||
}
|
||||
const leafOrNode = (
|
||||
maybeEAView as ExcalidrawView
|
||||
).getActiveEmbeddable();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { t } from "src/lang/helpers";
|
||||
import { DEBUGGING } from "src/utils/debugHelper";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { CustomMutationObserver } from "src/utils/debugHelper";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import {
|
||||
@@ -49,7 +50,7 @@ export class ObserverManager {
|
||||
this.addWorkspaceDrawerObserver();
|
||||
}
|
||||
} catch (e) {
|
||||
new Notice("Error adding ObserverManager", 6000);
|
||||
new Notice(t("ERROR_ADDING_OBSERVER_MANAGER"), 6000);
|
||||
console.error("Error adding ObserverManager", e);
|
||||
}
|
||||
this.plugin.logStartupEvent("ObserverManager added");
|
||||
|
||||
@@ -2,22 +2,33 @@ import { updateExcalidrawLib } from "src/constants/constants";
|
||||
import { ExcalidrawLib } from "../../types/excalidrawLib";
|
||||
import { Packages } from "../../types/types";
|
||||
import { Notice } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
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;
|
||||
declare let reactDOM: typeof ReactDOM;
|
||||
declare let excalidrawLib: typeof ExcalidrawLib;
|
||||
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;
|
||||
@@ -25,12 +36,30 @@ export class PackageManager {
|
||||
try {
|
||||
this.EXCALIDRAW_PACKAGE = unpackExcalidraw();
|
||||
|
||||
// Use safe evaluation for unpacking the Excalidraw package
|
||||
excalidrawLib = errorHandler.safeEval(
|
||||
`(function() {${this.EXCALIDRAW_PACKAGE};return ExcalidrawLib;})()`,
|
||||
// Evaluate Excalidraw in the main window with the same private React
|
||||
// instance used by the plugin bundle. The runtime is passed explicitly
|
||||
// because window.React and window.ReactDOM are deliberately not set.
|
||||
const loadExcalidraw = errorHandler.safeEval<
|
||||
(
|
||||
reactInstance: typeof React,
|
||||
reactDOMInstance: typeof ReactDOM,
|
||||
jsxRuntime: unknown,
|
||||
jsxDevRuntime: unknown,
|
||||
) => typeof ExcalidrawLib
|
||||
>(
|
||||
`(function(React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime) {
|
||||
${this.EXCALIDRAW_PACKAGE};
|
||||
return ExcalidrawLib;
|
||||
})`,
|
||||
"PackageManager constructor - excalidrawLib initialization",
|
||||
window,
|
||||
);
|
||||
excalidrawLib = loadExcalidraw(
|
||||
react,
|
||||
reactDOM,
|
||||
ReactJSXRuntime,
|
||||
ReactJSXDevRuntime,
|
||||
);
|
||||
|
||||
if (!excalidrawLib) {
|
||||
throw new Error("Failed to initialize excalidrawLib");
|
||||
@@ -49,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,
|
||||
@@ -84,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
|
||||
@@ -120,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
|
||||
@@ -134,7 +233,11 @@ export class PackageManager {
|
||||
}>(
|
||||
`(function() {
|
||||
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
|
||||
return {react: React, reactDOM: ReactDOM, excalidrawLib: ExcalidrawLib};
|
||||
return {
|
||||
react: React,
|
||||
reactDOM: ReactDOM,
|
||||
excalidrawLib: ExcalidrawLib,
|
||||
};
|
||||
})()`,
|
||||
"PackageManager.getPackage - package evaluation",
|
||||
win,
|
||||
@@ -150,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) {
|
||||
@@ -171,41 +277,26 @@ export class PackageManager {
|
||||
|
||||
public deletePackage(win: Window) {
|
||||
try {
|
||||
this.disposeObsidianHosts(win);
|
||||
|
||||
const pkg = this.packageMap.get(win);
|
||||
if (!pkg) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { react, reactDOM, excalidrawLib } = pkg;
|
||||
|
||||
const { excalidrawLib } = pkg;
|
||||
if (win.ExcalidrawLib === excalidrawLib) {
|
||||
// Safely clean up resources
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
if (
|
||||
excalidrawLib &&
|
||||
typeof excalidrawLib.destroyObsidianUtils === "function"
|
||||
) {
|
||||
excalidrawLib.destroyObsidianUtils();
|
||||
}
|
||||
delete win.ExcalidrawLib;
|
||||
}, "PackageManager.deletePackage - cleanup ExcalidrawLib");
|
||||
}
|
||||
|
||||
if (win.React === react) {
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
delete win.React;
|
||||
}, "PackageManager.deletePackage - cleanup React");
|
||||
}
|
||||
|
||||
if (win.ReactDOM === reactDOM) {
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
delete win.ReactDOM;
|
||||
}, "PackageManager.deletePackage - cleanup ReactDOM");
|
||||
}
|
||||
|
||||
this.packageMap.delete(win);
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "PackageManager.deletePackage");
|
||||
} catch (error: unknown) {
|
||||
errorHandler.handleError(
|
||||
normalizeError(error),
|
||||
"PackageManager.deletePackage",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,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,165 @@
|
||||
import { JSON_parse } from "src/constants/constants";
|
||||
import {
|
||||
DEFAULT_SETTINGS,
|
||||
type ExcalidrawSettings,
|
||||
} from "src/core/settingsDefaults";
|
||||
import { PreviewImageType } from "src/types/utilTypes";
|
||||
import {
|
||||
decryptPersistedAPIKeys,
|
||||
encryptPersistedAPIKeys,
|
||||
} from "src/utils/settingsKeyObfuscation";
|
||||
|
||||
type PersistedExcalidrawSettings = Partial<ExcalidrawSettings> &
|
||||
Record<string, unknown>;
|
||||
|
||||
interface PluginSettingsHost {
|
||||
settings: ExcalidrawSettings;
|
||||
loadData(): Promise<unknown>;
|
||||
saveData(data: unknown): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns plugin settings persistence, default assembly, and compatibility
|
||||
* migrations while leaving startup readiness and settings UI registration to
|
||||
* the plugin lifecycle.
|
||||
*/
|
||||
export class PluginSettingsManager {
|
||||
public constructor(private readonly host: PluginSettingsHost) {}
|
||||
|
||||
/**
|
||||
* Loads persisted settings, applies defaults and migrations, and decrypts
|
||||
* protected API-key fields.
|
||||
*
|
||||
* @remarks Unknown persisted properties are intentionally retained.
|
||||
*/
|
||||
public async loadSettings(): Promise<void> {
|
||||
const persistedSettings = ((await this.host.loadData()) ??
|
||||
{}) as PersistedExcalidrawSettings;
|
||||
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
|
||||
let didSettingsMigration = false;
|
||||
this.host.settings = Object.assign(
|
||||
{},
|
||||
DEFAULT_SETTINGS,
|
||||
decryptedSettings,
|
||||
);
|
||||
if (typeof decryptedSettings.libraryStorageMode === "undefined") {
|
||||
const legacyLibrary: unknown =
|
||||
typeof decryptedSettings.library === "string" &&
|
||||
decryptedSettings.library !== "" &&
|
||||
decryptedSettings.library !== "deprecated"
|
||||
? JSON_parse(decryptedSettings.library)
|
||||
: decryptedSettings.library2;
|
||||
const legacyLibraryRecord =
|
||||
typeof legacyLibrary === "object" && legacyLibrary !== null
|
||||
? (legacyLibrary as Record<string, unknown>)
|
||||
: null;
|
||||
const hasLegacyItems = Boolean(
|
||||
(Array.isArray(legacyLibraryRecord?.library) &&
|
||||
legacyLibraryRecord.library.length) ||
|
||||
(Array.isArray(legacyLibraryRecord?.libraryItems) &&
|
||||
legacyLibraryRecord.libraryItems.length),
|
||||
);
|
||||
this.host.settings.libraryStorageMode = hasLegacyItems
|
||||
? "data-json"
|
||||
: "vault";
|
||||
this.host.settings.libraryMigrationStatus = hasLegacyItems
|
||||
? "pending"
|
||||
: "not-required";
|
||||
didSettingsMigration = true;
|
||||
}
|
||||
const savedMarkdownImageSettings = decryptedSettings.markdownImageSettings;
|
||||
if (!savedMarkdownImageSettings) {
|
||||
this.host.settings.markdownImageSettings = {
|
||||
defaults: {
|
||||
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
|
||||
width: this.host.settings.mdSVGwidth,
|
||||
fontFamily: this.host.settings.mdFont,
|
||||
fontColor: this.host.settings.mdFontColor ?? "#000000",
|
||||
border: {
|
||||
enabled: false,
|
||||
color: this.host.settings.mdBorderColor,
|
||||
},
|
||||
css: "",
|
||||
transclusion: {
|
||||
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
|
||||
border: {
|
||||
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
|
||||
.border,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
didSettingsMigration = true;
|
||||
} else {
|
||||
this.host.settings.markdownImageSettings = {
|
||||
defaults: {
|
||||
...DEFAULT_SETTINGS.markdownImageSettings.defaults,
|
||||
...savedMarkdownImageSettings.defaults,
|
||||
border: {
|
||||
...DEFAULT_SETTINGS.markdownImageSettings.defaults.border,
|
||||
...savedMarkdownImageSettings.defaults?.border,
|
||||
},
|
||||
transclusion: {
|
||||
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion,
|
||||
...savedMarkdownImageSettings.defaults?.transclusion,
|
||||
border: {
|
||||
...DEFAULT_SETTINGS.markdownImageSettings.defaults.transclusion
|
||||
.border,
|
||||
...savedMarkdownImageSettings.defaults?.transclusion?.border,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
const markdownImageDefaults = this.host.settings.markdownImageSettings
|
||||
.defaults as unknown as Record<string, unknown>;
|
||||
if ("theme" in markdownImageDefaults) {
|
||||
delete markdownImageDefaults.theme;
|
||||
didSettingsMigration = true;
|
||||
}
|
||||
const settingsRecord = this.host.settings as unknown as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
if (
|
||||
typeof settingsRecord.iframelyAllowed === "boolean" &&
|
||||
typeof this.host.settings.oEmbedAllowed !== "boolean"
|
||||
) {
|
||||
this.host.settings.oEmbedAllowed = settingsRecord.iframelyAllowed;
|
||||
didSettingsMigration = true;
|
||||
}
|
||||
if ("iframelyAllowed" in settingsRecord) {
|
||||
delete settingsRecord.iframelyAllowed;
|
||||
didSettingsMigration = true;
|
||||
}
|
||||
if (!this.host.settings.previewImageType) {
|
||||
// Migration introduced in 1.9.13.
|
||||
if (typeof this.host.settings.displaySVGInPreview === "undefined") {
|
||||
this.host.settings.previewImageType = PreviewImageType.SVGIMG;
|
||||
} else {
|
||||
this.host.settings.previewImageType = this.host.settings
|
||||
.displaySVGInPreview
|
||||
? PreviewImageType.SVGIMG
|
||||
: PreviewImageType.PNG;
|
||||
}
|
||||
}
|
||||
const encryptedPersistedSettings = encryptPersistedAPIKeys(
|
||||
this.host.settings as PersistedExcalidrawSettings,
|
||||
);
|
||||
const shouldPersistEncryptedSettings =
|
||||
JSON.stringify(encryptedPersistedSettings) !==
|
||||
JSON.stringify(persistedSettings);
|
||||
if (didSettingsMigration || shouldPersistEncryptedSettings) {
|
||||
await this.host.saveData(encryptedPersistedSettings);
|
||||
}
|
||||
}
|
||||
|
||||
/** Encrypts protected fields and persists the current settings object. */
|
||||
public async saveSettings(): Promise<void> {
|
||||
await this.host.saveData(
|
||||
encryptPersistedAPIKeys(
|
||||
this.host.settings as PersistedExcalidrawSettings,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { log } from "src/utils/debugHelper";
|
||||
|
||||
/** Stores and formats plugin startup timing events without owning startup order. */
|
||||
export class StartupTimer {
|
||||
private readonly events: string[] = [];
|
||||
private lastLogTimestamp: number;
|
||||
|
||||
public constructor(
|
||||
initialTimestamp: number,
|
||||
private readonly pluginVersion: string,
|
||||
) {
|
||||
this.lastLogTimestamp = initialTimestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a new timing baseline while retaining events recorded before the
|
||||
* reset, matching the existing constructor-to-layout startup breakdown.
|
||||
*/
|
||||
public reset(timestamp: number): void {
|
||||
this.lastLogTimestamp = timestamp;
|
||||
}
|
||||
|
||||
/** Records one startup event with total and previous-event elapsed times. */
|
||||
public logEvent(message: string, loadTimestamp: number): void {
|
||||
const timestamp = Date.now();
|
||||
this.events.push(
|
||||
`${message}\nTotal: ${timestamp - loadTimestamp}ms Delta: ${timestamp - this.lastLogTimestamp}ms\n`,
|
||||
);
|
||||
this.lastLogTimestamp = timestamp;
|
||||
}
|
||||
|
||||
/** Writes the complete startup timing breakdown to the debug log. */
|
||||
public printBreakdown(): void {
|
||||
log(
|
||||
`Excalidraw ${this.pluginVersion} startup breakdown:\n${this.events.join(
|
||||
"\n",
|
||||
)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -344,7 +344,7 @@ export class StencilLibraryManager {
|
||||
|
||||
for (const item of this.currentItems) {
|
||||
const next = nextById.get(item.id);
|
||||
if (!next || JSON.stringify(next) !== JSON.stringify(item)) {
|
||||
if (!next || JSON.stringify(next, null, 2) !== JSON.stringify(item, null, 2)) {
|
||||
affectedPaths.add(
|
||||
this.itemSource.get(item.id) ?? this.getLocalLibraryPath(),
|
||||
);
|
||||
@@ -389,7 +389,7 @@ export class StencilLibraryManager {
|
||||
version: 2,
|
||||
libraryItems: updated,
|
||||
};
|
||||
if (JSON.stringify(existingData) !== JSON.stringify(nextData)) {
|
||||
if (JSON.stringify(existingData, null, 2) !== JSON.stringify(nextData, null, 2)) {
|
||||
await this.persistLibraryFile(path, nextData);
|
||||
}
|
||||
}
|
||||
@@ -487,7 +487,7 @@ export class StencilLibraryManager {
|
||||
return;
|
||||
}
|
||||
await this.ensureFolder();
|
||||
const content = JSON.stringify(data);
|
||||
const content = JSON.stringify(data, null, 2);
|
||||
if (existing) {
|
||||
await this.plugin.app.vault.modify(existing, content);
|
||||
return;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { WorkspaceWindow } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { getAllWindowDocuments } from "../../utils/obsidianUtils";
|
||||
import { setStyleText } from "src/utils/htmlUtils";
|
||||
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
});
|
||||
+1488
-2620
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -246,6 +246,10 @@ export default {
|
||||
"OCR full drawing: Grab text from freedraw + images to clipboard and doc.props",
|
||||
TASKBONE_NOT_ENABLED:
|
||||
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
|
||||
OCR_ABORT_NO_ELEMENTS:
|
||||
"Aborting OCR because there are no image or freedraw elements on the canvas.",
|
||||
OCR_ALREADY_PROCESSED:
|
||||
"The drawing has already been processed, you will find the result in the frontmatter in Markdown view mode. If you ran the command from the Obsidian panel in Excalidraw then you can ctrl(cmd)+click the command to force the rescanning.",
|
||||
RERUN_OCR:
|
||||
"OCR full drawing re-run: Grab text from freedraw + images to clipboard and doc.props",
|
||||
RUN_OCR_ELEMENTS:
|
||||
@@ -1216,6 +1220,19 @@ export default {
|
||||
"If enabled, Excalidraw will execute file-level <code>excalidraw-onload-script</code> code in all drawings you open from now on, until you disable this setting. " +
|
||||
"This creates a risk if you download markdown files from unknown sources: a malicious actor can use <code>excalidraw-onload-script</code> " +
|
||||
"to run any command in Obsidian and potentially transfer data to the internet. Only enable this if you trust the file and its source.",
|
||||
AUTOSTART_SCRIPT_PROMPT:
|
||||
"wants to run automatically every time you open an Excalidraw drawing. Do you want to allow this?",
|
||||
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
|
||||
'You can change this later from the Command Palette ("Autostart scripts") or in Settings → Compatibility → Autostart scripts.',
|
||||
AUTOSTART_SCRIPT_ALLOW: "Autostart",
|
||||
AUTOSTART_SCRIPT_DENY: "Manual start only",
|
||||
AUTOSTART_SCRIPT_ASK_LATER: "Ask every time",
|
||||
AUTOSTART_SCRIPTS_HEAD: "Autostart scripts",
|
||||
AUTOSTART_SCRIPTS_DESC:
|
||||
"Scripts appear here once they ask for permission to run automatically every time a new Excalidraw view opens (running the script once, manually, is what triggers the request). Change a script's setting at any time.",
|
||||
AUTOSTART_SCRIPTS_EMPTY: "No scripts have requested autostart permission yet.",
|
||||
AUTOSTART_SCRIPT_FAILED_WARNING:
|
||||
"This script failed the last time it tried to autostart.",
|
||||
ENABLE_COMMAND_LINKS_NAME: "Enable command links (cmd://)",
|
||||
ENABLE_COMMAND_LINKS_CONFIRMATION:
|
||||
"This link triggers an Obsidian command via <code>cmd://</code>. Do you want to enable command links?",
|
||||
@@ -1467,6 +1484,7 @@ export default {
|
||||
PROMPT_BUTTON_NEVERMIND: "Nevermind",
|
||||
PROMPT_BUTTON_OK: "OK",
|
||||
PROMPT_BUTTON_CANCEL: "Cancel",
|
||||
PROMPT_BUTTON_CLOSE: "Close",
|
||||
PROMPT_BUTTON_INSERT_LINE: "Insert new line",
|
||||
PROMPT_BUTTON_INSERT_SPACE: "Insert space",
|
||||
PROMPT_BUTTON_INSERT_LINK: "Insert markdown link to file",
|
||||
@@ -1493,6 +1511,7 @@ export default {
|
||||
|
||||
//InsertPDFModal.ts
|
||||
IPM_PAGES_TO_IMPORT_NAME: "Pages to import",
|
||||
IPM_PAGES_TO_IMPORT_DESC: "E.g.: 1,3-5,7,9-10",
|
||||
IPM_SELECT_PAGES_TO_IMPORT: "Please select pages to import",
|
||||
IPM_ADD_BORDER_BOX_NAME: "Add border box",
|
||||
IPM_ADD_FRAME_NAME: "Add page to frame",
|
||||
@@ -1829,4 +1848,20 @@ Thank you & Enjoy!
|
||||
PEN_SETTINGS_CAP_END: "Cap End",
|
||||
PEN_SETTINGS_SAVE: "Save Changes",
|
||||
PEN_SETTINGS_CANCEL: "Cancel",
|
||||
|
||||
//ObserverManager.ts
|
||||
ERROR_ADDING_OBSERVER_MANAGER: "Error adding ObserverManager",
|
||||
|
||||
//PublishOutOfDateFiles.ts
|
||||
POODF_TITLE: "Out of date SVG files",
|
||||
POODF_CHECK_RECURSIVE: "Check recursive",
|
||||
POODF_OPEN_SELECTED: "Open selected",
|
||||
|
||||
//ImageCache.ts
|
||||
IMAGE_CACHE_INITIALIZED:
|
||||
"Excalidraw image cache is initialized - you may now retry opening your damaged drawing.",
|
||||
|
||||
//carveout.ts
|
||||
NEW_DRAWING_TIMEOUT:
|
||||
"File not found. New Excalidraw drawing is taking too long to create. Please try again.",
|
||||
};
|
||||
@@ -1185,6 +1185,20 @@ export default {
|
||||
"Si está habilitado, Excalidraw ejecutará el <code>excalidraw-onload-script</code> a nivel de archivo en todos los dibujos que abras a partir de ahora, hasta que desactives esta opción. " +
|
||||
"Esto crea un riesgo si descargas archivos Markdown de fuentes desconocidas: un actor malicioso puede usar <code>excalidraw-onload-script</code> " +
|
||||
"para ejecutar cualquier comando en Obsidian y potencialmente transferir datos a internet. Actívalo solo si confías en el archivo y en su origen.",
|
||||
AUTOSTART_SCRIPT_PROMPT:
|
||||
"quiere ejecutarse automáticamente cada vez que abras un dibujo de Excalidraw. ¿Deseas permitirlo?",
|
||||
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
|
||||
'Puedes cambiar esto más tarde desde la paleta de comandos ("Scripts de inicio automático") o en Ajustes → Compatibilidad → Scripts de inicio automático.',
|
||||
AUTOSTART_SCRIPT_ALLOW: "Inicio automático",
|
||||
AUTOSTART_SCRIPT_DENY: "Solo manual",
|
||||
AUTOSTART_SCRIPT_ASK_LATER: "Preguntar cada vez",
|
||||
AUTOSTART_SCRIPTS_HEAD: "Scripts de inicio automático",
|
||||
AUTOSTART_SCRIPTS_DESC:
|
||||
"Los scripts aparecen aquí una vez que solicitan permiso para ejecutarse automáticamente cada vez que se abre un nuevo dibujo de Excalidraw (ejecutar el script una vez manualmente es lo que activa la solicitud). Puedes cambiar el ajuste de un script en cualquier momento.",
|
||||
AUTOSTART_SCRIPTS_EMPTY:
|
||||
"Ningún script ha solicitado permiso de inicio automático todavía.",
|
||||
AUTOSTART_SCRIPT_FAILED_WARNING:
|
||||
"Este script falló la última vez que intentó iniciarse automáticamente.",
|
||||
ENABLE_COMMAND_LINKS_NAME: "Habilitar enlaces de comandos (cmd://)",
|
||||
ENABLE_COMMAND_LINKS_CONFIRMATION:
|
||||
"Este enlace ejecuta un comando de Obsidian mediante <code>cmd://</code>. ¿Quieres habilitar los enlaces de comandos?",
|
||||
@@ -1429,6 +1443,7 @@ export default {
|
||||
PROMPT_BUTTON_NEVERMIND: "No importa",
|
||||
PROMPT_BUTTON_OK: "OK",
|
||||
PROMPT_BUTTON_CANCEL: "Cancelar",
|
||||
PROMPT_BUTTON_CLOSE: "Cerrar",
|
||||
PROMPT_BUTTON_INSERT_LINE: "Insertar nueva línea",
|
||||
PROMPT_BUTTON_INSERT_SPACE: "Insertar espacio",
|
||||
PROMPT_BUTTON_INSERT_LINK: "Insertar enlace Markdown a un archivo",
|
||||
@@ -1456,6 +1471,7 @@ export default {
|
||||
|
||||
//InsertPDFModal.ts
|
||||
IPM_PAGES_TO_IMPORT_NAME: "Páginas para importar",
|
||||
IPM_PAGES_TO_IMPORT_DESC: "P. ej.: 1,3-5,7,9-10",
|
||||
IPM_SELECT_PAGES_TO_IMPORT: "Por favor, selecciona las páginas para importar",
|
||||
IPM_ADD_BORDER_BOX_NAME: "Añadir recuadro de borde",
|
||||
IPM_ADD_FRAME_NAME: "Añadir página a un marco(frame)",
|
||||
@@ -1664,4 +1680,26 @@ Si quieres ver lo que ya es posible hoy, aquí tienes una presentación de las f
|
||||
"Puede volver a habilitar esto en: Opciones → Excalidraw → Básico → Advertir sobre actualizaciones de complementos incompletos.",
|
||||
VERSION_MISMATCH_REDOWNLOAD: "Volver a descargar complemento",
|
||||
VERSION_MISMATCH_IGNORE: "Ignorar",
|
||||
|
||||
//Taskbone.ts
|
||||
OCR_ABORT_NO_ELEMENTS:
|
||||
"Cancelando el OCR porque no hay elementos de imagen o dibujo a mano alzada en el lienzo.",
|
||||
OCR_ALREADY_PROCESSED:
|
||||
"El dibujo ya ha sido procesado, encontrará el resultado en el frontmatter en modo de vista Markdown. Si ejecutó el comando desde el panel de Obsidian en Excalidraw, puede hacer ctrl(cmd)+clic en el comando para forzar el reescaneo.",
|
||||
|
||||
//ObserverManager.ts
|
||||
ERROR_ADDING_OBSERVER_MANAGER: "Error al añadir ObserverManager",
|
||||
|
||||
//PublishOutOfDateFiles.ts
|
||||
POODF_TITLE: "Archivos SVG desactualizados",
|
||||
POODF_CHECK_RECURSIVE: "Comprobar de forma recursiva",
|
||||
POODF_OPEN_SELECTED: "Abrir seleccionados",
|
||||
|
||||
//ImageCache.ts
|
||||
IMAGE_CACHE_INITIALIZED:
|
||||
"La caché de imágenes de Excalidraw se ha inicializado - ahora puede volver a intentar abrir su dibujo dañado.",
|
||||
|
||||
//carveout.ts
|
||||
NEW_DRAWING_TIMEOUT:
|
||||
"Archivo no encontrado. El nuevo dibujo de Excalidraw está tardando demasiado en crearse. Inténtelo de nuevo.",
|
||||
};
|
||||
@@ -1090,6 +1090,19 @@ export default {
|
||||
"Если эта настройка включена, Excalidraw будет выполнять <code>excalidraw-onload-script</code> на уровне файла во всех рисунках, которые вы откроете далее, пока вы не отключите эту настройку. " +
|
||||
"Это создаёт риск, если вы загружаете Markdown-файлы из неизвестных источников: злоумышленник может использовать <code>excalidraw-onload-script</code> " +
|
||||
"для запуска любой команды в Obsidian и потенциальной передачи данных в интернет. Включайте это только если доверяете файлу и его источнику.",
|
||||
AUTOSTART_SCRIPT_PROMPT:
|
||||
"хочет запускаться автоматически каждый раз, когда вы открываете рисунок Excalidraw. Разрешить это?",
|
||||
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
|
||||
"Позже это можно изменить в командной палитре («Автозапуск скриптов») или в Настройках → Совместимость → Автозапуск скриптов.",
|
||||
AUTOSTART_SCRIPT_ALLOW: "Автозапуск",
|
||||
AUTOSTART_SCRIPT_DENY: "Только вручную",
|
||||
AUTOSTART_SCRIPT_ASK_LATER: "Спрашивать каждый раз",
|
||||
AUTOSTART_SCRIPTS_HEAD: "Автозапуск скриптов",
|
||||
AUTOSTART_SCRIPTS_DESC:
|
||||
"Скрипты появляются здесь после того, как они запрашивают разрешение автоматически запускаться каждый раз при открытии нового рисунка Excalidraw (запрос инициируется однократным ручным запуском скрипта). Изменить настройку скрипта можно в любое время.",
|
||||
AUTOSTART_SCRIPTS_EMPTY: "Ни один скрипт ещё не запрашивал разрешение на автозапуск.",
|
||||
AUTOSTART_SCRIPT_FAILED_WARNING:
|
||||
"Этот скрипт завершился ошибкой при последнем автозапуске.",
|
||||
ENABLE_COMMAND_LINKS_NAME: "Включить ссылки-команды (cmd://)",
|
||||
ENABLE_COMMAND_LINKS_CONFIRMATION:
|
||||
"Эта ссылка запускает команду Obsidian через <code>cmd://</code>. Включить ссылки-команды?",
|
||||
@@ -1266,6 +1279,7 @@ export default {
|
||||
PROMPT_BUTTON_NEVERMIND: "Неважно",
|
||||
PROMPT_BUTTON_OK: "OK",
|
||||
PROMPT_BUTTON_CANCEL: "Отменить",
|
||||
PROMPT_BUTTON_CLOSE: "Закрыть",
|
||||
PROMPT_BUTTON_INSERT_LINE: "Вставить новую строку",
|
||||
PROMPT_BUTTON_INSERT_SPACE: "Вставить пробел",
|
||||
PROMPT_BUTTON_INSERT_LINK: "Вставить ссылку на файл в формате markdown",
|
||||
@@ -1291,6 +1305,7 @@ export default {
|
||||
|
||||
//InsertPDFModal.ts
|
||||
IPM_PAGES_TO_IMPORT_NAME: "Страницы для импорта",
|
||||
IPM_PAGES_TO_IMPORT_DESC: "Например: 1,3-5,7,9-10",
|
||||
IPM_SELECT_PAGES_TO_IMPORT: "Пожалуйста, выберите страницы для импорта",
|
||||
IPM_ADD_BORDER_BOX_NAME: "Добавить рамку",
|
||||
IPM_ADD_FRAME_NAME: "Добавить страницу в кадр",
|
||||
@@ -1301,4 +1316,26 @@ export default {
|
||||
IPM_GROUP_PAGES_DESC:
|
||||
"Это позволит объединить все страницы в одну группу. Это рекомендуется делать, если вы блокируете страницы после импорта, потому что группу будет легче разблокировать позже, чем разблокировать каждую по отдельности.",
|
||||
IPM_SELECT_PDF: "Пожалуйста, выберите файл PDF",
|
||||
|
||||
//Taskbone.ts
|
||||
OCR_ABORT_NO_ELEMENTS:
|
||||
"Отмена OCR, так как на холсте нет элементов изображения или рисования от руки.",
|
||||
OCR_ALREADY_PROCESSED:
|
||||
"Рисунок уже обработан, результат можно найти во frontmatter в режиме просмотра Markdown. Если вы запустили команду с панели Obsidian в Excalidraw, вы можете нажать ctrl(cmd)+клик по команде, чтобы принудительно повторить сканирование.",
|
||||
|
||||
//ObserverManager.ts
|
||||
ERROR_ADDING_OBSERVER_MANAGER: "Ошибка при добавлении ObserverManager",
|
||||
|
||||
//PublishOutOfDateFiles.ts
|
||||
POODF_TITLE: "Устаревшие файлы SVG",
|
||||
POODF_CHECK_RECURSIVE: "Проверить рекурсивно",
|
||||
POODF_OPEN_SELECTED: "Открыть выбранное",
|
||||
|
||||
//ImageCache.ts
|
||||
IMAGE_CACHE_INITIALIZED:
|
||||
"Кэш изображений Excalidraw инициализирован - теперь вы можете повторить попытку открытия повреждённого рисунка.",
|
||||
|
||||
//carveout.ts
|
||||
NEW_DRAWING_TIMEOUT:
|
||||
"Файл не найден. Создание нового рисунка Excalidraw занимает слишком много времени. Пожалуйста, попробуйте снова.",
|
||||
};
|
||||
@@ -215,6 +215,9 @@ export default {
|
||||
ABOUT_EXCALIDRAW: "关于 Excalidraw",
|
||||
RUN_OCR: "OCR 整个绘图:识别涂鸦和图片里的文本并复制到剪贴板和笔记属性中",
|
||||
TASKBONE_NOT_ENABLED: "Taskbone OCR 未启用。请前往插件设置将其开启。",
|
||||
OCR_ABORT_NO_ELEMENTS: "正在中止 OCR,因为画布上没有图像或手绘元素。",
|
||||
OCR_ALREADY_PROCESSED:
|
||||
"该绘图已经处理过,您可以在 Markdown 视图模式下的 frontmatter 中找到结果。如果您是从 Excalidraw 的 Obsidian 面板运行此命令,可以按住 ctrl(cmd) 并点击该命令以强制重新扫描。",
|
||||
RERUN_OCR:
|
||||
"重新 OCR 整个绘图:识别涂鸦和图片里的文本并复制到剪贴板和笔记属性中",
|
||||
RUN_OCR_ELEMENTS: "OCR 选中的元素:识别涂鸦和图片里的文本并复制到剪贴板",
|
||||
@@ -1131,6 +1134,18 @@ export default {
|
||||
"启用后,Excalidraw 会在你之后打开的所有绘图中执行文件级别的 <code>excalidraw-onload-script</code>,直到你关闭此设置。" +
|
||||
"如果你从未知来源下载 Markdown 文件,这会带来风险:恶意行为者可以利用 <code>excalidraw-onload-script</code> " +
|
||||
"在 Obsidian 中运行任意命令,并且有可能将数据传输到互联网。只有在你信任该文件及其来源时才启用此功能。",
|
||||
AUTOSTART_SCRIPT_PROMPT:
|
||||
"希望在你每次打开 Excalidraw 绘图时自动运行。是否允许?",
|
||||
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
|
||||
"你以后可以在命令面板(“自动启动脚本”)或设置 → 兼容性 → 自动启动脚本中更改此设置。",
|
||||
AUTOSTART_SCRIPT_ALLOW: "自动启动",
|
||||
AUTOSTART_SCRIPT_DENY: "仅手动启动",
|
||||
AUTOSTART_SCRIPT_ASK_LATER: "每次都询问",
|
||||
AUTOSTART_SCRIPTS_HEAD: "自动启动脚本",
|
||||
AUTOSTART_SCRIPTS_DESC:
|
||||
"脚本在请求权限以便每次打开新的 Excalidraw 绘图时自动运行后会出现在这里(手动运行一次脚本即可触发该请求)。你可以随时更改脚本的设置。",
|
||||
AUTOSTART_SCRIPTS_EMPTY: "尚无脚本请求自动启动权限。",
|
||||
AUTOSTART_SCRIPT_FAILED_WARNING: "该脚本上次自动启动时失败了。",
|
||||
ENABLE_COMMAND_LINKS_NAME: "启用命令链接(cmd://)",
|
||||
ENABLE_COMMAND_LINKS_CONFIRMATION:
|
||||
"此链接会通过 <code>cmd://</code> 触发 Obsidian 命令。是否启用命令链接?",
|
||||
@@ -1370,6 +1385,7 @@ export default {
|
||||
PROMPT_BUTTON_NEVERMIND: "算了",
|
||||
PROMPT_BUTTON_OK: "OK",
|
||||
PROMPT_BUTTON_CANCEL: "取消",
|
||||
PROMPT_BUTTON_CLOSE: "关闭",
|
||||
PROMPT_BUTTON_INSERT_LINE: "插入一行",
|
||||
PROMPT_BUTTON_INSERT_SPACE: "插入空格",
|
||||
PROMPT_BUTTON_INSERT_LINK: "插入内部链接",
|
||||
@@ -1395,6 +1411,7 @@ export default {
|
||||
|
||||
//InsertPDFModal.ts
|
||||
IPM_PAGES_TO_IMPORT_NAME: "要导入的页面",
|
||||
IPM_PAGES_TO_IMPORT_DESC: "例如:1,3-5,7,9-10",
|
||||
IPM_SELECT_PAGES_TO_IMPORT: "请选择页面以进行导入",
|
||||
IPM_ADD_BORDER_BOX_NAME: "添加带边框的盒子容器",
|
||||
IPM_ADD_FRAME_NAME: "添加页面到画框",
|
||||
@@ -1636,4 +1653,19 @@ Obsidian 的 Excalidraw 插件远不只是画图工具。由于它与 Obsidian
|
||||
EXTRAS_GATEWAY_COMP_PLUGIN: "Excalidraw Extras 插件",
|
||||
EXTRAS_GATEWAY_UPDATE_TITLE: "Excalidraw 需要新版本的 Extras 插件",
|
||||
EXTRAS_GATEWAY_UPDATE_BTN: "打开社区插件",
|
||||
|
||||
//ObserverManager.ts
|
||||
ERROR_ADDING_OBSERVER_MANAGER: "添加 ObserverManager 时出错",
|
||||
|
||||
//PublishOutOfDateFiles.ts
|
||||
POODF_TITLE: "过期的 SVG 文件",
|
||||
POODF_CHECK_RECURSIVE: "递归检查",
|
||||
POODF_OPEN_SELECTED: "打开所选项",
|
||||
|
||||
//ImageCache.ts
|
||||
IMAGE_CACHE_INITIALIZED:
|
||||
"Excalidraw 图像缓存已初始化 - 您现在可以重试打开损坏的绘图。",
|
||||
|
||||
//carveout.ts
|
||||
NEW_DRAWING_TIMEOUT: "未找到文件。新建 Excalidraw 绘图耗时过长。请重试。",
|
||||
};
|
||||
@@ -215,6 +215,9 @@ export default {
|
||||
ABOUT_EXCALIDRAW: "關於 Excalidraw",
|
||||
RUN_OCR: "OCR 整個繪圖:識別塗鴉和圖片裡的文字並複製到剪貼簿和筆記屬性中",
|
||||
TASKBONE_NOT_ENABLED: "Taskbone OCR 未啟用。請前往外掛設定將其開啟。",
|
||||
OCR_ABORT_NO_ELEMENTS: "正在中止 OCR,因為畫布上沒有圖像或手繪元素。",
|
||||
OCR_ALREADY_PROCESSED:
|
||||
"此繪圖已經處理過,您可以在 Markdown 檢視模式下的 frontmatter 中找到結果。如果您是從 Excalidraw 的 Obsidian 面板執行此命令,可以按住 ctrl(cmd) 並點擊該命令以強制重新掃描。",
|
||||
RERUN_OCR:
|
||||
"重新 OCR 整個繪圖:識別塗鴉和圖片裡的文字並複製到剪貼簿和筆記屬性中",
|
||||
RUN_OCR_ELEMENTS: "OCR 選中的元素:識別塗鴉和圖片裡的文字並複製到剪貼簿",
|
||||
@@ -1131,6 +1134,18 @@ export default {
|
||||
"啟用後,Excalidraw 會在你之後開啟的所有繪圖中執行檔案級別的 <code>excalidraw-onload-script</code>,直到你關閉此設定。" +
|
||||
"如果你從未知來源下載 Markdown 檔案,這會帶來風險:惡意行為者可以利用 <code>excalidraw-onload-script</code> " +
|
||||
"在 Obsidian 中執行任意命令,並且有可能將資料傳輸到網際網路。只有在你信任該檔案及其來源時才啟用此功能。",
|
||||
AUTOSTART_SCRIPT_PROMPT:
|
||||
"希望在你每次開啟 Excalidraw 繪圖時自動執行。是否允許?",
|
||||
AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT:
|
||||
"你之後可以在命令選擇區(「自動啟動指令碼」)或設定 → 相容性 → 自動啟動指令碼中變更此設定。",
|
||||
AUTOSTART_SCRIPT_ALLOW: "自動啟動",
|
||||
AUTOSTART_SCRIPT_DENY: "僅手動啟動",
|
||||
AUTOSTART_SCRIPT_ASK_LATER: "每次都詢問",
|
||||
AUTOSTART_SCRIPTS_HEAD: "自動啟動指令碼",
|
||||
AUTOSTART_SCRIPTS_DESC:
|
||||
"指令碼在請求權限以便每次開啟新的 Excalidraw 繪圖時自動執行後會出現在這裡(手動執行一次指令碼即可觸發該請求)。你可以隨時變更指令碼的設定。",
|
||||
AUTOSTART_SCRIPTS_EMPTY: "尚無指令碼請求自動啟動權限。",
|
||||
AUTOSTART_SCRIPT_FAILED_WARNING: "該指令碼上次自動啟動時失敗了。",
|
||||
ENABLE_COMMAND_LINKS_NAME: "啟用命令連結(cmd://)",
|
||||
ENABLE_COMMAND_LINKS_CONFIRMATION:
|
||||
"此連結會透過 <code>cmd://</code> 觸發 Obsidian 命令。是否啟用命令連結?",
|
||||
@@ -1370,6 +1385,7 @@ export default {
|
||||
PROMPT_BUTTON_NEVERMIND: "算了",
|
||||
PROMPT_BUTTON_OK: "OK",
|
||||
PROMPT_BUTTON_CANCEL: "取消",
|
||||
PROMPT_BUTTON_CLOSE: "關閉",
|
||||
PROMPT_BUTTON_INSERT_LINE: "插入一行",
|
||||
PROMPT_BUTTON_INSERT_SPACE: "插入空格",
|
||||
PROMPT_BUTTON_INSERT_LINK: "插入內部連結",
|
||||
@@ -1395,6 +1411,7 @@ export default {
|
||||
|
||||
//InsertPDFModal.ts
|
||||
IPM_PAGES_TO_IMPORT_NAME: "要匯入的頁面",
|
||||
IPM_PAGES_TO_IMPORT_DESC: "例如:1,3-5,7,9-10",
|
||||
IPM_SELECT_PAGES_TO_IMPORT: "請選擇頁面以進行匯入",
|
||||
IPM_ADD_BORDER_BOX_NAME: "新增帶邊框的盒子容器",
|
||||
IPM_ADD_FRAME_NAME: "新增頁面到畫框",
|
||||
@@ -1636,4 +1653,19 @@ Obsidian 的 Excalidraw 外掛遠不只是畫圖工具。由於它與 Obsidian
|
||||
EXTRAS_GATEWAY_COMP_PLUGIN: "Excalidraw Extras 外掛",
|
||||
EXTRAS_GATEWAY_UPDATE_TITLE: "Excalidraw 需要新版本的 Extras 外掛",
|
||||
EXTRAS_GATEWAY_UPDATE_BTN: "開啟社群外掛",
|
||||
|
||||
//ObserverManager.ts
|
||||
ERROR_ADDING_OBSERVER_MANAGER: "新增 ObserverManager 時發生錯誤",
|
||||
|
||||
//PublishOutOfDateFiles.ts
|
||||
POODF_TITLE: "過期的 SVG 檔案",
|
||||
POODF_CHECK_RECURSIVE: "遞迴檢查",
|
||||
POODF_OPEN_SELECTED: "開啟所選項",
|
||||
|
||||
//ImageCache.ts
|
||||
IMAGE_CACHE_INITIALIZED:
|
||||
"Excalidraw 圖片快取已初始化 - 您現在可以重試開啟損壞的繪圖。",
|
||||
|
||||
//carveout.ts
|
||||
NEW_DRAWING_TIMEOUT: "找不到檔案。建立新的 Excalidraw 繪圖耗時過長。請重試。",
|
||||
};
|
||||
@@ -0,0 +1,105 @@
|
||||
import { Modal, Setting } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { fragWithHTML } from "src/utils/utils";
|
||||
|
||||
/**
|
||||
* Lists every script that has ever called `ExcalidrawAutomate.
|
||||
* registerAutostart()` (i.e. the user ran it at least once), each with an
|
||||
* editable Autostart / Manual start only / Ask every time control (reusing
|
||||
* the exact same labels as the permission prompt's buttons, so the two
|
||||
* surfaces speak one consistent vocabulary), and a warning if the script's
|
||||
* most recent autostart run failed (`settings.autostartScriptFailures`,
|
||||
* purely informational - it never changes the script's setting on its
|
||||
* own). A "Manual start only" (deny) decision is not a dead end: it can be
|
||||
* switched straight back to Autostart or Ask every time from here, without
|
||||
* needing to re-run the script to get prompted again.
|
||||
*
|
||||
* Rendered as a bordered table (header row + one row per script), reusing
|
||||
* the AI provider table's existing `.excalidraw-ai-provider-table` CSS (see
|
||||
* `renderAISettings()` in `settings.ts`) rather than adding near-duplicate
|
||||
* rules to `styles.css`, and rather than a foldable `<details>` section,
|
||||
* since this is a short, flat list rather than a large collapsible
|
||||
* settings group. Rendered both inline in Settings (under the Startup
|
||||
* script setting, in the ExcalidrawAutomate section) and inside
|
||||
* `AutostartScriptsModal` for the Command Palette entry point, matching
|
||||
* how `EmbeddalbeMDFileCustomDataSettingsComponent` is reused across
|
||||
* contexts.
|
||||
*/
|
||||
export class AutostartScriptsSettingsComponent {
|
||||
constructor(
|
||||
private contentEl: HTMLElement,
|
||||
private plugin: ExcalidrawPlugin,
|
||||
) {}
|
||||
|
||||
render(): void {
|
||||
this.contentEl.empty();
|
||||
this.contentEl.addClass("excalidraw-ai-provider-table");
|
||||
|
||||
const autostartScripts = this.plugin.settings.autostartScripts;
|
||||
const scriptNames = Object.keys(autostartScripts).sort();
|
||||
|
||||
const headerSetting = new Setting(this.contentEl)
|
||||
.setName(t("AUTOSTART_SCRIPTS_HEAD"))
|
||||
.setDesc(fragWithHTML(t("AUTOSTART_SCRIPTS_DESC")));
|
||||
headerSetting.settingEl.addClass("excalidraw-ai-provider-table__header");
|
||||
|
||||
if (scriptNames.length === 0) {
|
||||
const emptyRow = new Setting(this.contentEl).setDesc(
|
||||
t("AUTOSTART_SCRIPTS_EMPTY"),
|
||||
);
|
||||
emptyRow.settingEl.addClass("excalidraw-ai-provider-table__row");
|
||||
return;
|
||||
}
|
||||
|
||||
scriptNames.forEach((scriptName) => {
|
||||
const rowSetting = new Setting(this.contentEl)
|
||||
.setName(scriptName)
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("allow", t("AUTOSTART_SCRIPT_ALLOW"))
|
||||
.addOption("deny", t("AUTOSTART_SCRIPT_DENY"))
|
||||
.addOption("unknown", t("AUTOSTART_SCRIPT_ASK_LATER"))
|
||||
.setValue(autostartScripts[scriptName])
|
||||
.onChange(async (value) => {
|
||||
autostartScripts[scriptName] = value as
|
||||
| "allow"
|
||||
| "deny"
|
||||
| "unknown";
|
||||
await this.plugin.saveSettings();
|
||||
}),
|
||||
);
|
||||
rowSetting.settingEl.addClass("excalidraw-ai-provider-table__row");
|
||||
|
||||
if (this.plugin.settings.autostartScriptFailures[scriptName]) {
|
||||
rowSetting.setDesc(
|
||||
fragWithHTML(
|
||||
`<span style="color: var(--text-error);">${t("AUTOSTART_SCRIPT_FAILED_WARNING")}</span>`,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class AutostartScriptsModal extends Modal {
|
||||
constructor(private plugin: ExcalidrawPlugin) {
|
||||
super(plugin.app);
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.titleEl.setText(t("AUTOSTART_SCRIPTS_HEAD"));
|
||||
new AutostartScriptsSettingsComponent(
|
||||
this.contentEl,
|
||||
this.plugin,
|
||||
).render();
|
||||
|
||||
new Setting(this.contentEl).addButton((button) =>
|
||||
button.setButtonText(t("PROMPT_BUTTON_CLOSE")).onClick(() => this.close()),
|
||||
);
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
this.contentEl.empty();
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { Modal, Notice, Setting, TFile } from "obsidian";
|
||||
import { getEA } from "src/core";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import {
|
||||
fragWithHTML,
|
||||
@@ -81,7 +81,7 @@ export class ExportDialog extends Modal {
|
||||
this.theme = getExportTheme(
|
||||
this.plugin,
|
||||
this.file,
|
||||
this.api.getAppState().theme as string,
|
||||
this.api.getAppState().theme,
|
||||
);
|
||||
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
|
||||
this.embedScene = shouldEmbedScene(this.plugin, this.file);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { BaseComponent, Setting, Modifier } from "obsidian";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { ExcalidrawSettings } from "src/core/settings";
|
||||
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
|
||||
import { modifierLabel } from "src/utils/modifierkeyHelper";
|
||||
import { fragWithHTML } from "src/utils/utils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
@@ -288,7 +288,7 @@ export class InsertPDFModal extends Modal {
|
||||
numPagesMessages();
|
||||
new Setting(ce)
|
||||
.setName(t("IPM_PAGES_TO_IMPORT_NAME"))
|
||||
.setDesc("e.g.: 1,3-5,7,9-10")
|
||||
.setDesc(t("IPM_PAGES_TO_IMPORT_DESC"))
|
||||
.addText((text) => {
|
||||
pageRangesTextComponent = text;
|
||||
text.setValue("").onChange(async (value) => {
|
||||
|
||||
@@ -17,8 +17,50 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
|
||||
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
|
||||
`,
|
||||
// ${getYouTubeDiv("p9MBFxUoOXQ")}
|
||||
"2.26.0": `
|
||||
"2.27.0": `
|
||||
## Maintenance
|
||||
- Refactoring the plugin. Removed unused functions, improved code structure and readability. Removed the obsolete Draw.io/Diagram plugin integration (since the other plugin no longer works and is not maintained) and retired the Create DrawIO file script from the script library.
|
||||
- Migrated the embedded Excalidraw runtime from the retired UMD build path to a dedicated ESM-source-based Obsidian package while preserving offline operation, popout windows, and runtime Mermaid loading through Excalidraw Extras. The Assistant UI font is now bundled instead of fetched from the internet, and the plugin-private React runtime is generated from the official npm package entrypoints instead of legacy UMD files.
|
||||
- Updated the plugin-private React and ReactDOM runtime to React 19.
|
||||
|
||||
## Fixed
|
||||
- The Excalidraw color palette now uses its natural height when space is available instead of being unnecessarily limited to a short, vertically scrolling panel. Its native color control also remains aligned with the hex input.
|
||||
- The text-to-diagram chat history menu is visible again, allowing saved chats to be restored and deleted.
|
||||
- Stencil library is persisted with tab-indented JSON to support Git diffs. [#2883](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2883)
|
||||
- Custom color-picker top picks (pinned by dragging a color onto the strip) are now saved with the drawing instead of being forgotten on reload.
|
||||
- Changing the canvas background color from the color-picker popover no longer leaves the popover's own theming out of sync until it's closed and reopened.
|
||||
|
||||
## New from Excalidraw.com
|
||||
- Improved bucket tool and eyedropper support [#11849](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11849)
|
||||
- Respect box selection mode ('contain' vs 'overlap') in lasso selection [#11862](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11862)
|
||||
- Color-picker top picks can now be customized by dragging a color from the palette onto the strip; right-click the strip to reset [#11872](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11872)
|
||||
|
||||
## New in Excalidraw Automate
|
||||
- Scripts can now register custom buttons in the selected-element context menu (the small toolbar shown above a selected element):
|
||||
\`\`\`ts
|
||||
registerElementActionProvider(getActions: (element: ExcalidrawElement) => readonly {id: string, title: string, icon: string, action: () => void}[]): (() => void) | null;
|
||||
\`\`\`
|
||||
- Scripts can now ask to be automatically re-run every time a new Excalidraw view is opened, with a user-confirmed Allow/Deny/Ask-me-later prompt; a fresh Allow also attaches the script to every other currently-open view immediately. Manage which scripts are allowed to autostart from the "Autostart scripts" command or the Compatibility settings section:
|
||||
\`\`\`ts
|
||||
registerAutostart(): Promise<"allow" | "deny" | "pending">;
|
||||
\`\`\`
|
||||
`,
|
||||
"2.26.4": `
|
||||
## Fixed
|
||||
- Markdown-image edits could be lost in some usage scenarios, 2.26.3 did not provide a broad enough fix. [#2865](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2865)
|
||||
|
||||
`,
|
||||
"2.26.3": `
|
||||
## Fixed
|
||||
- Editing one Markdown image and immediately selecting another to edit could silently drop the first image's contents, both from memory and from the note on disk. Reported on the [Sketch Your Mind community](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}/t/excalidraw-2-26-0/7791/2). 🙏
|
||||
- Deleting the last local Markdown image via the Excalidraw properties panel's delete button no longer skips the prompt to keep or delete its Markdown content. Deletion detection now covers every trigger (keyboard, Cut, context menu, panel button, or scripts) uniformly.
|
||||
|
||||
## New from Excalidraw.com
|
||||
- New tool: Bucket fill. See more tools menu, or press B to toggle the bucket fill tool. [#11799](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11799)
|
||||
`,
|
||||
"2.26.2": `
|
||||
${getYouTubeDiv("p9MBFxUoOXQ")}
|
||||
|
||||
## New
|
||||
- Stencil libraries can now be stored as vault files instead of \`data.json\`, improving plugin settings stability. Existing users are offered a safe, merge-first migration. To sync libraries, enable **Sync all other types** in Obsidian Sync. To view library files, enable **Show all file types** in Obsidian settings.
|
||||
- Added editable Markdown images.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Modal, Setting, TFile, TAbstractFile } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { log } from "src/utils/debugHelper";
|
||||
import { getIMGFilename } from "src/utils/fileUtils";
|
||||
@@ -110,7 +111,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
|
||||
|
||||
onOpen() {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText(`Out of Date SVG Files`);
|
||||
this.titleEl.setText(t("POODF_TITLE"));
|
||||
void this.createForm(false);
|
||||
}
|
||||
|
||||
@@ -144,7 +145,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
|
||||
};
|
||||
if (!recursive) {
|
||||
const bRecursive = div.createEl("button", {
|
||||
text: "Check Recursive",
|
||||
text: t("POODF_CHECK_RECURSIVE"),
|
||||
cls: "excalidraw-prompt-button",
|
||||
});
|
||||
bRecursive.onclick = () => {
|
||||
@@ -178,7 +179,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
|
||||
};
|
||||
if (!recursive) {
|
||||
const bRecursive = div.createEl("button", {
|
||||
text: "Check Recursive",
|
||||
text: t("POODF_CHECK_RECURSIVE"),
|
||||
cls: "excalidraw-prompt-button",
|
||||
});
|
||||
bRecursive.onclick = () => {
|
||||
@@ -187,7 +188,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
|
||||
};
|
||||
}
|
||||
const bOpen = div.createEl("button", {
|
||||
text: "Open Selected",
|
||||
text: t("POODF_OPEN_SELECTED"),
|
||||
cls: "excalidraw-prompt-button",
|
||||
});
|
||||
bOpen.onclick = () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { App, Component, MarkdownRenderer, Modal } from "obsidian";
|
||||
import { isVersionNewerThanOther } from "src/utils/utils";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import type ExcalidrawPlugin from "../../core/main";
|
||||
import { RELEASE_NOTES } from "./Messages";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
@@ -996,6 +996,28 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
"In case the script wants to replace the sidepanel tab it created earlier, call closeSidepanelTab() first, then createSidepanelTab() again.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "registerElementActionProvider",
|
||||
code:
|
||||
"registerElementActionProvider(getActions: (element: ExcalidrawElement) => readonly {id: string, title: string, icon: string, action: () => void}[]): (() => void) | null;",
|
||||
desc:
|
||||
"Registers custom action buttons in the selected-element context menu (the small toolbar shown above a single selected element). " +
|
||||
"getActions is called with the selected element whenever the selection, element type, fileId, or customData changes; return an empty array to show nothing. " +
|
||||
"Registration is cleared automatically when the view closes, and cleared for this script specifically if the script's file is deleted while the view is still open. " +
|
||||
"Calling this again for the same script in the same view (e.g. running the script again while it is already registered) does not create a duplicate - it is a no-op that returns null. " +
|
||||
"Returns a cleanup function to unregister manually, or null if there is no active target view or this script is already registered in it.",
|
||||
after: '((element) => element.type === "rectangle" ? [{id: "my-action", title: "My Action", icon: "star", action: () => console.log(element.id)}] : []);',
|
||||
},
|
||||
{
|
||||
field: "registerAutostart",
|
||||
code: 'registerAutostart(): Promise<"allow" | "deny" | "pending">;',
|
||||
desc:
|
||||
"Requests permission for this script to be automatically re-run every time a new Excalidraw view is opened. " +
|
||||
"The first time a given script calls this, the user is prompted to Allow, Deny, or decide later; the decision persists and is not asked again unless the user changes it (via the \"Autostart scripts\" command or settings section) or previously picked \"Ask me later\". " +
|
||||
"A fresh Allow also immediately re-runs the script in every other currently-open Excalidraw view, so it attaches everywhere right away instead of only the next time each view is opened. " +
|
||||
'Returns "allow", "deny", or "pending" (no active script, or the user has not yet decided). Typically called near the top of a script, guarding whatever the script wants to re-register on autostart, e.g. registerElementActionProvider().',
|
||||
after: "();",
|
||||
},
|
||||
{
|
||||
field: "getSidepanelLeaf",
|
||||
code: "getSidepanelLeaf(): WorkspaceLeaf | null;",
|
||||
|
||||
@@ -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 { ExcalidrawSettings } from "src/core/settings";
|
||||
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);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ButtonComponent, DropdownComponent, TFile } from "obsidian";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import type ExcalidrawPlugin from "../../core/main";
|
||||
import { Modal, Setting, TextComponent } from "obsidian";
|
||||
import { FileSuggestionModal } from "../Suggesters/FileSuggestionModal";
|
||||
import {
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
/**
|
||||
* Owns the four per-drawing embedded-data registries on `ExcalidrawData`:
|
||||
* embedded files, LaTeX equations, local Markdown images, and Mermaid
|
||||
* diagrams. Each registry mirrors its entries into a matching plugin-wide
|
||||
* "master" map (`ExcalidrawPlugin.filesMaster`/`equationsMaster`/
|
||||
* `markdownImagesMaster`/`mermaidsMaster`) so intra-vault copy/paste can
|
||||
* restore a fileId's data in a drawing that never natively loaded it.
|
||||
* Extracted intact from `ExcalidrawData.ts`; `ExcalidrawData` keeps every
|
||||
* method below as a public delegate for compatibility with its existing
|
||||
* callers.
|
||||
*/
|
||||
import type { FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import type { MarkdownImageData } from "src/types/markdownImageTypes";
|
||||
import type { EmbeddedFile } from "./EmbeddedFileLoader";
|
||||
import type { ExcalidrawData, EquationItem, MermaidItem } from "./ExcalidrawData";
|
||||
|
||||
export class EmbeddedDataRegistries {
|
||||
/**
|
||||
* `embeddedFileCtor` is constructor-injected (rather than imported as a
|
||||
* value) so this module stays type-only with respect to
|
||||
* `EmbeddedFileLoader.ts`, matching the existing pattern used to avoid
|
||||
* adding new circular-import edges around the `ExcalidrawData` cluster
|
||||
* (see `ViewLinkNavigationManager`/`ViewExcalidrawExtensionRenderer`).
|
||||
*/
|
||||
constructor(
|
||||
private host: ExcalidrawData,
|
||||
private embeddedFileCtor: typeof EmbeddedFile,
|
||||
) {}
|
||||
|
||||
//--------------
|
||||
//Files
|
||||
//--------------
|
||||
public setFile(fileId: FileId, data: EmbeddedFile) {
|
||||
//always store absolute path because in case of paste, relative path may not resolve ok
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
this.host.files.set(fileId, data);
|
||||
|
||||
if (data.isHyperLink || data.isLocalLink) {
|
||||
this.host.plugin.filesMaster.set(fileId, {
|
||||
isHyperLink: data.isHyperLink,
|
||||
isLocalLink: data.isLocalLink,
|
||||
path: data.hyperlink,
|
||||
blockrefData: null,
|
||||
hasSVGwithBitmap: data.isSVGwithBitmap,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data.file) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parts = data.linkParts.original.split("#");
|
||||
this.host.plugin.filesMaster.set(fileId, {
|
||||
isHyperLink: false,
|
||||
isLocalLink: false,
|
||||
path: data.file.path + (data.shouldScale() ? "" : "|100%"),
|
||||
blockrefData: parts.length === 1 ? null : parts[1],
|
||||
hasSVGwithBitmap: data.isSVGwithBitmap,
|
||||
colorMapJSON: data.colorMap ? JSON.stringify(data.colorMap) : null,
|
||||
});
|
||||
}
|
||||
|
||||
public getFiles(): EmbeddedFile[] {
|
||||
return Array.from(this.host.files.values());
|
||||
}
|
||||
|
||||
public getFile(fileId: FileId): EmbeddedFile {
|
||||
let embeddedFile = this.host.files.get(fileId);
|
||||
if (embeddedFile) {
|
||||
return embeddedFile;
|
||||
}
|
||||
const masterFile = this.host.plugin.filesMaster.get(fileId);
|
||||
if (!masterFile) {
|
||||
return embeddedFile;
|
||||
}
|
||||
embeddedFile = new this.embeddedFileCtor(
|
||||
this.host.plugin,
|
||||
this.host.file.path,
|
||||
masterFile.blockrefData
|
||||
? `${masterFile.path}#${masterFile.blockrefData}`
|
||||
: masterFile.path,
|
||||
masterFile.colorMapJSON,
|
||||
);
|
||||
this.host.files.set(fileId, embeddedFile);
|
||||
return embeddedFile;
|
||||
}
|
||||
|
||||
public getFileEntries() {
|
||||
return this.host.files.entries();
|
||||
}
|
||||
|
||||
public deleteFile(fileId: FileId) {
|
||||
this.host.files.delete(fileId);
|
||||
//deliberately not deleting from plugin.filesMaster
|
||||
//could be present in other drawings as well
|
||||
}
|
||||
|
||||
//Image copy/paste support
|
||||
public hasFile(fileId: FileId): boolean {
|
||||
if (this.host.files.has(fileId)) {
|
||||
return true;
|
||||
}
|
||||
if (this.host.plugin.filesMaster.has(fileId)) {
|
||||
const masterFile = this.host.plugin.filesMaster.get(fileId);
|
||||
if (masterFile.isHyperLink || masterFile.isLocalLink) {
|
||||
this.host.files.set(
|
||||
fileId,
|
||||
new this.embeddedFileCtor(
|
||||
this.host.plugin,
|
||||
this.host.file.path,
|
||||
masterFile.path,
|
||||
),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
const path = masterFile.path.split("|")[0].split("#")[0];
|
||||
if (!this.host.app.vault.getAbstractFileByPath(path)) {
|
||||
this.host.plugin.filesMaster.delete(fileId);
|
||||
return true;
|
||||
} // the file no longer exists
|
||||
const fixScale = masterFile.path.endsWith("100%");
|
||||
const embeddedFile = new this.embeddedFileCtor(
|
||||
this.host.plugin,
|
||||
this.host.file.path,
|
||||
(masterFile.blockrefData
|
||||
? `${path}#${masterFile.blockrefData}`
|
||||
: path) + (fixScale ? "|100%" : ""),
|
||||
masterFile.colorMapJSON,
|
||||
);
|
||||
this.host.files.set(fileId, embeddedFile);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//--------------
|
||||
//Equations
|
||||
//--------------
|
||||
public setEquation(
|
||||
fileId: FileId,
|
||||
data: { latex: string; isLoaded: boolean },
|
||||
) {
|
||||
this.host.equations.set(fileId, {
|
||||
latex: data.latex,
|
||||
isLoaded: data.isLoaded,
|
||||
});
|
||||
this.host.plugin.equationsMaster.set(fileId, data.latex);
|
||||
}
|
||||
|
||||
public getEquation(fileId: FileId): EquationItem {
|
||||
const result = this.host.equations.get(fileId);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
const latex = this.host.plugin.equationsMaster.get(fileId);
|
||||
if (!latex) {
|
||||
return result;
|
||||
}
|
||||
this.host.equations.set(fileId, { latex, isLoaded: false });
|
||||
return { latex, isLoaded: false };
|
||||
}
|
||||
|
||||
public getEquationEntries() {
|
||||
return this.host.equations?.entries();
|
||||
}
|
||||
|
||||
public deleteEquation(fileId: FileId) {
|
||||
this.host.equations.delete(fileId);
|
||||
//deliberately not deleting from plugin.equationsMaster
|
||||
//could be present in other drawings as well
|
||||
}
|
||||
|
||||
//Image copy/paste support
|
||||
public hasEquation(fileId: FileId): boolean {
|
||||
if (this.host.equations.has(fileId)) {
|
||||
return true;
|
||||
}
|
||||
if (this.host.plugin.equationsMaster.has(fileId)) {
|
||||
this.host.equations.set(fileId, {
|
||||
latex: this.host.plugin.equationsMaster.get(fileId),
|
||||
isLoaded: false,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//--------------
|
||||
//Local Markdown images
|
||||
//--------------
|
||||
|
||||
/** Stores a local Markdown-image source and makes it available for intra-vault copy/paste. */
|
||||
public setMarkdownImage(fileId: FileId, data: MarkdownImageData): void {
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
const value = { markdown: data.markdown ?? "" };
|
||||
this.host.markdownImages.set(fileId, value);
|
||||
this.host.plugin.markdownImagesMaster.set(fileId, value);
|
||||
}
|
||||
|
||||
/** Returns local Markdown, restoring it from the intra-vault copy master. */
|
||||
public getMarkdownImage(fileId: FileId): MarkdownImageData | undefined {
|
||||
const local = this.host.markdownImages.get(fileId);
|
||||
if (local) {
|
||||
return local;
|
||||
}
|
||||
const master = this.host.plugin.markdownImagesMaster.get(fileId);
|
||||
if (master) {
|
||||
const value = { ...master };
|
||||
this.host.markdownImages.set(fileId, value);
|
||||
return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Returns whether local Markdown exists, restoring intra-vault clipboard data. */
|
||||
public hasMarkdownImage(fileId: FileId): boolean {
|
||||
return Boolean(this.getMarkdownImage(fileId));
|
||||
}
|
||||
|
||||
/** Removes a local source, optionally discarding its clipboard master entry. */
|
||||
public deleteMarkdownImage(fileId: FileId, clearMaster = false): void {
|
||||
this.host.markdownImages.delete(fileId);
|
||||
if (clearMaster) {
|
||||
this.host.plugin.markdownImagesMaster.delete(fileId);
|
||||
}
|
||||
// Normally retain the master entry for copies already on the clipboard.
|
||||
}
|
||||
|
||||
//--------------
|
||||
//Mermaids
|
||||
//--------------
|
||||
public setMermaid(
|
||||
fileId: FileId,
|
||||
data: { mermaid: string; isLoaded: boolean },
|
||||
) {
|
||||
this.host.mermaids.set(fileId, {
|
||||
mermaid: data.mermaid,
|
||||
isLoaded: data.isLoaded,
|
||||
});
|
||||
this.host.plugin.mermaidsMaster.set(fileId, data.mermaid);
|
||||
}
|
||||
|
||||
public getMermaid(fileId: FileId): MermaidItem {
|
||||
const result = this.host.mermaids.get(fileId);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
const mermaid = this.host.plugin.mermaidsMaster.get(fileId);
|
||||
if (!mermaid) {
|
||||
return result;
|
||||
}
|
||||
this.host.mermaids.set(fileId, { mermaid, isLoaded: false });
|
||||
return { mermaid, isLoaded: false };
|
||||
}
|
||||
|
||||
public getMermaidEntries() {
|
||||
return this.host.mermaids.entries();
|
||||
}
|
||||
|
||||
public deleteMermaid(fileId: FileId) {
|
||||
this.host.mermaids.delete(fileId);
|
||||
//deliberately not deleting from plugin.mermaidsMaster
|
||||
//could be present in other drawings as well
|
||||
}
|
||||
|
||||
//Image copy/paste support
|
||||
public hasMermaid(fileId: FileId): boolean {
|
||||
if (this.host.mermaids.has(fileId)) {
|
||||
return true;
|
||||
}
|
||||
if (this.host.plugin.mermaidsMaster.has(fileId)) {
|
||||
this.host.mermaids.set(fileId, {
|
||||
mermaid: this.host.plugin.mermaidsMaster.get(fileId),
|
||||
isLoaded: false,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { App, Component, MarkdownRenderer, Notice, TFile } from "obsidian";
|
||||
import {
|
||||
DEVICE,
|
||||
DEFAULT_MD_EMBED_CSS,
|
||||
fileid,
|
||||
IMAGE_TYPES,
|
||||
@@ -22,7 +23,7 @@ import { createSVG } from "src/utils/excalidrawAutomateUtils";
|
||||
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
|
||||
import { t } from "../lang/helpers";
|
||||
import { tex2dataURL } from "./LaTeX";
|
||||
import ExcalidrawPlugin from "../core/main";
|
||||
import type ExcalidrawPlugin from "../core/main";
|
||||
import type { PdfJsDocumentProxy } from "src/types/pdfJsTypes";
|
||||
import {
|
||||
blobToBase64,
|
||||
@@ -70,7 +71,7 @@ import {
|
||||
} from "src/types/embeddedFileLoaderTypes";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { setStyleText } from "src/utils/htmlUtils";
|
||||
import { hideElement, setStyle } from "src/utils/styleUtils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
import {
|
||||
isInstanceOfHTMLImageElement,
|
||||
isInstanceOfSVGElement,
|
||||
@@ -182,6 +183,131 @@ const waitForMarkdownPostProcessors = (
|
||||
});
|
||||
};
|
||||
|
||||
const waitForDocumentFonts = async (doc: Document): Promise<void> => {
|
||||
const fontSet = doc.fonts;
|
||||
if (!fontSet) {
|
||||
return;
|
||||
}
|
||||
// FontFaceSet.ready can hang on some environments if a face stalls.
|
||||
await Promise.race([
|
||||
fontSet.ready,
|
||||
new Promise<void>((resolve) => {
|
||||
window.setTimeout(resolve, 500);
|
||||
}),
|
||||
]);
|
||||
};
|
||||
|
||||
const measureElementHeight = (element: Element | null): number => {
|
||||
if (!element) {
|
||||
return 0;
|
||||
}
|
||||
const typedElement = element as HTMLElement;
|
||||
const rectHeight = Number(typedElement.getBoundingClientRect?.().height ?? 0);
|
||||
return Math.max(
|
||||
Number(typedElement.scrollHeight ?? 0),
|
||||
Number(typedElement.offsetHeight ?? 0),
|
||||
Number(typedElement.clientHeight ?? 0),
|
||||
Number.isFinite(rectHeight) ? rectHeight : 0,
|
||||
);
|
||||
};
|
||||
|
||||
const getCssPixelValue = (value: string | null | undefined): number => {
|
||||
if (!value) {
|
||||
return 0;
|
||||
}
|
||||
const parsed = Number.parseFloat(value);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
};
|
||||
|
||||
const measureRenderedContentHeight = (element: Element | null): number => {
|
||||
if (!element) {
|
||||
return 0;
|
||||
}
|
||||
const typedElement = element as HTMLElement;
|
||||
const ownerWindow = typedElement.ownerDocument.defaultView;
|
||||
const hostRect = typedElement.getBoundingClientRect();
|
||||
let maxContentBottom = 0;
|
||||
|
||||
typedElement.querySelectorAll("*").forEach((child) => {
|
||||
const childElement = child as HTMLElement;
|
||||
const childRect = childElement.getBoundingClientRect();
|
||||
if (!Number.isFinite(childRect.bottom)) {
|
||||
return;
|
||||
}
|
||||
maxContentBottom = Math.max(maxContentBottom, childRect.bottom - hostRect.top);
|
||||
});
|
||||
|
||||
const lastChild = typedElement.lastElementChild as HTMLElement | null;
|
||||
const lastChildMarginBottom =
|
||||
ownerWindow && lastChild
|
||||
? getCssPixelValue(ownerWindow.getComputedStyle(lastChild).marginBottom)
|
||||
: 0;
|
||||
const hostPaddingBottom = ownerWindow
|
||||
? getCssPixelValue(ownerWindow.getComputedStyle(typedElement).paddingBottom)
|
||||
: 0;
|
||||
|
||||
return Math.max(
|
||||
measureElementHeight(typedElement),
|
||||
maxContentBottom + lastChildMarginBottom,
|
||||
hostRect.height,
|
||||
) + hostPaddingBottom;
|
||||
};
|
||||
|
||||
const appendMarkdownBottomSpacer = (
|
||||
container: HTMLElement,
|
||||
paddingBottom: number,
|
||||
): void => {
|
||||
const existingSpacer = container.querySelector(
|
||||
".excalidraw-md-padding-spacer",
|
||||
);
|
||||
if (existingSpacer?.parentElement) {
|
||||
existingSpacer.parentElement.removeChild(existingSpacer);
|
||||
}
|
||||
if (!(paddingBottom > 0)) {
|
||||
return;
|
||||
}
|
||||
// FIX: WebKit/iOS will often return a 0 bounding client rect for completely empty divs.
|
||||
// We insert a zero-width space so the layout engine is forced to render the block and measure its height.
|
||||
const paddingSpacer = createDiv({text: "​"});
|
||||
paddingSpacer.setAttribute("class", "excalidraw-md-padding-spacer");
|
||||
|
||||
setStyle(paddingSpacer, {
|
||||
display: "block",
|
||||
width: "100%",
|
||||
height: `${paddingBottom}px`,
|
||||
minHeight: `${paddingBottom}px`,
|
||||
color: "transparent",
|
||||
lineHeight: "0px"
|
||||
});
|
||||
container.appendChild(paddingSpacer);
|
||||
};
|
||||
|
||||
const ISOLATED_MARKDOWN_RENDER_CSS = `
|
||||
.excalidraw-md-host,
|
||||
.excalidraw-md-host * {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.excalidraw-md-host {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
letter-spacing: 0px;
|
||||
word-spacing: 0px;
|
||||
text-rendering: geometricPrecision;
|
||||
-webkit-text-size-adjust: none;
|
||||
text-size-adjust: none;
|
||||
font-kerning: none;
|
||||
font-variant-ligatures: none;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-word;
|
||||
}
|
||||
`;
|
||||
|
||||
const snapshotRenderedCanvases = (container: HTMLElement): void => {
|
||||
container.querySelectorAll("canvas").forEach((canvas) => {
|
||||
try {
|
||||
@@ -1364,7 +1490,7 @@ export class EmbeddedFilesLoader {
|
||||
depth,
|
||||
inFile: null,
|
||||
hasSVGwithBitmap: false,
|
||||
elements: result.elements as ExcalidrawElement[],
|
||||
elements: result.elements,
|
||||
});
|
||||
if (this.terminate) {
|
||||
return;
|
||||
@@ -1796,7 +1922,7 @@ export class EmbeddedFilesLoader {
|
||||
? `.excalidraw-md-host.theme-light{color-scheme:light;--background-primary:#ffffff;--background-secondary:#f5f5f5;--text-normal:#2e3338;--text-muted:#6b6b6b;--link-color:#086ddd}.excalidraw-md-host.theme-light a{color:var(--link-color)}.excalidraw-md-host.theme-light th{background-color:#dedede}.excalidraw-md-host.theme-light pre[class*=language-],.excalidraw-md-host.theme-light :not(pre)>code[class*=language-]{color:#393a34;background-color:#f5f5f5;border-color:#ddd}.excalidraw-md-host.theme-light blockquote{background-color:rgba(0,0,0,.06)}`
|
||||
: "";
|
||||
let style: string = overrides
|
||||
? `${DEFAULT_MD_EMBED_CSS}\n${markdownImageThemeCSS}\n${overrides.render.css}`
|
||||
? `${DEFAULT_MD_EMBED_CSS}\n${ISOLATED_MARKDOWN_RENDER_CSS}\n${markdownImageThemeCSS}\n${overrides.render.css}`
|
||||
: (safeFrontmatter[FRONTMATTER_KEYS["md-css"].name] ?? "");
|
||||
|
||||
let frontmatterCSSisAfile = false;
|
||||
@@ -1820,6 +1946,9 @@ export class EmbeddedFilesLoader {
|
||||
style += DEFAULT_MD_EMBED_CSS;
|
||||
}
|
||||
}
|
||||
if (!style.includes(ISOLATED_MARKDOWN_RENDER_CSS)) {
|
||||
style = `${ISOLATED_MARKDOWN_RENDER_CSS}\n${style}`;
|
||||
}
|
||||
|
||||
const borderColor: string = overrides
|
||||
? overrides.render.border.enabled
|
||||
@@ -1852,10 +1981,13 @@ export class EmbeddedFilesLoader {
|
||||
const svgClass = overrides?.isTransclusion
|
||||
? ' class="excalidraw-md-transclusion"'
|
||||
: "";
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg"${svgClass} width="${linkParts.width}px" height="${svgHeight}px">${
|
||||
|
||||
// FIX: Added viewBox="0 0 ${linkParts.width} ${svgHeight}"
|
||||
// This is mandatory for Safari to respect the width/height of the SVG when loaded as an image.
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg"${svgClass} width="${linkParts.width}px" height="${svgHeight}px" viewBox="0 0 ${linkParts.width} ${svgHeight}">${
|
||||
style ? `<style>${style}</style>` : ""
|
||||
}<foreignObject x="${inset}" y="${inset}" width="${width}px" height="${height}px">${xml}${
|
||||
xmlFooter //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/286#issuecomment-982179639
|
||||
xmlFooter
|
||||
}</foreignObject>${border}${
|
||||
fontDef !== "" ? `<defs><style>${fontDef}</style></defs>` : ""
|
||||
}</svg>`;
|
||||
@@ -1872,14 +2004,15 @@ export class EmbeddedFilesLoader {
|
||||
if (fontName !== "") {
|
||||
setStyle(mdDIV, { fontFamily: fontName });
|
||||
}
|
||||
const markdownImagePaddingBottom =
|
||||
overrides && !overrides.isTransclusion
|
||||
? overrides.render.paddingBottom
|
||||
: 0;
|
||||
setStyle(mdDIV, {
|
||||
overflow: "auto",
|
||||
overflow: "hidden",
|
||||
display: "block",
|
||||
color: fontColor && fontColor !== "" ? fontColor : "initial",
|
||||
paddingBottom:
|
||||
overrides && !overrides.isTransclusion
|
||||
? `${overrides.render.paddingBottom}px`
|
||||
: undefined,
|
||||
paddingBottom: undefined,
|
||||
});
|
||||
|
||||
const renderHost = mainDocument.body.createDiv();
|
||||
@@ -1894,6 +2027,27 @@ export class EmbeddedFilesLoader {
|
||||
zIndex: "-1",
|
||||
});
|
||||
renderHost.appendChild(mdDIV);
|
||||
const isolatedRenderStyleEl = deliberateCreateElement(
|
||||
mainDocument,
|
||||
"style",
|
||||
) as HTMLStyleElement;
|
||||
setStyleText(
|
||||
isolatedRenderStyleEl,
|
||||
ISOLATED_MARKDOWN_RENDER_CSS.replaceAll(
|
||||
".excalidraw-md-host",
|
||||
`.${MARKDOWN_TO_SVG_RENDER_CLASS}`,
|
||||
),
|
||||
);
|
||||
mainDocument.head.appendChild(isolatedRenderStyleEl);
|
||||
const isolatedFontStyleEl =
|
||||
fontDef !== ""
|
||||
? (deliberateCreateElement(mainDocument, "style") as HTMLStyleElement)
|
||||
: null;
|
||||
if (isolatedFontStyleEl) {
|
||||
setStyleText(isolatedFontStyleEl, fontDef);
|
||||
mainDocument.head.appendChild(isolatedFontStyleEl);
|
||||
await waitForDocumentFonts(mainDocument);
|
||||
}
|
||||
const renderComponent = new Component();
|
||||
renderComponent.load();
|
||||
let renderedDIV: HTMLDivElement | null = null;
|
||||
@@ -1912,10 +2066,13 @@ export class EmbeddedFilesLoader {
|
||||
} finally {
|
||||
renderComponent.unload();
|
||||
renderHost.remove();
|
||||
isolatedRenderStyleEl.remove();
|
||||
isolatedFontStyleEl?.remove();
|
||||
}
|
||||
if (renderedDIV) {
|
||||
mdDIV = renderedDIV;
|
||||
}
|
||||
appendMarkdownBottomSpacer(mdDIV, markdownImagePaddingBottom);
|
||||
if (this.terminate) {
|
||||
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
|
||||
}
|
||||
@@ -2063,18 +2220,65 @@ export class EmbeddedFilesLoader {
|
||||
//First I need to create a fully self contained copy of the document to convert
|
||||
//blank styles into inline styles using computedStyle
|
||||
const iframeHost = mainDocument.body.createDiv();
|
||||
hideElement(iframeHost);
|
||||
// Use a fixed off-screen container with STRICT width boundaries to defeat iOS iframe flattening.
|
||||
setStyle(iframeHost, {
|
||||
position: "fixed",
|
||||
left: "-100000px",
|
||||
top: "0",
|
||||
width: `${linkParts.width}px`,
|
||||
height: "10000px", // Give it plenty of room to render without scrollbars
|
||||
overflow: "hidden",
|
||||
visibility: "hidden",
|
||||
pointerEvents: "none",
|
||||
});
|
||||
let xmlINiframe = "";
|
||||
let xmlFooter = "";
|
||||
let iframeContentHeight = 0;
|
||||
let iframeFooterHeight = 0;
|
||||
try {
|
||||
const iframe = iframeHost.createEl("iframe");
|
||||
// FIX: Lock the iframe's internal dimensions
|
||||
setStyle(iframe, {
|
||||
width: `${linkParts.width}px`,
|
||||
height: "100%",
|
||||
border: "none",
|
||||
margin: "0",
|
||||
padding: "0"
|
||||
});
|
||||
|
||||
const iframeDoc = iframe.contentWindow.document;
|
||||
const iframeWindow = iframe.contentWindow;
|
||||
|
||||
// FIX: Force the iframe's body to respect the target width and prevent text inflation
|
||||
// Removed `overflow: hidden !important` so we don't accidentally clip valid heights on iOS measurement.
|
||||
const bodyReset = deliberateCreateElement(iframeDoc, "style") as HTMLStyleElement;
|
||||
setStyleText(bodyReset, `
|
||||
html, body {
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
width: ${linkParts.width}px !important;
|
||||
max-width: ${linkParts.width}px !important;
|
||||
overflow: visible !important;
|
||||
-webkit-text-size-adjust: none !important;
|
||||
text-size-adjust: none !important;
|
||||
}
|
||||
`);
|
||||
iframeDoc.head.appendChild(bodyReset);
|
||||
|
||||
if (style) {
|
||||
// Obsidian style.css does not good in this case, yet the code scanner enforces it
|
||||
const styleEl = deliberateCreateElement(iframeDoc, "style") as HTMLStyleElement;
|
||||
setStyleText(styleEl, style);
|
||||
iframeDoc.head.appendChild(styleEl);
|
||||
}
|
||||
if (fontDef !== "") {
|
||||
const fontStyleEl = deliberateCreateElement(
|
||||
iframeDoc,
|
||||
"style",
|
||||
) as HTMLStyleElement;
|
||||
setStyleText(fontStyleEl, fontDef);
|
||||
iframeDoc.head.appendChild(fontStyleEl);
|
||||
}
|
||||
// Inject the MathJax CHTML stylesheet into the iframe so that mjx-* custom elements
|
||||
// are styled correctly when measuring scroll height and computing inline styles.
|
||||
if (mjxCHtmlStyleContent) {
|
||||
@@ -2087,10 +2291,11 @@ export class EmbeddedFilesLoader {
|
||||
const footerDIV = createDiv();
|
||||
footerDIV.setAttribute("class", "excalidraw-md-footer");
|
||||
iframeDoc.body.appendChild(footerDIV);
|
||||
await waitForDocumentFonts(iframeDoc);
|
||||
|
||||
iframeDoc.body.querySelectorAll("*").forEach((el: HTMLElement) => {
|
||||
const elementStyle = el.style;
|
||||
const computedStyle = window.getComputedStyle(el);
|
||||
const computedStyle = iframeWindow.getComputedStyle(el);
|
||||
let style = "";
|
||||
for (const [prop] of Object.entries(elementStyle)) {
|
||||
if (Object.hasOwn(elementStyle ?? {}, prop)) {
|
||||
@@ -2101,6 +2306,9 @@ export class EmbeddedFilesLoader {
|
||||
el.setAttribute("style", style);
|
||||
});
|
||||
|
||||
iframeContentHeight = measureRenderedContentHeight(stylingDIV);
|
||||
iframeFooterHeight = measureRenderedContentHeight(footerDIV);
|
||||
|
||||
xmlINiframe = new XMLSerializer().serializeToString(stylingDIV);
|
||||
xmlFooter = new XMLSerializer().serializeToString(footerDIV);
|
||||
} finally {
|
||||
@@ -2127,11 +2335,20 @@ export class EmbeddedFilesLoader {
|
||||
try {
|
||||
host.appendChild(svgEl);
|
||||
mainDocument.body.appendChild(host);
|
||||
footerHeight = svgEl.querySelector(".excalidraw-md-footer").scrollHeight;
|
||||
const height =
|
||||
svgEl.querySelector(".excalidraw-md-host").scrollHeight + footerHeight;
|
||||
footerHeight = Math.max(
|
||||
measureRenderedContentHeight(svgEl.querySelector(".excalidraw-md-footer")),
|
||||
iframeFooterHeight,
|
||||
);
|
||||
const contentHeight = Math.max(
|
||||
measureRenderedContentHeight(svgEl.querySelector(".excalidraw-md-host")),
|
||||
iframeContentHeight,
|
||||
);
|
||||
const borderHeight = drawBorder ? 4 : 0;
|
||||
const measuredHeight = Math.ceil(height + borderHeight);
|
||||
// Safari on iOS under-reports foreignObject content height intermittently.
|
||||
const iOSSafetyPadding = DEVICE.isIOS ? 1 : 0;
|
||||
const measuredHeight = Math.ceil(
|
||||
contentHeight + footerHeight + borderHeight + iOSSafetyPadding,
|
||||
);
|
||||
svgHeight = overrides?.fullHeight
|
||||
? measuredHeight
|
||||
: measuredHeight <= linkParts.height
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type React from "react";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import LZString from "lz-string";
|
||||
import {
|
||||
@@ -16,6 +17,8 @@ import {
|
||||
ExcalidrawFrameElement,
|
||||
ExcalidrawTextContainer,
|
||||
ElementsMap,
|
||||
FixedPointBinding,
|
||||
BoundElement,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
|
||||
import {
|
||||
@@ -85,7 +88,12 @@ import {
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddedFile, EmbeddedFilesLoader } from "./EmbeddedFileLoader";
|
||||
import { tex2dataURL } from "./LaTeX";
|
||||
import { LatexSuitePlugin, NewFileActions } from "src/shared/Dialogs/Prompt";
|
||||
import {
|
||||
LatexSuitePlugin,
|
||||
MultiOptionConfirmationPrompt,
|
||||
NewFileActions,
|
||||
} from "src/shared/Dialogs/Prompt";
|
||||
import { t } from "src/lang/helpers";
|
||||
import {
|
||||
ConnectionPoint,
|
||||
DeviceType,
|
||||
@@ -208,6 +216,7 @@ import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
|
||||
import { AIRequest, ExcalidrawAISettings } from "src/types/AIUtilTypes";
|
||||
import { getAspectRatio } from "src/utils/YoutTubeUtils";
|
||||
import { getPDFCropRect } from "src/utils/PDFUtils";
|
||||
import type { SelectedElementMenuAction } from "src/types/elementActionTypes";
|
||||
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
|
||||
import { URL_REGISTRY, URLs } from "src/constants/safeUrls";
|
||||
|
||||
@@ -574,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") {
|
||||
@@ -1440,7 +1449,7 @@ export class ExcalidrawAutomate {
|
||||
elements,
|
||||
appState: {
|
||||
...templateAppstate,
|
||||
theme: (templateAppstate.theme ?? this.canvas.theme) as string,
|
||||
theme: (templateAppstate.theme ?? this.canvas.theme),
|
||||
viewBackgroundColor:
|
||||
templateAppstate.viewBackgroundColor ??
|
||||
this.canvas.viewBackgroundColor,
|
||||
@@ -1715,7 +1724,7 @@ export class ExcalidrawAutomate {
|
||||
...{
|
||||
appState: {
|
||||
...scene.appState,
|
||||
theme: view.getViewExportTheme(theme),
|
||||
theme: view.getViewExportTheme(theme) as "dark" | "light",
|
||||
exportEmbedScene: view.getViewExportEmbedScene(embedScene),
|
||||
},
|
||||
},
|
||||
@@ -3839,6 +3848,135 @@ export class ExcalidrawAutomate {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a provider of custom action buttons for the selected-element
|
||||
* context menu (the small toolbar shown above a single selected element).
|
||||
* `getActions` is called with the currently selected element whenever the
|
||||
* selection, element type, fileId, or customData changes, and should
|
||||
* return the buttons to show for that element (an empty array shows
|
||||
* nothing). Registration is tied to the current view: it is automatically
|
||||
* cleared when the view closes, and cleared for this script specifically
|
||||
* if the script's file is deleted while the view is still open. Calling
|
||||
* this a second time for the same script in the same view (e.g. running
|
||||
* the script again while it is already registered) does not create a
|
||||
* duplicate registration - it logs a message and returns null instead.
|
||||
* @param getActions - Given the selected element, returns the action
|
||||
* buttons to display, or an empty array to show none.
|
||||
* @returns A cleanup function that unregisters the provider, or null if
|
||||
* there is no active target view to register against, or if this script
|
||||
* has already registered a provider in this view.
|
||||
*/
|
||||
public registerElementActionProvider(
|
||||
getActions: (
|
||||
element: ExcalidrawElement,
|
||||
) => readonly SelectedElementMenuAction[],
|
||||
): (() => void) | null {
|
||||
if (!this.targetView?.selectedElementActionsMenu) {
|
||||
errorMessage(
|
||||
"targetView not set or not ready",
|
||||
"registerElementActionProvider()",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const id = this.activeScript ?? nanoid();
|
||||
if (this.targetView.selectedElementActionsMenu.hasProvider(id)) {
|
||||
errorMessage(
|
||||
"This script has already registered an element action provider in this view",
|
||||
"registerElementActionProvider()",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const unregister =
|
||||
this.targetView.selectedElementActionsMenu.registerProvider({
|
||||
id,
|
||||
getActions,
|
||||
});
|
||||
if (this.activeScript) {
|
||||
this.plugin.scriptEngine.trackElementActionProvider(
|
||||
this.activeScript,
|
||||
unregister,
|
||||
);
|
||||
}
|
||||
// registerProvider() primes the menu to recompute actions on its next
|
||||
// update(), but nothing else calls update() until the next genuine
|
||||
// selection/scene change. If an eligible element is already selected
|
||||
// at registration time (e.g. a script run via command palette while
|
||||
// something is selected), force that recompute immediately instead of
|
||||
// waiting for the user to reselect.
|
||||
const appState = this.targetView.excalidrawAPI?.getAppState();
|
||||
if (appState) {
|
||||
this.targetView.selectedElementActionsMenu.update(
|
||||
this.targetView.getViewElements(),
|
||||
appState,
|
||||
);
|
||||
}
|
||||
return unregister;
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests permission for the active script to be automatically re-run
|
||||
* every time a new Excalidraw view is opened (see
|
||||
* `ScriptEngine.runAutostartScripts()`). The first time a given script
|
||||
* calls this, the user is prompted to Allow, Deny, or decide later; the
|
||||
* decision persists in plugin settings (viewable/editable via the
|
||||
* "Autostart scripts" command and settings section) and is not asked
|
||||
* again unless the user changes it or previously picked "Ask me later".
|
||||
* A fresh "allow" also immediately re-runs the script in every other
|
||||
* currently-open Excalidraw view, so it attaches everywhere right away
|
||||
* instead of only the next time each view is opened.
|
||||
* @returns "allow" if the script is permitted to autostart, "deny" if
|
||||
* the user has denied it, or "pending" if there is no active script or
|
||||
* the user has not yet made a decision.
|
||||
*/
|
||||
public async registerAutostart(): Promise<"allow" | "deny" | "pending"> {
|
||||
const scriptName = this.activeScript;
|
||||
if (!scriptName) {
|
||||
errorMessage("no active script", "registerAutostart()");
|
||||
return "pending";
|
||||
}
|
||||
const autostartScripts = this.plugin.settings.autostartScripts;
|
||||
let state = autostartScripts[scriptName];
|
||||
if (!state) {
|
||||
state = "unknown";
|
||||
autostartScripts[scriptName] = state;
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
if (state === "allow" || state === "deny") {
|
||||
return state;
|
||||
}
|
||||
const prompt = new MultiOptionConfirmationPrompt<
|
||||
"allow" | "deny" | "pending" | null
|
||||
>(
|
||||
this.plugin,
|
||||
`<b>${scriptName}</b> ${t("AUTOSTART_SCRIPT_PROMPT")}<br><br>` +
|
||||
`<span style="color: var(--text-muted); font-size: var(--font-smaller);">` +
|
||||
`${t("AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT")}</span>`,
|
||||
new Map([
|
||||
[t("AUTOSTART_SCRIPT_ALLOW"), "allow"],
|
||||
[t("AUTOSTART_SCRIPT_DENY"), "deny"],
|
||||
[t("AUTOSTART_SCRIPT_ASK_LATER"), "pending"],
|
||||
]),
|
||||
t("AUTOSTART_SCRIPT_ASK_LATER"),
|
||||
);
|
||||
const decision = await prompt.waitForClose;
|
||||
if (decision === "allow" || decision === "deny") {
|
||||
autostartScripts[scriptName] = decision;
|
||||
await this.plugin.saveSettings();
|
||||
if (decision === "allow") {
|
||||
// A freshly granted "allow" should attach the script to every other
|
||||
// currently-open view immediately, not only the next time each view
|
||||
// is opened (that ongoing case is handled separately by
|
||||
// ScriptEngine.runAutostartScripts() at view-mount time).
|
||||
this.plugin.scriptEngine.attachAutostartScriptToOpenViews(
|
||||
scriptName,
|
||||
this.targetView,
|
||||
);
|
||||
}
|
||||
return decision;
|
||||
}
|
||||
return "pending";
|
||||
}
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered when the user closes an Excalidraw view.
|
||||
*/
|
||||
@@ -4576,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;
|
||||
}
|
||||
@@ -4597,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)
|
||||
) {
|
||||
@@ -4643,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)!;
|
||||
@@ -4665,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
|
||||
}),
|
||||
@@ -4887,9 +5042,7 @@ export class ExcalidrawAutomate {
|
||||
);
|
||||
return false;
|
||||
}
|
||||
this.copyViewElementsToEAforEditing(
|
||||
res.content as unknown as ExcalidrawElement[],
|
||||
);
|
||||
this.copyViewElementsToEAforEditing(res.content);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
|
||||
export class ExcalidrawConfig {
|
||||
public areaLimit: number = 16777216;
|
||||
|
||||
+93
-631
@@ -18,25 +18,20 @@ import {
|
||||
refreshTextDimensions,
|
||||
getContainerElement,
|
||||
loadSceneFonts,
|
||||
MD_MARKDOWN_IMAGES,
|
||||
} from "../constants/constants";
|
||||
import ExcalidrawPlugin from "../core/main";
|
||||
import { TextMode } from "./TextMode";
|
||||
import type ExcalidrawView from "../view/ExcalidrawView";
|
||||
import { addAppendUpdateCustomData } from "../utils/elementCustomDataUtils";
|
||||
import {
|
||||
compress,
|
||||
decompress,
|
||||
getBinaryFileFromDataURL,
|
||||
getExportTheme,
|
||||
getLinkParts,
|
||||
hasExportTheme,
|
||||
isVersionNewerThanOther,
|
||||
LinkParts,
|
||||
updateFrontmatterInString,
|
||||
wrapTextAtCharLength,
|
||||
arrayToMap,
|
||||
compressAsync,
|
||||
} from "../utils/sceneDataUtils";
|
||||
import { isObsidianThemeDark } from "../utils/obsidianUtils";
|
||||
import { cleanBlockRef, cleanSectionHeading } from "../utils/pathUtils";
|
||||
@@ -47,6 +42,7 @@ import {
|
||||
NonDeletedExcalidrawElement,
|
||||
ExcalidrawTextElement,
|
||||
FileId,
|
||||
Theme,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import {
|
||||
BinaryFiles,
|
||||
@@ -54,6 +50,7 @@ import {
|
||||
SceneData,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddedFile } from "./EmbeddedFileLoader";
|
||||
import { EmbeddedDataRegistries } from "./EmbeddedDataRegistries";
|
||||
import { MimeType } from "src/types/embeddedFileLoaderTypes";
|
||||
import { MultiOptionConfirmationPrompt } from "./Dialogs/Prompt";
|
||||
import {
|
||||
@@ -76,6 +73,35 @@ import {
|
||||
type MarkdownImageCustomData,
|
||||
type MarkdownImageData,
|
||||
} from "src/types/markdownImageTypes";
|
||||
import {
|
||||
changeThemeOfExcalidrawMD,
|
||||
DRAWING_COMPRESSED_REG,
|
||||
getExcalidrawMarkdownHeader,
|
||||
getExcalidrawMarkdownHeaderSection,
|
||||
getJSON,
|
||||
getMarkdownDrawingSection,
|
||||
getMarkdownDrawingSectionAsync,
|
||||
parseMarkdownImages,
|
||||
RE_EXCALIDRAWDATA_FALLBACK_2,
|
||||
RE_EXCALIDRAWDATA_NOSECTION_OK,
|
||||
RE_TEXTELEMENTS_FALLBACK_2,
|
||||
RE_TEXTELEMENTS_NOSECTION_OK,
|
||||
syncMarkdownImagesInHeader,
|
||||
unwrapMarkdownImageBlock,
|
||||
} from "./excalidrawMarkdownParsing";
|
||||
|
||||
export {
|
||||
changeThemeOfExcalidrawMD,
|
||||
DRAWING_COMPRESSED_REG,
|
||||
getExcalidrawMarkdownHeader,
|
||||
getExcalidrawMarkdownHeaderSection,
|
||||
getJSON,
|
||||
getMarkdownDrawingSection,
|
||||
getMarkdownDrawingSectionAsync,
|
||||
parseMarkdownImages,
|
||||
syncMarkdownImagesInHeader,
|
||||
unwrapMarkdownImageBlock,
|
||||
};
|
||||
|
||||
type SceneDataWithFiles = SceneData & { files: BinaryFiles };
|
||||
|
||||
@@ -85,7 +111,19 @@ type LegacyGridColor = NonNullable<
|
||||
MajorGridFrequency?: number;
|
||||
};
|
||||
|
||||
type ExcalidrawDataScene = SceneDataWithFiles & {
|
||||
/**
|
||||
* `SceneDataWithFiles` (via `SceneData`) already declares optional
|
||||
* `elements`/`appState` fields. Intersecting it directly would make
|
||||
* TypeScript intersect those declarations with the stricter ones below
|
||||
* (e.g. `readonly ExcalidrawElement[] & Mutable<ExcalidrawElement>[]`)
|
||||
* instead of replacing them, which silently collapses every `.filter()`/
|
||||
* `.find()` call on `scene.elements` to `any`. Omitting them first makes
|
||||
* this an actual override.
|
||||
*/
|
||||
type ExcalidrawDataScene = Omit<
|
||||
SceneDataWithFiles,
|
||||
"elements" | "appState"
|
||||
> & {
|
||||
type?: string;
|
||||
version?: number;
|
||||
source?: string;
|
||||
@@ -203,456 +241,8 @@ export const REGEX_LINK = {
|
||||
},
|
||||
};
|
||||
|
||||
//added \n at and of DRAWING_REG: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/357
|
||||
const DRAWING_REG = /\n##? Drawing\n[^`]*(```json\n)([\s\S]*?)```\n/gm; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/182
|
||||
const DRAWING_REG_FALLBACK = /\n##? Drawing\n(```json\n)?(.*)(```)?(%%)?/gm;
|
||||
export const DRAWING_COMPRESSED_REG =
|
||||
/(\n##? Drawing\n[^`]*(?:```compressed-json\n))([\s\S]*?)(```\n)/gm; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/182
|
||||
const DRAWING_COMPRESSED_REG_FALLBACK =
|
||||
/(\n##? Drawing\n(?:```compressed-json\n)?)(.*)((```)?(%%)?)/gm;
|
||||
export const REG_LINKINDEX_HYPERLINK = /^\w+:\/\//;
|
||||
|
||||
const isCompressedMD = (data: string): boolean => {
|
||||
return data.match(/```compressed-json\n/gm) !== null;
|
||||
};
|
||||
|
||||
const getDecompressedScene = (
|
||||
data: string,
|
||||
): [string | null, RegExpMatchIteratorResult] => {
|
||||
let res = data.matchAll(DRAWING_COMPRESSED_REG);
|
||||
|
||||
//In case the user adds a text element with the contents "# Drawing\n"
|
||||
let parts;
|
||||
parts = res.next();
|
||||
if (parts.done) {
|
||||
//did not find a match
|
||||
res = data.matchAll(DRAWING_COMPRESSED_REG_FALLBACK);
|
||||
parts = res.next();
|
||||
}
|
||||
if (parts.value && parts.value.length > 1) {
|
||||
return [decompress(parts.value[2]), parts];
|
||||
}
|
||||
return [null, parts];
|
||||
};
|
||||
|
||||
export const changeThemeOfExcalidrawMD = (data: string): string => {
|
||||
const compressed = isCompressedMD(data);
|
||||
let scene = compressed ? getDecompressedScene(data)[0] : data;
|
||||
if (!scene) {
|
||||
return data;
|
||||
}
|
||||
if (isObsidianThemeDark) {
|
||||
if ((scene.match(/"theme"\s*:\s*"light"\s*,/g) || []).length === 1) {
|
||||
scene = scene.replace(/"theme"\s*:\s*"light"\s*,/, `"theme": "dark",`);
|
||||
}
|
||||
} else if ((scene.match(/"theme"\s*:\s*"dark"\s*,/g) || []).length === 1) {
|
||||
scene = scene.replace(/"theme"\s*:\s*"dark"\s*,/, `"theme": "light",`);
|
||||
}
|
||||
if (compressed) {
|
||||
return data.replace(DRAWING_COMPRESSED_REG, `$1${compress(scene)}$3`);
|
||||
}
|
||||
return scene;
|
||||
};
|
||||
|
||||
export function getJSON(data: string): { scene: string; pos: number } {
|
||||
let res;
|
||||
if (isCompressedMD(data)) {
|
||||
const [result, parts] = getDecompressedScene(data);
|
||||
if (result) {
|
||||
return {
|
||||
scene: result.substring(0, result.lastIndexOf("}") + 1),
|
||||
pos: parts.value.index,
|
||||
}; //this is a workaround in case sync merges two files together and one version is still an old version without the ```codeblock
|
||||
}
|
||||
return { scene: data, pos: parts.value ? parts.value.index : 0 };
|
||||
}
|
||||
res = data.matchAll(DRAWING_REG);
|
||||
|
||||
//In case the user adds a text element with the contents "# Drawing\n"
|
||||
let parts;
|
||||
parts = res.next();
|
||||
if (parts.done) {
|
||||
//did not find a match
|
||||
res = data.matchAll(DRAWING_REG_FALLBACK);
|
||||
parts = res.next();
|
||||
}
|
||||
if (parts.value && parts.value.length > 1) {
|
||||
const result = parts.value[2];
|
||||
return {
|
||||
scene: result.substring(0, result.lastIndexOf("}") + 1),
|
||||
pos: parts.value.index,
|
||||
}; //this is a workaround in case sync merges two files together and one version is still an old version without the ```codeblock
|
||||
}
|
||||
return { scene: data, pos: parts.value ? parts.value.index : 0 };
|
||||
}
|
||||
|
||||
export async function getMarkdownDrawingSectionAsync(
|
||||
jsonString: string,
|
||||
compressed: boolean,
|
||||
) {
|
||||
const result = compressed
|
||||
? `## Drawing\n\x60\x60\x60compressed-json\n${await compressAsync(
|
||||
jsonString,
|
||||
)}\n\x60\x60\x60\n%%`
|
||||
: `## Drawing\n\x60\x60\x60json\n${jsonString}\n\x60\x60\x60\n%%`;
|
||||
return result;
|
||||
}
|
||||
|
||||
export function getMarkdownDrawingSection(
|
||||
jsonString: string,
|
||||
compressed: boolean,
|
||||
): string {
|
||||
const result = compressed
|
||||
? `## Drawing\n\x60\x60\x60compressed-json\n${compress(
|
||||
jsonString,
|
||||
)}\n\x60\x60\x60\n%%`
|
||||
: `## Drawing\n\x60\x60\x60json\n${jsonString}\n\x60\x60\x60\n%%`;
|
||||
return result;
|
||||
}
|
||||
|
||||
const MARKDOWN_IMAGE_OPEN_MARKER =
|
||||
/^<!-- excalidraw-markdown-image:([\w-]+) -->$/gm;
|
||||
|
||||
type MarkdownImageBlock = {
|
||||
fileId: FileId;
|
||||
start: number;
|
||||
bodyStart: number;
|
||||
bodyEnd: number;
|
||||
end: number;
|
||||
};
|
||||
|
||||
const getMarkdownImageBlocks = (data: string): MarkdownImageBlock[] => {
|
||||
const blocks: MarkdownImageBlock[] = [];
|
||||
const openMarker = new RegExp(MARKDOWN_IMAGE_OPEN_MARKER);
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = openMarker.exec(data)) !== null) {
|
||||
const fileId = match[1] as FileId;
|
||||
const bodySeparator = data.startsWith("\r\n\r\n", openMarker.lastIndex)
|
||||
? "\r\n\r\n"
|
||||
: "\n\n";
|
||||
if (!data.startsWith(bodySeparator, openMarker.lastIndex)) {
|
||||
continue;
|
||||
}
|
||||
const closeMarker = `<!-- /excalidraw-markdown-image:${fileId} -->`;
|
||||
const closeIndex = data.indexOf(
|
||||
`${bodySeparator}${closeMarker}`,
|
||||
openMarker.lastIndex + bodySeparator.length,
|
||||
);
|
||||
if (closeIndex === -1) {
|
||||
continue;
|
||||
}
|
||||
const end = closeIndex + bodySeparator.length + closeMarker.length;
|
||||
blocks.push({
|
||||
fileId,
|
||||
start: match.index,
|
||||
bodyStart: openMarker.lastIndex + bodySeparator.length,
|
||||
bodyEnd: closeIndex,
|
||||
end,
|
||||
});
|
||||
openMarker.lastIndex = end;
|
||||
}
|
||||
return blocks;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads locally stored Markdown-image bodies from marker-delimited blocks.
|
||||
* Marker matching is deliberately independent of headings and block position.
|
||||
*/
|
||||
export function parseMarkdownImages(data: string): Map<FileId, MarkdownImageData> {
|
||||
const result = new Map<FileId, MarkdownImageData>();
|
||||
getMarkdownImageBlocks(data).forEach((block) =>
|
||||
result.set(block.fileId, {
|
||||
markdown: data.substring(block.bodyStart, block.bodyEnd),
|
||||
}),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a local Markdown-image block's marker comments while preserving its
|
||||
* Markdown body and surrounding document content exactly.
|
||||
*
|
||||
* @param data - Complete Excalidraw Markdown document.
|
||||
* @param fileId - File ID identifying the local Markdown-image block.
|
||||
* @param markdown - Optional current in-memory body to preserve instead of a
|
||||
* potentially stale body from the document.
|
||||
* @returns The document with the matching marker comments removed.
|
||||
*/
|
||||
export function unwrapMarkdownImageBlock(
|
||||
data: string,
|
||||
fileId: FileId,
|
||||
markdown?: string,
|
||||
): string {
|
||||
const blocks = getMarkdownImageBlocks(data).filter(
|
||||
(block) => block.fileId === fileId,
|
||||
);
|
||||
let updated = data;
|
||||
for (let index = blocks.length - 1; index >= 0; index--) {
|
||||
const block = blocks[index];
|
||||
updated =
|
||||
updated.slice(0, block.start) +
|
||||
(markdown ?? updated.slice(block.bodyStart, block.bodyEnd)) +
|
||||
updated.slice(block.end);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
const serializeMarkdownImageBlock = (
|
||||
fileId: FileId,
|
||||
markdown: string,
|
||||
): string =>
|
||||
`<!-- excalidraw-markdown-image:${fileId} -->\n\n${markdown}\n\n<!-- /excalidraw-markdown-image:${fileId} -->`;
|
||||
|
||||
/**
|
||||
* Synchronizes local Markdown-image bodies in the user-editable note header.
|
||||
* Existing blocks stay where the user placed them; only missing blocks receive
|
||||
* the default scaffolding immediately above Excalidraw Data.
|
||||
*/
|
||||
export function syncMarkdownImagesInHeader(
|
||||
header: string,
|
||||
markdownImages: ReadonlyMap<FileId, MarkdownImageData>,
|
||||
): string {
|
||||
const blocks = getMarkdownImageBlocks(header);
|
||||
const existingIds = new Set<FileId>();
|
||||
let updated = header;
|
||||
for (let index = blocks.length - 1; index >= 0; index--) {
|
||||
const block = blocks[index];
|
||||
const data = markdownImages.get(block.fileId);
|
||||
if (!data) {
|
||||
updated = updated.slice(0, block.start) + updated.slice(block.end);
|
||||
continue;
|
||||
}
|
||||
existingIds.add(block.fileId);
|
||||
updated =
|
||||
updated.slice(0, block.bodyStart) +
|
||||
data.markdown +
|
||||
updated.slice(block.bodyEnd);
|
||||
}
|
||||
|
||||
const missing = [...markdownImages.entries()].filter(
|
||||
([fileId]) => !existingIds.has(fileId),
|
||||
);
|
||||
if (missing.length > 0) {
|
||||
const hasExistingBlocks = getMarkdownImageBlocks(updated).length > 0;
|
||||
const hasScaffoldingHeading = updated
|
||||
.split(/\r?\n/)
|
||||
.some((line) => line.trimEnd() === MD_MARKDOWN_IMAGES);
|
||||
const blocksToAppend = missing
|
||||
.map(([fileId, data]) => serializeMarkdownImageBlock(fileId, data.markdown))
|
||||
.join("\n\n");
|
||||
updated = `${updated.replace(/\s*$/, "")}${
|
||||
hasExistingBlocks || hasScaffoldingHeading
|
||||
? "\n\n"
|
||||
: `\n\n${MD_MARKDOWN_IMAGES}\n\n`
|
||||
}${blocksToAppend}\n\n`;
|
||||
} else if (markdownImages.size === 0) {
|
||||
updated = updated.replace(
|
||||
new RegExp(`(?:^|\\n)${MD_MARKDOWN_IMAGES}[ \\t]*\\n*$`),
|
||||
"\n",
|
||||
);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
//WITHSECTION refers to back of the card note (see this.inputEl.onkeyup in SelectCard.ts)
|
||||
const RE_EXCALIDRAWDATA_WITHSECTION_OK =
|
||||
/^(#\n+)%%\n+# Excalidraw Data(?:\n|$)/m;
|
||||
const RE_EXCALIDRAWDATA_WITHSECTION_NOTOK =
|
||||
/#\n+%%\n+# Excalidraw Data(?:\n|$)/m;
|
||||
const RE_EXCALIDRAWDATA_NOSECTION_OK = /^(%%\n+)?# Excalidraw Data(?:\n|$)/m;
|
||||
|
||||
//WITHSECTION refers to back of the card note (see this.inputEl.onkeyup in SelectCard.ts)
|
||||
const RE_TEXTELEMENTS_WITHSECTION_OK = /^#\n+%%\n+##? Text Elements(?:\n|$)/m;
|
||||
const RE_TEXTELEMENTS_WITHSECTION_NOTOK = /#\n+%%\n+##? Text Elements(?:\n|$)/m;
|
||||
const RE_TEXTELEMENTS_NOSECTION_OK = /^(%%\n+)?##? Text Elements(?:\n|$)/m;
|
||||
|
||||
//The issue is that when editing in markdown embeds the user can delete the last enter causing two sections
|
||||
//to collide. This is particularly problematic when the user is editing the last section before # Text Elements
|
||||
const RE_EXCALIDRAWDATA_FALLBACK_1 = /(.*)%%\n+# Excalidraw Data(?:\n|$)/m;
|
||||
const RE_EXCALIDRAWDATA_FALLBACK_2 = /(.*)# Excalidraw Data(?:\n|$)/m;
|
||||
|
||||
const RE_TEXTELEMENTS_FALLBACK_1 = /(.*)%%\n+##? Text Elements(?:\n|$)/m;
|
||||
const RE_TEXTELEMENTS_FALLBACK_2 = /(.*)##? Text Elements(?:\n|$)/m;
|
||||
|
||||
const RE_DRAWING = /^(%%\n+)?##? Drawing\n/m;
|
||||
|
||||
export function getExcalidrawMarkdownHeader(data: string): {
|
||||
header: string;
|
||||
shouldFixTrailingHashtag: boolean;
|
||||
processingOk: boolean;
|
||||
} {
|
||||
//The base case scenario is at the top, continued with fallbacks in order of likelihood and file structure
|
||||
//change history for sake of backward compatibility
|
||||
|
||||
/* Expected markdown structure:
|
||||
bla bla bla
|
||||
#
|
||||
%%
|
||||
# Excalidraw Data
|
||||
*/
|
||||
|
||||
//trimming the json because in legacy excalidraw files the JSON was a single string resulting in very slow regexp parsing
|
||||
const drawingTrimLocation = data.search(RE_DRAWING);
|
||||
if (drawingTrimLocation > 0) {
|
||||
data = data.substring(0, drawingTrimLocation);
|
||||
}
|
||||
|
||||
const m1 = data.match(RE_EXCALIDRAWDATA_WITHSECTION_OK);
|
||||
let trimLocation = m1?.index ?? -1; //data.search(RE_EXCALIDRAWDATA_WITHSECTION_OK);
|
||||
let shouldFixTrailingHashtag = false;
|
||||
if (trimLocation > 0) {
|
||||
trimLocation += m1[1].length; //accounts for the "(#\n\s*)" which I want to leave there untouched
|
||||
}
|
||||
|
||||
/* Expected markdown structure (this happens when the user deletes the last empty line of the last back-of-the-card note):
|
||||
bla bla bla#
|
||||
%%
|
||||
# Excalidraw Data
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_EXCALIDRAWDATA_WITHSECTION_NOTOK);
|
||||
if (trimLocation > 0) {
|
||||
shouldFixTrailingHashtag = true;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure
|
||||
a)
|
||||
bla bla bla
|
||||
%%
|
||||
# Excalidraw Data
|
||||
b)
|
||||
bla bla bla
|
||||
# Excalidraw Data
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_EXCALIDRAWDATA_NOSECTION_OK);
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla%%
|
||||
# Excalidraw Data
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
const res = data.match(RE_EXCALIDRAWDATA_FALLBACK_1);
|
||||
if (res && Boolean(res[1])) {
|
||||
trimLocation = res.index + res[1].length;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla# Excalidraw Data
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
const res = data.match(RE_EXCALIDRAWDATA_FALLBACK_2);
|
||||
if (res && Boolean(res[1])) {
|
||||
trimLocation = res.index + res[1].length;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla
|
||||
#
|
||||
%%
|
||||
# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_TEXTELEMENTS_WITHSECTION_OK);
|
||||
if (trimLocation > 0) {
|
||||
trimLocation += 2; //accounts for the "#\n" which I want to leave there untouched
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla#
|
||||
%%
|
||||
# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_TEXTELEMENTS_WITHSECTION_NOTOK);
|
||||
if (trimLocation > 0) {
|
||||
shouldFixTrailingHashtag = true;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure
|
||||
a)
|
||||
bla bla bla
|
||||
%%
|
||||
# Text Elements
|
||||
b)
|
||||
bla bla bla
|
||||
# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_TEXTELEMENTS_NOSECTION_OK);
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla%%
|
||||
# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
const res = data.match(RE_TEXTELEMENTS_FALLBACK_1);
|
||||
if (res && Boolean(res[1])) {
|
||||
trimLocation = res.index + res[1].length;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
const res = data.match(RE_TEXTELEMENTS_FALLBACK_2);
|
||||
if (res && Boolean(res[1])) {
|
||||
trimLocation = res.index + res[1].length;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
a)
|
||||
bla bla bla
|
||||
# Drawing
|
||||
b)
|
||||
bla bla bla
|
||||
%%
|
||||
# Drawing
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
if (drawingTrimLocation > 0) {
|
||||
trimLocation = drawingTrimLocation;
|
||||
}
|
||||
}
|
||||
if (trimLocation === -1) {
|
||||
return {
|
||||
header: data.endsWith("\n") ? data : `${data}\n`,
|
||||
shouldFixTrailingHashtag,
|
||||
processingOk: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
header: data.substring(0, trimLocation),
|
||||
shouldFixTrailingHashtag,
|
||||
processingOk: true,
|
||||
};
|
||||
}
|
||||
|
||||
export const getExcalidrawMarkdownHeaderSection = (
|
||||
data: string,
|
||||
keys?: [string, string][],
|
||||
): string => {
|
||||
const { header, shouldFixTrailingHashtag, processingOk } =
|
||||
getExcalidrawMarkdownHeader(data);
|
||||
if (!processingOk) {
|
||||
return header;
|
||||
}
|
||||
|
||||
const updatedHeader = updateFrontmatterInString(header, keys);
|
||||
//this should be removed at a later time. Left it here to remediate 1.4.9 mistake
|
||||
/*const REG_IMG = /(^---[\w\W]*?---\n)(!\[\[.*?]]\n(%%\n)?)/m; //(%%\n)? because of 1.4.8-beta... to be backward compatible with anyone who installed that version
|
||||
if (header.match(REG_IMG)) {
|
||||
header = header.replace(REG_IMG, "$1");
|
||||
}*/
|
||||
//end of remove
|
||||
return shouldFixTrailingHashtag
|
||||
? `${updatedHeader}\n#\n`
|
||||
: updatedHeader.endsWith("\n")
|
||||
? header
|
||||
: `${header}\n`;
|
||||
};
|
||||
|
||||
export type EquationItem = { latex: string; isLoaded: boolean };
|
||||
export type MermaidItem = { mermaid: string; isLoaded: boolean };
|
||||
|
||||
@@ -664,7 +254,8 @@ export class ExcalidrawData {
|
||||
public scene: ExcalidrawDataScene = null;
|
||||
public deletedElements: ExcalidrawElement[] = [];
|
||||
public file: TFile = null;
|
||||
private app: App;
|
||||
//public: read by EmbeddedDataRegistries via its constructor-injected host reference
|
||||
public app: App;
|
||||
private showLinkBrackets: boolean;
|
||||
private linkPrefix: string;
|
||||
public embeddableTheme: "light" | "dark" | "auto" | "default" = "auto";
|
||||
@@ -676,14 +267,17 @@ export class ExcalidrawData {
|
||||
public elementLinks: Map<string, string> = null;
|
||||
public files: Map<FileId, EmbeddedFile> = null; //fileId, path
|
||||
public markdownImages: Map<FileId, MarkdownImageData> = null;
|
||||
private equations: Map<FileId, EquationItem> = null; //fileId, path
|
||||
private mermaids: Map<FileId, MermaidItem> = null; //fileId, path
|
||||
//public: read by EmbeddedDataRegistries via its constructor-injected host reference
|
||||
public equations: Map<FileId, EquationItem> = null; //fileId, path
|
||||
public mermaids: Map<FileId, MermaidItem> = null; //fileId, path
|
||||
private compatibilityMode: boolean = false;
|
||||
private textElementCommentedOut: boolean = false;
|
||||
selectedElementIds: { [key: string]: boolean } = {}; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/609
|
||||
private embeddedDataRegistries: EmbeddedDataRegistries;
|
||||
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
//public: read by EmbeddedDataRegistries via its constructor-injected host reference
|
||||
public plugin: ExcalidrawPlugin,
|
||||
private view?: ExcalidrawView,
|
||||
) {
|
||||
this.app = this.plugin.app;
|
||||
@@ -691,6 +285,7 @@ export class ExcalidrawData {
|
||||
this.markdownImages = new Map<FileId, MarkdownImageData>();
|
||||
this.equations = new Map<FileId, EquationItem>();
|
||||
this.mermaids = new Map<FileId, MermaidItem>();
|
||||
this.embeddedDataRegistries = new EmbeddedDataRegistries(this, EmbeddedFile);
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
@@ -707,6 +302,7 @@ export class ExcalidrawData {
|
||||
this.textMode = null;
|
||||
this.loaded = false;
|
||||
this.elementLinks = null;
|
||||
this.embeddedDataRegistries = null;
|
||||
this.files = null;
|
||||
this.markdownImages = null;
|
||||
this.equations = null;
|
||||
@@ -1030,8 +626,7 @@ export class ExcalidrawData {
|
||||
(el: ExcalidrawElement): el is NonDeletedExcalidrawElement =>
|
||||
!el.isDeleted,
|
||||
);
|
||||
this.scene.elements =
|
||||
nonDeletedSceneElements as Mutable<ExcalidrawElement>[];
|
||||
this.scene.elements = nonDeletedSceneElements;
|
||||
|
||||
//once off migration of legacy scenes
|
||||
if (
|
||||
@@ -1076,7 +671,7 @@ export class ExcalidrawData {
|
||||
this.plugin,
|
||||
this.file,
|
||||
"light",
|
||||
);
|
||||
) as Theme;
|
||||
} else if (this.plugin.settings.matchThemeAlways) {
|
||||
this.scene.appState.theme = isObsidianThemeDark() ? "dark" : "light";
|
||||
}
|
||||
@@ -1155,14 +750,24 @@ export class ExcalidrawData {
|
||||
/^((%%\n*)?# Excalidraw Data\n\n?## Text Elements(?:\n|$))/m,
|
||||
) ?? data.match(/^((%%\n*)?##? Text Elements(?:\n|$))/m);
|
||||
|
||||
// "# Excalidraw Data" (or equivalent) was found above, so `position` was
|
||||
// not -1 and we got here, but there may be no "## Text Elements" heading
|
||||
// anywhere in the remaining data (e.g. a hand-authored or externally
|
||||
// generated file with zero text elements, or one where the heading was
|
||||
// deleted while "## Element Links" / "## Embedded Files" / the block-ref
|
||||
// text below it were left in place). Falling back to "" instead of
|
||||
// throwing on a null match lets execution fall through to the existing
|
||||
// Element Links / Embedded Files / text-element parsing below, exactly as
|
||||
// happens today for a file with an empty "## Text Elements" section.
|
||||
// https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2871
|
||||
const textElementsMatch = normalMatch
|
||||
? normalMatch[0]
|
||||
: data.match(/(.*##? Text Elements(?:\n|$))/m)[0];
|
||||
: (data.match(/(.*##? Text Elements(?:\n|$))/m)?.[0] ?? "");
|
||||
|
||||
data = data.slice(textElementsMatch.length);
|
||||
this.textElementCommentedOut = textElementsMatch.startsWith("%%\n");
|
||||
position = 0;
|
||||
let parts;
|
||||
let parts: RegExpMatchIteratorResult;
|
||||
|
||||
//load element links
|
||||
const elementLinkMap = new Map<string, string>();
|
||||
@@ -1530,7 +1135,7 @@ export class ExcalidrawData {
|
||||
//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) {
|
||||
this.textElements.delete(key); //if no longer in the scene, delete the text element
|
||||
} else {
|
||||
@@ -1607,7 +1212,7 @@ export class ExcalidrawData {
|
||||
const res = REGEX_LINK.getRes(text);
|
||||
let linkIcon = false;
|
||||
let urlIcon = false;
|
||||
let parts;
|
||||
let parts: RegExpMatchIteratorResult;
|
||||
if (text.match(REG_LINKINDEX_HYPERLINK)) {
|
||||
link = text;
|
||||
urlIcon = true;
|
||||
@@ -1709,7 +1314,7 @@ export class ExcalidrawData {
|
||||
private quickParse(text: string): [string, string] {
|
||||
const hasTransclusion = (text: string): boolean => {
|
||||
const res = REGEX_LINK.getRes(text);
|
||||
let parts;
|
||||
let parts: RegExpMatchIteratorResult;
|
||||
while (!(parts = res.next()).done) {
|
||||
if (REGEX_LINK.isTransclusion(parts)) {
|
||||
return true;
|
||||
@@ -1727,7 +1332,7 @@ export class ExcalidrawData {
|
||||
const res = REGEX_LINK.getRes(text);
|
||||
let linkIcon = false;
|
||||
let urlIcon = false;
|
||||
let parts;
|
||||
let parts: RegExpMatchIteratorResult;
|
||||
if (text.match(REG_LINKINDEX_HYPERLINK)) {
|
||||
link = text;
|
||||
urlIcon = true;
|
||||
@@ -1783,7 +1388,7 @@ export class ExcalidrawData {
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/566
|
||||
const element = this.scene.elements.filter(
|
||||
(el: ExcalidrawElement) => el.id === key,
|
||||
);
|
||||
) as Mutable<ExcalidrawTextElement>[];
|
||||
const elementString = this.textElements.get(key).raw;
|
||||
if (
|
||||
element &&
|
||||
@@ -2462,105 +2067,28 @@ export class ExcalidrawData {
|
||||
this is going to do the job
|
||||
*/
|
||||
public setFile(fileId: FileId, data: EmbeddedFile) {
|
||||
//always store absolute path because in case of paste, relative path may not resolve ok
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
this.files.set(fileId, data);
|
||||
|
||||
if (data.isHyperLink || data.isLocalLink) {
|
||||
this.plugin.filesMaster.set(fileId, {
|
||||
isHyperLink: data.isHyperLink,
|
||||
isLocalLink: data.isLocalLink,
|
||||
path: data.hyperlink,
|
||||
blockrefData: null,
|
||||
hasSVGwithBitmap: data.isSVGwithBitmap,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data.file) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parts = data.linkParts.original.split("#");
|
||||
this.plugin.filesMaster.set(fileId, {
|
||||
isHyperLink: false,
|
||||
isLocalLink: false,
|
||||
path: data.file.path + (data.shouldScale() ? "" : "|100%"),
|
||||
blockrefData: parts.length === 1 ? null : parts[1],
|
||||
hasSVGwithBitmap: data.isSVGwithBitmap,
|
||||
colorMapJSON: data.colorMap ? JSON.stringify(data.colorMap) : null,
|
||||
});
|
||||
this.embeddedDataRegistries.setFile(fileId, data);
|
||||
}
|
||||
|
||||
public getFiles(): EmbeddedFile[] {
|
||||
return Object.values(this.files);
|
||||
return this.embeddedDataRegistries.getFiles();
|
||||
}
|
||||
|
||||
public getFile(fileId: FileId): EmbeddedFile {
|
||||
let embeddedFile = this.files.get(fileId);
|
||||
if (embeddedFile) {
|
||||
return embeddedFile;
|
||||
}
|
||||
const masterFile = this.plugin.filesMaster.get(fileId);
|
||||
if (!masterFile) {
|
||||
return embeddedFile;
|
||||
}
|
||||
embeddedFile = new EmbeddedFile(
|
||||
this.plugin,
|
||||
this.file.path,
|
||||
masterFile.blockrefData
|
||||
? `${masterFile.path}#${masterFile.blockrefData}`
|
||||
: masterFile.path,
|
||||
masterFile.colorMapJSON,
|
||||
);
|
||||
this.files.set(fileId, embeddedFile);
|
||||
return embeddedFile;
|
||||
return this.embeddedDataRegistries.getFile(fileId);
|
||||
}
|
||||
|
||||
public getFileEntries() {
|
||||
return this.files.entries();
|
||||
return this.embeddedDataRegistries.getFileEntries();
|
||||
}
|
||||
|
||||
public deleteFile(fileId: FileId) {
|
||||
this.files.delete(fileId);
|
||||
//deliberately not deleting from plugin.filesMaster
|
||||
//could be present in other drawings as well
|
||||
this.embeddedDataRegistries.deleteFile(fileId);
|
||||
}
|
||||
|
||||
//Image copy/paste support
|
||||
public hasFile(fileId: FileId): boolean {
|
||||
if (this.files.has(fileId)) {
|
||||
return true;
|
||||
}
|
||||
if (this.plugin.filesMaster.has(fileId)) {
|
||||
const masterFile = this.plugin.filesMaster.get(fileId);
|
||||
if (masterFile.isHyperLink || masterFile.isLocalLink) {
|
||||
this.files.set(
|
||||
fileId,
|
||||
new EmbeddedFile(this.plugin, this.file.path, masterFile.path),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
const path = masterFile.path.split("|")[0].split("#")[0];
|
||||
if (!this.app.vault.getAbstractFileByPath(path)) {
|
||||
this.plugin.filesMaster.delete(fileId);
|
||||
return true;
|
||||
} // the file no longer exists
|
||||
const fixScale = masterFile.path.endsWith("100%");
|
||||
const embeddedFile = new EmbeddedFile(
|
||||
this.plugin,
|
||||
this.file.path,
|
||||
(masterFile.blockrefData
|
||||
? `${path}#${masterFile.blockrefData}`
|
||||
: path) + (fixScale ? "|100%" : ""),
|
||||
masterFile.colorMapJSON,
|
||||
);
|
||||
this.files.set(fileId, embeddedFile);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return this.embeddedDataRegistries.hasFile(fileId);
|
||||
}
|
||||
|
||||
//--------------
|
||||
@@ -2570,46 +2098,24 @@ export class ExcalidrawData {
|
||||
fileId: FileId,
|
||||
data: { latex: string; isLoaded: boolean },
|
||||
) {
|
||||
this.equations.set(fileId, { latex: data.latex, isLoaded: data.isLoaded });
|
||||
this.plugin.equationsMaster.set(fileId, data.latex);
|
||||
this.embeddedDataRegistries.setEquation(fileId, data);
|
||||
}
|
||||
|
||||
public getEquation(fileId: FileId): { latex: string; isLoaded: boolean } {
|
||||
const result = this.equations.get(fileId);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
const latex = this.plugin.equationsMaster.get(fileId);
|
||||
if (!latex) {
|
||||
return result;
|
||||
}
|
||||
this.equations.set(fileId, { latex, isLoaded: false });
|
||||
return { latex, isLoaded: false };
|
||||
return this.embeddedDataRegistries.getEquation(fileId);
|
||||
}
|
||||
|
||||
public getEquationEntries() {
|
||||
return this.equations?.entries();
|
||||
return this.embeddedDataRegistries.getEquationEntries();
|
||||
}
|
||||
|
||||
public deleteEquation(fileId: FileId) {
|
||||
this.equations.delete(fileId);
|
||||
//deliberately not deleting from plugin.equationsMaster
|
||||
//could be present in other drawings as well
|
||||
this.embeddedDataRegistries.deleteEquation(fileId);
|
||||
}
|
||||
|
||||
//Image copy/paste support
|
||||
public hasEquation(fileId: FileId): boolean {
|
||||
if (this.equations.has(fileId)) {
|
||||
return true;
|
||||
}
|
||||
if (this.plugin.equationsMaster.has(fileId)) {
|
||||
this.equations.set(fileId, {
|
||||
latex: this.plugin.equationsMaster.get(fileId),
|
||||
isLoaded: false,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return this.embeddedDataRegistries.hasEquation(fileId);
|
||||
}
|
||||
|
||||
//--------------
|
||||
@@ -2618,41 +2124,22 @@ export class ExcalidrawData {
|
||||
|
||||
/** Stores a local Markdown-image source and makes it available for intra-vault copy/paste. */
|
||||
public setMarkdownImage(fileId: FileId, data: MarkdownImageData): void {
|
||||
if (!data) {
|
||||
return;
|
||||
}
|
||||
const value = { markdown: data.markdown ?? "" };
|
||||
this.markdownImages.set(fileId, value);
|
||||
this.plugin.markdownImagesMaster.set(fileId, value);
|
||||
this.embeddedDataRegistries.setMarkdownImage(fileId, data);
|
||||
}
|
||||
|
||||
/** Returns local Markdown, restoring it from the intra-vault copy master. */
|
||||
public getMarkdownImage(fileId: FileId): MarkdownImageData | undefined {
|
||||
const local = this.markdownImages.get(fileId);
|
||||
if (local) {
|
||||
return local;
|
||||
}
|
||||
const master = this.plugin.markdownImagesMaster.get(fileId);
|
||||
if (master) {
|
||||
const value = { ...master };
|
||||
this.markdownImages.set(fileId, value);
|
||||
return value;
|
||||
}
|
||||
return undefined;
|
||||
return this.embeddedDataRegistries.getMarkdownImage(fileId);
|
||||
}
|
||||
|
||||
/** Returns whether local Markdown exists, restoring intra-vault clipboard data. */
|
||||
public hasMarkdownImage(fileId: FileId): boolean {
|
||||
return Boolean(this.getMarkdownImage(fileId));
|
||||
return this.embeddedDataRegistries.hasMarkdownImage(fileId);
|
||||
}
|
||||
|
||||
/** Removes a local source, optionally discarding its clipboard master entry. */
|
||||
public deleteMarkdownImage(fileId: FileId, clearMaster = false): void {
|
||||
this.markdownImages.delete(fileId);
|
||||
if (clearMaster) {
|
||||
this.plugin.markdownImagesMaster.delete(fileId);
|
||||
}
|
||||
// Normally retain the master entry for copies already on the clipboard.
|
||||
this.embeddedDataRegistries.deleteMarkdownImage(fileId, clearMaster);
|
||||
}
|
||||
|
||||
//--------------
|
||||
@@ -2662,49 +2149,24 @@ export class ExcalidrawData {
|
||||
fileId: FileId,
|
||||
data: { mermaid: string; isLoaded: boolean },
|
||||
) {
|
||||
this.mermaids.set(fileId, {
|
||||
mermaid: data.mermaid,
|
||||
isLoaded: data.isLoaded,
|
||||
});
|
||||
this.plugin.mermaidsMaster.set(fileId, data.mermaid);
|
||||
this.embeddedDataRegistries.setMermaid(fileId, data);
|
||||
}
|
||||
|
||||
public getMermaid(fileId: FileId): { mermaid: string; isLoaded: boolean } {
|
||||
const result = this.mermaids.get(fileId);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
const mermaid = this.plugin.mermaidsMaster.get(fileId);
|
||||
if (!mermaid) {
|
||||
return result;
|
||||
}
|
||||
this.mermaids.set(fileId, { mermaid, isLoaded: false });
|
||||
return { mermaid, isLoaded: false };
|
||||
return this.embeddedDataRegistries.getMermaid(fileId);
|
||||
}
|
||||
|
||||
public getMermaidEntries() {
|
||||
return this.mermaids.entries();
|
||||
return this.embeddedDataRegistries.getMermaidEntries();
|
||||
}
|
||||
|
||||
public deleteMermaid(fileId: FileId) {
|
||||
this.mermaids.delete(fileId);
|
||||
//deliberately not deleting from plugin.mermaidsMaster
|
||||
//could be present in other drawings as well
|
||||
this.embeddedDataRegistries.deleteMermaid(fileId);
|
||||
}
|
||||
|
||||
//Image copy/paste support
|
||||
public hasMermaid(fileId: FileId): boolean {
|
||||
if (this.mermaids.has(fileId)) {
|
||||
return true;
|
||||
}
|
||||
if (this.plugin.mermaidsMaster.has(fileId)) {
|
||||
this.mermaids.set(fileId, {
|
||||
mermaid: this.plugin.mermaidsMaster.get(fileId),
|
||||
isLoaded: false,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
return this.embeddedDataRegistries.hasMermaid(fileId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { App, Notice, TFile } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { PDFPageViewProps, Size } from "src/types/embeddedFileLoaderTypes";
|
||||
import { convertSVGStringToElement, errorlog } from "../utils/utils";
|
||||
@@ -218,9 +219,7 @@ class ImageCache {
|
||||
} finally {
|
||||
this.isInitializing = false;
|
||||
if (this.initializationNotice) {
|
||||
new Notice(
|
||||
"Excalidraw Image Cache is Initialized - You may now retry opening your damaged drawing.",
|
||||
);
|
||||
new Notice(t("IMAGE_CACHE_INITIALIZED"));
|
||||
this.initializationNotice = false;
|
||||
}
|
||||
log("Initialized Excalidraw Image Cache");
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ import type { ExcalidrawExtrasAPI } from "@zsviczian/excalidraw-extras-api";
|
||||
|
||||
export const updateEquation = async (
|
||||
equation: string,
|
||||
fileId: string,
|
||||
fileId: FileId,
|
||||
view: ExcalidrawView,
|
||||
addFiles: (files: FileData[], view: ExcalidrawView) => void,
|
||||
) => {
|
||||
|
||||
@@ -579,5 +579,14 @@ export async function updateMarkdownImage(
|
||||
return false;
|
||||
}
|
||||
view.setDirty();
|
||||
// Persist right after every successful render instead of only on specific UI events (switching
|
||||
// elements, closing the sidepanel, etc.). Those events are not reliable signals of "the user is
|
||||
// done": the sidepanel can be hidden/collapsed (no close event fires) or be a popout window that
|
||||
// is moved out of view, and none of that tells us whether the editor is still visible. Saving
|
||||
// here ties persistence directly to the one thing we know for certain changed: the element in
|
||||
// the scene. forceSave's waitIfBusy avoids silently no-oping against a concurrent save, and the
|
||||
// override bypasses the embeddableIsEditingSelf debounce without touching it, so this does not
|
||||
// disrupt the ongoing edit the way a reload()-driven refresh would.
|
||||
await view.forceSave(true, true);
|
||||
return true;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ExcalidrawAutomate } from "../ExcalidrawAutomate";
|
||||
import { Notice, requestUrl } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import FrontmatterEditor from "src/shared/Frontmatter";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
@@ -105,19 +106,13 @@ export default class Taskbone {
|
||||
)),
|
||||
);
|
||||
if (viewElements.length === 0) {
|
||||
new Notice(
|
||||
"Aborting OCR because there are no image or freedraw elements on the canvas.",
|
||||
4000,
|
||||
);
|
||||
new Notice(t("OCR_ABORT_NO_ELEMENTS"), 4000);
|
||||
ea.destroy();
|
||||
return;
|
||||
}
|
||||
const fe = new FrontmatterEditor(view.data);
|
||||
if (addToFrontmatter && fe.hasKey("taskbone-ocr") && !forceReScan) {
|
||||
new Notice(
|
||||
"The drawing has already been processed, you will find the result in the frontmatter in markdown view mode. If you ran the command from the Obsidian Panel in Excalidraw then you can CTRL(CMD)+click the command to force the rescaning.",
|
||||
4000,
|
||||
);
|
||||
new Notice(t("OCR_ALREADY_PROCESSED"), 4000);
|
||||
ea.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
+163
-2
@@ -32,6 +32,13 @@ export class ScriptEngine {
|
||||
//https://stackoverflow.com/questions/60218638/how-to-force-re-render-if-map-value-changes
|
||||
public scriptIconMap: ScriptIconMap;
|
||||
eaInstances = new WeakArray<ExcalidrawAutomate>();
|
||||
/**
|
||||
* Selected-element action-provider unregister callbacks registered via
|
||||
* `ExcalidrawAutomate.registerElementActionProvider()`, keyed by script
|
||||
* name. Cleared in `unloadScript()` so a deleted script's buttons don't
|
||||
* linger in views that are still open.
|
||||
*/
|
||||
private elementActionProviders = new Map<string, Set<() => void>>();
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.plugin = plugin;
|
||||
@@ -61,6 +68,7 @@ export class ScriptEngine {
|
||||
this.eaInstances.forEach((ea) => ea.destroy());
|
||||
this.eaInstances.clear();
|
||||
this.eaInstances = null;
|
||||
this.elementActionProviders.clear();
|
||||
this.scriptIconMap = null;
|
||||
this.plugin = null;
|
||||
this.scriptPath = null;
|
||||
@@ -86,7 +94,9 @@ export class ScriptEngine {
|
||||
if (!file.path.startsWith(this.scriptPath)) {
|
||||
return;
|
||||
}
|
||||
this.unloadScript(this.getScriptName(file), file.path);
|
||||
const scriptName = this.getScriptName(file);
|
||||
this.unloadScript(scriptName, file.path);
|
||||
await this.purgeAutostartPermission(scriptName);
|
||||
this.handleSvgFileChange(file.path);
|
||||
}
|
||||
|
||||
@@ -108,7 +118,9 @@ export class ScriptEngine {
|
||||
const oldFileIsScript = oldPath.startsWith(this.scriptPath);
|
||||
const newFileIsScript = file.path.startsWith(this.scriptPath);
|
||||
if (oldFileIsScript) {
|
||||
this.unloadScript(this.getScriptName(oldPath), oldPath);
|
||||
const oldScriptName = this.getScriptName(oldPath);
|
||||
this.unloadScript(oldScriptName, oldPath);
|
||||
await this.purgeAutostartPermission(oldScriptName);
|
||||
this.handleSvgFileChange(oldPath);
|
||||
}
|
||||
if (newFileIsScript) {
|
||||
@@ -254,6 +266,149 @@ export class ScriptEngine {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a cleanup callback for a selected-element action provider a
|
||||
* script registered via `ExcalidrawAutomate.registerElementActionProvider()`,
|
||||
* so it can be unregistered if the script's file is deleted while a view
|
||||
* using it is still open. Not needed for the ordinary view-close case,
|
||||
* which `SelectedElementActionsMenu.destroy()` already handles.
|
||||
*/
|
||||
public trackElementActionProvider(
|
||||
scriptName: string,
|
||||
unregister: () => void,
|
||||
): void {
|
||||
let providers = this.elementActionProviders.get(scriptName);
|
||||
if (!providers) {
|
||||
providers = new Set();
|
||||
this.elementActionProviders.set(scriptName, providers);
|
||||
}
|
||||
providers.add(unregister);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a script's entry from `settings.autostartScripts` and
|
||||
* `settings.autostartScriptFailures` when its file is deleted or renamed
|
||||
* away, so a stale allow/deny permission or failure flag does not linger
|
||||
* under a name that no longer resolves to any script file. A renamed
|
||||
* script starts fresh (prompts again) under its new name.
|
||||
*/
|
||||
private async purgeAutostartPermission(scriptName: string): Promise<void> {
|
||||
const hasPermission = scriptName in this.plugin.settings.autostartScripts;
|
||||
const hasFailureFlag =
|
||||
scriptName in this.plugin.settings.autostartScriptFailures;
|
||||
if (!hasPermission && !hasFailureFlag) {
|
||||
return;
|
||||
}
|
||||
delete this.plugin.settings.autostartScripts[scriptName];
|
||||
delete this.plugin.settings.autostartScriptFailures[scriptName];
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Records whether a script's most recent autostart run failed, so it can
|
||||
* be surfaced as a warning in the autostart settings/modal UI. Only
|
||||
* writes to disk when the flag actually changes (not on every autostart
|
||||
* run) to avoid a `saveSettings()` call every time an allow-listed
|
||||
* script runs. Purely informational: never touches `autostartScripts`
|
||||
* itself, so a failing script is never auto-removed from the allow
|
||||
* list - the user does that manually.
|
||||
*/
|
||||
private async recordAutostartResult(
|
||||
scriptName: string,
|
||||
failed: boolean,
|
||||
): Promise<void> {
|
||||
const failures = this.plugin.settings.autostartScriptFailures;
|
||||
if (Boolean(failures[scriptName]) === failed) {
|
||||
return;
|
||||
}
|
||||
if (failed) {
|
||||
failures[scriptName] = true;
|
||||
} else {
|
||||
delete failures[scriptName];
|
||||
}
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads and executes a single autostart-permitted script against a single
|
||||
* view, catching and logging its own error so one bad script never
|
||||
* affects the caller's other scripts/views. Shared by
|
||||
* `attachAutostartScriptToOpenViews()` and `runAutostartScripts()`.
|
||||
*/
|
||||
private async runAutostartScriptInView(
|
||||
scriptName: string,
|
||||
file: TFile,
|
||||
view: ExcalidrawView,
|
||||
where: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const script = stripYamlFrontmatter(await this.app.vault.read(file));
|
||||
if (script) {
|
||||
await this.executeScript(view, script, scriptName, file);
|
||||
}
|
||||
await this.recordAutostartResult(scriptName, false);
|
||||
} catch (error: unknown) {
|
||||
errorlog({ where, scriptName, error });
|
||||
await this.recordAutostartResult(scriptName, true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called by `ExcalidrawAutomate.registerAutostart()` right after a script
|
||||
* is freshly granted autostart permission, so the script attaches to
|
||||
* every other currently-open Excalidraw view immediately instead of only
|
||||
* the next time each view is opened. Reuses the same `executeScript()`
|
||||
* path `runAutostartScripts()` uses for newly-opened views; one script
|
||||
* failing does not affect the others.
|
||||
*/
|
||||
public attachAutostartScriptToOpenViews(
|
||||
scriptName: string,
|
||||
excludeView?: ExcalidrawView,
|
||||
): void {
|
||||
const file = this.getScriptFileByName(scriptName);
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
const views = getExcalidrawViews(this.app, true).filter(
|
||||
(view) => view !== excludeView,
|
||||
);
|
||||
views.forEach((view) => {
|
||||
void this.runAutostartScriptInView(
|
||||
scriptName,
|
||||
file,
|
||||
view,
|
||||
"ScriptEngine.attachAutostartScriptToOpenViews",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs every script the user has allow-listed for autostart (see
|
||||
* `ExcalidrawAutomate.registerAutostart()`) once against a newly-opened
|
||||
* view. Called from `ExcalidrawRoot.ts`'s mount effect, after the view's
|
||||
* `selectedElementActionsMenu` is ready. Fire-and-forget: does not block
|
||||
* initial render. Deliberately independent of the sidepanel autostart
|
||||
* feature (`Sidepanel.ts`, not touched) — different persisted field,
|
||||
* different trigger, different execution owner.
|
||||
*/
|
||||
public runAutostartScripts(view: ExcalidrawView): void {
|
||||
const autostartScripts = this.plugin.settings.autostartScripts;
|
||||
Object.keys(autostartScripts)
|
||||
.filter((scriptName) => autostartScripts[scriptName] === "allow")
|
||||
.forEach((scriptName) => {
|
||||
const file = this.getScriptFileByName(scriptName);
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
void this.runAutostartScriptInView(
|
||||
scriptName,
|
||||
file,
|
||||
view,
|
||||
"ScriptEngine.runAutostartScripts",
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
unloadScript(basename: string, path: string) {
|
||||
if (!path.endsWith(".md")) {
|
||||
return;
|
||||
@@ -262,6 +417,12 @@ export class ScriptEngine {
|
||||
this.scriptIconMap = { ...this.scriptIconMap };
|
||||
this.updateToolPannels();
|
||||
|
||||
const providers = this.elementActionProviders.get(basename);
|
||||
if (providers) {
|
||||
providers.forEach((unregister) => unregister());
|
||||
this.elementActionProviders.delete(basename);
|
||||
}
|
||||
|
||||
const commandId = `${PLUGIN_ID}:${basename}`;
|
||||
if (!this.app.commands.commands[commandId]) {
|
||||
return;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { App, FuzzyMatch, TFile } from "obsidian";
|
||||
import { SuggestionModal } from "./SuggestionModal";
|
||||
import { LinkSuggestion } from "src/types/types";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import {
|
||||
getLinkSuggestionsFiltered,
|
||||
getSortedLinkMatches,
|
||||
|
||||
@@ -0,0 +1,474 @@
|
||||
/**
|
||||
* Parsing helpers for the "## Drawing" scene section, the user-editable
|
||||
* Markdown header that precedes it, and the marker-delimited local
|
||||
* Markdown-image blocks stored inside that header. Extracted intact from
|
||||
* `ExcalidrawData.ts`, which remains the primary consumer alongside several
|
||||
* other modules that read or write the same Markdown structure.
|
||||
*/
|
||||
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import {
|
||||
compress,
|
||||
compressAsync,
|
||||
decompress,
|
||||
updateFrontmatterInString,
|
||||
} from "../utils/sceneDataUtils";
|
||||
import { isObsidianThemeDark } from "../utils/obsidianUtils";
|
||||
import { MD_MARKDOWN_IMAGES } from "../constants/constants";
|
||||
import { type MarkdownImageData } from "src/types/markdownImageTypes";
|
||||
|
||||
type RegExpMatchIteratorResult = IteratorResult<RegExpMatchArray, undefined>;
|
||||
|
||||
//added \n at and of DRAWING_REG: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/357
|
||||
const DRAWING_REG = /\n##? Drawing\n[^`]*(```json\n)([\s\S]*?)```\n/gm; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/182
|
||||
const DRAWING_REG_FALLBACK = /\n##? Drawing\n(```json\n)?(.*)(```)?(%%)?/gm;
|
||||
export const DRAWING_COMPRESSED_REG =
|
||||
/(\n##? Drawing\n[^`]*(?:```compressed-json\n))([\s\S]*?)(```\n)/gm; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/182
|
||||
const DRAWING_COMPRESSED_REG_FALLBACK =
|
||||
/(\n##? Drawing\n(?:```compressed-json\n)?)(.*)((```)?(%%)?)/gm;
|
||||
|
||||
const isCompressedMD = (data: string): boolean => {
|
||||
return data.match(/```compressed-json\n/gm) !== null;
|
||||
};
|
||||
|
||||
const getDecompressedScene = (
|
||||
data: string,
|
||||
): [string | null, RegExpMatchIteratorResult] => {
|
||||
let res = data.matchAll(DRAWING_COMPRESSED_REG);
|
||||
|
||||
//In case the user adds a text element with the contents "# Drawing\n"
|
||||
let parts: RegExpMatchIteratorResult;
|
||||
parts = res.next();
|
||||
if (parts.done) {
|
||||
//did not find a match
|
||||
res = data.matchAll(DRAWING_COMPRESSED_REG_FALLBACK);
|
||||
parts = res.next();
|
||||
}
|
||||
if (parts.value && parts.value.length > 1) {
|
||||
return [decompress(parts.value[2]), parts];
|
||||
}
|
||||
return [null, parts];
|
||||
};
|
||||
|
||||
export const changeThemeOfExcalidrawMD = (data: string): string => {
|
||||
const compressed = isCompressedMD(data);
|
||||
let scene = compressed ? getDecompressedScene(data)[0] : data;
|
||||
if (!scene) {
|
||||
return data;
|
||||
}
|
||||
if (isObsidianThemeDark) {
|
||||
if ((scene.match(/"theme"\s*:\s*"light"\s*,/g) || []).length === 1) {
|
||||
scene = scene.replace(/"theme"\s*:\s*"light"\s*,/, `"theme": "dark",`);
|
||||
}
|
||||
} else if ((scene.match(/"theme"\s*:\s*"dark"\s*,/g) || []).length === 1) {
|
||||
scene = scene.replace(/"theme"\s*:\s*"dark"\s*,/, `"theme": "light",`);
|
||||
}
|
||||
if (compressed) {
|
||||
return data.replace(DRAWING_COMPRESSED_REG, `$1${compress(scene)}$3`);
|
||||
}
|
||||
return scene;
|
||||
};
|
||||
|
||||
export function getJSON(data: string): { scene: string; pos: number } {
|
||||
let res: IterableIterator<RegExpMatchArray>;
|
||||
if (isCompressedMD(data)) {
|
||||
const [result, parts] = getDecompressedScene(data);
|
||||
if (result) {
|
||||
return {
|
||||
scene: result.substring(0, result.lastIndexOf("}") + 1),
|
||||
pos: parts.value.index,
|
||||
}; //this is a workaround in case sync merges two files together and one version is still an old version without the ```codeblock
|
||||
}
|
||||
return { scene: data, pos: parts.value ? parts.value.index : 0 };
|
||||
}
|
||||
res = data.matchAll(DRAWING_REG);
|
||||
|
||||
//In case the user adds a text element with the contents "# Drawing\n"
|
||||
let parts: RegExpMatchIteratorResult;
|
||||
parts = res.next();
|
||||
if (parts.done) {
|
||||
//did not find a match
|
||||
res = data.matchAll(DRAWING_REG_FALLBACK);
|
||||
parts = res.next();
|
||||
}
|
||||
if (parts.value && parts.value.length > 1) {
|
||||
const result = parts.value[2];
|
||||
return {
|
||||
scene: result.substring(0, result.lastIndexOf("}") + 1),
|
||||
pos: parts.value.index,
|
||||
}; //this is a workaround in case sync merges two files together and one version is still an old version without the ```codeblock
|
||||
}
|
||||
return { scene: data, pos: parts.value ? parts.value.index : 0 };
|
||||
}
|
||||
|
||||
export async function getMarkdownDrawingSectionAsync(
|
||||
jsonString: string,
|
||||
compressed: boolean,
|
||||
) {
|
||||
const result = compressed
|
||||
? `## Drawing\n\x60\x60\x60compressed-json\n${await compressAsync(
|
||||
jsonString,
|
||||
)}\n\x60\x60\x60\n%%`
|
||||
: `## Drawing\n\x60\x60\x60json\n${jsonString}\n\x60\x60\x60\n%%`;
|
||||
return result;
|
||||
}
|
||||
|
||||
export function getMarkdownDrawingSection(
|
||||
jsonString: string,
|
||||
compressed: boolean,
|
||||
): string {
|
||||
const result = compressed
|
||||
? `## Drawing\n\x60\x60\x60compressed-json\n${compress(
|
||||
jsonString,
|
||||
)}\n\x60\x60\x60\n%%`
|
||||
: `## Drawing\n\x60\x60\x60json\n${jsonString}\n\x60\x60\x60\n%%`;
|
||||
return result;
|
||||
}
|
||||
|
||||
const MARKDOWN_IMAGE_OPEN_MARKER =
|
||||
/^<!-- excalidraw-markdown-image:([\w-]+) -->$/gm;
|
||||
|
||||
type MarkdownImageBlock = {
|
||||
fileId: FileId;
|
||||
start: number;
|
||||
bodyStart: number;
|
||||
bodyEnd: number;
|
||||
end: number;
|
||||
};
|
||||
|
||||
const getMarkdownImageBlocks = (data: string): MarkdownImageBlock[] => {
|
||||
const blocks: MarkdownImageBlock[] = [];
|
||||
const openMarker = new RegExp(MARKDOWN_IMAGE_OPEN_MARKER);
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = openMarker.exec(data)) !== null) {
|
||||
const fileId = match[1] as FileId;
|
||||
const bodySeparator = data.startsWith("\r\n\r\n", openMarker.lastIndex)
|
||||
? "\r\n\r\n"
|
||||
: "\n\n";
|
||||
if (!data.startsWith(bodySeparator, openMarker.lastIndex)) {
|
||||
continue;
|
||||
}
|
||||
const closeMarker = `<!-- /excalidraw-markdown-image:${fileId} -->`;
|
||||
const closeIndex = data.indexOf(
|
||||
`${bodySeparator}${closeMarker}`,
|
||||
openMarker.lastIndex + bodySeparator.length,
|
||||
);
|
||||
if (closeIndex === -1) {
|
||||
continue;
|
||||
}
|
||||
const end = closeIndex + bodySeparator.length + closeMarker.length;
|
||||
blocks.push({
|
||||
fileId,
|
||||
start: match.index,
|
||||
bodyStart: openMarker.lastIndex + bodySeparator.length,
|
||||
bodyEnd: closeIndex,
|
||||
end,
|
||||
});
|
||||
openMarker.lastIndex = end;
|
||||
}
|
||||
return blocks;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads locally stored Markdown-image bodies from marker-delimited blocks.
|
||||
* Marker matching is deliberately independent of headings and block position.
|
||||
*/
|
||||
export function parseMarkdownImages(data: string): Map<FileId, MarkdownImageData> {
|
||||
const result = new Map<FileId, MarkdownImageData>();
|
||||
getMarkdownImageBlocks(data).forEach((block) =>
|
||||
result.set(block.fileId, {
|
||||
markdown: data.substring(block.bodyStart, block.bodyEnd),
|
||||
}),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a local Markdown-image block's marker comments while preserving its
|
||||
* Markdown body and surrounding document content exactly.
|
||||
*
|
||||
* @param data - Complete Excalidraw Markdown document.
|
||||
* @param fileId - File ID identifying the local Markdown-image block.
|
||||
* @param markdown - Optional current in-memory body to preserve instead of a
|
||||
* potentially stale body from the document.
|
||||
* @returns The document with the matching marker comments removed.
|
||||
*/
|
||||
export function unwrapMarkdownImageBlock(
|
||||
data: string,
|
||||
fileId: FileId,
|
||||
markdown?: string,
|
||||
): string {
|
||||
const blocks = getMarkdownImageBlocks(data).filter(
|
||||
(block) => block.fileId === fileId,
|
||||
);
|
||||
let updated = data;
|
||||
for (let index = blocks.length - 1; index >= 0; index--) {
|
||||
const block = blocks[index];
|
||||
updated =
|
||||
updated.slice(0, block.start) +
|
||||
(markdown ?? updated.slice(block.bodyStart, block.bodyEnd)) +
|
||||
updated.slice(block.end);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
const serializeMarkdownImageBlock = (
|
||||
fileId: FileId,
|
||||
markdown: string,
|
||||
): string =>
|
||||
`<!-- excalidraw-markdown-image:${fileId} -->\n\n${markdown}\n\n<!-- /excalidraw-markdown-image:${fileId} -->`;
|
||||
|
||||
/**
|
||||
* Synchronizes local Markdown-image bodies in the user-editable note header.
|
||||
* Existing blocks stay where the user placed them; only missing blocks receive
|
||||
* the default scaffolding immediately above Excalidraw Data.
|
||||
*/
|
||||
export function syncMarkdownImagesInHeader(
|
||||
header: string,
|
||||
markdownImages: ReadonlyMap<FileId, MarkdownImageData>,
|
||||
): string {
|
||||
const blocks = getMarkdownImageBlocks(header);
|
||||
const existingIds = new Set<FileId>();
|
||||
let updated = header;
|
||||
for (let index = blocks.length - 1; index >= 0; index--) {
|
||||
const block = blocks[index];
|
||||
const data = markdownImages.get(block.fileId);
|
||||
if (!data) {
|
||||
updated = updated.slice(0, block.start) + updated.slice(block.end);
|
||||
continue;
|
||||
}
|
||||
existingIds.add(block.fileId);
|
||||
updated =
|
||||
updated.slice(0, block.bodyStart) +
|
||||
data.markdown +
|
||||
updated.slice(block.bodyEnd);
|
||||
}
|
||||
|
||||
const missing = [...markdownImages.entries()].filter(
|
||||
([fileId]) => !existingIds.has(fileId),
|
||||
);
|
||||
if (missing.length > 0) {
|
||||
const hasExistingBlocks = getMarkdownImageBlocks(updated).length > 0;
|
||||
const hasScaffoldingHeading = updated
|
||||
.split(/\r?\n/)
|
||||
.some((line) => line.trimEnd() === MD_MARKDOWN_IMAGES);
|
||||
const blocksToAppend = missing
|
||||
.map(([fileId, data]) => serializeMarkdownImageBlock(fileId, data.markdown))
|
||||
.join("\n\n");
|
||||
updated = `${updated.replace(/\s*$/, "")}${
|
||||
hasExistingBlocks || hasScaffoldingHeading
|
||||
? "\n\n"
|
||||
: `\n\n${MD_MARKDOWN_IMAGES}\n\n`
|
||||
}${blocksToAppend}\n\n`;
|
||||
} else if (markdownImages.size === 0) {
|
||||
updated = updated.replace(
|
||||
new RegExp(`(?:^|\\n)${MD_MARKDOWN_IMAGES}[ \\t]*\\n*$`),
|
||||
"\n",
|
||||
);
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
//WITHSECTION refers to back of the card note (see this.inputEl.onkeyup in SelectCard.ts)
|
||||
const RE_EXCALIDRAWDATA_WITHSECTION_OK =
|
||||
/^(#\n+)%%\n+# Excalidraw Data(?:\n|$)/m;
|
||||
const RE_EXCALIDRAWDATA_WITHSECTION_NOTOK =
|
||||
/#\n+%%\n+# Excalidraw Data(?:\n|$)/m;
|
||||
// Also used directly by ExcalidrawData's own text-element-section detection.
|
||||
export const RE_EXCALIDRAWDATA_NOSECTION_OK =
|
||||
/^(%%\n+)?# Excalidraw Data(?:\n|$)/m;
|
||||
|
||||
//WITHSECTION refers to back of the card note (see this.inputEl.onkeyup in SelectCard.ts)
|
||||
const RE_TEXTELEMENTS_WITHSECTION_OK = /^#\n+%%\n+##? Text Elements(?:\n|$)/m;
|
||||
const RE_TEXTELEMENTS_WITHSECTION_NOTOK = /#\n+%%\n+##? Text Elements(?:\n|$)/m;
|
||||
// Also used directly by ExcalidrawData's own text-element-section detection.
|
||||
export const RE_TEXTELEMENTS_NOSECTION_OK =
|
||||
/^(%%\n+)?##? Text Elements(?:\n|$)/m;
|
||||
|
||||
//The issue is that when editing in markdown embeds the user can delete the last enter causing two sections
|
||||
//to collide. This is particularly problematic when the user is editing the last section before # Text Elements
|
||||
const RE_EXCALIDRAWDATA_FALLBACK_1 = /(.*)%%\n+# Excalidraw Data(?:\n|$)/m;
|
||||
// Also used directly by ExcalidrawData's own text-element-section detection.
|
||||
export const RE_EXCALIDRAWDATA_FALLBACK_2 = /(.*)# Excalidraw Data(?:\n|$)/m;
|
||||
|
||||
const RE_TEXTELEMENTS_FALLBACK_1 = /(.*)%%\n+##? Text Elements(?:\n|$)/m;
|
||||
// Also used directly by ExcalidrawData's own text-element-section detection.
|
||||
export const RE_TEXTELEMENTS_FALLBACK_2 = /(.*)##? Text Elements(?:\n|$)/m;
|
||||
|
||||
const RE_DRAWING = /^(%%\n+)?##? Drawing\n/m;
|
||||
|
||||
export function getExcalidrawMarkdownHeader(data: string): {
|
||||
header: string;
|
||||
shouldFixTrailingHashtag: boolean;
|
||||
processingOk: boolean;
|
||||
} {
|
||||
//The base case scenario is at the top, continued with fallbacks in order of likelihood and file structure
|
||||
//change history for sake of backward compatibility
|
||||
|
||||
/* Expected markdown structure:
|
||||
bla bla bla
|
||||
#
|
||||
%%
|
||||
# Excalidraw Data
|
||||
*/
|
||||
|
||||
//trimming the json because in legacy excalidraw files the JSON was a single string resulting in very slow regexp parsing
|
||||
const drawingTrimLocation = data.search(RE_DRAWING);
|
||||
if (drawingTrimLocation > 0) {
|
||||
data = data.substring(0, drawingTrimLocation);
|
||||
}
|
||||
|
||||
const m1 = data.match(RE_EXCALIDRAWDATA_WITHSECTION_OK);
|
||||
let trimLocation = m1?.index ?? -1; //data.search(RE_EXCALIDRAWDATA_WITHSECTION_OK);
|
||||
let shouldFixTrailingHashtag = false;
|
||||
if (trimLocation > 0) {
|
||||
trimLocation += m1[1].length; //accounts for the "(#\n\s*)" which I want to leave there untouched
|
||||
}
|
||||
|
||||
/* Expected markdown structure (this happens when the user deletes the last empty line of the last back-of-the-card note):
|
||||
bla bla bla#
|
||||
%%
|
||||
# Excalidraw Data
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_EXCALIDRAWDATA_WITHSECTION_NOTOK);
|
||||
if (trimLocation > 0) {
|
||||
shouldFixTrailingHashtag = true;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure
|
||||
a)
|
||||
bla bla bla
|
||||
%%
|
||||
# Excalidraw Data
|
||||
b)
|
||||
bla bla bla
|
||||
# Excalidraw Data
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_EXCALIDRAWDATA_NOSECTION_OK);
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla%%
|
||||
# Excalidraw Data
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
const res = data.match(RE_EXCALIDRAWDATA_FALLBACK_1);
|
||||
if (res && Boolean(res[1])) {
|
||||
trimLocation = res.index + res[1].length;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla# Excalidraw Data
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
const res = data.match(RE_EXCALIDRAWDATA_FALLBACK_2);
|
||||
if (res && Boolean(res[1])) {
|
||||
trimLocation = res.index + res[1].length;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla
|
||||
#
|
||||
%%
|
||||
# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_TEXTELEMENTS_WITHSECTION_OK);
|
||||
if (trimLocation > 0) {
|
||||
trimLocation += 2; //accounts for the "#\n" which I want to leave there untouched
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla#
|
||||
%%
|
||||
# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_TEXTELEMENTS_WITHSECTION_NOTOK);
|
||||
if (trimLocation > 0) {
|
||||
shouldFixTrailingHashtag = true;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure
|
||||
a)
|
||||
bla bla bla
|
||||
%%
|
||||
# Text Elements
|
||||
b)
|
||||
bla bla bla
|
||||
# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
trimLocation = data.search(RE_TEXTELEMENTS_NOSECTION_OK);
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla%%
|
||||
# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
const res = data.match(RE_TEXTELEMENTS_FALLBACK_1);
|
||||
if (res && Boolean(res[1])) {
|
||||
trimLocation = res.index + res[1].length;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
bla bla bla# Text Elements
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
const res = data.match(RE_TEXTELEMENTS_FALLBACK_2);
|
||||
if (res && Boolean(res[1])) {
|
||||
trimLocation = res.index + res[1].length;
|
||||
}
|
||||
}
|
||||
/* Expected markdown structure:
|
||||
a)
|
||||
bla bla bla
|
||||
# Drawing
|
||||
b)
|
||||
bla bla bla
|
||||
%%
|
||||
# Drawing
|
||||
*/
|
||||
if (trimLocation === -1) {
|
||||
if (drawingTrimLocation > 0) {
|
||||
trimLocation = drawingTrimLocation;
|
||||
}
|
||||
}
|
||||
if (trimLocation === -1) {
|
||||
return {
|
||||
header: data.endsWith("\n") ? data : `${data}\n`,
|
||||
shouldFixTrailingHashtag,
|
||||
processingOk: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
header: data.substring(0, trimLocation),
|
||||
shouldFixTrailingHashtag,
|
||||
processingOk: true,
|
||||
};
|
||||
}
|
||||
|
||||
export const getExcalidrawMarkdownHeaderSection = (
|
||||
data: string,
|
||||
keys?: [string, string][],
|
||||
): string => {
|
||||
const { header, shouldFixTrailingHashtag, processingOk } =
|
||||
getExcalidrawMarkdownHeader(data);
|
||||
if (!processingOk) {
|
||||
return header;
|
||||
}
|
||||
|
||||
const updatedHeader = updateFrontmatterInString(header, keys);
|
||||
//this should be removed at a later time. Left it here to remediate 1.4.9 mistake
|
||||
/*const REG_IMG = /(^---[\w\W]*?---\n)(!\[\[.*?]]\n(%%\n)?)/m; //(%%\n)? because of 1.4.8-beta... to be backward compatible with anyone who installed that version
|
||||
if (header.match(REG_IMG)) {
|
||||
header = header.replace(REG_IMG, "$1");
|
||||
}*/
|
||||
//end of remove
|
||||
return shouldFixTrailingHashtag
|
||||
? `${updatedHeader}\n#\n`
|
||||
: updatedHeader.endsWith("\n")
|
||||
? header
|
||||
: `${header}\n`;
|
||||
};
|
||||
@@ -1,71 +1,54 @@
|
||||
import { randomId, randomInteger } from "../utils";
|
||||
|
||||
import {
|
||||
ExcalidrawLinearElement,
|
||||
FillStyle,
|
||||
GroupId,
|
||||
RoundnessType,
|
||||
StrokeStyle,
|
||||
import type {
|
||||
ExcalidrawEllipseElement,
|
||||
ExcalidrawLineElement,
|
||||
ExcalidrawRectangleElement,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import type { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import type { LocalPoint } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
import type { Radians } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
|
||||
/** Internal, unbranded working point used by every geometry helper in this
|
||||
* module (bezier/ellipse/path math, matrix transforms). Only converted to
|
||||
* the real fork's branded `LocalPoint` at the point an element is finalized
|
||||
* -- see `toLocalPoint()`. */
|
||||
export type Point = [number, number];
|
||||
|
||||
export type ExcalidrawElementBase = {
|
||||
id: string;
|
||||
x: number;
|
||||
y: number;
|
||||
strokeColor: string;
|
||||
backgroundColor: string;
|
||||
fillStyle: FillStyle;
|
||||
strokeWidth: number;
|
||||
strokeStyle: StrokeStyle;
|
||||
roundness: null | { type: RoundnessType; value?: number };
|
||||
roughness: number;
|
||||
opacity: number;
|
||||
width: number;
|
||||
height: number;
|
||||
angle: number;
|
||||
/** Random integer used to seed shape generation so that the roughjs shape
|
||||
doesn't differ across renders. */
|
||||
seed: number;
|
||||
/** Integer that is sequentially incremented on each change. Used to reconcile
|
||||
elements during collaboration or when saving to server. */
|
||||
version: number;
|
||||
/** Random integer that is regenerated on each change.
|
||||
Used for deterministic reconciliation of updates during collaboration,
|
||||
in case the versions (see above) are identical. */
|
||||
versionNonce: number;
|
||||
isDeleted: boolean;
|
||||
/** List of groups the element belongs to.
|
||||
Ordered from deepest to shallowest. */
|
||||
groupIds: GroupId[];
|
||||
/** Ids of (linear) elements that are bound to this element. */
|
||||
boundElementIds: ExcalidrawLinearElement["id"][] | null;
|
||||
};
|
||||
/**
|
||||
* Mutable local copy of the fork's element base shape. The real
|
||||
* `_ExcalidrawElementBase` type is `Readonly` and not exported on its own,
|
||||
* so this is derived via `Omit` from `ExcalidrawRectangleElement` (which
|
||||
* adds nothing beyond the `type` discriminant over the real base) rather
|
||||
* than hand-duplicating every field -- field types can't drift from the
|
||||
* real ones this way. `Mutable` strips the `readonly` modifiers so the
|
||||
* existing object-literal-mutation style in attributes.ts keeps working.
|
||||
*/
|
||||
export type ExcalidrawElementBase = Mutable<
|
||||
Omit<ExcalidrawRectangleElement, "type">
|
||||
>;
|
||||
|
||||
export type ExcalidrawRectangle = ExcalidrawElementBase & {
|
||||
type: "rectangle";
|
||||
};
|
||||
export type ExcalidrawRectangle = Mutable<ExcalidrawRectangleElement>;
|
||||
|
||||
export type ExcalidrawLine = ExcalidrawElementBase & {
|
||||
type: "line";
|
||||
points: readonly Point[];
|
||||
};
|
||||
export type ExcalidrawEllipse = Mutable<ExcalidrawEllipseElement>;
|
||||
|
||||
export type ExcalidrawEllipse = ExcalidrawElementBase & {
|
||||
type: "ellipse";
|
||||
};
|
||||
export type ExcalidrawLine = Mutable<ExcalidrawLineElement>;
|
||||
|
||||
export type ExcalidrawGenericElement =
|
||||
| ExcalidrawRectangle
|
||||
| ExcalidrawEllipse
|
||||
| ExcalidrawLine
|
||||
| ExcalidrawDraw;
|
||||
| ExcalidrawLine;
|
||||
|
||||
export type ExcalidrawDraw = ExcalidrawElementBase & {
|
||||
type: "line";
|
||||
points: readonly Point[];
|
||||
};
|
||||
/**
|
||||
* Reimplements the fork's `pointFrom<LocalPoint>(x, y)` locally instead of
|
||||
* importing it: at runtime that function is just `[x, y] as Point` (a pure
|
||||
* compile-time brand, verified against packages/math/src/point.ts in the
|
||||
* fork), and this plugin never imports runtime Excalidraw code directly --
|
||||
* the actual runtime is loaded separately per-window via `PackageManager`/
|
||||
* `window.ExcalidrawLib`. Importing it here would statically bundle a
|
||||
* second copy of fork code into the plugin build.
|
||||
*/
|
||||
const toLocalPoint = ([x, y]: Point): LocalPoint => [x, y] as LocalPoint;
|
||||
|
||||
export function createExElement(): ExcalidrawElementBase {
|
||||
return {
|
||||
@@ -82,13 +65,20 @@ export function createExElement(): ExcalidrawElementBase {
|
||||
opacity: 100,
|
||||
width: 0,
|
||||
height: 0,
|
||||
angle: 0,
|
||||
angle: 0 as Radians,
|
||||
seed: randomInteger(),
|
||||
version: 0,
|
||||
versionNonce: 0,
|
||||
isDeleted: false,
|
||||
groupIds: [],
|
||||
boundElementIds: null,
|
||||
// The following match the real fork's own newElement() defaults for a
|
||||
// freshly created, not-yet-in-scene element (packages/element/src/newElement.ts).
|
||||
frameId: null,
|
||||
index: null,
|
||||
boundElements: null,
|
||||
updated: Date.now(),
|
||||
link: null,
|
||||
locked: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -99,14 +89,6 @@ export function createExRect(): ExcalidrawRectangle {
|
||||
};
|
||||
}
|
||||
|
||||
export function createExLine(): ExcalidrawLine {
|
||||
return {
|
||||
...createExElement(),
|
||||
type: "line",
|
||||
points: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function createExEllipse(): ExcalidrawEllipse {
|
||||
return {
|
||||
...createExElement(),
|
||||
@@ -114,10 +96,18 @@ export function createExEllipse(): ExcalidrawEllipse {
|
||||
};
|
||||
}
|
||||
|
||||
export function createExDraw(): ExcalidrawDraw {
|
||||
/** SVG shapes converted to a "line" element are always closed, fillable
|
||||
* regions (the polygon feature didn't exist yet when this module was
|
||||
* written; every caller wants `polygon: true`). */
|
||||
export function createExLine(points: readonly Point[] = []): ExcalidrawLine {
|
||||
return {
|
||||
...createExElement(),
|
||||
type: "line",
|
||||
points: [],
|
||||
polygon: true,
|
||||
points: points.map(toLocalPoint),
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
startArrowhead: null,
|
||||
endArrowhead: null,
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { randomId } from "../utils";
|
||||
import { presAttrsToElementValues } from "../attributes";
|
||||
import { ExcalidrawElementBase } from "../elements/ExcalidrawElement";
|
||||
|
||||
export function getGroupAttrs(groups: Group[]): Record<string, unknown> {
|
||||
export function getGroupAttrs(groups: Group[]): Partial<ExcalidrawElementBase> {
|
||||
return groups.reduce((acc, { element }) => {
|
||||
const elVals = presAttrsToElementValues(element);
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import * as path from "./path";
|
||||
|
||||
export default {
|
||||
path,
|
||||
};
|
||||
@@ -1,35 +0,0 @@
|
||||
import { RawElement } from "../../types";
|
||||
import { getElementBoundaries } from "../utils";
|
||||
import pathToPoints from "./utils/path-to-points";
|
||||
|
||||
const parse = (node: Element) => {
|
||||
const data = node.getAttribute("d");
|
||||
const backgroundColor = node.getAttribute("fill");
|
||||
const strokeColor = node.getAttribute("stroke");
|
||||
|
||||
return {
|
||||
data: data || "",
|
||||
backgroundColor:
|
||||
(backgroundColor !== "currentColor" && backgroundColor) || "transparent",
|
||||
strokeColor: (strokeColor !== "currentColor" && strokeColor) || "#000000",
|
||||
};
|
||||
};
|
||||
|
||||
export const convert = (node: Element): RawElement[] => {
|
||||
const { data, backgroundColor, strokeColor } = parse(node);
|
||||
const elementsPoints = pathToPoints(data);
|
||||
|
||||
return elementsPoints.map((points) => {
|
||||
const boundaries = getElementBoundaries(points);
|
||||
|
||||
return {
|
||||
type: "line",
|
||||
roughness: 0,
|
||||
strokeSharpness: "sharp",
|
||||
points,
|
||||
backgroundColor,
|
||||
strokeColor,
|
||||
...boundaries,
|
||||
};
|
||||
});
|
||||
};
|
||||
@@ -1,66 +0,0 @@
|
||||
import { safeNumber } from "../../../utils";
|
||||
|
||||
/**
|
||||
* Get a point at a given section of a cubic bezier curve.
|
||||
* This function only supports two dimensions curves
|
||||
* @see https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B%C3%A9zier_curves
|
||||
*/
|
||||
const getPointOfCubicCurve = (
|
||||
controlPoints: number[][],
|
||||
section: number,
|
||||
): number[] =>
|
||||
Array.from({ length: 2 }).map((v, i) => {
|
||||
const point =
|
||||
controlPoints[0][i] * (1 - section) ** 3 +
|
||||
3 * controlPoints[1][i] * section * (1 - section) ** 2 +
|
||||
3 * controlPoints[2][i] * section ** 2 * (1 - section) +
|
||||
controlPoints[3][i] * section ** 3;
|
||||
|
||||
return safeNumber(point);
|
||||
});
|
||||
|
||||
/**
|
||||
* Get a point at a given section of a quadratic bezier curve.
|
||||
* This function only supports two dimensions curves
|
||||
* @see https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Quadratic_B%C3%A9zier_curves
|
||||
*/
|
||||
const getPointOfQuadraticCurve = (
|
||||
controlPoints: number[][],
|
||||
section: number,
|
||||
): number[] =>
|
||||
Array.from({ length: 2 }).map((v, i) => {
|
||||
const point =
|
||||
controlPoints[0][i] * (1 - section) ** 2 +
|
||||
2 * controlPoints[1][i] * section * (1 - section) +
|
||||
controlPoints[2][i] * section ** 2;
|
||||
|
||||
return safeNumber(point);
|
||||
});
|
||||
|
||||
/**
|
||||
* Get list of points for a cubic bézier curve.
|
||||
* Starting point is not returned
|
||||
*/
|
||||
export const curveToPoints = (
|
||||
type: "cubic" | "quadratic",
|
||||
controlPoints: number[][],
|
||||
nbPoints = 10,
|
||||
): number[][] => {
|
||||
if (nbPoints <= 0) {
|
||||
throw new Error("Requested amount of points must be positive");
|
||||
} else if (nbPoints > 100) {
|
||||
nbPoints = 100;
|
||||
}
|
||||
|
||||
return Array.from({ length: nbPoints }, (value, index) => {
|
||||
const section = safeNumber(((100 / nbPoints) * (index + 1)) / 100);
|
||||
|
||||
if (type === "cubic") {
|
||||
return getPointOfCubicCurve(controlPoints, section);
|
||||
} else if (type === "quadratic") {
|
||||
return getPointOfQuadraticCurve(controlPoints, section);
|
||||
}
|
||||
|
||||
throw new Error("Invalid bézier curve type requested");
|
||||
});
|
||||
};
|
||||
@@ -1,140 +0,0 @@
|
||||
const degreeToRadian = (degree: number): number => (degree * Math.PI) / 180;
|
||||
|
||||
/**
|
||||
* Get each possible ellipses center points given two points and ellipse radius
|
||||
* @see https://math.stackexchange.com/questions/2240031/solving-an-equation-for-an-ellipse
|
||||
*/
|
||||
export const getEllipsesCenter = (
|
||||
curX: number,
|
||||
curY: number,
|
||||
destX: number,
|
||||
destY: number,
|
||||
radiusX: number,
|
||||
radiusY: number,
|
||||
): number[][] => [
|
||||
[
|
||||
(curX + destX) / 2 +
|
||||
((radiusX * (curY - destY)) / (2 * radiusY)) *
|
||||
Math.sqrt(
|
||||
4 /
|
||||
((curX - destX) ** 2 / radiusX ** 2 +
|
||||
(curY - destY) ** 2 / radiusY ** 2) -
|
||||
1,
|
||||
),
|
||||
(curY + destY) / 2 -
|
||||
((radiusY * (curX - destX)) / (2 * radiusX)) *
|
||||
Math.sqrt(
|
||||
4 /
|
||||
((curX - destX) ** 2 / radiusX ** 2 +
|
||||
(curY - destY) ** 2 / radiusY ** 2) -
|
||||
1,
|
||||
),
|
||||
],
|
||||
[
|
||||
(curX + destX) / 2 -
|
||||
((radiusX * (curY - destY)) / (2 * radiusY)) *
|
||||
Math.sqrt(
|
||||
4 /
|
||||
((curX - destX) ** 2 / radiusX ** 2 +
|
||||
(curY - destY) ** 2 / radiusY ** 2) -
|
||||
1,
|
||||
),
|
||||
(curY + destY) / 2 +
|
||||
((radiusY * (curX - destX)) / (2 * radiusX)) *
|
||||
Math.sqrt(
|
||||
4 /
|
||||
((curX - destX) ** 2 / radiusX ** 2 +
|
||||
(curY - destY) ** 2 / radiusY ** 2) -
|
||||
1,
|
||||
),
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Get point of ellipse at given degree
|
||||
*/
|
||||
const getPointAtDegree = (
|
||||
centerX: number,
|
||||
centerY: number,
|
||||
radiusX: number,
|
||||
radiusY: number,
|
||||
degree: number,
|
||||
): number[] => [
|
||||
Math.round(radiusX * Math.cos(degreeToRadian(degree)) + centerX),
|
||||
Math.round(radiusY * Math.sin(degreeToRadian(degree)) + centerY),
|
||||
];
|
||||
|
||||
/**
|
||||
* Get all points of a given ellipse
|
||||
*/
|
||||
export const getEllipsePoints = (
|
||||
centerX: number,
|
||||
centerY: number,
|
||||
radiusX: number,
|
||||
radiusY: number,
|
||||
): number[][] => {
|
||||
const points: number[][] = [];
|
||||
|
||||
for (let i = 0; i < 360; i += 1) {
|
||||
const pointAtDegree = getPointAtDegree(
|
||||
centerX,
|
||||
centerY,
|
||||
radiusX,
|
||||
radiusY,
|
||||
i,
|
||||
);
|
||||
const existingPoint = points.find(
|
||||
([x, y]) => x === pointAtDegree[0] && y === pointAtDegree[1],
|
||||
);
|
||||
|
||||
if (!existingPoint) {
|
||||
points.push(pointAtDegree);
|
||||
}
|
||||
}
|
||||
|
||||
return points;
|
||||
};
|
||||
|
||||
/**
|
||||
* Find ellipse arc given sweep parameter
|
||||
*/
|
||||
export const findArc = (
|
||||
points: number[][],
|
||||
sweep: boolean,
|
||||
curX: number,
|
||||
curY: number,
|
||||
destX: number,
|
||||
destY: number,
|
||||
): number[][] => {
|
||||
const indexCur = points.findIndex(
|
||||
([x, y]) => x === Math.round(curX) && y === Math.round(curY),
|
||||
);
|
||||
const indexDest = points.findIndex(
|
||||
([x, y]) => x === Math.round(destX) && y === Math.round(destY),
|
||||
);
|
||||
const arc = [];
|
||||
const step = sweep ? -1 : 1;
|
||||
|
||||
let i = indexDest;
|
||||
|
||||
// Checking if indices exist prevents runtime crashes
|
||||
if (indexCur !== -1 && indexDest !== -1) {
|
||||
while (i >= -1 && i <= points.length) {
|
||||
arc.push(points[i]);
|
||||
|
||||
if (i === indexCur) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (sweep && i === 0) {
|
||||
i = points.length;
|
||||
} else if (!sweep && i === points.length - 1) {
|
||||
i = -1;
|
||||
} else {
|
||||
i += step;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return arc.reverse();
|
||||
};
|
||||
@@ -1,313 +0,0 @@
|
||||
import { PathCommand } from "../../../types";
|
||||
import { safeNumber } from "../../../utils";
|
||||
import { curveToPoints } from "./bezier";
|
||||
import { findArc, getEllipsePoints, getEllipsesCenter } from "./ellipse";
|
||||
|
||||
const PATH_COMMANDS_REGEX =
|
||||
/(?:([HhVv] *-?\d*(?:\.\d+)?)|([MmLlTt](?: *-?\d*(?:\.\d+)?(?:,| *)?){2})|([Cc](?: *-?\d*(?:\.\d+)?(?:,| *)?){6})|([QqSs](?: *-?\d*(?:\.\d+)?(?:,| *)?){4})|([Aa](?: *-?\d*(?:\.\d+)?(?:,| *)?){7})|(z|Z))/g;
|
||||
const COMMAND_REGEX = /(?:[MmLlHhVvCcSsQqTtAaZz]|(-?\d+(?:\.\d+)?))/g;
|
||||
|
||||
const handleMoveToAndLineTo = (
|
||||
currentPosition: number[],
|
||||
parameters: number[],
|
||||
isRelative: boolean,
|
||||
): number[] => {
|
||||
if (isRelative) {
|
||||
return [
|
||||
currentPosition[0] + parameters[0],
|
||||
currentPosition[1] + parameters[1],
|
||||
];
|
||||
}
|
||||
|
||||
return parameters;
|
||||
};
|
||||
|
||||
const handleHorizontalLineTo = (
|
||||
currentPosition: number[],
|
||||
x: number,
|
||||
isRelative: boolean,
|
||||
): number[] => {
|
||||
if (isRelative) {
|
||||
return [currentPosition[0] + x, currentPosition[1]];
|
||||
}
|
||||
|
||||
return [x, currentPosition[1]];
|
||||
};
|
||||
|
||||
const handleVerticalLineTo = (
|
||||
currentPosition: number[],
|
||||
y: number,
|
||||
isRelative: boolean,
|
||||
): number[] => {
|
||||
if (isRelative) {
|
||||
return [currentPosition[0], currentPosition[1] + y];
|
||||
}
|
||||
|
||||
return [currentPosition[0], y];
|
||||
};
|
||||
|
||||
const handleCubicCurveTo = (
|
||||
currentPosition: number[],
|
||||
parameters: number[],
|
||||
lastCommand: PathCommand,
|
||||
isSimpleForm: boolean,
|
||||
isRelative: boolean,
|
||||
): number[][] => {
|
||||
const controlPoints = [currentPosition];
|
||||
let inferredControlPoint;
|
||||
|
||||
if (isSimpleForm) {
|
||||
inferredControlPoint = ["C", "c"].includes(lastCommand?.type)
|
||||
? [
|
||||
currentPosition[0] - (lastCommand.parameters[2] - currentPosition[0]),
|
||||
currentPosition[1] - (lastCommand.parameters[3] - currentPosition[1]),
|
||||
]
|
||||
: currentPosition;
|
||||
}
|
||||
|
||||
if (isRelative) {
|
||||
controlPoints.push(
|
||||
inferredControlPoint || [
|
||||
currentPosition[0] + parameters[0],
|
||||
currentPosition[1] + parameters[1],
|
||||
],
|
||||
[currentPosition[0] + parameters[2], currentPosition[1] + parameters[3]],
|
||||
[currentPosition[0] + parameters[4], currentPosition[1] + parameters[5]],
|
||||
);
|
||||
} else {
|
||||
controlPoints.push(
|
||||
inferredControlPoint || [parameters[0], parameters[1]],
|
||||
[parameters[2], parameters[3]],
|
||||
[parameters[4], parameters[5]],
|
||||
);
|
||||
}
|
||||
|
||||
return curveToPoints("cubic", controlPoints);
|
||||
};
|
||||
|
||||
const handleQuadraticCurveTo = (
|
||||
currentPosition: number[],
|
||||
parameters: number[],
|
||||
lastCommand: PathCommand,
|
||||
isSimpleForm: boolean,
|
||||
isRelative: boolean,
|
||||
): number[][] => {
|
||||
const controlPoints = [currentPosition];
|
||||
let inferredControlPoint;
|
||||
|
||||
if (isSimpleForm) {
|
||||
inferredControlPoint = ["Q", "q"].includes(lastCommand?.type)
|
||||
? [
|
||||
currentPosition[0] - (lastCommand.parameters[0] - currentPosition[0]),
|
||||
currentPosition[1] - (lastCommand.parameters[1] - currentPosition[1]),
|
||||
]
|
||||
: currentPosition;
|
||||
}
|
||||
|
||||
if (isRelative) {
|
||||
controlPoints.push(
|
||||
inferredControlPoint || [
|
||||
currentPosition[0] + parameters[0],
|
||||
currentPosition[1] + parameters[1],
|
||||
],
|
||||
[currentPosition[0] + parameters[2], currentPosition[1] + parameters[3]],
|
||||
);
|
||||
} else {
|
||||
controlPoints.push(inferredControlPoint || [parameters[0], parameters[1]], [
|
||||
parameters[2],
|
||||
parameters[3],
|
||||
]);
|
||||
}
|
||||
|
||||
return curveToPoints("quadratic", controlPoints);
|
||||
};
|
||||
|
||||
/**
|
||||
* @todo handle arcs rotation
|
||||
* @todo handle specific cases where only one ellipse can exist
|
||||
*/
|
||||
const handleArcTo = (
|
||||
currentPosition: number[],
|
||||
[radiusX, radiusY, , large, sweep, destX, destY]: number[],
|
||||
isRelative: boolean,
|
||||
): number[][] => {
|
||||
destX = isRelative ? currentPosition[0] + destX : destX;
|
||||
destY = isRelative ? currentPosition[1] + destY : destY;
|
||||
|
||||
const ellipsesCenter = getEllipsesCenter(
|
||||
currentPosition[0],
|
||||
currentPosition[1],
|
||||
destX,
|
||||
destY,
|
||||
radiusX,
|
||||
radiusY,
|
||||
);
|
||||
|
||||
const ellipsesPoints = [
|
||||
getEllipsePoints(
|
||||
ellipsesCenter[0][0],
|
||||
ellipsesCenter[0][1],
|
||||
radiusX,
|
||||
radiusY,
|
||||
),
|
||||
getEllipsePoints(
|
||||
ellipsesCenter[1][0],
|
||||
ellipsesCenter[1][1],
|
||||
radiusX,
|
||||
radiusY,
|
||||
),
|
||||
];
|
||||
|
||||
const arcs = [
|
||||
findArc(
|
||||
ellipsesPoints[0],
|
||||
!!sweep,
|
||||
currentPosition[0],
|
||||
currentPosition[1],
|
||||
destX,
|
||||
destY,
|
||||
),
|
||||
findArc(
|
||||
ellipsesPoints[1],
|
||||
!!sweep,
|
||||
currentPosition[0],
|
||||
currentPosition[1],
|
||||
destX,
|
||||
destY,
|
||||
),
|
||||
];
|
||||
|
||||
const finalArc = arcs.reduce(
|
||||
(arc, curArc) =>
|
||||
(large && curArc.length > arc.length) ||
|
||||
(!large && (!arc.length || curArc.length < arc.length))
|
||||
? curArc
|
||||
: arc,
|
||||
[],
|
||||
);
|
||||
|
||||
return finalArc;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert a SVG path data to list of points
|
||||
*/
|
||||
const pathToPoints = (path: string): number[][][] => {
|
||||
const commands = path.match(PATH_COMMANDS_REGEX);
|
||||
const elements = [];
|
||||
const commandsHistory = [];
|
||||
let currentPosition = [0, 0];
|
||||
let points = [];
|
||||
|
||||
if (!commands?.length) {
|
||||
throw new Error("No commands found in given path");
|
||||
}
|
||||
|
||||
for (const command of commands) {
|
||||
const lastCommand = commandsHistory[commandsHistory.length - 2];
|
||||
const commandMatch = command.match(COMMAND_REGEX);
|
||||
|
||||
currentPosition = points[points.length - 1] || currentPosition;
|
||||
|
||||
if (commandMatch?.length) {
|
||||
const commandType = commandMatch[0];
|
||||
const parameters = commandMatch
|
||||
.slice(1, commandMatch.length)
|
||||
.map((parameter) => safeNumber(Number(parameter)));
|
||||
const isRelative = commandType.toLowerCase() === commandType;
|
||||
|
||||
commandsHistory.push({
|
||||
type: commandType,
|
||||
parameters,
|
||||
isRelative,
|
||||
});
|
||||
|
||||
switch (commandType) {
|
||||
case "M":
|
||||
case "m":
|
||||
case "L":
|
||||
case "l":
|
||||
points.push(
|
||||
handleMoveToAndLineTo(currentPosition, parameters, isRelative),
|
||||
);
|
||||
|
||||
break;
|
||||
case "H":
|
||||
case "h":
|
||||
points.push(
|
||||
handleHorizontalLineTo(currentPosition, parameters[0], isRelative),
|
||||
);
|
||||
|
||||
break;
|
||||
case "V":
|
||||
case "v":
|
||||
points.push(
|
||||
handleVerticalLineTo(currentPosition, parameters[0], isRelative),
|
||||
);
|
||||
|
||||
break;
|
||||
case "C":
|
||||
case "c":
|
||||
case "S":
|
||||
case "s":
|
||||
points.push(
|
||||
...handleCubicCurveTo(
|
||||
currentPosition,
|
||||
parameters,
|
||||
lastCommand,
|
||||
["S", "s"].includes(commandType),
|
||||
isRelative,
|
||||
),
|
||||
);
|
||||
|
||||
break;
|
||||
case "Q":
|
||||
case "q":
|
||||
case "T":
|
||||
case "t":
|
||||
points.push(
|
||||
...handleQuadraticCurveTo(
|
||||
currentPosition,
|
||||
parameters,
|
||||
lastCommand,
|
||||
["T", "t"].includes(commandType),
|
||||
isRelative,
|
||||
),
|
||||
);
|
||||
|
||||
break;
|
||||
case "A":
|
||||
case "a":
|
||||
points.push(...handleArcTo(currentPosition, parameters, isRelative));
|
||||
|
||||
break;
|
||||
case "Z":
|
||||
case "z":
|
||||
if (points.length) {
|
||||
if (
|
||||
currentPosition[0] !== points[0][0] ||
|
||||
currentPosition[1] !== points[0][1]
|
||||
) {
|
||||
points.push(points[0]);
|
||||
}
|
||||
|
||||
elements.push(points);
|
||||
}
|
||||
|
||||
points = [];
|
||||
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// console.error("Unsupported command provided will be ignored:", command);
|
||||
}
|
||||
}
|
||||
|
||||
if (elements.length === 0 && points.length) {
|
||||
elements.push(points);
|
||||
}
|
||||
|
||||
return elements;
|
||||
};
|
||||
|
||||
export default pathToPoints;
|
||||
@@ -1,39 +0,0 @@
|
||||
import { ElementBoundaries } from "../types";
|
||||
|
||||
export const getElementBoundaries = (points: number[][]): ElementBoundaries => {
|
||||
const { x, y } = points.reduce(
|
||||
(boundaries, [x, y]) => {
|
||||
if (x < boundaries.x.min) {
|
||||
boundaries.x.min = x;
|
||||
}
|
||||
if (x > boundaries.x.max) {
|
||||
boundaries.x.max = x;
|
||||
}
|
||||
if (y < boundaries.y.min) {
|
||||
boundaries.y.min = y;
|
||||
}
|
||||
if (y > boundaries.y.max) {
|
||||
boundaries.y.max = y;
|
||||
}
|
||||
|
||||
return boundaries;
|
||||
},
|
||||
{
|
||||
x: {
|
||||
min: Infinity,
|
||||
max: 0,
|
||||
},
|
||||
y: {
|
||||
min: Infinity,
|
||||
max: 0,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
x: x.min,
|
||||
y: y.min,
|
||||
width: x.max - x.min,
|
||||
height: y.max - y.min,
|
||||
};
|
||||
};
|
||||
@@ -1,125 +0,0 @@
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawLinearElement,
|
||||
ExcalidrawTextElement,
|
||||
FillStyle,
|
||||
GroupId,
|
||||
RoundnessType,
|
||||
StrokeStyle,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
|
||||
export type PathCommand = {
|
||||
type: string;
|
||||
parameters: number[];
|
||||
isRelative: boolean;
|
||||
};
|
||||
|
||||
export type RawElement = {
|
||||
type: string;
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
points: number[][];
|
||||
backgroundColor: string;
|
||||
strokeColor: string;
|
||||
};
|
||||
|
||||
export type ElementBoundaries = {
|
||||
x: number;
|
||||
y: number;
|
||||
height: number;
|
||||
width: number;
|
||||
};
|
||||
|
||||
/* from Excalidraw codebase */
|
||||
|
||||
// 1-based in case we ever do `if(element.fontFamily)`
|
||||
export const FONT_FAMILY = {
|
||||
1: "Virgil",
|
||||
2: "Helvetica",
|
||||
3: "Cascadia",
|
||||
} as const;
|
||||
|
||||
export declare type RoughPoint = [number, number];
|
||||
export type Point = Readonly<RoughPoint>;
|
||||
|
||||
export declare type Line = [Point, Point];
|
||||
export interface Rectangle {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
type _ExcalidrawElementBase = Readonly<{
|
||||
id: string;
|
||||
x: number;
|
||||
y: number;
|
||||
strokeColor: string;
|
||||
backgroundColor: string;
|
||||
fillStyle: FillStyle;
|
||||
strokeWidth: number;
|
||||
strokeStyle: StrokeStyle;
|
||||
roundness: null | { type: RoundnessType; value?: number };
|
||||
roughness: number;
|
||||
opacity: number;
|
||||
width: number;
|
||||
height: number;
|
||||
angle: number;
|
||||
/** Random integer used to seed shape generation so that the roughjs shape
|
||||
doesn't differ across renders. */
|
||||
seed: number;
|
||||
/** Integer that is sequentially incremented on each change. Used to reconcile
|
||||
elements during collaboration or when saving to server. */
|
||||
version: number;
|
||||
/** Random integer that is regenerated on each change.
|
||||
Used for deterministic reconciliation of updates during collaboration,
|
||||
in case the versions (see above) are identical. */
|
||||
versionNonce: number;
|
||||
isDeleted: boolean;
|
||||
/** List of groups the element belongs to.
|
||||
Ordered from deepest to shallowest. */
|
||||
groupIds: readonly GroupId[];
|
||||
/** Ids of (linear) elements that are bound to this element. */
|
||||
boundElementIds: readonly ExcalidrawLinearElement["id"][] | null;
|
||||
}>;
|
||||
|
||||
export type ExcalidrawSelectionElement = _ExcalidrawElementBase & {
|
||||
type: "selection";
|
||||
};
|
||||
|
||||
export type ExcalidrawRectangleElement = _ExcalidrawElementBase & {
|
||||
type: "rectangle";
|
||||
};
|
||||
|
||||
export type ExcalidrawDiamondElement = _ExcalidrawElementBase & {
|
||||
type: "diamond";
|
||||
};
|
||||
|
||||
export type ExcalidrawEllipseElement = _ExcalidrawElementBase & {
|
||||
type: "ellipse";
|
||||
};
|
||||
|
||||
/**
|
||||
* These are elements that don't have any additional properties.
|
||||
*/
|
||||
export type ExcalidrawGenericElement =
|
||||
| ExcalidrawSelectionElement
|
||||
| ExcalidrawRectangleElement
|
||||
| ExcalidrawDiamondElement
|
||||
| ExcalidrawEllipseElement;
|
||||
|
||||
/**
|
||||
* ExcalidrawElement should be JSON serializable and (eventually) contain
|
||||
* no computed data. The list of all ExcalidrawElements should be shareable
|
||||
* between peers and contain no state local to the peer.
|
||||
*/
|
||||
export type _ExcalidrawElement =
|
||||
| ExcalidrawGenericElement
|
||||
| ExcalidrawTextElement
|
||||
| ExcalidrawLinearElement;
|
||||
|
||||
export type NonDeleted<TElement extends ExcalidrawElement> = TElement & {
|
||||
isDeleted: false;
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Random } from "roughjs/bin/math";
|
||||
import { nanoid } from "nanoid";
|
||||
import { Point } from "./elements/ExcalidrawElement";
|
||||
import type { Point } from "./elements/ExcalidrawElement";
|
||||
|
||||
const random = new Random(Date.now());
|
||||
|
||||
@@ -8,8 +8,6 @@ export const randomInteger = (): number => Math.floor(random.next() * 2 ** 31);
|
||||
|
||||
export const randomId = (): string => nanoid();
|
||||
|
||||
export const safeNumber = (number: number): number => Number(number.toFixed(2));
|
||||
|
||||
export function dimensionsFromPoints(points: number[][]): number[] {
|
||||
const xCoords = points.map(([x]) => x);
|
||||
const yCoords = points.map(([, y]) => y);
|
||||
|
||||
@@ -7,11 +7,9 @@ import {
|
||||
ExcalidrawRectangle,
|
||||
ExcalidrawEllipse,
|
||||
ExcalidrawLine,
|
||||
ExcalidrawDraw,
|
||||
createExRect,
|
||||
createExEllipse,
|
||||
createExLine,
|
||||
createExDraw,
|
||||
Point,
|
||||
} from "./elements/ExcalidrawElement";
|
||||
import {
|
||||
@@ -276,10 +274,9 @@ const walkers = {
|
||||
const [width, height] = dimensionsFromPoints(relativePoints);
|
||||
|
||||
const line: ExcalidrawLine = {
|
||||
...createExLine(),
|
||||
...createExLine(relativePoints.concat([[0, 0]])),
|
||||
...getGroupAttrs(groups),
|
||||
...presAttrsToElementValues(el),
|
||||
points: relativePoints.concat([[0, 0]]),
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
@@ -317,10 +314,9 @@ const walkers = {
|
||||
const shouldFill = !hasFill || (hasFill && fill !== "none");
|
||||
|
||||
const line: ExcalidrawLine = {
|
||||
...createExLine(),
|
||||
...createExLine(relativePoints.concat(shouldFill ? [[0, 0]] : [])),
|
||||
...getGroupAttrs(groups),
|
||||
...presAttrsToElementValues(el),
|
||||
points: relativePoints.concat(shouldFill ? [[0, 0]] : []),
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
@@ -379,14 +375,14 @@ const walkers = {
|
||||
const fillColor = get(el, "fill", "black");
|
||||
const fillRule = get(el, "fill-rule", "nonzero");
|
||||
|
||||
let elements: ExcalidrawDraw[] = [];
|
||||
let elements: ExcalidrawLine[] = [];
|
||||
let localGroup = randomId();
|
||||
|
||||
switch (fillRule) {
|
||||
case "nonzero": {
|
||||
let initialWindingOrder = "clockwise";
|
||||
|
||||
elements = points.map((pointArr, idx): ExcalidrawDraw => {
|
||||
elements = points.map((pointArr, idx): ExcalidrawLine => {
|
||||
const tPoints: Point[] = transformPoints(pointArr, mat4.clone(mat));
|
||||
const x = tPoints[0][0];
|
||||
const y = tPoints[0][1];
|
||||
@@ -409,11 +405,10 @@ const walkers = {
|
||||
}
|
||||
|
||||
return {
|
||||
...createExDraw(),
|
||||
...createExLine(relativePoints),
|
||||
strokeWidth: 0,
|
||||
strokeColor: "#00000000",
|
||||
...presAttrs(el, groups),
|
||||
points: relativePoints,
|
||||
backgroundColor,
|
||||
width,
|
||||
height,
|
||||
@@ -425,7 +420,7 @@ const walkers = {
|
||||
break;
|
||||
}
|
||||
case "evenodd":
|
||||
elements = points.map((pointArr, idx): ExcalidrawDraw => {
|
||||
elements = points.map((pointArr, idx): ExcalidrawLine => {
|
||||
const tPoints: Point[] = transformPoints(pointArr, mat4.clone(mat));
|
||||
const x = tPoints[0][0];
|
||||
const y = tPoints[0][1];
|
||||
@@ -441,9 +436,8 @@ const walkers = {
|
||||
}
|
||||
|
||||
return {
|
||||
...createExDraw(),
|
||||
...createExLine(relativePoints),
|
||||
...presAttrs(el, groups),
|
||||
points: relativePoints,
|
||||
width,
|
||||
height,
|
||||
x: x + getNum(el, "x", 0),
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Types for the selected-element action menu provider mechanism
|
||||
* (`view.selectedElementActionsMenu`), shared between the view-owned
|
||||
* `SelectedElementActionsMenu` component and the public
|
||||
* `ExcalidrawAutomate.registerElementActionProvider()` scripting API.
|
||||
*/
|
||||
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
|
||||
export type SelectedElementMenuAction = {
|
||||
id: string;
|
||||
title: string;
|
||||
icon: string;
|
||||
action: () => void;
|
||||
};
|
||||
|
||||
export type SelectedElementMenuProvider = {
|
||||
id: string;
|
||||
getActions: (
|
||||
element: ExcalidrawElement,
|
||||
) => readonly SelectedElementMenuAction[];
|
||||
};
|
||||
Vendored
+66
-2
@@ -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>;
|
||||
|
||||
@@ -52,9 +52,6 @@ export type ExcalidrawViewAppState = Omit<
|
||||
Partial<AppState>,
|
||||
"showHyperlinkPopup"
|
||||
> & {
|
||||
currentStrokeOptions?: unknown;
|
||||
resetCustomPen?: unknown;
|
||||
customPens?: unknown[];
|
||||
pinnedScripts?: string[];
|
||||
showHyperlinkPopup?:
|
||||
| AppState["showHyperlinkPopup"]
|
||||
|
||||
+20
-53
@@ -1,54 +1,21 @@
|
||||
export interface StrokeOptions {
|
||||
thinning: number;
|
||||
smoothing: number;
|
||||
streamline: number;
|
||||
easing: string;
|
||||
simulatePressure?: boolean;
|
||||
start: {
|
||||
cap: boolean;
|
||||
taper: number | boolean;
|
||||
easing: string;
|
||||
};
|
||||
end: {
|
||||
cap: boolean;
|
||||
taper: number | boolean;
|
||||
easing: string;
|
||||
};
|
||||
}
|
||||
import type {
|
||||
ObsidianExtendedFillStyle,
|
||||
ObsidianPenOptions,
|
||||
ObsidianPenStrokeOptions,
|
||||
ObsidianPenStyle,
|
||||
ObsidianPenType,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/obsidianTypes";
|
||||
|
||||
export interface PenOptions {
|
||||
highlighter: boolean;
|
||||
constantPressure: boolean;
|
||||
hasOutline: boolean;
|
||||
outlineWidth: number;
|
||||
options: StrokeOptions;
|
||||
}
|
||||
|
||||
export declare type ExtendedFillStyle =
|
||||
| "dots"
|
||||
| "zigzag"
|
||||
| "zigzag-line"
|
||||
| "dashed"
|
||||
| "hachure"
|
||||
| "cross-hatch"
|
||||
| "solid"
|
||||
| "";
|
||||
export declare type PenType =
|
||||
| "default"
|
||||
| "highlighter"
|
||||
| "finetip"
|
||||
| "fountain"
|
||||
| "marker"
|
||||
| "thick-thin"
|
||||
| "thin-thick-thin";
|
||||
|
||||
export interface PenStyle {
|
||||
type: PenType;
|
||||
freedrawOnly: boolean;
|
||||
strokeColor?: string;
|
||||
backgroundColor?: string;
|
||||
fillStyle: ExtendedFillStyle;
|
||||
strokeWidth: number;
|
||||
roughness: number;
|
||||
penOptions: PenOptions;
|
||||
}
|
||||
/**
|
||||
* Local names for the custom-pen types, aliased to the canonical
|
||||
* definitions owned by the Excalidraw fork
|
||||
* (packages/excalidraw/obsidianTypes.ts, referenced by
|
||||
* `AppState.customPens`/`currentStrokeOptions`). The fork cannot depend on
|
||||
* this plugin, so the shapes live there and are aliased here rather than
|
||||
* duplicated -- edit the fork's `Obsidian*` types, not these.
|
||||
*/
|
||||
export type StrokeOptions = ObsidianPenStrokeOptions;
|
||||
export type PenOptions = ObsidianPenOptions;
|
||||
export type ExtendedFillStyle = ObsidianExtendedFillStyle;
|
||||
export type PenType = ObsidianPenType;
|
||||
export type PenStyle = ObsidianPenStyle;
|
||||
Vendored
+13
-4
@@ -1,4 +1,15 @@
|
||||
import { TFile, View, WorkspaceLeaf } from "obsidian";
|
||||
import {
|
||||
TFile,
|
||||
View,
|
||||
WorkspaceLeaf,
|
||||
PluginManifest,
|
||||
Hotkey,
|
||||
TAbstractFile,
|
||||
MenuItem,
|
||||
Component,
|
||||
EventRef,
|
||||
WorkspaceContainer,
|
||||
} from "obsidian";
|
||||
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
|
||||
import { ExcalidrawLib } from "./excalidrawLib";
|
||||
import type { PdfJsLibrary } from "./pdfJsTypes";
|
||||
@@ -160,6 +171,7 @@ export type LocalGraphView = View & {
|
||||
declare global {
|
||||
interface Window {
|
||||
ExcalidrawAutomate: ExcalidrawAutomate;
|
||||
ExcalidrawLib: typeof ExcalidrawLib;
|
||||
pdfjsLib: PdfJsLibrary;
|
||||
unpackBase64Deflate?: (value: string) => string;
|
||||
PolyBool?: PolyBoolLibrary;
|
||||
@@ -168,9 +180,6 @@ declare global {
|
||||
setAlwaysOnTop(flag: boolean): void;
|
||||
};
|
||||
eval: (x: string) => unknown;
|
||||
React?: typeof import("react");
|
||||
ReactDOM?: typeof import("react-dom/client");
|
||||
ExcalidrawLib?: typeof ExcalidrawLib;
|
||||
MathJax?: {
|
||||
typesetPromise(elements: HTMLElement[]): Promise<void>;
|
||||
};
|
||||
|
||||
+15
-101
@@ -24,7 +24,6 @@ import {
|
||||
} from "src/types/AIUtilTypes";
|
||||
import {
|
||||
decryptProviderProfiles,
|
||||
decryptStoredAPIKey,
|
||||
} from "src/utils/settingsKeyObfuscation";
|
||||
import {
|
||||
getGeminiImageRequestConfig,
|
||||
@@ -449,16 +448,6 @@ const joinURL = (baseURL: string, path: string): string => {
|
||||
return `${normalizeBaseURL(baseURL)}/${path.replace(/^\/+/, "")}`;
|
||||
};
|
||||
|
||||
const inferLegacyBaseURL = (url: string, suffix: string): string => {
|
||||
const normalized = normalizeBaseURL(url);
|
||||
if (!normalized) {
|
||||
return "";
|
||||
}
|
||||
return normalized.endsWith(suffix)
|
||||
? normalized.slice(0, -suffix.length)
|
||||
: normalized;
|
||||
};
|
||||
|
||||
const inferConfiguredBaseURL = (url: string): string => {
|
||||
const normalized = normalizeBaseURL(url);
|
||||
if (!normalized) {
|
||||
@@ -473,13 +462,6 @@ const inferConfiguredBaseURL = (url: string): string => {
|
||||
: normalized;
|
||||
};
|
||||
|
||||
const getResolvedProvider = (
|
||||
request: AIRequest,
|
||||
plugin: ExcalidrawPlugin,
|
||||
): AIProvider => {
|
||||
return request.provider ?? plugin.settings.aiProvider ?? "openai";
|
||||
};
|
||||
|
||||
const getProviderProfiles = (
|
||||
plugin: ExcalidrawPlugin,
|
||||
): Record<string, AIProviderProfile> => {
|
||||
@@ -488,17 +470,9 @@ const getProviderProfiles = (
|
||||
? decryptProviderProfiles(plugin.settings.aiProviderProfiles)
|
||||
: {
|
||||
OpenAI: {
|
||||
provider: plugin.settings.aiProvider ?? "openai",
|
||||
apiKey: decryptStoredAPIKey(
|
||||
plugin.settings.aiAPIKey || plugin.settings.openAIAPIToken,
|
||||
),
|
||||
baseURL:
|
||||
inferConfiguredBaseURL(plugin.settings.aiBaseURL) ||
|
||||
inferLegacyBaseURL(
|
||||
plugin.settings.openAIURL,
|
||||
"/chat/completions",
|
||||
) ||
|
||||
DEFAULT_PROVIDER_BASE_URLS[plugin.settings.aiProvider ?? "openai"],
|
||||
provider: "openai",
|
||||
apiKey: "",
|
||||
baseURL: URLs.API_OPENAI_COM_V1,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -527,36 +501,15 @@ const getModelConfigs = (plugin: ExcalidrawPlugin, kind: "text" | "image") => {
|
||||
return plugin.settings.aiTextModelConfigs;
|
||||
}
|
||||
|
||||
if (
|
||||
plugin.settings.aiVisionModelConfigs &&
|
||||
Object.keys(plugin.settings.aiVisionModelConfigs).length > 0
|
||||
) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(plugin.settings.aiVisionModelConfigs).map(
|
||||
([modelId, config]) => [
|
||||
modelId,
|
||||
{
|
||||
...config,
|
||||
multimodalSupport: config.multimodalSupport ?? true,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const defaultTextModel =
|
||||
plugin.settings.aiDefaultTextModel ||
|
||||
plugin.settings.aiDefaultVisionModel ||
|
||||
plugin.settings.openAIDefaultTextModel ||
|
||||
plugin.settings.openAIDefaultVisionModel ||
|
||||
"gpt-5-mini";
|
||||
|
||||
return {
|
||||
[defaultTextModel]: {
|
||||
providerId: getDefaultProviderProfileId(plugin),
|
||||
model: defaultTextModel,
|
||||
endpoint:
|
||||
plugin.settings.aiTextEndpoint || plugin.settings.openAIURL || "",
|
||||
endpoint: "",
|
||||
multimodalSupport: true,
|
||||
},
|
||||
};
|
||||
@@ -564,18 +517,7 @@ const getModelConfigs = (plugin: ExcalidrawPlugin, kind: "text" | "image") => {
|
||||
|
||||
const defaultImageModel =
|
||||
plugin.settings.aiDefaultImageGenerationModel ||
|
||||
plugin.settings.openAIDefaultImageGenerationModel ||
|
||||
"gpt-image-1";
|
||||
const legacyCapability = plugin.settings.aiImageModelCapabilities?.[
|
||||
defaultImageModel
|
||||
] as
|
||||
| {
|
||||
supportedSizes?: string[];
|
||||
supportsPromptImageTransforms?: boolean;
|
||||
supportsMaskImageEdits?: boolean;
|
||||
supportsImageEdits?: boolean;
|
||||
}
|
||||
| undefined;
|
||||
|
||||
return plugin.settings.aiImageModelConfigs &&
|
||||
Object.keys(plugin.settings.aiImageModelConfigs).length > 0
|
||||
@@ -584,15 +526,9 @@ const getModelConfigs = (plugin: ExcalidrawPlugin, kind: "text" | "image") => {
|
||||
[defaultImageModel]: {
|
||||
providerId: getDefaultProviderProfileId(plugin),
|
||||
model: defaultImageModel,
|
||||
supportedSizes: legacyCapability?.supportedSizes ?? ["1024x1024"],
|
||||
supportsPromptImageTransforms:
|
||||
legacyCapability?.supportsPromptImageTransforms ??
|
||||
legacyCapability?.supportsImageEdits ??
|
||||
true,
|
||||
supportsMaskImageEdits:
|
||||
legacyCapability?.supportsMaskImageEdits ??
|
||||
legacyCapability?.supportsImageEdits ??
|
||||
true,
|
||||
supportedSizes: ["1024x1024"],
|
||||
supportsPromptImageTransforms: true,
|
||||
supportsMaskImageEdits: true,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -611,13 +547,11 @@ const getSelectedModelConfigId = (
|
||||
request.textModelId,
|
||||
plugin.settings.aiDefaultMultimodalModel,
|
||||
plugin.settings.aiDefaultTextModel,
|
||||
plugin.settings.aiDefaultVisionModel,
|
||||
]
|
||||
: [
|
||||
request.textModelId,
|
||||
plugin.settings.aiDefaultTextModel,
|
||||
plugin.settings.aiDefaultMultimodalModel,
|
||||
plugin.settings.aiDefaultVisionModel,
|
||||
];
|
||||
|
||||
const normalizedConfiguredIds = configuredIds.filter(Boolean);
|
||||
@@ -682,7 +616,7 @@ const getResolvedModelConfig = (
|
||||
const provider =
|
||||
request.provider ??
|
||||
profile?.provider ??
|
||||
getResolvedProvider(request, plugin);
|
||||
"openai";
|
||||
const hasRequestBaseURL = Boolean(request.baseURL?.trim());
|
||||
const baseURL = normalizeBaseURL(
|
||||
(hasRequestBaseURL ? inferConfiguredBaseURL(request.baseURL) : "") ||
|
||||
@@ -705,8 +639,7 @@ const getResolvedModelConfig = (
|
||||
apiKey:
|
||||
request.apiKey?.trim() ||
|
||||
profile?.apiKey ||
|
||||
plugin.settings.aiAPIKey ||
|
||||
plugin.settings.openAIAPIToken,
|
||||
"",
|
||||
baseURL,
|
||||
endpoint,
|
||||
model: request.model?.trim() || selectedConfig?.model || "",
|
||||
@@ -718,9 +651,6 @@ const getResolvedModelConfig = (
|
||||
}
|
||||
|
||||
const imageConfig = selectedConfig as AIImageModelConfig;
|
||||
const legacySupportsImageEdits = (
|
||||
imageConfig as AIImageModelConfig & { supportsImageEdits?: boolean }
|
||||
).supportsImageEdits;
|
||||
const resolvedModel = request.model?.trim() || selectedConfig?.model || "";
|
||||
const geminiSupportedSizes = getGeminiSupportedSizes(provider, resolvedModel);
|
||||
return {
|
||||
@@ -730,11 +660,9 @@ const getResolvedModelConfig = (
|
||||
? geminiSupportedSizes
|
||||
: [...(imageConfig.supportedSizes ?? ["1024x1024"])],
|
||||
supportsPromptImageTransforms:
|
||||
imageConfig.supportsPromptImageTransforms ??
|
||||
legacySupportsImageEdits ??
|
||||
true,
|
||||
imageConfig.supportsPromptImageTransforms ?? true,
|
||||
supportsMaskImageEdits:
|
||||
imageConfig.supportsMaskImageEdits ?? legacySupportsImageEdits ?? true,
|
||||
imageConfig.supportsMaskImageEdits ?? true,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -754,10 +682,7 @@ const resolveAIConfig = (
|
||||
"image",
|
||||
request,
|
||||
) as ResolvedImageConfig,
|
||||
maxTokens:
|
||||
resolvedPlugin.settings.aiDefaultMaxResponseTokens ||
|
||||
resolvedPlugin.settings.aiDefaultMaxTokens ||
|
||||
resolvedPlugin.settings.openAIDefaultTextModelMaxTokens,
|
||||
maxTokens: resolvedPlugin.settings.aiDefaultMaxResponseTokens,
|
||||
maxOutgoingTokens: resolvedPlugin.settings.aiDefaultMaxOutgoingTokens || 0,
|
||||
};
|
||||
};
|
||||
@@ -2279,10 +2204,6 @@ const requestAI = async (
|
||||
"defaultMultimodalModel",
|
||||
plugin.settings.aiDefaultMultimodalModel || "<empty>",
|
||||
),
|
||||
debugValueLine(
|
||||
"legacyVisionDefault",
|
||||
plugin.settings.aiDefaultVisionModel || "<empty>",
|
||||
),
|
||||
debugValueLine("resolvedProvider", config.text.provider),
|
||||
debugValueLine("resolvedModel", config.text.model),
|
||||
debugValueLine("resolvedEndpoint", config.text.endpoint),
|
||||
@@ -2530,9 +2451,6 @@ export const getAISettings = (
|
||||
AIImageModelConfig
|
||||
>,
|
||||
).map(([modelId, config]) => {
|
||||
const legacySupportsImageEdits = (
|
||||
config as AIImageModelConfig & { supportsImageEdits?: boolean }
|
||||
).supportsImageEdits;
|
||||
const geminiSupportedSizes = getGeminiSupportedSizes(
|
||||
providerProfiles[config.providerId]?.provider,
|
||||
config.model,
|
||||
@@ -2546,11 +2464,9 @@ export const getAISettings = (
|
||||
? geminiSupportedSizes
|
||||
: [...(config.supportedSizes ?? ["1024x1024"])],
|
||||
supportsPromptImageTransforms:
|
||||
config.supportsPromptImageTransforms ??
|
||||
legacySupportsImageEdits ??
|
||||
true,
|
||||
config.supportsPromptImageTransforms ?? true,
|
||||
supportsMaskImageEdits:
|
||||
config.supportsMaskImageEdits ?? legacySupportsImageEdits ?? true,
|
||||
config.supportsMaskImageEdits ?? true,
|
||||
},
|
||||
];
|
||||
}),
|
||||
@@ -2583,9 +2499,7 @@ export const getAISettings = (
|
||||
defaultMaxOutgoingTokens:
|
||||
resolvedPlugin.settings.aiDefaultMaxOutgoingTokens || 0,
|
||||
defaultMaxResponseTokens:
|
||||
resolvedPlugin.settings.aiDefaultMaxResponseTokens ||
|
||||
resolvedPlugin.settings.aiDefaultMaxTokens ||
|
||||
resolvedPlugin.settings.openAIDefaultTextModelMaxTokens,
|
||||
resolvedPlugin.settings.aiDefaultMaxResponseTokens,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { getCropFileNameAndFolder, getListOfTemplateFiles } from "./fileUtils";
|
||||
import { Notice, TFile } from "obsidian";
|
||||
import { Radians } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
export const CROPPED_PREFIX = "cropped_";
|
||||
export const ANNOTATED_PREFIX = "annotated_";
|
||||
@@ -255,9 +256,7 @@ export const createImageCropperFile = async (
|
||||
}
|
||||
//console.log({counter, file});
|
||||
if (!file || !(file instanceof TFile)) {
|
||||
new Notice(
|
||||
"File not found. NewExcalidraw Drawing is taking too long to create. Please try again.",
|
||||
);
|
||||
new Notice(t("NEW_DRAWING_TIMEOUT"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Converts identifiers or objects with identifiers into a keyed lookup map.
|
||||
*
|
||||
* @param items - Values to index, or an existing map to reuse.
|
||||
* @returns The original map when one is supplied; otherwise, a new map keyed
|
||||
* by each string value or object's `id` property.
|
||||
*/
|
||||
export function arrayToMap<T extends { id: string } | string>(
|
||||
items: readonly T[] | Map<string, T>,
|
||||
) {
|
||||
if (items instanceof Map) {
|
||||
return items;
|
||||
}
|
||||
return items.reduce((acc: Map<string, T>, element) => {
|
||||
acc.set(typeof element === "string" ? element : element.id, element);
|
||||
return acc;
|
||||
}, new Map());
|
||||
}
|
||||
@@ -77,10 +77,10 @@ export const patchMobileView = (
|
||||
view: ExcalidrawView,
|
||||
opts?: { keepAlive?: boolean; isActive?: () => boolean },
|
||||
): (() => void) | void => {
|
||||
if (!DEVICE.isPhone) {
|
||||
if (!DEVICE.isMobile) {
|
||||
return;
|
||||
}
|
||||
log("patching mobile view");
|
||||
// log("patching mobile view");
|
||||
const parent = getParentOfClass(view.containerEl, "mod-top");
|
||||
if (parent) {
|
||||
if (!parent.hasClass("mod-visible")) {
|
||||
|
||||
@@ -110,7 +110,7 @@ export const setDynamicStyle = (
|
||||
//const doc = view.ownerDocument;
|
||||
const st = view?.excalidrawAPI?.getAppState?.();
|
||||
|
||||
const isLightTheme = st?.theme === "light" || st?.theme === "light";
|
||||
const isLightTheme = st?.theme === "light";
|
||||
|
||||
if (color === "transparent") {
|
||||
color = "#ffffff";
|
||||
|
||||
@@ -6,18 +6,38 @@ import { getDataURL } from "./coreUtils";
|
||||
|
||||
export { getEmbeddedFilenameParts } from "./embeddedFilenameParts";
|
||||
|
||||
/**
|
||||
* Loads a vault font and creates its data URL and `@font-face` definition.
|
||||
*
|
||||
* @param app - Obsidian application used to resolve and read the font file.
|
||||
* @param fontFileName - Vault link path or font filename to resolve.
|
||||
* @param sourcePath - Vault path from which the font link is resolved.
|
||||
* @param name - Optional font-family name overriding the file basename.
|
||||
* @returns The font definition, resolved family name, encoded data URL, and
|
||||
* original buffer. Empty strings and a null buffer are returned when the font
|
||||
* cannot be resolved.
|
||||
* @remarks
|
||||
* MIME types and CSS format names intentionally preserve the established
|
||||
* extension mapping used by plugin startup and embedded SVG font loading.
|
||||
*/
|
||||
export async function getFontDataURL(
|
||||
app: App,
|
||||
fontFileName: string,
|
||||
sourcePath: string,
|
||||
name?: string,
|
||||
): Promise<{ fontDef: string; fontName: string; dataURL: string }> {
|
||||
): Promise<{
|
||||
fontDef: string;
|
||||
fontName: string;
|
||||
dataURL: string;
|
||||
arrayBuffer: ArrayBuffer | null;
|
||||
}> {
|
||||
let fontDef = "";
|
||||
let fontName = "";
|
||||
let dataURL = "";
|
||||
let arrayBuffer: ArrayBuffer | null = null;
|
||||
const f = app.metadataCache.getFirstLinkpathDest(fontFileName, sourcePath);
|
||||
if (f) {
|
||||
const ab = await app.vault.readBinary(f);
|
||||
arrayBuffer = await app.vault.readBinary(f);
|
||||
let mimeType = "";
|
||||
let format = "";
|
||||
|
||||
@@ -42,23 +62,44 @@ export async function getFontDataURL(
|
||||
mimeType = "application/octet-stream";
|
||||
}
|
||||
fontName = name ?? f.basename;
|
||||
dataURL = await getDataURL(ab, mimeType);
|
||||
dataURL = await getDataURL(arrayBuffer, mimeType);
|
||||
const split = dataURL.split(";base64,", 2);
|
||||
dataURL = `${split[0]};charset=utf-8;base64,${split[1]}`;
|
||||
fontDef = ` @font-face {font-family: "${fontName}";src: url("${dataURL}") format("${format}")}`;
|
||||
}
|
||||
return { fontDef, fontName, dataURL };
|
||||
return { fontDef, fontName, dataURL, arrayBuffer };
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes SVG markup as a base64 data URL.
|
||||
*
|
||||
* @param svg - Serialized SVG markup.
|
||||
* @returns A base64-encoded `data:image/svg+xml` URL.
|
||||
* @remarks
|
||||
* Literal ` ` entities are converted to spaces before encoding because
|
||||
* they are not valid predefined XML entities. URI encoding is converted to a
|
||||
* byte string before `btoa()` so non-Latin text remains UTF-8 safe.
|
||||
*/
|
||||
export function svgToBase64(svg: string): string {
|
||||
const cleanSvg = svg.replaceAll(" ", " ");
|
||||
const encodedData = encodeURIComponent(cleanSvg).replace(
|
||||
/%([0-9A-F]{2})/g,
|
||||
(_match, p1) => String.fromCharCode(parseInt(p1, 16)),
|
||||
(_match: string, hexByte: string) =>
|
||||
String.fromCharCode(parseInt(hexByte, 16)),
|
||||
);
|
||||
return `data:image/svg+xml;base64,${btoa(encodedData)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads an image source and reports its intrinsic dimensions.
|
||||
*
|
||||
* @param src - Image URL, blob URL, or data URL accepted by `HTMLImageElement`.
|
||||
* @returns The image's natural width and height after it loads.
|
||||
* @throws Rejects with the browser image error when loading fails.
|
||||
* @remarks
|
||||
* This intentionally preserves native image loading behavior without adding a
|
||||
* timeout, cross-origin mode, or rendered-size fallback.
|
||||
*/
|
||||
export async function getImageSize(
|
||||
src: string,
|
||||
): Promise<{ height: number; width: number }> {
|
||||
@@ -168,6 +209,18 @@ export function getExportPadding(
|
||||
return plugin.settings.exportPaddingSVG;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies a rectangular canvas region into a new canvas, optionally scaling it.
|
||||
* Based on: https://stackoverflow.com/a/54555834
|
||||
*
|
||||
* @param srcCanvas - Source canvas to crop.
|
||||
* @param crop - Source rectangle in canvas coordinates.
|
||||
* @param output - Destination dimensions; defaults to the crop dimensions.
|
||||
* @returns A newly created canvas containing the cropped image.
|
||||
* @remarks
|
||||
* This preserves the existing `drawImage()` behavior without clamping the
|
||||
* source rectangle or changing browser interpolation and transparency rules.
|
||||
*/
|
||||
export function cropCanvas(
|
||||
srcCanvas: HTMLCanvasElement,
|
||||
crop: { left: number; top: number; width: number; height: number },
|
||||
@@ -195,6 +248,14 @@ export function cropCanvas(
|
||||
return dstCanvas;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes a synchronous or asynchronous function through a promise boundary.
|
||||
*
|
||||
* @param fn - Function to invoke.
|
||||
* @param args - Arguments passed to `fn`.
|
||||
* @returns A promise that adopts the function's returned value or thenable.
|
||||
* @remarks Synchronous exceptions thrown by `fn` become promise rejections.
|
||||
*/
|
||||
export async function promiseTry<TValue, TArgs extends unknown[]>(
|
||||
fn: (...args: TArgs) => PromiseLike<TValue> | TValue,
|
||||
...args: TArgs
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
AppState,
|
||||
BinaryFiles,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { getTextMode } from "src/shared/TextMode";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
@@ -13,14 +13,13 @@ import {
|
||||
FileId,
|
||||
FixedPoint,
|
||||
FontString,
|
||||
Theme,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { normalizePath, TFile } from "obsidian";
|
||||
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import {
|
||||
getCommonBoundingBox,
|
||||
IMAGE_TYPES,
|
||||
restoreElements,
|
||||
REG_LINKINDEX_INVALIDCHARS,
|
||||
THEME_FILTER,
|
||||
EXCALIDRAW_PLUGIN,
|
||||
@@ -60,6 +59,14 @@ import { ColorMap, FileData } from "src/types/embeddedFileLoaderTypes";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import type { StrokeWidthKey } from "@zsviczian/excalidraw/types/common/src/constants";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { cloneElement } from "./excalidrawElementUtils";
|
||||
|
||||
export {
|
||||
cloneElement,
|
||||
estimateBounds,
|
||||
getBoundTextElementId,
|
||||
repositionElementsToCursor,
|
||||
} from "./excalidrawElementUtils";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
|
||||
@@ -546,8 +553,7 @@ export async function createPNG(
|
||||
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
|
||||
elements,
|
||||
appState: {
|
||||
theme:
|
||||
forceTheme ?? template?.appState?.theme ?? canvasTheme ?? "light",
|
||||
theme: (forceTheme ?? template?.appState?.theme ?? canvasTheme ?? "light") as Theme,
|
||||
viewBackgroundColor:
|
||||
template?.appState?.viewBackgroundColor ?? canvasBackgroundColor,
|
||||
...(template?.appState?.frameRendering
|
||||
@@ -621,7 +627,7 @@ export const updateElementLinksToObsidianLinks = ({
|
||||
linkedFile: file,
|
||||
hostFile,
|
||||
}) ?? link;
|
||||
} catch (e) {
|
||||
} catch (e: unknown) {
|
||||
errorlog({
|
||||
where: "excalidrawAutomateUtils.updateElementLinksToObsidianLinks",
|
||||
fn: window.ExcalidrawAutomate.onUpdateElementLinkForExportHook,
|
||||
@@ -688,8 +694,7 @@ export async function createSVG(
|
||||
});
|
||||
}
|
||||
|
||||
const theme =
|
||||
forceTheme ?? template?.appState?.theme ?? canvasTheme ?? "light";
|
||||
const theme = (forceTheme ?? template?.appState?.theme ?? canvasTheme ?? "light") as Theme;
|
||||
const withTheme =
|
||||
exportSettings?.withTheme ?? plugin.settings.exportWithTheme;
|
||||
|
||||
@@ -811,40 +816,6 @@ function estimateLineBound(
|
||||
return [minX, minY, maxX, maxY];
|
||||
}
|
||||
|
||||
export function estimateBounds(
|
||||
elements: ExcalidrawElement[],
|
||||
): [number, number, number, number] {
|
||||
const bb = getCommonBoundingBox(elements);
|
||||
return [bb.minX, bb.minY, bb.maxX, bb.maxY];
|
||||
}
|
||||
|
||||
export function repositionElementsToCursor(
|
||||
elements: ExcalidrawElement[],
|
||||
newPosition: { x: number; y: number },
|
||||
center: boolean = false,
|
||||
): ExcalidrawElement[] {
|
||||
const [x1, y1, x2, y2] = estimateBounds(elements);
|
||||
let [offsetX, offsetY] = [0, 0];
|
||||
if (center) {
|
||||
[offsetX, offsetY] = [
|
||||
newPosition.x - (x1 + x2) / 2,
|
||||
newPosition.y - (y1 + y2) / 2,
|
||||
];
|
||||
} else {
|
||||
[offsetX, offsetY] = [newPosition.x - x1, newPosition.y - y1];
|
||||
}
|
||||
|
||||
elements.forEach((element: Mutable<ExcalidrawElement>) => {
|
||||
element.x = element.x + offsetX;
|
||||
element.y = element.y + offsetY;
|
||||
});
|
||||
|
||||
return restoreElements(elements, null, {
|
||||
refreshDimensions: true,
|
||||
repairBindings: true,
|
||||
});
|
||||
}
|
||||
|
||||
export const search = async (view: ExcalidrawView) => {
|
||||
const ea = view.plugin.ea;
|
||||
ea.reset();
|
||||
@@ -874,7 +845,7 @@ export const search = async (view: ExcalidrawView) => {
|
||||
}
|
||||
const res = text.matchAll(/"(.*?)"/g);
|
||||
let query: string[] = [];
|
||||
let parts;
|
||||
let parts: IteratorResult<RegExpMatchArray, undefined>;
|
||||
while (!(parts = res.next()).done) {
|
||||
query.push(parts.value[1]);
|
||||
}
|
||||
@@ -1029,16 +1000,6 @@ export const getImagesMatchingQuery = (
|
||||
);
|
||||
};
|
||||
|
||||
export const cloneElement = (
|
||||
el: ExcalidrawElement,
|
||||
): Mutable<ExcalidrawElement> => {
|
||||
const newEl = JSON.parse(JSON.stringify(el)) as Mutable<ExcalidrawElement>;
|
||||
newEl.version = el.version + 1;
|
||||
newEl.updated = Date.now();
|
||||
newEl.versionNonce = Math.floor(Math.random() * 1000000000);
|
||||
return newEl;
|
||||
};
|
||||
|
||||
export const verifyMinimumPluginVersion = (
|
||||
requiredVersion: string,
|
||||
): boolean => {
|
||||
@@ -1048,12 +1009,6 @@ export const verifyMinimumPluginVersion = (
|
||||
);
|
||||
};
|
||||
|
||||
export const getBoundTextElementId = (container: ExcalidrawElement | null) => {
|
||||
return container?.boundElements?.length
|
||||
? container?.boundElements?.find((ele) => ele.type === "text")?.id || null
|
||||
: null;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* FixedPoint represents the fixed point binding information in form of a vertical and
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { getCommonBoundingBox, restoreElements } from "src/constants/constants";
|
||||
|
||||
/**
|
||||
* Calculates the axis-aligned bounds shared by a collection of elements.
|
||||
*
|
||||
* @param elements - Elements whose bounds should be measured.
|
||||
* @returns The minimum and maximum coordinates as `[minX, minY, maxX, maxY]`.
|
||||
*/
|
||||
export function estimateBounds(
|
||||
elements: ExcalidrawElement[],
|
||||
): [number, number, number, number] {
|
||||
const bb = getCommonBoundingBox(elements);
|
||||
return [bb.minX, bb.minY, bb.maxX, bb.maxY];
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves elements so their top-left corner or center is at a scene position.
|
||||
*
|
||||
* @param elements - Elements to reposition. Their coordinates are mutated.
|
||||
* @param newPosition - Target scene position.
|
||||
* @param center - Whether to align the combined center instead of the top-left.
|
||||
* @returns Restored elements with dimensions refreshed and bindings repaired.
|
||||
*/
|
||||
export function repositionElementsToCursor(
|
||||
elements: ExcalidrawElement[],
|
||||
newPosition: { x: number; y: number },
|
||||
center: boolean = false,
|
||||
): ExcalidrawElement[] {
|
||||
const [x1, y1, x2, y2] = estimateBounds(elements);
|
||||
let [offsetX, offsetY] = [0, 0];
|
||||
if (center) {
|
||||
[offsetX, offsetY] = [
|
||||
newPosition.x - (x1 + x2) / 2,
|
||||
newPosition.y - (y1 + y2) / 2,
|
||||
];
|
||||
} else {
|
||||
[offsetX, offsetY] = [newPosition.x - x1, newPosition.y - y1];
|
||||
}
|
||||
|
||||
elements.forEach((element: Mutable<ExcalidrawElement>) => {
|
||||
element.x = element.x + offsetX;
|
||||
element.y = element.y + offsetY;
|
||||
});
|
||||
|
||||
return restoreElements(elements, null, {
|
||||
refreshDimensions: true,
|
||||
repairBindings: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deep-clones an element while advancing its Excalidraw version metadata.
|
||||
*
|
||||
* @param element - Element to clone.
|
||||
* @returns A mutable clone with the same ID and refreshed version metadata.
|
||||
* @remarks This internal helper does not assign a new element ID.
|
||||
*/
|
||||
export function cloneElement(
|
||||
element: ExcalidrawElement,
|
||||
): Mutable<ExcalidrawElement> {
|
||||
const clone = JSON.parse(
|
||||
JSON.stringify(element),
|
||||
) as Mutable<ExcalidrawElement>;
|
||||
clone.version = element.version + 1;
|
||||
clone.updated = Date.now();
|
||||
clone.versionNonce = Math.floor(Math.random() * 1000000000);
|
||||
return clone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the ID of the first text element bound to a container.
|
||||
*
|
||||
* @param container - Container element, or `null` when none is available.
|
||||
* @returns The bound text element ID, or `null` when no text is bound.
|
||||
*/
|
||||
export function getBoundTextElementId(
|
||||
container: ExcalidrawElement | null,
|
||||
): string | null {
|
||||
return container?.boundElements?.length
|
||||
? container.boundElements.find((element) => element.type === "text")?.id ||
|
||||
null
|
||||
: null;
|
||||
}
|
||||
@@ -1,63 +1,16 @@
|
||||
import type {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawImageElement,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import type { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { getCommonBoundingBox, restoreElements } from "src/constants/constants";
|
||||
import { getEA } from "src/core";
|
||||
import { t } from "src/lang/helpers";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { errorlog } from "./utils";
|
||||
|
||||
function estimateBounds(
|
||||
elements: ExcalidrawElement[],
|
||||
): [number, number, number, number] {
|
||||
const bb = getCommonBoundingBox(elements);
|
||||
return [bb.minX, bb.minY, bb.maxX, bb.maxY];
|
||||
}
|
||||
|
||||
export function repositionElementsToCursor(
|
||||
elements: ExcalidrawElement[],
|
||||
newPosition: { x: number; y: number },
|
||||
center: boolean = false,
|
||||
): ExcalidrawElement[] {
|
||||
const [x1, y1, x2, y2] = estimateBounds(elements);
|
||||
let [offsetX, offsetY] = [0, 0];
|
||||
if (center) {
|
||||
[offsetX, offsetY] = [
|
||||
newPosition.x - (x1 + x2) / 2,
|
||||
newPosition.y - (y1 + y2) / 2,
|
||||
];
|
||||
} else {
|
||||
[offsetX, offsetY] = [newPosition.x - x1, newPosition.y - y1];
|
||||
}
|
||||
|
||||
elements.forEach((element: Mutable<ExcalidrawElement>) => {
|
||||
element.x = element.x + offsetX;
|
||||
element.y = element.y + offsetY;
|
||||
});
|
||||
|
||||
return restoreElements(elements, null, {
|
||||
refreshDimensions: true,
|
||||
repairBindings: true,
|
||||
});
|
||||
}
|
||||
|
||||
export const cloneElement = (
|
||||
el: ExcalidrawElement,
|
||||
): Mutable<ExcalidrawElement> => {
|
||||
const newEl = JSON.parse(JSON.stringify(el)) as Mutable<ExcalidrawElement>;
|
||||
newEl.version = el.version + 1;
|
||||
newEl.updated = Date.now();
|
||||
newEl.versionNonce = Math.floor(Math.random() * 1000000000);
|
||||
return newEl;
|
||||
};
|
||||
|
||||
export const getBoundTextElementId = (container: ExcalidrawElement | null) => {
|
||||
return container?.boundElements?.length
|
||||
? container.boundElements.find((ele) => ele.type === "text")?.id || null
|
||||
: null;
|
||||
};
|
||||
export {
|
||||
cloneElement,
|
||||
getBoundTextElementId,
|
||||
repositionElementsToCursor,
|
||||
} from "./excalidrawElementUtils";
|
||||
|
||||
export const insertLaTeXToView = (
|
||||
view: ExcalidrawView,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ColorMaster } from "@zsviczian/colormaster";
|
||||
import type { TInput } from "@zsviczian/colormaster/types";
|
||||
import {
|
||||
MAX_IMAGE_SIZE,
|
||||
IMAGE_TYPES,
|
||||
@@ -20,13 +22,14 @@ import {
|
||||
getExcalidrawMarkdownHeaderSection,
|
||||
REGEX_TAGS,
|
||||
} from "../shared/ExcalidrawData";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawFrameElement,
|
||||
ExcalidrawImageElement,
|
||||
ExcalidrawTextElement,
|
||||
FileId,
|
||||
NonDeletedExcalidrawElement,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { getAllNestedExcalidrawFiles } from "./fileUtils";
|
||||
import {
|
||||
@@ -686,7 +689,12 @@ export async function addBackOfTheNoteCard(
|
||||
if (activate) {
|
||||
window.setTimeout(() => {
|
||||
api.updateScene({
|
||||
appState: { activeEmbeddable: { element: el, state: "active" } },
|
||||
appState: {
|
||||
activeEmbeddable: {
|
||||
element: el as NonDeletedExcalidrawElement,
|
||||
state: "active",
|
||||
},
|
||||
},
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
if (found) {
|
||||
@@ -804,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(
|
||||
@@ -929,15 +940,22 @@ export function getViewColorPalette(
|
||||
return getDefaultColorPalette();
|
||||
}
|
||||
|
||||
const basePalette = colorPalette[palette];
|
||||
// AppState["colorPalette"][palette] is typed as ColorPaletteCustom (a
|
||||
// config-shaped record) upstream, but at the AppState/runtime level the
|
||||
// fork actually stores it as a flat list of single colors and/or grouped
|
||||
// color tuples -- confirmed against this function's own already-typed
|
||||
// flattenPalette() helper below (readonly (string | string[])[]).
|
||||
const basePalette = colorPalette[palette] as unknown as
|
||||
| string
|
||||
| readonly (string | string[])[];
|
||||
|
||||
if (!Array.isArray(basePalette)) {
|
||||
return [basePalette];
|
||||
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;
|
||||
@@ -952,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;
|
||||
};
|
||||
@@ -963,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;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Notice } from "obsidian";
|
||||
import { DEVICE, EXCALIDRAW_PLUGIN } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { download } from "./fileUtils";
|
||||
import { svgToBase64 } from "./utils";
|
||||
import { svgToBase64 } from "./embeddedAssetUtils";
|
||||
import {
|
||||
PageDimensions,
|
||||
PageOrientation,
|
||||
|
||||
+37
-2
@@ -18,9 +18,9 @@ import {
|
||||
FRONTMATTER_KEYS,
|
||||
URLFETCHTIMEOUT,
|
||||
} from "src/constants/constants";
|
||||
import { ExcalidrawSettings } from "src/core/settings";
|
||||
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
|
||||
import { errorlog, getDataURL } from "./coreUtils";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import {
|
||||
getAttachmentsFolderAndFilePath,
|
||||
splitFolderAndFilename,
|
||||
@@ -286,6 +286,41 @@ export const getDataURLFromURL = async (
|
||||
: (url as DataURL);
|
||||
};
|
||||
|
||||
/**
|
||||
* Decodes a base64 data URL into binary data, fetching remote URLs first.
|
||||
*
|
||||
* @param dataURL - A base64 data URL or an HTTP, HTTPS, or FTP URL.
|
||||
* @returns The decoded bytes, or `null` when the input cannot be resolved to a
|
||||
* base64 payload.
|
||||
* @remarks
|
||||
* Remote URL handling intentionally preserves the existing MIME inference and
|
||||
* `getDataURLFromURL()` fallback behavior used on desktop and mobile.
|
||||
*/
|
||||
export async function getBinaryFileFromDataURL(
|
||||
dataURL: string,
|
||||
): Promise<ArrayBuffer> {
|
||||
if (!dataURL) {
|
||||
return null;
|
||||
}
|
||||
if (dataURL.match(/^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i)) {
|
||||
const hyperlink = dataURL;
|
||||
const extension = getURLImageExtension(hyperlink);
|
||||
const mimeType = getMimeType(extension);
|
||||
dataURL = await getDataURLFromURL(hyperlink, mimeType);
|
||||
}
|
||||
const base64Match = dataURL.match(/base64,(.*)/);
|
||||
if (!base64Match) {
|
||||
return null;
|
||||
}
|
||||
const binaryString = window.atob(base64Match[1]);
|
||||
const len = binaryString.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
export const blobToBase64 = async (blob: Blob): Promise<string> => {
|
||||
const arrayBuffer = await blob.arrayBuffer();
|
||||
const bytes = new Uint8Array(arrayBuffer);
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Reads only the SFNT metadata required to register a local Excalidraw font.
|
||||
*
|
||||
* @packageDocumentation
|
||||
*/
|
||||
|
||||
const SFNT_HEADER_SIZE = 12;
|
||||
const TABLE_RECORD_SIZE = 16;
|
||||
const TABLE_TAG_SIZE = 4;
|
||||
const TABLE_OFFSET_POSITION = 8;
|
||||
const TABLE_LENGTH_POSITION = 12;
|
||||
|
||||
const HEAD_UNITS_PER_EM_POSITION = 18;
|
||||
const HEAD_REQUIRED_LENGTH = HEAD_UNITS_PER_EM_POSITION + 2;
|
||||
const HHEA_ASCENDER_POSITION = 4;
|
||||
const HHEA_DESCENDER_POSITION = 6;
|
||||
const HHEA_REQUIRED_LENGTH = HHEA_DESCENDER_POSITION + 2;
|
||||
|
||||
const SUPPORTED_SFNT_SIGNATURES = new Set([
|
||||
0x00010000, // TrueType outlines
|
||||
0x4f54544f, // OTTO: OpenType with CFF/CFF2 outlines
|
||||
0x74727565, // true: legacy Apple TrueType
|
||||
0x74797031, // typ1: legacy OpenType wrapper
|
||||
]);
|
||||
|
||||
/** Font metrics registered for Excalidraw's local font family. */
|
||||
export interface FontMetrics {
|
||||
/** Raw `head.unitsPerEm` value. The narrow cast preserves uncommon values. */
|
||||
unitsPerEm: 1000 | 1024 | 2048;
|
||||
/** Raw `hhea.ascender` value. */
|
||||
ascender: number;
|
||||
/** Raw `hhea.descender` value. */
|
||||
descender: number;
|
||||
/** Unitless line height derived using the plugin's established formula. */
|
||||
lineHeight: number;
|
||||
}
|
||||
|
||||
type SfntTable = {
|
||||
offset: number;
|
||||
length: number;
|
||||
};
|
||||
|
||||
const readTableTag = (view: DataView, offset: number): string => {
|
||||
let tag = "";
|
||||
for (let index = 0; index < TABLE_TAG_SIZE; index++) {
|
||||
tag += String.fromCharCode(view.getUint8(offset + index));
|
||||
}
|
||||
return tag;
|
||||
};
|
||||
|
||||
const isRangeAvailable = (
|
||||
byteLength: number,
|
||||
offset: number,
|
||||
length: number,
|
||||
): boolean =>
|
||||
Number.isSafeInteger(offset) &&
|
||||
Number.isSafeInteger(length) &&
|
||||
offset >= 0 &&
|
||||
length >= 0 &&
|
||||
offset <= byteLength - length;
|
||||
|
||||
const findRequiredTables = (
|
||||
view: DataView,
|
||||
): { head: SfntTable; hhea: SfntTable } | null => {
|
||||
if (view.byteLength < SFNT_HEADER_SIZE) {
|
||||
return null;
|
||||
}
|
||||
if (!SUPPORTED_SFNT_SIGNATURES.has(view.getUint32(0))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const tableCount = view.getUint16(4);
|
||||
const directoryLength = tableCount * TABLE_RECORD_SIZE;
|
||||
if (!isRangeAvailable(view.byteLength, SFNT_HEADER_SIZE, directoryLength)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let head: SfntTable | null = null;
|
||||
let hhea: SfntTable | null = null;
|
||||
for (let index = 0; index < tableCount && (!head || !hhea); index++) {
|
||||
const recordOffset = SFNT_HEADER_SIZE + index * TABLE_RECORD_SIZE;
|
||||
const tag = readTableTag(view, recordOffset);
|
||||
if (tag !== "head" && tag !== "hhea") {
|
||||
continue;
|
||||
}
|
||||
const table = {
|
||||
offset: view.getUint32(recordOffset + TABLE_OFFSET_POSITION),
|
||||
length: view.getUint32(recordOffset + TABLE_LENGTH_POSITION),
|
||||
};
|
||||
if (!isRangeAvailable(view.byteLength, table.offset, table.length)) {
|
||||
return null;
|
||||
}
|
||||
if (tag === "head") {
|
||||
head = table;
|
||||
} else {
|
||||
hhea = table;
|
||||
}
|
||||
}
|
||||
return head && hhea ? { head, hhea } : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads the vertical metrics needed by Excalidraw from a TTF or OTF buffer.
|
||||
*
|
||||
* @param fontData - Complete SFNT font data from a `.ttf` or `.otf` file.
|
||||
* @returns Parsed metrics, or `null` when the font is unsupported or malformed.
|
||||
* @remarks
|
||||
* Only the SFNT table directory plus `head.unitsPerEm`, `hhea.ascender`, and
|
||||
* `hhea.descender` are read. Glyph outlines, names, and layout tables are left
|
||||
* to the browser and Excalidraw, as they were never consumed by the plugin.
|
||||
*/
|
||||
export function getFontMetrics(fontData: ArrayBuffer): FontMetrics | null {
|
||||
const view = new DataView(fontData);
|
||||
const tables = findRequiredTables(view);
|
||||
if (
|
||||
!tables ||
|
||||
tables.head.length < HEAD_REQUIRED_LENGTH ||
|
||||
tables.hhea.length < HHEA_REQUIRED_LENGTH
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const unitsPerEm = view.getUint16(
|
||||
tables.head.offset + HEAD_UNITS_PER_EM_POSITION,
|
||||
);
|
||||
const ascender = view.getInt16(
|
||||
tables.hhea.offset + HHEA_ASCENDER_POSITION,
|
||||
);
|
||||
const descender = view.getInt16(
|
||||
tables.hhea.offset + HHEA_DESCENDER_POSITION,
|
||||
);
|
||||
if (unitsPerEm === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
// Excalidraw's type lists common values only; retain the font's exact value.
|
||||
unitsPerEm: unitsPerEm as FontMetrics["unitsPerEm"],
|
||||
ascender,
|
||||
descender,
|
||||
lineHeight: (ascender - descender) / unitsPerEm,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { TFile } from "obsidian";
|
||||
import { cleanBlockRef, cleanSectionHeading } from "./pathUtils";
|
||||
|
||||
/** Parsed components of an Obsidian drawing or embedded-file link. */
|
||||
export type LinkParts = {
|
||||
original: string;
|
||||
path: string;
|
||||
isBlockRef: boolean;
|
||||
ref: string;
|
||||
width: number;
|
||||
height: number;
|
||||
page: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Splits a drawing or embedded-file link into its path, reference, dimensions,
|
||||
* and optional PDF page.
|
||||
*
|
||||
* @param filename - Link text to parse.
|
||||
* @param file - Current file, used when the link omits its path.
|
||||
* @returns Parsed link components with cleaned heading or block references.
|
||||
* @remarks
|
||||
* This preserves the existing permissive regular-expression parser. It is not
|
||||
* a general-purpose Obsidian link parser and intentionally retains its current
|
||||
* handling of malformed or partially specified links.
|
||||
*/
|
||||
export function getLinkParts(filename: string, file?: TFile): LinkParts {
|
||||
const linkPattern = /(^[^#|]*)#?(\^)?([^|]*)?\|?(\d*)x?(\d*)/;
|
||||
const parts = filename.match(linkPattern);
|
||||
const isBlockRef = parts[2] === "^";
|
||||
let page = parseInt(parts[3]?.match(/page=(\d*)/)?.[1]);
|
||||
page = isNaN(page) ? null : page;
|
||||
return {
|
||||
original: filename,
|
||||
path: file && parts[1] === "" ? file.path : parts[1],
|
||||
isBlockRef,
|
||||
ref: parts[3]?.match(/^page=\d*$/i)
|
||||
? parts[3]
|
||||
: isBlockRef
|
||||
? cleanBlockRef(parts[3])
|
||||
: cleanSectionHeading(parts[3]),
|
||||
width: parts[4] ? parseInt(parts[4]) : undefined,
|
||||
height: parts[5] ? parseInt(parts[5]) : undefined,
|
||||
page,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import type React from "react";
|
||||
import { Modifier } from "obsidian";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { ExcalidrawSettings } from "src/core/settings";
|
||||
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
export {
|
||||
labelALT,
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
MarkdownView,
|
||||
OpenViewState,
|
||||
parseFrontMatterEntry,
|
||||
parseYaml,
|
||||
stringifyYaml,
|
||||
TextFileView,
|
||||
TFile,
|
||||
View,
|
||||
@@ -21,7 +23,6 @@ import {
|
||||
FRONTMATTER_KEYS,
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
} from "src/constants/constants";
|
||||
import { parse, stringify } from "yaml";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { setStyle } from "./styleUtils";
|
||||
import { isInstanceOfHTMLBodyElement } from "./typechecks";
|
||||
@@ -378,6 +379,17 @@ export const openLeaf = ({
|
||||
return { leaf, promise };
|
||||
};
|
||||
|
||||
/**
|
||||
* Merges an Excalidraw Markdown template into a target Markdown document.
|
||||
*
|
||||
* Existing target frontmatter values take precedence. Arrays present in both
|
||||
* documents are merged in target-first order, while template-only keys are
|
||||
* appended using Obsidian's YAML parser and serializer.
|
||||
*
|
||||
* @param template - Template Markdown containing frontmatter and optional body.
|
||||
* @param target - Target Markdown whose existing frontmatter is preserved.
|
||||
* @returns The merged Markdown document.
|
||||
*/
|
||||
export function mergeMarkdownFiles(template: string, target: string): string {
|
||||
// Template frontmatter
|
||||
const templateFrontmatterEnd = template.indexOf("---", 4);
|
||||
@@ -385,7 +397,7 @@ export function mergeMarkdownFiles(template: string, target: string): string {
|
||||
.substring(4, templateFrontmatterEnd)
|
||||
.trim();
|
||||
const templateContent = template.substring(templateFrontmatterEnd + 3);
|
||||
const templateFrontmatterObj = (parse(templateFrontmatterRaw) ||
|
||||
const templateFrontmatterObj = (parseYaml(templateFrontmatterRaw) ||
|
||||
{}) as FrontMatterCache;
|
||||
|
||||
const hasTargetFM =
|
||||
@@ -397,7 +409,7 @@ export function mergeMarkdownFiles(template: string, target: string): string {
|
||||
.replace(/\s+$/, ""); // keep as-is
|
||||
const targetContent = target.substring(targetFrontmatterEnd + 3);
|
||||
|
||||
const targetFrontmatterObj: FrontMatterCache = (parse(
|
||||
const targetFrontmatterObj: FrontMatterCache = (parseYaml(
|
||||
targetFrontmatterRaw,
|
||||
) || {}) as FrontMatterCache;
|
||||
|
||||
@@ -414,7 +426,7 @@ export function mergeMarkdownFiles(template: string, target: string): string {
|
||||
const tplArr = templateFrontmatterObj[k] as unknown[];
|
||||
const merged = [...tArr, ...tplArr.filter((v) => !tArr.includes(v))];
|
||||
// Produce YAML for just this key
|
||||
const mergedYaml = stringify({ [k]: merged }).trimEnd();
|
||||
const mergedYaml = stringifyYaml({ [k]: merged }).trimEnd();
|
||||
targetFrontmatterRaw =
|
||||
replaceYamlKeyBlock(targetFrontmatterRaw, k, mergedYaml) ??
|
||||
targetFrontmatterRaw;
|
||||
@@ -430,14 +442,14 @@ export function mergeMarkdownFiles(template: string, target: string): string {
|
||||
}
|
||||
|
||||
const appended = Object.keys(newKeys).length
|
||||
? `${targetFrontmatterRaw}\n${stringify(newKeys).trimEnd()}`
|
||||
? `${targetFrontmatterRaw}\n${stringifyYaml(newKeys).trimEnd()}`
|
||||
: targetFrontmatterRaw;
|
||||
|
||||
return `---\n${appended}\n---\n${targetContent}\n\n${templateContent.trim()}\n`;
|
||||
}
|
||||
// No frontmatter in target: use template FM + target content + template content
|
||||
const targetContent = target.trim();
|
||||
const templateFMYaml = stringify(templateFrontmatterObj).trimEnd();
|
||||
const templateFMYaml = stringifyYaml(templateFrontmatterObj).trimEnd();
|
||||
return `---\n${templateFMYaml}\n---\n${targetContent}\n\n${templateContent.trim()}\n`;
|
||||
}
|
||||
|
||||
|
||||
+17
-145
@@ -7,108 +7,15 @@ import type { TFile } from "obsidian";
|
||||
import { FRONTMATTER_KEYS, getContainerElement } from "src/constants/constants";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import LZString from "lz-string";
|
||||
import {
|
||||
getDataURLFromURL,
|
||||
getMimeType,
|
||||
getURLImageExtension,
|
||||
} from "./fileUtils";
|
||||
import { cleanBlockRef, cleanSectionHeading } from "./pathUtils";
|
||||
import { runCompressionWorker } from "src/shared/Workers/compression-worker";
|
||||
import { arrayToMap } from "./collectionUtils";
|
||||
|
||||
export function wrapTextAtCharLength(
|
||||
text: string,
|
||||
lineLen: number,
|
||||
forceWrap: boolean = false,
|
||||
tolerance: number = 0,
|
||||
): string {
|
||||
if (!lineLen) {
|
||||
return text;
|
||||
}
|
||||
let outstring = "";
|
||||
if (forceWrap) {
|
||||
for (const t of text.split("\n")) {
|
||||
const v = t.match(new RegExp(`(.){1,${lineLen}}`, "g"));
|
||||
outstring += v ? `${v.join("\n")}\n` : "\n";
|
||||
}
|
||||
return outstring.replace(/\n$/, "");
|
||||
}
|
||||
|
||||
const reg = new RegExp(
|
||||
`(.{1,${lineLen}})(\\s+|$\\n?)|([^\\s]{1,${lineLen + tolerance}})(\\s+|$\\n?)?`,
|
||||
"gm",
|
||||
);
|
||||
const res = text.matchAll(reg);
|
||||
let parts;
|
||||
while (!(parts = res.next()).done) {
|
||||
outstring += parts.value[1]
|
||||
? parts.value[1].trimEnd()
|
||||
: parts.value[3].trimEnd();
|
||||
const newLine =
|
||||
(parts.value[2] ? parts.value[2].split("\n").length - 1 : 0) +
|
||||
(parts.value[4] ? parts.value[4].split("\n").length - 1 : 0);
|
||||
outstring += "\n".repeat(newLine);
|
||||
if (newLine === 0) {
|
||||
outstring += "\n";
|
||||
}
|
||||
}
|
||||
return outstring.replace(/\n$/, "");
|
||||
}
|
||||
|
||||
export async function getBinaryFileFromDataURL(
|
||||
dataURL: string,
|
||||
): Promise<ArrayBuffer> {
|
||||
if (!dataURL) {
|
||||
return null;
|
||||
}
|
||||
if (dataURL.match(/^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i)) {
|
||||
const hyperlink = dataURL;
|
||||
const extension = getURLImageExtension(hyperlink);
|
||||
const mimeType = getMimeType(extension);
|
||||
dataURL = await getDataURLFromURL(hyperlink, mimeType);
|
||||
}
|
||||
const parts = dataURL.matchAll(/base64,(.*)/g).next();
|
||||
if (!parts.value) {
|
||||
return null;
|
||||
}
|
||||
const binaryString = window.atob(parts.value[1]);
|
||||
const len = binaryString.length;
|
||||
const bytes = new Uint8Array(len);
|
||||
for (let i = 0; i < len; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
export type LinkParts = {
|
||||
original: string;
|
||||
path: string;
|
||||
isBlockRef: boolean;
|
||||
ref: string;
|
||||
width: number;
|
||||
height: number;
|
||||
page: number;
|
||||
};
|
||||
|
||||
export function getLinkParts(fname: string, file?: TFile): LinkParts {
|
||||
const reg = /(^[^#|]*)#?(\^)?([^|]*)?\|?(\d*)x?(\d*)/;
|
||||
const parts = fname.match(reg);
|
||||
const isBlockRef = parts[2] === "^";
|
||||
let page = parseInt(parts[3]?.match(/page=(\d*)/)?.[1]);
|
||||
page = isNaN(page) ? null : page;
|
||||
return {
|
||||
original: fname,
|
||||
path: file && parts[1] === "" ? file.path : parts[1],
|
||||
isBlockRef,
|
||||
ref: parts[3]?.match(/^page=\d*$/i)
|
||||
? parts[3]
|
||||
: isBlockRef
|
||||
? cleanBlockRef(parts[3])
|
||||
: cleanSectionHeading(parts[3]),
|
||||
width: parts[4] ? parseInt(parts[4]) : undefined,
|
||||
height: parts[5] ? parseInt(parts[5]) : undefined,
|
||||
page,
|
||||
};
|
||||
}
|
||||
export { arrayToMap };
|
||||
export { getBinaryFileFromDataURL } from "./fileUtils";
|
||||
export { getLinkParts } from "./linkUtils";
|
||||
export type { LinkParts } from "./linkUtils";
|
||||
export { wrapTextAtCharLength } from "./textUtils";
|
||||
export { isVersionNewerThanOther } from "./versionUtils";
|
||||
|
||||
export async function compressAsync(data: string): Promise<string> {
|
||||
return await runCompressionWorker(data, "compress");
|
||||
@@ -179,52 +86,17 @@ export function getExportTheme(
|
||||
return plugin.settings.exportWithTheme ? theme : "light";
|
||||
}
|
||||
|
||||
export function isVersionNewerThanOther(
|
||||
version: string,
|
||||
otherVersion: string,
|
||||
): boolean {
|
||||
if (!version || !otherVersion) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const v = version.match(/(\d*)\.(\d*)\.(\d*)/);
|
||||
const o = otherVersion.match(/(\d*)\.(\d*)\.(\d*)/);
|
||||
|
||||
return Boolean(
|
||||
v &&
|
||||
v.length === 4 &&
|
||||
o &&
|
||||
o.length === 4 &&
|
||||
!(
|
||||
isNaN(parseInt(v[1])) ||
|
||||
isNaN(parseInt(v[2])) ||
|
||||
isNaN(parseInt(v[3]))
|
||||
) &&
|
||||
!(
|
||||
isNaN(parseInt(o[1])) ||
|
||||
isNaN(parseInt(o[2])) ||
|
||||
isNaN(parseInt(o[3]))
|
||||
) &&
|
||||
(parseInt(v[1]) > parseInt(o[1]) ||
|
||||
(parseInt(v[1]) >= parseInt(o[1]) && parseInt(v[2]) > parseInt(o[2])) ||
|
||||
(parseInt(v[1]) >= parseInt(o[1]) &&
|
||||
parseInt(v[2]) >= parseInt(o[2]) &&
|
||||
parseInt(v[3]) > parseInt(o[3]))),
|
||||
);
|
||||
}
|
||||
|
||||
export function arrayToMap<T extends { id: string } | string>(
|
||||
items: readonly T[] | Map<string, T>,
|
||||
) {
|
||||
if (items instanceof Map) {
|
||||
return items;
|
||||
}
|
||||
return items.reduce((acc: Map<string, T>, element) => {
|
||||
acc.set(typeof element === "string" ? element : element.id, element);
|
||||
return acc;
|
||||
}, new Map());
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates or inserts simple, single-line properties in serialized frontmatter.
|
||||
*
|
||||
* @param data - Markdown text whose frontmatter should be updated.
|
||||
* @param keyValuePairs - Property names and serialized values to apply.
|
||||
* @returns The updated text, or the original text when there is nothing to do.
|
||||
* @remarks
|
||||
* This intentionally preserves the existing string-based behavior: it does not
|
||||
* parse YAML, and insertion requires an opening `---` followed by a newline.
|
||||
*/
|
||||
export function updateFrontmatterInString(
|
||||
data: string,
|
||||
keyValuePairs?: [string, string][],
|
||||
|
||||
@@ -4,6 +4,7 @@ import { getEA } from "src/core";
|
||||
import { t } from "src/lang/helpers";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import type { NormalizedZoomValue } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import type { Theme } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { hideElement, setStyle, showElement } from "./styleUtils";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
@@ -122,7 +123,7 @@ export async function captureScreenshot(
|
||||
appState: {
|
||||
viewModeEnabled: true,
|
||||
linkOpacity: 0,
|
||||
theme: options.theme,
|
||||
theme: options.theme as Theme,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import { ExcalidrawSidepanelView } from "src/view/sidepanel/Sidepanel";
|
||||
import { errorlog } from "./coreUtils";
|
||||
import { getIMGFilename, createOrOverwriteFile } from "./fileUtils";
|
||||
import { hideElement, setButtonBgColor, showElement } from "./styleUtils";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
|
||||
export const installButton = async (
|
||||
plugin: ExcalidrawPlugin,
|
||||
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user